From 668abae137826d92520487e0e4d3c2e1e361a726 Mon Sep 17 00:00:00 2001 From: ScriptedAlchemy Date: Thu, 3 Sep 2026 09:24:44 +0000 Subject: [PATCH 01/20] feat(lineage): add examples/host-test probe and runtime-held request.lineage from live host captures Add the host-test probe example (every canonical event family, host-test and host-test-raw MCP servers, rendered CLI dump, scripted isolated-home probe:install/capture/uninstall for claude, codex, and cursor), capture real Claude Code 2.1.257, Codex 0.147.0, and Cursor 3.18.25 sessions with nested subagents into redacted fixtures, and record the evidence matrix. Build lineage into the framework from what was observed: an agent lineage registry in @agent-bundle/runtime journaled through the state kernel, fed by agent/start, agent/stop, and tool/before|after, resolving request.lineage on events, generated MCP tools (Claude claudecode/toolUseId, Codex x-codex-turn-metadata, Cursor MCP: hook window), routed CLI, and rendered scripts, with typed per-host unavailability, dated lineage capability rows, and the Workbench Lifecycles lineage axis and chain. Accept Claude PostToolUse content-block array tool_response for MCP tools, which the probe showed the pinned validator rejecting on every MCP call. --- .changeset/request-lineage.md | 6 + README.md | 1 + docs/audits/2026-09-03-host-lineage-matrix.md | 189 ++++++++++ docs/entry-conventions.md | 60 ++- docs/framework-mode.md | 18 +- examples/host-test/README.md | 109 ++++++ examples/host-test/agent-bundle.config.ts | 28 ++ examples/host-test/package.json | 41 +++ .../host-test/rstest.route-unit.config.ts | 4 + examples/host-test/scripts/probe.mjs | 331 +++++++++++++++++ examples/host-test/src/capture.ts | 284 ++++++++++++++ examples/host-test/src/cli/dump.tsx | 47 +++ examples/host-test/src/dump.ts | 153 ++++++++ examples/host-test/src/event-route.tsx | 26 ++ examples/host-test/src/events/agent/idle.tsx | 13 + examples/host-test/src/events/agent/start.tsx | 13 + examples/host-test/src/events/agent/stop.tsx | 13 + .../host-test/src/events/compact/after.tsx | 13 + .../host-test/src/events/compact/before.tsx | 13 + .../host-test/src/events/config/change.tsx | 13 + examples/host-test/src/events/file/change.tsx | 13 + .../src/events/permission/denied.tsx | 13 + .../src/events/permission/request.tsx | 13 + .../host-test/src/events/prompt/submit.tsx | 13 + examples/host-test/src/events/session/end.tsx | 13 + .../host-test/src/events/session/start.tsx | 13 + examples/host-test/src/events/stop.tsx | 13 + .../host-test/src/events/stop/failure.tsx | 13 + .../host-test/src/events/task/complete.tsx | 13 + examples/host-test/src/events/task/create.tsx | 13 + examples/host-test/src/events/tool/after.tsx | 13 + examples/host-test/src/events/tool/before.tsx | 13 + .../host-test/src/events/tool/failure.tsx | 13 + .../host-test/src/events/workspace/open.tsx | 13 + examples/host-test/src/log.ts | 102 ++++++ examples/host-test/src/mcp/host-test-raw.ts | 48 +++ .../src/mcp/host-test/tools/dump.tsx | 28 ++ .../src/mcp/host-test/tools/reset.tsx | 50 +++ .../host-test/src/skills/host-test/SKILL.md | 32 ++ examples/host-test/src/state.ts | 83 +++++ .../host-test/tests/route-unit/routes.test.ts | 214 +++++++++++ examples/host-test/tsconfig.json | 13 + fixtures/host-lineage/claude-2.1.257.ndjson | 32 ++ fixtures/host-lineage/codex-0.147.0.ndjson | 41 +++ fixtures/host-lineage/cursor-3.18.25.ndjson | 87 +++++ package.json | 1 + .../src/mcp/harness/tools/context.tsx | 5 + .../adapters/capabilities/claude-2.1.250.json | 28 ++ .../adapters/capabilities/codex-0.147.0.json | 28 ++ .../capabilities/cursor-2026-08-28.json | 28 ++ .../adapters/capabilities/portable-1.0.0.json | 22 ++ .../src/adapters/hook-contract.ts | 8 +- .../agent-bundle/src/build/entry-shell.ts | 49 ++- .../src/contracts/request-provenance.ts | 23 +- .../dev/playground/lifecycle-render-child.ts | 1 + .../playground/lifecycle-replay-service.ts | 31 ++ .../agent-bundle/src/events/projection.ts | 9 +- .../agent-bundle/src/mcp-server-runtime.ts | 120 +++++- packages/agent-bundle/src/test/mcp.ts | 25 ++ .../tests/adapter-capability-states.test.ts | 32 ++ .../agent-bundle/tests/entry-shell.test.ts | 10 +- .../agent-bundle/tests/event-project.test.ts | 5 +- .../tests/generated-route-server.test.ts | 1 + packages/agent-bundle/tests/hooks.test.ts | 2 +- .../tests/lifecycle-replay-routes.test.ts | 3 +- .../tests/lifecycle-replay-service.test.ts | 8 +- .../tests/packed-stdio-projection.test.ts | 1 + .../tests/projection/mcp-in-memory.test.ts | 1 + .../tests/projection/mcp-lineage.test.ts | 115 ++++++ .../tests/route-unit/render-route.test.ts | 20 + packages/rsc-runtime/package.json | 4 + packages/rsc-runtime/rslib.config.ts | 18 + packages/rsc-runtime/src/agent-request.ts | 61 +++- packages/rsc-runtime/src/index.ts | 4 + packages/rsc-runtime/src/lineage-native.ts | 85 +++++ packages/rsc-runtime/src/lineage/index.ts | 29 ++ packages/rsc-runtime/src/lineage/registry.ts | 345 ++++++++++++++++++ packages/rsc-runtime/src/lineage/state.ts | 174 +++++++++ packages/rsc-runtime/src/notices/state.ts | 11 +- packages/rsc-runtime/src/plugin.ts | 3 + .../tests/lineage-registry.test.ts | 204 +++++++++++ .../src/lifecycles/lifecycles-model.ts | 22 ++ .../src/lifecycles/lifecycles-page.css | 5 + .../src/lifecycles/lifecycles-page.tsx | 37 ++ packages/workbench/src/request-provenance.ts | 30 +- .../lifecycles-page-browser-fixture.tsx | 3 + .../workbench/tests/lifecycle-client.test.ts | 2 + .../workbench/tests/lifecycles-model.test.ts | 2 + .../workbench/tests/lifecycles-page.test.ts | 1 + pnpm-lock.yaml | 25 ++ 90 files changed, 3880 insertions(+), 48 deletions(-) create mode 100644 .changeset/request-lineage.md create mode 100644 docs/audits/2026-09-03-host-lineage-matrix.md create mode 100644 examples/host-test/README.md create mode 100644 examples/host-test/agent-bundle.config.ts create mode 100644 examples/host-test/package.json create mode 100644 examples/host-test/rstest.route-unit.config.ts create mode 100644 examples/host-test/scripts/probe.mjs create mode 100644 examples/host-test/src/capture.ts create mode 100644 examples/host-test/src/cli/dump.tsx create mode 100644 examples/host-test/src/dump.ts create mode 100644 examples/host-test/src/event-route.tsx create mode 100644 examples/host-test/src/events/agent/idle.tsx create mode 100644 examples/host-test/src/events/agent/start.tsx create mode 100644 examples/host-test/src/events/agent/stop.tsx create mode 100644 examples/host-test/src/events/compact/after.tsx create mode 100644 examples/host-test/src/events/compact/before.tsx create mode 100644 examples/host-test/src/events/config/change.tsx create mode 100644 examples/host-test/src/events/file/change.tsx create mode 100644 examples/host-test/src/events/permission/denied.tsx create mode 100644 examples/host-test/src/events/permission/request.tsx create mode 100644 examples/host-test/src/events/prompt/submit.tsx create mode 100644 examples/host-test/src/events/session/end.tsx create mode 100644 examples/host-test/src/events/session/start.tsx create mode 100644 examples/host-test/src/events/stop.tsx create mode 100644 examples/host-test/src/events/stop/failure.tsx create mode 100644 examples/host-test/src/events/task/complete.tsx create mode 100644 examples/host-test/src/events/task/create.tsx create mode 100644 examples/host-test/src/events/tool/after.tsx create mode 100644 examples/host-test/src/events/tool/before.tsx create mode 100644 examples/host-test/src/events/tool/failure.tsx create mode 100644 examples/host-test/src/events/workspace/open.tsx create mode 100644 examples/host-test/src/log.ts create mode 100644 examples/host-test/src/mcp/host-test-raw.ts create mode 100644 examples/host-test/src/mcp/host-test/tools/dump.tsx create mode 100644 examples/host-test/src/mcp/host-test/tools/reset.tsx create mode 100644 examples/host-test/src/skills/host-test/SKILL.md create mode 100644 examples/host-test/src/state.ts create mode 100644 examples/host-test/tests/route-unit/routes.test.ts create mode 100644 examples/host-test/tsconfig.json create mode 100644 fixtures/host-lineage/claude-2.1.257.ndjson create mode 100644 fixtures/host-lineage/codex-0.147.0.ndjson create mode 100644 fixtures/host-lineage/cursor-3.18.25.ndjson create mode 100644 packages/agent-bundle/tests/projection/mcp-lineage.test.ts create mode 100644 packages/rsc-runtime/src/lineage-native.ts create mode 100644 packages/rsc-runtime/src/lineage/index.ts create mode 100644 packages/rsc-runtime/src/lineage/registry.ts create mode 100644 packages/rsc-runtime/src/lineage/state.ts create mode 100644 packages/rsc-runtime/tests/lineage-registry.test.ts diff --git a/.changeset/request-lineage.md b/.changeset/request-lineage.md new file mode 100644 index 000000000..2d7f986c4 --- /dev/null +++ b/.changeset/request-lineage.md @@ -0,0 +1,6 @@ +--- +'@agent-bundle/runtime': patch +'agent-bundle': patch +--- + +Add `request.lineage` to `AgentRequestContext` on every surface (event routes, generated MCP tools, routed CLI, rendered scripts): `{ conversation, root, parent?, depth, generation?, subagent?, resolution }` resolved by the new runtime-held agent lineage registry (`@agent-bundle/runtime/lineage`, journaled through the state kernel beside project state) that the `agent/start`/`agent/stop` and `tool/before`/`tool/after` families feed, with hook→MCP correlation from Claude `claudecode/toolUseId`, Codex `x-codex-turn-metadata`, and Cursor's open `MCP:` pre-tool hook. Unavailable lineage carries a typed reason (`no-subagent-events`, `id-not-resolvable`, `cloud-agent-no-user-hooks`, `no-shared-runtime`, `unsupported-surface`, `not-provided`); every pinned capability table gains dated `lineage` rows, the Workbench Lifecycles view shows the lineage axis and chain, `openInMemoryMcpServer` accepts `lineage`/`lineageHost`, and Claude `PostToolUse` hooks now accept the content-block array `tool_response` that MCP tools deliver instead of failing the route. diff --git a/README.md b/README.md index 0d034428e..b27a07c28 100644 --- a/README.md +++ b/README.md @@ -90,6 +90,7 @@ The [package README](packages/agent-bundle/README.md) is the full reference: con | [Hooks and Scripts](examples/hooks-and-scripts) | simulate a hook and inspect script traces | `pnpm example:hooks` | | [MCP App](examples/mcp-app) | an interactive MCP App with a deterministic eval | `pnpm example:mcp-app` | | [Audiobook Curator](examples/audiobook-curator) | a real media-management plugin for Claude or Codex | `pnpm example:audiobook` | +| [Host Test](examples/host-test) | probe what Claude, Codex, and Cursor send to hooks and MCP calls | `pnpm example:host-test` | Run these from the repository root. `pnpm examples:check` validates and builds every example noninteractively. diff --git a/docs/audits/2026-09-03-host-lineage-matrix.md b/docs/audits/2026-09-03-host-lineage-matrix.md new file mode 100644 index 000000000..b358e794c --- /dev/null +++ b/docs/audits/2026-09-03-host-lineage-matrix.md @@ -0,0 +1,189 @@ +# Host lineage evidence matrix — what each host tells a plugin about conversations and subagents + +Date: 2026-09-03. Probe: `examples/host-test` (this repository, built from the +same commit as this document) installed into isolated homes under +`/tmp/host-test/-home` through `agent-bundle install `; the real +`~/.claude`, `~/.codex`, and `~/.cursor` were never opened. Every number below +comes from the redacted capture logs checked in under `fixtures/host-lineage/` +(`claude-2.1.257.ndjson`, `codex-0.147.0.ndjson`, `cursor-3.18.25.ndjson`); +ids are quoted as recorded, e-mail addresses and the operator home directory +are redacted, and long tool payloads are clipped. + +| Host | Binary observed | Session driver | Subagent mechanism exercised | Depth reached | +| --- | --- | --- | --- | --- | +| Claude Code | 2.1.257 (`claude -p`, `--dangerously-skip-permissions`) | Real Claude Code process; the model was a scripted stand-in behind `ANTHROPIC_BASE_URL` because this machine has no signed-in Claude account (`claude auth status` → `loggedIn: false`). Hooks, MCP, and subagent plumbing are the host's own. | `Agent` tool (`subagent_type: general-purpose`), subagent spawned a nested `Agent` | 2 | +| Codex CLI | 0.147.0 (`codex exec --json --dangerously-bypass-hook-trust`, `[features] multi_agent`, `[agents] max_depth = 3`) | Real model (`gpt-5.6-sol`) with the operator's `auth.json` copied byte-for-byte into the isolated `CODEX_HOME` | `collaborationspawn_agent` (`fork_turns: all`), the spawned thread spawned a nested thread | 2 | +| Cursor IDE | 3.18.25 desktop, isolated `--user-data-dir` on Xvfb, `cursorAuth/*` profile rows transplanted, driven over CDP in the Agents pane (`Auto` model) | Real model | `Task` tool (`subagent_type: general-purpose`), the subagent spawned a nested `Task` | 2 | +| Cursor CLI (`cursor-agent`) | 2026.08.31 build present | **Not driven**: `cursor-agent status` → `Not logged in`, and logging in requires a browser flow. | — | — | +| Portable (Agent Plugins 1.0.0) | — | No hooks surface exists in the contract, so nothing to capture. | — | — | + +Terminology: "root" is the conversation the user typed into; "subagent" is a +child spawned by the root; "nested" is a child of that subagent. `*` marks a +field the framework already lifts into the request context. + +## 1. Ids present per host × event (as delivered to plugin hooks) + +### Claude Code 2.1.257 + +| Event (native) | `session_id`* | `agent_id` | `agent_type` | `tool_use_id` | `prompt_id` | `transcript_path` / `agent_transcript_path` | Other | +| --- | --- | --- | --- | --- | --- | --- | --- | +| SessionStart | root | — | — | — | — | root transcript | `source`, `cwd`, no `permission_mode` | +| UserPromptSubmit | root | — | — | — | yes | root | `prompt`, `permission_mode` | +| PreToolUse / PostToolUse (root turn) | root | — | — | `toolu_…` | yes | root | `tool_name`, `tool_input`, `tool_response`, `duration_ms` (Post) | +| PreToolUse / PostToolUse (inside a subagent) | **root** | **subagent's** (`aca96ce761c9f0cea`) | `general-purpose` | `toolu_…` | root's | root transcript (not the subagent's) | same | +| PreToolUse / PostToolUse (inside the nested agent) | **root** | **nested's** (`ac093bdad0566ffa7`) | `general-purpose` | | root's | root | no reference to `aca96…` | +| SubagentStart | root | the new agent | `general-purpose` | — | yes | root transcript | **no parent agent id** | +| SubagentStop | root | the stopping agent | `general-purpose` | — | yes | root transcript + `agent_transcript_path` = `/subagents/agent-.jsonl` (flat; nested agent's path does not name its parent) | `stop_hook_active`, `last_assistant_message`, `background_tasks[]` (lists every running subagent with `id`, `type: subagent`, `agent_type`, `description`), `session_crons` | +| Stop | root | — | — | — | yes | root | `background_tasks[]`, `session_crons` | +| SessionEnd | root | — | — | — | yes | root | `reason` | + +Not observed in the scenario (the host did not emit them): `Notification`, +`PermissionRequest`/`PermissionDenied` (permissions were bypassed), +`PreCompact`/`PostCompact`, `FileChanged`, `ConfigChange`, `TaskCreated`/ +`TaskCompleted`, `TeammateIdle`, `StopFailure`, `PostToolUseFailure`. + +Payload excerpt (SubagentStart of the nested agent — note the absence of any +parent field): + +```json +{"session_id":"a7f96472-e9d0-447a-826d-36da9b635fd6","transcript_path":"…/-tmp-host-test-claude-workspace/a7f96472-….jsonl","cwd":"/tmp/host-test/claude-workspace","prompt_id":"96a54da1-f00b-48ec-8f84-2d42b7de5ba4","agent_id":"ac093bdad0566ffa7","agent_type":"general-purpose","hook_event_name":"SubagentStart"} +``` + +### Codex CLI 0.147.0 + +| Event (native) | `session_id`* | `agent_id` | `agent_type` | `turn_id` | `tool_use_id` | `transcript_path` / `agent_transcript_path` | Other | +| --- | --- | --- | --- | --- | --- | --- | --- | +| SessionStart | root thread | — | — | — | — | root rollout | `model`, `permission_mode`, `source` | +| UserPromptSubmit | root | — | — | root turn | — | root rollout | `prompt`, `model`, `permission_mode` | +| PreToolUse / PostToolUse (root turn) | root | — | — | root turn | `exec-` (shell/patch/MCP) or `call_` (collaboration tools) | root rollout | `tool_name` is `Bash`, `apply_patch`, `mcp__host_test__dump`, `collaborationspawn_agent`, `collaborationwait_agent`; `tool_response` is a string for shell/patch and an object for MCP | +| PreToolUse / PostToolUse (inside a subagent) | **root** | **subagent thread** (`01a06660-8faf-…`) | `default` | **subagent's own turn** | | **the subagent's own rollout** | | +| PreToolUse / PostToolUse (inside the nested thread) | **root** | **nested thread** (`01a06661-100a-…`) | `default` | nested turn | | nested rollout | no reference to the parent thread | +| SubagentStart | root | new thread | `default` | new thread's turn | — | **the new thread's own rollout** | `model`, `permission_mode`; **no parent id** | +| SubagentStop | root | stopping thread | `default` | its turn | — | `transcript_path` = **the parent thread's rollout**, `agent_transcript_path` = own rollout | `stop_hook_active`, `last_assistant_message` | +| Stop | root | — | — | root turn | — | root rollout | `last_assistant_message` | +| SessionEnd | root | — | — | — | — | root rollout | `reason: "other"`; delivered only after the MCP-hosted runtime had exited, so it ran through the standalone fallback | + +The `message` argument of `collaborationspawn_agent` reaches hooks +**encrypted** (`gAAAA…` token), so a hook cannot read the child's task text. +Codex writes `Skill descriptions were shortened…` and hook-trust warnings as +`item.type: "error"` stream items; they are advisory. + +Payload excerpt (SubagentStop of the nested thread — parent recoverable only +from the rollout filename in `transcript_path`): + +```json +{"session_id":"01a06660-110e-7290-8d1c-8ef1b2b68fc2","turn_id":"01a06661-1086-75c0-abff-e27b0913fccf","transcript_path":"…/rollout-2026-09-03T08-26-39-01a06660-8faf-7122-80af-24ba2da81ad7.jsonl","agent_transcript_path":"…/rollout-2026-09-03T08-27-12-01a06661-100a-7ad3-a0f5-b0e6ffdb4b11.jsonl","cwd":"/tmp/host-test/codex-workspace","hook_event_name":"SubagentStop","model":"gpt-5.6-sol","permission_mode":"bypassPermissions","stop_hook_active":false,"agent_id":"01a06661-100a-7ad3-a0f5-b0e6ffdb4b11","agent_type":"default","last_assistant_message":"…"} +``` + +### Cursor 3.18.25 (desktop) + +| Event (native) | `conversation_id`* | `session_id`* | `generation_id` | `subagent_id` / `tool_call_id` | `parent_conversation_id` | `is_parallel_worker` | `user_email` | Other | +| --- | --- | --- | --- | --- | --- | --- | --- | --- | +| beforeSubmitPrompt | root | = conversation_id | per generation | — | — | — | yes | `prompt`, `attachments`, `model`, `model_id`, `composer_mode`, `cursor_version`, `workspace_roots`, `transcript_path: null` | +| preToolUse / postToolUse (root) | root | = conversation_id | per generation | `tool_use_id` (`call--\nfc__` for model tools, plain uuid for `Shell` and `MCP:*`) | — | — | yes | `tool_name` (`Read`, `Grep`, `Shell`, `Write`, `Task`, `MCP:dump`, `MCP:probe`), `tool_input`, `tool_output` (JSON string, Post), `duration` (Post), `cwd: ""` on `Shell`, `model: ""` on `Task` | +| preToolUse / postToolUse (inside a subagent) | **a new conversation id** (`bf617dfd-…`) | = that new id | new | tool_use_id | **absent** | **absent** | yes | **nothing in the payload names the parent** | +| preToolUse / postToolUse (inside the nested agent) | another new id (`46efda32-…`) | = id | new | | absent | absent | yes | | +| subagentStart | **the parent's** conversation id | = parent | **equals the conversation id** (not a generation) | `subagent_id` = `tool_call_id` = the parent's `Task` `tool_use_id` (a two-line composite) | = conversation_id | `false` | yes | `subagent_type`, `subagent_model`, `task` (full prompt), parent `transcript_path`; **the child's conversation id is not included** | +| subagentStop | parent's | = parent | = conversation id | `subagent_id` | = conversation_id | — | yes | `status`, `duration_ms`, `message_count`, `tool_call_count`, `loop_count`, `task`, `description`, `agent_transcript_path: null` | +| stop | root | = root | root generation | — | — | — | yes | `status`, `loop_count`, `input_tokens`, `output_tokens`, `cache_read_tokens`, `cache_write_tokens`, root `transcript_path` | + +Not delivered to the plugin in this run: `sessionStart` (never fired for the +plugin; the sibling raw-hooks probe on the same build saw none either), +`workspaceOpen` (fired to user-level hooks only), `sessionEnd` (nothing arrived +when the window was closed with the agent idle), `postToolUseFailure`, +`preCompact`. `preToolUse` was delivered twice for some `Read`/`Grep` calls +with the same `tool_use_id` (pairs 3/4, 9/10, … in the fixture). + +Payload excerpt (subagentStart — the only place the parent link exists, and it +does not name the child conversation): + +```json +{"conversation_id":"b60ae0c1-2f85-4c4d-b3e5-b512f9b06e4c","generation_id":"b60ae0c1-2f85-4c4d-b3e5-b512f9b06e4c","model":"default","subagent_id":"call-2ec9530d-b502-4c4f-8a6e-63f0bf7ebc9a-29\nfc_49466487-df47-9fb4-8b10-079ee845fb97_0","subagent_type":"general-purpose","task":"…","parent_conversation_id":"b60ae0c1-2f85-4c4d-b3e5-b512f9b06e4c","tool_call_id":"call-2ec9530d-…\nfc_49466487-…_0","subagent_model":"default","is_parallel_worker":false,"session_id":"b60ae0c1-2f85-4c4d-b3e5-b512f9b06e4c","hook_event_name":"subagentStart","cursor_version":"3.18.25","workspace_roots":["/tmp/host-test/cursor-workspace"],"user_email":"probe@example.invalid","transcript_path":"…/agent-transcripts/b60ae0c1-…/b60ae0c1-….jsonl"} +``` + +## 2. Which id a subagent's own events carry + +| Host | Root events carry | Subagent events carry | Nested events carry | Parent named on the child's events? | Parent named on subagent start/stop? | +| --- | --- | --- | --- | --- | --- | +| Claude | `session_id` | root `session_id` + own `agent_id` | root `session_id` + own `agent_id` | no | no (only `agent_id` of the child) | +| Codex | `session_id` (= root thread), `turn_id` | root `session_id` + own `agent_id` (= thread id) + own `turn_id` | same shape | no | not on start; **stop** carries the parent's rollout path in `transcript_path` | +| Cursor | `conversation_id` (= `session_id`) + `generation_id` | **a fresh `conversation_id`** with no marker | fresh `conversation_id` | **no** | yes — `parent_conversation_id` on start/stop, but the child's conversation id is absent, so the link is only closable by ordering | + +Depth: every host allowed depth 2 in this scenario (Codex configured +`max_depth = 3`; Claude reported `subagent_stats.max_depth: 2`; Cursor ran a +nested `Task`). None emits a depth counter. + +## 3. Hook ↔ MCP ordering and what the MCP server can see + +Ordering was identical on all three hosts: the pre-tool hook for the MCP call +fires, then the MCP server receives `tools/call`, then the post-tool hook +fires (fixture rows Claude 5→6, Codex 9→10→11, Cursor 81→82→83). + +| Host | Pre-tool hook `tool_name` for an MCP call | `tool_use_id` | MCP `tools/call` `_meta` | Client info | MCP session id | Can the server correlate without hooks? | +| --- | --- | --- | --- | --- | --- | --- | +| Claude | `mcp__plugin_host-test_host-test__dump` | `toolu_…` | `{ progressToken, "claudecode/toolUseId": "" }` | `claude-code` 2.1.257 | none (stdio) | **Yes** — `claudecode/toolUseId` equals the hook's `tool_use_id`; the hook supplies `session_id`/`agent_id` | +| Codex | `mcp__host_test__dump` | `exec-` | `{ progressToken, plugin_id, threadId, "x-codex-turn-metadata": { session_id, thread_id, turn_id, parent_thread_id?, forked_from_thread_id?, thread_source: "user"|"subagent", subagent_kind?, sandbox, workspaces{…git commit…}, model, reasoning_effort, turn_started_at_unix_ms } }` | `codex-mcp-client` 0.147.0 | none | **Yes, fully** — lineage (thread, parent, root) is in `_meta` itself | +| Cursor | `MCP:dump` | plain uuid | `{ progressToken }` only | `cursor-vscode` 1.0.0 | none | **No** — only the pre-tool hook (tool name + ordering) can attach a conversation | + +Claude's `PostToolUse` for MCP tools delivers `tool_response` as an **array of +content blocks**, not an object; the framework's pinned validator rejected +every such event (`native tool_response must be an object`, confirmed in the +host's `--debug hooks` log). Fixed in this change set. + +## 4. Environment variable names seen by plugin processes (names only) + +| Host | Hook process (standalone wrapper) | MCP server process | +| --- | --- | --- | +| Claude | `CLAUDE_CODE_CHILD_SESSION`, `CLAUDE_CODE_ENTRYPOINT`, `CLAUDE_CODE_MESSAGING_SOCKET`, `CLAUDE_CODE_MESSAGING_TOKEN`, `CLAUDE_CODE_SESSION_ID`, `CLAUDE_CONFIG_DIR`, `CLAUDE_ENV_FILE`, `CLAUDE_PID`, `CLAUDE_PLUGIN_DATA`, `CLAUDE_PLUGIN_ROOT`, `CLAUDE_PROJECT_DIR` (+ inherited `ANTHROPIC_*`) | `AGENT_BUNDLE_PLUGIN_ROOT`, `CLAUDE_CODE_ENTRYPOINT`, `CLAUDE_CODE_MESSAGING_SOCKET`, `CLAUDE_CODE_MESSAGING_TOKEN`, `CLAUDE_CODE_SESSION_ID`, `CLAUDE_CONFIG_DIR`, `CLAUDE_PLUGIN_DATA`, `CLAUDE_PLUGIN_ROOT`, `CLAUDE_PROJECT_DIR` | +| Codex | `CODEX_HOME`, `CLAUDE_PLUGIN_DATA`, `CLAUDE_PLUGIN_ROOT`, `PLUGIN_DATA`, `PLUGIN_ROOT` (full operator environment inherited, e.g. `HOST_TEST_LOG_DIR`) | `AGENT_BUNDLE_PLUGIN_ROOT` only — Codex does **not** pass the operator environment to MCP servers | +| Cursor | `CURSOR_EXTENSION_HOST_ROLE`, `CURSOR_PLUGIN_ROOT`, `CURSOR_PROJECT_DIR`, `CURSOR_USER_EMAIL`, `CURSOR_VERSION`, `CURSOR_WORKSPACE_LABEL`, `CLAUDE_PLUGIN_ROOT`, `CLAUDE_PROJECT_DIR` | `AGENT_BUNDLE_PLUGIN_ROOT` (+ the IDE's inherited environment) | + +`CLAUDE_CODE_SESSION_ID` is the only per-conversation id any host exposes +through the environment, and it is the root session, not the subagent. Cursor +gives shell commands the agent runs `CURSOR_CONVERSATION_ID`/`CURSOR_REQUEST_ID` +(observed in this operator's own shell), but hook processes receive neither. + +## 5. Answers to the maintainer's question + +**Can the root plugin know its children?** + +| Host | Answer | How | +| --- | --- | --- | +| Claude | Yes, with the parent inferred | `SubagentStart` names the child (`agent_id`). The parent is not in the payload; it is the agent whose `Agent`/`Task` `PreToolUse` is open when `SubagentStart` fires (root when none is open). `Stop`/`SubagentStop` also list every running child in `background_tasks[]`. | +| Codex | Yes | `SubagentStart` names the child thread; the parent is inferred from the open `collaborationspawn_agent` call and confirmed at `SubagentStop` by the parent rollout in `transcript_path`. MCP calls carry `parent_thread_id` directly. | +| Cursor | Yes for the spawn, weakly for the child's traffic | `subagentStart` carries `parent_conversation_id`, `subagent_id`/`tool_call_id`, `is_parallel_worker`. The child's own `conversation_id` is not in that payload, so the first event with an unseen conversation id after a `subagentStart` is bound to it (unambiguous when children start sequentially; ambiguous for parallel workers). | + +**Can a plugin running under a subagent know its parent/root?** + +| Host | Root | Parent | +| --- | --- | --- | +| Claude | Yes — `session_id` on every event is the root session | Only through the runtime's registry (inferred at `SubagentStart`); nothing in the child's payload | +| Codex | Yes — `session_id` is the root thread on every event, and `_meta.x-codex-turn-metadata.session_id` on MCP calls | Yes on MCP calls (`parent_thread_id`); on hooks only through the registry (or the parent rollout at `SubagentStop`) | +| Cursor | Only through the registry — a child's payload carries neither root nor parent | Only through the registry (ordering-bound) | + +**Actor principal facts** (for #391): Cursor delivers `user_email` on every hook +payload and `CURSOR_USER_EMAIL` in the hook environment; Claude and Codex +deliver no user identity to hooks or MCP servers. + +## 6. Framework consequences landed with this audit + +- `request.lineage` on `AgentRequestContext` (events, generated MCP tools, + routed CLI, rendered scripts): `{ conversation, generation?, parent?, root, + depth, subagent? }` resolved by the runtime-held registry described in + `docs/entry-conventions.md`, or a typed `unavailable` reason + (`no-subagent-events`, `id-not-resolvable`, `cloud-agent-no-user-hooks`, + `no-shared-runtime`, `unsupported-surface`). +- Hook→MCP correlation: Codex from `_meta`, Claude from + `claudecode/toolUseId`, Cursor from the open `MCP:` pre-tool hook. +- Claude `PostToolUse` array `tool_response` accepted. + +## 7. Gaps and host-blocked items + +| Gap | Host | Evidence | Status | +| --- | --- | --- | --- | +| No parent id on `SubagentStart`; child events carry no parent | Claude, Codex | §1, §2 | Inferred from the open spawn tool call; filed as a host request | +| Child conversation id absent from `subagentStart`; child events carry no parent/root | Cursor | §1, §2 | Ordering-bound in the registry; ambiguous for parallel workers; filed | +| `_meta` carries no conversation/tool-call id | Cursor | §3 | Hook-correlated only; filed | +| `sessionStart`, `workspaceOpen`, `sessionEnd` not delivered to plugin hooks | Cursor | §1 | Recorded; owned by the Cursor installer/emitter lane for follow-up | +| Cursor CLI not exercised | Cursor | table above | Needs a signed-in `cursor-agent`; not attempted on the operator's account | +| Claude session used a scripted model | Claude | table above | Host plumbing is real; model text is not evidence of anything | diff --git a/docs/entry-conventions.md b/docs/entry-conventions.md index eb0d087c9..c15cef544 100644 --- a/docs/entry-conventions.md +++ b/docs/entry-conventions.md @@ -381,12 +381,64 @@ await renderRoute('tool:curator/status', { }); ``` -The same seam accepts `actor`, `workspace`, and `capabilities`; tests can use -`unavailable(...)` to pin a transport's honest absence semantics. `invokeCli` -(routed commands) and `runScript` (conventional scripts) accept the same -`context` for their rendered surfaces and open the request scope with the +The same seam accepts `actor`, `workspace`, `lineage`, and `capabilities`; +tests can use `unavailable(...)` to pin a transport's honest absence semantics. +`invokeCli` (routed commands) and `runScript` (conventional scripts) accept the +same `context` for their rendered surfaces and open the request scope with the surface-specific `invocation.kind` the generated executable would use. +#### Conversation lineage (`request.lineage`) + +`(await agent()).lineage` is an `Observed` with one shape on +every surface — event routes, generated MCP tools, routed CLI commands, and +rendered scripts: + +```ts +interface AgentLineage { + conversation: string; // the agent whose activity this is + root: string; // the user-facing conversation at depth 0 + parent?: string; // absent at the root + depth: number; // 0 at the root, +1 per subagent level + generation?: string; // Cursor generation_id, Codex turn_id, Claude prompt_id + subagent?: { id: string; type?: string; toolCallId?: string; isParallelWorker?: boolean }; + resolution: 'native' | 'registry' | 'inferred'; +} +``` + +Hooks are thin clients to the warm runtime, so lineage is runtime-held state: +the generated MCP process owns an **agent lineage registry** +(`@agent-bundle/runtime/lineage`), journaled through the state kernel beside +the project's own durable state (`/state`, definition id +`@agent-bundle/runtime/agent-lineage/v1`, bounded retention of stopped nodes +and unclaimed spawn calls). The `agent/start` and `agent/stop` families feed +it, `tool/before`/`tool/after` open and close the correlation window every +MCP call is matched against, and the registry resolves `parent`/`root`/`depth` +for every event by the id the payload carries. The observed host vocabulary +(2026-09-03, [evidence matrix](audits/2026-09-03-host-lineage-matrix.md)): + +| Host | `conversation` | `root` | Parent of a new subagent | MCP call correlation | +| --- | --- | --- | --- | --- | +| Claude | `agent_id`, else `session_id` | `session_id` | the agent whose `Agent`/`Task` `PreToolUse` is the newest unclaimed spawn | `_meta["claudecode/toolUseId"]` = the open `PreToolUse` `tool_use_id` | +| Codex | `agent_id`, else `session_id` | `session_id` | the thread whose `spawn_agent` call is the newest unclaimed spawn | `_meta["x-codex-turn-metadata"]` carries `thread_id`, `parent_thread_id`, `session_id`, `turn_id` natively | +| Cursor | `conversation_id` | the bound root | `parent_conversation_id` on `subagentStart`; the child's fresh `conversation_id` is bound to the newest pending start when it first speaks | the newest open `preToolUse` whose `tool_name` is `MCP:` | + +`resolution` says which of those paths produced the answer. When none can, +the axis is `unavailable` with a typed reason: `no-subagent-events` (the +target defines no subagent families — portable), `id-not-resolvable` (the +payload names an agent the registry never saw start, e.g. a cold runtime), +`cloud-agent-no-user-hooks` (Cursor cloud agents run no user hooks), +`no-shared-runtime` (a standalone hook process holds no registry; Claude and +Codex root payloads still resolve to depth 0 from the payload alone), +`unsupported-surface` (routed CLI and rendered scripts run outside any host +conversation), or `not-provided` (no registry was mounted). Per-host +capability rows live under `lineage` in each pinned capability table. + +Route-unit tests inject the axis through the same context seam +(`context: { lineage: available({ conversation, root, depth: 0, resolution: 'native' }, 'native') }`); +the in-memory MCP proof level accepts a registry +(`openInMemoryMcpServer({ lineage, lineageHost })`) so hook→MCP correlation +is testable without a spawned process. + ### Migration nudges Source validation reports **informational** nudges (never errors — migrations diff --git a/docs/framework-mode.md b/docs/framework-mode.md index 996b03d13..85e2ad00e 100644 --- a/docs/framework-mode.md +++ b/docs/framework-mode.md @@ -16,7 +16,8 @@ Agent Bundle has one newcomer model: Component. It does the work and returns `Agent.*`; there is no public `execute`/`render` split. 4. **Opt in to context.** Call `await agent()` inside that component only when - host, session, actor, workspace, capability, or state context is needed. + host, session, actor, workspace, lineage, capability, or state context is + needed. 5. **Share the shell once.** An optional `src/layout.tsx` (and `src/mcp//layout.tsx` for one server) default-exports a component receiving `{ children, route, signal }` (`AgentLayoutProps` from @@ -104,11 +105,16 @@ public host wire protocol. Every generated request scope — MCP tools, resources, and prompts, event routes, plain and rendered routed CLI commands, rendered scripts, and Workbench replay — installs the same typed `AgentRequestContext`. `await agent()` -returns the invocation plus `Observed` `host`, `session`, `actor`, and -`workspace` axes (an `available` value with its provenance, or a typed -`unavailable` reason — never a fabricated string), request capabilities, -progress, the request signal, and the `state`, `notices`, and `providers` -slots. The handle is request-scoped: it survives `await`, two concurrent +returns the invocation plus `Observed` `host`, `session`, `actor`, +`workspace`, and `lineage` axes (an `available` value with its provenance, or +a typed `unavailable` reason — never a fabricated string), request +capabilities, progress, the request signal, and the `state`, `notices`, and +`providers` slots. `lineage` places the request in the host's conversation +tree — `{ conversation, root, parent?, depth, generation?, subagent? }` — +resolved by the warm runtime's registry that the subagent start/stop and +pre-tool event families feed; see +[Conversation lineage](entry-conventions.md#conversation-lineage-requestlineage) +for the per-host vocabulary and the typed reasons it is unavailable. The handle is request-scoped: it survives `await`, two concurrent requests never observe each other, and reading a captured handle after the request closes throws a typed `AgentRequestError`. A synchronous Server Component or utility that cannot `await` calls `useAgent()` instead; it diff --git a/examples/host-test/README.md b/examples/host-test/README.md new file mode 100644 index 000000000..3bbae0699 --- /dev/null +++ b/examples/host-test/README.md @@ -0,0 +1,109 @@ +# Host Test + +A probing plugin. Install it into a Claude Code, Codex, or Cursor home, drive +one agent session, and read back exactly what that host sent to every plugin +hook and MCP call — the raw envelope, the framework request context each +handler saw, and (once the framework resolves it) the conversation lineage. +It is the acceptance vehicle for `request.lineage` and the evidence source for +`docs/audits/*-host-lineage-matrix.md`. + +From the repository root, launch the Workbench with: + +```bash +pnpm example:host-test +``` + +## What the probe records + +Every canonical event family the framework admits has a semantic event route +under `src/events/**`, each restricted to the hosts whose pinned capability +table supports it. Every route appends one NDJSON line and dispatches a +bounded summary into the durable state kernel (`src/state.ts`, +`host-test/captures`, workspace-durable). A line carries: + +| Field | Contents | +| --- | --- | +| `event.native` | The complete host payload, byte for byte, with secret-looking values replaced by `[redacted]`. | +| `event.canonical` | The framework's canonical identity (`event`, `idempotencyKey`, `observedAt`, `provenance`). | +| `request` | `(await agent())` as the route saw it: `invocation`, `host`, `session`, `actor`, `workspace`, `capabilities`, provider keys, whether state and notices were mounted, and `lineage` when the runtime supplies it. | +| `ids` | Every identity-shaped native field (`conversation_id`, `generation_id`, `session_id`, `subagent_id`, `tool_call_id`, `agent_id`, `turn_id`, `user_email`, …) lifted out for filtering. | +| `process` | `pid`, `ppid`, `cwd`, `execPath`, entry file, uptime — of the process that ran the route. | +| `runtime` | `shared-runtime` when the hook reached the warm MCP-hosted runtime, `standalone-hook` when it fell back to the hook process, `mcp-server`, or `cli`. | +| `env.names` | Environment variable **names** matching `CURSOR_*`, `CLAUDE_*`, `CODEX_*`, `AGENT_BUNDLE_*`, `PLUGIN_*`, `MCP_*`, `HOST_TEST_*`. Values are never written. | + +Two MCP servers ship in the plugin: + +- `host-test` (generated routes, `src/mcp/host-test/tools/`): `dump` (filter by + any conversation/session/subagent id, `full` for raw lines) and `reset`. Each + `dump` call records the request context the generated server mounted for it. +- `host-test-raw` (hand-rolled stdio factory, `src/mcp/host-test-raw.ts`): + `probe` records the raw SDK request context — session id, JSON-RPC id, + `_meta`, lifted envelope, negotiated client info — so hook↔MCP correlation is + judged against the wire. + +The rendered CLI `host-test dump [--conversation ] [--full] [--log ]` +(`dist/bin/host-test.js`) reads the same log outside any host. + +The log lives at `$HOST_TEST_LOG_DIR/captures.ndjson` when that variable is +set, otherwise `$AGENT_BUNDLE_PLUGIN_ROOT/state/host-test/captures.ndjson` +(the installed plugin root the host hands its MCP servers), otherwise beside +the artifact that ran the hook, otherwise `~/.host-test/`. `dump` always +prints the path it used. + +## Scripted probing lifecycle + +Everything runs in an isolated home under `/tmp/host-test/-home` +(override with `HOST_TEST_ROOT`); the real `~/.claude`, `~/.codex`, and +`~/.cursor` are never opened or written. + +```bash +pnpm --filter @agent-bundle-example/host-test build +pnpm --filter @agent-bundle-example/host-test probe:install claude # or codex | cursor +pnpm --filter @agent-bundle-example/host-test probe:capture claude # one scripted session +pnpm --filter @agent-bundle-example/host-test probe:status claude +pnpm --filter @agent-bundle-example/host-test probe:uninstall claude +``` + +- `probe:install` builds when needed, creates the isolated home plus a scratch + git workspace, copies the host's sign-in file byte-for-byte into the isolated + home (`--no-auth` skips it; the copy is removed by `probe:uninstall`), and + runs `agent-bundle install --from artifact/` with `HOME`, + `CLAUDE_CONFIG_DIR`, or `CODEX_HOME` pointed at the isolated home. For Cursor + it prints the isolated IDE launch line (`--user-data-dir`, `--extensions-dir`). +- `probe:capture` runs the scenario prompt through `claude -p`, `codex exec`, or + `cursor-agent -p`: a shell command, a file edit, `dump`, `probe`, one subagent + that repeats those and tries a nested subagent, then `HOST_TEST_DONE`. The + session transcript and a copy of `captures.ndjson` land in + `/tmp/host-test//`, followed by a rendered `host-test dump`. +- `probe:uninstall` runs the host's own uninstall (`claude plugin uninstall`, + `codex plugin remove`, or removing `~/.cursor/plugins/local/host-test`) and + deletes the isolated home. Captures under `/tmp/host-test//` survive. + +Cursor IDE sessions cannot be driven by `-p`; launch the isolated instance with +the printed command, open the Agents pane, and use the same scenario prompt. + +## Workbench walkthrough + +1. **Overview** lists the twenty event routes, both MCP servers, the skill, and + the routed CLI with their per-target capability judgments — `workspace/open` + is Cursor-only, `task/*` and `file/change` are Claude-only, and portable + carries no hooks at all. +2. **Hooks** simulates any family with canonical input; the route appends a + record to the log and returns an empty result (only `session/start` speaks + an `additional_context` line naming the log path). +3. **Playground** runs `host-test dump` and the `dump` tool against the same + log, so a simulated hook is visible from the MCP surface immediately. +4. **Lifecycles** replays checked-in native receipts and shows the request + context — and lineage — each replay mounted. + +## Noninteractive checks + +```bash +cd examples/host-test +pnpm validate +pnpm build +pnpm typecheck +pnpm test +``` + +`pnpm check` runs the four in order. diff --git a/examples/host-test/agent-bundle.config.ts b/examples/host-test/agent-bundle.config.ts new file mode 100644 index 000000000..4696972c5 --- /dev/null +++ b/examples/host-test/agent-bundle.config.ts @@ -0,0 +1,28 @@ +import { defineConfig } from 'agent-bundle/config'; + +export default defineConfig({ + marketplace: true, + mcp: { + servers: { + // Declared without an entry so the conventional src/mcp/host-test-raw.ts + // factory is served under the framework stdio lifecycle shell. + 'host-test-raw': { transport: 'stdio' }, + }, + }, + plugin: { + description: + 'Probe what each agent host sends to plugin hooks and MCP servers: raw payloads, request context, lineage.', + // The host-native plugin slug; the npm package name is scoped and never + // becomes a slug. + name: 'host-test', + }, + runtime: { node: '22.19.0' }, + // Every canonical event family lives under src/events/** and restricts its + // own targets to the hosts whose pinned capability table supports it, so + // one probe covers claude, codex, and cursor without a per-host config. + // The generated `host-test` MCP server (src/mcp/host-test/tools) hosts the + // shared event runtime; `src/mcp/host-test-raw.ts` is a hand-rolled stdio + // server that records the raw MCP request envelope for correlation. + // The rendered `src/cli/dump.tsx` command compiles into dist/bin/host-test.js. + targets: ['claude', 'codex', 'cursor', 'portable'], +}); diff --git a/examples/host-test/package.json b/examples/host-test/package.json new file mode 100644 index 000000000..926dca108 --- /dev/null +++ b/examples/host-test/package.json @@ -0,0 +1,41 @@ +{ + "name": "@agent-bundle-example/host-test", + "version": "1.0.0", + "private": true, + "license": "Apache-2.0", + "description": "A host-probing agent-bundle plugin: every hook family, an MCP server, and a CLI that record exactly what each host sends.", + "type": "module", + "engines": { + "node": ">=22.19.0" + }, + "files": [ + "artifact", + "README.md" + ], + "bin": { + "host-test": "./dist/bin/host-test.js" + }, + "scripts": { + "build": "agent-bundle build --output artifact", + "check": "pnpm validate && pnpm build && pnpm typecheck && pnpm test", + "dev": "agent-bundle dev", + "probe:install": "node scripts/probe.mjs install", + "probe:uninstall": "node scripts/probe.mjs uninstall", + "probe:capture": "node scripts/probe.mjs capture", + "probe:status": "node scripts/probe.mjs status", + "test": "rstest --config rstest.route-unit.config.ts", + "typecheck": "tsc -p tsconfig.json --noEmit", + "validate": "agent-bundle validate" + }, + "dependencies": { + "@agent-bundle/runtime": "workspace:*", + "@modelcontextprotocol/server": "2.0.0", + "react": "19.2.8", + "zod": "4.5.4" + }, + "devDependencies": { + "@rstest/core": "0.11.10", + "@types/react": "19.2.18", + "agent-bundle": "workspace:*" + } +} diff --git a/examples/host-test/rstest.route-unit.config.ts b/examples/host-test/rstest.route-unit.config.ts new file mode 100644 index 000000000..d4adc77ee --- /dev/null +++ b/examples/host-test/rstest.route-unit.config.ts @@ -0,0 +1,4 @@ +import { defineConfig } from '@rstest/core'; +import { agentBundleRstest } from 'agent-bundle/rstest'; + +export default defineConfig(await agentBundleRstest()); diff --git a/examples/host-test/scripts/probe.mjs b/examples/host-test/scripts/probe.mjs new file mode 100644 index 000000000..de1cdd3aa --- /dev/null +++ b/examples/host-test/scripts/probe.mjs @@ -0,0 +1,331 @@ +#!/usr/bin/env node +// Scripted probe lifecycle: install the built host-test artifact into an +// ISOLATED host home, drive one capture session, copy the log out, and +// uninstall. Nothing here touches the real ~/.claude, ~/.codex, or ~/.cursor. +// +// node scripts/probe.mjs install [--no-auth] [--root ] +// node scripts/probe.mjs capture [--prompt ] [--model ] [--timeout ] +// node scripts/probe.mjs uninstall [--keep-home] +// node scripts/probe.mjs status +import { spawnSync } from 'node:child_process'; +import { copyFileSync, existsSync, mkdirSync, readFileSync, rmSync, statSync, writeFileSync } from 'node:fs'; +import { homedir } from 'node:os'; +import { dirname, join, resolve } from 'node:path'; +import { DatabaseSync } from 'node:sqlite'; +import { fileURLToPath } from 'node:url'; + +const exampleRoot = resolve(dirname(fileURLToPath(import.meta.url)), '..'); +const HOSTS = ['claude', 'codex', 'cursor']; +const PLUGIN = 'host-test'; +const MARKETPLACE = 'host-test-marketplace'; + +const parseArgs = (argv) => { + const [command, host, ...rest] = argv; + const flags = { auth: true, keepHome: false }; + for (let index = 0; index < rest.length; index += 1) { + const flag = rest[index]; + switch (flag) { + case '--no-auth': flags.auth = false; break; + case '--keep-home': flags.keepHome = true; break; + case '--root': flags.root = rest[++index]; break; + case '--prompt': flags.prompt = rest[++index]; break; + case '--model': flags.model = rest[++index]; break; + case '--timeout': flags.timeout = Number(rest[++index]); break; + default: throw new Error(`Unknown flag ${flag}`); + } + } + return { command, flags, host }; +}; + +const { command, flags, host } = parseArgs(process.argv.slice(2)); +if (!['install', 'capture', 'uninstall', 'status'].includes(command) || !HOSTS.includes(host)) { + console.error('usage: probe.mjs [flags]'); + process.exit(2); +} + +const root = resolve(flags.root ?? process.env.HOST_TEST_ROOT ?? '/tmp/host-test'); +const paths = { + artifact: join(exampleRoot, 'artifact', host), + captures: join(root, host), + home: join(root, `${host}-home`), + logDir: join(root, host, 'log'), + workspace: join(root, `${host}-workspace`), +}; +const realHome = homedir(); + +/** The isolated environment every host command runs with. HOME moves; auth is copied opaquely. */ +const isolatedEnvironment = () => { + const environment = { ...process.env, HOME: paths.home, HOST_TEST_LOG_DIR: paths.logDir }; + switch (host) { + case 'claude': + environment.CLAUDE_CONFIG_DIR = join(paths.home, '.claude'); + break; + case 'codex': + environment.CODEX_HOME = join(paths.home, '.codex'); + break; + case 'cursor': + // Cursor reads ~/.cursor from HOME; the IDE additionally needs its own + // --user-data-dir so the real profile is never opened. + break; + default: + throw new Error(`unreachable host ${host}`); + } + // Nothing from the real host homes leaks through inherited variables. + delete environment.ANTHROPIC_API_KEY; + return environment; +}; + +const run = (commandName, args, options = {}) => { + const result = spawnSync(commandName, args, { + cwd: options.cwd ?? exampleRoot, + encoding: 'utf8', + env: options.env ?? isolatedEnvironment(), + maxBuffer: 64 * 1024 * 1024, + stdio: options.inherit ? 'inherit' : 'pipe', + timeout: options.timeout, + }); + if (result.error) throw result.error; + return result; +}; + +const log = (message) => console.log(`[probe:${host}] ${message}`); + +const copyOpaque = (source, destination, label) => { + if (!existsSync(source)) { + log(`no ${label} at ${source}; the isolated home will be unauthenticated`); + return false; + } + mkdirSync(dirname(destination), { recursive: true }); + copyFileSync(source, destination); + const mode = statSync(source).mode & 0o777; + writeFileSync(destination, readFileSync(destination), { mode }); + log(`copied ${label} byte-for-byte into the isolated home (never read as data)`); + return true; +}; + +/** Copies only the `cursorAuth/*` rows; every other profile row stays behind. */ +const transplantCursorAuth = (source, destination) => { + if (!existsSync(source)) { + log(`no Cursor profile store at ${source}; the isolated IDE will be signed out`); + return; + } + const from = new DatabaseSync(`file:${source}?mode=ro`, { open: true, readOnly: true }); + const rows = from.prepare("select key, value from ItemTable where key like 'cursorAuth/%'").all(); + from.close(); + const to = new DatabaseSync(destination); + to.exec('CREATE TABLE IF NOT EXISTS ItemTable (key TEXT UNIQUE ON CONFLICT REPLACE, value BLOB)'); + const insert = to.prepare('INSERT OR REPLACE INTO ItemTable (key, value) VALUES (?, ?)'); + for (const row of rows) insert.run(row.key, row.value); + to.close(); + log(`transplanted ${rows.length} Cursor sign-in row(s) into the isolated profile (values never read as data)`); +}; + +const ensureArtifact = () => { + if (!existsSync(join(paths.artifact, 'INSTALL.md'))) { + log('artifact missing; running pnpm build'); + const built = run('pnpm', ['build'], { env: process.env, inherit: true }); + if (built.status !== 0) throw new Error('pnpm build failed'); + } +}; + +const install = () => { + ensureArtifact(); + mkdirSync(paths.home, { mode: 0o700, recursive: true }); + mkdirSync(paths.logDir, { recursive: true }); + mkdirSync(paths.workspace, { recursive: true }); + if (!existsSync(join(paths.workspace, '.git'))) { + run('git', ['init', '-q', '-b', 'probe-main', paths.workspace], { env: process.env }); + writeFileSync(join(paths.workspace, 'README.md'), '# host-test probe workspace\n'); + run('git', ['-C', paths.workspace, 'add', '.'], { env: process.env }); + run('git', ['-C', paths.workspace, '-c', 'user.email=probe@host-test', '-c', 'user.name=probe', 'commit', '-q', '-m', 'probe workspace'], { env: process.env }); + } + switch (host) { + case 'claude': { + const config = join(paths.home, '.claude'); + mkdirSync(config, { recursive: true }); + if (flags.auth) copyOpaque(join(realHome, '.claude', '.credentials.json'), join(config, '.credentials.json'), 'Claude credentials'); + // Claude keeps onboarding + trust state in ~/.claude.json; seed the + // minimum so a non-interactive turn never blocks on first-run prompts. + writeFileSync(join(paths.home, '.claude.json'), JSON.stringify({ + hasCompletedOnboarding: true, + projects: { [paths.workspace]: { hasTrustDialogAccepted: true } }, + }, null, 2)); + break; + } + case 'codex': { + const codexHome = join(paths.home, '.codex'); + mkdirSync(codexHome, { recursive: true }); + if (flags.auth) copyOpaque(join(realHome, '.codex', 'auth.json'), join(codexHome, 'auth.json'), 'Codex auth.json'); + // Codex 0.147 gates subagents behind the multi-agent features; hooks + // from an installed plugin additionally need trust, which probe:capture + // bypasses per invocation with --dangerously-bypass-hook-trust. + writeFileSync(join(codexHome, 'config.toml'), [ + 'approval_policy = "never"', + 'sandbox_mode = "workspace-write"', + 'suppress_unstable_features_warning = true', + '', + '[agents]', + 'enabled = true', + 'max_depth = 3', + '', + '[features]', + 'multi_agent = true', + '', + '[features.multi_agent_v2]', + 'enabled = true', + '', + ].join('\n')); + break; + } + case 'cursor': { + mkdirSync(join(paths.home, '.cursor'), { recursive: true }); + // The IDE needs its own profile so the real one is never opened; the + // agent pane needs a signed-in account, so the sign-in rows are copied + // out of the real profile store into the empty isolated one. + const userDir = join(paths.home, '.config', 'Cursor', 'User'); + mkdirSync(join(userDir, 'globalStorage'), { recursive: true }); + writeFileSync(join(userDir, 'settings.json'), JSON.stringify({ + 'security.workspace.trust.enabled': false, + 'telemetry.telemetryLevel': 'off', + 'update.mode': 'none', + 'window.restoreWindows': 'none', + }, null, 2)); + if (flags.auth) transplantCursorAuth(join(realHome, '.config', 'Cursor', 'User', 'globalStorage', 'state.vscdb'), join(userDir, 'globalStorage', 'state.vscdb')); + break; + } + default: + throw new Error(`unreachable host ${host}`); + } + const result = run('pnpm', ['exec', 'agent-bundle', 'install', host, '--from', paths.artifact, '--json']); + process.stdout.write(result.stdout); + process.stderr.write(result.stderr); + if (result.status !== 0) throw new Error(`agent-bundle install ${host} failed with ${result.status}`); + log(`installed into isolated home ${paths.home}`); + log(`capture log directory: ${paths.logDir}`); + if (host === 'cursor') { + log('launch the isolated IDE with (add DISPLAY=: under Xvfb; --remote-debugging-port enables CDP driving):'); + log(` HOME=${paths.home} HOST_TEST_LOG_DIR=${paths.logDir} cursor --no-sandbox --disable-gpu --user-data-dir ${join(paths.home, '.config', 'Cursor')} --extensions-dir ${join(paths.home, '.cursor', 'extensions')} --skip-release-notes --disable-workspace-trust --remote-debugging-port=9334 ${paths.workspace}`); + } +}; + +const scenarioPrompt = () => flags.prompt ?? [ + 'You are exercising the host-test probe plugin. Do exactly these steps in order, without asking questions.', + '1. Run the shell command `pwd`.', + '2. Create a file named probe-note.txt in the current directory containing the single line `host-test`.', + '3. Call the `dump` tool of the host-test MCP server with an empty object as arguments and remember its `log.path`.', + '4. Call the `probe` tool of the host-test-raw MCP server with {"note":"root"}.', + '5. If you have a subagent or Task tool, spawn exactly one subagent with these instructions: "Run the shell command `pwd`, call the host-test `dump` tool with {}, call the host-test-raw `probe` tool with {\\"note\\":\\"subagent\\"}, then if you can spawn a nested subagent do so with the instruction to run `pwd` and call `probe` with {\\"note\\":\\"nested\\"}, and finally reply with every id you saw." If you have no subagent tool, say so.', + '6. Reply with exactly one final line: HOST_TEST_DONE ', +].join('\n'); + +const captureClaude = () => { + const args = [ + '-p', scenarioPrompt(), + '--output-format', 'json', + '--dangerously-skip-permissions', + '--model', flags.model ?? 'sonnet', + ]; + log(`claude ${args.slice(2).join(' ')}`); + const result = run('claude', args, { cwd: paths.workspace, timeout: flags.timeout ?? 900_000 }); + return result; +}; + +const captureCodex = () => { + const args = [ + 'exec', + '--skip-git-repo-check', + '--sandbox', 'workspace-write', + '--dangerously-bypass-hook-trust', + '--json', + '-C', paths.workspace, + ...(flags.model === undefined ? [] : ['--model', flags.model]), + scenarioPrompt(), + ]; + log(`codex ${args.slice(0, -1).join(' ')} ""`); + return run('codex', args, { cwd: paths.workspace, timeout: flags.timeout ?? 900_000 }); +}; + +const captureCursor = () => { + const args = [ + '-p', scenarioPrompt(), + '--output-format', 'json', + '--force', + ...(flags.model === undefined ? [] : ['--model', flags.model]), + ]; + log(`cursor-agent ${args.slice(2).join(' ')} (IDE sessions are driven manually; see probe:install output)`); + return run('cursor-agent', args, { cwd: paths.workspace, timeout: flags.timeout ?? 900_000 }); +}; + +const capture = () => { + if (!existsSync(paths.home)) throw new Error(`isolated home ${paths.home} missing; run probe:install ${host} first`); + mkdirSync(paths.captures, { recursive: true }); + const stamp = new Date().toISOString().replaceAll(/[:.]/gu, '-'); + let result; + switch (host) { + case 'claude': result = captureClaude(); break; + case 'codex': result = captureCodex(); break; + case 'cursor': result = captureCursor(); break; + default: throw new Error(`unreachable host ${host}`); + } + writeFileSync(join(paths.captures, `session-${stamp}.stdout.txt`), result.stdout ?? ''); + writeFileSync(join(paths.captures, `session-${stamp}.stderr.txt`), result.stderr ?? ''); + log(`host exit ${result.status}; transcript at ${join(paths.captures, `session-${stamp}.*`)}`); + const logFile = join(paths.logDir, 'captures.ndjson'); + if (existsSync(logFile)) { + const copy = join(paths.captures, `captures-${stamp}.ndjson`); + copyFileSync(logFile, copy); + const lines = readFileSync(copy, 'utf8').split('\n').filter(Boolean).length; + log(`copied ${lines} capture record(s) to ${copy}`); + const dump = run(process.execPath, [join(exampleRoot, 'dist', 'bin', 'host-test.js'), 'dump', '--log', copy], { env: process.env }); + process.stdout.write(dump.stdout); + process.stderr.write(dump.stderr); + } else { + log(`no capture log was written at ${logFile}: the host dispatched no hook and no MCP call reached the probe`); + } +}; + +const uninstall = () => { + if (!existsSync(paths.home)) { + log(`isolated home ${paths.home} is already gone`); + return; + } + const attempt = (commandName, args) => { + const result = run(commandName, args); + log(`${commandName} ${args.join(' ')} -> exit ${result.status}${result.status === 0 ? '' : `: ${(result.stderr || result.stdout).trim().slice(0, 300)}`}`); + }; + switch (host) { + case 'claude': + attempt('claude', ['plugin', 'uninstall', `${PLUGIN}@${MARKETPLACE}`]); + break; + case 'codex': + attempt('codex', ['plugin', 'remove', `${PLUGIN}@${MARKETPLACE}`]); + break; + case 'cursor': + rmSync(join(paths.home, '.cursor', 'plugins', 'local', PLUGIN), { force: true, recursive: true }); + log('removed ~/.cursor/plugins/local/host-test from the isolated home'); + break; + default: + throw new Error(`unreachable host ${host}`); + } + if (!flags.keepHome) { + rmSync(paths.home, { force: true, recursive: true }); + rmSync(paths.workspace, { force: true, recursive: true }); + log(`removed isolated home ${paths.home} and workspace (copied auth included); captures stay in ${paths.captures}`); + } +}; + +const status = () => { + log(`isolated home: ${paths.home} (${existsSync(paths.home) ? 'present' : 'absent'})`); + log(`workspace: ${paths.workspace} (${existsSync(paths.workspace) ? 'present' : 'absent'})`); + const logFile = join(paths.logDir, 'captures.ndjson'); + log(`live log: ${logFile} (${existsSync(logFile) ? `${readFileSync(logFile, 'utf8').split('\n').filter(Boolean).length} record(s)` : 'absent'})`); + log(`captures: ${paths.captures}`); +}; + +switch (command) { + case 'install': install(); break; + case 'capture': capture(); break; + case 'uninstall': uninstall(); break; + case 'status': status(); break; + default: throw new Error(`unreachable command ${command}`); +} diff --git a/examples/host-test/src/capture.ts b/examples/host-test/src/capture.ts new file mode 100644 index 000000000..f32b4f4a7 --- /dev/null +++ b/examples/host-test/src/capture.ts @@ -0,0 +1,284 @@ +import { basename, dirname, resolve } from 'node:path'; + +import { + agent, + type AgentRequestContext, + type AgentStateHandle, + type JsonObject, + type JsonValue, +} from '@agent-bundle/runtime'; +import type { AgentEventRouteProps } from 'agent-bundle'; + +import { appendLogLine, resolveLog, type ResolvedLog } from './log.js'; +import type { CaptureEvents, CaptureSummary, CapturesState } from './state.js'; + +export type CaptureKind = CaptureSummary['kind']; +export type CaptureRuntime = CaptureSummary['runtime']; + +/** Native payload keys that identify a conversation, agent, turn, or tool call on some host. */ +export const IDENTITY_KEYS = Object.freeze([ + 'conversation_id', + 'generation_id', + 'session_id', + 'subagent_id', + 'parent_conversation_id', + 'parent_session_id', + 'tool_call_id', + 'tool_use_id', + 'agent_id', + 'agent_type', + 'subagent_type', + 'is_parallel_worker', + 'is_background_agent', + 'transcript_path', + 'agent_transcript_path', + 'turn_id', + 'thread_id', + 'task_id', + 'teammate_name', + 'team_name', + 'model', + 'user_email', + 'cwd', + 'workspace_roots', + 'source', + 'hook_event_name', +] as const); + +const ENV_NAME_PREFIXES = Object.freeze([ + 'CURSOR_', + 'CLAUDE_', + 'CODEX_', + 'AGENT_BUNDLE_', + 'PLUGIN_', + 'HOST_TEST_', + 'MCP_', + 'ANTHROPIC_', + 'OPENAI_', +] as const); + +// `progressToken` is MCP plumbing, not a credential. +const SECRET_KEY = /(?:(? { + if (typeof value === 'string') { + if (SECRET_KEY.test(key) || SECRET_VALUE.test(value)) return '[redacted]'; + return value; + } + if (Array.isArray(value)) return value.map((item) => redactSecrets(item, key)); + if (value !== null && typeof value === 'object') { + const out: Record = {}; + for (const [nestedKey, nested] of Object.entries(value)) { + out[nestedKey] = redactSecrets(nested, nestedKey); + } + return out; + } + return value; +}; + +/** Variable names only — values never leave the process, redacted or not. */ +export const environmentNames = ( + environment: Readonly> = process.env, +): readonly string[] => Object.keys(environment) + .filter((name) => ENV_NAME_PREFIXES.some((prefix) => name.startsWith(prefix)) || name === 'TERM_PROGRAM') + .sort((left, right) => left.localeCompare(right)); + +const asJson = (value: unknown): JsonValue => JSON.parse(JSON.stringify(value ?? null)) as JsonValue; + +export const extractIds = (native: Readonly>): Record => { + const ids: Record = {}; + for (const key of IDENTITY_KEYS) { + const value = native[key]; + if (typeof value === 'string' || typeof value === 'boolean' || typeof value === 'number' || value === null) { + ids[key] = typeof value === 'string' && value.length > 1024 ? `${value.slice(0, 1021)}...` : value; + } else if (Array.isArray(value) && value.every((item) => typeof item === 'string')) { + ids[key] = value.join('\u0000'); + } + } + return ids; +}; + +const detectRuntime = (context: AgentRequestContext, argv: readonly string[]): CaptureRuntime => { + const entry = argv[1]; + const leaf = entry === undefined ? undefined : basename(dirname(resolve(entry))); + switch (context.invocation.kind) { + case 'event': + return leaf === 'hooks' ? 'standalone-hook' : 'shared-runtime'; + case 'tool': + return 'mcp-server'; + case 'cli': + return 'cli'; + case 'script': + return 'script'; + case 'workbench': + return 'unknown'; + default: { + const unreachable: never = context.invocation.kind; + throw new Error(`Unhandled invocation kind ${String(unreachable)}`); + } + } +}; + +/** The framework request context as the route observed it, minus non-data members. */ +export const snapshotRequest = (context: AgentRequestContext): JsonObject => { + const lineage = (context as AgentRequestContext & { readonly lineage?: unknown }).lineage; + return { + actor: asJson(context.actor), + capabilities: asJson(context.capabilities), + hasNotices: context.notices !== undefined, + hasState: context.state !== undefined, + host: asJson(context.host), + invocation: asJson(context.invocation), + ...(lineage === undefined ? {} : { lineage: asJson(lineage) }), + providers: { + keys: Object.keys(context.providers).sort((left, right) => left.localeCompare(right)), + processLifetime: asJson(context.providers.processLifetime), + }, + session: asJson(context.session), + workspace: asJson(context.workspace), + }; +}; + +export interface CaptureInput { + readonly event?: AgentEventRouteProps; + readonly kind: CaptureKind; + /** Anything the surface saw that the framework context does not carry (raw MCP `extra`, argv). */ + readonly observed?: JsonObject; +} + +export interface CaptureRecord { + readonly env: { readonly names: readonly string[] }; + readonly event?: { readonly canonical: JsonValue; readonly native: JsonValue }; + readonly host: string; + readonly ids: Record; + readonly kind: CaptureKind; + readonly observed?: JsonObject; + readonly process: { + readonly cwd: string; + readonly entry: string | null; + readonly execPath: string; + readonly nodeVersion: string; + readonly pid: number; + readonly ppid: number; + readonly uptimeMs: number; + }; + readonly recordedAt: string; + readonly request: JsonObject; + readonly runtime: CaptureRuntime; + readonly sequence: number; +} + +let sequence = 0; + +const processFacts = (): CaptureRecord['process'] => ({ + cwd: process.cwd(), + entry: process.argv[1] ?? null, + execPath: process.execPath, + nodeVersion: process.version, + pid: process.pid, + ppid: process.ppid, + uptimeMs: Math.round(process.uptime() * 1000), +}); + +/** + * Records an observation from a surface that has no framework request scope + * (the hand-rolled `host-test-raw` stdio server): the raw MCP envelope is the + * whole point, so it is stored verbatim minus secret-looking values. + */ +export const captureRaw = (host: string, observed: JsonObject): { readonly log: ResolvedLog; readonly record: CaptureRecord } => { + const log = resolveLog(); + sequence += 1; + const record: CaptureRecord = { + env: { names: environmentNames() }, + host, + ids: {}, + kind: 'mcp', + observed: redactSecrets(observed) as JsonObject, + process: processFacts(), + recordedAt: new Date().toISOString(), + request: { unavailable: 'hand-rolled stdio server: no framework request context is mounted' }, + runtime: 'mcp-server', + sequence, + }; + appendLogLine(log, asJson(record)); + return { log, record }; +}; + +export interface CaptureOutcome { + readonly log: ResolvedLog; + readonly record: CaptureRecord; + readonly state: + | { readonly revision: number; readonly state: 'committed' } + | { readonly reason: string; readonly state: 'unavailable' }; +} + +const captureState = (context: AgentRequestContext): AgentStateHandle | undefined => + context.state as AgentStateHandle | undefined; + +/** + * Records one observation: the complete raw host payload, the framework's + * canonical request context, process identity, and environment variable + * names. The plain NDJSON line is written first (it is the complete record); + * the durable kernel keeps a bounded summary for cross-process correlation. + */ +export const capture = async (input: CaptureInput): Promise => { + const context = await agent(); + const log = resolveLog(); + const runtime = detectRuntime(context, process.argv); + const native = input.event?.native ?? {}; + const host = context.host.state === 'available' + ? context.host.value.name + : input.event?.canonical.provenance.host ?? 'unknown'; + sequence += 1; + const recordedAt = new Date().toISOString(); + const record: CaptureRecord = { + env: { names: environmentNames() }, + ...(input.event === undefined + ? {} + : { + event: { + canonical: asJson(input.event.canonical), + native: redactSecrets(asJson(input.event.native)), + }, + }), + host, + ids: extractIds(native), + kind: input.kind, + ...(input.observed === undefined ? {} : { observed: redactSecrets(input.observed) as JsonObject }), + process: processFacts(), + recordedAt, + request: snapshotRequest(context), + runtime, + sequence, + }; + appendLogLine(log, asJson(record)); + + const state = captureState(context); + if (state === undefined) { + return { log, record, state: { reason: 'no state handle mounted on this request', state: 'unavailable' } }; + } + const summary: CaptureSummary = { + ...(input.event === undefined ? {} : { event: input.event.canonical.event, nativeEvent: input.event.canonical.provenance.nativeEvent }), + host, + ids: record.ids, + invocationId: context.invocation.id, + kind: input.kind, + recordedAt, + runtime, + sequence, + }; + try { + const committed = await state.dispatch('captured', summary, { + idempotencyKey: `capture:${input.event?.canonical.idempotencyKey ?? context.invocation.id}`, + signal: context.signal, + }); + return { log, record, state: { revision: committed.revision, state: 'committed' } }; + } catch (error) { + return { + log, + record, + state: { reason: error instanceof Error ? error.message : String(error), state: 'unavailable' }, + }; + } +}; diff --git a/examples/host-test/src/cli/dump.tsx b/examples/host-test/src/cli/dump.tsx new file mode 100644 index 000000000..dd6c5deb6 --- /dev/null +++ b/examples/host-test/src/cli/dump.tsx @@ -0,0 +1,47 @@ +import { dirname, resolve } from 'node:path'; + +import { Agent, type JsonValue } from '@agent-bundle/runtime'; +import type { CliRouteConfig, CliRouteProps } from 'agent-bundle'; +import React from 'react'; +import { z } from 'zod'; + +import { capture } from '../capture.js'; +import { dumpCaptures, dumpResultSchema, renderDumpMarkdown } from '../dump.js'; +import { resolveLog } from '../log.js'; + +export const config = { + description: 'Print the host-test capture log: every hook payload and MCP call the probe recorded, with the request context each one saw.', +} satisfies CliRouteConfig; + +// Routed CLI argv projection needs literal zod, so the dump filter is restated +// here; the MCP tool and this command share the same execution in ../dump.ts. +export const inputSchema = z.object({ + conversation: z.string().min(1).max(1024).optional(), + full: z.boolean().optional(), + limit: z.number().int().min(1).max(5000).optional(), + /** Read this captures.ndjson instead of the resolved default. */ + log: z.string().min(1).max(4096).optional(), +}).strict(); + +export const resultSchema = dumpResultSchema; + +export default async function Dump({ input }: CliRouteProps) { + const log = input.log === undefined + ? resolveLog() + : { dir: dirname(resolve(input.log)), path: resolve(input.log), source: 'env:HOST_TEST_LOG_DIR' as const }; + if (input.log === undefined) { + // Only the default log is also written to: a dump of someone else's file + // must not append a record to it. + await capture({ kind: 'cli', observed: { command: 'dump' } }); + } + const result = await dumpCaptures({ + ...(input.conversation === undefined ? {} : { conversation: input.conversation }), + ...(input.full === undefined ? {} : { full: input.full }), + ...(input.limit === undefined ? {} : { limit: input.limit }), + }, log); + return ( + + {renderDumpMarkdown(result)} + + ); +} diff --git a/examples/host-test/src/dump.ts b/examples/host-test/src/dump.ts new file mode 100644 index 000000000..2a392af7b --- /dev/null +++ b/examples/host-test/src/dump.ts @@ -0,0 +1,153 @@ +import { + agent, + type AgentStateHandle, + type JsonObject, + type JsonValue, +} from '@agent-bundle/runtime'; +import { z } from 'zod'; + +import type { CaptureRecord } from './capture.js'; +import { readLog, resolveLog, type ResolvedLog } from './log.js'; +import type { CaptureEvents, CapturesState } from './state.js'; + +export const dumpInputSchema = z.object({ + /** Match any identity field (conversation_id, session_id, subagent_id, ...) exactly. */ + conversation: z.string().min(1).max(1024).optional(), + /** Include the complete raw records instead of the compact summary. */ + full: z.boolean().optional(), + kinds: z.array(z.enum(['event', 'mcp', 'cli'])).optional(), + limit: z.number().int().min(1).max(5000).optional(), +}).strict(); + +export type DumpInput = z.output; + +const stateSummarySchema = z.object({ + reason: z.string().optional(), + revision: z.number().int().nonnegative().optional(), + state: z.enum(['available', 'unavailable']), + summarized: z.number().int().nonnegative().optional(), + total: z.number().int().nonnegative().optional(), +}).strict(); + +export const dumpResultSchema = z.object({ + filter: dumpInputSchema, + log: z.object({ + malformed: z.number().int().nonnegative(), + path: z.string(), + source: z.string(), + }).strict(), + matched: z.number().int().nonnegative(), + records: z.array(z.record(z.string(), z.unknown())), + state: stateSummarySchema, + total: z.number().int().nonnegative(), +}).strict(); + +export type DumpResult = z.output; + +const asCaptures = (records: readonly Record[]): CaptureRecord[] => records + .filter((record) => typeof record['kind'] === 'string' && typeof record['recordedAt'] === 'string') + .map((record) => record as unknown as CaptureRecord); + +const matchesConversation = (record: CaptureRecord, conversation: string): boolean => { + if (Object.values(record.ids).some((value) => value === conversation)) return true; + const session = (record.request as { session?: { value?: { sessionId?: string } } }).session; + if (session?.value?.sessionId === conversation) return true; + const lineage = JSON.stringify((record.request as { lineage?: unknown }).lineage ?? null); + return lineage.includes(JSON.stringify(conversation)); +}; + +/** The compact shape a human or an agent scans first; `full` returns the whole line. */ +export const summarizeRecord = (record: CaptureRecord, index: number): JsonObject => { + const request = record.request as { + readonly lineage?: JsonValue; + readonly session?: JsonValue; + readonly invocation?: { readonly id?: string; readonly kind?: string }; + }; + const observedTool = (record.observed as { readonly tool?: unknown } | undefined)?.tool; + return { + ...(record.event === undefined + ? typeof observedTool === 'string' ? { event: `mcp:${observedTool}` } : {} + : { event: (record.event.canonical as { event: string }).event }), + host: record.host, + ids: record.ids, + index, + invocation: request.invocation?.id ?? null, + kind: record.kind, + ...(request.lineage === undefined ? {} : { lineage: request.lineage }), + ...(record.event === undefined + ? {} + : { nativeEvent: (record.event.canonical as { provenance: { nativeEvent: string } }).provenance.nativeEvent }), + ...(record.observed === undefined ? {} : { observed: record.observed }), + pid: record.process.pid, + recordedAt: record.recordedAt, + runtime: record.runtime, + sequence: record.sequence, + }; +}; + +export const dumpCaptures = async ( + input: DumpInput, + log: ResolvedLog = resolveLog(), +): Promise => { + const { malformed, records } = await readLog(log); + const captures = asCaptures(records); + const indexed = captures.map((record, position) => ({ index: position + 1, record })); + const filtered = indexed + .filter(({ record }) => input.kinds === undefined || input.kinds.includes(record.kind)) + .filter(({ record }) => input.conversation === undefined || matchesConversation(record, input.conversation)); + const limited = input.limit === undefined ? filtered : filtered.slice(Math.max(0, filtered.length - input.limit)); + + let state: DumpResult['state']; + const context = await agent(); + const handle = context.state as AgentStateHandle | undefined; + if (handle === undefined) { + state = { reason: 'no state handle mounted on this request', state: 'unavailable' }; + } else { + try { + const snapshot = await handle.read({ signal: context.signal }); + state = { + revision: snapshot.revision, + state: 'available', + summarized: snapshot.state.captures.length, + total: snapshot.state.total, + }; + } catch (error) { + state = { reason: error instanceof Error ? error.message : String(error), state: 'unavailable' }; + } + } + + return { + filter: input, + log: { malformed, path: log.path, source: log.source }, + matched: filtered.length, + records: input.full === true + ? limited.map(({ index, record }): Record => ({ index, ...record })) + : limited.map(({ index, record }) => summarizeRecord(record, index)), + state, + total: captures.length, + }; +}; + +export const renderDumpMarkdown = (result: DumpResult): string => { + const lines = [ + '# host-test captures', + '', + `- Log: \`${result.log.path}\` (${result.log.source}, ${String(result.total)} records, ${String(result.log.malformed)} malformed)`, + `- Durable state: ${result.state.state === 'available' + ? `revision ${String(result.state.revision)}, ${String(result.state.total)} total, ${String(result.state.summarized)} summarized` + : `unavailable (${result.state.reason ?? 'unknown'})`}`, + `- Matched: ${String(result.matched)}${result.filter.conversation === undefined ? '' : ` for ${result.filter.conversation}`}`, + '', + '| # | kind | event | host | runtime | ids |', + '| --- | --- | --- | --- | --- | --- |', + ]; + for (const record of result.records) { + const summary = record as Partial> & { readonly ids?: JsonObject }; + const ids = Object.entries(summary.ids ?? {}) + .filter(([key]) => key !== 'cwd' && key !== 'hook_event_name' && key !== 'transcript_path' && key !== 'agent_transcript_path') + .map(([key, value]) => `${key}=${String(value)}`) + .join(', '); + lines.push(`| ${String(summary.index ?? '')} | ${String(summary.kind ?? '')} | ${String(summary.event ?? summary.nativeEvent ?? '')} | ${String(summary.host ?? '')} | ${String(summary.runtime ?? '')} | ${ids} |`); + } + return lines.join('\n'); +}; diff --git a/examples/host-test/src/event-route.tsx b/examples/host-test/src/event-route.tsx new file mode 100644 index 000000000..c21d981c5 --- /dev/null +++ b/examples/host-test/src/event-route.tsx @@ -0,0 +1,26 @@ +import { Agent } from '@agent-bundle/runtime'; +import type { AgentEventRouteProps } from 'agent-bundle'; +import React from 'react'; + +import { capture } from './capture.js'; + +/** + * Every event family renders through this one observer: record the complete + * native envelope plus the framework context, then return an empty result so + * no host decision channel is touched. Only `session/start` announces the log + * path, because it is the one family every host lets a plugin speak into. + */ +export const observeEvent = async ( + props: AgentEventRouteProps, + options: { readonly announce?: boolean } = {}, +): Promise => { + const outcome = await capture({ event: props, kind: 'event' }); + if (options.announce !== true) return ; + return ( + + + {`host-test probe is recording this ${props.canonical.provenance.host} session to ${outcome.log.path} (durable state: ${outcome.state.state}).`} + + + ); +}; diff --git a/examples/host-test/src/events/agent/idle.tsx b/examples/host-test/src/events/agent/idle.tsx new file mode 100644 index 000000000..0a7baf6cc --- /dev/null +++ b/examples/host-test/src/events/agent/idle.tsx @@ -0,0 +1,13 @@ +import type { AgentEventRouteConfig, AgentEventRouteProps } from 'agent-bundle'; + +import { observeEvent } from '../../event-route.js'; + +export const config = { + fallback: 'standalone', + runtime: 'shared', + targets: ['claude'], +} satisfies AgentEventRouteConfig; + +export default async function AgentIdle(props: AgentEventRouteProps) { + return observeEvent(props); +} diff --git a/examples/host-test/src/events/agent/start.tsx b/examples/host-test/src/events/agent/start.tsx new file mode 100644 index 000000000..a378bc0fb --- /dev/null +++ b/examples/host-test/src/events/agent/start.tsx @@ -0,0 +1,13 @@ +import type { AgentEventRouteConfig, AgentEventRouteProps } from 'agent-bundle'; + +import { observeEvent } from '../../event-route.js'; + +export const config = { + fallback: 'standalone', + runtime: 'shared', + targets: ['claude', 'codex', 'cursor'], +} satisfies AgentEventRouteConfig; + +export default async function AgentStart(props: AgentEventRouteProps) { + return observeEvent(props); +} diff --git a/examples/host-test/src/events/agent/stop.tsx b/examples/host-test/src/events/agent/stop.tsx new file mode 100644 index 000000000..e23289427 --- /dev/null +++ b/examples/host-test/src/events/agent/stop.tsx @@ -0,0 +1,13 @@ +import type { AgentEventRouteConfig, AgentEventRouteProps } from 'agent-bundle'; + +import { observeEvent } from '../../event-route.js'; + +export const config = { + fallback: 'standalone', + runtime: 'shared', + targets: ['claude', 'codex', 'cursor'], +} satisfies AgentEventRouteConfig; + +export default async function AgentStop(props: AgentEventRouteProps) { + return observeEvent(props); +} diff --git a/examples/host-test/src/events/compact/after.tsx b/examples/host-test/src/events/compact/after.tsx new file mode 100644 index 000000000..5b0534f3a --- /dev/null +++ b/examples/host-test/src/events/compact/after.tsx @@ -0,0 +1,13 @@ +import type { AgentEventRouteConfig, AgentEventRouteProps } from 'agent-bundle'; + +import { observeEvent } from '../../event-route.js'; + +export const config = { + fallback: 'standalone', + runtime: 'shared', + targets: ['claude', 'codex'], +} satisfies AgentEventRouteConfig; + +export default async function CompactAfter(props: AgentEventRouteProps) { + return observeEvent(props); +} diff --git a/examples/host-test/src/events/compact/before.tsx b/examples/host-test/src/events/compact/before.tsx new file mode 100644 index 000000000..c0bf98aee --- /dev/null +++ b/examples/host-test/src/events/compact/before.tsx @@ -0,0 +1,13 @@ +import type { AgentEventRouteConfig, AgentEventRouteProps } from 'agent-bundle'; + +import { observeEvent } from '../../event-route.js'; + +export const config = { + fallback: 'standalone', + runtime: 'shared', + targets: ['claude', 'codex', 'cursor'], +} satisfies AgentEventRouteConfig; + +export default async function CompactBefore(props: AgentEventRouteProps) { + return observeEvent(props); +} diff --git a/examples/host-test/src/events/config/change.tsx b/examples/host-test/src/events/config/change.tsx new file mode 100644 index 000000000..bed8d32d2 --- /dev/null +++ b/examples/host-test/src/events/config/change.tsx @@ -0,0 +1,13 @@ +import type { AgentEventRouteConfig, AgentEventRouteProps } from 'agent-bundle'; + +import { observeEvent } from '../../event-route.js'; + +export const config = { + fallback: 'standalone', + runtime: 'shared', + targets: ['claude'], +} satisfies AgentEventRouteConfig; + +export default async function ConfigChange(props: AgentEventRouteProps) { + return observeEvent(props); +} diff --git a/examples/host-test/src/events/file/change.tsx b/examples/host-test/src/events/file/change.tsx new file mode 100644 index 000000000..4c66974fa --- /dev/null +++ b/examples/host-test/src/events/file/change.tsx @@ -0,0 +1,13 @@ +import type { AgentEventRouteConfig, AgentEventRouteProps } from 'agent-bundle'; + +import { observeEvent } from '../../event-route.js'; + +export const config = { + fallback: 'standalone', + runtime: 'shared', + targets: ['claude'], +} satisfies AgentEventRouteConfig; + +export default async function FileChange(props: AgentEventRouteProps) { + return observeEvent(props); +} diff --git a/examples/host-test/src/events/permission/denied.tsx b/examples/host-test/src/events/permission/denied.tsx new file mode 100644 index 000000000..0db04aa29 --- /dev/null +++ b/examples/host-test/src/events/permission/denied.tsx @@ -0,0 +1,13 @@ +import type { AgentEventRouteConfig, AgentEventRouteProps } from 'agent-bundle'; + +import { observeEvent } from '../../event-route.js'; + +export const config = { + fallback: 'standalone', + runtime: 'shared', + targets: ['claude'], +} satisfies AgentEventRouteConfig; + +export default async function PermissionDenied(props: AgentEventRouteProps) { + return observeEvent(props); +} diff --git a/examples/host-test/src/events/permission/request.tsx b/examples/host-test/src/events/permission/request.tsx new file mode 100644 index 000000000..e72d39680 --- /dev/null +++ b/examples/host-test/src/events/permission/request.tsx @@ -0,0 +1,13 @@ +import type { AgentEventRouteConfig, AgentEventRouteProps } from 'agent-bundle'; + +import { observeEvent } from '../../event-route.js'; + +export const config = { + fallback: 'standalone', + runtime: 'shared', + targets: ['claude', 'codex'], +} satisfies AgentEventRouteConfig; + +export default async function PermissionRequest(props: AgentEventRouteProps) { + return observeEvent(props); +} diff --git a/examples/host-test/src/events/prompt/submit.tsx b/examples/host-test/src/events/prompt/submit.tsx new file mode 100644 index 000000000..e8953004b --- /dev/null +++ b/examples/host-test/src/events/prompt/submit.tsx @@ -0,0 +1,13 @@ +import type { AgentEventRouteConfig, AgentEventRouteProps } from 'agent-bundle'; + +import { observeEvent } from '../../event-route.js'; + +export const config = { + fallback: 'standalone', + runtime: 'shared', + targets: ['claude', 'codex', 'cursor'], +} satisfies AgentEventRouteConfig; + +export default async function PromptSubmit(props: AgentEventRouteProps) { + return observeEvent(props); +} diff --git a/examples/host-test/src/events/session/end.tsx b/examples/host-test/src/events/session/end.tsx new file mode 100644 index 000000000..160f710d6 --- /dev/null +++ b/examples/host-test/src/events/session/end.tsx @@ -0,0 +1,13 @@ +import type { AgentEventRouteConfig, AgentEventRouteProps } from 'agent-bundle'; + +import { observeEvent } from '../../event-route.js'; + +export const config = { + fallback: 'standalone', + runtime: 'shared', + targets: ['claude', 'codex', 'cursor'], +} satisfies AgentEventRouteConfig; + +export default async function SessionEnd(props: AgentEventRouteProps) { + return observeEvent(props); +} diff --git a/examples/host-test/src/events/session/start.tsx b/examples/host-test/src/events/session/start.tsx new file mode 100644 index 000000000..22958a579 --- /dev/null +++ b/examples/host-test/src/events/session/start.tsx @@ -0,0 +1,13 @@ +import type { AgentEventRouteConfig, AgentEventRouteProps } from 'agent-bundle'; + +import { observeEvent } from '../../event-route.js'; + +export const config = { + fallback: 'standalone', + runtime: 'shared', + targets: ['claude', 'codex', 'cursor'], +} satisfies AgentEventRouteConfig; + +export default async function SessionStart(props: AgentEventRouteProps) { + return observeEvent(props, { announce: true }); +} diff --git a/examples/host-test/src/events/stop.tsx b/examples/host-test/src/events/stop.tsx new file mode 100644 index 000000000..0f1ae98a6 --- /dev/null +++ b/examples/host-test/src/events/stop.tsx @@ -0,0 +1,13 @@ +import type { AgentEventRouteConfig, AgentEventRouteProps } from 'agent-bundle'; + +import { observeEvent } from '../event-route.js'; + +export const config = { + fallback: 'standalone', + runtime: 'shared', + targets: ['claude', 'codex', 'cursor'], +} satisfies AgentEventRouteConfig; + +export default async function Stop(props: AgentEventRouteProps) { + return observeEvent(props); +} diff --git a/examples/host-test/src/events/stop/failure.tsx b/examples/host-test/src/events/stop/failure.tsx new file mode 100644 index 000000000..2e5a2b3ed --- /dev/null +++ b/examples/host-test/src/events/stop/failure.tsx @@ -0,0 +1,13 @@ +import type { AgentEventRouteConfig, AgentEventRouteProps } from 'agent-bundle'; + +import { observeEvent } from '../../event-route.js'; + +export const config = { + fallback: 'standalone', + runtime: 'shared', + targets: ['claude'], +} satisfies AgentEventRouteConfig; + +export default async function StopFailure(props: AgentEventRouteProps) { + return observeEvent(props); +} diff --git a/examples/host-test/src/events/task/complete.tsx b/examples/host-test/src/events/task/complete.tsx new file mode 100644 index 000000000..7aa36bdcc --- /dev/null +++ b/examples/host-test/src/events/task/complete.tsx @@ -0,0 +1,13 @@ +import type { AgentEventRouteConfig, AgentEventRouteProps } from 'agent-bundle'; + +import { observeEvent } from '../../event-route.js'; + +export const config = { + fallback: 'standalone', + runtime: 'shared', + targets: ['claude'], +} satisfies AgentEventRouteConfig; + +export default async function TaskComplete(props: AgentEventRouteProps) { + return observeEvent(props); +} diff --git a/examples/host-test/src/events/task/create.tsx b/examples/host-test/src/events/task/create.tsx new file mode 100644 index 000000000..53a444e7f --- /dev/null +++ b/examples/host-test/src/events/task/create.tsx @@ -0,0 +1,13 @@ +import type { AgentEventRouteConfig, AgentEventRouteProps } from 'agent-bundle'; + +import { observeEvent } from '../../event-route.js'; + +export const config = { + fallback: 'standalone', + runtime: 'shared', + targets: ['claude'], +} satisfies AgentEventRouteConfig; + +export default async function TaskCreate(props: AgentEventRouteProps) { + return observeEvent(props); +} diff --git a/examples/host-test/src/events/tool/after.tsx b/examples/host-test/src/events/tool/after.tsx new file mode 100644 index 000000000..e32367e05 --- /dev/null +++ b/examples/host-test/src/events/tool/after.tsx @@ -0,0 +1,13 @@ +import type { AgentEventRouteConfig, AgentEventRouteProps } from 'agent-bundle'; + +import { observeEvent } from '../../event-route.js'; + +export const config = { + fallback: 'standalone', + runtime: 'shared', + targets: ['claude', 'codex', 'cursor'], +} satisfies AgentEventRouteConfig; + +export default async function ToolAfter(props: AgentEventRouteProps) { + return observeEvent(props); +} diff --git a/examples/host-test/src/events/tool/before.tsx b/examples/host-test/src/events/tool/before.tsx new file mode 100644 index 000000000..abba871e6 --- /dev/null +++ b/examples/host-test/src/events/tool/before.tsx @@ -0,0 +1,13 @@ +import type { AgentEventRouteConfig, AgentEventRouteProps } from 'agent-bundle'; + +import { observeEvent } from '../../event-route.js'; + +export const config = { + fallback: 'standalone', + runtime: 'shared', + targets: ['claude', 'codex', 'cursor'], +} satisfies AgentEventRouteConfig; + +export default async function ToolBefore(props: AgentEventRouteProps) { + return observeEvent(props); +} diff --git a/examples/host-test/src/events/tool/failure.tsx b/examples/host-test/src/events/tool/failure.tsx new file mode 100644 index 000000000..4cb6727d6 --- /dev/null +++ b/examples/host-test/src/events/tool/failure.tsx @@ -0,0 +1,13 @@ +import type { AgentEventRouteConfig, AgentEventRouteProps } from 'agent-bundle'; + +import { observeEvent } from '../../event-route.js'; + +export const config = { + fallback: 'standalone', + runtime: 'shared', + targets: ['claude', 'cursor'], +} satisfies AgentEventRouteConfig; + +export default async function ToolFailure(props: AgentEventRouteProps) { + return observeEvent(props); +} diff --git a/examples/host-test/src/events/workspace/open.tsx b/examples/host-test/src/events/workspace/open.tsx new file mode 100644 index 000000000..e43fbd65b --- /dev/null +++ b/examples/host-test/src/events/workspace/open.tsx @@ -0,0 +1,13 @@ +import type { AgentEventRouteConfig, AgentEventRouteProps } from 'agent-bundle'; + +import { observeEvent } from '../../event-route.js'; + +export const config = { + fallback: 'standalone', + runtime: 'shared', + targets: ['cursor'], +} satisfies AgentEventRouteConfig; + +export default async function WorkspaceOpen(props: AgentEventRouteProps) { + return observeEvent(props); +} diff --git a/examples/host-test/src/log.ts b/examples/host-test/src/log.ts new file mode 100644 index 000000000..ebf7e7b9a --- /dev/null +++ b/examples/host-test/src/log.ts @@ -0,0 +1,102 @@ +import { appendFileSync, mkdirSync } from 'node:fs'; +import { readFile, rm } from 'node:fs/promises'; +import { homedir } from 'node:os'; +import { dirname, isAbsolute, join, resolve } from 'node:path'; + +import type { JsonValue } from '@agent-bundle/runtime'; + +export const LOG_DIR_ENV = 'HOST_TEST_LOG_DIR'; +export const LOG_FILE_NAME = 'captures.ndjson'; + +export type LogDirSource = + | 'env:HOST_TEST_LOG_DIR' + | 'env:AGENT_BUNDLE_PLUGIN_ROOT' + | 'argv:artifact-root' + | 'home'; + +export interface ResolvedLog { + readonly dir: string; + readonly path: string; + readonly source: LogDirSource; +} + +const artifactRootFromArgv = (argv: readonly string[]): string | undefined => { + const entry = argv[1]; + if (entry === undefined || !isAbsolute(entry)) return undefined; + // Generated hook wrappers live at /hooks/.mjs and generated + // MCP entries at /mcp/.mjs, so the artifact root is two levels up. + const parent = dirname(resolve(entry)); + const leaf = parent.slice(parent.lastIndexOf('/') + 1); + return leaf === 'hooks' || leaf === 'mcp' ? dirname(parent) : undefined; +}; + +/** + * Where the plain-file capture log lives. Every process of one installed + * plugin (hook wrappers, the shared runtime, both MCP servers) must agree, so + * the resolution prefers explicit configuration, then the installed plugin + * root the host handed us, then the artifact root derived from the running + * entry, and only then the home directory. + */ +export const resolveLog = ( + environment: Readonly> = process.env, + argv: readonly string[] = process.argv, +): ResolvedLog => { + const explicit = environment[LOG_DIR_ENV]; + if (explicit !== undefined && explicit.trim() !== '') { + const dir = resolve(explicit); + return { dir, path: join(dir, LOG_FILE_NAME), source: 'env:HOST_TEST_LOG_DIR' }; + } + const pluginRoot = environment['AGENT_BUNDLE_PLUGIN_ROOT']; + if (pluginRoot !== undefined && pluginRoot.trim() !== '') { + const dir = join(resolve(pluginRoot), 'state', 'host-test'); + return { dir, path: join(dir, LOG_FILE_NAME), source: 'env:AGENT_BUNDLE_PLUGIN_ROOT' }; + } + const artifactRoot = artifactRootFromArgv(argv); + if (artifactRoot !== undefined) { + const dir = join(artifactRoot, 'state', 'host-test'); + return { dir, path: join(dir, LOG_FILE_NAME), source: 'argv:artifact-root' }; + } + const dir = join(homedir(), '.host-test'); + return { dir, path: join(dir, LOG_FILE_NAME), source: 'home' }; +}; + +/** Appends one NDJSON line with a single write so concurrent hook processes interleave by line. */ +export const appendLogLine = (log: ResolvedLog, record: JsonValue): void => { + mkdirSync(log.dir, { recursive: true }); + appendFileSync(log.path, `${JSON.stringify(record)}\n`, 'utf8'); +}; + +export interface ReadLogResult { + readonly malformed: number; + readonly records: readonly Record[]; +} + +export const readLog = async (log: ResolvedLog): Promise => { + let text: string; + try { + text = await readFile(log.path, 'utf8'); + } catch (error) { + if ((error as NodeJS.ErrnoException).code === 'ENOENT') return { malformed: 0, records: [] }; + throw error; + } + const records: Record[] = []; + let malformed = 0; + for (const line of text.split('\n')) { + if (line.trim() === '') continue; + try { + const parsed = JSON.parse(line) as JsonValue; + if (parsed !== null && typeof parsed === 'object' && !Array.isArray(parsed)) { + records.push(parsed as Record); + } else { + malformed += 1; + } + } catch { + malformed += 1; + } + } + return { malformed, records }; +}; + +export const clearLog = async (log: ResolvedLog): Promise => { + await rm(log.path, { force: true }); +}; diff --git a/examples/host-test/src/mcp/host-test-raw.ts b/examples/host-test/src/mcp/host-test-raw.ts new file mode 100644 index 000000000..016eea708 --- /dev/null +++ b/examples/host-test/src/mcp/host-test-raw.ts @@ -0,0 +1,48 @@ +import { McpServer } from '@modelcontextprotocol/server'; +import type { JsonObject, JsonValue } from '@agent-bundle/runtime'; +import { z } from 'zod'; + +import { captureRaw, environmentNames } from '../capture.js'; + +const asJson = (value: unknown): JsonValue => JSON.parse(JSON.stringify(value ?? null)) as JsonValue; + +/** + * A deliberately hand-rolled stdio server (the framework lifecycle shell wraps + * this factory): it records the raw MCP request context the SDK hands a tool + * handler — session id, JSON-RPC id, `_meta`, the lifted envelope, the + * negotiated client identity — so hook↔MCP correlation can be judged against + * the wire rather than against what the generated server chooses to mount. + */ +export default () => { + const server = new McpServer({ name: 'host-test-raw', version: '1.0.0' }); + server.registerTool('probe', { + annotations: { readOnlyHint: true }, + description: + 'Record and return the raw MCP request envelope this server received (session id, request id, _meta, client info, env variable names).', + inputSchema: z.object({ note: z.string().max(1024).optional() }).strict(), + }, async (input, context) => { + const client = server.server.getClientVersion(); + const observed: JsonObject = { + client: asJson(client), + clientCapabilities: asJson(server.server.getClientCapabilities()), + env: { names: [...environmentNames()] }, + http: asJson(context.http), + mcpReq: { + _meta: asJson(context.mcpReq._meta), + envelope: asJson(context.mcpReq.envelope), + id: asJson(context.mcpReq.id), + method: context.mcpReq.method, + }, + note: input.note ?? null, + sessionId: context.sessionId ?? null, + tool: 'probe', + }; + const { log, record } = captureRaw(client?.name ?? 'unknown', observed); + const result = { log: log.path, observed, sequence: record.sequence }; + return { + content: [{ text: JSON.stringify(result, null, 2), type: 'text' as const }], + structuredContent: result, + }; + }); + return server; +}; diff --git a/examples/host-test/src/mcp/host-test/tools/dump.tsx b/examples/host-test/src/mcp/host-test/tools/dump.tsx new file mode 100644 index 000000000..cbbbb2ed1 --- /dev/null +++ b/examples/host-test/src/mcp/host-test/tools/dump.tsx @@ -0,0 +1,28 @@ +import { Agent, type JsonValue } from '@agent-bundle/runtime'; +import type { ToolConfig, ToolRouteProps } from 'agent-bundle'; +import React from 'react'; + +import { capture } from '../../../capture.js'; +import { dumpCaptures, dumpInputSchema, dumpResultSchema, renderDumpMarkdown } from '../../../dump.js'; + +export const config = { + annotations: { readOnlyHint: true }, + description: + 'Dump what the host-test probe has recorded from this host: every hook payload, the framework request context each one saw, and the MCP calls. Filter by any conversation, session, or subagent id.', +} satisfies ToolConfig; + +export const inputSchema = dumpInputSchema; +export const resultSchema = dumpResultSchema; + +export default async function Dump({ input }: ToolRouteProps) { + // The dump call is itself an observation: it records the request context the + // generated MCP server mounted for this tool call before reading the log. + const observed = await capture({ kind: 'mcp', observed: { tool: 'dump' } }); + const result = await dumpCaptures(input, observed.log); + return ( + + {renderDumpMarkdown(result)} + + + ); +} diff --git a/examples/host-test/src/mcp/host-test/tools/reset.tsx b/examples/host-test/src/mcp/host-test/tools/reset.tsx new file mode 100644 index 000000000..b2507dadb --- /dev/null +++ b/examples/host-test/src/mcp/host-test/tools/reset.tsx @@ -0,0 +1,50 @@ +import { Agent, agent, type AgentStateHandle, type JsonValue } from '@agent-bundle/runtime'; +import type { ToolConfig, ToolRouteProps } from 'agent-bundle'; +import React from 'react'; +import { z } from 'zod'; + +import { clearLog, resolveLog } from '../../../log.js'; +import type { CaptureEvents, CapturesState } from '../../../state.js'; + +export const config = { + annotations: { destructiveHint: true, readOnlyHint: false }, + description: 'Clear the host-test capture log and the durable capture summary so the next probe starts empty.', +} satisfies ToolConfig; + +export const inputSchema = z.object({}).strict(); + +export const resultSchema = z.object({ + clearedAt: z.string(), + log: z.string(), + state: z.enum(['cleared', 'unavailable']), + stateReason: z.string().optional(), +}).strict(); + +export default async function Reset(_props: ToolRouteProps) { + const context = await agent(); + const log = resolveLog(); + await clearLog(log); + const clearedAt = new Date().toISOString(); + const handle = context.state as AgentStateHandle | undefined; + let result: z.output; + if (handle === undefined) { + result = { clearedAt, log: log.path, state: 'unavailable', stateReason: 'no state handle mounted on this request' }; + } else { + try { + await handle.dispatch('cleared', { clearedAt }, { idempotencyKey: `reset:${context.invocation.id}`, signal: context.signal }); + result = { clearedAt, log: log.path, state: 'cleared' }; + } catch (error) { + result = { + clearedAt, + log: log.path, + state: 'unavailable', + stateReason: error instanceof Error ? error.message : String(error), + }; + } + } + return ( + + {`Cleared ${log.path}; durable state ${result.state}.`} + + ); +} diff --git a/examples/host-test/src/skills/host-test/SKILL.md b/examples/host-test/src/skills/host-test/SKILL.md new file mode 100644 index 000000000..35cde9592 --- /dev/null +++ b/examples/host-test/src/skills/host-test/SKILL.md @@ -0,0 +1,32 @@ +--- +name: host-test +description: Probe what this host sends to plugin hooks and MCP servers. Use when asked to run the host-test probe, dump host lineage, or check which conversation, session, or subagent ids a hook or MCP call carries. +--- + +# Host test probe + +This plugin records every hook event the host dispatches to it, plus every +call to its own MCP servers, into one NDJSON log and a durable state summary. +Nothing it records is sent anywhere; the log stays on this machine. + +## When to use + +- The user asks to "run the host-test probe", "dump the host log", or asks + which ids (conversation, session, subagent, tool call) this host exposes. +- You are a subagent and were asked to prove what the host tells plugins + about your parent. + +## Steps + +1. Run one shell command (for example `pwd`) so a tool hook fires. +2. Edit or create a small scratch file so a file-edit hook fires. +3. Call the `host-test` MCP server's `dump` tool with no arguments. +4. If a `probe` tool from the `host-test-raw` server is available, call it once + with `note` set to your own role (`root` or `subagent`). +5. If you can spawn a subagent, ask it to do steps 1, 3, and 4 with + `note: "subagent"` and to report the `log` path and the ids it saw. +6. Report the log path and the ids the dump shows, verbatim, without editing + the log file. + +Never delete or rewrite the log by hand; the `reset` tool is the only way to +clear it, and only when the user asks for a fresh probe. diff --git a/examples/host-test/src/state.ts b/examples/host-test/src/state.ts new file mode 100644 index 000000000..a31d8c7e1 --- /dev/null +++ b/examples/host-test/src/state.ts @@ -0,0 +1,83 @@ +import { defineState } from '@agent-bundle/runtime/state'; +import { z } from 'zod'; + +const text = z.string().max(4096); + +/** + * The bounded, durable summary of one capture. The complete raw record lives + * in the plain NDJSON log; the kernel keeps enough to correlate and to prove + * durability across processes without exceeding the state byte budget. + */ +export const CaptureSummarySchema = z.object({ + event: text.optional(), + host: text, + ids: z.record(z.string().max(64), z.union([z.string().max(1024), z.boolean(), z.number(), z.null()])), + invocationId: text, + kind: z.enum(['event', 'mcp', 'cli']), + nativeEvent: text.optional(), + recordedAt: text, + runtime: z.enum(['shared-runtime', 'standalone-hook', 'mcp-server', 'cli', 'script', 'unknown']), + sequence: z.number().int().nonnegative(), +}).strict(); + +export const CapturesStateSchema = z.object({ + captures: z.array(CaptureSummarySchema), + clearedAt: text.optional(), + total: z.number().int().nonnegative(), +}).strict(); + +export type CaptureSummary = z.output; +export type CapturesState = z.output; + +export const captureEventSchemas = { + captured: CaptureSummarySchema, + cleared: z.object({ clearedAt: text }).strict(), +} as const; + +export type CaptureEvents = typeof captureEventSchemas; + +/** Keep the durable ring bounded so a long probing session never trips the state byte budget. */ +export const CAPTURE_RING_SIZE = 400; + +const initial: CapturesState = { + captures: [], + total: 0, +}; + +export const capturesStateDefinition = defineState({ + budgets: { + maxStateBytes: 4 * 1_048_576, + }, + events: captureEventSchemas, + id: 'host-test/captures', + initial, + lifetime: 'workspace-durable', + reduce: (state, event): CapturesState => { + switch (event.name) { + case 'captured': { + const captures = [...state.captures, event.payload]; + return { + ...state, + captures: captures.length > CAPTURE_RING_SIZE + ? captures.slice(captures.length - CAPTURE_RING_SIZE) + : captures, + total: state.total + 1, + }; + } + case 'cleared': + return { captures: [], clearedAt: event.payload.clearedAt, total: 0 }; + default: { + const unreachable: never = event; + throw new Error(`Unhandled captures event ${String(unreachable)}`); + } + } + }, + schema: CapturesStateSchema, + version: 1, +}); + +export default defineState({ + ...capturesStateDefinition, + id: 'host-test/captures', + lifetime: 'workspace-durable', +}); diff --git a/examples/host-test/tests/route-unit/routes.test.ts b/examples/host-test/tests/route-unit/routes.test.ts new file mode 100644 index 000000000..01d3a26ac --- /dev/null +++ b/examples/host-test/tests/route-unit/routes.test.ts @@ -0,0 +1,214 @@ +import { mkdtemp, readFile, rm } from 'node:fs/promises'; +import { tmpdir } from 'node:os'; +import { join } from 'node:path'; + +import { afterEach, beforeEach, expect, it } from '@rstest/core'; +import { available } from '@agent-bundle/runtime'; +import { + createGeneratedRuntimeState, + type GeneratedRuntimeState, +} from '@agent-bundle/runtime/mount'; +import { createSqliteStateDriver } from '@agent-bundle/runtime/state/sqlite'; +import { expectDocument, renderRoute, testManifest } from 'agent-bundle/test'; + +import { LOG_DIR_ENV } from '../../src/log.js'; +import { + capturesStateDefinition, + type CaptureEvents, + type CapturesState, +} from '../../src/state.js'; + +const manifest = testManifest(); + +let stateRoot: string; +let logDir: string; +let runtimeState: GeneratedRuntimeState; +let sequence = 0; + +const eventInput = ( + event: 'agent/start' | 'agent/stop' | 'session/start' | 'tool/before', + native: Record, + host = 'claude', +) => ({ + canonical: { + event, + idempotencyKey: `${event}:${String(sequence)}`, + observedAt: `2026-09-03T08:00:${String(sequence++).padStart(2, '0')}.000Z`, + provenance: { + host, + hostContractRevision: 'route-unit', + nativeEvent: native.hook_event_name as string, + source: 'native', + }, + sequence, + }, + native, +}); + +const render = async (route: string, input: unknown, sessionId = 'root-session', host = 'claude') => { + const bindings = await runtimeState.requestBindings(); + try { + return await renderRoute(route, { + context: { + host: available({ name: host }, 'native'), + noticeLedger: bindings.noticeLedger, + session: available({ sessionId }, 'native'), + state: bindings.state, + workspace: available({ root: '/repo' }, 'native'), + }, + input, + }); + } finally { + await bindings.close(); + } +}; + +const readLogLines = async (): Promise[]> => + (await readFile(join(logDir, 'captures.ndjson'), 'utf8')) + .split('\n') + .filter((line) => line.trim() !== '') + .map((line) => JSON.parse(line) as Record); + +beforeEach(async () => { + stateRoot = await mkdtemp(join(tmpdir(), 'host-test-route-unit-')); + logDir = join(stateRoot, 'log'); + process.env[LOG_DIR_ENV] = logDir; + runtimeState = createGeneratedRuntimeState({ + definition: capturesStateDefinition, + driver: createSqliteStateDriver({ root: stateRoot }), + }); + sequence = 0; +}); + +afterEach(async () => { + delete process.env[LOG_DIR_ENV]; + await runtimeState.close(); + await rm(stateRoot, { force: true, recursive: true }); +}); + +it('compiles every canonical event family plus the MCP and CLI surfaces', () => { + expect(manifest.diagnostics.filter((diagnostic) => diagnostic.severity === 'error')).toEqual([]); + const routes = Object.keys(manifest.routes); + for (const family of [ + 'session/start', 'session/end', 'tool/before', 'tool/after', 'tool/failure', 'stop', 'stop/failure', + 'agent/start', 'agent/stop', 'agent/idle', 'workspace/open', 'prompt/submit', 'compact/before', + 'compact/after', 'permission/request', 'permission/denied', 'file/change', 'config/change', + 'task/create', 'task/complete', + ]) { + expect(routes, family).toContain(`event:${family}`); + } + expect(routes).toEqual(expect.arrayContaining(['tool:host-test/dump', 'tool:host-test/reset', 'cli:dump'])); +}); + +it('records the complete native envelope, the request context, and env names for every event', async () => { + const rendered = await render('event:session/start', eventInput('session/start', { + cwd: '/repo', + hook_event_name: 'SessionStart', + session_id: 'root-session', + source: 'startup', + transcript_path: '/tmp/transcript.jsonl', + })); + expectDocument(rendered).toHaveStatus('success').toContainContext('host-test probe is recording'); + expectDocument(rendered).toContainContext(join(logDir, 'captures.ndjson')); + + const [record] = await readLogLines(); + expect(record).toMatchObject({ + event: { + canonical: { event: 'session/start', provenance: { host: 'claude', nativeEvent: 'SessionStart' } }, + native: { hook_event_name: 'SessionStart', session_id: 'root-session', source: 'startup' }, + }, + host: 'claude', + ids: { session_id: 'root-session', source: 'startup' }, + kind: 'event', + request: { + hasState: true, + host: { state: 'available', value: { name: 'claude' } }, + invocation: { kind: 'event' }, + session: { state: 'available', value: { sessionId: 'root-session' } }, + }, + }); + const env = (record as { env: { names: string[] } }).env.names; + expect(env).toContain(LOG_DIR_ENV); + expect(JSON.stringify(record)).not.toContain(logDir.replace('captures.ndjson', 'value-should-not-appear')); +}); + +it('redacts secret-looking native values but keeps ids intact', async () => { + await render('event:tool/before', eventInput('tool/before', { + cwd: '/repo', + hook_event_name: 'PreToolUse', + session_id: 'root-session', + tool_input: { api_key: 'sk-live-abcdefghijklmnopqrstuvwxyz', command: 'pwd' }, + tool_name: 'Bash', + tool_use_id: 'toolu_01', + transcript_path: '/tmp/transcript.jsonl', + })); + const [record] = await readLogLines(); + const native = (record as { event: { native: Record } }).event.native; + expect(native.tool_input).toEqual({ api_key: '[redacted]', command: 'pwd' }); + expect(native.tool_use_id).toBe('toolu_01'); +}); + +it('keeps a bounded durable summary and dumps by any carried id', async () => { + await render('event:agent/start', eventInput('agent/start', { + agent_id: 'agent-1', + agent_type: 'general-purpose', + cwd: '/repo', + hook_event_name: 'SubagentStart', + session_id: 'root-session', + transcript_path: '/tmp/transcript.jsonl', + })); + await render('event:agent/stop', eventInput('agent/stop', { + agent_id: 'agent-1', + agent_transcript_path: null, + agent_type: 'general-purpose', + cwd: '/repo', + hook_event_name: 'SubagentStop', + last_assistant_message: null, + session_id: 'root-session', + stop_hook_active: false, + transcript_path: '/tmp/transcript.jsonl', + })); + await render('event:session/start', eventInput('session/start', { + cwd: '/repo', + hook_event_name: 'SessionStart', + session_id: 'other-session', + source: 'startup', + transcript_path: '/tmp/transcript.jsonl', + }), 'other-session'); + + const dumped = await render('tool:host-test/dump', { conversation: 'agent-1' }); + expectDocument(dumped).toHaveStatus('success'); + expect(dumped.document.value).toMatchObject({ + matched: 2, + records: [ + expect.objectContaining({ event: 'agent/start', ids: expect.objectContaining({ agent_id: 'agent-1' }) }), + expect.objectContaining({ event: 'agent/stop', ids: expect.objectContaining({ agent_id: 'agent-1' }) }), + ], + state: { revision: 4, state: 'available', summarized: 4, total: 4 }, + // Three events plus the dump call itself. + total: 4, + }); + + const everything = await render('tool:host-test/dump', { full: true }); + expect(everything.document.value).toMatchObject({ matched: 5, total: 5 }); + const records = (everything.document.value as { records: Record[] }).records; + expect(records.at(-1)).toMatchObject({ kind: 'mcp', observed: { tool: 'dump' }, request: { invocation: { kind: 'tool' } } }); +}); + +it('reset clears the log and the durable summary', async () => { + await render('event:session/start', eventInput('session/start', { + cwd: '/repo', + hook_event_name: 'SessionStart', + session_id: 'root-session', + source: 'startup', + transcript_path: '/tmp/transcript.jsonl', + })); + const reset = await render('tool:host-test/reset', {}); + expect(reset.document.value).toMatchObject({ state: 'cleared' }); + const dumped = await render('tool:host-test/dump', {}); + expect(dumped.document.value).toMatchObject({ + matched: 1, + records: [expect.objectContaining({ kind: 'mcp' })], + state: { state: 'available', summarized: 1, total: 1 }, + }); +}); diff --git a/examples/host-test/tsconfig.json b/examples/host-test/tsconfig.json new file mode 100644 index 000000000..67cbb7fcf --- /dev/null +++ b/examples/host-test/tsconfig.json @@ -0,0 +1,13 @@ +{ + "extends": "../../tsconfig.json", + "compilerOptions": { + "jsx": "react-jsx" + }, + "include": [ + "agent-bundle.config.ts", + "src/**/*.ts", + "src/**/*.tsx", + "tests/**/*.ts", + "tests/**/*.tsx" + ] +} diff --git a/fixtures/host-lineage/claude-2.1.257.ndjson b/fixtures/host-lineage/claude-2.1.257.ndjson new file mode 100644 index 000000000..c2951d76d --- /dev/null +++ b/fixtures/host-lineage/claude-2.1.257.ndjson @@ -0,0 +1,32 @@ +{"env":{"names":["ANTHROPIC_API_KEY","ANTHROPIC_BASE_URL","CLAUDE_CODE_CHILD_SESSION","CLAUDE_CODE_DISABLE_NONESSENTIAL_TRAFFIC","CLAUDE_CODE_ENTRYPOINT","CLAUDE_CODE_MESSAGING_SOCKET","CLAUDE_CODE_MESSAGING_TOKEN","CLAUDE_CODE_SESSION_ID","CLAUDE_CONFIG_DIR","CLAUDE_ENV_FILE","CLAUDE_PID","CLAUDE_PLUGIN_DATA","CLAUDE_PLUGIN_ROOT","CLAUDE_PROJECT_DIR","CURSOR_LAYOUT","CURSOR_RIPGREP_PATH","HOST_TEST_LOG_DIR"]},"event":{"canonical":{"event":"session/start","idempotencyKey":"155055116628f545723798ead3b8cb5b697796294d06b238652cf931a129e031","observedAt":"2026-09-03T08:46:25.038Z","provenance":{"host":"claude","hostContractRevision":"2.1.250","nativeEvent":"SessionStart","source":"native"},"sequence":1},"native":{"session_id":"a7f96472-e9d0-447a-826d-36da9b635fd6","transcript_path":"/tmp/host-test/claude-home/.claude/projects/-tmp-host-test-claude-workspace/a7f96472-e9d0-447a-826d-36da9b635fd6.jsonl","cwd":"/tmp/host-test/claude-workspace","hook_event_name":"SessionStart","source":"startup"}},"host":"claude","kind":"event","process":{"cwd":"/tmp/host-test/claude-workspace","entry":"/fast/projects/agent-bundle-worktrees/host-test/examples/host-test/artifact/claude/hooks/hooks-flight.mjs","pid":1071607,"ppid":1071604},"recordedAt":"2026-09-03T08:46:25.335Z","request":{"host":{"source":"native","state":"available","value":{"name":"claude"}},"invocation":{"kind":"event"},"session":{"source":"native","state":"available","value":{"sessionId":"a7f96472-e9d0-447a-826d-36da9b635fd6"}}},"runtime":"standalone-hook","sequence":1} +{"env":{"names":["AGENT_BUNDLE_PLUGIN_ROOT","ANTHROPIC_API_KEY","ANTHROPIC_BASE_URL","CLAUDE_CODE_DISABLE_NONESSENTIAL_TRAFFIC","CLAUDE_CODE_ENTRYPOINT","CLAUDE_CODE_MESSAGING_SOCKET","CLAUDE_CODE_MESSAGING_TOKEN","CLAUDE_CODE_SESSION_ID","CLAUDE_CONFIG_DIR","CLAUDE_PLUGIN_DATA","CLAUDE_PLUGIN_ROOT","CLAUDE_PROJECT_DIR","CURSOR_LAYOUT","CURSOR_RIPGREP_PATH","HOST_TEST_LOG_DIR"]},"event":{"canonical":{"event":"prompt/submit","idempotencyKey":"6a543826745d8f8d895629ee58ce83120a3743ab9fc4d3a5e4f90df2aeaef301","observedAt":"2026-09-03T08:46:25.692Z","provenance":{"host":"claude","hostContractRevision":"2.1.250","nativeEvent":"UserPromptSubmit","source":"native"},"sequence":1},"native":{"session_id":"a7f96472-e9d0-447a-826d-36da9b635fd6","transcript_path":"/tmp/host-test/claude-home/.claude/projects/-tmp-host-test-claude-workspace/a7f96472-e9d0-447a-826d-36da9b635fd6.jsonl","cwd":"/tmp/host-test/claude-workspace","prompt_id":"96a54da1-f00b-48ec-8f84-2d42b7de5ba4","permission_mode":"bypassPermissions","hook_event_name":"UserPromptSubmit","prompt":"You are exercising the host-test probe plugin. Do the scripted steps."}},"host":"claude","kind":"event","process":{"cwd":"/tmp/host-test/claude-workspace","entry":"/fast/projects/agent-bundle-worktrees/host-test/examples/host-test/artifact/claude/mcp/mcp-host-test-0d229f1b-flight.mjs","pid":1071574,"ppid":1070791},"recordedAt":"2026-09-03T08:46:25.812Z","request":{"host":{"source":"native","state":"available","value":{"name":"claude"}},"invocation":{"kind":"event"},"session":{"source":"native","state":"available","value":{"sessionId":"a7f96472-e9d0-447a-826d-36da9b635fd6"}}},"runtime":"shared-runtime","sequence":1} +{"event":{"canonical":{"event":"tool/before","idempotencyKey":"23cc59242ee35ff4ba59bf05a19d3062910dc4fd2772964359bf86f83032d1c8","observedAt":"2026-09-03T08:46:26.088Z","provenance":{"host":"claude","hostContractRevision":"2.1.250","nativeEvent":"PreToolUse","source":"native"},"sequence":2},"native":{"session_id":"a7f96472-e9d0-447a-826d-36da9b635fd6","transcript_path":"/tmp/host-test/claude-home/.claude/projects/-tmp-host-test-claude-workspace/a7f96472-e9d0-447a-826d-36da9b635fd6.jsonl","cwd":"/tmp/host-test/claude-workspace","prompt_id":"96a54da1-f00b-48ec-8f84-2d42b7de5ba4","permission_mode":"bypassPermissions","hook_event_name":"PreToolUse","tool_name":"Bash","tool_input":{"command":"pwd"},"tool_use_id":"toolu_mock_1"}},"host":"claude","kind":"event","process":{"cwd":"/tmp/host-test/claude-workspace","entry":"/fast/projects/agent-bundle-worktrees/host-test/examples/host-test/artifact/claude/mcp/mcp-host-test-0d229f1b-flight.mjs","pid":1071574,"ppid":1070791},"recordedAt":"2026-09-03T08:46:26.092Z","request":{"host":{"source":"native","state":"available","value":{"name":"claude"}},"invocation":{"kind":"event"},"session":{"source":"native","state":"available","value":{"sessionId":"a7f96472-e9d0-447a-826d-36da9b635fd6"}}},"runtime":"shared-runtime","sequence":2} +{"event":{"canonical":{"event":"tool/after","idempotencyKey":"dbfae77c05cf08fd90c148fd2df0edf056afe6d025f02f98a0bb9e5e6299e453","observedAt":"2026-09-03T08:46:26.287Z","provenance":{"host":"claude","hostContractRevision":"2.1.250","nativeEvent":"PostToolUse","source":"native"},"sequence":3},"native":{"session_id":"a7f96472-e9d0-447a-826d-36da9b635fd6","transcript_path":"/tmp/host-test/claude-home/.claude/projects/-tmp-host-test-claude-workspace/a7f96472-e9d0-447a-826d-36da9b635fd6.jsonl","cwd":"/tmp/host-test/claude-workspace","prompt_id":"96a54da1-f00b-48ec-8f84-2d42b7de5ba4","permission_mode":"bypassPermissions","hook_event_name":"PostToolUse","tool_name":"Bash","tool_input":{"command":"pwd"},"tool_response":{"stdout":"/tmp/host-test/claude-workspace","stderr":"","interrupted":false,"isImage":false,"noOutputExpected":false},"tool_use_id":"toolu_mock_1","duration_ms":44}},"host":"claude","kind":"event","process":{"cwd":"/tmp/host-test/claude-workspace","entry":"/fast/projects/agent-bundle-worktrees/host-test/examples/host-test/artifact/claude/mcp/mcp-host-test-0d229f1b-flight.mjs","pid":1071574,"ppid":1070791},"recordedAt":"2026-09-03T08:46:26.291Z","request":{"host":{"source":"native","state":"available","value":{"name":"claude"}},"invocation":{"kind":"event"},"session":{"source":"native","state":"available","value":{"sessionId":"a7f96472-e9d0-447a-826d-36da9b635fd6"}}},"runtime":"shared-runtime","sequence":3} +{"event":{"canonical":{"event":"tool/before","idempotencyKey":"5fddde8ce837cf8b65f20224dcd9ad6d91f1f3c9e443876962451ffe3d98377b","observedAt":"2026-09-03T08:46:26.500Z","provenance":{"host":"claude","hostContractRevision":"2.1.250","nativeEvent":"PreToolUse","source":"native"},"sequence":4},"native":{"session_id":"a7f96472-e9d0-447a-826d-36da9b635fd6","transcript_path":"/tmp/host-test/claude-home/.claude/projects/-tmp-host-test-claude-workspace/a7f96472-e9d0-447a-826d-36da9b635fd6.jsonl","cwd":"/tmp/host-test/claude-workspace","prompt_id":"96a54da1-f00b-48ec-8f84-2d42b7de5ba4","permission_mode":"bypassPermissions","hook_event_name":"PreToolUse","tool_name":"mcp__plugin_host-test_host-test__dump","tool_input":{},"tool_use_id":"toolu_mock_3"}},"host":"claude","kind":"event","process":{"cwd":"/tmp/host-test/claude-workspace","entry":"/fast/projects/agent-bundle-worktrees/host-test/examples/host-test/artifact/claude/mcp/mcp-host-test-0d229f1b-flight.mjs","pid":1071574,"ppid":1070791},"recordedAt":"2026-09-03T08:46:26.505Z","request":{"host":{"source":"native","state":"available","value":{"name":"claude"}},"invocation":{"kind":"event"},"session":{"source":"native","state":"available","value":{"sessionId":"a7f96472-e9d0-447a-826d-36da9b635fd6"}}},"runtime":"shared-runtime","sequence":4} +{"env":{"names":["AGENT_BUNDLE_PLUGIN_ROOT","ANTHROPIC_API_KEY","ANTHROPIC_BASE_URL","CLAUDE_CODE_DISABLE_NONESSENTIAL_TRAFFIC","CLAUDE_CODE_ENTRYPOINT","CLAUDE_CODE_MESSAGING_SOCKET","CLAUDE_CODE_MESSAGING_TOKEN","CLAUDE_CODE_SESSION_ID","CLAUDE_CONFIG_DIR","CLAUDE_PLUGIN_DATA","CLAUDE_PLUGIN_ROOT","CLAUDE_PROJECT_DIR","CURSOR_LAYOUT","CURSOR_RIPGREP_PATH","HOST_TEST_LOG_DIR"]},"host":"claude-code","kind":"mcp","observed":{"tool":"dump"},"process":{"cwd":"/tmp/host-test/claude-workspace","entry":"/fast/projects/agent-bundle-worktrees/host-test/examples/host-test/artifact/claude/mcp/mcp-host-test-0d229f1b-flight.mjs","pid":1071574,"ppid":1070791},"recordedAt":"2026-09-03T08:46:26.550Z","request":{"host":{"source":"native","state":"available","value":{"name":"claude-code"}},"invocation":{"kind":"tool"},"session":{"reason":"not-provided","state":"unavailable"}},"runtime":"mcp-server","sequence":5} +{"event":{"canonical":{"event":"tool/before","idempotencyKey":"2a6c24cf4256e6b4c50e129b8bac8b99029c57aa8b5c95c2d02c7ac6aa854010","observedAt":"2026-09-03T08:46:26.844Z","provenance":{"host":"claude","hostContractRevision":"2.1.250","nativeEvent":"PreToolUse","source":"native"},"sequence":5},"native":{"session_id":"a7f96472-e9d0-447a-826d-36da9b635fd6","transcript_path":"/tmp/host-test/claude-home/.claude/projects/-tmp-host-test-claude-workspace/a7f96472-e9d0-447a-826d-36da9b635fd6.jsonl","cwd":"/tmp/host-test/claude-workspace","prompt_id":"96a54da1-f00b-48ec-8f84-2d42b7de5ba4","permission_mode":"bypassPermissions","hook_event_name":"PreToolUse","tool_name":"mcp__plugin_host-test_host-test-raw__probe","tool_input":{"note":"root"},"tool_use_id":"toolu_mock_4"}},"host":"claude","kind":"event","process":{"cwd":"/tmp/host-test/claude-workspace","entry":"/fast/projects/agent-bundle-worktrees/host-test/examples/host-test/artifact/claude/mcp/mcp-host-test-0d229f1b-flight.mjs","pid":1071574,"ppid":1070791},"recordedAt":"2026-09-03T08:46:26.847Z","request":{"host":{"source":"native","state":"available","value":{"name":"claude"}},"invocation":{"kind":"event"},"session":{"source":"native","state":"available","value":{"sessionId":"a7f96472-e9d0-447a-826d-36da9b635fd6"}}},"runtime":"shared-runtime","sequence":6} +{"host":"claude-code","kind":"mcp","observed":{"client":{"name":"claude-code","title":"Claude Code","version":"2.1.257","websiteUrl":"https://claude.com/claude-code","description":"Anthropic's agentic coding tool"},"clientCapabilities":{"elicitation":{"form":{}},"roots":{"listChanged":true}},"env":{"names":["AGENT_BUNDLE_PLUGIN_ROOT","ANTHROPIC_API_KEY","ANTHROPIC_BASE_URL","CLAUDE_CODE_DISABLE_NONESSENTIAL_TRAFFIC","CLAUDE_CODE_ENTRYPOINT","CLAUDE_CODE_MESSAGING_SOCKET","CLAUDE_CODE_MESSAGING_TOKEN","CLAUDE_CODE_SESSION_ID","CLAUDE_CONFIG_DIR","CLAUDE_PLUGIN_DATA","CLAUDE_PLUGIN_ROOT","CLAUDE_PROJECT_DIR","CURSOR_LAYOUT","CURSOR_RIPGREP_PATH","HOST_TEST_LOG_DIR"]},"http":null,"mcpReq":{"_meta":{"progressToken":2,"claudecode/toolUseId":"toolu_mock_4"},"envelope":null,"id":2,"method":"tools/call"},"note":"root","sessionId":null,"tool":"probe"},"process":{"cwd":"/tmp/host-test/claude-workspace","entry":"/fast/projects/agent-bundle-worktrees/host-test/examples/host-test/artifact/claude/mcp/mcp-host-test-raw-6e9c1a1c.mjs","pid":1071578,"ppid":1070791},"recordedAt":"2026-09-03T08:46:26.907Z","request":{"unavailable":"hand-rolled stdio server: no framework request context is mounted"},"runtime":"mcp-server","sequence":1} +{"event":{"canonical":{"event":"tool/before","idempotencyKey":"dfde620d7b0b5f4fb21ffc6b77c5f81e88e4ce640974b3bfe51e35329b44adbd","observedAt":"2026-09-03T08:46:27.178Z","provenance":{"host":"claude","hostContractRevision":"2.1.250","nativeEvent":"PreToolUse","source":"native"},"sequence":6},"native":{"session_id":"a7f96472-e9d0-447a-826d-36da9b635fd6","transcript_path":"/tmp/host-test/claude-home/.claude/projects/-tmp-host-test-claude-workspace/a7f96472-e9d0-447a-826d-36da9b635fd6.jsonl","cwd":"/tmp/host-test/claude-workspace","prompt_id":"96a54da1-f00b-48ec-8f84-2d42b7de5ba4","permission_mode":"bypassPermissions","hook_event_name":"PreToolUse","tool_name":"Agent","tool_input":{"description":"host-test subagent probe","prompt":"SUBAGENT_PROBE_SCENARIO: run `pwd`, call the host-test dump tool with {}, call the host-test-raw probe tool with {\"note\":\"subagent\"}, spawn a nested subagent with NESTED_PROBE_SCENARIO if you can, then reply with every id you saw.","subagent_type":"general-purpose"},"tool_use_id":"toolu_mock_5"}},"host":"claude","kind":"event","process":{"cwd":"/tmp/host-test/claude-workspace","entry":"/fast/projects/agent-bundle-worktrees/host-test/examples/host-test/artifact/claude/mcp/mcp-host-test-0d229f1b-flight.mjs","pid":1071574,"ppid":1070791},"recordedAt":"2026-09-03T08:46:27.181Z","request":{"host":{"source":"native","state":"available","value":{"name":"claude"}},"invocation":{"kind":"event"},"session":{"source":"native","state":"available","value":{"sessionId":"a7f96472-e9d0-447a-826d-36da9b635fd6"}}},"runtime":"shared-runtime","sequence":7} +{"event":{"canonical":{"event":"agent/start","idempotencyKey":"ee006cf40eea65021f16e43dd99593bf98cfadd82fe8bba4541f4744f7a336b1","observedAt":"2026-09-03T08:46:27.329Z","provenance":{"host":"claude","hostContractRevision":"2.1.250","nativeEvent":"SubagentStart","source":"native"},"sequence":7},"native":{"session_id":"a7f96472-e9d0-447a-826d-36da9b635fd6","transcript_path":"/tmp/host-test/claude-home/.claude/projects/-tmp-host-test-claude-workspace/a7f96472-e9d0-447a-826d-36da9b635fd6.jsonl","cwd":"/tmp/host-test/claude-workspace","prompt_id":"96a54da1-f00b-48ec-8f84-2d42b7de5ba4","agent_id":"aca96ce761c9f0cea","agent_type":"general-purpose","hook_event_name":"SubagentStart"}},"host":"claude","kind":"event","process":{"cwd":"/tmp/host-test/claude-workspace","entry":"/fast/projects/agent-bundle-worktrees/host-test/examples/host-test/artifact/claude/mcp/mcp-host-test-0d229f1b-flight.mjs","pid":1071574,"ppid":1070791},"recordedAt":"2026-09-03T08:46:27.332Z","request":{"host":{"source":"native","state":"available","value":{"name":"claude"}},"invocation":{"kind":"event"},"session":{"source":"native","state":"available","value":{"sessionId":"a7f96472-e9d0-447a-826d-36da9b635fd6"}}},"runtime":"shared-runtime","sequence":8} +{"event":{"canonical":{"event":"tool/after","idempotencyKey":"d5fcba55ede859c8e4faf7cd25d29463d09ba0db5ec11a077d4d70f78f6a1564","observedAt":"2026-09-03T08:46:27.332Z","provenance":{"host":"claude","hostContractRevision":"2.1.250","nativeEvent":"PostToolUse","source":"native"},"sequence":8},"native":{"session_id":"a7f96472-e9d0-447a-826d-36da9b635fd6","transcript_path":"/tmp/host-test/claude-home/.claude/projects/-tmp-host-test-claude-workspace/a7f96472-e9d0-447a-826d-36da9b635fd6.jsonl","cwd":"/tmp/host-test/claude-workspace","prompt_id":"96a54da1-f00b-48ec-8f84-2d42b7de5ba4","permission_mode":"bypassPermissions","hook_event_name":"PostToolUse","tool_name":"Agent","tool_input":{"description":"host-test subagent probe","prompt":"SUBAGENT_PROBE_SCENARIO: run `pwd`, call the host-test dump tool with {}, call the host-test-raw probe tool with {\"note\":\"subagent\"}, spawn a nested subagent with NESTED_PROBE_SCENARIO if you can, then reply with every id you saw.","subagent_type":"general-purpose"},"tool_response":{"isAsync":true,"status":"async_launched","agentId":"aca96ce761c9f0cea","description":"host-test subagent probe","resolvedModel":"claude-sonnet-4-5","prompt":"SUBAGENT_PROBE_SCENARIO: run `pwd`, call the host-test dump tool with {}, call the host-test-raw probe tool with {\"note\":\"subagent\"}, spawn a nested subagent with NESTED_PROBE_SCENARIO if you can, then reply with every id you saw.","outputFile":"/tmp/claude-1000/-tmp-host-test-claude-workspace/a7f96472-e9d0-447a-826d-36da9b635fd6/tasks/aca96ce761c9f0cea.output","canReadOutputFile":true},"tool_use_id":"toolu_mock_5","duration_ms":6}},"host":"claude","kind":"event","process":{"cwd":"/tmp/host-test/claude-workspace","entry":"/fast/projects/agent-bundle-worktrees/host-test/examples/host-test/artifact/claude/mcp/mcp-host-test-0d229f1b-flight.mjs","pid":1071574,"ppid":1070791},"recordedAt":"2026-09-03T08:46:27.341Z","request":{"host":{"source":"native","state":"available","value":{"name":"claude"}},"invocation":{"kind":"event"},"session":{"source":"native","state":"available","value":{"sessionId":"a7f96472-e9d0-447a-826d-36da9b635fd6"}}},"runtime":"shared-runtime","sequence":9} +{"event":{"canonical":{"event":"tool/before","idempotencyKey":"76416c00a86fa4a487fec1d2516ef9bddc797039588f643fd94d54bfb1017e7c","observedAt":"2026-09-03T08:46:27.486Z","provenance":{"host":"claude","hostContractRevision":"2.1.250","nativeEvent":"PreToolUse","source":"native"},"sequence":9},"native":{"session_id":"a7f96472-e9d0-447a-826d-36da9b635fd6","transcript_path":"/tmp/host-test/claude-home/.claude/projects/-tmp-host-test-claude-workspace/a7f96472-e9d0-447a-826d-36da9b635fd6.jsonl","cwd":"/tmp/host-test/claude-workspace","prompt_id":"96a54da1-f00b-48ec-8f84-2d42b7de5ba4","permission_mode":"bypassPermissions","agent_id":"aca96ce761c9f0cea","agent_type":"general-purpose","hook_event_name":"PreToolUse","tool_name":"Bash","tool_input":{"command":"pwd"},"tool_use_id":"toolu_mock_6"}},"host":"claude","kind":"event","process":{"cwd":"/tmp/host-test/claude-workspace","entry":"/fast/projects/agent-bundle-worktrees/host-test/examples/host-test/artifact/claude/mcp/mcp-host-test-0d229f1b-flight.mjs","pid":1071574,"ppid":1070791},"recordedAt":"2026-09-03T08:46:27.490Z","request":{"host":{"source":"native","state":"available","value":{"name":"claude"}},"invocation":{"kind":"event"},"session":{"source":"native","state":"available","value":{"sessionId":"a7f96472-e9d0-447a-826d-36da9b635fd6"}}},"runtime":"shared-runtime","sequence":10} +{"event":{"canonical":{"event":"stop","idempotencyKey":"8dd460ae51c860cf76425007c4b3f3ed6bd4ea1b7f84af6ddf42b0e0ac35899f","observedAt":"2026-09-03T08:46:27.518Z","provenance":{"host":"claude","hostContractRevision":"2.1.250","nativeEvent":"Stop","source":"native"},"sequence":10},"native":{"session_id":"a7f96472-e9d0-447a-826d-36da9b635fd6","transcript_path":"/tmp/host-test/claude-home/.claude/projects/-tmp-host-test-claude-workspace/a7f96472-e9d0-447a-826d-36da9b635fd6.jsonl","cwd":"/tmp/host-test/claude-workspace","prompt_id":"96a54da1-f00b-48ec-8f84-2d42b7de5ba4","permission_mode":"bypassPermissions","hook_event_name":"Stop","stop_hook_active":false,"last_assistant_message":"HOST_TEST_DONE (mock model; see the probe log path in the dump result)","background_tasks":[{"id":"aca96ce761c9f0cea","type":"subagent","status":"running","description":"host-test subagent probe","agent_type":"general-purpose"}],"session_crons":[]}},"host":"claude","kind":"event","process":{"cwd":"/tmp/host-test/claude-workspace","entry":"/fast/projects/agent-bundle-worktrees/host-test/examples/host-test/artifact/claude/mcp/mcp-host-test-0d229f1b-flight.mjs","pid":1071574,"ppid":1070791},"recordedAt":"2026-09-03T08:46:27.521Z","request":{"host":{"source":"native","state":"available","value":{"name":"claude"}},"invocation":{"kind":"event"},"session":{"source":"native","state":"available","value":{"sessionId":"a7f96472-e9d0-447a-826d-36da9b635fd6"}}},"runtime":"shared-runtime","sequence":11} +{"event":{"canonical":{"event":"tool/after","idempotencyKey":"4b30dc62393cfe0536c9c79ca6c20189b1e4468148596b1e43634eca14f9a1f5","observedAt":"2026-09-03T08:46:27.640Z","provenance":{"host":"claude","hostContractRevision":"2.1.250","nativeEvent":"PostToolUse","source":"native"},"sequence":11},"native":{"session_id":"a7f96472-e9d0-447a-826d-36da9b635fd6","transcript_path":"/tmp/host-test/claude-home/.claude/projects/-tmp-host-test-claude-workspace/a7f96472-e9d0-447a-826d-36da9b635fd6.jsonl","cwd":"/tmp/host-test/claude-workspace","prompt_id":"96a54da1-f00b-48ec-8f84-2d42b7de5ba4","permission_mode":"bypassPermissions","agent_id":"aca96ce761c9f0cea","agent_type":"general-purpose","hook_event_name":"PostToolUse","tool_name":"Bash","tool_input":{"command":"pwd"},"tool_response":{"stdout":"/tmp/host-test/claude-workspace","stderr":"","interrupted":false,"isImage":false,"noOutputExpected":false},"tool_use_id":"toolu_mock_6","duration_ms":9}},"host":"claude","kind":"event","process":{"cwd":"/tmp/host-test/claude-workspace","entry":"/fast/projects/agent-bundle-worktrees/host-test/examples/host-test/artifact/claude/mcp/mcp-host-test-0d229f1b-flight.mjs","pid":1071574,"ppid":1070791},"recordedAt":"2026-09-03T08:46:27.642Z","request":{"host":{"source":"native","state":"available","value":{"name":"claude"}},"invocation":{"kind":"event"},"session":{"source":"native","state":"available","value":{"sessionId":"a7f96472-e9d0-447a-826d-36da9b635fd6"}}},"runtime":"shared-runtime","sequence":12} +{"event":{"canonical":{"event":"tool/before","idempotencyKey":"e6dbd3cbdabf0763b0dbe7c22866ff412d0ea7d52b1aaed1385296d39c6d2008","observedAt":"2026-09-03T08:46:27.789Z","provenance":{"host":"claude","hostContractRevision":"2.1.250","nativeEvent":"PreToolUse","source":"native"},"sequence":12},"native":{"session_id":"a7f96472-e9d0-447a-826d-36da9b635fd6","transcript_path":"/tmp/host-test/claude-home/.claude/projects/-tmp-host-test-claude-workspace/a7f96472-e9d0-447a-826d-36da9b635fd6.jsonl","cwd":"/tmp/host-test/claude-workspace","prompt_id":"96a54da1-f00b-48ec-8f84-2d42b7de5ba4","permission_mode":"bypassPermissions","agent_id":"aca96ce761c9f0cea","agent_type":"general-purpose","hook_event_name":"PreToolUse","tool_name":"mcp__plugin_host-test_host-test__dump","tool_input":{},"tool_use_id":"toolu_mock_8"}},"host":"claude","kind":"event","process":{"cwd":"/tmp/host-test/claude-workspace","entry":"/fast/projects/agent-bundle-worktrees/host-test/examples/host-test/artifact/claude/mcp/mcp-host-test-0d229f1b-flight.mjs","pid":1071574,"ppid":1070791},"recordedAt":"2026-09-03T08:46:27.793Z","request":{"host":{"source":"native","state":"available","value":{"name":"claude"}},"invocation":{"kind":"event"},"session":{"source":"native","state":"available","value":{"sessionId":"a7f96472-e9d0-447a-826d-36da9b635fd6"}}},"runtime":"shared-runtime","sequence":13} +{"host":"claude-code","kind":"mcp","observed":{"tool":"dump"},"process":{"cwd":"/tmp/host-test/claude-workspace","entry":"/fast/projects/agent-bundle-worktrees/host-test/examples/host-test/artifact/claude/mcp/mcp-host-test-0d229f1b-flight.mjs","pid":1071574,"ppid":1070791},"recordedAt":"2026-09-03T08:46:27.819Z","request":{"host":{"source":"native","state":"available","value":{"name":"claude-code"}},"invocation":{"kind":"tool"},"session":{"reason":"not-provided","state":"unavailable"}},"runtime":"mcp-server","sequence":14} +{"event":{"canonical":{"event":"tool/before","idempotencyKey":"b89ae7e6791d0446bf77685ae1eb1ef14b75d9dfb75f3cd9b511ce2429fc448e","observedAt":"2026-09-03T08:46:28.095Z","provenance":{"host":"claude","hostContractRevision":"2.1.250","nativeEvent":"PreToolUse","source":"native"},"sequence":13},"native":{"session_id":"a7f96472-e9d0-447a-826d-36da9b635fd6","transcript_path":"/tmp/host-test/claude-home/.claude/projects/-tmp-host-test-claude-workspace/a7f96472-e9d0-447a-826d-36da9b635fd6.jsonl","cwd":"/tmp/host-test/claude-workspace","prompt_id":"96a54da1-f00b-48ec-8f84-2d42b7de5ba4","permission_mode":"bypassPermissions","agent_id":"aca96ce761c9f0cea","agent_type":"general-purpose","hook_event_name":"PreToolUse","tool_name":"mcp__plugin_host-test_host-test-raw__probe","tool_input":{"note":"subagent"},"tool_use_id":"toolu_mock_9"}},"host":"claude","kind":"event","process":{"cwd":"/tmp/host-test/claude-workspace","entry":"/fast/projects/agent-bundle-worktrees/host-test/examples/host-test/artifact/claude/mcp/mcp-host-test-0d229f1b-flight.mjs","pid":1071574,"ppid":1070791},"recordedAt":"2026-09-03T08:46:28.098Z","request":{"host":{"source":"native","state":"available","value":{"name":"claude"}},"invocation":{"kind":"event"},"session":{"source":"native","state":"available","value":{"sessionId":"a7f96472-e9d0-447a-826d-36da9b635fd6"}}},"runtime":"shared-runtime","sequence":15} +{"host":"claude-code","kind":"mcp","observed":{"client":{"name":"claude-code","title":"Claude Code","version":"2.1.257","websiteUrl":"https://claude.com/claude-code","description":"Anthropic's agentic coding tool"},"clientCapabilities":{"elicitation":{"form":{}},"roots":{"listChanged":true}},"env":{"names":["AGENT_BUNDLE_PLUGIN_ROOT","ANTHROPIC_API_KEY","ANTHROPIC_BASE_URL","CLAUDE_CODE_DISABLE_NONESSENTIAL_TRAFFIC","CLAUDE_CODE_ENTRYPOINT","CLAUDE_CODE_MESSAGING_SOCKET","CLAUDE_CODE_MESSAGING_TOKEN","CLAUDE_CODE_SESSION_ID","CLAUDE_CONFIG_DIR","CLAUDE_PLUGIN_DATA","CLAUDE_PLUGIN_ROOT","CLAUDE_PROJECT_DIR","CURSOR_LAYOUT","CURSOR_RIPGREP_PATH","HOST_TEST_LOG_DIR"]},"http":null,"mcpReq":{"_meta":{"progressToken":3,"claudecode/toolUseId":"toolu_mock_9"},"envelope":null,"id":3,"method":"tools/call"},"note":"subagent","sessionId":null,"tool":"probe"},"process":{"cwd":"/tmp/host-test/claude-workspace","entry":"/fast/projects/agent-bundle-worktrees/host-test/examples/host-test/artifact/claude/mcp/mcp-host-test-raw-6e9c1a1c.mjs","pid":1071578,"ppid":1070791},"recordedAt":"2026-09-03T08:46:28.122Z","request":{"unavailable":"hand-rolled stdio server: no framework request context is mounted"},"runtime":"mcp-server","sequence":2} +{"event":{"canonical":{"event":"tool/before","idempotencyKey":"d42e7d6cf785b6d2b166b238f508f86a0daeea2bafd16719663ddf9579e231d9","observedAt":"2026-09-03T08:46:28.378Z","provenance":{"host":"claude","hostContractRevision":"2.1.250","nativeEvent":"PreToolUse","source":"native"},"sequence":14},"native":{"session_id":"a7f96472-e9d0-447a-826d-36da9b635fd6","transcript_path":"/tmp/host-test/claude-home/.claude/projects/-tmp-host-test-claude-workspace/a7f96472-e9d0-447a-826d-36da9b635fd6.jsonl","cwd":"/tmp/host-test/claude-workspace","prompt_id":"96a54da1-f00b-48ec-8f84-2d42b7de5ba4","permission_mode":"bypassPermissions","agent_id":"aca96ce761c9f0cea","agent_type":"general-purpose","hook_event_name":"PreToolUse","tool_name":"Agent","tool_input":{"description":"nested host-test probe","prompt":"NESTED_PROBE_SCENARIO: run `pwd`, call the host-test-raw probe tool with {\"note\":\"nested\"}, then reply with every id you saw.","subagent_type":"general-purpose"},"tool_use_id":"toolu_mock_10"}},"host":"claude","kind":"event","process":{"cwd":"/tmp/host-test/claude-workspace","entry":"/fast/projects/agent-bundle-worktrees/host-test/examples/host-test/artifact/claude/mcp/mcp-host-test-0d229f1b-flight.mjs","pid":1071574,"ppid":1070791},"recordedAt":"2026-09-03T08:46:28.380Z","request":{"host":{"source":"native","state":"available","value":{"name":"claude"}},"invocation":{"kind":"event"},"session":{"source":"native","state":"available","value":{"sessionId":"a7f96472-e9d0-447a-826d-36da9b635fd6"}}},"runtime":"shared-runtime","sequence":16} +{"event":{"canonical":{"event":"agent/start","idempotencyKey":"a58f839282b1768d4fd02a033c4aafa95bdef02aa86416a2a768f3a6bd81598b","observedAt":"2026-09-03T08:46:28.601Z","provenance":{"host":"claude","hostContractRevision":"2.1.250","nativeEvent":"SubagentStart","source":"native"},"sequence":15},"native":{"session_id":"a7f96472-e9d0-447a-826d-36da9b635fd6","transcript_path":"/tmp/host-test/claude-home/.claude/projects/-tmp-host-test-claude-workspace/a7f96472-e9d0-447a-826d-36da9b635fd6.jsonl","cwd":"/tmp/host-test/claude-workspace","prompt_id":"96a54da1-f00b-48ec-8f84-2d42b7de5ba4","agent_id":"ac093bdad0566ffa7","agent_type":"general-purpose","hook_event_name":"SubagentStart"}},"host":"claude","kind":"event","process":{"cwd":"/tmp/host-test/claude-workspace","entry":"/fast/projects/agent-bundle-worktrees/host-test/examples/host-test/artifact/claude/mcp/mcp-host-test-0d229f1b-flight.mjs","pid":1071574,"ppid":1070791},"recordedAt":"2026-09-03T08:46:28.603Z","request":{"host":{"source":"native","state":"available","value":{"name":"claude"}},"invocation":{"kind":"event"},"session":{"source":"native","state":"available","value":{"sessionId":"a7f96472-e9d0-447a-826d-36da9b635fd6"}}},"runtime":"shared-runtime","sequence":17} +{"event":{"canonical":{"event":"tool/after","idempotencyKey":"4429acdf4b3d6caa7d6cda951a6c558fa46a87bda4812fa269fb31b0471281b2","observedAt":"2026-09-03T08:46:28.603Z","provenance":{"host":"claude","hostContractRevision":"2.1.250","nativeEvent":"PostToolUse","source":"native"},"sequence":16},"native":{"session_id":"a7f96472-e9d0-447a-826d-36da9b635fd6","transcript_path":"/tmp/host-test/claude-home/.claude/projects/-tmp-host-test-claude-workspace/a7f96472-e9d0-447a-826d-36da9b635fd6.jsonl","cwd":"/tmp/host-test/claude-workspace","prompt_id":"96a54da1-f00b-48ec-8f84-2d42b7de5ba4","permission_mode":"bypassPermissions","agent_id":"aca96ce761c9f0cea","agent_type":"general-purpose","hook_event_name":"PostToolUse","tool_name":"Agent","tool_input":{"description":"nested host-test probe","prompt":"NESTED_PROBE_SCENARIO: run `pwd`, call the host-test-raw probe tool with {\"note\":\"nested\"}, then reply with every id you saw.","subagent_type":"general-purpose"},"tool_response":{"isAsync":true,"status":"async_launched","agentId":"ac093bdad0566ffa7","description":"nested host-test probe","resolvedModel":"claude-sonnet-4-5","prompt":"NESTED_PROBE_SCENARIO: run `pwd`, call the host-test-raw probe tool with {\"note\":\"nested\"}, then reply with every id you saw.","outputFile":"/tmp/claude-1000/-tmp-host-test-claude-workspace/a7f96472-e9d0-447a-826d-36da9b635fd6/tasks/ac093bdad0566ffa7.output","canReadOutputFile":true},"tool_use_id":"toolu_mock_10","duration_ms":4}},"host":"claude","kind":"event","process":{"cwd":"/tmp/host-test/claude-workspace","entry":"/fast/projects/agent-bundle-worktrees/host-test/examples/host-test/artifact/claude/mcp/mcp-host-test-0d229f1b-flight.mjs","pid":1071574,"ppid":1070791},"recordedAt":"2026-09-03T08:46:28.609Z","request":{"host":{"source":"native","state":"available","value":{"name":"claude"}},"invocation":{"kind":"event"},"session":{"source":"native","state":"available","value":{"sessionId":"a7f96472-e9d0-447a-826d-36da9b635fd6"}}},"runtime":"shared-runtime","sequence":18} +{"event":{"canonical":{"event":"tool/before","idempotencyKey":"7e6771796a0e97521ff6865ae81095b436501d05e5225dddb37785e195c40826","observedAt":"2026-09-03T08:46:28.751Z","provenance":{"host":"claude","hostContractRevision":"2.1.250","nativeEvent":"PreToolUse","source":"native"},"sequence":17},"native":{"session_id":"a7f96472-e9d0-447a-826d-36da9b635fd6","transcript_path":"/tmp/host-test/claude-home/.claude/projects/-tmp-host-test-claude-workspace/a7f96472-e9d0-447a-826d-36da9b635fd6.jsonl","cwd":"/tmp/host-test/claude-workspace","prompt_id":"96a54da1-f00b-48ec-8f84-2d42b7de5ba4","permission_mode":"bypassPermissions","agent_id":"ac093bdad0566ffa7","agent_type":"general-purpose","hook_event_name":"PreToolUse","tool_name":"Bash","tool_input":{"command":"pwd"},"tool_use_id":"toolu_mock_11"}},"host":"claude","kind":"event","process":{"cwd":"/tmp/host-test/claude-workspace","entry":"/fast/projects/agent-bundle-worktrees/host-test/examples/host-test/artifact/claude/mcp/mcp-host-test-0d229f1b-flight.mjs","pid":1071574,"ppid":1070791},"recordedAt":"2026-09-03T08:46:28.754Z","request":{"host":{"source":"native","state":"available","value":{"name":"claude"}},"invocation":{"kind":"event"},"session":{"source":"native","state":"available","value":{"sessionId":"a7f96472-e9d0-447a-826d-36da9b635fd6"}}},"runtime":"shared-runtime","sequence":19} +{"event":{"canonical":{"event":"agent/stop","idempotencyKey":"d13abb15dd74eabfd06d1a3bbfe96c31f7c23ac66438fc9b058c723be37be1f2","observedAt":"2026-09-03T08:46:28.754Z","provenance":{"host":"claude","hostContractRevision":"2.1.250","nativeEvent":"SubagentStop","source":"native"},"sequence":18},"native":{"session_id":"a7f96472-e9d0-447a-826d-36da9b635fd6","transcript_path":"/tmp/host-test/claude-home/.claude/projects/-tmp-host-test-claude-workspace/a7f96472-e9d0-447a-826d-36da9b635fd6.jsonl","cwd":"/tmp/host-test/claude-workspace","prompt_id":"96a54da1-f00b-48ec-8f84-2d42b7de5ba4","permission_mode":"bypassPermissions","agent_id":"aca96ce761c9f0cea","agent_type":"general-purpose","hook_event_name":"SubagentStop","stop_hook_active":false,"agent_transcript_path":"/tmp/host-test/claude-home/.claude/projects/-tmp-host-test-claude-workspace/a7f96472-e9d0-447a-826d-36da9b635fd6/subagents/agent-aca96ce761c9f0cea.jsonl","last_assistant_message":"SUBAGENT_DONE: reported every id from the dump and probe results above.","background_tasks":[{"id":"aca96ce761c9f0cea","type":"subagent","status":"running","description":"host-test subagent probe","agent_type":"general-purpose"},{"id":"ac093bdad0566ffa7","type":"subagent","status":"running","description":"nested host-test probe","agent_type":"general-purpose"}],"session_crons":[]}},"host":"claude","kind":"event","process":{"cwd":"/tmp/host-test/claude-workspace","entry":"/fast/projects/agent-bundle-worktrees/host-test/examples/host-test/artifact/claude/mcp/mcp-host-test-0d229f1b-flight.mjs","pid":1071574,"ppid":1070791},"recordedAt":"2026-09-03T08:46:28.762Z","request":{"host":{"source":"native","state":"available","value":{"name":"claude"}},"invocation":{"kind":"event"},"session":{"source":"native","state":"available","value":{"sessionId":"a7f96472-e9d0-447a-826d-36da9b635fd6"}}},"runtime":"shared-runtime","sequence":20} +{"event":{"canonical":{"event":"tool/after","idempotencyKey":"8acc5096401f0230c9ee7fa9be2ad40dba88e379129c7d24a1c0e167eee08563","observedAt":"2026-09-03T08:46:28.897Z","provenance":{"host":"claude","hostContractRevision":"2.1.250","nativeEvent":"PostToolUse","source":"native"},"sequence":19},"native":{"session_id":"a7f96472-e9d0-447a-826d-36da9b635fd6","transcript_path":"/tmp/host-test/claude-home/.claude/projects/-tmp-host-test-claude-workspace/a7f96472-e9d0-447a-826d-36da9b635fd6.jsonl","cwd":"/tmp/host-test/claude-workspace","prompt_id":"96a54da1-f00b-48ec-8f84-2d42b7de5ba4","permission_mode":"bypassPermissions","agent_id":"ac093bdad0566ffa7","agent_type":"general-purpose","hook_event_name":"PostToolUse","tool_name":"Bash","tool_input":{"command":"pwd"},"tool_response":{"stdout":"/tmp/host-test/claude-workspace","stderr":"","interrupted":false,"isImage":false,"noOutputExpected":false},"tool_use_id":"toolu_mock_11","duration_ms":10}},"host":"claude","kind":"event","process":{"cwd":"/tmp/host-test/claude-workspace","entry":"/fast/projects/agent-bundle-worktrees/host-test/examples/host-test/artifact/claude/mcp/mcp-host-test-0d229f1b-flight.mjs","pid":1071574,"ppid":1070791},"recordedAt":"2026-09-03T08:46:28.900Z","request":{"host":{"source":"native","state":"available","value":{"name":"claude"}},"invocation":{"kind":"event"},"session":{"source":"native","state":"available","value":{"sessionId":"a7f96472-e9d0-447a-826d-36da9b635fd6"}}},"runtime":"shared-runtime","sequence":21} +{"event":{"canonical":{"event":"prompt/submit","idempotencyKey":"b8c53ebcf3362adb4a74b952d88628069738eb9e70bc256b92e72840a99acb69","observedAt":"2026-09-03T08:46:29.003Z","provenance":{"host":"claude","hostContractRevision":"2.1.250","nativeEvent":"UserPromptSubmit","source":"native"},"sequence":20},"native":{"session_id":"a7f96472-e9d0-447a-826d-36da9b635fd6","transcript_path":"/tmp/host-test/claude-home/.claude/projects/-tmp-host-test-claude-workspace/a7f96472-e9d0-447a-826d-36da9b635fd6.jsonl","cwd":"/tmp/host-test/claude-workspace","prompt_id":"41a8b30c-65cf-42a7-af74-644f5a5c1875","permission_mode":"bypassPermissions","hook_event_name":"UserPromptSubmit","prompt":"\naca96ce761c9f0cea\ntoolu_mock_5\n/tmp/claude-1000/-tmp-host-test-claude-workspace/a7f96472-e9d0-447a-826d-36da9b635fd6/task…[+556 chars]"}},"host":"claude","kind":"event","process":{"cwd":"/tmp/host-test/claude-workspace","entry":"/fast/projects/agent-bundle-worktrees/host-test/examples/host-test/artifact/claude/mcp/mcp-host-test-0d229f1b-flight.mjs","pid":1071574,"ppid":1070791},"recordedAt":"2026-09-03T08:46:29.006Z","request":{"host":{"source":"native","state":"available","value":{"name":"claude"}},"invocation":{"kind":"event"},"session":{"source":"native","state":"available","value":{"sessionId":"a7f96472-e9d0-447a-826d-36da9b635fd6"}}},"runtime":"shared-runtime","sequence":22} +{"event":{"canonical":{"event":"tool/before","idempotencyKey":"375d8bed0b8de73d6be37d79fb5ddabda26e9b0c6d4c6bc437c391521986201f","observedAt":"2026-09-03T08:46:29.038Z","provenance":{"host":"claude","hostContractRevision":"2.1.250","nativeEvent":"PreToolUse","source":"native"},"sequence":21},"native":{"session_id":"a7f96472-e9d0-447a-826d-36da9b635fd6","transcript_path":"/tmp/host-test/claude-home/.claude/projects/-tmp-host-test-claude-workspace/a7f96472-e9d0-447a-826d-36da9b635fd6.jsonl","cwd":"/tmp/host-test/claude-workspace","prompt_id":"41a8b30c-65cf-42a7-af74-644f5a5c1875","permission_mode":"bypassPermissions","agent_id":"ac093bdad0566ffa7","agent_type":"general-purpose","hook_event_name":"PreToolUse","tool_name":"mcp__plugin_host-test_host-test-raw__probe","tool_input":{"note":"nested"},"tool_use_id":"toolu_mock_13"}},"host":"claude","kind":"event","process":{"cwd":"/tmp/host-test/claude-workspace","entry":"/fast/projects/agent-bundle-worktrees/host-test/examples/host-test/artifact/claude/mcp/mcp-host-test-0d229f1b-flight.mjs","pid":1071574,"ppid":1070791},"recordedAt":"2026-09-03T08:46:29.041Z","request":{"host":{"source":"native","state":"available","value":{"name":"claude"}},"invocation":{"kind":"event"},"session":{"source":"native","state":"available","value":{"sessionId":"a7f96472-e9d0-447a-826d-36da9b635fd6"}}},"runtime":"shared-runtime","sequence":23} +{"host":"claude-code","kind":"mcp","observed":{"client":{"name":"claude-code","title":"Claude Code","version":"2.1.257","websiteUrl":"https://claude.com/claude-code","description":"Anthropic's agentic coding tool"},"clientCapabilities":{"elicitation":{"form":{}},"roots":{"listChanged":true}},"env":{"names":["AGENT_BUNDLE_PLUGIN_ROOT","ANTHROPIC_API_KEY","ANTHROPIC_BASE_URL","CLAUDE_CODE_DISABLE_NONESSENTIAL_TRAFFIC","CLAUDE_CODE_ENTRYPOINT","CLAUDE_CODE_MESSAGING_SOCKET","CLAUDE_CODE_MESSAGING_TOKEN","CLAUDE_CODE_SESSION_ID","CLAUDE_CONFIG_DIR","CLAUDE_PLUGIN_DATA","CLAUDE_PLUGIN_ROOT","CLAUDE_PROJECT_DIR","CURSOR_LAYOUT","CURSOR_RIPGREP_PATH","HOST_TEST_LOG_DIR"]},"http":null,"mcpReq":{"_meta":{"progressToken":4,"claudecode/toolUseId":"toolu_mock_13"},"envelope":null,"id":4,"method":"tools/call"},"note":"nested","sessionId":null,"tool":"probe"},"process":{"cwd":"/tmp/host-test/claude-workspace","entry":"/fast/projects/agent-bundle-worktrees/host-test/examples/host-test/artifact/claude/mcp/mcp-host-test-raw-6e9c1a1c.mjs","pid":1071578,"ppid":1070791},"recordedAt":"2026-09-03T08:46:29.062Z","request":{"unavailable":"hand-rolled stdio server: no framework request context is mounted"},"runtime":"mcp-server","sequence":3} +{"event":{"canonical":{"event":"stop","idempotencyKey":"c9ba472646faa329a496e87ffcaa2057f4e1a4ae7689a46895bb9be9e8d9e4db","observedAt":"2026-09-03T08:46:29.157Z","provenance":{"host":"claude","hostContractRevision":"2.1.250","nativeEvent":"Stop","source":"native"},"sequence":22},"native":{"session_id":"a7f96472-e9d0-447a-826d-36da9b635fd6","transcript_path":"/tmp/host-test/claude-home/.claude/projects/-tmp-host-test-claude-workspace/a7f96472-e9d0-447a-826d-36da9b635fd6.jsonl","cwd":"/tmp/host-test/claude-workspace","prompt_id":"41a8b30c-65cf-42a7-af74-644f5a5c1875","permission_mode":"bypassPermissions","hook_event_name":"Stop","stop_hook_active":false,"last_assistant_message":"HOST_TEST_DONE (mock model; see the probe log path in the dump result)","background_tasks":[{"id":"ac093bdad0566ffa7","type":"subagent","status":"running","description":"nested host-test probe","agent_type":"general-purpose"}],"session_crons":[]}},"host":"claude","kind":"event","process":{"cwd":"/tmp/host-test/claude-workspace","entry":"/fast/projects/agent-bundle-worktrees/host-test/examples/host-test/artifact/claude/mcp/mcp-host-test-0d229f1b-flight.mjs","pid":1071574,"ppid":1070791},"recordedAt":"2026-09-03T08:46:29.159Z","request":{"host":{"source":"native","state":"available","value":{"name":"claude"}},"invocation":{"kind":"event"},"session":{"source":"native","state":"available","value":{"sessionId":"a7f96472-e9d0-447a-826d-36da9b635fd6"}}},"runtime":"shared-runtime","sequence":24} +{"event":{"canonical":{"event":"agent/stop","idempotencyKey":"fc01173a176e10503e309d607a83e06dc251bb48edd046a552609913b3bc8180","observedAt":"2026-09-03T08:46:29.302Z","provenance":{"host":"claude","hostContractRevision":"2.1.250","nativeEvent":"SubagentStop","source":"native"},"sequence":23},"native":{"session_id":"a7f96472-e9d0-447a-826d-36da9b635fd6","transcript_path":"/tmp/host-test/claude-home/.claude/projects/-tmp-host-test-claude-workspace/a7f96472-e9d0-447a-826d-36da9b635fd6.jsonl","cwd":"/tmp/host-test/claude-workspace","prompt_id":"41a8b30c-65cf-42a7-af74-644f5a5c1875","permission_mode":"bypassPermissions","agent_id":"ac093bdad0566ffa7","agent_type":"general-purpose","hook_event_name":"SubagentStop","stop_hook_active":false,"agent_transcript_path":"/tmp/host-test/claude-home/.claude/projects/-tmp-host-test-claude-workspace/a7f96472-e9d0-447a-826d-36da9b635fd6/subagents/agent-ac093bdad0566ffa7.jsonl","last_assistant_message":"NESTED_DONE: reported every id from the probe result above.","background_tasks":[{"id":"ac093bdad0566ffa7","type":"subagent","status":"running","description":"nested host-test probe","agent_type":"general-purpose"}],"session_crons":[]}},"host":"claude","kind":"event","process":{"cwd":"/tmp/host-test/claude-workspace","entry":"/fast/projects/agent-bundle-worktrees/host-test/examples/host-test/artifact/claude/mcp/mcp-host-test-0d229f1b-flight.mjs","pid":1071574,"ppid":1070791},"recordedAt":"2026-09-03T08:46:29.304Z","request":{"host":{"source":"native","state":"available","value":{"name":"claude"}},"invocation":{"kind":"event"},"session":{"source":"native","state":"available","value":{"sessionId":"a7f96472-e9d0-447a-826d-36da9b635fd6"}}},"runtime":"shared-runtime","sequence":25} +{"event":{"canonical":{"event":"prompt/submit","idempotencyKey":"f7b0acdf94045a59e9813e57f616689894cc411b5d60b92913bcc5e8b188087f","observedAt":"2026-09-03T08:46:29.489Z","provenance":{"host":"claude","hostContractRevision":"2.1.250","nativeEvent":"UserPromptSubmit","source":"native"},"sequence":24},"native":{"session_id":"a7f96472-e9d0-447a-826d-36da9b635fd6","transcript_path":"/tmp/host-test/claude-home/.claude/projects/-tmp-host-test-claude-workspace/a7f96472-e9d0-447a-826d-36da9b635fd6.jsonl","cwd":"/tmp/host-test/claude-workspace","prompt_id":"88eaceb2-67ed-4bdb-abed-84a52891719d","permission_mode":"bypassPermissions","hook_event_name":"UserPromptSubmit","prompt":"\nac093bdad0566ffa7\ntoolu_mock_10\n/tmp/claude-1000/-tmp-host-test-claude-workspace/a7f96472-e9d0-447a-826d-36da9b635fd6/tas…[+542 chars]"}},"host":"claude","kind":"event","process":{"cwd":"/tmp/host-test/claude-workspace","entry":"/fast/projects/agent-bundle-worktrees/host-test/examples/host-test/artifact/claude/mcp/mcp-host-test-0d229f1b-flight.mjs","pid":1071574,"ppid":1070791},"recordedAt":"2026-09-03T08:46:29.492Z","request":{"host":{"source":"native","state":"available","value":{"name":"claude"}},"invocation":{"kind":"event"},"session":{"source":"native","state":"available","value":{"sessionId":"a7f96472-e9d0-447a-826d-36da9b635fd6"}}},"runtime":"shared-runtime","sequence":26} +{"event":{"canonical":{"event":"stop","idempotencyKey":"c673791c3035f1621082031cbfe63d1dc60236957efcbd7fcfe3690624949fdd","observedAt":"2026-09-03T08:46:29.638Z","provenance":{"host":"claude","hostContractRevision":"2.1.250","nativeEvent":"Stop","source":"native"},"sequence":25},"native":{"session_id":"a7f96472-e9d0-447a-826d-36da9b635fd6","transcript_path":"/tmp/host-test/claude-home/.claude/projects/-tmp-host-test-claude-workspace/a7f96472-e9d0-447a-826d-36da9b635fd6.jsonl","cwd":"/tmp/host-test/claude-workspace","prompt_id":"88eaceb2-67ed-4bdb-abed-84a52891719d","permission_mode":"bypassPermissions","hook_event_name":"Stop","stop_hook_active":false,"last_assistant_message":"HOST_TEST_DONE (mock model; see the probe log path in the dump result)","background_tasks":[],"session_crons":[]}},"host":"claude","kind":"event","process":{"cwd":"/tmp/host-test/claude-workspace","entry":"/fast/projects/agent-bundle-worktrees/host-test/examples/host-test/artifact/claude/mcp/mcp-host-test-0d229f1b-flight.mjs","pid":1071574,"ppid":1070791},"recordedAt":"2026-09-03T08:46:29.641Z","request":{"host":{"source":"native","state":"available","value":{"name":"claude"}},"invocation":{"kind":"event"},"session":{"source":"native","state":"available","value":{"sessionId":"a7f96472-e9d0-447a-826d-36da9b635fd6"}}},"runtime":"shared-runtime","sequence":27} +{"event":{"canonical":{"event":"session/end","idempotencyKey":"a45c5e72b8c3c8298ff57e3cb08bb0968787a765b66d2cf08dd437bf8f659994","observedAt":"2026-09-03T08:46:29.826Z","provenance":{"host":"claude","hostContractRevision":"2.1.250","nativeEvent":"SessionEnd","source":"native"},"sequence":1},"native":{"session_id":"a7f96472-e9d0-447a-826d-36da9b635fd6","transcript_path":"/tmp/host-test/claude-home/.claude/projects/-tmp-host-test-claude-workspace/a7f96472-e9d0-447a-826d-36da9b635fd6.jsonl","cwd":"/tmp/host-test/claude-workspace","prompt_id":"88eaceb2-67ed-4bdb-abed-84a52891719d","hook_event_name":"SessionEnd","reason":"other"}},"host":"claude","kind":"event","process":{"cwd":"/tmp/host-test/claude-workspace","entry":"/fast/projects/agent-bundle-worktrees/host-test/examples/host-test/artifact/claude/hooks/hooks-flight.mjs","pid":1076993,"ppid":1076991},"recordedAt":"2026-09-03T08:46:30.070Z","request":{"host":{"source":"native","state":"available","value":{"name":"claude"}},"invocation":{"kind":"event"},"session":{"source":"native","state":"available","value":{"sessionId":"a7f96472-e9d0-447a-826d-36da9b635fd6"}}},"runtime":"standalone-hook","sequence":1} diff --git a/fixtures/host-lineage/codex-0.147.0.ndjson b/fixtures/host-lineage/codex-0.147.0.ndjson new file mode 100644 index 000000000..1e3f5d31e --- /dev/null +++ b/fixtures/host-lineage/codex-0.147.0.ndjson @@ -0,0 +1,41 @@ +{"env":{"names":["AGENT_BUNDLE_PLUGIN_ROOT"]},"event":{"canonical":{"event":"session/start","idempotencyKey":"1e8e3b2a09981e22bb91d86ead42188604fdee97f9230dda41dc6dce6057f3f1","observedAt":"2026-09-03T08:26:09.242Z","provenance":{"host":"codex","hostContractRevision":"0.147.0","nativeEvent":"SessionStart","source":"native"},"sequence":1},"native":{"session_id":"01a06660-110e-7290-8d1c-8ef1b2b68fc2","transcript_path":"/tmp/host-test/codex-home/.codex/sessions/2026/09/03/rollout-2026-09-03T08-26-06-01a06660-110e-7290-8d1c-8ef1b2b68fc2.jsonl","cwd":"/tmp/host-test/codex-workspace","hook_event_name":"SessionStart","model":"gpt-5.6-sol","permission_mode":"bypassPermissions","source":"startup"}},"host":"codex","kind":"event","process":{"cwd":"/tmp/host-test/codex-home/.codex/plugins/cache/host-test-marketplace/host-test/1.0.0","entry":"/tmp/host-test/codex-home/.codex/plugins/cache/host-test-marketplace/host-test/1.0.0/mcp/mcp-host-test-0d229f1b-flight.mjs","pid":3858309,"ppid":3857224},"recordedAt":"2026-09-03T08:26:09.332Z","request":{"host":{"source":"native","state":"available","value":{"name":"codex"}},"invocation":{"kind":"event"},"session":{"source":"native","state":"available","value":{"sessionId":"01a06660-110e-7290-8d1c-8ef1b2b68fc2"}}},"runtime":"shared-runtime","sequence":1} +{"event":{"canonical":{"event":"prompt/submit","idempotencyKey":"652eb2dd41f5bd4a9eefae2724aef1d611262c50b4e66df68761cf45a51f3f40","observedAt":"2026-09-03T08:26:09.582Z","provenance":{"host":"codex","hostContractRevision":"0.147.0","nativeEvent":"UserPromptSubmit","source":"native"},"sequence":2},"native":{"session_id":"01a06660-110e-7290-8d1c-8ef1b2b68fc2","turn_id":"01a06660-1179-7bd2-bb02-d4cac726b2a0","transcript_path":"/tmp/host-test/codex-home/.codex/sessions/2026/09/03/rollout-2026-09-03T08-26-06-01a06660-110e-7290-8d1c-8ef1b2b68fc2.jsonl","cwd":"/tmp/host-test/codex-workspace","hook_event_name":"UserPromptSubmit","model":"gpt-5.6-sol","permission_mode":"bypassPermissions","prompt":"You are exercising the host-test probe plugin. Do exactly these steps in order, without asking questions.\n1. Run the shell command `pwd`.\n2. Create a file named probe-note.txt in the current directory…[+747 chars]"}},"host":"codex","kind":"event","process":{"cwd":"/tmp/host-test/codex-home/.codex/plugins/cache/host-test-marketplace/host-test/1.0.0","entry":"/tmp/host-test/codex-home/.codex/plugins/cache/host-test-marketplace/host-test/1.0.0/mcp/mcp-host-test-0d229f1b-flight.mjs","pid":3858309,"ppid":3857224},"recordedAt":"2026-09-03T08:26:09.589Z","request":{"host":{"source":"native","state":"available","value":{"name":"codex"}},"invocation":{"kind":"event"},"session":{"source":"native","state":"available","value":{"sessionId":"01a06660-110e-7290-8d1c-8ef1b2b68fc2"}}},"runtime":"shared-runtime","sequence":2} +{"event":{"canonical":{"event":"tool/before","idempotencyKey":"5ebb5f95e4ebf2677ec9135b7fb536204a0b388fae13bb108f25e677d71a716b","observedAt":"2026-09-03T08:26:13.334Z","provenance":{"host":"codex","hostContractRevision":"0.147.0","nativeEvent":"PreToolUse","source":"native"},"sequence":3},"native":{"session_id":"01a06660-110e-7290-8d1c-8ef1b2b68fc2","turn_id":"01a06660-1179-7bd2-bb02-d4cac726b2a0","transcript_path":"/tmp/host-test/codex-home/.codex/sessions/2026/09/03/rollout-2026-09-03T08-26-06-01a06660-110e-7290-8d1c-8ef1b2b68fc2.jsonl","cwd":"/tmp/host-test/codex-workspace","hook_event_name":"PreToolUse","model":"gpt-5.6-sol","permission_mode":"bypassPermissions","tool_name":"Bash","tool_input":{"command":"sed -n '1,240p' /tmp/host-test/codex-home/.codex/plugins/cache/host-test-marketplace/host-test/1.0.0/skills/host-test/SKILL.md"},"tool_use_id":"exec-95e92c51-9373-4a8e-9cc1-5f2bf32efee1"}},"host":"codex","kind":"event","process":{"cwd":"/tmp/host-test/codex-home/.codex/plugins/cache/host-test-marketplace/host-test/1.0.0","entry":"/tmp/host-test/codex-home/.codex/plugins/cache/host-test-marketplace/host-test/1.0.0/mcp/mcp-host-test-0d229f1b-flight.mjs","pid":3858309,"ppid":3857224},"recordedAt":"2026-09-03T08:26:13.339Z","request":{"host":{"source":"native","state":"available","value":{"name":"codex"}},"invocation":{"kind":"event"},"session":{"source":"native","state":"available","value":{"sessionId":"01a06660-110e-7290-8d1c-8ef1b2b68fc2"}}},"runtime":"shared-runtime","sequence":3} +{"event":{"canonical":{"event":"tool/after","idempotencyKey":"863f202d02e6468cc647d110727b173f43cb35ba3579d30c2980b4ebeb2b3e56","observedAt":"2026-09-03T08:26:13.593Z","provenance":{"host":"codex","hostContractRevision":"0.147.0","nativeEvent":"PostToolUse","source":"native"},"sequence":4},"native":{"session_id":"01a06660-110e-7290-8d1c-8ef1b2b68fc2","turn_id":"01a06660-1179-7bd2-bb02-d4cac726b2a0","transcript_path":"/tmp/host-test/codex-home/.codex/sessions/2026/09/03/rollout-2026-09-03T08-26-06-01a06660-110e-7290-8d1c-8ef1b2b68fc2.jsonl","cwd":"/tmp/host-test/codex-workspace","hook_event_name":"PostToolUse","model":"gpt-5.6-sol","permission_mode":"bypassPermissions","tool_name":"Bash","tool_input":{"command":"sed -n '1,240p' /tmp/host-test/codex-home/.codex/plugins/cache/host-test-marketplace/host-test/1.0.0/skills/host-test/SKILL.md"},"tool_response":"---\nname: host-test\ndescription: Probe what this host sends to plugin hooks and MCP servers. Use when asked to run the host-test probe, dump host lineage, or check which conversation, session, or subagent ids a hook or MCP call carries.\n---\n\n# Host test probe\n\nThis plugin records every hook event the host dispatches to it, plus every\ncall to its own MCP servers, into one NDJSON log and a durable s…[+1064 chars]","tool_use_id":"exec-95e92c51-9373-4a8e-9cc1-5f2bf32efee1"}},"host":"codex","kind":"event","process":{"cwd":"/tmp/host-test/codex-home/.codex/plugins/cache/host-test-marketplace/host-test/1.0.0","entry":"/tmp/host-test/codex-home/.codex/plugins/cache/host-test-marketplace/host-test/1.0.0/mcp/mcp-host-test-0d229f1b-flight.mjs","pid":3858309,"ppid":3857224},"recordedAt":"2026-09-03T08:26:13.597Z","request":{"host":{"source":"native","state":"available","value":{"name":"codex"}},"invocation":{"kind":"event"},"session":{"source":"native","state":"available","value":{"sessionId":"01a06660-110e-7290-8d1c-8ef1b2b68fc2"}}},"runtime":"shared-runtime","sequence":4} +{"event":{"canonical":{"event":"tool/before","idempotencyKey":"619625fb82f4ea7246343b7d2f27cada2a903c94031cf5a75abd2316dd1a4621","observedAt":"2026-09-03T08:26:17.751Z","provenance":{"host":"codex","hostContractRevision":"0.147.0","nativeEvent":"PreToolUse","source":"native"},"sequence":5},"native":{"session_id":"01a06660-110e-7290-8d1c-8ef1b2b68fc2","turn_id":"01a06660-1179-7bd2-bb02-d4cac726b2a0","transcript_path":"/tmp/host-test/codex-home/.codex/sessions/2026/09/03/rollout-2026-09-03T08-26-06-01a06660-110e-7290-8d1c-8ef1b2b68fc2.jsonl","cwd":"/tmp/host-test/codex-workspace","hook_event_name":"PreToolUse","model":"gpt-5.6-sol","permission_mode":"bypassPermissions","tool_name":"Bash","tool_input":{"command":"pwd"},"tool_use_id":"exec-c5f2c1db-06f5-4694-ade7-af24014725e5"}},"host":"codex","kind":"event","process":{"cwd":"/tmp/host-test/codex-home/.codex/plugins/cache/host-test-marketplace/host-test/1.0.0","entry":"/tmp/host-test/codex-home/.codex/plugins/cache/host-test-marketplace/host-test/1.0.0/mcp/mcp-host-test-0d229f1b-flight.mjs","pid":3858309,"ppid":3857224},"recordedAt":"2026-09-03T08:26:17.758Z","request":{"host":{"source":"native","state":"available","value":{"name":"codex"}},"invocation":{"kind":"event"},"session":{"source":"native","state":"available","value":{"sessionId":"01a06660-110e-7290-8d1c-8ef1b2b68fc2"}}},"runtime":"shared-runtime","sequence":5} +{"event":{"canonical":{"event":"tool/after","idempotencyKey":"c4ed76a5546494d4689682a3d7c3c02c2dce105d2abb6b1ec33079f43fc9ba6f","observedAt":"2026-09-03T08:26:18.021Z","provenance":{"host":"codex","hostContractRevision":"0.147.0","nativeEvent":"PostToolUse","source":"native"},"sequence":6},"native":{"session_id":"01a06660-110e-7290-8d1c-8ef1b2b68fc2","turn_id":"01a06660-1179-7bd2-bb02-d4cac726b2a0","transcript_path":"/tmp/host-test/codex-home/.codex/sessions/2026/09/03/rollout-2026-09-03T08-26-06-01a06660-110e-7290-8d1c-8ef1b2b68fc2.jsonl","cwd":"/tmp/host-test/codex-workspace","hook_event_name":"PostToolUse","model":"gpt-5.6-sol","permission_mode":"bypassPermissions","tool_name":"Bash","tool_input":{"command":"pwd"},"tool_response":"/tmp/host-test/codex-workspace\n","tool_use_id":"exec-c5f2c1db-06f5-4694-ade7-af24014725e5"}},"host":"codex","kind":"event","process":{"cwd":"/tmp/host-test/codex-home/.codex/plugins/cache/host-test-marketplace/host-test/1.0.0","entry":"/tmp/host-test/codex-home/.codex/plugins/cache/host-test-marketplace/host-test/1.0.0/mcp/mcp-host-test-0d229f1b-flight.mjs","pid":3858309,"ppid":3857224},"recordedAt":"2026-09-03T08:26:18.025Z","request":{"host":{"source":"native","state":"available","value":{"name":"codex"}},"invocation":{"kind":"event"},"session":{"source":"native","state":"available","value":{"sessionId":"01a06660-110e-7290-8d1c-8ef1b2b68fc2"}}},"runtime":"shared-runtime","sequence":6} +{"event":{"canonical":{"event":"tool/before","idempotencyKey":"532a079e1fcdc4cf9c8cfd93cb0329b0e7c995feb6ff0c763e9b98aed305833b","observedAt":"2026-09-03T08:26:21.549Z","provenance":{"host":"codex","hostContractRevision":"0.147.0","nativeEvent":"PreToolUse","source":"native"},"sequence":7},"native":{"session_id":"01a06660-110e-7290-8d1c-8ef1b2b68fc2","turn_id":"01a06660-1179-7bd2-bb02-d4cac726b2a0","transcript_path":"/tmp/host-test/codex-home/.codex/sessions/2026/09/03/rollout-2026-09-03T08-26-06-01a06660-110e-7290-8d1c-8ef1b2b68fc2.jsonl","cwd":"/tmp/host-test/codex-workspace","hook_event_name":"PreToolUse","model":"gpt-5.6-sol","permission_mode":"bypassPermissions","tool_name":"apply_patch","tool_input":{"command":"*** Begin Patch\n*** Add File: /tmp/host-test/codex-workspace/probe-note.txt\n+host-test\n*** End Patch"},"tool_use_id":"exec-ef038ff6-41f4-47e9-b808-69cc9de68031"}},"host":"codex","kind":"event","process":{"cwd":"/tmp/host-test/codex-home/.codex/plugins/cache/host-test-marketplace/host-test/1.0.0","entry":"/tmp/host-test/codex-home/.codex/plugins/cache/host-test-marketplace/host-test/1.0.0/mcp/mcp-host-test-0d229f1b-flight.mjs","pid":3858309,"ppid":3857224},"recordedAt":"2026-09-03T08:26:21.553Z","request":{"host":{"source":"native","state":"available","value":{"name":"codex"}},"invocation":{"kind":"event"},"session":{"source":"native","state":"available","value":{"sessionId":"01a06660-110e-7290-8d1c-8ef1b2b68fc2"}}},"runtime":"shared-runtime","sequence":7} +{"event":{"canonical":{"event":"tool/after","idempotencyKey":"3de3c86c19f1d59daf78b45ced65583735fb43c62aa4c058601f22bc4736843e","observedAt":"2026-09-03T08:26:21.867Z","provenance":{"host":"codex","hostContractRevision":"0.147.0","nativeEvent":"PostToolUse","source":"native"},"sequence":8},"native":{"session_id":"01a06660-110e-7290-8d1c-8ef1b2b68fc2","turn_id":"01a06660-1179-7bd2-bb02-d4cac726b2a0","transcript_path":"/tmp/host-test/codex-home/.codex/sessions/2026/09/03/rollout-2026-09-03T08-26-06-01a06660-110e-7290-8d1c-8ef1b2b68fc2.jsonl","cwd":"/tmp/host-test/codex-workspace","hook_event_name":"PostToolUse","model":"gpt-5.6-sol","permission_mode":"bypassPermissions","tool_name":"apply_patch","tool_input":{"command":"*** Begin Patch\n*** Add File: /tmp/host-test/codex-workspace/probe-note.txt\n+host-test\n*** End Patch"},"tool_response":"Exit code: 0\nWall time: 0.2 seconds\nOutput:\nSuccess. Updated the following files:\nA /tmp/host-test/codex-workspace/probe-note.txt\n","tool_use_id":"exec-ef038ff6-41f4-47e9-b808-69cc9de68031"}},"host":"codex","kind":"event","process":{"cwd":"/tmp/host-test/codex-home/.codex/plugins/cache/host-test-marketplace/host-test/1.0.0","entry":"/tmp/host-test/codex-home/.codex/plugins/cache/host-test-marketplace/host-test/1.0.0/mcp/mcp-host-test-0d229f1b-flight.mjs","pid":3858309,"ppid":3857224},"recordedAt":"2026-09-03T08:26:21.870Z","request":{"host":{"source":"native","state":"available","value":{"name":"codex"}},"invocation":{"kind":"event"},"session":{"source":"native","state":"available","value":{"sessionId":"01a06660-110e-7290-8d1c-8ef1b2b68fc2"}}},"runtime":"shared-runtime","sequence":8} +{"event":{"canonical":{"event":"tool/before","idempotencyKey":"4ff7a1273e1a9ec96fc8cacd08f9537f459a3f0099fb502c00d9ba22a7f1155e","observedAt":"2026-09-03T08:26:30.176Z","provenance":{"host":"codex","hostContractRevision":"0.147.0","nativeEvent":"PreToolUse","source":"native"},"sequence":9},"native":{"session_id":"01a06660-110e-7290-8d1c-8ef1b2b68fc2","turn_id":"01a06660-1179-7bd2-bb02-d4cac726b2a0","transcript_path":"/tmp/host-test/codex-home/.codex/sessions/2026/09/03/rollout-2026-09-03T08-26-06-01a06660-110e-7290-8d1c-8ef1b2b68fc2.jsonl","cwd":"/tmp/host-test/codex-workspace","hook_event_name":"PreToolUse","model":"gpt-5.6-sol","permission_mode":"bypassPermissions","tool_name":"mcp__host_test__dump","tool_input":{},"tool_use_id":"exec-0a6138e5-b465-4dad-85c2-6c32efa77537"}},"host":"codex","kind":"event","process":{"cwd":"/tmp/host-test/codex-home/.codex/plugins/cache/host-test-marketplace/host-test/1.0.0","entry":"/tmp/host-test/codex-home/.codex/plugins/cache/host-test-marketplace/host-test/1.0.0/mcp/mcp-host-test-0d229f1b-flight.mjs","pid":3858309,"ppid":3857224},"recordedAt":"2026-09-03T08:26:30.180Z","request":{"host":{"source":"native","state":"available","value":{"name":"codex"}},"invocation":{"kind":"event"},"session":{"source":"native","state":"available","value":{"sessionId":"01a06660-110e-7290-8d1c-8ef1b2b68fc2"}}},"runtime":"shared-runtime","sequence":9} +{"env":{"names":["AGENT_BUNDLE_PLUGIN_ROOT"]},"host":"codex-mcp-client","kind":"mcp","observed":{"tool":"dump"},"process":{"cwd":"/tmp/host-test/codex-home/.codex/plugins/cache/host-test-marketplace/host-test/1.0.0","entry":"/tmp/host-test/codex-home/.codex/plugins/cache/host-test-marketplace/host-test/1.0.0/mcp/mcp-host-test-0d229f1b-flight.mjs","pid":3858309,"ppid":3857224},"recordedAt":"2026-09-03T08:26:30.205Z","request":{"host":{"source":"native","state":"available","value":{"name":"codex-mcp-client"}},"invocation":{"kind":"tool"},"session":{"reason":"not-provided","state":"unavailable"}},"runtime":"mcp-server","sequence":10} +{"event":{"canonical":{"event":"tool/after","idempotencyKey":"d5871acbb04dcbff67d9858c9cf869e93262e24703292dc5be2f97baa6d623f3","observedAt":"2026-09-03T08:26:30.340Z","provenance":{"host":"codex","hostContractRevision":"0.147.0","nativeEvent":"PostToolUse","source":"native"},"sequence":10},"native":{"session_id":"01a06660-110e-7290-8d1c-8ef1b2b68fc2","turn_id":"01a06660-1179-7bd2-bb02-d4cac726b2a0","transcript_path":"/tmp/host-test/codex-home/.codex/sessions/2026/09/03/rollout-2026-09-03T08-26-06-01a06660-110e-7290-8d1c-8ef1b2b68fc2.jsonl","cwd":"/tmp/host-test/codex-workspace","hook_event_name":"PostToolUse","model":"gpt-5.6-sol","permission_mode":"bypassPermissions","tool_name":"mcp__host_test__dump","tool_input":{},"tool_response":{"content":[{"type":"text","text":"# host-test captures\n\n- Log: `/tmp/host-test/codex-home/.codex/plugins/cache/host-test-marketplace/host-test/1.0.0/state/host-test/captures.ndjson` (env:AGENT_BUNDLE_PLUGIN_ROOT, 10 records, 0 malformed)\n- Durable state: revision 10, 10 total, 10 summarized\n- Matched: 10\n\n| # | kind | event | host | runtime | ids |\n| --- | --- | --- | --- | --- | --- |\n| 1 | event | session/start | codex | shared-…[+1881 chars]"},{"type":"text","text":"{\"filter\":{},\"log\":{\"malformed\":0,\"path\":\"/tmp/host-test/codex-home/.codex/plugins/cache/host-test-marketplace/host-test/1.0.0/state/host-test/captures.ndjson\",\"source\":\"env:AGENT_BUNDLE_PLUGIN_ROOT\"},\"matched\":10,\"records\":[{\"event\":\"session/start\",\"host\":\"codex\",\"ids\":{\"session_id\":\"01a06660-110e-7290-8d1c-8ef1b2b68fc2\",\"transcript_path\":\"/tmp/host-test/codex-home/.codex/sessions/2026/09/03/roll…[+5795 chars]"}],"structuredContent":{"filter":{},"log":{"malformed":0,"path":"/tmp/host-test/codex-home/.codex/plugins/cache/host-test-marketplace/host-test/1.0.0/state/host-test/captures.ndjson","source":"env:AGENT_BUNDLE_PLUGIN_ROOT"},"matched":10,"records":[{"event":"session/start","host":"codex","ids":{"session_id":"01a06660-110e-7290-8d1c-8ef1b2b68fc2","transcript_path":"/tmp/host-test/codex-home/.codex/sessions/2026/09/03/rollout-2026-09-03T08-26-06-01a06660-110e-7290-8d1c-8ef1b2b68fc2.jsonl","model":"gpt-5.6-sol","cwd":"/tmp/host-test/codex-workspace","source":"startup","hook_event_name":"SessionStart"},"index":1,"invocation":"f955caa0-55ca-41e8-ac42-ac5f55e3e0a0","kind":"event","nativeEvent":"SessionStart","pid":3858309,"recordedAt":"2026-09-03T08:26:09.332Z","runtime":"shared-runtime","sequence":1},{"event":"prompt/submit","host":"codex","ids":{"session_id":"01a06660-110e-7290-8d1c-8ef1b2b68fc2","transcript_path":"/tmp/host-test/codex-home/.codex/sessions/2026/09/03/rollout-2026-09-03T08-26-06-01a06660-110e-7290-8d1c-8ef1b2b68fc2.jsonl","turn_id":"01a06660-1179-7bd2-bb02-d4cac726b2a0","model":"gpt-5.6-sol","cwd":"/tmp/host-test/codex-workspace","hook_event_name":"UserPromptSubmit"},"index":2,"invocation":"28ad6669-cc31-47aa-8bea-fec282246140","kind":"event","nativeEvent":"UserPromptSubmit","pid":3858309,"recordedAt":"2026-09-03T08:26:09.589Z","runtime":"shared-runtime","sequence":2},{"event":"tool/before","host":"codex","ids":{"session_id":"01a06660-110e-7290-8d1c-8ef1b2b68fc2","tool_use_id":"exec-95e92c51-9373-4a8e-9cc1-5f2bf32efee1","transcript_path":"/tmp/host-test/codex-home/.codex/sessions/2026/09/03/rollout-2026-09-03T08-26-06-01a06660-110e-7290-8d1c-8ef1b2b68fc2.jsonl","turn_id":"01a06660-1179-7bd2-bb02-d4cac726b2a0","model":"gpt-5.6-sol","cwd":"/tmp/host-test/codex-workspace","hook_event_name":"PreToolUse"},"index":3,"invocation":"a07845ee-f3fe-44c6-8db5-1e4e782dd79d","kind":"event","nativeEvent":"PreToolUse","pid":3858309,"recordedAt":"2026-09-03T08:26:13.339Z","runtime":"shared-runtime","sequence":3},{"event":"tool/after","host":"codex","ids":{"session_id":"01a06660-110e-7290-8d1c-8ef1b2b68fc2","tool_use_id":"exec-95e92c51-9373-4a8e-9cc1-5f2bf32efee1","transcript_path":"/tmp/host-test/codex-home/.codex/sessions/2026/09/03/rollout-2026-09-03T08-26-06-01a06660-110e-7290-8d1c-8ef1b2b68fc2.jsonl","turn_id":"01a06660-1179-7bd2-bb02-d4cac726b2a0","model":"gpt-5.6-sol","cwd":"/tmp/host-test/codex-workspace","hook_event_name":"PostToolUse"},"index":4,"invocation":"b80dfe2c-4eb9-48cc-bf6d-b6aedfab03e5","kind":"event","nativeEvent":"PostToolUse","pid":3858309,"recordedAt":"2026-09-03T08:26:13.597Z","runtime":"shared-runtime","sequence":4},{"event":"tool/before","host":"codex","ids":{"session_id":"01a06660-110e-7290-8d1c-8ef1b2b68fc2","tool_use_id":"exec-c5f2c1db-06f5-4694-ade7-af24014725e5","transcript_path":"/tmp/host-test/codex-home/.codex/sessions/2026/09/03/rollout-2026-09-03T08-26-06-01a06660-110e-7290-8d1c-8ef1b2b68fc2.jsonl","turn_id":"01a06660-1179-7bd2-bb02-d4cac726b2a0","model":"gpt-5.6-sol","cwd":"/tmp/host-test/codex-workspace","hook_event_name":"PreToolUse"},"index":5,"invocation":"be84ef2a-b274-45d9-ae27-2003011c3b0b","kind":"event","nativeEvent":"PreToolUse","pid":3858309,"recordedAt":"2026-09-03T08:26:17.758Z","runtime":"shared-runtime","sequence":5},{"event":"tool/after","host":"codex","ids":{"session_id":"01a06660-110e-7290-8d1c-8ef1b2b68fc2","tool_use_id":"exec-c5f2c1db-06f5-4694-ade7-af24014725e5","transcript_path":"/tmp/host-test/codex-home/.codex/sessions/2026/09/03/rollout-2026-09-03T08-26-06-01a06660-110e-7290-8d1c-8ef1b2b68fc2.jsonl","turn_id":"01a06660-1179-7bd2-bb02-d4cac726b2a0","model":"gpt-5.6-sol","cwd":"/tmp/host-test/codex-workspace","hook_event_name":"PostToolUse"},"index":6,"invocation":"b2ab7a72-0d5a-4f00-819d-3e6bd851e781","kind":"event","nativeEvent":"PostToolUse","pid":3858309,"recordedAt":"2026-09-03T08:26:18.025Z","runtime":"shared-runtime","sequence":6},{"event":"tool/before","host":"codex","ids":{"session_id":"01a06660-110e-7290-8d1c-8ef1b2b68fc2","tool_use_id":"exec-ef038ff6-41f4-47e9-b808-69cc9de68031","transcript_path":"/tmp/host-test/codex-home/.codex/sessions/2026/09/03/rollout-2026-09-03T08-26-06-01a06660-110e-7290-8d1c-8ef1b2b68fc2.jsonl","turn_id":"01a06660-1179-7bd2-bb02-d4cac726b2a0","model":"gpt-5.6-sol","cwd":"/tmp/host-test/codex-workspace","hook_event_name":"PreToolUse"},"index":7,"invocation":"069d634a-c254-4f80-b759-c3d965dce4ce","kind":"event","nativeEvent":"PreToolUse","pid":3858309,"recordedAt":"2026-09-03T08:26:21.553Z","runtime":"shared-runtime","sequence":7},{"event":"tool/after","host":"codex","ids":{"session_id":"01a06660-110e-7290-8d1c-8ef1b2b68fc2","tool_use_id":"exec-ef038ff6-41f4-47e9-b808-69cc9de68031","transcript_path":"/tmp/host-test/codex-home/.codex/sessions/2026/09/03/rollout-2026-09-03T08-26-06-01a06660-110e-7290-8d1c-8ef1b2b68fc2.jsonl","turn_id":"01a06660-1179-7bd2-bb02-d4cac726b2a0","model":"gpt-5.6-sol","cwd":"/tmp/host-test/codex-workspace","hook_event_name":"PostToolUse"},"index":8,"invocation":"473dc135-d21e-4e25-a1ac-3611e8a94e75","kind":"event","nativeEvent":"PostToolUse","pid":3858309,"recordedAt":"2026-09-03T08:26:21.870Z","runtime":"shared-runtime","sequence":8},{"event":"tool/before","host":"codex","ids":{"session_id":"01a06660-110e-7290-8d1c-8ef1b2b68fc2","tool_use_id":"exec-0a6138e5-b465-4dad-85c2-6c32efa77537","transcript_path":"/tmp/host-test/codex-home/.codex/sessions/2026/09/03/rollout-2026-09-03T08-26-06-01a06660-110e-7290-8d1c-8ef1b2b68fc2.jsonl","turn_id":"01a06660-1179-7bd2-bb02-d4cac726b2a0","model":"gpt-5.6-sol","cwd":"/tmp/host-test/codex-workspace","hook_event_name":"PreToolUse"},"index":9,"invocation":"a9621e00-10cd-471e-b1a5-4a0cee82e76d","kind":"event","nativeEvent":"PreToolUse","pid":3858309,"recordedAt":"2026-09-03T08:26:30.180Z","runtime":"shared-runtime","sequence":9},{"event":"mcp:dump","host":"codex-mcp-client","ids":{},"index":10,"invocation":"183a74e8-89a8-4e22-815c-0009dbaffbd4","kind":"mcp","observed":{"tool":"dump"},"pid":3858309,"recordedAt":"2026-09-03T08:26:30.205Z","runtime":"mcp-server","sequence":10}],"state":{"revision":10,"state":"available","summarized":10,"total":10},"total":10}},"tool_use_id":"exec-0a6138e5-b465-4dad-85c2-6c32efa77537"}},"host":"codex","kind":"event","process":{"cwd":"/tmp/host-test/codex-home/.codex/plugins/cache/host-test-marketplace/host-test/1.0.0","entry":"/tmp/host-test/codex-home/.codex/plugins/cache/host-test-marketplace/host-test/1.0.0/mcp/mcp-host-test-0d229f1b-flight.mjs","pid":3858309,"ppid":3857224},"recordedAt":"2026-09-03T08:26:30.343Z","request":{"host":{"source":"native","state":"available","value":{"name":"codex"}},"invocation":{"kind":"event"},"session":{"source":"native","state":"available","value":{"sessionId":"01a06660-110e-7290-8d1c-8ef1b2b68fc2"}}},"runtime":"shared-runtime","sequence":11} +{"event":{"canonical":{"event":"tool/before","idempotencyKey":"04e396435f2e832dcacb8062b48e982dd4280127bb912a65a39b4987d6e03f97","observedAt":"2026-09-03T08:26:34.407Z","provenance":{"host":"codex","hostContractRevision":"0.147.0","nativeEvent":"PreToolUse","source":"native"},"sequence":11},"native":{"session_id":"01a06660-110e-7290-8d1c-8ef1b2b68fc2","turn_id":"01a06660-1179-7bd2-bb02-d4cac726b2a0","transcript_path":"/tmp/host-test/codex-home/.codex/sessions/2026/09/03/rollout-2026-09-03T08-26-06-01a06660-110e-7290-8d1c-8ef1b2b68fc2.jsonl","cwd":"/tmp/host-test/codex-workspace","hook_event_name":"PreToolUse","model":"gpt-5.6-sol","permission_mode":"bypassPermissions","tool_name":"mcp__host_test_raw__probe","tool_input":{"note":"root"},"tool_use_id":"exec-4d65c735-17c4-4e57-809b-e2512e0722af"}},"host":"codex","kind":"event","process":{"cwd":"/tmp/host-test/codex-home/.codex/plugins/cache/host-test-marketplace/host-test/1.0.0","entry":"/tmp/host-test/codex-home/.codex/plugins/cache/host-test-marketplace/host-test/1.0.0/mcp/mcp-host-test-0d229f1b-flight.mjs","pid":3858309,"ppid":3857224},"recordedAt":"2026-09-03T08:26:34.410Z","request":{"host":{"source":"native","state":"available","value":{"name":"codex"}},"invocation":{"kind":"event"},"session":{"source":"native","state":"available","value":{"sessionId":"01a06660-110e-7290-8d1c-8ef1b2b68fc2"}}},"runtime":"shared-runtime","sequence":12} +{"host":"codex-mcp-client","kind":"mcp","observed":{"client":{"name":"codex-mcp-client","title":"Codex","version":"0.147.0"},"clientCapabilities":{"elicitation":{"form":{},"url":{}}},"env":{"names":["AGENT_BUNDLE_PLUGIN_ROOT"]},"http":null,"mcpReq":{"_meta":{"progressToken":1,"x-codex-turn-metadata":{"session_id":"01a06660-110e-7290-8d1c-8ef1b2b68fc2","thread_id":"01a06660-110e-7290-8d1c-8ef1b2b68fc2","turn_id":"01a06660-1179-7bd2-bb02-d4cac726b2a0","thread_source":"user","sandbox":"seccomp","workspaces":{"/tmp/host-test/codex-workspace":{"latest_git_commit_hash":"840e5bd01b2601e82ed34c286c17597b29959a50","has_changes":false}},"turn_started_at_unix_ms":1788423967117,"model":"gpt-5.6-sol","reasoning_effort":"low"},"plugin_id":"host-test@host-test-marketplace","threadId":"01a06660-110e-7290-8d1c-8ef1b2b68fc2"},"envelope":null,"id":2,"method":"tools/call"},"note":"root","sessionId":null,"tool":"probe"},"process":{"cwd":"/tmp/host-test/codex-home/.codex/plugins/cache/host-test-marketplace/host-test/1.0.0","entry":"/tmp/host-test/codex-home/.codex/plugins/cache/host-test-marketplace/host-test/1.0.0/mcp/mcp-host-test-raw-6e9c1a1c.mjs","pid":3858311,"ppid":3857224},"recordedAt":"2026-09-03T08:26:34.434Z","request":{"unavailable":"hand-rolled stdio server: no framework request context is mounted"},"runtime":"mcp-server","sequence":1} +{"event":{"canonical":{"event":"tool/after","idempotencyKey":"eda74ab0baaba6939fd226fa21e6d453a9fab439d28cd18089a0f791184b43e7","observedAt":"2026-09-03T08:26:34.555Z","provenance":{"host":"codex","hostContractRevision":"0.147.0","nativeEvent":"PostToolUse","source":"native"},"sequence":12},"native":{"session_id":"01a06660-110e-7290-8d1c-8ef1b2b68fc2","turn_id":"01a06660-1179-7bd2-bb02-d4cac726b2a0","transcript_path":"/tmp/host-test/codex-home/.codex/sessions/2026/09/03/rollout-2026-09-03T08-26-06-01a06660-110e-7290-8d1c-8ef1b2b68fc2.jsonl","cwd":"/tmp/host-test/codex-workspace","hook_event_name":"PostToolUse","model":"gpt-5.6-sol","permission_mode":"bypassPermissions","tool_name":"mcp__host_test_raw__probe","tool_input":{"note":"root"},"tool_response":{"content":[{"type":"text","text":"{\n \"log\": \"/tmp/host-test/codex-home/.codex/plugins/cache/host-test-marketplace/host-test/1.0.0/state/host-test/captures.ndjson\",\n \"observed\": {\n \"client\": {\n \"name\": \"codex-mcp-client\",\n \"title\": \"Codex\",\n \"version\": \"0.147.0\"\n },\n \"clientCapabilities\": {\n \"elicitation\": {\n \"form\": {},\n \"url\": {}\n }\n },\n \"env\": {\n \"names\": [\n \"AG…[+1045 chars]"}],"structuredContent":{"log":"/tmp/host-test/codex-home/.codex/plugins/cache/host-test-marketplace/host-test/1.0.0/state/host-test/captures.ndjson","observed":{"client":{"name":"codex-mcp-client","title":"Codex","version":"0.147.0"},"clientCapabilities":{"elicitation":{"form":{},"url":{}}},"env":{"names":["AGENT_BUNDLE_PLUGIN_ROOT"]},"http":null,"mcpReq":{"_meta":{"progressToken":1,"x-codex-turn-metadata":{"session_id":"01a06660-110e-7290-8d1c-8ef1b2b68fc2","thread_id":"01a06660-110e-7290-8d1c-8ef1b2b68fc2","turn_id":"01a06660-1179-7bd2-bb02-d4cac726b2a0","thread_source":"user","sandbox":"seccomp","workspaces":{"/tmp/host-test/codex-workspace":{"latest_git_commit_hash":"840e5bd01b2601e82ed34c286c17597b29959a50","has_changes":false}},"turn_started_at_unix_ms":1788423967117,"model":"gpt-5.6-sol","reasoning_effort":"low"},"plugin_id":"host-test@host-test-marketplace","threadId":"01a06660-110e-7290-8d1c-8ef1b2b68fc2"},"envelope":null,"id":2,"method":"tools/call"},"note":"root","sessionId":null,"tool":"probe"},"sequence":1}},"tool_use_id":"exec-4d65c735-17c4-4e57-809b-e2512e0722af"}},"host":"codex","kind":"event","process":{"cwd":"/tmp/host-test/codex-home/.codex/plugins/cache/host-test-marketplace/host-test/1.0.0","entry":"/tmp/host-test/codex-home/.codex/plugins/cache/host-test-marketplace/host-test/1.0.0/mcp/mcp-host-test-0d229f1b-flight.mjs","pid":3858309,"ppid":3857224},"recordedAt":"2026-09-03T08:26:34.557Z","request":{"host":{"source":"native","state":"available","value":{"name":"codex"}},"invocation":{"kind":"event"},"session":{"source":"native","state":"available","value":{"sessionId":"01a06660-110e-7290-8d1c-8ef1b2b68fc2"}}},"runtime":"shared-runtime","sequence":13} +{"event":{"canonical":{"event":"tool/before","idempotencyKey":"d5e06f7e0dbc9abdd4d2f7c0a088ee1d8977f1934aed9dddf1cf228f55d63e19","observedAt":"2026-09-03T08:26:39.381Z","provenance":{"host":"codex","hostContractRevision":"0.147.0","nativeEvent":"PreToolUse","source":"native"},"sequence":13},"native":{"session_id":"01a06660-110e-7290-8d1c-8ef1b2b68fc2","turn_id":"01a06660-1179-7bd2-bb02-d4cac726b2a0","transcript_path":"/tmp/host-test/codex-home/.codex/sessions/2026/09/03/rollout-2026-09-03T08-26-06-01a06660-110e-7290-8d1c-8ef1b2b68fc2.jsonl","cwd":"/tmp/host-test/codex-workspace","hook_event_name":"PreToolUse","model":"gpt-5.6-sol","permission_mode":"bypassPermissions","tool_name":"collaborationspawn_agent","tool_input":{"task_name":"host_probe","fork_turns":"all","message":"gAAAAABqmS8_g19TGnhuKaT5LDXvLNvDv6L8__mOPflsORszsGWPDP-oX6n3LT-sXjY3sZYySt8eCZNmPgontuZQTdtYSm15-hhLddgG_rkTTiswdW24I_GxnaSWsaqtJiG7F1fbmODfoOQiELTKl-qgovqFLmkFcNjQMg-d5cp5mCZV33VXmA3CqYTwTGZPn0OZSiAZCtyxkb3Tcz7w1-yfagfSIwQKfZFzcrH0xQyNVrtKFX4q-WZdQvKiM4Xg9fmHyAN5C2TPTJXTaEfW7xnpMp9crtvCdFfMi1ujSSCQ8X0VOrgV627SMdC84lTAL15t9sdn4AT2YeJH3vC6DeiHdiviSluNfT-MB4eiayqaDijwUnbGqS6NSs0qQcvZ9kbIHIa5xtbFMJ1i…[+124 chars]"},"tool_use_id":"call_3koNvBFvpKYdTIqLb1xDOjSX"}},"host":"codex","kind":"event","process":{"cwd":"/tmp/host-test/codex-home/.codex/plugins/cache/host-test-marketplace/host-test/1.0.0","entry":"/tmp/host-test/codex-home/.codex/plugins/cache/host-test-marketplace/host-test/1.0.0/mcp/mcp-host-test-0d229f1b-flight.mjs","pid":3858309,"ppid":3857224},"recordedAt":"2026-09-03T08:26:39.383Z","request":{"host":{"source":"native","state":"available","value":{"name":"codex"}},"invocation":{"kind":"event"},"session":{"source":"native","state":"available","value":{"sessionId":"01a06660-110e-7290-8d1c-8ef1b2b68fc2"}}},"runtime":"shared-runtime","sequence":14} +{"event":{"canonical":{"event":"tool/after","idempotencyKey":"2c7dd33f5d1a3fdbfe530141a7adaa2702d103853358db7a7723f772900d3101","observedAt":"2026-09-03T08:26:39.627Z","provenance":{"host":"codex","hostContractRevision":"0.147.0","nativeEvent":"PostToolUse","source":"native"},"sequence":14},"native":{"session_id":"01a06660-110e-7290-8d1c-8ef1b2b68fc2","turn_id":"01a06660-1179-7bd2-bb02-d4cac726b2a0","transcript_path":"/tmp/host-test/codex-home/.codex/sessions/2026/09/03/rollout-2026-09-03T08-26-06-01a06660-110e-7290-8d1c-8ef1b2b68fc2.jsonl","cwd":"/tmp/host-test/codex-workspace","hook_event_name":"PostToolUse","model":"gpt-5.6-sol","permission_mode":"bypassPermissions","tool_name":"collaborationspawn_agent","tool_input":{"task_name":"host_probe","fork_turns":"all","message":"gAAAAABqmS8_g19TGnhuKaT5LDXvLNvDv6L8__mOPflsORszsGWPDP-oX6n3LT-sXjY3sZYySt8eCZNmPgontuZQTdtYSm15-hhLddgG_rkTTiswdW24I_GxnaSWsaqtJiG7F1fbmODfoOQiELTKl-qgovqFLmkFcNjQMg-d5cp5mCZV33VXmA3CqYTwTGZPn0OZSiAZCtyxkb3Tcz7w1-yfagfSIwQKfZFzcrH0xQyNVrtKFX4q-WZdQvKiM4Xg9fmHyAN5C2TPTJXTaEfW7xnpMp9crtvCdFfMi1ujSSCQ8X0VOrgV627SMdC84lTAL15t9sdn4AT2YeJH3vC6DeiHdiviSluNfT-MB4eiayqaDijwUnbGqS6NSs0qQcvZ9kbIHIa5xtbFMJ1i…[+124 chars]"},"tool_response":"{\"task_name\":\"/root/host_probe\"}","tool_use_id":"call_3koNvBFvpKYdTIqLb1xDOjSX"}},"host":"codex","kind":"event","process":{"cwd":"/tmp/host-test/codex-home/.codex/plugins/cache/host-test-marketplace/host-test/1.0.0","entry":"/tmp/host-test/codex-home/.codex/plugins/cache/host-test-marketplace/host-test/1.0.0/mcp/mcp-host-test-0d229f1b-flight.mjs","pid":3858309,"ppid":3857224},"recordedAt":"2026-09-03T08:26:39.630Z","request":{"host":{"source":"native","state":"available","value":{"name":"codex"}},"invocation":{"kind":"event"},"session":{"source":"native","state":"available","value":{"sessionId":"01a06660-110e-7290-8d1c-8ef1b2b68fc2"}}},"runtime":"shared-runtime","sequence":15} +{"event":{"canonical":{"event":"agent/start","idempotencyKey":"78c26879ca28b706235959ef92f7cbf48a1e92352efbccd613cc255b7f604663","observedAt":"2026-09-03T08:26:41.031Z","provenance":{"host":"codex","hostContractRevision":"0.147.0","nativeEvent":"SubagentStart","source":"native"},"sequence":15},"native":{"session_id":"01a06660-110e-7290-8d1c-8ef1b2b68fc2","turn_id":"01a06660-901a-77f1-a660-ac3c549409c0","transcript_path":"/tmp/host-test/codex-home/.codex/sessions/2026/09/03/rollout-2026-09-03T08-26-39-01a06660-8faf-7122-80af-24ba2da81ad7.jsonl","cwd":"/tmp/host-test/codex-workspace","hook_event_name":"SubagentStart","model":"gpt-5.6-sol","permission_mode":"bypassPermissions","agent_id":"01a06660-8faf-7122-80af-24ba2da81ad7","agent_type":"default"}},"host":"codex","kind":"event","process":{"cwd":"/tmp/host-test/codex-home/.codex/plugins/cache/host-test-marketplace/host-test/1.0.0","entry":"/tmp/host-test/codex-home/.codex/plugins/cache/host-test-marketplace/host-test/1.0.0/mcp/mcp-host-test-0d229f1b-flight.mjs","pid":3858309,"ppid":3857224},"recordedAt":"2026-09-03T08:26:41.035Z","request":{"host":{"source":"native","state":"available","value":{"name":"codex"}},"invocation":{"kind":"event"},"session":{"source":"native","state":"available","value":{"sessionId":"01a06660-110e-7290-8d1c-8ef1b2b68fc2"}}},"runtime":"shared-runtime","sequence":16} +{"event":{"canonical":{"event":"tool/before","idempotencyKey":"0691cad187cf66ea2a958f024c6097f5250ebe6ce8519bcfce3ef65ef448a1f4","observedAt":"2026-09-03T08:26:43.122Z","provenance":{"host":"codex","hostContractRevision":"0.147.0","nativeEvent":"PreToolUse","source":"native"},"sequence":16},"native":{"session_id":"01a06660-110e-7290-8d1c-8ef1b2b68fc2","turn_id":"01a06660-1179-7bd2-bb02-d4cac726b2a0","transcript_path":"/tmp/host-test/codex-home/.codex/sessions/2026/09/03/rollout-2026-09-03T08-26-06-01a06660-110e-7290-8d1c-8ef1b2b68fc2.jsonl","cwd":"/tmp/host-test/codex-workspace","hook_event_name":"PreToolUse","model":"gpt-5.6-sol","permission_mode":"bypassPermissions","tool_name":"collaborationwait_agent","tool_input":{"timeout_ms":3600000},"tool_use_id":"call_sWiia6GTw0YUCkOdk5dtZZ2d"}},"host":"codex","kind":"event","process":{"cwd":"/tmp/host-test/codex-home/.codex/plugins/cache/host-test-marketplace/host-test/1.0.0","entry":"/tmp/host-test/codex-home/.codex/plugins/cache/host-test-marketplace/host-test/1.0.0/mcp/mcp-host-test-0d229f1b-flight.mjs","pid":3858309,"ppid":3857224},"recordedAt":"2026-09-03T08:26:43.125Z","request":{"host":{"source":"native","state":"available","value":{"name":"codex"}},"invocation":{"kind":"event"},"session":{"source":"native","state":"available","value":{"sessionId":"01a06660-110e-7290-8d1c-8ef1b2b68fc2"}}},"runtime":"shared-runtime","sequence":17} +{"event":{"canonical":{"event":"tool/before","idempotencyKey":"1b4f45e6b509b3b4bc13070aeb35010be1f23331fabc1045db408885dd4ba4ea","observedAt":"2026-09-03T08:26:44.715Z","provenance":{"host":"codex","hostContractRevision":"0.147.0","nativeEvent":"PreToolUse","source":"native"},"sequence":17},"native":{"session_id":"01a06660-110e-7290-8d1c-8ef1b2b68fc2","turn_id":"01a06660-901a-77f1-a660-ac3c549409c0","agent_id":"01a06660-8faf-7122-80af-24ba2da81ad7","agent_type":"default","transcript_path":"/tmp/host-test/codex-home/.codex/sessions/2026/09/03/rollout-2026-09-03T08-26-39-01a06660-8faf-7122-80af-24ba2da81ad7.jsonl","cwd":"/tmp/host-test/codex-workspace","hook_event_name":"PreToolUse","model":"gpt-5.6-sol","permission_mode":"bypassPermissions","tool_name":"Bash","tool_input":{"command":"sed -n '1,240p' /tmp/host-test/codex-home/.codex/plugins/cache/host-test-marketplace/host-test/1.0.0/skills/host-test/SKILL.md"},"tool_use_id":"exec-e30d430f-1276-4ebf-8074-d39a832daa2c"}},"host":"codex","kind":"event","process":{"cwd":"/tmp/host-test/codex-home/.codex/plugins/cache/host-test-marketplace/host-test/1.0.0","entry":"/tmp/host-test/codex-home/.codex/plugins/cache/host-test-marketplace/host-test/1.0.0/mcp/mcp-host-test-0d229f1b-flight.mjs","pid":3858309,"ppid":3857224},"recordedAt":"2026-09-03T08:26:44.717Z","request":{"host":{"source":"native","state":"available","value":{"name":"codex"}},"invocation":{"kind":"event"},"session":{"source":"native","state":"available","value":{"sessionId":"01a06660-110e-7290-8d1c-8ef1b2b68fc2"}}},"runtime":"shared-runtime","sequence":18} +{"event":{"canonical":{"event":"tool/after","idempotencyKey":"422a078037175d19b9578804c15f73dddc52ee907c4ebb13613bbe386e3b218b","observedAt":"2026-09-03T08:26:44.917Z","provenance":{"host":"codex","hostContractRevision":"0.147.0","nativeEvent":"PostToolUse","source":"native"},"sequence":18},"native":{"session_id":"01a06660-110e-7290-8d1c-8ef1b2b68fc2","turn_id":"01a06660-901a-77f1-a660-ac3c549409c0","agent_id":"01a06660-8faf-7122-80af-24ba2da81ad7","agent_type":"default","transcript_path":"/tmp/host-test/codex-home/.codex/sessions/2026/09/03/rollout-2026-09-03T08-26-39-01a06660-8faf-7122-80af-24ba2da81ad7.jsonl","cwd":"/tmp/host-test/codex-workspace","hook_event_name":"PostToolUse","model":"gpt-5.6-sol","permission_mode":"bypassPermissions","tool_name":"Bash","tool_input":{"command":"sed -n '1,240p' /tmp/host-test/codex-home/.codex/plugins/cache/host-test-marketplace/host-test/1.0.0/skills/host-test/SKILL.md"},"tool_response":"---\nname: host-test\ndescription: Probe what this host sends to plugin hooks and MCP servers. Use when asked to run the host-test probe, dump host lineage, or check which conversation, session, or subagent ids a hook or MCP call carries.\n---\n\n# Host test probe\n\nThis plugin records every hook event the host dispatches to it, plus every\ncall to its own MCP servers, into one NDJSON log and a durable s…[+1064 chars]","tool_use_id":"exec-e30d430f-1276-4ebf-8074-d39a832daa2c"}},"host":"codex","kind":"event","process":{"cwd":"/tmp/host-test/codex-home/.codex/plugins/cache/host-test-marketplace/host-test/1.0.0","entry":"/tmp/host-test/codex-home/.codex/plugins/cache/host-test-marketplace/host-test/1.0.0/mcp/mcp-host-test-0d229f1b-flight.mjs","pid":3858309,"ppid":3857224},"recordedAt":"2026-09-03T08:26:44.919Z","request":{"host":{"source":"native","state":"available","value":{"name":"codex"}},"invocation":{"kind":"event"},"session":{"source":"native","state":"available","value":{"sessionId":"01a06660-110e-7290-8d1c-8ef1b2b68fc2"}}},"runtime":"shared-runtime","sequence":19} +{"event":{"canonical":{"event":"tool/before","idempotencyKey":"2162cfeb8e17d9fd600a9b63de1b5900764b8c15c332b495ac1d3aef25e98b2b","observedAt":"2026-09-03T08:26:57.604Z","provenance":{"host":"codex","hostContractRevision":"0.147.0","nativeEvent":"PreToolUse","source":"native"},"sequence":19},"native":{"session_id":"01a06660-110e-7290-8d1c-8ef1b2b68fc2","turn_id":"01a06660-901a-77f1-a660-ac3c549409c0","agent_id":"01a06660-8faf-7122-80af-24ba2da81ad7","agent_type":"default","transcript_path":"/tmp/host-test/codex-home/.codex/sessions/2026/09/03/rollout-2026-09-03T08-26-39-01a06660-8faf-7122-80af-24ba2da81ad7.jsonl","cwd":"/tmp/host-test/codex-workspace","hook_event_name":"PreToolUse","model":"gpt-5.6-sol","permission_mode":"bypassPermissions","tool_name":"Bash","tool_input":{"command":"pwd"},"tool_use_id":"exec-4463842b-359f-4d0e-8ec2-bb4d4bbd4189"}},"host":"codex","kind":"event","process":{"cwd":"/tmp/host-test/codex-home/.codex/plugins/cache/host-test-marketplace/host-test/1.0.0","entry":"/tmp/host-test/codex-home/.codex/plugins/cache/host-test-marketplace/host-test/1.0.0/mcp/mcp-host-test-0d229f1b-flight.mjs","pid":3858309,"ppid":3857224},"recordedAt":"2026-09-03T08:26:57.607Z","request":{"host":{"source":"native","state":"available","value":{"name":"codex"}},"invocation":{"kind":"event"},"session":{"source":"native","state":"available","value":{"sessionId":"01a06660-110e-7290-8d1c-8ef1b2b68fc2"}}},"runtime":"shared-runtime","sequence":20} +{"event":{"canonical":{"event":"tool/after","idempotencyKey":"e53d6639b21e81bfe8d112785d700c28d0491e6d1f6577609020c9b39c4806ac","observedAt":"2026-09-03T08:26:57.877Z","provenance":{"host":"codex","hostContractRevision":"0.147.0","nativeEvent":"PostToolUse","source":"native"},"sequence":20},"native":{"session_id":"01a06660-110e-7290-8d1c-8ef1b2b68fc2","turn_id":"01a06660-901a-77f1-a660-ac3c549409c0","agent_id":"01a06660-8faf-7122-80af-24ba2da81ad7","agent_type":"default","transcript_path":"/tmp/host-test/codex-home/.codex/sessions/2026/09/03/rollout-2026-09-03T08-26-39-01a06660-8faf-7122-80af-24ba2da81ad7.jsonl","cwd":"/tmp/host-test/codex-workspace","hook_event_name":"PostToolUse","model":"gpt-5.6-sol","permission_mode":"bypassPermissions","tool_name":"Bash","tool_input":{"command":"pwd"},"tool_response":"/tmp/host-test/codex-workspace\n","tool_use_id":"exec-4463842b-359f-4d0e-8ec2-bb4d4bbd4189"}},"host":"codex","kind":"event","process":{"cwd":"/tmp/host-test/codex-home/.codex/plugins/cache/host-test-marketplace/host-test/1.0.0","entry":"/tmp/host-test/codex-home/.codex/plugins/cache/host-test-marketplace/host-test/1.0.0/mcp/mcp-host-test-0d229f1b-flight.mjs","pid":3858309,"ppid":3857224},"recordedAt":"2026-09-03T08:26:57.880Z","request":{"host":{"source":"native","state":"available","value":{"name":"codex"}},"invocation":{"kind":"event"},"session":{"source":"native","state":"available","value":{"sessionId":"01a06660-110e-7290-8d1c-8ef1b2b68fc2"}}},"runtime":"shared-runtime","sequence":21} +{"event":{"canonical":{"event":"tool/before","idempotencyKey":"135e5f5586fa9345d304349bcceb9de092be96c6ab40d94aa57c0db9343d290d","observedAt":"2026-09-03T08:27:07.771Z","provenance":{"host":"codex","hostContractRevision":"0.147.0","nativeEvent":"PreToolUse","source":"native"},"sequence":21},"native":{"session_id":"01a06660-110e-7290-8d1c-8ef1b2b68fc2","turn_id":"01a06660-901a-77f1-a660-ac3c549409c0","agent_id":"01a06660-8faf-7122-80af-24ba2da81ad7","agent_type":"default","transcript_path":"/tmp/host-test/codex-home/.codex/sessions/2026/09/03/rollout-2026-09-03T08-26-39-01a06660-8faf-7122-80af-24ba2da81ad7.jsonl","cwd":"/tmp/host-test/codex-workspace","hook_event_name":"PreToolUse","model":"gpt-5.6-sol","permission_mode":"bypassPermissions","tool_name":"mcp__host_test_raw__probe","tool_input":{"note":"subagent"},"tool_use_id":"exec-0838fda4-077b-4926-aeca-c47fc66e987a"}},"host":"codex","kind":"event","process":{"cwd":"/tmp/host-test/codex-home/.codex/plugins/cache/host-test-marketplace/host-test/1.0.0","entry":"/tmp/host-test/codex-home/.codex/plugins/cache/host-test-marketplace/host-test/1.0.0/mcp/mcp-host-test-0d229f1b-flight.mjs","pid":3858309,"ppid":3857224},"recordedAt":"2026-09-03T08:27:07.774Z","request":{"host":{"source":"native","state":"available","value":{"name":"codex"}},"invocation":{"kind":"event"},"session":{"source":"native","state":"available","value":{"sessionId":"01a06660-110e-7290-8d1c-8ef1b2b68fc2"}}},"runtime":"shared-runtime","sequence":22} +{"host":"codex-mcp-client","kind":"mcp","observed":{"client":{"name":"codex-mcp-client","title":"Codex","version":"0.147.0"},"clientCapabilities":{"elicitation":{"form":{},"url":{}}},"env":{"names":["AGENT_BUNDLE_PLUGIN_ROOT"]},"http":null,"mcpReq":{"_meta":{"progressToken":1,"x-codex-turn-metadata":{"session_id":"01a06660-110e-7290-8d1c-8ef1b2b68fc2","thread_id":"01a06660-8faf-7122-80af-24ba2da81ad7","turn_id":"01a06660-901a-77f1-a660-ac3c549409c0","forked_from_thread_id":"01a06660-110e-7290-8d1c-8ef1b2b68fc2","parent_thread_id":"01a06660-110e-7290-8d1c-8ef1b2b68fc2","turn_started_at_unix_ms":1788423999528,"subagent_kind":"thread_spawn","thread_source":"subagent","sandbox":"seccomp","workspaces":{"/tmp/host-test/codex-workspace":{"latest_git_commit_hash":"840e5bd01b2601e82ed34c286c17597b29959a50","has_changes":true}},"model":"gpt-5.6-sol","reasoning_effort":"low"},"plugin_id":"host-test@host-test-marketplace","threadId":"01a06660-8faf-7122-80af-24ba2da81ad7"},"envelope":null,"id":2,"method":"tools/call"},"note":"subagent","sessionId":null,"tool":"probe"},"process":{"cwd":"/tmp/host-test/codex-home/.codex/plugins/cache/host-test-marketplace/host-test/1.0.0","entry":"/tmp/host-test/codex-home/.codex/plugins/cache/host-test-marketplace/host-test/1.0.0/mcp/mcp-host-test-raw-6e9c1a1c.mjs","pid":3875797,"ppid":3857224},"recordedAt":"2026-09-03T08:27:07.802Z","request":{"unavailable":"hand-rolled stdio server: no framework request context is mounted"},"runtime":"mcp-server","sequence":1} +{"event":{"canonical":{"event":"tool/after","idempotencyKey":"63d353a89942a79366e73af377bf5a689b8021931cdea846d88a6014e8462ba0","observedAt":"2026-09-03T08:27:07.924Z","provenance":{"host":"codex","hostContractRevision":"0.147.0","nativeEvent":"PostToolUse","source":"native"},"sequence":22},"native":{"session_id":"01a06660-110e-7290-8d1c-8ef1b2b68fc2","turn_id":"01a06660-901a-77f1-a660-ac3c549409c0","agent_id":"01a06660-8faf-7122-80af-24ba2da81ad7","agent_type":"default","transcript_path":"/tmp/host-test/codex-home/.codex/sessions/2026/09/03/rollout-2026-09-03T08-26-39-01a06660-8faf-7122-80af-24ba2da81ad7.jsonl","cwd":"/tmp/host-test/codex-workspace","hook_event_name":"PostToolUse","model":"gpt-5.6-sol","permission_mode":"bypassPermissions","tool_name":"mcp__host_test_raw__probe","tool_input":{"note":"subagent"},"tool_response":{"content":[{"type":"text","text":"{\n \"log\": \"/tmp/host-test/codex-home/.codex/plugins/cache/host-test-marketplace/host-test/1.0.0/state/host-test/captures.ndjson\",\n \"observed\": {\n \"client\": {\n \"name\": \"codex-mcp-client\",\n \"title\": \"Codex\",\n \"version\": \"0.147.0\"\n },\n \"clientCapabilities\": {\n \"elicitation\": {\n \"form\": {},\n \"url\": {}\n }\n },\n \"env\": {\n \"names\": [\n \"AG…[+1240 chars]"}],"structuredContent":{"log":"/tmp/host-test/codex-home/.codex/plugins/cache/host-test-marketplace/host-test/1.0.0/state/host-test/captures.ndjson","observed":{"client":{"name":"codex-mcp-client","title":"Codex","version":"0.147.0"},"clientCapabilities":{"elicitation":{"form":{},"url":{}}},"env":{"names":["AGENT_BUNDLE_PLUGIN_ROOT"]},"http":null,"mcpReq":{"_meta":{"progressToken":1,"x-codex-turn-metadata":{"session_id":"01a06660-110e-7290-8d1c-8ef1b2b68fc2","thread_id":"01a06660-8faf-7122-80af-24ba2da81ad7","turn_id":"01a06660-901a-77f1-a660-ac3c549409c0","forked_from_thread_id":"01a06660-110e-7290-8d1c-8ef1b2b68fc2","parent_thread_id":"01a06660-110e-7290-8d1c-8ef1b2b68fc2","turn_started_at_unix_ms":1788423999528,"subagent_kind":"thread_spawn","thread_source":"subagent","sandbox":"seccomp","workspaces":{"/tmp/host-test/codex-workspace":{"latest_git_commit_hash":"840e5bd01b2601e82ed34c286c17597b29959a50","has_changes":true}},"model":"gpt-5.6-sol","reasoning_effort":"low"},"plugin_id":"host-test@host-test-marketplace","threadId":"01a06660-8faf-7122-80af-24ba2da81ad7"},"envelope":null,"id":2,"method":"tools/call"},"note":"subagent","sessionId":null,"tool":"probe"},"sequence":1}},"tool_use_id":"exec-0838fda4-077b-4926-aeca-c47fc66e987a"}},"host":"codex","kind":"event","process":{"cwd":"/tmp/host-test/codex-home/.codex/plugins/cache/host-test-marketplace/host-test/1.0.0","entry":"/tmp/host-test/codex-home/.codex/plugins/cache/host-test-marketplace/host-test/1.0.0/mcp/mcp-host-test-0d229f1b-flight.mjs","pid":3858309,"ppid":3857224},"recordedAt":"2026-09-03T08:27:07.927Z","request":{"host":{"source":"native","state":"available","value":{"name":"codex"}},"invocation":{"kind":"event"},"session":{"source":"native","state":"available","value":{"sessionId":"01a06660-110e-7290-8d1c-8ef1b2b68fc2"}}},"runtime":"shared-runtime","sequence":23} +{"event":{"canonical":{"event":"tool/before","idempotencyKey":"45c9c3c0883719053b67ede27f9438bde96b76483183797de9aa725f31fa9ef7","observedAt":"2026-09-03T08:27:12.228Z","provenance":{"host":"codex","hostContractRevision":"0.147.0","nativeEvent":"PreToolUse","source":"native"},"sequence":23},"native":{"session_id":"01a06660-110e-7290-8d1c-8ef1b2b68fc2","turn_id":"01a06660-901a-77f1-a660-ac3c549409c0","agent_id":"01a06660-8faf-7122-80af-24ba2da81ad7","agent_type":"default","transcript_path":"/tmp/host-test/codex-home/.codex/sessions/2026/09/03/rollout-2026-09-03T08-26-39-01a06660-8faf-7122-80af-24ba2da81ad7.jsonl","cwd":"/tmp/host-test/codex-workspace","hook_event_name":"PreToolUse","model":"gpt-5.6-sol","permission_mode":"bypassPermissions","tool_name":"collaborationspawn_agent","tool_input":{"task_name":"nested_probe","fork_turns":"all","message":"gAAAAABqmS9gJS-ZzDXc4tXnr-oXVucubpoXWytRvhbolKooOiEkK5P4a69s-ZtDEQv3JIGxHcm98juMC-EigUNR5g0y2Dz8VMZ3tF_b1LuTBNVH2akXuv0r-YbDlWcQcNhpvetcy0m5AtiO5u_z7h7Lpqi3LGjCooI9njhdWOF6i9ozFYVW8Ps8jn1_9csZcvod8Poqzmz7P3P8svjcYqb_JxHNEB0eSV-t3o8E1aEBI7Z1u0SqYptdfxstQYVRy6DDFWRnMdhc9-eZigjD-ovCz5eyFbjIPw=="},"tool_use_id":"call_i63o2ohoAVpJXjlsGEjoK4we"}},"host":"codex","kind":"event","process":{"cwd":"/tmp/host-test/codex-home/.codex/plugins/cache/host-test-marketplace/host-test/1.0.0","entry":"/tmp/host-test/codex-home/.codex/plugins/cache/host-test-marketplace/host-test/1.0.0/mcp/mcp-host-test-0d229f1b-flight.mjs","pid":3858309,"ppid":3857224},"recordedAt":"2026-09-03T08:27:12.230Z","request":{"host":{"source":"native","state":"available","value":{"name":"codex"}},"invocation":{"kind":"event"},"session":{"source":"native","state":"available","value":{"sessionId":"01a06660-110e-7290-8d1c-8ef1b2b68fc2"}}},"runtime":"shared-runtime","sequence":24} +{"event":{"canonical":{"event":"tool/after","idempotencyKey":"47593d2080a0e2018920990fc6ad7fa29157d8919cdc97bdeae989a623f11fd3","observedAt":"2026-09-03T08:27:12.504Z","provenance":{"host":"codex","hostContractRevision":"0.147.0","nativeEvent":"PostToolUse","source":"native"},"sequence":24},"native":{"session_id":"01a06660-110e-7290-8d1c-8ef1b2b68fc2","turn_id":"01a06660-901a-77f1-a660-ac3c549409c0","agent_id":"01a06660-8faf-7122-80af-24ba2da81ad7","agent_type":"default","transcript_path":"/tmp/host-test/codex-home/.codex/sessions/2026/09/03/rollout-2026-09-03T08-26-39-01a06660-8faf-7122-80af-24ba2da81ad7.jsonl","cwd":"/tmp/host-test/codex-workspace","hook_event_name":"PostToolUse","model":"gpt-5.6-sol","permission_mode":"bypassPermissions","tool_name":"collaborationspawn_agent","tool_input":{"task_name":"nested_probe","fork_turns":"all","message":"gAAAAABqmS9gJS-ZzDXc4tXnr-oXVucubpoXWytRvhbolKooOiEkK5P4a69s-ZtDEQv3JIGxHcm98juMC-EigUNR5g0y2Dz8VMZ3tF_b1LuTBNVH2akXuv0r-YbDlWcQcNhpvetcy0m5AtiO5u_z7h7Lpqi3LGjCooI9njhdWOF6i9ozFYVW8Ps8jn1_9csZcvod8Poqzmz7P3P8svjcYqb_JxHNEB0eSV-t3o8E1aEBI7Z1u0SqYptdfxstQYVRy6DDFWRnMdhc9-eZigjD-ovCz5eyFbjIPw=="},"tool_response":"{\"task_name\":\"/root/host_probe/nested_probe\"}","tool_use_id":"call_i63o2ohoAVpJXjlsGEjoK4we"}},"host":"codex","kind":"event","process":{"cwd":"/tmp/host-test/codex-home/.codex/plugins/cache/host-test-marketplace/host-test/1.0.0","entry":"/tmp/host-test/codex-home/.codex/plugins/cache/host-test-marketplace/host-test/1.0.0/mcp/mcp-host-test-0d229f1b-flight.mjs","pid":3858309,"ppid":3857224},"recordedAt":"2026-09-03T08:27:12.508Z","request":{"host":{"source":"native","state":"available","value":{"name":"codex"}},"invocation":{"kind":"event"},"session":{"source":"native","state":"available","value":{"sessionId":"01a06660-110e-7290-8d1c-8ef1b2b68fc2"}}},"runtime":"shared-runtime","sequence":25} +{"event":{"canonical":{"event":"agent/start","idempotencyKey":"6286e8fff003036ab2e735e7b05687f5a155407761c35e6fb65e464f6e61dd1d","observedAt":"2026-09-03T08:27:14.329Z","provenance":{"host":"codex","hostContractRevision":"0.147.0","nativeEvent":"SubagentStart","source":"native"},"sequence":25},"native":{"session_id":"01a06660-110e-7290-8d1c-8ef1b2b68fc2","turn_id":"01a06661-1086-75c0-abff-e27b0913fccf","transcript_path":"/tmp/host-test/codex-home/.codex/sessions/2026/09/03/rollout-2026-09-03T08-27-12-01a06661-100a-7ad3-a0f5-b0e6ffdb4b11.jsonl","cwd":"/tmp/host-test/codex-workspace","hook_event_name":"SubagentStart","model":"gpt-5.6-sol","permission_mode":"bypassPermissions","agent_id":"01a06661-100a-7ad3-a0f5-b0e6ffdb4b11","agent_type":"default"}},"host":"codex","kind":"event","process":{"cwd":"/tmp/host-test/codex-home/.codex/plugins/cache/host-test-marketplace/host-test/1.0.0","entry":"/tmp/host-test/codex-home/.codex/plugins/cache/host-test-marketplace/host-test/1.0.0/mcp/mcp-host-test-0d229f1b-flight.mjs","pid":3858309,"ppid":3857224},"recordedAt":"2026-09-03T08:27:14.332Z","request":{"host":{"source":"native","state":"available","value":{"name":"codex"}},"invocation":{"kind":"event"},"session":{"source":"native","state":"available","value":{"sessionId":"01a06660-110e-7290-8d1c-8ef1b2b68fc2"}}},"runtime":"shared-runtime","sequence":26} +{"event":{"canonical":{"event":"tool/before","idempotencyKey":"9dfd1c4d38c8c13679e81dc900d403863f7e65b6c9fcec30934282a6a24b8838","observedAt":"2026-09-03T08:27:16.135Z","provenance":{"host":"codex","hostContractRevision":"0.147.0","nativeEvent":"PreToolUse","source":"native"},"sequence":26},"native":{"session_id":"01a06660-110e-7290-8d1c-8ef1b2b68fc2","turn_id":"01a06660-901a-77f1-a660-ac3c549409c0","agent_id":"01a06660-8faf-7122-80af-24ba2da81ad7","agent_type":"default","transcript_path":"/tmp/host-test/codex-home/.codex/sessions/2026/09/03/rollout-2026-09-03T08-26-39-01a06660-8faf-7122-80af-24ba2da81ad7.jsonl","cwd":"/tmp/host-test/codex-workspace","hook_event_name":"PreToolUse","model":"gpt-5.6-sol","permission_mode":"bypassPermissions","tool_name":"collaborationwait_agent","tool_input":{"timeout_ms":3600000},"tool_use_id":"call_cnvSQy5J3H78Vj0wkCBo1VPF"}},"host":"codex","kind":"event","process":{"cwd":"/tmp/host-test/codex-home/.codex/plugins/cache/host-test-marketplace/host-test/1.0.0","entry":"/tmp/host-test/codex-home/.codex/plugins/cache/host-test-marketplace/host-test/1.0.0/mcp/mcp-host-test-0d229f1b-flight.mjs","pid":3858309,"ppid":3857224},"recordedAt":"2026-09-03T08:27:16.137Z","request":{"host":{"source":"native","state":"available","value":{"name":"codex"}},"invocation":{"kind":"event"},"session":{"source":"native","state":"available","value":{"sessionId":"01a06660-110e-7290-8d1c-8ef1b2b68fc2"}}},"runtime":"shared-runtime","sequence":27} +{"event":{"canonical":{"event":"tool/before","idempotencyKey":"931faac1f7c850890c5c60a43eb4170d155285b2b42b5484e928f74098df4682","observedAt":"2026-09-03T08:27:18.433Z","provenance":{"host":"codex","hostContractRevision":"0.147.0","nativeEvent":"PreToolUse","source":"native"},"sequence":27},"native":{"session_id":"01a06660-110e-7290-8d1c-8ef1b2b68fc2","turn_id":"01a06661-1086-75c0-abff-e27b0913fccf","agent_id":"01a06661-100a-7ad3-a0f5-b0e6ffdb4b11","agent_type":"default","transcript_path":"/tmp/host-test/codex-home/.codex/sessions/2026/09/03/rollout-2026-09-03T08-27-12-01a06661-100a-7ad3-a0f5-b0e6ffdb4b11.jsonl","cwd":"/tmp/host-test/codex-workspace","hook_event_name":"PreToolUse","model":"gpt-5.6-sol","permission_mode":"bypassPermissions","tool_name":"Bash","tool_input":{"command":"sed -n '1,240p' /tmp/host-test/codex-home/.codex/plugins/cache/host-test-marketplace/host-test/1.0.0/skills/host-test/SKILL.md"},"tool_use_id":"exec-b71c9ea3-f32f-422a-97ee-a7d3132687c8"}},"host":"codex","kind":"event","process":{"cwd":"/tmp/host-test/codex-home/.codex/plugins/cache/host-test-marketplace/host-test/1.0.0","entry":"/tmp/host-test/codex-home/.codex/plugins/cache/host-test-marketplace/host-test/1.0.0/mcp/mcp-host-test-0d229f1b-flight.mjs","pid":3858309,"ppid":3857224},"recordedAt":"2026-09-03T08:27:18.437Z","request":{"host":{"source":"native","state":"available","value":{"name":"codex"}},"invocation":{"kind":"event"},"session":{"source":"native","state":"available","value":{"sessionId":"01a06660-110e-7290-8d1c-8ef1b2b68fc2"}}},"runtime":"shared-runtime","sequence":28} +{"event":{"canonical":{"event":"tool/after","idempotencyKey":"8c41b24901d7641f319dcaf99a44fd54ceebc6ed1bd993b077b0ef0288175ce0","observedAt":"2026-09-03T08:27:18.778Z","provenance":{"host":"codex","hostContractRevision":"0.147.0","nativeEvent":"PostToolUse","source":"native"},"sequence":28},"native":{"session_id":"01a06660-110e-7290-8d1c-8ef1b2b68fc2","turn_id":"01a06661-1086-75c0-abff-e27b0913fccf","agent_id":"01a06661-100a-7ad3-a0f5-b0e6ffdb4b11","agent_type":"default","transcript_path":"/tmp/host-test/codex-home/.codex/sessions/2026/09/03/rollout-2026-09-03T08-27-12-01a06661-100a-7ad3-a0f5-b0e6ffdb4b11.jsonl","cwd":"/tmp/host-test/codex-workspace","hook_event_name":"PostToolUse","model":"gpt-5.6-sol","permission_mode":"bypassPermissions","tool_name":"Bash","tool_input":{"command":"sed -n '1,240p' /tmp/host-test/codex-home/.codex/plugins/cache/host-test-marketplace/host-test/1.0.0/skills/host-test/SKILL.md"},"tool_response":"---\nname: host-test\ndescription: Probe what this host sends to plugin hooks and MCP servers. Use when asked to run the host-test probe, dump host lineage, or check which conversation, session, or subagent ids a hook or MCP call carries.\n---\n\n# Host test probe\n\nThis plugin records every hook event the host dispatches to it, plus every\ncall to its own MCP servers, into one NDJSON log and a durable s…[+1064 chars]","tool_use_id":"exec-b71c9ea3-f32f-422a-97ee-a7d3132687c8"}},"host":"codex","kind":"event","process":{"cwd":"/tmp/host-test/codex-home/.codex/plugins/cache/host-test-marketplace/host-test/1.0.0","entry":"/tmp/host-test/codex-home/.codex/plugins/cache/host-test-marketplace/host-test/1.0.0/mcp/mcp-host-test-0d229f1b-flight.mjs","pid":3858309,"ppid":3857224},"recordedAt":"2026-09-03T08:27:18.781Z","request":{"host":{"source":"native","state":"available","value":{"name":"codex"}},"invocation":{"kind":"event"},"session":{"source":"native","state":"available","value":{"sessionId":"01a06660-110e-7290-8d1c-8ef1b2b68fc2"}}},"runtime":"shared-runtime","sequence":29} +{"event":{"canonical":{"event":"tool/before","idempotencyKey":"803653e4593a965edc9f7548b4ce18cef0e2ccdc33368b1bf7193dd6be421671","observedAt":"2026-09-03T08:27:22.965Z","provenance":{"host":"codex","hostContractRevision":"0.147.0","nativeEvent":"PreToolUse","source":"native"},"sequence":29},"native":{"session_id":"01a06660-110e-7290-8d1c-8ef1b2b68fc2","turn_id":"01a06661-1086-75c0-abff-e27b0913fccf","agent_id":"01a06661-100a-7ad3-a0f5-b0e6ffdb4b11","agent_type":"default","transcript_path":"/tmp/host-test/codex-home/.codex/sessions/2026/09/03/rollout-2026-09-03T08-27-12-01a06661-100a-7ad3-a0f5-b0e6ffdb4b11.jsonl","cwd":"/tmp/host-test/codex-workspace","hook_event_name":"PreToolUse","model":"gpt-5.6-sol","permission_mode":"bypassPermissions","tool_name":"Bash","tool_input":{"command":"pwd"},"tool_use_id":"exec-82f71d52-db27-4be7-8d8e-970fd48ef453"}},"host":"codex","kind":"event","process":{"cwd":"/tmp/host-test/codex-home/.codex/plugins/cache/host-test-marketplace/host-test/1.0.0","entry":"/tmp/host-test/codex-home/.codex/plugins/cache/host-test-marketplace/host-test/1.0.0/mcp/mcp-host-test-0d229f1b-flight.mjs","pid":3858309,"ppid":3857224},"recordedAt":"2026-09-03T08:27:22.967Z","request":{"host":{"source":"native","state":"available","value":{"name":"codex"}},"invocation":{"kind":"event"},"session":{"source":"native","state":"available","value":{"sessionId":"01a06660-110e-7290-8d1c-8ef1b2b68fc2"}}},"runtime":"shared-runtime","sequence":30} +{"event":{"canonical":{"event":"tool/after","idempotencyKey":"8a515336e19c0e7b6ef7548e3e3f56cad4b90a2400cd6d3c14d96a8b7f4d0cd0","observedAt":"2026-09-03T08:27:23.216Z","provenance":{"host":"codex","hostContractRevision":"0.147.0","nativeEvent":"PostToolUse","source":"native"},"sequence":30},"native":{"session_id":"01a06660-110e-7290-8d1c-8ef1b2b68fc2","turn_id":"01a06661-1086-75c0-abff-e27b0913fccf","agent_id":"01a06661-100a-7ad3-a0f5-b0e6ffdb4b11","agent_type":"default","transcript_path":"/tmp/host-test/codex-home/.codex/sessions/2026/09/03/rollout-2026-09-03T08-27-12-01a06661-100a-7ad3-a0f5-b0e6ffdb4b11.jsonl","cwd":"/tmp/host-test/codex-workspace","hook_event_name":"PostToolUse","model":"gpt-5.6-sol","permission_mode":"bypassPermissions","tool_name":"Bash","tool_input":{"command":"pwd"},"tool_response":"/tmp/host-test/codex-workspace\n","tool_use_id":"exec-82f71d52-db27-4be7-8d8e-970fd48ef453"}},"host":"codex","kind":"event","process":{"cwd":"/tmp/host-test/codex-home/.codex/plugins/cache/host-test-marketplace/host-test/1.0.0","entry":"/tmp/host-test/codex-home/.codex/plugins/cache/host-test-marketplace/host-test/1.0.0/mcp/mcp-host-test-0d229f1b-flight.mjs","pid":3858309,"ppid":3857224},"recordedAt":"2026-09-03T08:27:23.219Z","request":{"host":{"source":"native","state":"available","value":{"name":"codex"}},"invocation":{"kind":"event"},"session":{"source":"native","state":"available","value":{"sessionId":"01a06660-110e-7290-8d1c-8ef1b2b68fc2"}}},"runtime":"shared-runtime","sequence":31} +{"event":{"canonical":{"event":"tool/before","idempotencyKey":"2dc5f799dca6297dd71d0c1b30094f4610366d8ab36541e5c72e0598f2ed1e81","observedAt":"2026-09-03T08:27:31.234Z","provenance":{"host":"codex","hostContractRevision":"0.147.0","nativeEvent":"PreToolUse","source":"native"},"sequence":31},"native":{"session_id":"01a06660-110e-7290-8d1c-8ef1b2b68fc2","turn_id":"01a06661-1086-75c0-abff-e27b0913fccf","agent_id":"01a06661-100a-7ad3-a0f5-b0e6ffdb4b11","agent_type":"default","transcript_path":"/tmp/host-test/codex-home/.codex/sessions/2026/09/03/rollout-2026-09-03T08-27-12-01a06661-100a-7ad3-a0f5-b0e6ffdb4b11.jsonl","cwd":"/tmp/host-test/codex-workspace","hook_event_name":"PreToolUse","model":"gpt-5.6-sol","permission_mode":"bypassPermissions","tool_name":"mcp__host_test_raw__probe","tool_input":{"note":"nested"},"tool_use_id":"exec-0a972e9d-6e53-4618-aef0-5dd124eca0eb"}},"host":"codex","kind":"event","process":{"cwd":"/tmp/host-test/codex-home/.codex/plugins/cache/host-test-marketplace/host-test/1.0.0","entry":"/tmp/host-test/codex-home/.codex/plugins/cache/host-test-marketplace/host-test/1.0.0/mcp/mcp-host-test-0d229f1b-flight.mjs","pid":3858309,"ppid":3857224},"recordedAt":"2026-09-03T08:27:31.237Z","request":{"host":{"source":"native","state":"available","value":{"name":"codex"}},"invocation":{"kind":"event"},"session":{"source":"native","state":"available","value":{"sessionId":"01a06660-110e-7290-8d1c-8ef1b2b68fc2"}}},"runtime":"shared-runtime","sequence":32} +{"host":"codex-mcp-client","kind":"mcp","observed":{"client":{"name":"codex-mcp-client","title":"Codex","version":"0.147.0"},"clientCapabilities":{"elicitation":{"form":{},"url":{}}},"env":{"names":["AGENT_BUNDLE_PLUGIN_ROOT"]},"http":null,"mcpReq":{"_meta":{"progressToken":1,"x-codex-turn-metadata":{"session_id":"01a06660-110e-7290-8d1c-8ef1b2b68fc2","thread_id":"01a06661-100a-7ad3-a0f5-b0e6ffdb4b11","turn_id":"01a06661-1086-75c0-abff-e27b0913fccf","forked_from_thread_id":"01a06660-8faf-7122-80af-24ba2da81ad7","parent_thread_id":"01a06660-8faf-7122-80af-24ba2da81ad7","turn_started_at_unix_ms":1788424032400,"subagent_kind":"thread_spawn","thread_source":"subagent","sandbox":"seccomp","workspaces":{"/tmp/host-test/codex-workspace":{"latest_git_commit_hash":"840e5bd01b2601e82ed34c286c17597b29959a50","has_changes":true}},"model":"gpt-5.6-sol","reasoning_effort":"low"},"plugin_id":"host-test@host-test-marketplace","threadId":"01a06661-100a-7ad3-a0f5-b0e6ffdb4b11"},"envelope":null,"id":2,"method":"tools/call"},"note":"nested","sessionId":null,"tool":"probe"},"process":{"cwd":"/tmp/host-test/codex-home/.codex/plugins/cache/host-test-marketplace/host-test/1.0.0","entry":"/tmp/host-test/codex-home/.codex/plugins/cache/host-test-marketplace/host-test/1.0.0/mcp/mcp-host-test-raw-6e9c1a1c.mjs","pid":3893894,"ppid":3857224},"recordedAt":"2026-09-03T08:27:31.270Z","request":{"unavailable":"hand-rolled stdio server: no framework request context is mounted"},"runtime":"mcp-server","sequence":1} +{"event":{"canonical":{"event":"tool/after","idempotencyKey":"5ebf0f08aa17dc8616793f3ac236f526f45cb1498a7b1fb61a50276de8367b43","observedAt":"2026-09-03T08:27:31.425Z","provenance":{"host":"codex","hostContractRevision":"0.147.0","nativeEvent":"PostToolUse","source":"native"},"sequence":32},"native":{"session_id":"01a06660-110e-7290-8d1c-8ef1b2b68fc2","turn_id":"01a06661-1086-75c0-abff-e27b0913fccf","agent_id":"01a06661-100a-7ad3-a0f5-b0e6ffdb4b11","agent_type":"default","transcript_path":"/tmp/host-test/codex-home/.codex/sessions/2026/09/03/rollout-2026-09-03T08-27-12-01a06661-100a-7ad3-a0f5-b0e6ffdb4b11.jsonl","cwd":"/tmp/host-test/codex-workspace","hook_event_name":"PostToolUse","model":"gpt-5.6-sol","permission_mode":"bypassPermissions","tool_name":"mcp__host_test_raw__probe","tool_input":{"note":"nested"},"tool_response":{"content":[{"type":"text","text":"{\n \"log\": \"/tmp/host-test/codex-home/.codex/plugins/cache/host-test-marketplace/host-test/1.0.0/state/host-test/captures.ndjson\",\n \"observed\": {\n \"client\": {\n \"name\": \"codex-mcp-client\",\n \"title\": \"Codex\",\n \"version\": \"0.147.0\"\n },\n \"clientCapabilities\": {\n \"elicitation\": {\n \"form\": {},\n \"url\": {}\n }\n },\n \"env\": {\n \"names\": [\n \"AG…[+1238 chars]"}],"structuredContent":{"log":"/tmp/host-test/codex-home/.codex/plugins/cache/host-test-marketplace/host-test/1.0.0/state/host-test/captures.ndjson","observed":{"client":{"name":"codex-mcp-client","title":"Codex","version":"0.147.0"},"clientCapabilities":{"elicitation":{"form":{},"url":{}}},"env":{"names":["AGENT_BUNDLE_PLUGIN_ROOT"]},"http":null,"mcpReq":{"_meta":{"progressToken":1,"x-codex-turn-metadata":{"session_id":"01a06660-110e-7290-8d1c-8ef1b2b68fc2","thread_id":"01a06661-100a-7ad3-a0f5-b0e6ffdb4b11","turn_id":"01a06661-1086-75c0-abff-e27b0913fccf","forked_from_thread_id":"01a06660-8faf-7122-80af-24ba2da81ad7","parent_thread_id":"01a06660-8faf-7122-80af-24ba2da81ad7","turn_started_at_unix_ms":1788424032400,"subagent_kind":"thread_spawn","thread_source":"subagent","sandbox":"seccomp","workspaces":{"/tmp/host-test/codex-workspace":{"latest_git_commit_hash":"840e5bd01b2601e82ed34c286c17597b29959a50","has_changes":true}},"model":"gpt-5.6-sol","reasoning_effort":"low"},"plugin_id":"host-test@host-test-marketplace","threadId":"01a06661-100a-7ad3-a0f5-b0e6ffdb4b11"},"envelope":null,"id":2,"method":"tools/call"},"note":"nested","sessionId":null,"tool":"probe"},"sequence":1}},"tool_use_id":"exec-0a972e9d-6e53-4618-aef0-5dd124eca0eb"}},"host":"codex","kind":"event","process":{"cwd":"/tmp/host-test/codex-home/.codex/plugins/cache/host-test-marketplace/host-test/1.0.0","entry":"/tmp/host-test/codex-home/.codex/plugins/cache/host-test-marketplace/host-test/1.0.0/mcp/mcp-host-test-0d229f1b-flight.mjs","pid":3858309,"ppid":3857224},"recordedAt":"2026-09-03T08:27:31.428Z","request":{"host":{"source":"native","state":"available","value":{"name":"codex"}},"invocation":{"kind":"event"},"session":{"source":"native","state":"available","value":{"sessionId":"01a06660-110e-7290-8d1c-8ef1b2b68fc2"}}},"runtime":"shared-runtime","sequence":33} +{"event":{"canonical":{"event":"agent/stop","idempotencyKey":"48883f4939c8abbcbac8a702cce924707cfb874458346d3e28f4ad588e7b0316","observedAt":"2026-09-03T08:27:38.364Z","provenance":{"host":"codex","hostContractRevision":"0.147.0","nativeEvent":"SubagentStop","source":"native"},"sequence":33},"native":{"session_id":"01a06660-110e-7290-8d1c-8ef1b2b68fc2","turn_id":"01a06661-1086-75c0-abff-e27b0913fccf","transcript_path":"/tmp/host-test/codex-home/.codex/sessions/2026/09/03/rollout-2026-09-03T08-26-39-01a06660-8faf-7122-80af-24ba2da81ad7.jsonl","agent_transcript_path":"/tmp/host-test/codex-home/.codex/sessions/2026/09/03/rollout-2026-09-03T08-27-12-01a06661-100a-7ad3-a0f5-b0e6ffdb4b11.jsonl","cwd":"/tmp/host-test/codex-workspace","hook_event_name":"SubagentStop","model":"gpt-5.6-sol","permission_mode":"bypassPermissions","stop_hook_active":false,"agent_id":"01a06661-100a-7ad3-a0f5-b0e6ffdb4b11","agent_type":"default","last_assistant_message":"session_id=01a06660-110e-7290-8d1c-8ef1b2b68fc2 thread_id=01a06661-100a-7ad3-a0f5-b0e6ffdb4b11 turn_id=01a06661-1086-75c0-abff-e27b0913fccf forked_from_thread_id=01a06660-8faf-7122-80af-24ba2da81ad7 p…[+157 chars]"}},"host":"codex","kind":"event","process":{"cwd":"/tmp/host-test/codex-home/.codex/plugins/cache/host-test-marketplace/host-test/1.0.0","entry":"/tmp/host-test/codex-home/.codex/plugins/cache/host-test-marketplace/host-test/1.0.0/mcp/mcp-host-test-0d229f1b-flight.mjs","pid":3858309,"ppid":3857224},"recordedAt":"2026-09-03T08:27:38.367Z","request":{"host":{"source":"native","state":"available","value":{"name":"codex"}},"invocation":{"kind":"event"},"session":{"source":"native","state":"available","value":{"sessionId":"01a06660-110e-7290-8d1c-8ef1b2b68fc2"}}},"runtime":"shared-runtime","sequence":34} +{"event":{"canonical":{"event":"tool/after","idempotencyKey":"23d525fda0140b785d5bf9545342d2b16752e783c4abcfa83f2e740d96e5eb7a","observedAt":"2026-09-03T08:27:38.544Z","provenance":{"host":"codex","hostContractRevision":"0.147.0","nativeEvent":"PostToolUse","source":"native"},"sequence":34},"native":{"session_id":"01a06660-110e-7290-8d1c-8ef1b2b68fc2","turn_id":"01a06660-901a-77f1-a660-ac3c549409c0","agent_id":"01a06660-8faf-7122-80af-24ba2da81ad7","agent_type":"default","transcript_path":"/tmp/host-test/codex-home/.codex/sessions/2026/09/03/rollout-2026-09-03T08-26-39-01a06660-8faf-7122-80af-24ba2da81ad7.jsonl","cwd":"/tmp/host-test/codex-workspace","hook_event_name":"PostToolUse","model":"gpt-5.6-sol","permission_mode":"bypassPermissions","tool_name":"collaborationwait_agent","tool_input":{"timeout_ms":3600000},"tool_response":"{\"message\":\"Wait completed.\",\"timed_out\":false}","tool_use_id":"call_cnvSQy5J3H78Vj0wkCBo1VPF"}},"host":"codex","kind":"event","process":{"cwd":"/tmp/host-test/codex-home/.codex/plugins/cache/host-test-marketplace/host-test/1.0.0","entry":"/tmp/host-test/codex-home/.codex/plugins/cache/host-test-marketplace/host-test/1.0.0/mcp/mcp-host-test-0d229f1b-flight.mjs","pid":3858309,"ppid":3857224},"recordedAt":"2026-09-03T08:27:38.547Z","request":{"host":{"source":"native","state":"available","value":{"name":"codex"}},"invocation":{"kind":"event"},"session":{"source":"native","state":"available","value":{"sessionId":"01a06660-110e-7290-8d1c-8ef1b2b68fc2"}}},"runtime":"shared-runtime","sequence":35} +{"event":{"canonical":{"event":"agent/stop","idempotencyKey":"e6a2c8797cedf713e823af2a4ec03ea079b1c89f419715a189491913cdc3b899","observedAt":"2026-09-03T08:27:47.866Z","provenance":{"host":"codex","hostContractRevision":"0.147.0","nativeEvent":"SubagentStop","source":"native"},"sequence":35},"native":{"session_id":"01a06660-110e-7290-8d1c-8ef1b2b68fc2","turn_id":"01a06660-901a-77f1-a660-ac3c549409c0","transcript_path":"/tmp/host-test/codex-home/.codex/sessions/2026/09/03/rollout-2026-09-03T08-26-06-01a06660-110e-7290-8d1c-8ef1b2b68fc2.jsonl","agent_transcript_path":"/tmp/host-test/codex-home/.codex/sessions/2026/09/03/rollout-2026-09-03T08-26-39-01a06660-8faf-7122-80af-24ba2da81ad7.jsonl","cwd":"/tmp/host-test/codex-workspace","hook_event_name":"SubagentStop","model":"gpt-5.6-sol","permission_mode":"bypassPermissions","stop_hook_active":false,"agent_id":"01a06660-8faf-7122-80af-24ba2da81ad7","agent_type":"default","last_assistant_message":"Subagent IDs: session_id=01a06660-110e-7290-8d1c-8ef1b2b68fc2 thread_id=01a06660-8faf-7122-80af-24ba2da81ad7 turn_id=01a06660-901a-77f1-a660-ac3c549409c0 forked_from_thread_id=01a06660-110e-7290-8d1c-…[+745 chars]"}},"host":"codex","kind":"event","process":{"cwd":"/tmp/host-test/codex-home/.codex/plugins/cache/host-test-marketplace/host-test/1.0.0","entry":"/tmp/host-test/codex-home/.codex/plugins/cache/host-test-marketplace/host-test/1.0.0/mcp/mcp-host-test-0d229f1b-flight.mjs","pid":3858309,"ppid":3857224},"recordedAt":"2026-09-03T08:27:47.869Z","request":{"host":{"source":"native","state":"available","value":{"name":"codex"}},"invocation":{"kind":"event"},"session":{"source":"native","state":"available","value":{"sessionId":"01a06660-110e-7290-8d1c-8ef1b2b68fc2"}}},"runtime":"shared-runtime","sequence":36} +{"event":{"canonical":{"event":"tool/after","idempotencyKey":"ca41bb023ffa8c21d80fb82850dba56c19bf23573ec03154ca7f3a27908d7760","observedAt":"2026-09-03T08:27:48.014Z","provenance":{"host":"codex","hostContractRevision":"0.147.0","nativeEvent":"PostToolUse","source":"native"},"sequence":36},"native":{"session_id":"01a06660-110e-7290-8d1c-8ef1b2b68fc2","turn_id":"01a06660-1179-7bd2-bb02-d4cac726b2a0","transcript_path":"/tmp/host-test/codex-home/.codex/sessions/2026/09/03/rollout-2026-09-03T08-26-06-01a06660-110e-7290-8d1c-8ef1b2b68fc2.jsonl","cwd":"/tmp/host-test/codex-workspace","hook_event_name":"PostToolUse","model":"gpt-5.6-sol","permission_mode":"bypassPermissions","tool_name":"collaborationwait_agent","tool_input":{"timeout_ms":3600000},"tool_response":"{\"message\":\"Wait completed.\",\"timed_out\":false}","tool_use_id":"call_sWiia6GTw0YUCkOdk5dtZZ2d"}},"host":"codex","kind":"event","process":{"cwd":"/tmp/host-test/codex-home/.codex/plugins/cache/host-test-marketplace/host-test/1.0.0","entry":"/tmp/host-test/codex-home/.codex/plugins/cache/host-test-marketplace/host-test/1.0.0/mcp/mcp-host-test-0d229f1b-flight.mjs","pid":3858309,"ppid":3857224},"recordedAt":"2026-09-03T08:27:48.016Z","request":{"host":{"source":"native","state":"available","value":{"name":"codex"}},"invocation":{"kind":"event"},"session":{"source":"native","state":"available","value":{"sessionId":"01a06660-110e-7290-8d1c-8ef1b2b68fc2"}}},"runtime":"shared-runtime","sequence":37} +{"event":{"canonical":{"event":"stop","idempotencyKey":"0e32e11b3117b25f5b21f764a6cb758a4a7432797972f72328125f367b8727a0","observedAt":"2026-09-03T08:27:50.414Z","provenance":{"host":"codex","hostContractRevision":"0.147.0","nativeEvent":"Stop","source":"native"},"sequence":37},"native":{"session_id":"01a06660-110e-7290-8d1c-8ef1b2b68fc2","turn_id":"01a06660-1179-7bd2-bb02-d4cac726b2a0","transcript_path":"/tmp/host-test/codex-home/.codex/sessions/2026/09/03/rollout-2026-09-03T08-26-06-01a06660-110e-7290-8d1c-8ef1b2b68fc2.jsonl","cwd":"/tmp/host-test/codex-workspace","hook_event_name":"Stop","model":"gpt-5.6-sol","permission_mode":"bypassPermissions","stop_hook_active":false,"last_assistant_message":"HOST_TEST_DONE /tmp/host-test/codex-home/.codex/plugins/cache/host-test-marketplace/host-test/1.0.0/state/host-test/captures.ndjson"}},"host":"codex","kind":"event","process":{"cwd":"/tmp/host-test/codex-home/.codex/plugins/cache/host-test-marketplace/host-test/1.0.0","entry":"/tmp/host-test/codex-home/.codex/plugins/cache/host-test-marketplace/host-test/1.0.0/mcp/mcp-host-test-0d229f1b-flight.mjs","pid":3858309,"ppid":3857224},"recordedAt":"2026-09-03T08:27:50.417Z","request":{"host":{"source":"native","state":"available","value":{"name":"codex"}},"invocation":{"kind":"event"},"session":{"source":"native","state":"available","value":{"sessionId":"01a06660-110e-7290-8d1c-8ef1b2b68fc2"}}},"runtime":"shared-runtime","sequence":38} diff --git a/fixtures/host-lineage/cursor-3.18.25.ndjson b/fixtures/host-lineage/cursor-3.18.25.ndjson new file mode 100644 index 000000000..273b771c8 --- /dev/null +++ b/fixtures/host-lineage/cursor-3.18.25.ndjson @@ -0,0 +1,87 @@ +{"env":{"names":["CLAUDE_PLUGIN_ROOT","CLAUDE_PROJECT_DIR","CURSOR_EXTENSION_HOST_ROLE","CURSOR_LAYOUT","CURSOR_PLUGIN_ROOT","CURSOR_PROJECT_DIR","CURSOR_RIPGREP_PATH","CURSOR_USER_EMAIL","CURSOR_VERSION","CURSOR_WORKSPACE_LABEL","HOST_TEST_LOG_DIR"]},"event":{"canonical":{"event":"prompt/submit","idempotencyKey":"a00076b4d26b58f5b8f04f081a8bf655f721b6b7df030607d908747171076454","observedAt":"2026-09-03T08:35:23.673Z","provenance":{"host":"cursor","hostContractRevision":"2026-08-28","nativeEvent":"beforeSubmitPrompt","source":"native"},"sequence":1},"native":{"conversation_id":"b60ae0c1-2f85-4c4d-b3e5-b512f9b06e4c","generation_id":"d4b2603b-ebfe-45ee-832d-b30d048defbb","model":"default","model_id":"default","composer_mode":"agent","prompt":"You are exercising the host-test probe plugin. Do exactly these steps in order, without asking questions and without pausing for confirmation.\n1. Run the shell command `pwd`.\n2. Create a file named pr…[+777 chars]","attachments":[],"session_id":"b60ae0c1-2f85-4c4d-b3e5-b512f9b06e4c","hook_event_name":"beforeSubmitPrompt","cursor_version":"3.18.25","workspace_roots":["/tmp/host-test/cursor-workspace"],"user_email":"probe@example.invalid","transcript_path":null}},"host":"cursor","kind":"event","process":{"cwd":"/tmp/host-test/cursor-home/.cursor/plugins/local/host-test","entry":"/tmp/host-test/cursor-home/.cursor/plugins/local/host-test/hooks/hooks-flight.mjs","pid":58914,"ppid":4120845},"recordedAt":"2026-09-03T08:35:23.873Z","request":{"host":{"source":"native","state":"available","value":{"name":"cursor"}},"invocation":{"kind":"event"},"session":{"source":"native","state":"available","value":{"sessionId":"b60ae0c1-2f85-4c4d-b3e5-b512f9b06e4c"}}},"runtime":"standalone-hook","sequence":1} +{"env":{"names":["AGENT_BUNDLE_PLUGIN_ROOT","HOST_TEST_LOG_DIR"]},"event":{"canonical":{"event":"tool/before","idempotencyKey":"eaedbfff722523b0986e4985013bdc64bfdaf1aa78d6d9d455d67c45449614ed","observedAt":"2026-09-03T08:35:28.088Z","provenance":{"host":"cursor","hostContractRevision":"2026-08-28","nativeEvent":"preToolUse","source":"native"},"sequence":1},"native":{"conversation_id":"b60ae0c1-2f85-4c4d-b3e5-b512f9b06e4c","generation_id":"d4b2603b-ebfe-45ee-832d-b30d048defbb","model":"default","tool_name":"Read","tool_input":{"file_path":"/tmp/host-test/cursor-home/.cursor/plugins/cache/local/host-test/skills/host-test/SKILL.md"},"tool_use_id":"call-130a53a3-5718-473b-8101-a9c73231b7be-0\nfc_76ffef3f-2276-97fd-a40d-770e2dd5bc0b_0","session_id":"b60ae0c1-2f85-4c4d-b3e5-b512f9b06e4c","hook_event_name":"preToolUse","cursor_version":"3.18.25","workspace_roots":["/tmp/host-test/cursor-workspace"],"user_email":"probe@example.invalid","transcript_path":null}},"host":"cursor","kind":"event","process":{"cwd":"/tmp/host-test/cursor-home","entry":"/tmp/host-test/cursor-home/.cursor/plugins/local/host-test/mcp/mcp-host-test-0d229f1b-flight.mjs","pid":59574,"ppid":4119277},"recordedAt":"2026-09-03T08:35:28.158Z","request":{"host":{"source":"native","state":"available","value":{"name":"cursor"}},"invocation":{"kind":"event"},"session":{"source":"native","state":"available","value":{"sessionId":"b60ae0c1-2f85-4c4d-b3e5-b512f9b06e4c"}}},"runtime":"shared-runtime","sequence":1} +{"event":{"canonical":{"event":"tool/before","idempotencyKey":"181c314d05cb8f3c4c7162ef2525c1dfa4ea39cf7d395904d07d710de728102f","observedAt":"2026-09-03T08:35:33.765Z","provenance":{"host":"cursor","hostContractRevision":"2026-08-28","nativeEvent":"preToolUse","source":"native"},"sequence":2},"native":{"conversation_id":"b60ae0c1-2f85-4c4d-b3e5-b512f9b06e4c","generation_id":"d4b2603b-ebfe-45ee-832d-b30d048defbb","model":"default","tool_name":"Grep","tool_input":{"pattern":"","file_path":"/tmp/host-test/cursor-home","glob":"**/host-test/**/SKILL.md","output_mode":"files_with_matches"},"tool_use_id":"call-334ad91f-d3d5-430a-8539-0b73d670296e-2\nfc_3b11fda7-9819-970c-a73f-d3ff394c18c4_1","session_id":"b60ae0c1-2f85-4c4d-b3e5-b512f9b06e4c","hook_event_name":"preToolUse","cursor_version":"3.18.25","workspace_roots":["/tmp/host-test/cursor-workspace"],"user_email":"probe@example.invalid","transcript_path":"/tmp/host-test/cursor-home/.cursor/projects/tmp-host-test-cursor-workspace/agent-transcripts/b60ae0c1-2f85-4c4d-b3e5-b512f9b06e4c/b60ae0c1-2f85-4c4d-b3e5-b512f9b06e4c.jsonl"}},"host":"cursor","kind":"event","process":{"cwd":"/tmp/host-test/cursor-home","entry":"/tmp/host-test/cursor-home/.cursor/plugins/local/host-test/mcp/mcp-host-test-0d229f1b-flight.mjs","pid":59574,"ppid":4119277},"recordedAt":"2026-09-03T08:35:33.770Z","request":{"host":{"source":"native","state":"available","value":{"name":"cursor"}},"invocation":{"kind":"event"},"session":{"source":"native","state":"available","value":{"sessionId":"b60ae0c1-2f85-4c4d-b3e5-b512f9b06e4c"}}},"runtime":"shared-runtime","sequence":2} +{"event":{"canonical":{"event":"tool/before","idempotencyKey":"08c0550e4d5097893e08ac2f656f6cd1aacd200d96f20215bd75f3312c0fc520","observedAt":"2026-09-03T08:35:33.828Z","provenance":{"host":"cursor","hostContractRevision":"2026-08-28","nativeEvent":"preToolUse","source":"native"},"sequence":4},"native":{"conversation_id":"b60ae0c1-2f85-4c4d-b3e5-b512f9b06e4c","generation_id":"d4b2603b-ebfe-45ee-832d-b30d048defbb","model":"default","tool_name":"Shell","tool_input":{"command":"pwd","cwd":"","timeout":30000},"tool_use_id":"25c45009-ca76-4283-9371-b9146187c78d","cwd":"","session_id":"b60ae0c1-2f85-4c4d-b3e5-b512f9b06e4c","hook_event_name":"preToolUse","cursor_version":"3.18.25","workspace_roots":["/tmp/host-test/cursor-workspace"],"user_email":"probe@example.invalid","transcript_path":"/tmp/host-test/cursor-home/.cursor/projects/tmp-host-test-cursor-workspace/agent-transcripts/b60ae0c1-2f85-4c4d-b3e5-b512f9b06e4c/b60ae0c1-2f85-4c4d-b3e5-b512f9b06e4c.jsonl"}},"host":"cursor","kind":"event","process":{"cwd":"/tmp/host-test/cursor-home","entry":"/tmp/host-test/cursor-home/.cursor/plugins/local/host-test/mcp/mcp-host-test-0d229f1b-flight.mjs","pid":59574,"ppid":4119277},"recordedAt":"2026-09-03T08:35:33.832Z","request":{"host":{"source":"native","state":"available","value":{"name":"cursor"}},"invocation":{"kind":"event"},"session":{"source":"native","state":"available","value":{"sessionId":"b60ae0c1-2f85-4c4d-b3e5-b512f9b06e4c"}}},"runtime":"shared-runtime","sequence":4} +{"event":{"canonical":{"event":"tool/after","idempotencyKey":"e68626441922a7703f06d94a45ccdbdecdd5ab5f03fa99be7671ffa1279b7343","observedAt":"2026-09-03T08:35:34.016Z","provenance":{"host":"cursor","hostContractRevision":"2026-08-28","nativeEvent":"postToolUse","source":"native"},"sequence":5},"native":{"conversation_id":"b60ae0c1-2f85-4c4d-b3e5-b512f9b06e4c","generation_id":"d4b2603b-ebfe-45ee-832d-b30d048defbb","model":"default","tool_name":"Grep","tool_input":{"pattern":"","file_path":"/tmp/host-test/cursor-home","glob":"**/host-test/**/SKILL.md","output_mode":"files_with_matches"},"tool_output":"{\"pattern\":\"\",\"success\":true}","duration":87.947,"tool_use_id":"call-334ad91f-d3d5-430a-8539-0b73d670296e-2\nfc_3b11fda7-9819-970c-a73f-d3ff394c18c4_1","session_id":"b60ae0c1-2f85-4c4d-b3e5-b512f9b06e4c","hook_event_name":"postToolUse","cursor_version":"3.18.25","workspace_roots":["/tmp/host-test/cursor-workspace"],"user_email":"probe@example.invalid","transcript_path":"/tmp/host-test/cursor-home/.cursor/projects/tmp-host-test-cursor-workspace/agent-transcripts/b60ae0c1-2f85-4c4d-b3e5-b512f9b06e4c/b60ae0c1-2f85-4c4d-b3e5-b512f9b06e4c.jsonl"}},"host":"cursor","kind":"event","process":{"cwd":"/tmp/host-test/cursor-home","entry":"/tmp/host-test/cursor-home/.cursor/plugins/local/host-test/mcp/mcp-host-test-0d229f1b-flight.mjs","pid":59574,"ppid":4119277},"recordedAt":"2026-09-03T08:35:34.020Z","request":{"host":{"source":"native","state":"available","value":{"name":"cursor"}},"invocation":{"kind":"event"},"session":{"source":"native","state":"available","value":{"sessionId":"b60ae0c1-2f85-4c4d-b3e5-b512f9b06e4c"}}},"runtime":"shared-runtime","sequence":5} +{"event":{"canonical":{"event":"tool/after","idempotencyKey":"89fc9f545b524d66a5740e5d83ec920ef4bd81b475af5e3b8a223d5eb6e66820","observedAt":"2026-09-03T08:35:39.310Z","provenance":{"host":"cursor","hostContractRevision":"2026-08-28","nativeEvent":"postToolUse","source":"native"},"sequence":7},"native":{"conversation_id":"b60ae0c1-2f85-4c4d-b3e5-b512f9b06e4c","generation_id":"d4b2603b-ebfe-45ee-832d-b30d048defbb","model":"default","tool_name":"Shell","tool_input":{"command":"pwd","cwd":"","timeout":30000},"tool_output":"{\"output\":\"/tmp/host-test/cursor-workspace\\n\",\"exitCode\":0}","duration":5279.734,"tool_use_id":"25c45009-ca76-4283-9371-b9146187c78d","cwd":"","session_id":"b60ae0c1-2f85-4c4d-b3e5-b512f9b06e4c","hook_event_name":"postToolUse","cursor_version":"3.18.25","workspace_roots":["/tmp/host-test/cursor-workspace"],"user_email":"probe@example.invalid","transcript_path":"/tmp/host-test/cursor-home/.cursor/projects/tmp-host-test-cursor-workspace/agent-transcripts/b60ae0c1-2f85-4c4d-b3e5-b512f9b06e4c/b60ae0c1-2f85-4c4d-b3e5-b512f9b06e4c.jsonl"}},"host":"cursor","kind":"event","process":{"cwd":"/tmp/host-test/cursor-home","entry":"/tmp/host-test/cursor-home/.cursor/plugins/local/host-test/mcp/mcp-host-test-0d229f1b-flight.mjs","pid":59574,"ppid":4119277},"recordedAt":"2026-09-03T08:35:39.314Z","request":{"host":{"source":"native","state":"available","value":{"name":"cursor"}},"invocation":{"kind":"event"},"session":{"source":"native","state":"available","value":{"sessionId":"b60ae0c1-2f85-4c4d-b3e5-b512f9b06e4c"}}},"runtime":"shared-runtime","sequence":7} +{"event":{"canonical":{"event":"tool/after","idempotencyKey":"f79b75149c4a1e04cc07a09aa1808702c72d31bde903d4acc47ed85454226bb6","observedAt":"2026-09-03T08:35:42.730Z","provenance":{"host":"cursor","hostContractRevision":"2026-08-28","nativeEvent":"postToolUse","source":"native"},"sequence":10},"native":{"conversation_id":"b60ae0c1-2f85-4c4d-b3e5-b512f9b06e4c","generation_id":"d4b2603b-ebfe-45ee-832d-b30d048defbb","model":"default","tool_name":"Read","tool_input":{"file_path":"/tmp/host-test/cursor-home/.cursor/plugins/local/host-test/skills/host-test/SKILL.md"},"tool_output":"{\"file_path\":\"/tmp/host-test/cursor-home/.cursor/plugins/local/host-test/skills/host-test/SKILL.md\",\"content_length\":1464}","duration":6.139,"tool_use_id":"call-e9be6a5e-b7b6-4f51-a276-11f12b6c0e83-4\nfc_11d0162b-5607-95d3-b74e-8ac934bd945a_0","session_id":"b60ae0c1-2f85-4c4d-b3e5-b512f9b06e4c","hook_event_name":"postToolUse","cursor_version":"3.18.25","workspace_roots":["/tmp/host-test/cursor-workspace"],"user_email":"probe@example.invalid","transcript_path":"/tmp/host-test/cursor-home/.cursor/projects/tmp-host-test-cursor-workspace/agent-transcripts/b60ae0c1-2f85-4c4d-b3e5-b512f9b06e4c/b60ae0c1-2f85-4c4d-b3e5-b512f9b06e4c.jsonl"}},"host":"cursor","kind":"event","process":{"cwd":"/tmp/host-test/cursor-home","entry":"/tmp/host-test/cursor-home/.cursor/plugins/local/host-test/mcp/mcp-host-test-0d229f1b-flight.mjs","pid":59574,"ppid":4119277},"recordedAt":"2026-09-03T08:35:42.734Z","request":{"host":{"source":"native","state":"available","value":{"name":"cursor"}},"invocation":{"kind":"event"},"session":{"source":"native","state":"available","value":{"sessionId":"b60ae0c1-2f85-4c4d-b3e5-b512f9b06e4c"}}},"runtime":"shared-runtime","sequence":10} +{"event":{"canonical":{"event":"tool/before","idempotencyKey":"07c1cdddd4f7fc778b67907282fb02a19e9f7c78df08b002da6d79081e34cb31","observedAt":"2026-09-03T08:35:42.935Z","provenance":{"host":"cursor","hostContractRevision":"2026-08-28","nativeEvent":"preToolUse","source":"native"},"sequence":11},"native":{"conversation_id":"b60ae0c1-2f85-4c4d-b3e5-b512f9b06e4c","generation_id":"d4b2603b-ebfe-45ee-832d-b30d048defbb","model":"default","tool_name":"Write","tool_input":{"file_path":"/tmp/host-test/cursor-workspace/probe-note.txt","content":"host-test\n"},"tool_use_id":"call-e9be6a5e-b7b6-4f51-a276-11f12b6c0e83-5\nfc_11d0162b-5607-95d3-b74e-8ac934bd945a_1","session_id":"b60ae0c1-2f85-4c4d-b3e5-b512f9b06e4c","hook_event_name":"preToolUse","cursor_version":"3.18.25","workspace_roots":["/tmp/host-test/cursor-workspace"],"user_email":"probe@example.invalid","transcript_path":"/tmp/host-test/cursor-home/.cursor/projects/tmp-host-test-cursor-workspace/agent-transcripts/b60ae0c1-2f85-4c4d-b3e5-b512f9b06e4c/b60ae0c1-2f85-4c4d-b3e5-b512f9b06e4c.jsonl"}},"host":"cursor","kind":"event","process":{"cwd":"/tmp/host-test/cursor-home","entry":"/tmp/host-test/cursor-home/.cursor/plugins/local/host-test/mcp/mcp-host-test-0d229f1b-flight.mjs","pid":59574,"ppid":4119277},"recordedAt":"2026-09-03T08:35:42.939Z","request":{"host":{"source":"native","state":"available","value":{"name":"cursor"}},"invocation":{"kind":"event"},"session":{"source":"native","state":"available","value":{"sessionId":"b60ae0c1-2f85-4c4d-b3e5-b512f9b06e4c"}}},"runtime":"shared-runtime","sequence":11} +{"event":{"canonical":{"event":"tool/after","idempotencyKey":"04aa3a3f28b54208dde8f4fc19862c0cf361d7d162133cbb08a4e8a875eeced5","observedAt":"2026-09-03T08:35:43.158Z","provenance":{"host":"cursor","hostContractRevision":"2026-08-28","nativeEvent":"postToolUse","source":"native"},"sequence":12},"native":{"conversation_id":"b60ae0c1-2f85-4c4d-b3e5-b512f9b06e4c","generation_id":"d4b2603b-ebfe-45ee-832d-b30d048defbb","model":"default","tool_name":"Write","tool_input":{"file_path":"/tmp/host-test/cursor-workspace/probe-note.txt","content":"host-test\n"},"tool_output":"{\"file_path\":\"/tmp/host-test/cursor-workspace/probe-note.txt\",\"success\":true}","duration":57.59,"tool_use_id":"call-e9be6a5e-b7b6-4f51-a276-11f12b6c0e83-5\nfc_11d0162b-5607-95d3-b74e-8ac934bd945a_1","session_id":"b60ae0c1-2f85-4c4d-b3e5-b512f9b06e4c","hook_event_name":"postToolUse","cursor_version":"3.18.25","workspace_roots":["/tmp/host-test/cursor-workspace"],"user_email":"probe@example.invalid","transcript_path":"/tmp/host-test/cursor-home/.cursor/projects/tmp-host-test-cursor-workspace/agent-transcripts/b60ae0c1-2f85-4c4d-b3e5-b512f9b06e4c/b60ae0c1-2f85-4c4d-b3e5-b512f9b06e4c.jsonl"}},"host":"cursor","kind":"event","process":{"cwd":"/tmp/host-test/cursor-home","entry":"/tmp/host-test/cursor-home/.cursor/plugins/local/host-test/mcp/mcp-host-test-0d229f1b-flight.mjs","pid":59574,"ppid":4119277},"recordedAt":"2026-09-03T08:35:43.161Z","request":{"host":{"source":"native","state":"available","value":{"name":"cursor"}},"invocation":{"kind":"event"},"session":{"source":"native","state":"available","value":{"sessionId":"b60ae0c1-2f85-4c4d-b3e5-b512f9b06e4c"}}},"runtime":"shared-runtime","sequence":12} +{"event":{"canonical":{"event":"tool/before","idempotencyKey":"4a69f7219a3da1d964036bf3c72dcb03477ed6ecb599282d319d7c2aa03f97a9","observedAt":"2026-09-03T08:35:46.721Z","provenance":{"host":"cursor","hostContractRevision":"2026-08-28","nativeEvent":"preToolUse","source":"native"},"sequence":13},"native":{"conversation_id":"b60ae0c1-2f85-4c4d-b3e5-b512f9b06e4c","generation_id":"d4b2603b-ebfe-45ee-832d-b30d048defbb","model":"default","tool_name":"Shell","tool_input":{"command":"ls /tmp/host-test/cursor-home/.cursor/projects/tmp-host-test-cursor-workspace/ 2>/dev/null; ls /tmp/host-test/cursor-home/.cursor/plugins/local/host-test/ 2>/dev/null; find /tmp/host-test/cursor-home/.cursor -name '*mcp*' 2>/dev/null | head -40","cwd":"","timeout":30000},"tool_use_id":"669ac667-188f-4ae1-b4d1-5f9f26ed6425","cwd":"","session_id":"b60ae0c1-2f85-4c4d-b3e5-b512f9b06e4c","hook_event_name":"preToolUse","cursor_version":"3.18.25","workspace_roots":["/tmp/host-test/cursor-workspace"],"user_email":"probe@example.invalid","transcript_path":"/tmp/host-test/cursor-home/.cursor/projects/tmp-host-test-cursor-workspace/agent-transcripts/b60ae0c1-2f85-4c4d-b3e5-b512f9b06e4c/b60ae0c1-2f85-4c4d-b3e5-b512f9b06e4c.jsonl"}},"host":"cursor","kind":"event","process":{"cwd":"/tmp/host-test/cursor-home","entry":"/tmp/host-test/cursor-home/.cursor/plugins/local/host-test/mcp/mcp-host-test-0d229f1b-flight.mjs","pid":59574,"ppid":4119277},"recordedAt":"2026-09-03T08:35:46.724Z","request":{"host":{"source":"native","state":"available","value":{"name":"cursor"}},"invocation":{"kind":"event"},"session":{"source":"native","state":"available","value":{"sessionId":"b60ae0c1-2f85-4c4d-b3e5-b512f9b06e4c"}}},"runtime":"shared-runtime","sequence":13} +{"event":{"canonical":{"event":"tool/after","idempotencyKey":"9f634009b4e655c43878d5b37ef31a565b42b0877f33b36af6aa638cb4acaaf8","observedAt":"2026-09-03T08:35:52.097Z","provenance":{"host":"cursor","hostContractRevision":"2026-08-28","nativeEvent":"postToolUse","source":"native"},"sequence":14},"native":{"conversation_id":"b60ae0c1-2f85-4c4d-b3e5-b512f9b06e4c","generation_id":"d4b2603b-ebfe-45ee-832d-b30d048defbb","model":"default","tool_name":"Shell","tool_input":{"command":"ls /tmp/host-test/cursor-home/.cursor/projects/tmp-host-test-cursor-workspace/ 2>/dev/null; ls /tmp/host-test/cursor-home/.cursor/plugins/local/host-test/ 2>/dev/null; find /tmp/host-test/cursor-home/.cursor -name '*mcp*' 2>/dev/null | head -40","cwd":"","timeout":30000},"tool_output":"{\"output\":\"agent-transcripts\\ncanvases\\nmcps\\nterminals\\nINSTALL.md\\nhooks\\ninstall.mjs\\nmcp\\nmcp.json\\nskills\\nstate\\n/tmp/host-test/cursor-home/.cursor/projects/tmp-host-test-cursor-workspace/mcps\\n…[+5378 chars]","duration":5203.202,"tool_use_id":"669ac667-188f-4ae1-b4d1-5f9f26ed6425","cwd":"","session_id":"b60ae0c1-2f85-4c4d-b3e5-b512f9b06e4c","hook_event_name":"postToolUse","cursor_version":"3.18.25","workspace_roots":["/tmp/host-test/cursor-workspace"],"user_email":"probe@example.invalid","transcript_path":"/tmp/host-test/cursor-home/.cursor/projects/tmp-host-test-cursor-workspace/agent-transcripts/b60ae0c1-2f85-4c4d-b3e5-b512f9b06e4c/b60ae0c1-2f85-4c4d-b3e5-b512f9b06e4c.jsonl"}},"host":"cursor","kind":"event","process":{"cwd":"/tmp/host-test/cursor-home","entry":"/tmp/host-test/cursor-home/.cursor/plugins/local/host-test/mcp/mcp-host-test-0d229f1b-flight.mjs","pid":59574,"ppid":4119277},"recordedAt":"2026-09-03T08:35:52.100Z","request":{"host":{"source":"native","state":"available","value":{"name":"cursor"}},"invocation":{"kind":"event"},"session":{"source":"native","state":"available","value":{"sessionId":"b60ae0c1-2f85-4c4d-b3e5-b512f9b06e4c"}}},"runtime":"shared-runtime","sequence":14} +{"event":{"canonical":{"event":"tool/before","idempotencyKey":"4ad54f94e440b0236459b9505a546801b010299fbfeee2f7b71c82609ba14385","observedAt":"2026-09-03T08:35:55.268Z","provenance":{"host":"cursor","hostContractRevision":"2026-08-28","nativeEvent":"preToolUse","source":"native"},"sequence":15},"native":{"conversation_id":"b60ae0c1-2f85-4c4d-b3e5-b512f9b06e4c","generation_id":"d4b2603b-ebfe-45ee-832d-b30d048defbb","model":"default","tool_name":"Shell","tool_input":{"command":"find /tmp/host-test/cursor-home/.cursor/projects/tmp-host-test-cursor-workspace/mcps -type f | head -100; ls -la /tmp/host-test/cursor-home/.cursor/projects/tmp-host-test-cursor-workspace/mcps/","cwd":"","timeout":30000},"tool_use_id":"6d8e2fd3-f989-4a15-abe9-83003584d116","cwd":"","session_id":"b60ae0c1-2f85-4c4d-b3e5-b512f9b06e4c","hook_event_name":"preToolUse","cursor_version":"3.18.25","workspace_roots":["/tmp/host-test/cursor-workspace"],"user_email":"probe@example.invalid","transcript_path":"/tmp/host-test/cursor-home/.cursor/projects/tmp-host-test-cursor-workspace/agent-transcripts/b60ae0c1-2f85-4c4d-b3e5-b512f9b06e4c/b60ae0c1-2f85-4c4d-b3e5-b512f9b06e4c.jsonl"}},"host":"cursor","kind":"event","process":{"cwd":"/tmp/host-test/cursor-home","entry":"/tmp/host-test/cursor-home/.cursor/plugins/local/host-test/mcp/mcp-host-test-0d229f1b-flight.mjs","pid":59574,"ppid":4119277},"recordedAt":"2026-09-03T08:35:55.271Z","request":{"host":{"source":"native","state":"available","value":{"name":"cursor"}},"invocation":{"kind":"event"},"session":{"source":"native","state":"available","value":{"sessionId":"b60ae0c1-2f85-4c4d-b3e5-b512f9b06e4c"}}},"runtime":"shared-runtime","sequence":15} +{"event":{"canonical":{"event":"tool/after","idempotencyKey":"bd67c20e89db05bd891645bda062e4cd84b62c08e03bb4f60b5f22aded667d4b","observedAt":"2026-09-03T08:36:00.577Z","provenance":{"host":"cursor","hostContractRevision":"2026-08-28","nativeEvent":"postToolUse","source":"native"},"sequence":16},"native":{"conversation_id":"b60ae0c1-2f85-4c4d-b3e5-b512f9b06e4c","generation_id":"d4b2603b-ebfe-45ee-832d-b30d048defbb","model":"default","tool_name":"Shell","tool_input":{"command":"find /tmp/host-test/cursor-home/.cursor/projects/tmp-host-test-cursor-workspace/mcps -type f | head -100; ls -la /tmp/host-test/cursor-home/.cursor/projects/tmp-host-test-cursor-workspace/mcps/","cwd":"","timeout":30000},"tool_output":"{\"output\":\"/tmp/host-test/cursor-home/.cursor/projects/tmp-host-test-cursor-workspace/mcps/plugin-xclaude-plugin-xc-all/tools/xcode_clean.json\\n/tmp/host-test/cursor-home/.cursor/projects/tmp-host-tes…[+14850 chars]","duration":5151.012,"tool_use_id":"6d8e2fd3-f989-4a15-abe9-83003584d116","cwd":"","session_id":"b60ae0c1-2f85-4c4d-b3e5-b512f9b06e4c","hook_event_name":"postToolUse","cursor_version":"3.18.25","workspace_roots":["/tmp/host-test/cursor-workspace"],"user_email":"probe@example.invalid","transcript_path":"/tmp/host-test/cursor-home/.cursor/projects/tmp-host-test-cursor-workspace/agent-transcripts/b60ae0c1-2f85-4c4d-b3e5-b512f9b06e4c/b60ae0c1-2f85-4c4d-b3e5-b512f9b06e4c.jsonl"}},"host":"cursor","kind":"event","process":{"cwd":"/tmp/host-test/cursor-home","entry":"/tmp/host-test/cursor-home/.cursor/plugins/local/host-test/mcp/mcp-host-test-0d229f1b-flight.mjs","pid":59574,"ppid":4119277},"recordedAt":"2026-09-03T08:36:00.581Z","request":{"host":{"source":"native","state":"available","value":{"name":"cursor"}},"invocation":{"kind":"event"},"session":{"source":"native","state":"available","value":{"sessionId":"b60ae0c1-2f85-4c4d-b3e5-b512f9b06e4c"}}},"runtime":"shared-runtime","sequence":16} +{"event":{"canonical":{"event":"tool/before","idempotencyKey":"c0b44a00c565d2b4deb49363d902568a06b86377652165876d99a5cd6d1ec905","observedAt":"2026-09-03T08:36:08.168Z","provenance":{"host":"cursor","hostContractRevision":"2026-08-28","nativeEvent":"preToolUse","source":"native"},"sequence":25},"native":{"conversation_id":"b60ae0c1-2f85-4c4d-b3e5-b512f9b06e4c","generation_id":"d4b2603b-ebfe-45ee-832d-b30d048defbb","model":"default","tool_name":"Shell","tool_input":{"command":"# Inspect how MCP tools are typically invoked; check for call patterns in docs or harness\nls /tmp/host-test/cursor-home/.cursor/projects/tmp-host-test-cursor-workspace/mcps/plugin-host-test-host-test/\ncat /tmp/host-test/cursor-home/.cursor/plugins/local/host-test/mcp.json\n# Also check state for existing log path\nls -la /tmp/host-test/cursor-home/.cursor/plugins/local/host-test/state/ 2>/dev/null\nf…[+120 chars]","cwd":"","timeout":30000},"tool_use_id":"9b0373d5-d0c0-489b-9177-9eed0f6855a7","cwd":"","session_id":"b60ae0c1-2f85-4c4d-b3e5-b512f9b06e4c","hook_event_name":"preToolUse","cursor_version":"3.18.25","workspace_roots":["/tmp/host-test/cursor-workspace"],"user_email":"probe@example.invalid","transcript_path":"/tmp/host-test/cursor-home/.cursor/projects/tmp-host-test-cursor-workspace/agent-transcripts/b60ae0c1-2f85-4c4d-b3e5-b512f9b06e4c/b60ae0c1-2f85-4c4d-b3e5-b512f9b06e4c.jsonl"}},"host":"cursor","kind":"event","process":{"cwd":"/tmp/host-test/cursor-home","entry":"/tmp/host-test/cursor-home/.cursor/plugins/local/host-test/mcp/mcp-host-test-0d229f1b-flight.mjs","pid":59574,"ppid":4119277},"recordedAt":"2026-09-03T08:36:08.170Z","request":{"host":{"source":"native","state":"available","value":{"name":"cursor"}},"invocation":{"kind":"event"},"session":{"source":"native","state":"available","value":{"sessionId":"b60ae0c1-2f85-4c4d-b3e5-b512f9b06e4c"}}},"runtime":"shared-runtime","sequence":25} +{"event":{"canonical":{"event":"tool/after","idempotencyKey":"81be984658ceb4f9999362ce5076b1b5eee1428ae6401def61701218db5044c9","observedAt":"2026-09-03T08:36:13.477Z","provenance":{"host":"cursor","hostContractRevision":"2026-08-28","nativeEvent":"postToolUse","source":"native"},"sequence":26},"native":{"conversation_id":"b60ae0c1-2f85-4c4d-b3e5-b512f9b06e4c","generation_id":"d4b2603b-ebfe-45ee-832d-b30d048defbb","model":"default","tool_name":"Shell","tool_input":{"command":"# Inspect how MCP tools are typically invoked; check for call patterns in docs or harness\nls /tmp/host-test/cursor-home/.cursor/projects/tmp-host-test-cursor-workspace/mcps/plugin-host-test-host-test/\ncat /tmp/host-test/cursor-home/.cursor/plugins/local/host-test/mcp.json\n# Also check state for existing log path\nls -la /tmp/host-test/cursor-home/.cursor/plugins/local/host-test/state/ 2>/dev/null\nf…[+120 chars]","cwd":"","timeout":30000},"tool_output":"{\"output\":\"SERVER_METADATA.json\\nresources\\ntools\\n{\\\"mcpServers\\\":{\\\"host-test\\\":{\\\"args\\\":[\\\"${CURSOR_PLUGIN_ROOT}/mcp/mcp-host-test-0d229f1b.mjs\\\"],\\\"command\\\":\\\"node\\\",\\\"env\\\":{\\\"AGENT_BUNDLE_PLUG…[+1288 chars]","duration":5139.924,"tool_use_id":"9b0373d5-d0c0-489b-9177-9eed0f6855a7","cwd":"","session_id":"b60ae0c1-2f85-4c4d-b3e5-b512f9b06e4c","hook_event_name":"postToolUse","cursor_version":"3.18.25","workspace_roots":["/tmp/host-test/cursor-workspace"],"user_email":"probe@example.invalid","transcript_path":"/tmp/host-test/cursor-home/.cursor/projects/tmp-host-test-cursor-workspace/agent-transcripts/b60ae0c1-2f85-4c4d-b3e5-b512f9b06e4c/b60ae0c1-2f85-4c4d-b3e5-b512f9b06e4c.jsonl"}},"host":"cursor","kind":"event","process":{"cwd":"/tmp/host-test/cursor-home","entry":"/tmp/host-test/cursor-home/.cursor/plugins/local/host-test/mcp/mcp-host-test-0d229f1b-flight.mjs","pid":59574,"ppid":4119277},"recordedAt":"2026-09-03T08:36:13.480Z","request":{"host":{"source":"native","state":"available","value":{"name":"cursor"}},"invocation":{"kind":"event"},"session":{"source":"native","state":"available","value":{"sessionId":"b60ae0c1-2f85-4c4d-b3e5-b512f9b06e4c"}}},"runtime":"shared-runtime","sequence":26} +{"event":{"canonical":{"event":"tool/before","idempotencyKey":"1d751d49cc214e7db1f7c80dac766b2631f46b178075e76525d4790a332ad7cd","observedAt":"2026-09-03T08:36:23.281Z","provenance":{"host":"cursor","hostContractRevision":"2026-08-28","nativeEvent":"preToolUse","source":"native"},"sequence":29},"native":{"conversation_id":"b60ae0c1-2f85-4c4d-b3e5-b512f9b06e4c","generation_id":"d4b2603b-ebfe-45ee-832d-b30d048defbb","model":"default","tool_name":"Shell","tool_input":{"command":"# Look for CallMcpTool usage patterns or agent transcripts that show how MCP was called\nrg -l \"CallMcpTool|plugin-host-test\" /tmp/host-test/cursor-home/.cursor/projects/tmp-host-test-cursor-workspace/agent-transcripts 2>/dev/null | head -5\nrg -n \"CallMcpTool\" /tmp/host-test/cursor-home/.cursor/skills-cursor --glob '*.md' 2>/dev/null | head -20\n# Check INSTALL for how probe expects to be used\nhead …[+567 chars]","cwd":"","timeout":30000},"tool_use_id":"7379f254-832f-4473-a90d-9471774136d8","cwd":"","session_id":"b60ae0c1-2f85-4c4d-b3e5-b512f9b06e4c","hook_event_name":"preToolUse","cursor_version":"3.18.25","workspace_roots":["/tmp/host-test/cursor-workspace"],"user_email":"probe@example.invalid","transcript_path":"/tmp/host-test/cursor-home/.cursor/projects/tmp-host-test-cursor-workspace/agent-transcripts/b60ae0c1-2f85-4c4d-b3e5-b512f9b06e4c/b60ae0c1-2f85-4c4d-b3e5-b512f9b06e4c.jsonl"}},"host":"cursor","kind":"event","process":{"cwd":"/tmp/host-test/cursor-home","entry":"/tmp/host-test/cursor-home/.cursor/plugins/local/host-test/mcp/mcp-host-test-0d229f1b-flight.mjs","pid":59574,"ppid":4119277},"recordedAt":"2026-09-03T08:36:23.284Z","request":{"host":{"source":"native","state":"available","value":{"name":"cursor"}},"invocation":{"kind":"event"},"session":{"source":"native","state":"available","value":{"sessionId":"b60ae0c1-2f85-4c4d-b3e5-b512f9b06e4c"}}},"runtime":"shared-runtime","sequence":29} +{"event":{"canonical":{"event":"tool/after","idempotencyKey":"af339eacd09999679dc16ec9a4fe1e30244a1b1d0093331f5df5a4fcc186e8ff","observedAt":"2026-09-03T08:36:50.466Z","provenance":{"host":"cursor","hostContractRevision":"2026-08-28","nativeEvent":"postToolUse","source":"native"},"sequence":30},"native":{"conversation_id":"b60ae0c1-2f85-4c4d-b3e5-b512f9b06e4c","generation_id":"d4b2603b-ebfe-45ee-832d-b30d048defbb","model":"default","tool_name":"Shell","tool_input":{"command":"# Look for CallMcpTool usage patterns or agent transcripts that show how MCP was called\nrg -l \"CallMcpTool|plugin-host-test\" /tmp/host-test/cursor-home/.cursor/projects/tmp-host-test-cursor-workspace/agent-transcripts 2>/dev/null | head -5\nrg -n \"CallMcpTool\" /tmp/host-test/cursor-home/.cursor/skills-cursor --glob '*.md' 2>/dev/null | head -20\n# Check INSTALL for how probe expects to be used\nhead …[+567 chars]","cwd":"","timeout":30000},"tool_output":"{\"output\":\"# Install host-test\\n\\nProbe what each agent host sends to plugin hooks and MCP servers: raw payloads, request context, lineage.\\n\\nVersion: `1.0.0`\\n\\nRun these commands from this bundle d…[+1734 chars]","duration":27006.185,"tool_use_id":"7379f254-832f-4473-a90d-9471774136d8","cwd":"","session_id":"b60ae0c1-2f85-4c4d-b3e5-b512f9b06e4c","hook_event_name":"postToolUse","cursor_version":"3.18.25","workspace_roots":["/tmp/host-test/cursor-workspace"],"user_email":"probe@example.invalid","transcript_path":"/tmp/host-test/cursor-home/.cursor/projects/tmp-host-test-cursor-workspace/agent-transcripts/b60ae0c1-2f85-4c4d-b3e5-b512f9b06e4c/b60ae0c1-2f85-4c4d-b3e5-b512f9b06e4c.jsonl"}},"host":"cursor","kind":"event","process":{"cwd":"/tmp/host-test/cursor-home","entry":"/tmp/host-test/cursor-home/.cursor/plugins/local/host-test/mcp/mcp-host-test-0d229f1b-flight.mjs","pid":59574,"ppid":4119277},"recordedAt":"2026-09-03T08:36:50.470Z","request":{"host":{"source":"native","state":"available","value":{"name":"cursor"}},"invocation":{"kind":"event"},"session":{"source":"native","state":"available","value":{"sessionId":"b60ae0c1-2f85-4c4d-b3e5-b512f9b06e4c"}}},"runtime":"shared-runtime","sequence":30} +{"event":{"canonical":{"event":"tool/before","idempotencyKey":"733fe88a8551968a6751c980c739d2e1558e323e038d8a8c359030c52491cc83","observedAt":"2026-09-03T08:36:57.600Z","provenance":{"host":"cursor","hostContractRevision":"2026-08-28","nativeEvent":"preToolUse","source":"native"},"sequence":31},"native":{"conversation_id":"b60ae0c1-2f85-4c4d-b3e5-b512f9b06e4c","generation_id":"d4b2603b-ebfe-45ee-832d-b30d048defbb","model":"default","tool_name":"Shell","tool_input":{"command":"# Check agent transcripts for how previous probes called MCP\nls /tmp/host-test/cursor-home/.cursor/projects/tmp-host-test-cursor-workspace/agent-transcripts/ 2>/dev/null | head\n# Also check if there's an mcp invoke CLI\nwhich cursor 2>/dev/null; which mcp 2>/dev/null\n# Look at recent captures to see log.path format from dump\ntail -5 /tmp/host-test/cursor/log/captures.ndjson 2>/dev/null | head -c 20…[+412 chars]","cwd":"","timeout":30000},"tool_use_id":"a0bffe3f-776f-4e56-b6de-a62c301ef63d","cwd":"","session_id":"b60ae0c1-2f85-4c4d-b3e5-b512f9b06e4c","hook_event_name":"preToolUse","cursor_version":"3.18.25","workspace_roots":["/tmp/host-test/cursor-workspace"],"user_email":"probe@example.invalid","transcript_path":"/tmp/host-test/cursor-home/.cursor/projects/tmp-host-test-cursor-workspace/agent-transcripts/b60ae0c1-2f85-4c4d-b3e5-b512f9b06e4c/b60ae0c1-2f85-4c4d-b3e5-b512f9b06e4c.jsonl"}},"host":"cursor","kind":"event","process":{"cwd":"/tmp/host-test/cursor-home","entry":"/tmp/host-test/cursor-home/.cursor/plugins/local/host-test/mcp/mcp-host-test-0d229f1b-flight.mjs","pid":59574,"ppid":4119277},"recordedAt":"2026-09-03T08:36:57.604Z","request":{"host":{"source":"native","state":"available","value":{"name":"cursor"}},"invocation":{"kind":"event"},"session":{"source":"native","state":"available","value":{"sessionId":"b60ae0c1-2f85-4c4d-b3e5-b512f9b06e4c"}}},"runtime":"shared-runtime","sequence":31} +{"event":{"canonical":{"event":"tool/after","idempotencyKey":"4a9d2d9dd8c5265c2c3d9dad17e2ca098b3d1c686b1b4254d02fb26ca14436a4","observedAt":"2026-09-03T08:37:03.165Z","provenance":{"host":"cursor","hostContractRevision":"2026-08-28","nativeEvent":"postToolUse","source":"native"},"sequence":32},"native":{"conversation_id":"b60ae0c1-2f85-4c4d-b3e5-b512f9b06e4c","generation_id":"d4b2603b-ebfe-45ee-832d-b30d048defbb","model":"default","tool_name":"Shell","tool_input":{"command":"# Check agent transcripts for how previous probes called MCP\nls /tmp/host-test/cursor-home/.cursor/projects/tmp-host-test-cursor-workspace/agent-transcripts/ 2>/dev/null | head\n# Also check if there's an mcp invoke CLI\nwhich cursor 2>/dev/null; which mcp 2>/dev/null\n# Look at recent captures to see log.path format from dump\ntail -5 /tmp/host-test/cursor/log/captures.ndjson 2>/dev/null | head -c 20…[+412 chars]","cwd":"","timeout":30000},"tool_output":"{\"output\":\"b60ae0c1-2f85-4c4d-b3e5-b512f9b06e4c\\n/home/user/.local/bin/cursor\\n{\\\"env\\\":{\\\"names\\\":[\\\"AGENT_BUNDLE_PLUGIN_ROOT\\\",\\\"HOST_TEST_LOG_DIR\\\"]},\\\"event\\\":{\\\"canonical\\\":{\\\"event\\\":\\\"tool/befo…[+8699 chars]","duration":5306.283,"tool_use_id":"a0bffe3f-776f-4e56-b6de-a62c301ef63d","cwd":"","session_id":"b60ae0c1-2f85-4c4d-b3e5-b512f9b06e4c","hook_event_name":"postToolUse","cursor_version":"3.18.25","workspace_roots":["/tmp/host-test/cursor-workspace"],"user_email":"probe@example.invalid","transcript_path":"/tmp/host-test/cursor-home/.cursor/projects/tmp-host-test-cursor-workspace/agent-transcripts/b60ae0c1-2f85-4c4d-b3e5-b512f9b06e4c/b60ae0c1-2f85-4c4d-b3e5-b512f9b06e4c.jsonl"}},"host":"cursor","kind":"event","process":{"cwd":"/tmp/host-test/cursor-home","entry":"/tmp/host-test/cursor-home/.cursor/plugins/local/host-test/mcp/mcp-host-test-0d229f1b-flight.mjs","pid":59574,"ppid":4119277},"recordedAt":"2026-09-03T08:37:03.169Z","request":{"host":{"source":"native","state":"available","value":{"name":"cursor"}},"invocation":{"kind":"event"},"session":{"source":"native","state":"available","value":{"sessionId":"b60ae0c1-2f85-4c4d-b3e5-b512f9b06e4c"}}},"runtime":"shared-runtime","sequence":32} +{"event":{"canonical":{"event":"tool/before","idempotencyKey":"93fbfaec1bd9d4027b5545efd90d93c1abd3a04b13402e0e8c068708489f2498","observedAt":"2026-09-03T08:37:21.570Z","provenance":{"host":"cursor","hostContractRevision":"2026-08-28","nativeEvent":"preToolUse","source":"native"},"sequence":41},"native":{"conversation_id":"b60ae0c1-2f85-4c4d-b3e5-b512f9b06e4c","generation_id":"d4b2603b-ebfe-45ee-832d-b30d048defbb","model":"default","tool_name":"Shell","tool_input":{"command":"# Check STATUS for host-test MCP servers; look for how tools get exposed to the model\nls /tmp/host-test/cursor-home/.cursor/projects/tmp-host-test-cursor-workspace/mcps/plugin-host-test-host-test/\nls /tmp/host-test/cursor-home/.cursor/projects/tmp-host-test-cursor-workspace/mcps/plugin-host-test-host-test-raw/\n# Check if there's a transport / socket to talk to running MCP\nrg -n \"log\\.path|HOST_TES…[+544 chars]","cwd":"","timeout":30000},"tool_use_id":"849cfa2e-59f3-4230-9946-47795913e861","cwd":"","session_id":"b60ae0c1-2f85-4c4d-b3e5-b512f9b06e4c","hook_event_name":"preToolUse","cursor_version":"3.18.25","workspace_roots":["/tmp/host-test/cursor-workspace"],"user_email":"probe@example.invalid","transcript_path":"/tmp/host-test/cursor-home/.cursor/projects/tmp-host-test-cursor-workspace/agent-transcripts/b60ae0c1-2f85-4c4d-b3e5-b512f9b06e4c/b60ae0c1-2f85-4c4d-b3e5-b512f9b06e4c.jsonl"}},"host":"cursor","kind":"event","process":{"cwd":"/tmp/host-test/cursor-home","entry":"/tmp/host-test/cursor-home/.cursor/plugins/local/host-test/mcp/mcp-host-test-0d229f1b-flight.mjs","pid":59574,"ppid":4119277},"recordedAt":"2026-09-03T08:37:21.574Z","request":{"host":{"source":"native","state":"available","value":{"name":"cursor"}},"invocation":{"kind":"event"},"session":{"source":"native","state":"available","value":{"sessionId":"b60ae0c1-2f85-4c4d-b3e5-b512f9b06e4c"}}},"runtime":"shared-runtime","sequence":41} +{"event":{"canonical":{"event":"tool/after","idempotencyKey":"b3a62ee39987ebda2e4850bb8ec9bafe72e0e4ec0fdaa8625c2f74bac564aa56","observedAt":"2026-09-03T08:37:27.076Z","provenance":{"host":"cursor","hostContractRevision":"2026-08-28","nativeEvent":"postToolUse","source":"native"},"sequence":42},"native":{"conversation_id":"b60ae0c1-2f85-4c4d-b3e5-b512f9b06e4c","generation_id":"d4b2603b-ebfe-45ee-832d-b30d048defbb","model":"default","tool_name":"Shell","tool_input":{"command":"# Check STATUS for host-test MCP servers; look for how tools get exposed to the model\nls /tmp/host-test/cursor-home/.cursor/projects/tmp-host-test-cursor-workspace/mcps/plugin-host-test-host-test/\nls /tmp/host-test/cursor-home/.cursor/projects/tmp-host-test-cursor-workspace/mcps/plugin-host-test-host-test-raw/\n# Check if there's a transport / socket to talk to running MCP\nrg -n \"log\\.path|HOST_TES…[+544 chars]","cwd":"","timeout":30000},"tool_output":"{\"output\":\"SERVER_METADATA.json\\nresources\\ntools\\nSERVER_METADATA.json\\ntools\\n108049:const LOG_DIR_ENV = 'HOST_TEST_LOG_DIR';\\n108050:const LOG_FILE_NAME = 'captures.ndjson';\\n108073: sou…[+14372 chars]","duration":5312.259,"tool_use_id":"849cfa2e-59f3-4230-9946-47795913e861","cwd":"","session_id":"b60ae0c1-2f85-4c4d-b3e5-b512f9b06e4c","hook_event_name":"postToolUse","cursor_version":"3.18.25","workspace_roots":["/tmp/host-test/cursor-workspace"],"user_email":"probe@example.invalid","transcript_path":"/tmp/host-test/cursor-home/.cursor/projects/tmp-host-test-cursor-workspace/agent-transcripts/b60ae0c1-2f85-4c4d-b3e5-b512f9b06e4c/b60ae0c1-2f85-4c4d-b3e5-b512f9b06e4c.jsonl"}},"host":"cursor","kind":"event","process":{"cwd":"/tmp/host-test/cursor-home","entry":"/tmp/host-test/cursor-home/.cursor/plugins/local/host-test/mcp/mcp-host-test-0d229f1b-flight.mjs","pid":59574,"ppid":4119277},"recordedAt":"2026-09-03T08:37:27.079Z","request":{"host":{"source":"native","state":"available","value":{"name":"cursor"}},"invocation":{"kind":"event"},"session":{"source":"native","state":"available","value":{"sessionId":"b60ae0c1-2f85-4c4d-b3e5-b512f9b06e4c"}}},"runtime":"shared-runtime","sequence":42} +{"event":{"canonical":{"event":"tool/before","idempotencyKey":"636c5bcacf6f1f58b47b1cb2a94891455514c125c3065209cdf3e93a908f8cd2","observedAt":"2026-09-03T08:37:32.452Z","provenance":{"host":"cursor","hostContractRevision":"2026-08-28","nativeEvent":"preToolUse","source":"native"},"sequence":43},"native":{"conversation_id":"b60ae0c1-2f85-4c4d-b3e5-b512f9b06e4c","generation_id":"d4b2603b-ebfe-45ee-832d-b30d048defbb","model":"default","tool_name":"Shell","tool_input":{"command":"# Search for CallMcpTool schema in cursor app resources\nrg -l \"CallMcpTool\" /usr/share/cursor/resources/app 2>/dev/null | head -10\nrg -l \"CallMcpTool\" /tmp/host-test --glob '!**/node_modules/**' 2>/dev/null | head -20\n# Also check if there's an mcp invoke via cursor CLI\ncursor --help 2>&1 | head -40\nls /tmp/host-test/*.mjs 2>/dev/null\nhead -50 /tmp/host-test/cdp.mjs 2>/dev/null\n","cwd":"","timeout":30000},"tool_use_id":"1b158dd5-f492-42f4-88ca-ae41fccccbc8","cwd":"","session_id":"b60ae0c1-2f85-4c4d-b3e5-b512f9b06e4c","hook_event_name":"preToolUse","cursor_version":"3.18.25","workspace_roots":["/tmp/host-test/cursor-workspace"],"user_email":"probe@example.invalid","transcript_path":"/tmp/host-test/cursor-home/.cursor/projects/tmp-host-test-cursor-workspace/agent-transcripts/b60ae0c1-2f85-4c4d-b3e5-b512f9b06e4c/b60ae0c1-2f85-4c4d-b3e5-b512f9b06e4c.jsonl"}},"host":"cursor","kind":"event","process":{"cwd":"/tmp/host-test/cursor-home","entry":"/tmp/host-test/cursor-home/.cursor/plugins/local/host-test/mcp/mcp-host-test-0d229f1b-flight.mjs","pid":59574,"ppid":4119277},"recordedAt":"2026-09-03T08:37:32.455Z","request":{"host":{"source":"native","state":"available","value":{"name":"cursor"}},"invocation":{"kind":"event"},"session":{"source":"native","state":"available","value":{"sessionId":"b60ae0c1-2f85-4c4d-b3e5-b512f9b06e4c"}}},"runtime":"shared-runtime","sequence":43} +{"event":{"canonical":{"event":"tool/after","idempotencyKey":"897447adb5038391b15a74cd8d5c9c24570284a91c1561d646bff8ce7629b340","observedAt":"2026-09-03T08:38:02.768Z","provenance":{"host":"cursor","hostContractRevision":"2026-08-28","nativeEvent":"postToolUse","source":"native"},"sequence":1},"native":{"conversation_id":"b60ae0c1-2f85-4c4d-b3e5-b512f9b06e4c","generation_id":"d4b2603b-ebfe-45ee-832d-b30d048defbb","model":"default","tool_name":"Shell","tool_input":{"command":"# Search for CallMcpTool schema in cursor app resources\nrg -l \"CallMcpTool\" /usr/share/cursor/resources/app 2>/dev/null | head -10\nrg -l \"CallMcpTool\" /tmp/host-test --glob '!**/node_modules/**' 2>/dev/null | head -20\n# Also check if there's an mcp invoke via cursor CLI\ncursor --help 2>&1 | head -40\nls /tmp/host-test/*.mjs 2>/dev/null\nhead -50 /tmp/host-test/cdp.mjs 2>/dev/null\n","cwd":"","timeout":30000},"tool_output":"{\"output\":\"/usr/share/cursor/resources/app/out/vs/workbench/workbench.glass.main.js\\n/usr/share/cursor/resources/app/extensions/cursor-commits/dist/main.js\\n/usr/share/cursor/resources/app/extensions/…[+634 chars]","duration":30067.358,"tool_use_id":"1b158dd5-f492-42f4-88ca-ae41fccccbc8","cwd":"","session_id":"b60ae0c1-2f85-4c4d-b3e5-b512f9b06e4c","hook_event_name":"postToolUse","cursor_version":"3.18.25","workspace_roots":["/tmp/host-test/cursor-workspace"],"user_email":"probe@example.invalid","transcript_path":"/tmp/host-test/cursor-home/.cursor/projects/tmp-host-test-cursor-workspace/agent-transcripts/b60ae0c1-2f85-4c4d-b3e5-b512f9b06e4c/b60ae0c1-2f85-4c4d-b3e5-b512f9b06e4c.jsonl"}},"host":"cursor","kind":"event","process":{"cwd":"/tmp/host-test/cursor-home","entry":"/tmp/host-test/cursor-home/.cursor/plugins/local/host-test/mcp/mcp-host-test-0d229f1b-flight.mjs","pid":197313,"ppid":4119277},"recordedAt":"2026-09-03T08:38:02.874Z","request":{"host":{"source":"native","state":"available","value":{"name":"cursor"}},"invocation":{"kind":"event"},"session":{"source":"native","state":"available","value":{"sessionId":"b60ae0c1-2f85-4c4d-b3e5-b512f9b06e4c"}}},"runtime":"shared-runtime","sequence":1} +{"event":{"canonical":{"event":"tool/before","idempotencyKey":"6d8154a7dd17005f941bb53a35448c9a1e83f9dc41496cc38f91835a884c189e","observedAt":"2026-09-03T08:38:05.578Z","provenance":{"host":"cursor","hostContractRevision":"2026-08-28","nativeEvent":"preToolUse","source":"native"},"sequence":3},"native":{"conversation_id":"b60ae0c1-2f85-4c4d-b3e5-b512f9b06e4c","generation_id":"d4b2603b-ebfe-45ee-832d-b30d048defbb","model":"default","tool_name":"Shell","tool_input":{"command":"rg -o '.{0,80}CallMcpTool.{0,120}' /usr/share/cursor/resources/app/extensions/cursor-agent-worker/dist/main.js 2>/dev/null | head -20\nrg -o '.{0,80}CallMcpTool.{0,120}' /usr/share/cursor/resources/app/extensions/cursor-local-agent-runtime/dist/main.js 2>/dev/null | head -20\n# Also look at mcp tool naming patterns in agent worker\nrg -o 'mcp_[a-zA-Z0-9_-]{5,60}' /usr/share/cursor/resources/app/exten…[+72 chars]","cwd":"","timeout":30000},"tool_use_id":"faf37053-3ee5-45b2-aca9-ce1be27c51cf","cwd":"","session_id":"b60ae0c1-2f85-4c4d-b3e5-b512f9b06e4c","hook_event_name":"preToolUse","cursor_version":"3.18.25","workspace_roots":["/tmp/host-test/cursor-workspace"],"user_email":"probe@example.invalid","transcript_path":"/tmp/host-test/cursor-home/.cursor/projects/tmp-host-test-cursor-workspace/agent-transcripts/b60ae0c1-2f85-4c4d-b3e5-b512f9b06e4c/b60ae0c1-2f85-4c4d-b3e5-b512f9b06e4c.jsonl"}},"host":"cursor","kind":"event","process":{"cwd":"/tmp/host-test/cursor-home","entry":"/tmp/host-test/cursor-home/.cursor/plugins/local/host-test/mcp/mcp-host-test-0d229f1b-flight.mjs","pid":197313,"ppid":4119277},"recordedAt":"2026-09-03T08:38:05.584Z","request":{"host":{"source":"native","state":"available","value":{"name":"cursor"}},"invocation":{"kind":"event"},"session":{"source":"native","state":"available","value":{"sessionId":"b60ae0c1-2f85-4c4d-b3e5-b512f9b06e4c"}}},"runtime":"shared-runtime","sequence":3} +{"event":{"canonical":{"event":"tool/after","idempotencyKey":"f6df0582b6d17ec71fdaa79fdb5e663c5996a1bed0b8d78f3af213df3d31e774","observedAt":"2026-09-03T08:38:11.005Z","provenance":{"host":"cursor","hostContractRevision":"2026-08-28","nativeEvent":"postToolUse","source":"native"},"sequence":17},"native":{"conversation_id":"b60ae0c1-2f85-4c4d-b3e5-b512f9b06e4c","generation_id":"d4b2603b-ebfe-45ee-832d-b30d048defbb","model":"default","tool_name":"Shell","tool_input":{"command":"rg -o '.{0,80}CallMcpTool.{0,120}' /usr/share/cursor/resources/app/extensions/cursor-agent-worker/dist/main.js 2>/dev/null | head -20\nrg -o '.{0,80}CallMcpTool.{0,120}' /usr/share/cursor/resources/app/extensions/cursor-local-agent-runtime/dist/main.js 2>/dev/null | head -20\n# Also look at mcp tool naming patterns in agent worker\nrg -o 'mcp_[a-zA-Z0-9_-]{5,60}' /usr/share/cursor/resources/app/exten…[+72 chars]","cwd":"","timeout":30000},"tool_output":"{\"output\":\"ons\\\",kind:\\\"map\\\",K:9,V:{kind:\\\"scalar\\\",T:9}}]),yf=Qe.makeMessageType(\\\"aiserver.v1.CallMcpToolParams\\\",()=>[{no:1,name:\\\"server\\\",kind:\\\"scalar\\\",T:9},{no:2,name:\\\"tool_name\\\",kind:\\\"sca…[+4715 chars]","duration":5245.65,"tool_use_id":"faf37053-3ee5-45b2-aca9-ce1be27c51cf","cwd":"","session_id":"b60ae0c1-2f85-4c4d-b3e5-b512f9b06e4c","hook_event_name":"postToolUse","cursor_version":"3.18.25","workspace_roots":["/tmp/host-test/cursor-workspace"],"user_email":"probe@example.invalid","transcript_path":"/tmp/host-test/cursor-home/.cursor/projects/tmp-host-test-cursor-workspace/agent-transcripts/b60ae0c1-2f85-4c4d-b3e5-b512f9b06e4c/b60ae0c1-2f85-4c4d-b3e5-b512f9b06e4c.jsonl"}},"host":"cursor","kind":"event","process":{"cwd":"/tmp/host-test/cursor-home","entry":"/tmp/host-test/cursor-home/.cursor/plugins/local/host-test/mcp/mcp-host-test-0d229f1b-flight.mjs","pid":197313,"ppid":4119277},"recordedAt":"2026-09-03T08:38:11.008Z","request":{"host":{"source":"native","state":"available","value":{"name":"cursor"}},"invocation":{"kind":"event"},"session":{"source":"native","state":"available","value":{"sessionId":"b60ae0c1-2f85-4c4d-b3e5-b512f9b06e4c"}}},"runtime":"shared-runtime","sequence":17} +{"event":{"canonical":{"event":"tool/before","idempotencyKey":"d12d197372513282463f2e0841c262e923ebe77c690f23b0942f4faf0e7ee89f","observedAt":"2026-09-03T08:38:16.365Z","provenance":{"host":"cursor","hostContractRevision":"2026-08-28","nativeEvent":"preToolUse","source":"native"},"sequence":18},"native":{"conversation_id":"b60ae0c1-2f85-4c4d-b3e5-b512f9b06e4c","generation_id":"d4b2603b-ebfe-45ee-832d-b30d048defbb","model":"default","tool_name":"Shell","tool_input":{"command":"# Extract CallMcpTool parameter names from the UI prompt text\nrg -o 'CallMcpTool.{0,500}' /usr/share/cursor/resources/app/extensions/cursor-agent-worker/dist/main.js 2>/dev/null | rg -o 'server[^,]{0,40}|toolName|tool_name|arguments|tool_args' | head -40\n# Also look for the tool definition JSON schema text\nrg -o 'name:\"CallMcpTool\".{0,800}' /usr/share/cursor/resources/app/extensions/cursor-agent-w…[+338 chars]","cwd":"","timeout":30000},"tool_use_id":"e1f4b8fe-9707-47ce-bbe4-08d4dc4c414a","cwd":"","session_id":"b60ae0c1-2f85-4c4d-b3e5-b512f9b06e4c","hook_event_name":"preToolUse","cursor_version":"3.18.25","workspace_roots":["/tmp/host-test/cursor-workspace"],"user_email":"probe@example.invalid","transcript_path":"/tmp/host-test/cursor-home/.cursor/projects/tmp-host-test-cursor-workspace/agent-transcripts/b60ae0c1-2f85-4c4d-b3e5-b512f9b06e4c/b60ae0c1-2f85-4c4d-b3e5-b512f9b06e4c.jsonl"}},"host":"cursor","kind":"event","process":{"cwd":"/tmp/host-test/cursor-home","entry":"/tmp/host-test/cursor-home/.cursor/plugins/local/host-test/mcp/mcp-host-test-0d229f1b-flight.mjs","pid":197313,"ppid":4119277},"recordedAt":"2026-09-03T08:38:16.368Z","request":{"host":{"source":"native","state":"available","value":{"name":"cursor"}},"invocation":{"kind":"event"},"session":{"source":"native","state":"available","value":{"sessionId":"b60ae0c1-2f85-4c4d-b3e5-b512f9b06e4c"}}},"runtime":"shared-runtime","sequence":18} +{"event":{"canonical":{"event":"tool/after","idempotencyKey":"aa40a3e1900065012ee7523464c50cb5eea376300da3d6235aa14fd2de8ac9be","observedAt":"2026-09-03T08:38:21.760Z","provenance":{"host":"cursor","hostContractRevision":"2026-08-28","nativeEvent":"postToolUse","source":"native"},"sequence":19},"native":{"conversation_id":"b60ae0c1-2f85-4c4d-b3e5-b512f9b06e4c","generation_id":"d4b2603b-ebfe-45ee-832d-b30d048defbb","model":"default","tool_name":"Shell","tool_input":{"command":"# Extract CallMcpTool parameter names from the UI prompt text\nrg -o 'CallMcpTool.{0,500}' /usr/share/cursor/resources/app/extensions/cursor-agent-worker/dist/main.js 2>/dev/null | rg -o 'server[^,]{0,40}|toolName|tool_name|arguments|tool_args' | head -40\n# Also look for the tool definition JSON schema text\nrg -o 'name:\"CallMcpTool\".{0,800}' /usr/share/cursor/resources/app/extensions/cursor-agent-w…[+338 chars]","cwd":"","timeout":30000},"tool_output":"{\"output\":\"server\\\"\\ntool_name\\ntool_args\\nserver.v1.CallMcpToolResult\\\"\\nserver\\\"\\ntool_name\\nserver.v1.GetMcpToolsParams\\\"\\nserver\\\"\\ntool_name\\nserver.v1.ReadMcpResourceStream\\\"\\nserver.v1.Step\\\"\\n…[+38 chars]","duration":5220.046,"tool_use_id":"e1f4b8fe-9707-47ce-bbe4-08d4dc4c414a","cwd":"","session_id":"b60ae0c1-2f85-4c4d-b3e5-b512f9b06e4c","hook_event_name":"postToolUse","cursor_version":"3.18.25","workspace_roots":["/tmp/host-test/cursor-workspace"],"user_email":"probe@example.invalid","transcript_path":"/tmp/host-test/cursor-home/.cursor/projects/tmp-host-test-cursor-workspace/agent-transcripts/b60ae0c1-2f85-4c4d-b3e5-b512f9b06e4c/b60ae0c1-2f85-4c4d-b3e5-b512f9b06e4c.jsonl"}},"host":"cursor","kind":"event","process":{"cwd":"/tmp/host-test/cursor-home","entry":"/tmp/host-test/cursor-home/.cursor/plugins/local/host-test/mcp/mcp-host-test-0d229f1b-flight.mjs","pid":197313,"ppid":4119277},"recordedAt":"2026-09-03T08:38:21.763Z","request":{"host":{"source":"native","state":"available","value":{"name":"cursor"}},"invocation":{"kind":"event"},"session":{"source":"native","state":"available","value":{"sessionId":"b60ae0c1-2f85-4c4d-b3e5-b512f9b06e4c"}}},"runtime":"shared-runtime","sequence":19} +{"event":{"canonical":{"event":"tool/before","idempotencyKey":"9b37400360c42bd7d3a7aa6435a18a746fa1793496cf962b81d898a702a5ac24","observedAt":"2026-09-03T08:38:26.673Z","provenance":{"host":"cursor","hostContractRevision":"2026-08-28","nativeEvent":"preToolUse","source":"native"},"sequence":20},"native":{"conversation_id":"b60ae0c1-2f85-4c4d-b3e5-b512f9b06e4c","generation_id":"d4b2603b-ebfe-45ee-832d-b30d048defbb","model":"default","tool_name":"Shell","tool_input":{"command":"# Find the exact tool description / parameter names exposed to the model\npython3 - <<'PY'\nimport re\npath='/usr/share/cursor/resources/app/extensions/cursor-agent-worker/dist/main.js'\ntext=open(path,'r',errors='ignore').read()\n# Find MCP Tool Access section\nidx=text.find('MCP Tool Access')\nprint('idx', idx)\nprint(text[idx:idx+2500] if idx>=0 else 'not found')\nprint('---')\nidx2=text.find('call any M…[+70 chars]","cwd":"","timeout":30000},"tool_use_id":"cfdf9a8e-4c82-4a40-b7f6-10bb61f81669","cwd":"","session_id":"b60ae0c1-2f85-4c4d-b3e5-b512f9b06e4c","hook_event_name":"preToolUse","cursor_version":"3.18.25","workspace_roots":["/tmp/host-test/cursor-workspace"],"user_email":"probe@example.invalid","transcript_path":"/tmp/host-test/cursor-home/.cursor/projects/tmp-host-test-cursor-workspace/agent-transcripts/b60ae0c1-2f85-4c4d-b3e5-b512f9b06e4c/b60ae0c1-2f85-4c4d-b3e5-b512f9b06e4c.jsonl"}},"host":"cursor","kind":"event","process":{"cwd":"/tmp/host-test/cursor-home","entry":"/tmp/host-test/cursor-home/.cursor/plugins/local/host-test/mcp/mcp-host-test-0d229f1b-flight.mjs","pid":197313,"ppid":4119277},"recordedAt":"2026-09-03T08:38:26.679Z","request":{"host":{"source":"native","state":"available","value":{"name":"cursor"}},"invocation":{"kind":"event"},"session":{"source":"native","state":"available","value":{"sessionId":"b60ae0c1-2f85-4c4d-b3e5-b512f9b06e4c"}}},"runtime":"shared-runtime","sequence":20} +{"event":{"canonical":{"event":"tool/before","idempotencyKey":"84137984d0a13ff4eee49d7ec352985b0b876db2840053dd4642fe80d906d584","observedAt":"2026-09-03T08:38:40.109Z","provenance":{"host":"cursor","hostContractRevision":"2026-08-28","nativeEvent":"preToolUse","source":"native"},"sequence":21},"native":{"conversation_id":"b60ae0c1-2f85-4c4d-b3e5-b512f9b06e4c","generation_id":"d4b2603b-ebfe-45ee-832d-b30d048defbb","model":"default","tool_name":"Shell","tool_input":{"command":"python3 - <<'PY'\npath='/usr/share/cursor/resources/app/extensions/cursor-agent-worker/dist/main.js'\ntext=open(path,'r',errors='ignore').read()\nidx=text.find('MCP Tool Access')\nprint('idx', idx)\nprint(text[idx:idx+2500] if idx>=0 else 'not found')\nprint('---')\nidx2=text.find('call any MCP tool')\nprint(text[idx2:idx2+2000] if idx2>=0 else 'not found2')\n# also find properties for CallMcpTool tool def…[+142 chars]","cwd":"","timeout":30000},"tool_use_id":"4074ade4-ea4d-4c2a-919a-53f219370add","cwd":"","session_id":"b60ae0c1-2f85-4c4d-b3e5-b512f9b06e4c","hook_event_name":"preToolUse","cursor_version":"3.18.25","workspace_roots":["/tmp/host-test/cursor-workspace"],"user_email":"probe@example.invalid","transcript_path":"/tmp/host-test/cursor-home/.cursor/projects/tmp-host-test-cursor-workspace/agent-transcripts/b60ae0c1-2f85-4c4d-b3e5-b512f9b06e4c/b60ae0c1-2f85-4c4d-b3e5-b512f9b06e4c.jsonl"}},"host":"cursor","kind":"event","process":{"cwd":"/tmp/host-test/cursor-home","entry":"/tmp/host-test/cursor-home/.cursor/plugins/local/host-test/mcp/mcp-host-test-0d229f1b-flight.mjs","pid":197313,"ppid":4119277},"recordedAt":"2026-09-03T08:38:40.111Z","request":{"host":{"source":"native","state":"available","value":{"name":"cursor"}},"invocation":{"kind":"event"},"session":{"source":"native","state":"available","value":{"sessionId":"b60ae0c1-2f85-4c4d-b3e5-b512f9b06e4c"}}},"runtime":"shared-runtime","sequence":21} +{"event":{"canonical":{"event":"tool/after","idempotencyKey":"5283e2e1f5ab28c43724abbc274e37055a49dbe6ff3a8ccc7c66cb36af490aa9","observedAt":"2026-09-03T08:38:40.457Z","provenance":{"host":"cursor","hostContractRevision":"2026-08-28","nativeEvent":"postToolUse","source":"native"},"sequence":22},"native":{"conversation_id":"b60ae0c1-2f85-4c4d-b3e5-b512f9b06e4c","generation_id":"d4b2603b-ebfe-45ee-832d-b30d048defbb","model":"default","tool_name":"Shell","tool_input":{"command":"python3 - <<'PY'\npath='/usr/share/cursor/resources/app/extensions/cursor-agent-worker/dist/main.js'\ntext=open(path,'r',errors='ignore').read()\nidx=text.find('MCP Tool Access')\nprint('idx', idx)\nprint(text[idx:idx+2500] if idx>=0 else 'not found')\nprint('---')\nidx2=text.find('call any MCP tool')\nprint(text[idx2:idx2+2000] if idx2>=0 else 'not found2')\n# also find properties for CallMcpTool tool def…[+142 chars]","cwd":"","timeout":30000},"tool_output":"{\"output\":\"idx -1\\nnot found\\n---\\nnot found2\\n\\\"CallMcpTool\\\" -1\\nname:\\\"CallMcpTool\\\" -1\\nCallMcpTool tool -1\\nserverIdentifier -1\\n\",\"exitCode\":0}","duration":147.075,"tool_use_id":"4074ade4-ea4d-4c2a-919a-53f219370add","cwd":"","session_id":"b60ae0c1-2f85-4c4d-b3e5-b512f9b06e4c","hook_event_name":"postToolUse","cursor_version":"3.18.25","workspace_roots":["/tmp/host-test/cursor-workspace"],"user_email":"probe@example.invalid","transcript_path":"/tmp/host-test/cursor-home/.cursor/projects/tmp-host-test-cursor-workspace/agent-transcripts/b60ae0c1-2f85-4c4d-b3e5-b512f9b06e4c/b60ae0c1-2f85-4c4d-b3e5-b512f9b06e4c.jsonl"}},"host":"cursor","kind":"event","process":{"cwd":"/tmp/host-test/cursor-home","entry":"/tmp/host-test/cursor-home/.cursor/plugins/local/host-test/mcp/mcp-host-test-0d229f1b-flight.mjs","pid":197313,"ppid":4119277},"recordedAt":"2026-09-03T08:38:40.460Z","request":{"host":{"source":"native","state":"available","value":{"name":"cursor"}},"invocation":{"kind":"event"},"session":{"source":"native","state":"available","value":{"sessionId":"b60ae0c1-2f85-4c4d-b3e5-b512f9b06e4c"}}},"runtime":"shared-runtime","sequence":22} +{"event":{"canonical":{"event":"tool/before","idempotencyKey":"2f5572f1a4871a9e549cf6814658b45a7f0c7375f6558a8303bc78544e9e6cd9","observedAt":"2026-09-03T08:38:44.882Z","provenance":{"host":"cursor","hostContractRevision":"2026-08-28","nativeEvent":"preToolUse","source":"native"},"sequence":23},"native":{"conversation_id":"b60ae0c1-2f85-4c4d-b3e5-b512f9b06e4c","generation_id":"d4b2603b-ebfe-45ee-832d-b30d048defbb","model":"default","tool_name":"Shell","tool_input":{"command":"rg -a -o 'You have a .CallMcpTool. tool available.{0,1500}' /usr/share/cursor/resources/app/extensions/cursor-agent-worker/dist/main.js | head -3\nrg -a -o 'serverIdentifier.{0,80}|toolName.{0,40}|Required parameters.{0,200}' /usr/share/cursor/resources/app/extensions/cursor-local-agent-runtime/dist/main.js | head -40\n# Look for tool JSON schema with server and toolName\nrg -a -o '.{0,100}toolName.{…[+109 chars]","cwd":"","timeout":30000},"tool_use_id":"f9f238a2-5fd4-49ad-b53b-fd9b92ab2403","cwd":"","session_id":"b60ae0c1-2f85-4c4d-b3e5-b512f9b06e4c","hook_event_name":"preToolUse","cursor_version":"3.18.25","workspace_roots":["/tmp/host-test/cursor-workspace"],"user_email":"probe@example.invalid","transcript_path":"/tmp/host-test/cursor-home/.cursor/projects/tmp-host-test-cursor-workspace/agent-transcripts/b60ae0c1-2f85-4c4d-b3e5-b512f9b06e4c/b60ae0c1-2f85-4c4d-b3e5-b512f9b06e4c.jsonl"}},"host":"cursor","kind":"event","process":{"cwd":"/tmp/host-test/cursor-home","entry":"/tmp/host-test/cursor-home/.cursor/plugins/local/host-test/mcp/mcp-host-test-0d229f1b-flight.mjs","pid":197313,"ppid":4119277},"recordedAt":"2026-09-03T08:38:44.886Z","request":{"host":{"source":"native","state":"available","value":{"name":"cursor"}},"invocation":{"kind":"event"},"session":{"source":"native","state":"available","value":{"sessionId":"b60ae0c1-2f85-4c4d-b3e5-b512f9b06e4c"}}},"runtime":"shared-runtime","sequence":23} +{"event":{"canonical":{"event":"tool/after","idempotencyKey":"25fd5188a0d36c94fffd7d90bf2b269557b4f6087270ac1d20df1069de742238","observedAt":"2026-09-03T08:38:45.213Z","provenance":{"host":"cursor","hostContractRevision":"2026-08-28","nativeEvent":"postToolUse","source":"native"},"sequence":24},"native":{"conversation_id":"b60ae0c1-2f85-4c4d-b3e5-b512f9b06e4c","generation_id":"d4b2603b-ebfe-45ee-832d-b30d048defbb","model":"default","tool_name":"Shell","tool_input":{"command":"rg -a -o 'You have a .CallMcpTool. tool available.{0,1500}' /usr/share/cursor/resources/app/extensions/cursor-agent-worker/dist/main.js | head -3\nrg -a -o 'serverIdentifier.{0,80}|toolName.{0,40}|Required parameters.{0,200}' /usr/share/cursor/resources/app/extensions/cursor-local-agent-runtime/dist/main.js | head -40\n# Look for tool JSON schema with server and toolName\nrg -a -o '.{0,100}toolName.{…[+109 chars]","cwd":"","timeout":30000},"tool_output":"{\"output\":\"toolName,description:e.description,arguments:e.i\\nserverIdentifiers}function ye(...e){var t,n,r,o,s;const[i,a]=e;return e.length<2?i:ge(a)?{server\\nserverIdentifiers:void 0,reason:null!==(n…[+2357 chars]","duration":141.409,"tool_use_id":"f9f238a2-5fd4-49ad-b53b-fd9b92ab2403","cwd":"","session_id":"b60ae0c1-2f85-4c4d-b3e5-b512f9b06e4c","hook_event_name":"postToolUse","cursor_version":"3.18.25","workspace_roots":["/tmp/host-test/cursor-workspace"],"user_email":"probe@example.invalid","transcript_path":"/tmp/host-test/cursor-home/.cursor/projects/tmp-host-test-cursor-workspace/agent-transcripts/b60ae0c1-2f85-4c4d-b3e5-b512f9b06e4c/b60ae0c1-2f85-4c4d-b3e5-b512f9b06e4c.jsonl"}},"host":"cursor","kind":"event","process":{"cwd":"/tmp/host-test/cursor-home","entry":"/tmp/host-test/cursor-home/.cursor/plugins/local/host-test/mcp/mcp-host-test-0d229f1b-flight.mjs","pid":197313,"ppid":4119277},"recordedAt":"2026-09-03T08:38:45.217Z","request":{"host":{"source":"native","state":"available","value":{"name":"cursor"}},"invocation":{"kind":"event"},"session":{"source":"native","state":"available","value":{"sessionId":"b60ae0c1-2f85-4c4d-b3e5-b512f9b06e4c"}}},"runtime":"shared-runtime","sequence":24} +{"event":{"canonical":{"event":"tool/before","idempotencyKey":"1503faabdb69be2b38077f36a0fccfd192ddfeeada61edd7b392035a58dce5d1","observedAt":"2026-09-03T08:38:48.812Z","provenance":{"host":"cursor","hostContractRevision":"2026-08-28","nativeEvent":"preToolUse","source":"native"},"sequence":25},"native":{"conversation_id":"b60ae0c1-2f85-4c4d-b3e5-b512f9b06e4c","generation_id":"d4b2603b-ebfe-45ee-832d-b30d048defbb","model":"default","tool_name":"Shell","tool_input":{"command":"# Kill the hung background search if still running\nkill 187199 2>/dev/null || true\n# Confirm log path that dump would return\necho \"expected log path: /tmp/host-test/cursor/log/captures.ndjson\"\nls -la /tmp/host-test/cursor/log/captures.ndjson\nwc -l /tmp/host-test/cursor/log/captures.ndjson\n","cwd":"","timeout":30000},"tool_use_id":"f2727f95-0fbe-4ce6-93a3-0f2a6b4d9673","cwd":"","session_id":"b60ae0c1-2f85-4c4d-b3e5-b512f9b06e4c","hook_event_name":"preToolUse","cursor_version":"3.18.25","workspace_roots":["/tmp/host-test/cursor-workspace"],"user_email":"probe@example.invalid","transcript_path":"/tmp/host-test/cursor-home/.cursor/projects/tmp-host-test-cursor-workspace/agent-transcripts/b60ae0c1-2f85-4c4d-b3e5-b512f9b06e4c/b60ae0c1-2f85-4c4d-b3e5-b512f9b06e4c.jsonl"}},"host":"cursor","kind":"event","process":{"cwd":"/tmp/host-test/cursor-home","entry":"/tmp/host-test/cursor-home/.cursor/plugins/local/host-test/mcp/mcp-host-test-0d229f1b-flight.mjs","pid":197313,"ppid":4119277},"recordedAt":"2026-09-03T08:38:48.815Z","request":{"host":{"source":"native","state":"available","value":{"name":"cursor"}},"invocation":{"kind":"event"},"session":{"source":"native","state":"available","value":{"sessionId":"b60ae0c1-2f85-4c4d-b3e5-b512f9b06e4c"}}},"runtime":"shared-runtime","sequence":25} +{"event":{"canonical":{"event":"tool/after","idempotencyKey":"486471c4af8aefb24b7023c442105110eed0f339e8d19a8375b65127199a0a02","observedAt":"2026-09-03T08:38:54.162Z","provenance":{"host":"cursor","hostContractRevision":"2026-08-28","nativeEvent":"postToolUse","source":"native"},"sequence":26},"native":{"conversation_id":"b60ae0c1-2f85-4c4d-b3e5-b512f9b06e4c","generation_id":"d4b2603b-ebfe-45ee-832d-b30d048defbb","model":"default","tool_name":"Shell","tool_input":{"command":"# Kill the hung background search if still running\nkill 187199 2>/dev/null || true\n# Confirm log path that dump would return\necho \"expected log path: /tmp/host-test/cursor/log/captures.ndjson\"\nls -la /tmp/host-test/cursor/log/captures.ndjson\nwc -l /tmp/host-test/cursor/log/captures.ndjson\n","cwd":"","timeout":30000},"tool_output":"{\"output\":\"expected log path: /tmp/host-test/cursor/log/captures.ndjson\\n-rw-rw-r-- 1 root root 291689 Sep 3 08:38 /tmp/host-test/cursor/log/captures.ndjson\\n69 /tmp/host-test/cursor/log/captures.ndj…[+20 chars]","duration":5177.415,"tool_use_id":"f2727f95-0fbe-4ce6-93a3-0f2a6b4d9673","cwd":"","session_id":"b60ae0c1-2f85-4c4d-b3e5-b512f9b06e4c","hook_event_name":"postToolUse","cursor_version":"3.18.25","workspace_roots":["/tmp/host-test/cursor-workspace"],"user_email":"probe@example.invalid","transcript_path":"/tmp/host-test/cursor-home/.cursor/projects/tmp-host-test-cursor-workspace/agent-transcripts/b60ae0c1-2f85-4c4d-b3e5-b512f9b06e4c/b60ae0c1-2f85-4c4d-b3e5-b512f9b06e4c.jsonl"}},"host":"cursor","kind":"event","process":{"cwd":"/tmp/host-test/cursor-home","entry":"/tmp/host-test/cursor-home/.cursor/plugins/local/host-test/mcp/mcp-host-test-0d229f1b-flight.mjs","pid":197313,"ppid":4119277},"recordedAt":"2026-09-03T08:38:54.166Z","request":{"host":{"source":"native","state":"available","value":{"name":"cursor"}},"invocation":{"kind":"event"},"session":{"source":"native","state":"available","value":{"sessionId":"b60ae0c1-2f85-4c4d-b3e5-b512f9b06e4c"}}},"runtime":"shared-runtime","sequence":26} +{"event":{"canonical":{"event":"tool/before","idempotencyKey":"6ba2778ea24b3bb6b35f1f51e1062af48cb437162d12e101e7795104c42eba32","observedAt":"2026-09-03T08:39:02.230Z","provenance":{"host":"cursor","hostContractRevision":"2026-08-28","nativeEvent":"preToolUse","source":"native"},"sequence":27},"native":{"conversation_id":"b60ae0c1-2f85-4c4d-b3e5-b512f9b06e4c","generation_id":"d4b2603b-ebfe-45ee-832d-b30d048defbb","model":"","tool_name":"Task","tool_input":{"description":"Host-test subagent probe","prompt":"You are exercising the host-test probe. Do these steps in order without asking questions:\n\n1. Run the shell command `pwd`.\n2. Call the host-test `dump` MCP tool with {}. Remember its log.path. The MCP server identifier is `plugin-host-test-host-test` (serverName `host-test`). Use CallMcpTool if available: server `plugin-host-test-host-test`, toolName `dump`, arguments `{}`. Read the tool descripto…[+900 chars]","model":"inherit","subagent_type":"generalPurpose"},"tool_use_id":"call-2ec9530d-b502-4c4f-8a6e-63f0bf7ebc9a-29\nfc_49466487-df47-9fb4-8b10-079ee845fb97_0","session_id":"b60ae0c1-2f85-4c4d-b3e5-b512f9b06e4c","hook_event_name":"preToolUse","cursor_version":"3.18.25","workspace_roots":["/tmp/host-test/cursor-workspace"],"user_email":"probe@example.invalid","transcript_path":"/tmp/host-test/cursor-home/.cursor/projects/tmp-host-test-cursor-workspace/agent-transcripts/b60ae0c1-2f85-4c4d-b3e5-b512f9b06e4c/b60ae0c1-2f85-4c4d-b3e5-b512f9b06e4c.jsonl"}},"host":"cursor","kind":"event","process":{"cwd":"/tmp/host-test/cursor-home","entry":"/tmp/host-test/cursor-home/.cursor/plugins/local/host-test/mcp/mcp-host-test-0d229f1b-flight.mjs","pid":197313,"ppid":4119277},"recordedAt":"2026-09-03T08:39:02.234Z","request":{"host":{"source":"native","state":"available","value":{"name":"cursor"}},"invocation":{"kind":"event"},"session":{"source":"native","state":"available","value":{"sessionId":"b60ae0c1-2f85-4c4d-b3e5-b512f9b06e4c"}}},"runtime":"shared-runtime","sequence":27} +{"event":{"canonical":{"event":"agent/start","idempotencyKey":"c31947320759d8649ab2172f323ca7c3d6c0a9241154c842891f2ea8b46f1d4f","observedAt":"2026-09-03T08:39:02.596Z","provenance":{"host":"cursor","hostContractRevision":"2026-08-28","nativeEvent":"subagentStart","source":"native"},"sequence":28},"native":{"conversation_id":"b60ae0c1-2f85-4c4d-b3e5-b512f9b06e4c","generation_id":"b60ae0c1-2f85-4c4d-b3e5-b512f9b06e4c","model":"default","subagent_id":"call-2ec9530d-b502-4c4f-8a6e-63f0bf7ebc9a-29\nfc_49466487-df47-9fb4-8b10-079ee845fb97_0","subagent_type":"general-purpose","task":"You are exercising the host-test probe. Do these steps in order without asking questions:\n\n1. Run the shell command `pwd`.\n2. Call the host-test `dump` MCP tool with {}. Remember its log.path. The MCP…[+1100 chars]","parent_conversation_id":"b60ae0c1-2f85-4c4d-b3e5-b512f9b06e4c","tool_call_id":"call-2ec9530d-b502-4c4f-8a6e-63f0bf7ebc9a-29\nfc_49466487-df47-9fb4-8b10-079ee845fb97_0","subagent_model":"default","is_parallel_worker":false,"session_id":"b60ae0c1-2f85-4c4d-b3e5-b512f9b06e4c","hook_event_name":"subagentStart","cursor_version":"3.18.25","workspace_roots":["/tmp/host-test/cursor-workspace"],"user_email":"probe@example.invalid","transcript_path":"/tmp/host-test/cursor-home/.cursor/projects/tmp-host-test-cursor-workspace/agent-transcripts/b60ae0c1-2f85-4c4d-b3e5-b512f9b06e4c/b60ae0c1-2f85-4c4d-b3e5-b512f9b06e4c.jsonl"}},"host":"cursor","kind":"event","process":{"cwd":"/tmp/host-test/cursor-home","entry":"/tmp/host-test/cursor-home/.cursor/plugins/local/host-test/mcp/mcp-host-test-0d229f1b-flight.mjs","pid":197313,"ppid":4119277},"recordedAt":"2026-09-03T08:39:02.601Z","request":{"host":{"source":"native","state":"available","value":{"name":"cursor"}},"invocation":{"kind":"event"},"session":{"source":"native","state":"available","value":{"sessionId":"b60ae0c1-2f85-4c4d-b3e5-b512f9b06e4c"}}},"runtime":"shared-runtime","sequence":28} +{"event":{"canonical":{"event":"tool/before","idempotencyKey":"fa0df98cb11017570b1ae6c78ccd432c7d8523c7cb1aaecaa50a146814528b4b","observedAt":"2026-09-03T08:39:10.312Z","provenance":{"host":"cursor","hostContractRevision":"2026-08-28","nativeEvent":"preToolUse","source":"native"},"sequence":29},"native":{"conversation_id":"bf617dfd-e03d-4d6b-adef-8f97e7df6b71","generation_id":"f528e734-0eb7-47aa-b39b-bfb3a06e3947","model":"default","tool_name":"Read","tool_input":{"file_path":"/tmp/host-test/cursor-home/.cursor/plugins/local/host-test/skills/host-test/SKILL.md"},"tool_use_id":"call-aee670cf-e1a1-471d-8f7e-03dc9fc5f395-1\nfc_a2f1916f-94d3-9c8d-a05e-f9d8a1919256_1","session_id":"bf617dfd-e03d-4d6b-adef-8f97e7df6b71","hook_event_name":"preToolUse","cursor_version":"3.18.25","workspace_roots":["/tmp/host-test/cursor-workspace"],"user_email":"probe@example.invalid","transcript_path":null}},"host":"cursor","kind":"event","process":{"cwd":"/tmp/host-test/cursor-home","entry":"/tmp/host-test/cursor-home/.cursor/plugins/local/host-test/mcp/mcp-host-test-0d229f1b-flight.mjs","pid":197313,"ppid":4119277},"recordedAt":"2026-09-03T08:39:10.315Z","request":{"host":{"source":"native","state":"available","value":{"name":"cursor"}},"invocation":{"kind":"event"},"session":{"source":"native","state":"available","value":{"sessionId":"bf617dfd-e03d-4d6b-adef-8f97e7df6b71"}}},"runtime":"shared-runtime","sequence":29} +{"event":{"canonical":{"event":"tool/after","idempotencyKey":"3a8dc0e92579b3b8843faf014c1c2a3cba8856ef73cd6354b98a4b0649a7f2d5","observedAt":"2026-09-03T08:39:10.513Z","provenance":{"host":"cursor","hostContractRevision":"2026-08-28","nativeEvent":"postToolUse","source":"native"},"sequence":30},"native":{"conversation_id":"bf617dfd-e03d-4d6b-adef-8f97e7df6b71","generation_id":"f528e734-0eb7-47aa-b39b-bfb3a06e3947","model":"default","tool_name":"Read","tool_input":{"file_path":"/tmp/host-test/cursor-home/.cursor/plugins/local/host-test/skills/host-test/SKILL.md"},"tool_output":"{\"file_path\":\"/tmp/host-test/cursor-home/.cursor/plugins/local/host-test/skills/host-test/SKILL.md\",\"content_length\":1464}","duration":4.69,"tool_use_id":"call-aee670cf-e1a1-471d-8f7e-03dc9fc5f395-1\nfc_a2f1916f-94d3-9c8d-a05e-f9d8a1919256_1","session_id":"bf617dfd-e03d-4d6b-adef-8f97e7df6b71","hook_event_name":"postToolUse","cursor_version":"3.18.25","workspace_roots":["/tmp/host-test/cursor-workspace"],"user_email":"probe@example.invalid","transcript_path":null}},"host":"cursor","kind":"event","process":{"cwd":"/tmp/host-test/cursor-home","entry":"/tmp/host-test/cursor-home/.cursor/plugins/local/host-test/mcp/mcp-host-test-0d229f1b-flight.mjs","pid":197313,"ppid":4119277},"recordedAt":"2026-09-03T08:39:10.516Z","request":{"host":{"source":"native","state":"available","value":{"name":"cursor"}},"invocation":{"kind":"event"},"session":{"source":"native","state":"available","value":{"sessionId":"bf617dfd-e03d-4d6b-adef-8f97e7df6b71"}}},"runtime":"shared-runtime","sequence":30} +{"event":{"canonical":{"event":"tool/before","idempotencyKey":"4f055307964fa09898114feb80d16b25a8fd4afa0789f7ab7fd2f0ca54878c05","observedAt":"2026-09-03T08:39:11.156Z","provenance":{"host":"cursor","hostContractRevision":"2026-08-28","nativeEvent":"preToolUse","source":"native"},"sequence":34},"native":{"conversation_id":"bf617dfd-e03d-4d6b-adef-8f97e7df6b71","generation_id":"f528e734-0eb7-47aa-b39b-bfb3a06e3947","model":"default","tool_name":"Shell","tool_input":{"command":"pwd","cwd":"","timeout":30000},"tool_use_id":"0c027404-e82e-40b1-bb6b-074984c46c03","cwd":"","session_id":"bf617dfd-e03d-4d6b-adef-8f97e7df6b71","hook_event_name":"preToolUse","cursor_version":"3.18.25","workspace_roots":["/tmp/host-test/cursor-workspace"],"user_email":"probe@example.invalid","transcript_path":null}},"host":"cursor","kind":"event","process":{"cwd":"/tmp/host-test/cursor-home","entry":"/tmp/host-test/cursor-home/.cursor/plugins/local/host-test/mcp/mcp-host-test-0d229f1b-flight.mjs","pid":197313,"ppid":4119277},"recordedAt":"2026-09-03T08:39:11.159Z","request":{"host":{"source":"native","state":"available","value":{"name":"cursor"}},"invocation":{"kind":"event"},"session":{"source":"native","state":"available","value":{"sessionId":"bf617dfd-e03d-4d6b-adef-8f97e7df6b71"}}},"runtime":"shared-runtime","sequence":34} +{"event":{"canonical":{"event":"tool/after","idempotencyKey":"445b2892bd3d1bfdbd48ece754dedb5c52e30ecae59bca60f46812c7377a7f98","observedAt":"2026-09-03T08:39:16.580Z","provenance":{"host":"cursor","hostContractRevision":"2026-08-28","nativeEvent":"postToolUse","source":"native"},"sequence":36},"native":{"conversation_id":"bf617dfd-e03d-4d6b-adef-8f97e7df6b71","generation_id":"f528e734-0eb7-47aa-b39b-bfb3a06e3947","model":"default","tool_name":"Shell","tool_input":{"command":"pwd","cwd":"","timeout":30000},"tool_output":"{\"output\":\"/tmp/host-test/cursor-workspace\\n\",\"exitCode\":0}","duration":5226.539,"tool_use_id":"0c027404-e82e-40b1-bb6b-074984c46c03","cwd":"","session_id":"bf617dfd-e03d-4d6b-adef-8f97e7df6b71","hook_event_name":"postToolUse","cursor_version":"3.18.25","workspace_roots":["/tmp/host-test/cursor-workspace"],"user_email":"probe@example.invalid","transcript_path":null}},"host":"cursor","kind":"event","process":{"cwd":"/tmp/host-test/cursor-home","entry":"/tmp/host-test/cursor-home/.cursor/plugins/local/host-test/mcp/mcp-host-test-0d229f1b-flight.mjs","pid":197313,"ppid":4119277},"recordedAt":"2026-09-03T08:39:16.582Z","request":{"host":{"source":"native","state":"available","value":{"name":"cursor"}},"invocation":{"kind":"event"},"session":{"source":"native","state":"available","value":{"sessionId":"bf617dfd-e03d-4d6b-adef-8f97e7df6b71"}}},"runtime":"shared-runtime","sequence":36} +{"event":{"canonical":{"event":"tool/before","idempotencyKey":"b60c304f550df1381db5c4fb0afd8c602030884480312a39e49df8e2010ef75d","observedAt":"2026-09-03T08:39:22.970Z","provenance":{"host":"cursor","hostContractRevision":"2026-08-28","nativeEvent":"preToolUse","source":"native"},"sequence":37},"native":{"conversation_id":"bf617dfd-e03d-4d6b-adef-8f97e7df6b71","generation_id":"f528e734-0eb7-47aa-b39b-bfb3a06e3947","model":"default","tool_name":"MCP:dump","tool_input":{},"tool_use_id":"0db858b5-ca63-4a57-b26d-de405d66ec63","session_id":"bf617dfd-e03d-4d6b-adef-8f97e7df6b71","hook_event_name":"preToolUse","cursor_version":"3.18.25","workspace_roots":["/tmp/host-test/cursor-workspace"],"user_email":"probe@example.invalid","transcript_path":null}},"host":"cursor","kind":"event","process":{"cwd":"/tmp/host-test/cursor-home","entry":"/tmp/host-test/cursor-home/.cursor/plugins/local/host-test/mcp/mcp-host-test-0d229f1b-flight.mjs","pid":197313,"ppid":4119277},"recordedAt":"2026-09-03T08:39:22.973Z","request":{"host":{"source":"native","state":"available","value":{"name":"cursor"}},"invocation":{"kind":"event"},"session":{"source":"native","state":"available","value":{"sessionId":"bf617dfd-e03d-4d6b-adef-8f97e7df6b71"}}},"runtime":"shared-runtime","sequence":37} +{"env":{"names":["AGENT_BUNDLE_PLUGIN_ROOT","HOST_TEST_LOG_DIR"]},"host":"cursor-vscode","kind":"mcp","observed":{"tool":"dump"},"process":{"cwd":"/tmp/host-test/cursor-home","entry":"/tmp/host-test/cursor-home/.cursor/plugins/local/host-test/mcp/mcp-host-test-0d229f1b-flight.mjs","pid":197313,"ppid":4119277},"recordedAt":"2026-09-03T08:39:23.051Z","request":{"host":{"source":"native","state":"available","value":{"name":"cursor-vscode"}},"invocation":{"kind":"tool"},"session":{"reason":"not-provided","state":"unavailable"}},"runtime":"mcp-server","sequence":38} +{"event":{"canonical":{"event":"tool/after","idempotencyKey":"3213a649b70326f05b900f7ae7013220c1cf4d5a675509a4e4f23fd4d6ddd5d9","observedAt":"2026-09-03T08:39:23.364Z","provenance":{"host":"cursor","hostContractRevision":"2026-08-28","nativeEvent":"postToolUse","source":"native"},"sequence":38},"native":{"conversation_id":"bf617dfd-e03d-4d6b-adef-8f97e7df6b71","generation_id":"f528e734-0eb7-47aa-b39b-bfb3a06e3947","model":"default","tool_name":"MCP:dump","tool_input":{},"tool_output":"{\"content\":[{\"type\":\"text\",\"text\":\"\"}],\"isError\":false}","duration":173.531,"tool_use_id":"0db858b5-ca63-4a57-b26d-de405d66ec63","session_id":"bf617dfd-e03d-4d6b-adef-8f97e7df6b71","hook_event_name":"postToolUse","cursor_version":"3.18.25","workspace_roots":["/tmp/host-test/cursor-workspace"],"user_email":"probe@example.invalid","transcript_path":null}},"host":"cursor","kind":"event","process":{"cwd":"/tmp/host-test/cursor-home","entry":"/tmp/host-test/cursor-home/.cursor/plugins/local/host-test/mcp/mcp-host-test-0d229f1b-flight.mjs","pid":197313,"ppid":4119277},"recordedAt":"2026-09-03T08:39:23.367Z","request":{"host":{"source":"native","state":"available","value":{"name":"cursor"}},"invocation":{"kind":"event"},"session":{"source":"native","state":"available","value":{"sessionId":"bf617dfd-e03d-4d6b-adef-8f97e7df6b71"}}},"runtime":"shared-runtime","sequence":39} +{"event":{"canonical":{"event":"tool/before","idempotencyKey":"4362f478ffa222a3b06d830d2d118063c2053bed1bc4c6079a374ed3cfb57fd7","observedAt":"2026-09-03T08:39:32.247Z","provenance":{"host":"cursor","hostContractRevision":"2026-08-28","nativeEvent":"preToolUse","source":"native"},"sequence":43},"native":{"conversation_id":"bf617dfd-e03d-4d6b-adef-8f97e7df6b71","generation_id":"f528e734-0eb7-47aa-b39b-bfb3a06e3947","model":"default","tool_name":"MCP:probe","tool_input":{"note":"subagent"},"tool_use_id":"7dc3525b-6f18-4414-b29c-73f606a74777","session_id":"bf617dfd-e03d-4d6b-adef-8f97e7df6b71","hook_event_name":"preToolUse","cursor_version":"3.18.25","workspace_roots":["/tmp/host-test/cursor-workspace"],"user_email":"probe@example.invalid","transcript_path":null}},"host":"cursor","kind":"event","process":{"cwd":"/tmp/host-test/cursor-home","entry":"/tmp/host-test/cursor-home/.cursor/plugins/local/host-test/mcp/mcp-host-test-0d229f1b-flight.mjs","pid":197313,"ppid":4119277},"recordedAt":"2026-09-03T08:39:32.251Z","request":{"host":{"source":"native","state":"available","value":{"name":"cursor"}},"invocation":{"kind":"event"},"session":{"source":"native","state":"available","value":{"sessionId":"bf617dfd-e03d-4d6b-adef-8f97e7df6b71"}}},"runtime":"shared-runtime","sequence":44} +{"host":"cursor-vscode","kind":"mcp","observed":{"client":{"name":"cursor-vscode","version":"1.0.0"},"clientCapabilities":{"elicitation":{"form":{}},"roots":{"listChanged":false},"extensions":{"io.modelcontextprotocol/ui":{"mimeTypes":["text/html;profile=mcp-app"]}}},"env":{"names":["AGENT_BUNDLE_PLUGIN_ROOT","HOST_TEST_LOG_DIR"]},"http":null,"mcpReq":{"_meta":{"progressToken":1},"envelope":null,"id":1,"method":"tools/call"},"note":"subagent","sessionId":null,"tool":"probe"},"process":{"cwd":"/tmp/host-test/cursor-home","entry":"/tmp/host-test/cursor-home/.cursor/plugins/local/host-test/mcp/mcp-host-test-raw-6e9c1a1c.mjs","pid":197724,"ppid":4119277},"recordedAt":"2026-09-03T08:39:32.311Z","request":{"unavailable":"hand-rolled stdio server: no framework request context is mounted"},"runtime":"mcp-server","sequence":1} +{"event":{"canonical":{"event":"tool/after","idempotencyKey":"95caea38e01439405fa599730efb5610fe8930831b1a6c3badea95bf330e2c5d","observedAt":"2026-09-03T08:39:32.467Z","provenance":{"host":"cursor","hostContractRevision":"2026-08-28","nativeEvent":"postToolUse","source":"native"},"sequence":44},"native":{"conversation_id":"bf617dfd-e03d-4d6b-adef-8f97e7df6b71","generation_id":"f528e734-0eb7-47aa-b39b-bfb3a06e3947","model":"default","tool_name":"MCP:probe","tool_input":{"note":"subagent"},"tool_output":"{\"content\":[{\"type\":\"text\",\"text\":\"{\\n \\\"log\\\": \\\"/tmp/host-test/cursor/log/captures.ndjson\\\",\\n \\\"observed\\\": {\\n \\\"client\\\": {\\n \\\"name\\\": \\\"cursor-vscode\\\",\\n \\\"version\\\": \\\"1.0.0\\\"\\…[+776 chars]","duration":32.971,"tool_use_id":"7dc3525b-6f18-4414-b29c-73f606a74777","session_id":"bf617dfd-e03d-4d6b-adef-8f97e7df6b71","hook_event_name":"postToolUse","cursor_version":"3.18.25","workspace_roots":["/tmp/host-test/cursor-workspace"],"user_email":"probe@example.invalid","transcript_path":null}},"host":"cursor","kind":"event","process":{"cwd":"/tmp/host-test/cursor-home","entry":"/tmp/host-test/cursor-home/.cursor/plugins/local/host-test/mcp/mcp-host-test-0d229f1b-flight.mjs","pid":197313,"ppid":4119277},"recordedAt":"2026-09-03T08:39:32.471Z","request":{"host":{"source":"native","state":"available","value":{"name":"cursor"}},"invocation":{"kind":"event"},"session":{"source":"native","state":"available","value":{"sessionId":"bf617dfd-e03d-4d6b-adef-8f97e7df6b71"}}},"runtime":"shared-runtime","sequence":45} +{"event":{"canonical":{"event":"tool/before","idempotencyKey":"a6e02b927b5fdef52a6973539f3cce49a87db9eb73cd8c200d87cff91f837d12","observedAt":"2026-09-03T08:39:42.475Z","provenance":{"host":"cursor","hostContractRevision":"2026-08-28","nativeEvent":"preToolUse","source":"native"},"sequence":45},"native":{"conversation_id":"bf617dfd-e03d-4d6b-adef-8f97e7df6b71","generation_id":"f528e734-0eb7-47aa-b39b-bfb3a06e3947","model":"","tool_name":"Task","tool_input":{"description":"Nested host-test probe","prompt":"You are a nested subagent exercising the host-test probe. Do these steps in order without asking questions:\n\n1. Run the shell command `pwd`.\n2. Call the host-test-raw `probe` MCP tool with {\"note\":\"nested\"}. Server identifier is `plugin-host-test-host-test-raw`. Use CallMcpTool: server `plugin-host-test-host-test-raw`, toolName `probe`, arguments `{\"note\":\"nested\"}`. Read the tool descriptor at `/…[+388 chars]","model":"inherit","subagent_type":"generalPurpose"},"tool_use_id":"call-29aa2614-81f6-4e3e-977b-6884e8d5ecf5-12\nfc_93a5d49e-dc4f-9a1a-a996-e646c9ac2513_1","session_id":"bf617dfd-e03d-4d6b-adef-8f97e7df6b71","hook_event_name":"preToolUse","cursor_version":"3.18.25","workspace_roots":["/tmp/host-test/cursor-workspace"],"user_email":"probe@example.invalid","transcript_path":null}},"host":"cursor","kind":"event","process":{"cwd":"/tmp/host-test/cursor-home","entry":"/tmp/host-test/cursor-home/.cursor/plugins/local/host-test/mcp/mcp-host-test-0d229f1b-flight.mjs","pid":197313,"ppid":4119277},"recordedAt":"2026-09-03T08:39:42.478Z","request":{"host":{"source":"native","state":"available","value":{"name":"cursor"}},"invocation":{"kind":"event"},"session":{"source":"native","state":"available","value":{"sessionId":"bf617dfd-e03d-4d6b-adef-8f97e7df6b71"}}},"runtime":"shared-runtime","sequence":46} +{"event":{"canonical":{"event":"agent/start","idempotencyKey":"4f9b8e0123b68cecf447bd9f877d4601c9af10b1d608484e23f9c7b47c4d37fb","observedAt":"2026-09-03T08:39:44.330Z","provenance":{"host":"cursor","hostContractRevision":"2026-08-28","nativeEvent":"subagentStart","source":"native"},"sequence":46},"native":{"conversation_id":"bf617dfd-e03d-4d6b-adef-8f97e7df6b71","generation_id":"bf617dfd-e03d-4d6b-adef-8f97e7df6b71","model":"default","subagent_id":"call-29aa2614-81f6-4e3e-977b-6884e8d5ecf5-12\nfc_93a5d49e-dc4f-9a1a-a996-e646c9ac2513_1","subagent_type":"general-purpose","task":"You are a nested subagent exercising the host-test probe. Do these steps in order without asking questions:\n\n1. Run the shell command `pwd`.\n2. Call the host-test-raw `probe` MCP tool with {\"note\":\"ne…[+588 chars]","parent_conversation_id":"bf617dfd-e03d-4d6b-adef-8f97e7df6b71","tool_call_id":"call-29aa2614-81f6-4e3e-977b-6884e8d5ecf5-12\nfc_93a5d49e-dc4f-9a1a-a996-e646c9ac2513_1","subagent_model":"default","is_parallel_worker":false,"session_id":"bf617dfd-e03d-4d6b-adef-8f97e7df6b71","hook_event_name":"subagentStart","cursor_version":"3.18.25","workspace_roots":["/tmp/host-test/cursor-workspace"],"user_email":"probe@example.invalid","transcript_path":null}},"host":"cursor","kind":"event","process":{"cwd":"/tmp/host-test/cursor-home","entry":"/tmp/host-test/cursor-home/.cursor/plugins/local/host-test/mcp/mcp-host-test-0d229f1b-flight.mjs","pid":197313,"ppid":4119277},"recordedAt":"2026-09-03T08:39:44.333Z","request":{"host":{"source":"native","state":"available","value":{"name":"cursor"}},"invocation":{"kind":"event"},"session":{"source":"native","state":"available","value":{"sessionId":"bf617dfd-e03d-4d6b-adef-8f97e7df6b71"}}},"runtime":"shared-runtime","sequence":47} +{"event":{"canonical":{"event":"tool/before","idempotencyKey":"1cd35164c84399aa59d8580b37d14d54902ca0365a85126077f050fcc6fb9c2d","observedAt":"2026-09-03T08:39:50.012Z","provenance":{"host":"cursor","hostContractRevision":"2026-08-28","nativeEvent":"preToolUse","source":"native"},"sequence":47},"native":{"conversation_id":"46efda32-55c4-436e-854f-5d0b77b908ce","generation_id":"26f71366-24b0-4a9c-b384-495b94a50364","model":"default","tool_name":"Read","tool_input":{"file_path":"/tmp/host-test/cursor-home/.cursor/skills/host-test/SKILL.md"},"tool_use_id":"call-2cfa09cb-e5d7-49b5-aa84-42a65678a93e-1\nfc_b4e3ca68-9c76-9563-a2e8-4f6829a21107_1","session_id":"46efda32-55c4-436e-854f-5d0b77b908ce","hook_event_name":"preToolUse","cursor_version":"3.18.25","workspace_roots":["/tmp/host-test/cursor-workspace"],"user_email":"probe@example.invalid","transcript_path":null}},"host":"cursor","kind":"event","process":{"cwd":"/tmp/host-test/cursor-home","entry":"/tmp/host-test/cursor-home/.cursor/plugins/local/host-test/mcp/mcp-host-test-0d229f1b-flight.mjs","pid":197313,"ppid":4119277},"recordedAt":"2026-09-03T08:39:50.015Z","request":{"host":{"source":"native","state":"available","value":{"name":"cursor"}},"invocation":{"kind":"event"},"session":{"source":"native","state":"available","value":{"sessionId":"46efda32-55c4-436e-854f-5d0b77b908ce"}}},"runtime":"shared-runtime","sequence":48} +{"event":{"canonical":{"event":"tool/before","idempotencyKey":"ceaa9c3f923f12c4b6fb4ba997c38df3b3708aab8c07bee39720ad875f571672","observedAt":"2026-09-03T08:39:50.144Z","provenance":{"host":"cursor","hostContractRevision":"2026-08-28","nativeEvent":"preToolUse","source":"native"},"sequence":49},"native":{"conversation_id":"46efda32-55c4-436e-854f-5d0b77b908ce","generation_id":"26f71366-24b0-4a9c-b384-495b94a50364","model":"default","tool_name":"Shell","tool_input":{"command":"pwd","cwd":"","timeout":30000},"tool_use_id":"6daf24be-ee5a-43e4-9c52-b7660293cc3f","cwd":"","session_id":"46efda32-55c4-436e-854f-5d0b77b908ce","hook_event_name":"preToolUse","cursor_version":"3.18.25","workspace_roots":["/tmp/host-test/cursor-workspace"],"user_email":"probe@example.invalid","transcript_path":null}},"host":"cursor","kind":"event","process":{"cwd":"/tmp/host-test/cursor-home","entry":"/tmp/host-test/cursor-home/.cursor/plugins/local/host-test/mcp/mcp-host-test-0d229f1b-flight.mjs","pid":197313,"ppid":4119277},"recordedAt":"2026-09-03T08:39:50.147Z","request":{"host":{"source":"native","state":"available","value":{"name":"cursor"}},"invocation":{"kind":"event"},"session":{"source":"native","state":"available","value":{"sessionId":"46efda32-55c4-436e-854f-5d0b77b908ce"}}},"runtime":"shared-runtime","sequence":50} +{"event":{"canonical":{"event":"tool/after","idempotencyKey":"136e20124884b5aaf22984076150c16ffa13d746612c009b683b567d9c4abdcb","observedAt":"2026-09-03T08:39:50.221Z","provenance":{"host":"cursor","hostContractRevision":"2026-08-28","nativeEvent":"postToolUse","source":"native"},"sequence":50},"native":{"conversation_id":"46efda32-55c4-436e-854f-5d0b77b908ce","generation_id":"26f71366-24b0-4a9c-b384-495b94a50364","model":"default","tool_name":"Read","tool_input":{"file_path":"/tmp/host-test/cursor-home/.cursor/projects/tmp-host-test-cursor-workspace/mcps/plugin-host-test-host-test-raw/tools/probe.json"},"tool_output":"{\"file_path\":\"/tmp/host-test/cursor-home/.cursor/projects/tmp-host-test-cursor-workspace/mcps/plugin-host-test-host-test-raw/tools/probe.json\",\"content_length\":444}","duration":3.351,"tool_use_id":"call-2cfa09cb-e5d7-49b5-aa84-42a65678a93e-2\nfc_b4e3ca68-9c76-9563-a2e8-4f6829a21107_2","session_id":"46efda32-55c4-436e-854f-5d0b77b908ce","hook_event_name":"postToolUse","cursor_version":"3.18.25","workspace_roots":["/tmp/host-test/cursor-workspace"],"user_email":"probe@example.invalid","transcript_path":null}},"host":"cursor","kind":"event","process":{"cwd":"/tmp/host-test/cursor-home","entry":"/tmp/host-test/cursor-home/.cursor/plugins/local/host-test/mcp/mcp-host-test-0d229f1b-flight.mjs","pid":197313,"ppid":4119277},"recordedAt":"2026-09-03T08:39:50.223Z","request":{"host":{"source":"native","state":"available","value":{"name":"cursor"}},"invocation":{"kind":"event"},"session":{"source":"native","state":"available","value":{"sessionId":"46efda32-55c4-436e-854f-5d0b77b908ce"}}},"runtime":"shared-runtime","sequence":51} +{"event":{"canonical":{"event":"tool/after","idempotencyKey":"5af354477bfea6934f84dfdb187df7cdfe3fbd52f1429955c751a1e5fcf5e14b","observedAt":"2026-09-03T08:39:55.462Z","provenance":{"host":"cursor","hostContractRevision":"2026-08-28","nativeEvent":"postToolUse","source":"native"},"sequence":51},"native":{"conversation_id":"46efda32-55c4-436e-854f-5d0b77b908ce","generation_id":"26f71366-24b0-4a9c-b384-495b94a50364","model":"default","tool_name":"Shell","tool_input":{"command":"pwd","cwd":"","timeout":30000},"tool_output":"{\"output\":\"/tmp/host-test/cursor-workspace\\n\",\"exitCode\":0}","duration":5141.276,"tool_use_id":"6daf24be-ee5a-43e4-9c52-b7660293cc3f","cwd":"","session_id":"46efda32-55c4-436e-854f-5d0b77b908ce","hook_event_name":"postToolUse","cursor_version":"3.18.25","workspace_roots":["/tmp/host-test/cursor-workspace"],"user_email":"probe@example.invalid","transcript_path":null}},"host":"cursor","kind":"event","process":{"cwd":"/tmp/host-test/cursor-home","entry":"/tmp/host-test/cursor-home/.cursor/plugins/local/host-test/mcp/mcp-host-test-0d229f1b-flight.mjs","pid":197313,"ppid":4119277},"recordedAt":"2026-09-03T08:39:55.465Z","request":{"host":{"source":"native","state":"available","value":{"name":"cursor"}},"invocation":{"kind":"event"},"session":{"source":"native","state":"available","value":{"sessionId":"46efda32-55c4-436e-854f-5d0b77b908ce"}}},"runtime":"shared-runtime","sequence":52} +{"event":{"canonical":{"event":"tool/before","idempotencyKey":"eb17f07098d0ad82b0b506b8e79c3ddf644ddd82ce9bc684f869de7d91a1b8db","observedAt":"2026-09-03T08:39:58.485Z","provenance":{"host":"cursor","hostContractRevision":"2026-08-28","nativeEvent":"preToolUse","source":"native"},"sequence":52},"native":{"conversation_id":"46efda32-55c4-436e-854f-5d0b77b908ce","generation_id":"26f71366-24b0-4a9c-b384-495b94a50364","model":"default","tool_name":"MCP:probe","tool_input":{"note":"nested"},"tool_use_id":"07f4c767-c618-4c89-9fdd-5c1a408e92d4","session_id":"46efda32-55c4-436e-854f-5d0b77b908ce","hook_event_name":"preToolUse","cursor_version":"3.18.25","workspace_roots":["/tmp/host-test/cursor-workspace"],"user_email":"probe@example.invalid","transcript_path":null}},"host":"cursor","kind":"event","process":{"cwd":"/tmp/host-test/cursor-home","entry":"/tmp/host-test/cursor-home/.cursor/plugins/local/host-test/mcp/mcp-host-test-0d229f1b-flight.mjs","pid":197313,"ppid":4119277},"recordedAt":"2026-09-03T08:39:58.488Z","request":{"host":{"source":"native","state":"available","value":{"name":"cursor"}},"invocation":{"kind":"event"},"session":{"source":"native","state":"available","value":{"sessionId":"46efda32-55c4-436e-854f-5d0b77b908ce"}}},"runtime":"shared-runtime","sequence":53} +{"host":"cursor-vscode","kind":"mcp","observed":{"client":{"name":"cursor-vscode","version":"1.0.0"},"clientCapabilities":{"elicitation":{"form":{}},"roots":{"listChanged":false},"extensions":{"io.modelcontextprotocol/ui":{"mimeTypes":["text/html;profile=mcp-app"]}}},"env":{"names":["AGENT_BUNDLE_PLUGIN_ROOT","HOST_TEST_LOG_DIR"]},"http":null,"mcpReq":{"_meta":{"progressToken":2},"envelope":null,"id":2,"method":"tools/call"},"note":"nested","sessionId":null,"tool":"probe"},"process":{"cwd":"/tmp/host-test/cursor-home","entry":"/tmp/host-test/cursor-home/.cursor/plugins/local/host-test/mcp/mcp-host-test-raw-6e9c1a1c.mjs","pid":197724,"ppid":4119277},"recordedAt":"2026-09-03T08:39:58.532Z","request":{"unavailable":"hand-rolled stdio server: no framework request context is mounted"},"runtime":"mcp-server","sequence":2} +{"event":{"canonical":{"event":"tool/after","idempotencyKey":"b0964c77a97ee7b0576a4176c9fdfbf611d928c3a6150704a0af36369c26c9c2","observedAt":"2026-09-03T08:39:58.678Z","provenance":{"host":"cursor","hostContractRevision":"2026-08-28","nativeEvent":"postToolUse","source":"native"},"sequence":53},"native":{"conversation_id":"46efda32-55c4-436e-854f-5d0b77b908ce","generation_id":"26f71366-24b0-4a9c-b384-495b94a50364","model":"default","tool_name":"MCP:probe","tool_input":{"note":"nested"},"tool_output":"{\"content\":[{\"type\":\"text\",\"text\":\"{\\n \\\"log\\\": \\\"/tmp/host-test/cursor/log/captures.ndjson\\\",\\n \\\"observed\\\": {\\n \\\"client\\\": {\\n \\\"name\\\": \\\"cursor-vscode\\\",\\n \\\"version\\\": \\\"1.0.0\\\"\\…[+774 chars]","duration":11.733,"tool_use_id":"07f4c767-c618-4c89-9fdd-5c1a408e92d4","session_id":"46efda32-55c4-436e-854f-5d0b77b908ce","hook_event_name":"postToolUse","cursor_version":"3.18.25","workspace_roots":["/tmp/host-test/cursor-workspace"],"user_email":"probe@example.invalid","transcript_path":null}},"host":"cursor","kind":"event","process":{"cwd":"/tmp/host-test/cursor-home","entry":"/tmp/host-test/cursor-home/.cursor/plugins/local/host-test/mcp/mcp-host-test-0d229f1b-flight.mjs","pid":197313,"ppid":4119277},"recordedAt":"2026-09-03T08:39:58.681Z","request":{"host":{"source":"native","state":"available","value":{"name":"cursor"}},"invocation":{"kind":"event"},"session":{"source":"native","state":"available","value":{"sessionId":"46efda32-55c4-436e-854f-5d0b77b908ce"}}},"runtime":"shared-runtime","sequence":54} +{"event":{"canonical":{"event":"agent/stop","idempotencyKey":"f81dbc37099d769e1e0c3df349f034a5bcd6893a97da3e946d6bc58184566fb4","observedAt":"2026-09-03T08:40:10.292Z","provenance":{"host":"cursor","hostContractRevision":"2026-08-28","nativeEvent":"subagentStop","source":"native"},"sequence":54},"native":{"conversation_id":"bf617dfd-e03d-4d6b-adef-8f97e7df6b71","generation_id":"bf617dfd-e03d-4d6b-adef-8f97e7df6b71","model":"default","subagent_id":"call-29aa2614-81f6-4e3e-977b-6884e8d5ecf5-12\nfc_93a5d49e-dc4f-9a1a-a996-e646c9ac2513_1","subagent_type":"general-purpose","status":"completed","duration_ms":25995,"parent_conversation_id":"bf617dfd-e03d-4d6b-adef-8f97e7df6b71","message_count":0,"tool_call_count":0,"loop_count":0,"task":"You are a nested subagent exercising the host-test probe. Do these steps in order without asking questions:\n\n1. Run the shell command `pwd`.\n2. Call the host-test-raw `probe` MCP tool with {\"note\":\"ne…[+588 chars]","description":"Nested host-test probe","session_id":"bf617dfd-e03d-4d6b-adef-8f97e7df6b71","hook_event_name":"subagentStop","cursor_version":"3.18.25","workspace_roots":["/tmp/host-test/cursor-workspace"],"user_email":"probe@example.invalid","transcript_path":null,"agent_transcript_path":null}},"host":"cursor","kind":"event","process":{"cwd":"/tmp/host-test/cursor-home","entry":"/tmp/host-test/cursor-home/.cursor/plugins/local/host-test/mcp/mcp-host-test-0d229f1b-flight.mjs","pid":197313,"ppid":4119277},"recordedAt":"2026-09-03T08:40:10.295Z","request":{"host":{"source":"native","state":"available","value":{"name":"cursor"}},"invocation":{"kind":"event"},"session":{"source":"native","state":"available","value":{"sessionId":"bf617dfd-e03d-4d6b-adef-8f97e7df6b71"}}},"runtime":"shared-runtime","sequence":55} +{"event":{"canonical":{"event":"agent/stop","idempotencyKey":"320dcc53cdcbc99bf150379bdafd24d48b9905758c51b280e20e32bf44a056d2","observedAt":"2026-09-03T08:41:22.238Z","provenance":{"host":"cursor","hostContractRevision":"2026-08-28","nativeEvent":"subagentStop","source":"native"},"sequence":55},"native":{"conversation_id":"b60ae0c1-2f85-4c4d-b3e5-b512f9b06e4c","generation_id":"b60ae0c1-2f85-4c4d-b3e5-b512f9b06e4c","model":"default","subagent_id":"call-2ec9530d-b502-4c4f-8a6e-63f0bf7ebc9a-29\nfc_49466487-df47-9fb4-8b10-079ee845fb97_0","subagent_type":"general-purpose","status":"completed","duration_ms":139598,"parent_conversation_id":"b60ae0c1-2f85-4c4d-b3e5-b512f9b06e4c","message_count":0,"tool_call_count":0,"loop_count":0,"task":"You are exercising the host-test probe. Do these steps in order without asking questions:\n\n1. Run the shell command `pwd`.\n2. Call the host-test `dump` MCP tool with {}. Remember its log.path. The MCP…[+1100 chars]","description":"Host-test subagent probe","session_id":"b60ae0c1-2f85-4c4d-b3e5-b512f9b06e4c","hook_event_name":"subagentStop","cursor_version":"3.18.25","workspace_roots":["/tmp/host-test/cursor-workspace"],"user_email":"probe@example.invalid","transcript_path":"/tmp/host-test/cursor-home/.cursor/projects/tmp-host-test-cursor-workspace/agent-transcripts/b60ae0c1-2f85-4c4d-b3e5-b512f9b06e4c/b60ae0c1-2f85-4c4d-b3e5-b512f9b06e4c.jsonl","agent_transcript_path":null}},"host":"cursor","kind":"event","process":{"cwd":"/tmp/host-test/cursor-home","entry":"/tmp/host-test/cursor-home/.cursor/plugins/local/host-test/mcp/mcp-host-test-0d229f1b-flight.mjs","pid":197313,"ppid":4119277},"recordedAt":"2026-09-03T08:41:22.242Z","request":{"host":{"source":"native","state":"available","value":{"name":"cursor"}},"invocation":{"kind":"event"},"session":{"source":"native","state":"available","value":{"sessionId":"b60ae0c1-2f85-4c4d-b3e5-b512f9b06e4c"}}},"runtime":"shared-runtime","sequence":56} +{"event":{"canonical":{"event":"tool/before","idempotencyKey":"3b05094399c497a1a51642d2164b58255598e68a1ff77be08ddf65709a3f4c21","observedAt":"2026-09-03T08:41:26.879Z","provenance":{"host":"cursor","hostContractRevision":"2026-08-28","nativeEvent":"preToolUse","source":"native"},"sequence":56},"native":{"conversation_id":"b60ae0c1-2f85-4c4d-b3e5-b512f9b06e4c","generation_id":"d4b2603b-ebfe-45ee-832d-b30d048defbb","model":"default","tool_name":"Shell","tool_input":{"command":"# Check if CallMcpTool appears in recent captures from my session - and get dump path from latest dump record\nrg -n '\"tool\":\"dump\"|\"note\":\"root\"|CallMcpTool' /tmp/host-test/cursor/log/captures.ndjson 2>/dev/null | tail -30\n# Also check if there's a way to invoke via node talking to the MCP - but prefer CallMcpTool\n# List tool files again to ensure we have the right server id\ncat /tmp/host-test/cur…[+110 chars]","cwd":"","timeout":30000},"tool_use_id":"4dffd7bc-21e0-48e7-b83a-98d83720dd29","cwd":"","session_id":"b60ae0c1-2f85-4c4d-b3e5-b512f9b06e4c","hook_event_name":"preToolUse","cursor_version":"3.18.25","workspace_roots":["/tmp/host-test/cursor-workspace"],"user_email":"probe@example.invalid","transcript_path":"/tmp/host-test/cursor-home/.cursor/projects/tmp-host-test-cursor-workspace/agent-transcripts/b60ae0c1-2f85-4c4d-b3e5-b512f9b06e4c/b60ae0c1-2f85-4c4d-b3e5-b512f9b06e4c.jsonl"}},"host":"cursor","kind":"event","process":{"cwd":"/tmp/host-test/cursor-home","entry":"/tmp/host-test/cursor-home/.cursor/plugins/local/host-test/mcp/mcp-host-test-0d229f1b-flight.mjs","pid":197313,"ppid":4119277},"recordedAt":"2026-09-03T08:41:26.882Z","request":{"host":{"source":"native","state":"available","value":{"name":"cursor"}},"invocation":{"kind":"event"},"session":{"source":"native","state":"available","value":{"sessionId":"b60ae0c1-2f85-4c4d-b3e5-b512f9b06e4c"}}},"runtime":"shared-runtime","sequence":57} +{"event":{"canonical":{"event":"tool/after","idempotencyKey":"66c7c85b3c9d2939ac8180073e0e10ae72c39fe15ed5ff107477ba476b1bdede","observedAt":"2026-09-03T08:41:32.316Z","provenance":{"host":"cursor","hostContractRevision":"2026-08-28","nativeEvent":"postToolUse","source":"native"},"sequence":57},"native":{"conversation_id":"b60ae0c1-2f85-4c4d-b3e5-b512f9b06e4c","generation_id":"d4b2603b-ebfe-45ee-832d-b30d048defbb","model":"default","tool_name":"Shell","tool_input":{"command":"# Check if CallMcpTool appears in recent captures from my session - and get dump path from latest dump record\nrg -n '\"tool\":\"dump\"|\"note\":\"root\"|CallMcpTool' /tmp/host-test/cursor/log/captures.ndjson 2>/dev/null | tail -30\n# Also check if there's a way to invoke via node talking to the MCP - but prefer CallMcpTool\n# List tool files again to ensure we have the right server id\ncat /tmp/host-test/cur…[+110 chars]","cwd":"","timeout":30000},"tool_output":"{\"output\":\"30:{\\\"env\\\":{\\\"names\\\":[\\\"AGENT_BUNDLE_PLUGIN_ROOT\\\",\\\"HOST_TEST_LOG_DIR\\\"]},\\\"event\\\":{\\\"canonical\\\":{\\\"event\\\":\\\"tool/before\\\",\\\"idempotencyKey\\\":\\\"1d751d49cc214e7db1f7c80dac766b2631f46b1…[+153896 chars]","duration":5257.842,"tool_use_id":"4dffd7bc-21e0-48e7-b83a-98d83720dd29","cwd":"","session_id":"b60ae0c1-2f85-4c4d-b3e5-b512f9b06e4c","hook_event_name":"postToolUse","cursor_version":"3.18.25","workspace_roots":["/tmp/host-test/cursor-workspace"],"user_email":"probe@example.invalid","transcript_path":"/tmp/host-test/cursor-home/.cursor/projects/tmp-host-test-cursor-workspace/agent-transcripts/b60ae0c1-2f85-4c4d-b3e5-b512f9b06e4c/b60ae0c1-2f85-4c4d-b3e5-b512f9b06e4c.jsonl"}},"host":"cursor","kind":"event","process":{"cwd":"/tmp/host-test/cursor-home","entry":"/tmp/host-test/cursor-home/.cursor/plugins/local/host-test/mcp/mcp-host-test-0d229f1b-flight.mjs","pid":197313,"ppid":4119277},"recordedAt":"2026-09-03T08:41:32.320Z","request":{"host":{"source":"native","state":"available","value":{"name":"cursor"}},"invocation":{"kind":"event"},"session":{"source":"native","state":"available","value":{"sessionId":"b60ae0c1-2f85-4c4d-b3e5-b512f9b06e4c"}}},"runtime":"shared-runtime","sequence":58} +{"event":{"canonical":{"event":"tool/before","idempotencyKey":"f1049cbf5a5eecfd1abed130f023ca785176d6e8a77208012799a23b9fc629e3","observedAt":"2026-09-03T08:41:42.374Z","provenance":{"host":"cursor","hostContractRevision":"2026-08-28","nativeEvent":"preToolUse","source":"native"},"sequence":62},"native":{"conversation_id":"b60ae0c1-2f85-4c4d-b3e5-b512f9b06e4c","generation_id":"d4b2603b-ebfe-45ee-832d-b30d048defbb","model":"default","tool_name":"Shell","tool_input":{"command":"# Extract just dump log.path from most recent dump MCP record without dumping huge lines\npython3 - <<'PY'\nimport json\npath='/tmp/host-test/cursor/log/captures.ndjson'\ndumps=[]\nprobes=[]\nwith open(path) as f:\n for line in f:\n try:\n o=json.loads(line)\n except Exception:\n continue\n kind=o.get('kind')\n if kind=='mcp':\n tool=(o.get('event'…[+1032 chars]","cwd":"","timeout":30000},"tool_use_id":"86b49414-c7b6-4a80-a27a-2ad186a751bc","cwd":"","session_id":"b60ae0c1-2f85-4c4d-b3e5-b512f9b06e4c","hook_event_name":"preToolUse","cursor_version":"3.18.25","workspace_roots":["/tmp/host-test/cursor-workspace"],"user_email":"probe@example.invalid","transcript_path":"/tmp/host-test/cursor-home/.cursor/projects/tmp-host-test-cursor-workspace/agent-transcripts/b60ae0c1-2f85-4c4d-b3e5-b512f9b06e4c/b60ae0c1-2f85-4c4d-b3e5-b512f9b06e4c.jsonl"}},"host":"cursor","kind":"event","process":{"cwd":"/tmp/host-test/cursor-home","entry":"/tmp/host-test/cursor-home/.cursor/plugins/local/host-test/mcp/mcp-host-test-0d229f1b-flight.mjs","pid":197313,"ppid":4119277},"recordedAt":"2026-09-03T08:41:42.378Z","request":{"host":{"source":"native","state":"available","value":{"name":"cursor"}},"invocation":{"kind":"event"},"session":{"source":"native","state":"available","value":{"sessionId":"b60ae0c1-2f85-4c4d-b3e5-b512f9b06e4c"}}},"runtime":"shared-runtime","sequence":63} +{"event":{"canonical":{"event":"tool/before","idempotencyKey":"d94891c115bc727cd5b36fe26010a3b4de60ee5c6f32cb1fa705d72909d44e0f","observedAt":"2026-09-03T08:41:46.835Z","provenance":{"host":"cursor","hostContractRevision":"2026-08-28","nativeEvent":"preToolUse","source":"native"},"sequence":63},"native":{"conversation_id":"b60ae0c1-2f85-4c4d-b3e5-b512f9b06e4c","generation_id":"d4b2603b-ebfe-45ee-832d-b30d048defbb","model":"default","tool_name":"Shell","tool_input":{"command":"# Use a tiny MCP client over stdio to call dump and probe the same way the host would — but that won't go through Cursor's MCP bridge.\n# Instead, check whether cursor agent has an invoke helper, or use the flight worker IPC if any.\nls /tmp/host-test/cursor-home/.cursor/plugins/local/host-test/mcp/\n# Look for unix sockets related to host-test MCP\nls -la /tmp/host-test/cursor-home/.cursor/plugins/lo…[+202 chars]","cwd":"","timeout":30000},"tool_use_id":"1b0a555e-cec5-46ac-bee6-d3ba53bcc477","cwd":"","session_id":"b60ae0c1-2f85-4c4d-b3e5-b512f9b06e4c","hook_event_name":"preToolUse","cursor_version":"3.18.25","workspace_roots":["/tmp/host-test/cursor-workspace"],"user_email":"probe@example.invalid","transcript_path":"/tmp/host-test/cursor-home/.cursor/projects/tmp-host-test-cursor-workspace/agent-transcripts/b60ae0c1-2f85-4c4d-b3e5-b512f9b06e4c/b60ae0c1-2f85-4c4d-b3e5-b512f9b06e4c.jsonl"}},"host":"cursor","kind":"event","process":{"cwd":"/tmp/host-test/cursor-home","entry":"/tmp/host-test/cursor-home/.cursor/plugins/local/host-test/mcp/mcp-host-test-0d229f1b-flight.mjs","pid":197313,"ppid":4119277},"recordedAt":"2026-09-03T08:41:46.842Z","request":{"host":{"source":"native","state":"available","value":{"name":"cursor"}},"invocation":{"kind":"event"},"session":{"source":"native","state":"available","value":{"sessionId":"b60ae0c1-2f85-4c4d-b3e5-b512f9b06e4c"}}},"runtime":"shared-runtime","sequence":64} +{"event":{"canonical":{"event":"tool/after","idempotencyKey":"7a5cd97e5093d37bc54311207c07cefdfee78bc3c0e4bf9035477cc99ffa59bc","observedAt":"2026-09-03T08:42:17.093Z","provenance":{"host":"cursor","hostContractRevision":"2026-08-28","nativeEvent":"postToolUse","source":"native"},"sequence":64},"native":{"conversation_id":"b60ae0c1-2f85-4c4d-b3e5-b512f9b06e4c","generation_id":"d4b2603b-ebfe-45ee-832d-b30d048defbb","model":"default","tool_name":"Shell","tool_input":{"command":"# Use a tiny MCP client over stdio to call dump and probe the same way the host would — but that won't go through Cursor's MCP bridge.\n# Instead, check whether cursor agent has an invoke helper, or use the flight worker IPC if any.\nls /tmp/host-test/cursor-home/.cursor/plugins/local/host-test/mcp/\n# Look for unix sockets related to host-test MCP\nls -la /tmp/host-test/cursor-home/.cursor/plugins/lo…[+202 chars]","cwd":"","timeout":30000},"tool_output":"{\"output\":\"mcp-host-test-0d229f1b-flight.mjs\\nmcp-host-test-0d229f1b.mjs\\nmcp-host-test-raw-6e9c1a1c.mjs\\ntotal 10840\\n-rw-r--r-- 1 root root 20480 Sep 3 08:35 -agent-bundle-runtime-agent-notice-le…[+651 chars]","duration":30045.52,"tool_use_id":"1b0a555e-cec5-46ac-bee6-d3ba53bcc477","cwd":"","session_id":"b60ae0c1-2f85-4c4d-b3e5-b512f9b06e4c","hook_event_name":"postToolUse","cursor_version":"3.18.25","workspace_roots":["/tmp/host-test/cursor-workspace"],"user_email":"probe@example.invalid","transcript_path":"/tmp/host-test/cursor-home/.cursor/projects/tmp-host-test-cursor-workspace/agent-transcripts/b60ae0c1-2f85-4c4d-b3e5-b512f9b06e4c/b60ae0c1-2f85-4c4d-b3e5-b512f9b06e4c.jsonl"}},"host":"cursor","kind":"event","process":{"cwd":"/tmp/host-test/cursor-home","entry":"/tmp/host-test/cursor-home/.cursor/plugins/local/host-test/mcp/mcp-host-test-0d229f1b-flight.mjs","pid":197313,"ppid":4119277},"recordedAt":"2026-09-03T08:42:17.095Z","request":{"host":{"source":"native","state":"available","value":{"name":"cursor"}},"invocation":{"kind":"event"},"session":{"source":"native","state":"available","value":{"sessionId":"b60ae0c1-2f85-4c4d-b3e5-b512f9b06e4c"}}},"runtime":"shared-runtime","sequence":65} +{"event":{"canonical":{"event":"tool/before","idempotencyKey":"6654f98ce6dcd011f56c4b8ec5a35f6292012f8662a3e457e80bfcb2a68d7084","observedAt":"2026-09-03T08:42:35.906Z","provenance":{"host":"cursor","hostContractRevision":"2026-08-28","nativeEvent":"preToolUse","source":"native"},"sequence":67},"native":{"conversation_id":"b60ae0c1-2f85-4c4d-b3e5-b512f9b06e4c","generation_id":"d4b2603b-ebfe-45ee-832d-b30d048defbb","model":"default","tool_name":"Shell","tool_input":{"command":"# Confirm probe-note.txt exists from step 2; print pwd again is not needed\ntest -f /tmp/host-test/cursor-workspace/probe-note.txt && cat /tmp/host-test/cursor-workspace/probe-note.txt\n# Show dump descriptor path exists (already read)\ntest -f /tmp/host-test/cursor-home/.cursor/projects/tmp-host-test-cursor-workspace/mcps/plugin-host-test-host-test/tools/dump.json && echo dump_schema_ok\ntest -f /tmp…[+148 chars]","cwd":"","timeout":30000},"tool_use_id":"92ca08dc-3bde-403c-9513-f5e91400fcf8","cwd":"","session_id":"b60ae0c1-2f85-4c4d-b3e5-b512f9b06e4c","hook_event_name":"preToolUse","cursor_version":"3.18.25","workspace_roots":["/tmp/host-test/cursor-workspace"],"user_email":"probe@example.invalid","transcript_path":"/tmp/host-test/cursor-home/.cursor/projects/tmp-host-test-cursor-workspace/agent-transcripts/b60ae0c1-2f85-4c4d-b3e5-b512f9b06e4c/b60ae0c1-2f85-4c4d-b3e5-b512f9b06e4c.jsonl"}},"host":"cursor","kind":"event","process":{"cwd":"/tmp/host-test/cursor-home","entry":"/tmp/host-test/cursor-home/.cursor/plugins/local/host-test/mcp/mcp-host-test-0d229f1b-flight.mjs","pid":197313,"ppid":4119277},"recordedAt":"2026-09-03T08:42:35.908Z","request":{"host":{"source":"native","state":"available","value":{"name":"cursor"}},"invocation":{"kind":"event"},"session":{"source":"native","state":"available","value":{"sessionId":"b60ae0c1-2f85-4c4d-b3e5-b512f9b06e4c"}}},"runtime":"shared-runtime","sequence":68} +{"event":{"canonical":{"event":"tool/after","idempotencyKey":"9b64505ed089142096e3af91ab754456c8880ee7f48e30fcd11c279393c83ada","observedAt":"2026-09-03T08:42:41.199Z","provenance":{"host":"cursor","hostContractRevision":"2026-08-28","nativeEvent":"postToolUse","source":"native"},"sequence":68},"native":{"conversation_id":"b60ae0c1-2f85-4c4d-b3e5-b512f9b06e4c","generation_id":"d4b2603b-ebfe-45ee-832d-b30d048defbb","model":"default","tool_name":"Shell","tool_input":{"command":"# Confirm probe-note.txt exists from step 2; print pwd again is not needed\ntest -f /tmp/host-test/cursor-workspace/probe-note.txt && cat /tmp/host-test/cursor-workspace/probe-note.txt\n# Show dump descriptor path exists (already read)\ntest -f /tmp/host-test/cursor-home/.cursor/projects/tmp-host-test-cursor-workspace/mcps/plugin-host-test-host-test/tools/dump.json && echo dump_schema_ok\ntest -f /tmp…[+148 chars]","cwd":"","timeout":30000},"tool_output":"{\"output\":\"host-test\\ndump_schema_ok\\nprobe_schema_ok\\n\",\"exitCode\":0}","duration":5142.91,"tool_use_id":"92ca08dc-3bde-403c-9513-f5e91400fcf8","cwd":"","session_id":"b60ae0c1-2f85-4c4d-b3e5-b512f9b06e4c","hook_event_name":"postToolUse","cursor_version":"3.18.25","workspace_roots":["/tmp/host-test/cursor-workspace"],"user_email":"probe@example.invalid","transcript_path":"/tmp/host-test/cursor-home/.cursor/projects/tmp-host-test-cursor-workspace/agent-transcripts/b60ae0c1-2f85-4c4d-b3e5-b512f9b06e4c/b60ae0c1-2f85-4c4d-b3e5-b512f9b06e4c.jsonl"}},"host":"cursor","kind":"event","process":{"cwd":"/tmp/host-test/cursor-home","entry":"/tmp/host-test/cursor-home/.cursor/plugins/local/host-test/mcp/mcp-host-test-0d229f1b-flight.mjs","pid":197313,"ppid":4119277},"recordedAt":"2026-09-03T08:42:41.201Z","request":{"host":{"source":"native","state":"available","value":{"name":"cursor"}},"invocation":{"kind":"event"},"session":{"source":"native","state":"available","value":{"sessionId":"b60ae0c1-2f85-4c4d-b3e5-b512f9b06e4c"}}},"runtime":"shared-runtime","sequence":69} +{"event":{"canonical":{"event":"tool/before","idempotencyKey":"64109a47d7e0261e5c2e105270b0a72ad11c577630229bfb764618b944ed15ce","observedAt":"2026-09-03T08:42:50.938Z","provenance":{"host":"cursor","hostContractRevision":"2026-08-28","nativeEvent":"preToolUse","source":"native"},"sequence":71},"native":{"conversation_id":"b60ae0c1-2f85-4c4d-b3e5-b512f9b06e4c","generation_id":"d4b2603b-ebfe-45ee-832d-b30d048defbb","model":"default","tool_name":"Shell","tool_input":{"command":"# Inspect whether GetMcpTools / CallMcpTool are expected in this agent's tool list by reading the composer matterhorn tool wiring message in logs\nrg -a -n 'CallMcpTool|GetMcpTools|plugin-host-test' /tmp/host-test/cursor-home/.config/Cursor/logs/20260903T083216/window1/*.log 2>/dev/null | tail -40\n# Also check agent transcript for tool definitions sent to me\npython3 - <<'PY'\nimport json, os\np='/tmp…[+579 chars]","cwd":"","timeout":30000},"tool_use_id":"5a1fc00f-dacc-4554-a600-c83edb970be8","cwd":"","session_id":"b60ae0c1-2f85-4c4d-b3e5-b512f9b06e4c","hook_event_name":"preToolUse","cursor_version":"3.18.25","workspace_roots":["/tmp/host-test/cursor-workspace"],"user_email":"probe@example.invalid","transcript_path":"/tmp/host-test/cursor-home/.cursor/projects/tmp-host-test-cursor-workspace/agent-transcripts/b60ae0c1-2f85-4c4d-b3e5-b512f9b06e4c/b60ae0c1-2f85-4c4d-b3e5-b512f9b06e4c.jsonl"}},"host":"cursor","kind":"event","process":{"cwd":"/tmp/host-test/cursor-home","entry":"/tmp/host-test/cursor-home/.cursor/plugins/local/host-test/mcp/mcp-host-test-0d229f1b-flight.mjs","pid":197313,"ppid":4119277},"recordedAt":"2026-09-03T08:42:50.940Z","request":{"host":{"source":"native","state":"available","value":{"name":"cursor"}},"invocation":{"kind":"event"},"session":{"source":"native","state":"available","value":{"sessionId":"b60ae0c1-2f85-4c4d-b3e5-b512f9b06e4c"}}},"runtime":"shared-runtime","sequence":72} +{"event":{"canonical":{"event":"tool/after","idempotencyKey":"0e6de723c73136c5ff54bde8e9a5b68cbd182f9530aba3e44ee9e7092b97d05a","observedAt":"2026-09-03T08:42:51.212Z","provenance":{"host":"cursor","hostContractRevision":"2026-08-28","nativeEvent":"postToolUse","source":"native"},"sequence":72},"native":{"conversation_id":"b60ae0c1-2f85-4c4d-b3e5-b512f9b06e4c","generation_id":"d4b2603b-ebfe-45ee-832d-b30d048defbb","model":"default","tool_name":"Shell","tool_input":{"command":"# Inspect whether GetMcpTools / CallMcpTool are expected in this agent's tool list by reading the composer matterhorn tool wiring message in logs\nrg -a -n 'CallMcpTool|GetMcpTools|plugin-host-test' /tmp/host-test/cursor-home/.config/Cursor/logs/20260903T083216/window1/*.log 2>/dev/null | tail -40\n# Also check agent transcript for tool definitions sent to me\npython3 - <<'PY'\nimport json, os\np='/tmp…[+579 chars]","cwd":"","timeout":30000},"tool_output":"{\"output\":\"/tmp/host-test/cursor-home/.config/Cursor/logs/20260903T083216/window1/workbench.mcp.allowlist.log:19:2026-09-03 08:35:25.467 [info] [MCPService] createClient: identifier=\\\"plugin-host-test…[+2330 chars]","duration":120.128,"tool_use_id":"5a1fc00f-dacc-4554-a600-c83edb970be8","cwd":"","session_id":"b60ae0c1-2f85-4c4d-b3e5-b512f9b06e4c","hook_event_name":"postToolUse","cursor_version":"3.18.25","workspace_roots":["/tmp/host-test/cursor-workspace"],"user_email":"probe@example.invalid","transcript_path":"/tmp/host-test/cursor-home/.cursor/projects/tmp-host-test-cursor-workspace/agent-transcripts/b60ae0c1-2f85-4c4d-b3e5-b512f9b06e4c/b60ae0c1-2f85-4c4d-b3e5-b512f9b06e4c.jsonl"}},"host":"cursor","kind":"event","process":{"cwd":"/tmp/host-test/cursor-home","entry":"/tmp/host-test/cursor-home/.cursor/plugins/local/host-test/mcp/mcp-host-test-0d229f1b-flight.mjs","pid":197313,"ppid":4119277},"recordedAt":"2026-09-03T08:42:51.214Z","request":{"host":{"source":"native","state":"available","value":{"name":"cursor"}},"invocation":{"kind":"event"},"session":{"source":"native","state":"available","value":{"sessionId":"b60ae0c1-2f85-4c4d-b3e5-b512f9b06e4c"}}},"runtime":"shared-runtime","sequence":73} +{"event":{"canonical":{"event":"tool/before","idempotencyKey":"d88a94a05473d23036ddd0bfcacd979512b2cda97956741af6765c7a0554a77f","observedAt":"2026-09-03T08:42:56.222Z","provenance":{"host":"cursor","hostContractRevision":"2026-08-28","nativeEvent":"preToolUse","source":"native"},"sequence":73},"native":{"conversation_id":"b60ae0c1-2f85-4c4d-b3e5-b512f9b06e4c","generation_id":"d4b2603b-ebfe-45ee-832d-b30d048defbb","model":"","tool_name":"Task","tool_input":{"description":"Root dump and probe","prompt":"Call these two MCP tools in order and return their full JSON results verbatim. Do nothing else.\n\n1) CallMcpTool with server=`plugin-host-test-host-test`, toolName=`dump`, arguments=`{}`\n (descriptor already at /tmp/host-test/cursor-home/.cursor/projects/tmp-host-test-cursor-workspace/mcps/plugin-host-test-host-test/tools/dump.json)\n\n2) CallMcpTool with server=`plugin-host-test-host-test-raw`, to…[+298 chars]","model":"inherit","subagent_type":"generalPurpose","run_in_background":false},"tool_use_id":"call-7e307548-94ae-4cad-a0f5-9f259da62a4a-40\nfc_98235bb8-f81a-95c9-a28f-e733cae6f1d4_0","session_id":"b60ae0c1-2f85-4c4d-b3e5-b512f9b06e4c","hook_event_name":"preToolUse","cursor_version":"3.18.25","workspace_roots":["/tmp/host-test/cursor-workspace"],"user_email":"probe@example.invalid","transcript_path":"/tmp/host-test/cursor-home/.cursor/projects/tmp-host-test-cursor-workspace/agent-transcripts/b60ae0c1-2f85-4c4d-b3e5-b512f9b06e4c/b60ae0c1-2f85-4c4d-b3e5-b512f9b06e4c.jsonl"}},"host":"cursor","kind":"event","process":{"cwd":"/tmp/host-test/cursor-home","entry":"/tmp/host-test/cursor-home/.cursor/plugins/local/host-test/mcp/mcp-host-test-0d229f1b-flight.mjs","pid":197313,"ppid":4119277},"recordedAt":"2026-09-03T08:42:56.225Z","request":{"host":{"source":"native","state":"available","value":{"name":"cursor"}},"invocation":{"kind":"event"},"session":{"source":"native","state":"available","value":{"sessionId":"b60ae0c1-2f85-4c4d-b3e5-b512f9b06e4c"}}},"runtime":"shared-runtime","sequence":74} +{"event":{"canonical":{"event":"agent/start","idempotencyKey":"01dc1856ccab70112d7d2d1ff9353f694f1458d219e7a6fa18fa2c5069fbc2e9","observedAt":"2026-09-03T08:42:56.494Z","provenance":{"host":"cursor","hostContractRevision":"2026-08-28","nativeEvent":"subagentStart","source":"native"},"sequence":74},"native":{"conversation_id":"b60ae0c1-2f85-4c4d-b3e5-b512f9b06e4c","generation_id":"b60ae0c1-2f85-4c4d-b3e5-b512f9b06e4c","model":"default","subagent_id":"call-7e307548-94ae-4cad-a0f5-9f259da62a4a-40\nfc_98235bb8-f81a-95c9-a28f-e733cae6f1d4_0","subagent_type":"general-purpose","task":"Call these two MCP tools in order and return their full JSON results verbatim. Do nothing else.\n\n1) CallMcpTool with server=`plugin-host-test-host-test`, toolName=`dump`, arguments=`{}`\n (descriptor…[+498 chars]","parent_conversation_id":"b60ae0c1-2f85-4c4d-b3e5-b512f9b06e4c","tool_call_id":"call-7e307548-94ae-4cad-a0f5-9f259da62a4a-40\nfc_98235bb8-f81a-95c9-a28f-e733cae6f1d4_0","subagent_model":"default","is_parallel_worker":false,"session_id":"b60ae0c1-2f85-4c4d-b3e5-b512f9b06e4c","hook_event_name":"subagentStart","cursor_version":"3.18.25","workspace_roots":["/tmp/host-test/cursor-workspace"],"user_email":"probe@example.invalid","transcript_path":"/tmp/host-test/cursor-home/.cursor/projects/tmp-host-test-cursor-workspace/agent-transcripts/b60ae0c1-2f85-4c4d-b3e5-b512f9b06e4c/b60ae0c1-2f85-4c4d-b3e5-b512f9b06e4c.jsonl"}},"host":"cursor","kind":"event","process":{"cwd":"/tmp/host-test/cursor-home","entry":"/tmp/host-test/cursor-home/.cursor/plugins/local/host-test/mcp/mcp-host-test-0d229f1b-flight.mjs","pid":197313,"ppid":4119277},"recordedAt":"2026-09-03T08:42:56.496Z","request":{"host":{"source":"native","state":"available","value":{"name":"cursor"}},"invocation":{"kind":"event"},"session":{"source":"native","state":"available","value":{"sessionId":"b60ae0c1-2f85-4c4d-b3e5-b512f9b06e4c"}}},"runtime":"shared-runtime","sequence":75} +{"event":{"canonical":{"event":"tool/before","idempotencyKey":"b66020a7fdd8b70e26cdd9f427555fddb65e3e5bca3e13dcdfcc0b2b0b5db241","observedAt":"2026-09-03T08:43:06.873Z","provenance":{"host":"cursor","hostContractRevision":"2026-08-28","nativeEvent":"preToolUse","source":"native"},"sequence":75},"native":{"conversation_id":"9f26d535-5d39-4248-a9b2-2faaa07cd364","generation_id":"792f90af-a361-4bb5-ae05-f97d035fde34","model":"default","tool_name":"Read","tool_input":{"file_path":"/tmp/host-test/cursor-home/.cursor/projects/tmp-host-test-cursor-workspace/mcps/plugin-host-test-host-test/tools/dump.json"},"tool_use_id":"call-479d6391-3dac-4fd4-9840-0b308ffd8982-1\nfc_997bc07b-6ffe-9114-8648-5448fa05e73a_1","session_id":"9f26d535-5d39-4248-a9b2-2faaa07cd364","hook_event_name":"preToolUse","cursor_version":"3.18.25","workspace_roots":["/tmp/host-test/cursor-workspace"],"user_email":"probe@example.invalid","transcript_path":null}},"host":"cursor","kind":"event","process":{"cwd":"/tmp/host-test/cursor-home","entry":"/tmp/host-test/cursor-home/.cursor/plugins/local/host-test/mcp/mcp-host-test-0d229f1b-flight.mjs","pid":197313,"ppid":4119277},"recordedAt":"2026-09-03T08:43:06.875Z","request":{"host":{"source":"native","state":"available","value":{"name":"cursor"}},"invocation":{"kind":"event"},"session":{"source":"native","state":"available","value":{"sessionId":"9f26d535-5d39-4248-a9b2-2faaa07cd364"}}},"runtime":"shared-runtime","sequence":76} +{"event":{"canonical":{"event":"tool/after","idempotencyKey":"ebc6a0de11a4cadb57712bd130a1538c10a1fb8d08796de5c9c1099b105c123c","observedAt":"2026-09-03T08:43:07.097Z","provenance":{"host":"cursor","hostContractRevision":"2026-08-28","nativeEvent":"postToolUse","source":"native"},"sequence":77},"native":{"conversation_id":"9f26d535-5d39-4248-a9b2-2faaa07cd364","generation_id":"792f90af-a361-4bb5-ae05-f97d035fde34","model":"default","tool_name":"Read","tool_input":{"file_path":"/tmp/host-test/cursor-home/.cursor/projects/tmp-host-test-cursor-workspace/mcps/plugin-host-test-host-test/tools/dump.json"},"tool_output":"{\"file_path\":\"/tmp/host-test/cursor-home/.cursor/projects/tmp-host-test-cursor-workspace/mcps/plugin-host-test-host-test/tools/dump.json\",\"content_length\":3562}","duration":3.434,"tool_use_id":"call-479d6391-3dac-4fd4-9840-0b308ffd8982-1\nfc_997bc07b-6ffe-9114-8648-5448fa05e73a_1","session_id":"9f26d535-5d39-4248-a9b2-2faaa07cd364","hook_event_name":"postToolUse","cursor_version":"3.18.25","workspace_roots":["/tmp/host-test/cursor-workspace"],"user_email":"probe@example.invalid","transcript_path":null}},"host":"cursor","kind":"event","process":{"cwd":"/tmp/host-test/cursor-home","entry":"/tmp/host-test/cursor-home/.cursor/plugins/local/host-test/mcp/mcp-host-test-0d229f1b-flight.mjs","pid":197313,"ppid":4119277},"recordedAt":"2026-09-03T08:43:07.101Z","request":{"host":{"source":"native","state":"available","value":{"name":"cursor"}},"invocation":{"kind":"event"},"session":{"source":"native","state":"available","value":{"sessionId":"9f26d535-5d39-4248-a9b2-2faaa07cd364"}}},"runtime":"shared-runtime","sequence":78} +{"event":{"canonical":{"event":"tool/before","idempotencyKey":"217ce2fee62d6afabddfb683cd0527258ea4501e1da432f21d4e0b7be9e48985","observedAt":"2026-09-03T08:43:11.929Z","provenance":{"host":"cursor","hostContractRevision":"2026-08-28","nativeEvent":"preToolUse","source":"native"},"sequence":79},"native":{"conversation_id":"9f26d535-5d39-4248-a9b2-2faaa07cd364","generation_id":"792f90af-a361-4bb5-ae05-f97d035fde34","model":"default","tool_name":"MCP:dump","tool_input":{},"tool_use_id":"06c5ca4a-a80b-4547-ab9b-26c040ce62e2","session_id":"9f26d535-5d39-4248-a9b2-2faaa07cd364","hook_event_name":"preToolUse","cursor_version":"3.18.25","workspace_roots":["/tmp/host-test/cursor-workspace"],"user_email":"probe@example.invalid","transcript_path":null}},"host":"cursor","kind":"event","process":{"cwd":"/tmp/host-test/cursor-home","entry":"/tmp/host-test/cursor-home/.cursor/plugins/local/host-test/mcp/mcp-host-test-0d229f1b-flight.mjs","pid":197313,"ppid":4119277},"recordedAt":"2026-09-03T08:43:11.932Z","request":{"host":{"source":"native","state":"available","value":{"name":"cursor"}},"invocation":{"kind":"event"},"session":{"source":"native","state":"available","value":{"sessionId":"9f26d535-5d39-4248-a9b2-2faaa07cd364"}}},"runtime":"shared-runtime","sequence":80} +{"host":"cursor-vscode","kind":"mcp","observed":{"tool":"dump"},"process":{"cwd":"/tmp/host-test/cursor-home","entry":"/tmp/host-test/cursor-home/.cursor/plugins/local/host-test/mcp/mcp-host-test-0d229f1b-flight.mjs","pid":197313,"ppid":4119277},"recordedAt":"2026-09-03T08:43:11.974Z","request":{"host":{"source":"native","state":"available","value":{"name":"cursor-vscode"}},"invocation":{"kind":"tool"},"session":{"reason":"not-provided","state":"unavailable"}},"runtime":"mcp-server","sequence":81} +{"event":{"canonical":{"event":"tool/after","idempotencyKey":"e05656dd131d9a37100033c27239fa265c3570d6efac4e790405d0eee91f1973","observedAt":"2026-09-03T08:43:12.204Z","provenance":{"host":"cursor","hostContractRevision":"2026-08-28","nativeEvent":"postToolUse","source":"native"},"sequence":80},"native":{"conversation_id":"9f26d535-5d39-4248-a9b2-2faaa07cd364","generation_id":"792f90af-a361-4bb5-ae05-f97d035fde34","model":"default","tool_name":"MCP:dump","tool_input":{},"tool_output":"{\"content\":[{\"type\":\"text\",\"text\":\"\"}],\"isError\":false}","duration":108.443,"tool_use_id":"06c5ca4a-a80b-4547-ab9b-26c040ce62e2","session_id":"9f26d535-5d39-4248-a9b2-2faaa07cd364","hook_event_name":"postToolUse","cursor_version":"3.18.25","workspace_roots":["/tmp/host-test/cursor-workspace"],"user_email":"probe@example.invalid","transcript_path":null}},"host":"cursor","kind":"event","process":{"cwd":"/tmp/host-test/cursor-home","entry":"/tmp/host-test/cursor-home/.cursor/plugins/local/host-test/mcp/mcp-host-test-0d229f1b-flight.mjs","pid":197313,"ppid":4119277},"recordedAt":"2026-09-03T08:43:12.206Z","request":{"host":{"source":"native","state":"available","value":{"name":"cursor"}},"invocation":{"kind":"event"},"session":{"source":"native","state":"available","value":{"sessionId":"9f26d535-5d39-4248-a9b2-2faaa07cd364"}}},"runtime":"shared-runtime","sequence":82} +{"event":{"canonical":{"event":"tool/before","idempotencyKey":"25b1a41eb71f3b1303e41c4c762e3e0c0e7451ed19deb28be5b74df50f1d0400","observedAt":"2026-09-03T08:43:16.303Z","provenance":{"host":"cursor","hostContractRevision":"2026-08-28","nativeEvent":"preToolUse","source":"native"},"sequence":83},"native":{"conversation_id":"9f26d535-5d39-4248-a9b2-2faaa07cd364","generation_id":"792f90af-a361-4bb5-ae05-f97d035fde34","model":"default","tool_name":"MCP:probe","tool_input":{"note":"root"},"tool_use_id":"bcab3099-404d-46dd-86df-e42c5eed56d5","session_id":"9f26d535-5d39-4248-a9b2-2faaa07cd364","hook_event_name":"preToolUse","cursor_version":"3.18.25","workspace_roots":["/tmp/host-test/cursor-workspace"],"user_email":"probe@example.invalid","transcript_path":null}},"host":"cursor","kind":"event","process":{"cwd":"/tmp/host-test/cursor-home","entry":"/tmp/host-test/cursor-home/.cursor/plugins/local/host-test/mcp/mcp-host-test-0d229f1b-flight.mjs","pid":197313,"ppid":4119277},"recordedAt":"2026-09-03T08:43:16.306Z","request":{"host":{"source":"native","state":"available","value":{"name":"cursor"}},"invocation":{"kind":"event"},"session":{"source":"native","state":"available","value":{"sessionId":"9f26d535-5d39-4248-a9b2-2faaa07cd364"}}},"runtime":"shared-runtime","sequence":85} +{"host":"cursor-vscode","kind":"mcp","observed":{"client":{"name":"cursor-vscode","version":"1.0.0"},"clientCapabilities":{"elicitation":{"form":{}},"roots":{"listChanged":false},"extensions":{"io.modelcontextprotocol/ui":{"mimeTypes":["text/html;profile=mcp-app"]}}},"env":{"names":["AGENT_BUNDLE_PLUGIN_ROOT","HOST_TEST_LOG_DIR"]},"http":null,"mcpReq":{"_meta":{"progressToken":4},"envelope":null,"id":4,"method":"tools/call"},"note":"root","sessionId":null,"tool":"probe"},"process":{"cwd":"/tmp/host-test/cursor-home","entry":"/tmp/host-test/cursor-home/.cursor/plugins/local/host-test/mcp/mcp-host-test-raw-6e9c1a1c.mjs","pid":197724,"ppid":4119277},"recordedAt":"2026-09-03T08:43:16.401Z","request":{"unavailable":"hand-rolled stdio server: no framework request context is mounted"},"runtime":"mcp-server","sequence":3} +{"event":{"canonical":{"event":"tool/before","idempotencyKey":"73b02620305ddfe470d1ac9e332882cffef754494a1c594900409c04b62c8aed","observedAt":"2026-09-03T08:43:26.338Z","provenance":{"host":"cursor","hostContractRevision":"2026-08-28","nativeEvent":"preToolUse","source":"native"},"sequence":85},"native":{"conversation_id":"9f26d535-5d39-4248-a9b2-2faaa07cd364","generation_id":"792f90af-a361-4bb5-ae05-f97d035fde34","model":"default","tool_name":"Shell","tool_input":{"command":"wc -l /tmp/host-test/cursor-home/.cursor/projects/tmp-host-test-cursor-workspace/agent-tools/74c7a696-0a6a-474c-b8b5-a51146b2c26c.txt; tail -c 2000 /tmp/host-test/cursor-home/.cursor/projects/tmp-host-test-cursor-workspace/agent-tools/74c7a696-0a6a-474c-b8b5-a51146b2c26c.txt; ls -la /tmp/host-test/cursor-home/.cursor/projects/tmp-host-test-cursor-workspace/agent-tools/ | head -50; find /tmp/host-t…[+140 chars]","cwd":"","timeout":30000},"tool_use_id":"4ce13fa9-4111-454a-a2c8-dcf26904f231","cwd":"","session_id":"9f26d535-5d39-4248-a9b2-2faaa07cd364","hook_event_name":"preToolUse","cursor_version":"3.18.25","workspace_roots":["/tmp/host-test/cursor-workspace"],"user_email":"probe@example.invalid","transcript_path":null}},"host":"cursor","kind":"event","process":{"cwd":"/tmp/host-test/cursor-home","entry":"/tmp/host-test/cursor-home/.cursor/plugins/local/host-test/mcp/mcp-host-test-0d229f1b-flight.mjs","pid":197313,"ppid":4119277},"recordedAt":"2026-09-03T08:43:26.341Z","request":{"host":{"source":"native","state":"available","value":{"name":"cursor"}},"invocation":{"kind":"event"},"session":{"source":"native","state":"available","value":{"sessionId":"9f26d535-5d39-4248-a9b2-2faaa07cd364"}}},"runtime":"shared-runtime","sequence":87} +{"event":{"canonical":{"event":"tool/after","idempotencyKey":"1cc9c32861520bf2f67bfdb258ff2bedc871d22a581481bbe88ecfba3e92f308","observedAt":"2026-09-03T08:43:31.632Z","provenance":{"host":"cursor","hostContractRevision":"2026-08-28","nativeEvent":"postToolUse","source":"native"},"sequence":86},"native":{"conversation_id":"9f26d535-5d39-4248-a9b2-2faaa07cd364","generation_id":"792f90af-a361-4bb5-ae05-f97d035fde34","model":"default","tool_name":"Shell","tool_input":{"command":"wc -l /tmp/host-test/cursor-home/.cursor/projects/tmp-host-test-cursor-workspace/agent-tools/74c7a696-0a6a-474c-b8b5-a51146b2c26c.txt; tail -c 2000 /tmp/host-test/cursor-home/.cursor/projects/tmp-host-test-cursor-workspace/agent-tools/74c7a696-0a6a-474c-b8b5-a51146b2c26c.txt; ls -la /tmp/host-test/cursor-home/.cursor/projects/tmp-host-test-cursor-workspace/agent-tools/ | head -50; find /tmp/host-t…[+140 chars]","cwd":"","timeout":30000},"tool_output":"{\"output\":\"214 /tmp/host-test/cursor-home/.cursor/projects/tmp-host-test-cursor-workspace/agent-tools/74c7a696-0a6a-474c-b8b5-a51146b2c26c.txt\\nll,\\\"model\\\":\\\"default\\\",\\\"user_email\\\":\\\"probe@example.…[+2676 chars]","duration":5143.26,"tool_use_id":"4ce13fa9-4111-454a-a2c8-dcf26904f231","cwd":"","session_id":"9f26d535-5d39-4248-a9b2-2faaa07cd364","hook_event_name":"postToolUse","cursor_version":"3.18.25","workspace_roots":["/tmp/host-test/cursor-workspace"],"user_email":"probe@example.invalid","transcript_path":null}},"host":"cursor","kind":"event","process":{"cwd":"/tmp/host-test/cursor-home","entry":"/tmp/host-test/cursor-home/.cursor/plugins/local/host-test/mcp/mcp-host-test-0d229f1b-flight.mjs","pid":197313,"ppid":4119277},"recordedAt":"2026-09-03T08:43:31.634Z","request":{"host":{"source":"native","state":"available","value":{"name":"cursor"}},"invocation":{"kind":"event"},"session":{"source":"native","state":"available","value":{"sessionId":"9f26d535-5d39-4248-a9b2-2faaa07cd364"}}},"runtime":"shared-runtime","sequence":88} +{"event":{"canonical":{"event":"tool/before","idempotencyKey":"96e9b39bcf7a76b59c89cda98d87442f9f55e6820bc0c6c0637bd20b4c3ac478","observedAt":"2026-09-03T08:43:38.774Z","provenance":{"host":"cursor","hostContractRevision":"2026-08-28","nativeEvent":"preToolUse","source":"native"},"sequence":87},"native":{"conversation_id":"9f26d535-5d39-4248-a9b2-2faaa07cd364","generation_id":"792f90af-a361-4bb5-ae05-f97d035fde34","model":"default","tool_name":"Shell","tool_input":{"command":"python3 - <<'PY'\nfrom pathlib import Path\np = Path('/tmp/host-test/cursor-home/.cursor/projects/tmp-host-test-cursor-workspace/agent-tools/74c7a696-0a6a-474c-b8b5-a51146b2c26c.txt')\ntext = p.read_text()\n# find start of JSON object\nidx = text.find('{\"filter\"')\nprint('idx', idx)\nprint('starts with markdown?', text[:20])\nprint('len', len(text))\n# Also look for ```json\nfor marker in ['```json', '```\\n…[+613 chars]","cwd":"","timeout":30000},"tool_use_id":"cfe9a558-3694-4bc5-b636-5b8d84d78793","cwd":"","session_id":"9f26d535-5d39-4248-a9b2-2faaa07cd364","hook_event_name":"preToolUse","cursor_version":"3.18.25","workspace_roots":["/tmp/host-test/cursor-workspace"],"user_email":"probe@example.invalid","transcript_path":null}},"host":"cursor","kind":"event","process":{"cwd":"/tmp/host-test/cursor-home","entry":"/tmp/host-test/cursor-home/.cursor/plugins/local/host-test/mcp/mcp-host-test-0d229f1b-flight.mjs","pid":197313,"ppid":4119277},"recordedAt":"2026-09-03T08:43:38.777Z","request":{"host":{"source":"native","state":"available","value":{"name":"cursor"}},"invocation":{"kind":"event"},"session":{"source":"native","state":"available","value":{"sessionId":"9f26d535-5d39-4248-a9b2-2faaa07cd364"}}},"runtime":"shared-runtime","sequence":89} +{"event":{"canonical":{"event":"tool/after","idempotencyKey":"d7d93f371412042bcb165b0f7c81b62aec91c2a2465ba163e81590699ee5ed5d","observedAt":"2026-09-03T08:43:44.107Z","provenance":{"host":"cursor","hostContractRevision":"2026-08-28","nativeEvent":"postToolUse","source":"native"},"sequence":88},"native":{"conversation_id":"9f26d535-5d39-4248-a9b2-2faaa07cd364","generation_id":"792f90af-a361-4bb5-ae05-f97d035fde34","model":"default","tool_name":"Shell","tool_input":{"command":"python3 - <<'PY'\nfrom pathlib import Path\np = Path('/tmp/host-test/cursor-home/.cursor/projects/tmp-host-test-cursor-workspace/agent-tools/74c7a696-0a6a-474c-b8b5-a51146b2c26c.txt')\ntext = p.read_text()\n# find start of JSON object\nidx = text.find('{\"filter\"')\nprint('idx', idx)\nprint('starts with markdown?', text[:20])\nprint('len', len(text))\n# Also look for ```json\nfor marker in ['```json', '```\\n…[+613 chars]","cwd":"","timeout":30000},"tool_output":"{\"output\":\"idx 49855\\nstarts with markdown? # host-test captures\\nlen 149822\\n```json -1\\n```\\n{ -1\\n\\n{\\\"filter\\\" 49854\\n{\\\"filter\\\" 49855\\nnlines 215\\nline 214 {\\\"filter\\\":{},\\\"log\\\":{\\\"malformed\\\":…[+351 chars]","duration":5180.782,"tool_use_id":"cfe9a558-3694-4bc5-b636-5b8d84d78793","cwd":"","session_id":"9f26d535-5d39-4248-a9b2-2faaa07cd364","hook_event_name":"postToolUse","cursor_version":"3.18.25","workspace_roots":["/tmp/host-test/cursor-workspace"],"user_email":"probe@example.invalid","transcript_path":null}},"host":"cursor","kind":"event","process":{"cwd":"/tmp/host-test/cursor-home","entry":"/tmp/host-test/cursor-home/.cursor/plugins/local/host-test/mcp/mcp-host-test-0d229f1b-flight.mjs","pid":197313,"ppid":4119277},"recordedAt":"2026-09-03T08:43:44.109Z","request":{"host":{"source":"native","state":"available","value":{"name":"cursor"}},"invocation":{"kind":"event"},"session":{"source":"native","state":"available","value":{"sessionId":"9f26d535-5d39-4248-a9b2-2faaa07cd364"}}},"runtime":"shared-runtime","sequence":90} +{"event":{"canonical":{"event":"tool/before","idempotencyKey":"ddfa4612a5ea71058596a6e7eb5d28f483f78e0164c2b552343a7ec4f9d2ddfb","observedAt":"2026-09-03T08:44:01.490Z","provenance":{"host":"cursor","hostContractRevision":"2026-08-28","nativeEvent":"preToolUse","source":"native"},"sequence":89},"native":{"conversation_id":"9f26d535-5d39-4248-a9b2-2faaa07cd364","generation_id":"792f90af-a361-4bb5-ae05-f97d035fde34","model":"default","tool_name":"Shell","tool_input":{"command":"python3 - <<'PY'\nfrom pathlib import Path\nimport json\np = Path('/tmp/host-test/cursor-home/.cursor/projects/tmp-host-test-cursor-workspace/agent-tools/74c7a696-0a6a-474c-b8b5-a51146b2c26c.txt')\ndump = p.read_text().splitlines()[-1]\nobj = json.loads(dump)\nprobe = {\n \"log\": \"/tmp/host-test/cursor/log/captures.ndjson\",\n \"observed\": {\n \"client\": {\n \"name\": \"cursor-vscode\",\n \"version\": \"…[+2067 chars]","cwd":"","timeout":30000},"tool_use_id":"f133fdf9-12c7-44cb-b3ab-e4c09008dbb6","cwd":"","session_id":"9f26d535-5d39-4248-a9b2-2faaa07cd364","hook_event_name":"preToolUse","cursor_version":"3.18.25","workspace_roots":["/tmp/host-test/cursor-workspace"],"user_email":"probe@example.invalid","transcript_path":null}},"host":"cursor","kind":"event","process":{"cwd":"/tmp/host-test/cursor-home","entry":"/tmp/host-test/cursor-home/.cursor/plugins/local/host-test/mcp/mcp-host-test-0d229f1b-flight.mjs","pid":197313,"ppid":4119277},"recordedAt":"2026-09-03T08:44:01.492Z","request":{"host":{"source":"native","state":"available","value":{"name":"cursor"}},"invocation":{"kind":"event"},"session":{"source":"native","state":"available","value":{"sessionId":"9f26d535-5d39-4248-a9b2-2faaa07cd364"}}},"runtime":"shared-runtime","sequence":91} +{"event":{"canonical":{"event":"tool/after","idempotencyKey":"5216f71769ac763d72f7bddde81d6ef2233618f5e278eb159055948029bfcf89","observedAt":"2026-09-03T08:44:06.821Z","provenance":{"host":"cursor","hostContractRevision":"2026-08-28","nativeEvent":"postToolUse","source":"native"},"sequence":90},"native":{"conversation_id":"9f26d535-5d39-4248-a9b2-2faaa07cd364","generation_id":"792f90af-a361-4bb5-ae05-f97d035fde34","model":"default","tool_name":"Shell","tool_input":{"command":"python3 - <<'PY'\nfrom pathlib import Path\nimport json\np = Path('/tmp/host-test/cursor-home/.cursor/projects/tmp-host-test-cursor-workspace/agent-tools/74c7a696-0a6a-474c-b8b5-a51146b2c26c.txt')\ndump = p.read_text().splitlines()[-1]\nobj = json.loads(dump)\nprobe = {\n \"log\": \"/tmp/host-test/cursor/log/captures.ndjson\",\n \"observed\": {\n \"client\": {\n \"name\": \"cursor-vscode\",\n \"version\": \"…[+2067 chars]","cwd":"","timeout":30000},"tool_output":"{\"output\":\"wrote /tmp/host-test/cursor-workspace/probe-out.txt bytes 100829\\nDUMP_LOG_PATH /tmp/host-test/cursor/log/captures.ndjson\\ndump chars 99967\\n\",\"exitCode\":0}","duration":5167.56,"tool_use_id":"f133fdf9-12c7-44cb-b3ab-e4c09008dbb6","cwd":"","session_id":"9f26d535-5d39-4248-a9b2-2faaa07cd364","hook_event_name":"postToolUse","cursor_version":"3.18.25","workspace_roots":["/tmp/host-test/cursor-workspace"],"user_email":"probe@example.invalid","transcript_path":null}},"host":"cursor","kind":"event","process":{"cwd":"/tmp/host-test/cursor-home","entry":"/tmp/host-test/cursor-home/.cursor/plugins/local/host-test/mcp/mcp-host-test-0d229f1b-flight.mjs","pid":197313,"ppid":4119277},"recordedAt":"2026-09-03T08:44:06.823Z","request":{"host":{"source":"native","state":"available","value":{"name":"cursor"}},"invocation":{"kind":"event"},"session":{"source":"native","state":"available","value":{"sessionId":"9f26d535-5d39-4248-a9b2-2faaa07cd364"}}},"runtime":"shared-runtime","sequence":92} +{"event":{"canonical":{"event":"tool/before","idempotencyKey":"43e281e0f3336db32d98933a12fa4da126fb58d3ce2e955efba3981811a55cb1","observedAt":"2026-09-03T08:44:18.158Z","provenance":{"host":"cursor","hostContractRevision":"2026-08-28","nativeEvent":"preToolUse","source":"native"},"sequence":93},"native":{"conversation_id":"9f26d535-5d39-4248-a9b2-2faaa07cd364","generation_id":"792f90af-a361-4bb5-ae05-f97d035fde34","model":"default","tool_name":"Shell","tool_input":{"command":"python3 - <<'PY'\nfrom pathlib import Path\ntext = Path('/tmp/host-test/cursor-workspace/probe-out.txt').read_text()\n# split into two parts under 90k for reading\nmid = 50000\nPath('/tmp/host-test/cursor-workspace/probe-out-a.txt').write_text(text[:mid])\nPath('/tmp/host-test/cursor-workspace/probe-out-b.txt').write_text(text[mid:])\nprint(len(text), len(text[:mid]), len(text[mid:]))\n# verify dump is va…[+408 chars]","cwd":"","timeout":30000},"tool_use_id":"fadbbe8d-4285-42d1-aae2-41b9aa51f54d","cwd":"","session_id":"9f26d535-5d39-4248-a9b2-2faaa07cd364","hook_event_name":"preToolUse","cursor_version":"3.18.25","workspace_roots":["/tmp/host-test/cursor-workspace"],"user_email":"probe@example.invalid","transcript_path":null}},"host":"cursor","kind":"event","process":{"cwd":"/tmp/host-test/cursor-home","entry":"/tmp/host-test/cursor-home/.cursor/plugins/local/host-test/mcp/mcp-host-test-0d229f1b-flight.mjs","pid":197313,"ppid":4119277},"recordedAt":"2026-09-03T08:44:18.160Z","request":{"host":{"source":"native","state":"available","value":{"name":"cursor"}},"invocation":{"kind":"event"},"session":{"source":"native","state":"available","value":{"sessionId":"9f26d535-5d39-4248-a9b2-2faaa07cd364"}}},"runtime":"shared-runtime","sequence":95} +{"event":{"canonical":{"event":"tool/after","idempotencyKey":"3c86a510439e3ab5e250a12237b5dc543ba8af088382802e3ddc3170b06e0fa6","observedAt":"2026-09-03T08:44:23.456Z","provenance":{"host":"cursor","hostContractRevision":"2026-08-28","nativeEvent":"postToolUse","source":"native"},"sequence":94},"native":{"conversation_id":"9f26d535-5d39-4248-a9b2-2faaa07cd364","generation_id":"792f90af-a361-4bb5-ae05-f97d035fde34","model":"default","tool_name":"Shell","tool_input":{"command":"python3 - <<'PY'\nfrom pathlib import Path\ntext = Path('/tmp/host-test/cursor-workspace/probe-out.txt').read_text()\n# split into two parts under 90k for reading\nmid = 50000\nPath('/tmp/host-test/cursor-workspace/probe-out-a.txt').write_text(text[:mid])\nPath('/tmp/host-test/cursor-workspace/probe-out-b.txt').write_text(text[mid:])\nprint(len(text), len(text[:mid]), len(text[mid:]))\n# verify dump is va…[+408 chars]","cwd":"","timeout":30000},"tool_output":"{\"output\":\"100829 50000 50829\\nline0 DUMP_LOG_PATH /tmp/host-test/cursor/log/captures.ndjson\\nnparts 45\\npart0 DUMP_LOG_PATH /tmp/host-test/cursor/log/captures.ndjson\\npart1 starts {\\\"filter\\\":{},\\\"lo…[+81 chars]","duration":5159.635,"tool_use_id":"fadbbe8d-4285-42d1-aae2-41b9aa51f54d","cwd":"","session_id":"9f26d535-5d39-4248-a9b2-2faaa07cd364","hook_event_name":"postToolUse","cursor_version":"3.18.25","workspace_roots":["/tmp/host-test/cursor-workspace"],"user_email":"probe@example.invalid","transcript_path":null}},"host":"cursor","kind":"event","process":{"cwd":"/tmp/host-test/cursor-home","entry":"/tmp/host-test/cursor-home/.cursor/plugins/local/host-test/mcp/mcp-host-test-0d229f1b-flight.mjs","pid":197313,"ppid":4119277},"recordedAt":"2026-09-03T08:44:23.458Z","request":{"host":{"source":"native","state":"available","value":{"name":"cursor"}},"invocation":{"kind":"event"},"session":{"source":"native","state":"available","value":{"sessionId":"9f26d535-5d39-4248-a9b2-2faaa07cd364"}}},"runtime":"shared-runtime","sequence":96} +{"event":{"canonical":{"event":"tool/before","idempotencyKey":"f316709fdd31710f2f227f99381dbcd819a04fcffcba3a258a7459ad31bdacab","observedAt":"2026-09-03T08:49:07.062Z","provenance":{"host":"cursor","hostContractRevision":"2026-08-28","nativeEvent":"preToolUse","source":"native"},"sequence":99},"native":{"conversation_id":"9f26d535-5d39-4248-a9b2-2faaa07cd364","generation_id":"792f90af-a361-4bb5-ae05-f97d035fde34","model":"default","tool_name":"Shell","tool_input":{"command":"python3 - <<'PY'\nfrom pathlib import Path\ntext = Path('/tmp/host-test/cursor-workspace/probe-out.txt').read_text()\nparts = text.split('\\n', 1)\nassert parts[0].startswith('DUMP_LOG_PATH')\nrest = parts[1]\n# dump is first line of rest, probe is after\ndump, _, probe = rest.partition('\\n')\n# Find cutoff marker from truncated response\ncutoff = '\"tool_use_id\":\"call-dd59e380-7635-46d8-8714-d4c2476fd1c3-23…[+2653 chars]","cwd":"","timeout":30000},"tool_use_id":"8fe7b9b0-8328-4734-9e31-f308cbf6381e","cwd":"","session_id":"9f26d535-5d39-4248-a9b2-2faaa07cd364","hook_event_name":"preToolUse","cursor_version":"3.18.25","workspace_roots":["/tmp/host-test/cursor-workspace"],"user_email":"probe@example.invalid","transcript_path":null}},"host":"cursor","kind":"event","process":{"cwd":"/tmp/host-test/cursor-home","entry":"/tmp/host-test/cursor-home/.cursor/plugins/local/host-test/mcp/mcp-host-test-0d229f1b-flight.mjs","pid":197313,"ppid":4119277},"recordedAt":"2026-09-03T08:49:07.086Z","request":{"host":{"source":"native","state":"available","value":{"name":"cursor"}},"invocation":{"kind":"event"},"session":{"source":"native","state":"available","value":{"sessionId":"9f26d535-5d39-4248-a9b2-2faaa07cd364"}}},"runtime":"shared-runtime","sequence":101} +{"event":{"canonical":{"event":"tool/after","idempotencyKey":"9c286e7c4b99b712b52743a8963a0fd04c588ef7fcbe7fc1f612ad8012557b52","observedAt":"2026-09-03T08:49:12.697Z","provenance":{"host":"cursor","hostContractRevision":"2026-08-28","nativeEvent":"postToolUse","source":"native"},"sequence":100},"native":{"conversation_id":"9f26d535-5d39-4248-a9b2-2faaa07cd364","generation_id":"792f90af-a361-4bb5-ae05-f97d035fde34","model":"default","tool_name":"Shell","tool_input":{"command":"python3 - <<'PY'\nfrom pathlib import Path\ntext = Path('/tmp/host-test/cursor-workspace/probe-out.txt').read_text()\nparts = text.split('\\n', 1)\nassert parts[0].startswith('DUMP_LOG_PATH')\nrest = parts[1]\n# dump is first line of rest, probe is after\ndump, _, probe = rest.partition('\\n')\n# Find cutoff marker from truncated response\ncutoff = '\"tool_use_id\":\"call-dd59e380-7635-46d8-8714-d4c2476fd1c3-23…[+2653 chars]","cwd":"","timeout":30000},"tool_output":"{\"output\":\"end_marker idx 41345\\ncontinuation starts: workspace_roots\\\":\\\"/tmp/host-test/cursor-workspace\\\",\\\"hook_event_name\\\":\\\"preToolUse\\ncontinuation len 57853\\nprobe len 805\\nwrote dump-full.jso…[+111 chars]","duration":5437.942,"tool_use_id":"8fe7b9b0-8328-4734-9e31-f308cbf6381e","cwd":"","session_id":"9f26d535-5d39-4248-a9b2-2faaa07cd364","hook_event_name":"postToolUse","cursor_version":"3.18.25","workspace_roots":["/tmp/host-test/cursor-workspace"],"user_email":"probe@example.invalid","transcript_path":null}},"host":"cursor","kind":"event","process":{"cwd":"/tmp/host-test/cursor-home","entry":"/tmp/host-test/cursor-home/.cursor/plugins/local/host-test/mcp/mcp-host-test-0d229f1b-flight.mjs","pid":197313,"ppid":4119277},"recordedAt":"2026-09-03T08:49:12.699Z","request":{"host":{"source":"native","state":"available","value":{"name":"cursor"}},"invocation":{"kind":"event"},"session":{"source":"native","state":"available","value":{"sessionId":"9f26d535-5d39-4248-a9b2-2faaa07cd364"}}},"runtime":"shared-runtime","sequence":102} +{"event":{"canonical":{"event":"agent/stop","idempotencyKey":"a8f652f1d802083c702236818d71bc96849f229e561252c352cef6474f684284","observedAt":"2026-09-03T08:49:26.954Z","provenance":{"host":"cursor","hostContractRevision":"2026-08-28","nativeEvent":"subagentStop","source":"native"},"sequence":103},"native":{"conversation_id":"b60ae0c1-2f85-4c4d-b3e5-b512f9b06e4c","generation_id":"b60ae0c1-2f85-4c4d-b3e5-b512f9b06e4c","model":"default","subagent_id":"call-7e307548-94ae-4cad-a0f5-9f259da62a4a-40\nfc_98235bb8-f81a-95c9-a28f-e733cae6f1d4_0","subagent_type":"general-purpose","status":"completed","duration_ms":390411,"parent_conversation_id":"b60ae0c1-2f85-4c4d-b3e5-b512f9b06e4c","message_count":0,"tool_call_count":0,"loop_count":0,"task":"Call these two MCP tools in order and return their full JSON results verbatim. Do nothing else.\n\n1) CallMcpTool with server=`plugin-host-test-host-test`, toolName=`dump`, arguments=`{}`\n (descriptor…[+498 chars]","description":"Root dump and probe","session_id":"b60ae0c1-2f85-4c4d-b3e5-b512f9b06e4c","hook_event_name":"subagentStop","cursor_version":"3.18.25","workspace_roots":["/tmp/host-test/cursor-workspace"],"user_email":"probe@example.invalid","transcript_path":"/tmp/host-test/cursor-home/.cursor/projects/tmp-host-test-cursor-workspace/agent-transcripts/b60ae0c1-2f85-4c4d-b3e5-b512f9b06e4c/b60ae0c1-2f85-4c4d-b3e5-b512f9b06e4c.jsonl","agent_transcript_path":null}},"host":"cursor","kind":"event","process":{"cwd":"/tmp/host-test/cursor-home","entry":"/tmp/host-test/cursor-home/.cursor/plugins/local/host-test/mcp/mcp-host-test-0d229f1b-flight.mjs","pid":197313,"ppid":4119277},"recordedAt":"2026-09-03T08:49:26.957Z","request":{"host":{"source":"native","state":"available","value":{"name":"cursor"}},"invocation":{"kind":"event"},"session":{"source":"native","state":"available","value":{"sessionId":"b60ae0c1-2f85-4c4d-b3e5-b512f9b06e4c"}}},"runtime":"shared-runtime","sequence":105} +{"event":{"canonical":{"event":"stop","idempotencyKey":"d784415a377cb20211f203ebca1c2274f19c61a00a8cedc3ca0c10585cd0ff52","observedAt":"2026-09-03T08:49:35.339Z","provenance":{"host":"cursor","hostContractRevision":"2026-08-28","nativeEvent":"stop","source":"native"},"sequence":104},"native":{"conversation_id":"b60ae0c1-2f85-4c4d-b3e5-b512f9b06e4c","generation_id":"d4b2603b-ebfe-45ee-832d-b30d048defbb","model":"default","model_id":"default","status":"completed","loop_count":0,"input_tokens":1449004,"output_tokens":10324,"cache_read_tokens":1155456,"cache_write_tokens":0,"session_id":"b60ae0c1-2f85-4c4d-b3e5-b512f9b06e4c","hook_event_name":"stop","cursor_version":"3.18.25","workspace_roots":["/tmp/host-test/cursor-workspace"],"user_email":"probe@example.invalid","transcript_path":"/tmp/host-test/cursor-home/.cursor/projects/tmp-host-test-cursor-workspace/agent-transcripts/b60ae0c1-2f85-4c4d-b3e5-b512f9b06e4c/b60ae0c1-2f85-4c4d-b3e5-b512f9b06e4c.jsonl"}},"host":"cursor","kind":"event","process":{"cwd":"/tmp/host-test/cursor-home","entry":"/tmp/host-test/cursor-home/.cursor/plugins/local/host-test/mcp/mcp-host-test-0d229f1b-flight.mjs","pid":197313,"ppid":4119277},"recordedAt":"2026-09-03T08:49:35.355Z","request":{"host":{"source":"native","state":"available","value":{"name":"cursor"}},"invocation":{"kind":"event"},"session":{"source":"native","state":"available","value":{"sessionId":"b60ae0c1-2f85-4c4d-b3e5-b512f9b06e4c"}}},"runtime":"shared-runtime","sequence":106} diff --git a/package.json b/package.json index 2439f77bd..12d16301e 100644 --- a/package.json +++ b/package.json @@ -56,6 +56,7 @@ "example:audiobook": "pnpm build && pnpm --filter @agent-bundle-example/audiobook-curator dev", "example:mcp-app": "pnpm build && pnpm --filter @agent-bundle-example/mcp-app dev", "example:skills": "pnpm build && pnpm --filter @agent-bundle-example/skills-starter dev", + "example:host-test": "pnpm build && pnpm --filter @agent-bundle-example/host-test dev", "examples:check": "pnpm build && node scripts/run-examples-check.mjs" }, "devDependencies": { diff --git a/packages/agent-bundle/fixtures/route-harness/src/mcp/harness/tools/context.tsx b/packages/agent-bundle/fixtures/route-harness/src/mcp/harness/tools/context.tsx index 5baa8a6bc..4b6d15138 100644 --- a/packages/agent-bundle/fixtures/route-harness/src/mcp/harness/tools/context.tsx +++ b/packages/agent-bundle/fixtures/route-harness/src/mcp/harness/tools/context.tsx @@ -14,6 +14,7 @@ export const inputSchema = z.object({ export const resultSchema = z.object({ actor: z.unknown(), host: z.unknown(), + lineage: z.unknown(), session: z.unknown(), workspace: z.unknown(), }).strict(); @@ -32,9 +33,13 @@ export default async function Context() { const workspace: JsonValue = context.workspace.state === 'available' ? { source: context.workspace.source, state: context.workspace.state, value: { root: context.workspace.value.root } } : { reason: context.workspace.reason, state: context.workspace.state }; + const lineage: JsonValue = context.lineage.state === 'available' + ? { source: context.lineage.source, state: context.lineage.state, value: JSON.parse(JSON.stringify(context.lineage.value)) as JsonValue } + : { reason: context.lineage.reason, state: context.lineage.state }; const result = { actor, host, + lineage, session, workspace, }; diff --git a/packages/agent-bundle/src/adapters/capabilities/claude-2.1.250.json b/packages/agent-bundle/src/adapters/capabilities/claude-2.1.250.json index 1a18db914..b7bb72600 100644 --- a/packages/agent-bundle/src/adapters/capabilities/claude-2.1.250.json +++ b/packages/agent-bundle/src/adapters/capabilities/claude-2.1.250.json @@ -156,6 +156,34 @@ "state": "supported" } }, + "lineage": { + "subagent-events": { + "state": "supported", + "evidence": [ + "2026-09-03 live capture (docs/audits/2026-09-03-host-lineage-matrix.md): SubagentStart/SubagentStop carry agent_id and agent_type; every hook inside a subagent carries the subagent's agent_id and the root session_id." + ] + }, + "root": { + "state": "supported", + "evidence": [ + "2026-09-03: session_id is the root session on every hook payload, including nested subagents." + ] + }, + "parent": { + "state": "degraded", + "reason": "2026-09-03: no hook payload names a subagent's parent; the runtime registry infers it from the Agent/Task PreToolUse that is open when SubagentStart fires (resolution: registry)." + }, + "depth": { + "state": "degraded", + "reason": "2026-09-03: no depth counter is delivered; the registry derives it from the inferred parent chain." + }, + "mcp-correlation": { + "state": "supported", + "evidence": [ + "2026-09-03: tools/call _meta carries claudecode/toolUseId equal to the PreToolUse tool_use_id, so the generated server resolves the caller's conversation through the open pre-tool hook." + ] + } + }, "observedCliVersion": "2.1.250", "plugin": { "agents": { diff --git a/packages/agent-bundle/src/adapters/capabilities/codex-0.147.0.json b/packages/agent-bundle/src/adapters/capabilities/codex-0.147.0.json index 16ce10cb0..9128e2a18 100644 --- a/packages/agent-bundle/src/adapters/capabilities/codex-0.147.0.json +++ b/packages/agent-bundle/src/adapters/capabilities/codex-0.147.0.json @@ -420,6 +420,34 @@ "state": "supported" } }, + "lineage": { + "subagent-events": { + "state": "supported", + "evidence": [ + "2026-09-03 live capture (docs/audits/2026-09-03-host-lineage-matrix.md): SubagentStart/SubagentStop carry agent_id (= thread id), agent_type, turn_id; hooks inside a subagent carry its agent_id and the root session_id." + ] + }, + "root": { + "state": "supported", + "evidence": [ + "2026-09-03: session_id is the root thread on every hook payload and in tools/call _meta.x-codex-turn-metadata.session_id." + ] + }, + "parent": { + "state": "degraded", + "reason": "2026-09-03: SubagentStart names no parent; SubagentStop carries the parent rollout in transcript_path and tools/call _meta carries parent_thread_id, so hooks resolve the parent through the registry (spawn_agent claim) while MCP calls resolve it natively." + }, + "depth": { + "state": "degraded", + "reason": "2026-09-03: no depth counter is delivered; the registry derives it from the parent chain." + }, + "mcp-correlation": { + "state": "supported", + "evidence": [ + "2026-09-03: tools/call _meta.x-codex-turn-metadata carries thread_id, parent_thread_id, forked_from_thread_id, thread_source, turn_id, and session_id; lineage resolves natively without hooks." + ] + } + }, "observedCliVersion": "0.147.0", "plugin": { "apps": { diff --git a/packages/agent-bundle/src/adapters/capabilities/cursor-2026-08-28.json b/packages/agent-bundle/src/adapters/capabilities/cursor-2026-08-28.json index 5ca77e8b6..d9a8e4289 100644 --- a/packages/agent-bundle/src/adapters/capabilities/cursor-2026-08-28.json +++ b/packages/agent-bundle/src/adapters/capabilities/cursor-2026-08-28.json @@ -315,6 +315,34 @@ "state": "supported" } }, + "lineage": { + "subagent-events": { + "state": "supported", + "evidence": [ + "2026-09-03 live capture on Cursor 3.18.25 (docs/audits/2026-09-03-host-lineage-matrix.md): subagentStart/subagentStop carry subagent_id (= the parent's Task tool_call_id), parent_conversation_id, subagent_type, is_parallel_worker; the child's own conversation_id is not included." + ] + }, + "root": { + "state": "degraded", + "reason": "2026-09-03: a child's events carry only their own fresh conversation_id, so the root is known only through the registry that bound the child at start (resolution: inferred)." + }, + "parent": { + "state": "degraded", + "reason": "2026-09-03: parent_conversation_id appears only on subagentStart/subagentStop; the child conversation is bound to the most recent pending start by ordering, which is ambiguous for parallel workers." + }, + "depth": { + "state": "degraded", + "reason": "2026-09-03: no depth counter is delivered; derived from the inferred parent chain." + }, + "mcp-correlation": { + "state": "degraded", + "reason": "2026-09-03: tools/call _meta carries only progressToken and the client name is cursor-vscode; the generated server resolves the caller through the open preToolUse whose tool_name is MCP:." + }, + "cloud": { + "state": "unavailable", + "reason": "2026-09-03: cloud agents run no user hooks (https://cursor.com/docs/hooks), so nothing feeds the registry there; request.lineage reports cloud-agent-no-user-hooks." + } + }, "observedCliVersion": "2026-08-28", "plugin": { "agents": { diff --git a/packages/agent-bundle/src/adapters/capabilities/portable-1.0.0.json b/packages/agent-bundle/src/adapters/capabilities/portable-1.0.0.json index 4d3276cd5..fbcd91bc6 100644 --- a/packages/agent-bundle/src/adapters/capabilities/portable-1.0.0.json +++ b/packages/agent-bundle/src/adapters/capabilities/portable-1.0.0.json @@ -122,6 +122,28 @@ "state": "unavailable" } }, + "lineage": { + "subagent-events": { + "state": "unavailable", + "reason": "2026-09-03: Agent Plugins 1.0.0 defines no hooks, so no subagent start/stop event exists; request.lineage reports no-subagent-events." + }, + "root": { + "state": "unavailable", + "reason": "2026-09-03: Agent Plugins 1.0.0 defines no hooks and the MCP request carries no conversation identity." + }, + "parent": { + "state": "unavailable", + "reason": "2026-09-03: Agent Plugins 1.0.0 defines no hooks." + }, + "depth": { + "state": "unavailable", + "reason": "2026-09-03: Agent Plugins 1.0.0 defines no hooks." + }, + "mcp-correlation": { + "state": "unavailable", + "reason": "2026-09-03: no pre-tool hook exists to open a correlation window and tools/call _meta is host-defined." + } + }, "observedSpecificationVersion": "1.0.0", "plugin": { "extensionDirectories": { diff --git a/packages/agent-bundle/src/adapters/hook-contract.ts b/packages/agent-bundle/src/adapters/hook-contract.ts index 9ac741379..da657ce7a 100644 --- a/packages/agent-bundle/src/adapters/hook-contract.ts +++ b/packages/agent-bundle/src/adapters/hook-contract.ts @@ -622,7 +622,7 @@ const eventRouteHookWrapperSource = ( "import { dirname, resolve } from 'node:path';", ...(standalone ? ["import { Worker } from 'node:worker_threads';"] : []), ...(standalone - ? ["import { agent, available, createAgentRenderDispatcher, runAgentRequest } from '@agent-bundle/runtime';"] + ? ["import { agent, available, createAgentRenderDispatcher, resolveNativeLineage, runAgentRequest, unavailable } from '@agent-bundle/runtime';"] : []), `import { EventRuntimeTransportError, requestEventRuntime } from ${JSON.stringify(eventIpcRuntimeSpecifier)};`, `import { ${standalone ? 'createCanonicalEventProps, projectEventDocument, ' : ''}validateNativeEventEnvelope } from ${JSON.stringify(eventProjectRuntimeSpecifier)};`, @@ -676,6 +676,7 @@ const eventRouteHookWrapperSource = ( ' host: context.host,', ' id,', ' invocation: dispatch.invocation,', + ' lineage: context.lineage,', ' requestInvocation: context.invocation,', ' session: context.session,', ' type: "render",', @@ -694,9 +695,12 @@ const eventRouteHookWrapperSource = ( ' const props = createCanonicalEventProps(canonicalEvent, native, target, nativeEvent, capabilityRevision, signal);', ' const sessionId = typeof native.session_id === "string" ? native.session_id : typeof native.conversation_id === "string" ? native.conversation_id : undefined;', ' const workspaceRoot = typeof native.cwd === "string" ? native.cwd : Array.isArray(native.workspace_roots) && typeof native.workspace_roots[0] === "string" ? native.workspace_roots[0] : undefined;', + // Standalone hooks hold no registry, so lineage is only what the payload proves (docs/audits/2026-09-03-host-lineage-matrix.md). + ' const lineage = target === "claude" || target === "codex" || target === "cursor" ? resolveNativeLineage(target, native) : unavailable("no-subagent-events");', ' const document = await runAgentRequest({', ' host: available({ name: target }, "native"),', ' invocation: { artifactEpoch, hostContractRevision: capabilityRevision, kind: "event", operationId: `event:${canonicalEvent}`, surface: canonicalEvent },', + ' lineage,', ' ...(sessionId === undefined ? {} : { session: available({ sessionId }, "native") }),', ' signal,', ' ...(workspaceRoot === undefined ? {} : { workspace: available({ root: workspaceRoot }, "native") }),', @@ -1249,7 +1253,7 @@ export const nativeHookWrapperSource = ( ' requireString(input, "tool_use_id");', ' if (canonicalEvent === "afterTool") {', ' if (target === "codex") { if (input.tool_response === undefined) fail("native PostToolUse tool_response is required"); }', - ' else if (!isRecord(input.tool_response)) fail("native PostToolUse tool_response must be an object");', + ' else if (typeof input.tool_response !== "object" || input.tool_response === null) fail("native PostToolUse tool_response must be an object or an array");', ' }', ' return;', ' }', diff --git a/packages/agent-bundle/src/build/entry-shell.ts b/packages/agent-bundle/src/build/entry-shell.ts index dac745e44..849f598ed 100644 --- a/packages/agent-bundle/src/build/entry-shell.ts +++ b/packages/agent-bundle/src/build/entry-shell.ts @@ -323,6 +323,7 @@ export const generatedCliBinEntrySource = (options: GeneratedCliBinEntryOptions) ' },', " host: unavailable('unsupported-surface'),", " invocation: { kind: 'cli', operationId: command.routeId, surface: command.path.join(' ') },", + " lineage: unavailable('unsupported-surface'),", ...(options.state === undefined ? [] : [' noticeLedger: bindings.noticeLedger,']), ` providers: ${providerValuesExpression(providers)},`, ' signal: context.signal,', @@ -518,6 +519,7 @@ export const generatedRenderedRouteWorkerSource = ( ' },', " host: unavailable('unsupported-surface'),", ' invocation: message.request,', + " lineage: unavailable('unsupported-surface'),", ...(options.state === undefined ? [] : [' noticeLedger: bindings.noticeLedger,']), " progress: { report: async (update) => { parentPort.postMessage({ id: message.id, type: 'progress', update }); } },", ` providers: ${providerValuesExpression(providers)},`, @@ -805,7 +807,7 @@ export const generatedRouteFlightWorkerSource = (options: GeneratedRouteFlightWo "import { parentPort } from 'node:worker_threads';", "import { createElement } from 'react';", "import { renderAgentFlight } from '@agent-bundle/runtime/flight/server';", - "import { runAgentRequest } from '@agent-bundle/runtime';", + "import { runAgentRequest, unavailable } from '@agent-bundle/runtime';", ...generatedStateImports(options.state, 'artifact'), ...noticeInboxImport(wiresInbox), ...routeImports(routes), @@ -849,6 +851,7 @@ export const generatedRouteFlightWorkerSource = (options: GeneratedRouteFlightWo ' ...(message.actor === undefined ? {} : { actor: message.actor }),', ' ...(message.host === undefined ? {} : { host: message.host }),', ' invocation: { ...message.requestInvocation, artifactEpoch: ARTIFACT_EPOCH, kind: message.invocation.kind, operationId: route.id, surface: route.name },', + " lineage: message.lineage ?? unavailable('not-provided'),", ...(options.state === undefined ? [] : [' noticeLedger: bindings.noticeLedger,']), ' progress: { report: async (update) => { parentPort.postMessage({ id: message.id, type: \'progress\', update }); } },', ` providers: ${providerValuesExpression(providers)},`, @@ -950,7 +953,8 @@ export const generatedRouteMcpEntrySource = (options: GeneratedRouteMcpEntryOpti const wiresInbox = wiresInboxRoute(options); const wiresResourceUpdated = wiresResourceUpdatedRoute(options); return [ - ...(hasEvents ? ["import { dirname, resolve } from 'node:path';"] : []), + `import { ${hasEvents ? 'dirname, ' : ''}join, resolve } from 'node:path';`, + "import { fileURLToPath } from 'node:url';", `import { createFlightWorkerHost, createGeneratedRouteMcpServer } from ${JSON.stringify(mcpServerRuntimeSpecifier)};`, ...(hasEvents ? [ @@ -958,12 +962,30 @@ export const generatedRouteMcpEntrySource = (options: GeneratedRouteMcpEntryOpti `import { createCanonicalEventProps, projectEventDocument } from ${JSON.stringify(eventProjectRuntimeSpecifier)};`, ] : []), + "import { agentLineageStateDefinition, createAgentLineageRegistry } from '@agent-bundle/runtime/lineage';", + "import { createSqliteStateDriver } from '@agent-bundle/runtime/state/sqlite';", "import mcpApps from 'agent-bundle/mcp-apps';", ...noticeDeliveryImports(wiresResourceUpdated), ...noticeInboxImport(wiresInbox), ...routeImports(routes), '', `const ARTIFACT_EPOCH = ${JSON.stringify(artifactEpoch)};`, + // The lineage registry journals beside the project's own durable state so + // a restarted MCP process still knows which subagents are alive. A store + // that cannot open degrades to an in-memory registry rather than failing + // the server: lineage is an observed axis, never a precondition. + "const lineageAnchor = process.env.AGENT_BUNDLE_PLUGIN_ROOT ?? fileURLToPath(new URL('..', import.meta.url));", + 'const openLineage = async () => {', + " const driver = createSqliteStateDriver({ root: join(resolve(lineageAnchor), 'state') });", + ' try {', + ' const store = await driver.open(agentLineageStateDefinition());', + ' return { dispose: async () => { await store.close(); await driver.close(); }, registry: createAgentLineageRegistry({ store }) };', + ' } catch (error) {', + " process.stderr.write(`agent-bundle lineage registry is in-memory only: ${error instanceof Error ? error.message : String(error)}\\n`);", + ' await driver.close().catch(() => undefined);', + ' return { dispose: async () => undefined, registry: createAgentLineageRegistry() };', + ' }', + '};', 'const routes = Object.freeze({', ...routeRecords(routes), ...noticeInboxRecord(wiresInbox), @@ -989,15 +1011,20 @@ export const generatedRouteMcpEntrySource = (options: GeneratedRouteMcpEntryOpti '', ] : []), - 'export default async () => createGeneratedRouteMcpServer({', - ' apps: mcpApps,', - ' artifactEpoch: ARTIFACT_EPOCH,', - ...(hasEvents ? [' events,'] : []), - ` host: createFlightWorkerHost(new URL(${JSON.stringify(`./${options.workerFile}`)}, import.meta.url), ARTIFACT_EPOCH),`, - ...(wiresResourceUpdated ? [' notices: noticeDelivery,'] : []), - ` plugin: ${stableJson(options.plugin)},`, - ' routes,', - '});', + 'export default async () => {', + ' const lineage = await openLineage();', + ' return createGeneratedRouteMcpServer({', + ' apps: mcpApps,', + ' artifactEpoch: ARTIFACT_EPOCH,', + ' disposeLineage: lineage.dispose,', + ...(hasEvents ? [' events,'] : []), + ` host: createFlightWorkerHost(new URL(${JSON.stringify(`./${options.workerFile}`)}, import.meta.url), ARTIFACT_EPOCH),`, + ' lineage: lineage.registry,', + ...(wiresResourceUpdated ? [' notices: noticeDelivery,'] : []), + ` plugin: ${stableJson(options.plugin)},`, + ' routes,', + ' });', + '};', '', ].join('\n'); }; diff --git a/packages/agent-bundle/src/contracts/request-provenance.ts b/packages/agent-bundle/src/contracts/request-provenance.ts index 7794d82cb..b4814e4a2 100644 --- a/packages/agent-bundle/src/contracts/request-provenance.ts +++ b/packages/agent-bundle/src/contracts/request-provenance.ts @@ -4,7 +4,11 @@ export type RequestProvenanceUnavailableReason = | 'not-provided' | 'unsupported-surface' | 'host-omitted' - | 'unauthenticated'; + | 'unauthenticated' + | 'no-subagent-events' + | 'id-not-resolvable' + | 'cloud-agent-no-user-hooks' + | 'no-shared-runtime'; export type RequestProvenanceAxis = | Readonly<{ @@ -24,6 +28,22 @@ export interface RequestInvocationProvenance { readonly surface?: string; } +/** The conversation tree position a request carried (`request.lineage`), on the wire. */ +export interface RequestLineageProvenance { + readonly conversation: string; + readonly depth: number; + readonly generation?: string; + readonly parent?: string; + readonly resolution: 'native' | 'registry' | 'inferred'; + readonly root: string; + readonly subagent?: Readonly<{ + readonly id: string; + readonly isParallelWorker?: boolean; + readonly toolCallId?: string; + readonly type?: string; + }>; +} + /** * Credential-free request identity projected onto a Workbench wire response. * Every observable axis is explicit; unknown values remain typed unavailable. @@ -32,6 +52,7 @@ export interface RequestContextProvenance { readonly actor: RequestProvenanceAxis>; readonly host: RequestProvenanceAxis>; readonly invocation: RequestInvocationProvenance; + readonly lineage: RequestProvenanceAxis; readonly session: RequestProvenanceAxis>; readonly workspace: RequestProvenanceAxis>; } diff --git a/packages/agent-bundle/src/dev/playground/lifecycle-render-child.ts b/packages/agent-bundle/src/dev/playground/lifecycle-render-child.ts index 4c5c9dd8b..e570c4758 100644 --- a/packages/agent-bundle/src/dev/playground/lifecycle-render-child.ts +++ b/packages/agent-bundle/src/dev/playground/lifecycle-render-child.ts @@ -67,6 +67,7 @@ const render = async (request: LifecycleRenderChildRequest): Promise>, key: string): str return typeof value === 'string' && value.trim() !== '' ? value : undefined; }; +/** + * What one replayed receipt proves about its place in the conversation tree: + * a Claude or Codex payload with no `agent_id` is the root itself; anything + * subagent-shaped (and every Cursor payload) needs the warm runtime's registry, + * which a deterministic replay does not have. + */ +const replayLineage = ( + native: Readonly>, + target: string, +): RequestContextProvenance['lineage'] => { + if (!concreteHosts.has(target)) return { reason: 'no-subagent-events', state: 'unavailable' }; + if (target === 'cursor') return { reason: 'no-shared-runtime', state: 'unavailable' }; + const root = nativeText(native, 'session_id'); + const agentId = nativeText(native, 'agent_id'); + if (root === undefined || agentId !== undefined) return { reason: 'no-shared-runtime', state: 'unavailable' }; + const generation = target === 'codex' ? nativeText(native, 'turn_id') : nativeText(native, 'prompt_id'); + return { + source: 'receipt', + state: 'available', + value: { + conversation: root, + depth: 0, + ...(generation === undefined ? {} : { generation }), + resolution: 'native', + root, + }, + }; +}; + const replayRequestContext = ( event: CanonicalAgentEvent, native: Readonly>, @@ -72,6 +101,7 @@ const replayRequestContext = ( operationId: routeId, surface: event, }, + lineage: replayLineage(native, target), session: sessionId === undefined ? { reason: 'not-provided', state: 'unavailable' } : { source: 'receipt', state: 'available', value: { sessionId } }, @@ -95,6 +125,7 @@ const renderContext = (requestContext: RequestContextProvenance): RenderRouteCon ? {} : { surface: requestContext.invocation.surface }), }, + lineage: requestContext.lineage, session: requestContext.session, workspace: requestContext.workspace, }); diff --git a/packages/agent-bundle/src/events/projection.ts b/packages/agent-bundle/src/events/projection.ts index 4c1e43f64..010e7948c 100644 --- a/packages/agent-bundle/src/events/projection.ts +++ b/packages/agent-bundle/src/events/projection.ts @@ -342,10 +342,11 @@ export const validateNativeEventEnvelope = ( if (!Object.hasOwn(native, 'tool_response') || native.tool_response === undefined) { return nativeEventError('native tool_response is required'); } - } else if ( - typeof native.tool_response !== 'object' || native.tool_response === null || Array.isArray(native.tool_response) - ) { - return nativeEventError('native tool_response must be an object'); + } else if (typeof native.tool_response !== 'object' || native.tool_response === null) { + // Claude documents `tool_response` as an object, but PostToolUse for an + // MCP tool delivers the tool's content-block array (observed on Claude + // Code 2.1.257, docs/audits/2026-09-03-host-lineage-matrix.md §3). + return nativeEventError('native tool_response must be an object or an array'); } } } diff --git a/packages/agent-bundle/src/mcp-server-runtime.ts b/packages/agent-bundle/src/mcp-server-runtime.ts index ddc9b096e..d4357b600 100644 --- a/packages/agent-bundle/src/mcp-server-runtime.ts +++ b/packages/agent-bundle/src/mcp-server-runtime.ts @@ -24,6 +24,7 @@ import { available, createAgentRenderDispatcher, createWarmFlightHost, + lineageHostFromClient, projectMcpRenderStream, runAgentRequest, unavailable, @@ -35,17 +36,20 @@ import type { AgentActorIdentity, AgentDocument, AgentHostIdentity, + AgentLineage, AgentProgressReporter, AgentRenderDispatch, AgentRenderDispatcher, AgentSessionIdentity, AgentWorkspaceIdentity, + LineageHost, McpProgressNotificationParams, McpProgressToken, Observed, WarmFlightHost, } from '@agent-bundle/runtime'; import type { AgentNoticeInboxSignaller, AgentNoticeInboxSignalOutcome } from '@agent-bundle/runtime/notices'; +import type { AgentLineageRegistry } from '@agent-bundle/runtime/lineage'; /** One route the generated server hosts, as the generated module records it. */ export interface GeneratedRouteRecord { @@ -78,7 +82,8 @@ export interface GeneratedMcpAppRecord { export interface GeneratedRouteRequestContext { readonly http?: { readonly authInfo?: { readonly clientId?: string } }; readonly mcpReq: { - readonly _meta?: { readonly progressToken?: McpProgressToken }; + /** Request `_meta`: the progress token plus host-specific correlation keys (`claudecode/toolUseId`, `x-codex-turn-metadata`). */ + readonly _meta?: { readonly progressToken?: McpProgressToken } & Readonly>; readonly notify?: (notification: { readonly method: 'notifications/progress'; readonly params: McpProgressNotificationParams; @@ -99,15 +104,40 @@ export interface RenderedGeneratedRoute { interface GeneratedRouteIdentity { readonly actor?: Observed; readonly host?: Observed; + readonly lineage: Observed; readonly session?: Observed; readonly workspace: Observed; } +/** + * Lineage for one MCP tool call: Codex names it in `_meta`, Claude names the + * pre-tool hook's `tool_use_id` in `_meta`, Cursor names nothing — so the + * registry falls back to the open `MCP:` pre-tool hook. Without a + * registry (a project with no event routes, or the in-memory proof level) the + * axis is honestly absent. + */ +const toolCallLineage = ( + registry: AgentLineageRegistry | undefined, + context: GeneratedRouteRequestContext, + toolName: string, + clientName: string | undefined, + fallbackHost: LineageHost | undefined, +): Observed => { + if (registry === undefined) return unavailable('not-provided'); + return registry.resolveToolCall({ + host: lineageHostFromClient(clientName) ?? fallbackHost, + meta: context.mcpReq._meta, + toolName, + }); +}; + /** Identity the server derives from the transport's own request context. */ const requestIdentity = ( context: GeneratedRouteRequestContext, clientName: string | undefined, + lineage: Observed, ): GeneratedRouteIdentity => ({ + lineage, ...(context.http?.authInfo?.clientId === undefined ? {} : { actor: available({ id: context.http.authInfo.clientId }, 'native') }), @@ -157,9 +187,9 @@ export const renderGeneratedRoute = async ( route: GeneratedRouteRecord, input: unknown, context: GeneratedRouteRequestContext, - identity?: { readonly clientName?: string }, + identity?: { readonly clientName?: string; readonly lineage?: Observed }, ): Promise => runAgentRequest({ - ...requestIdentity(context, identity?.clientName), + ...requestIdentity(context, identity?.clientName, identity?.lineage ?? unavailable('not-provided')), invocation: { artifactEpoch, kind: 'tool', operationId: route.id, surface: route.name }, signal: context.mcpReq.signal, }, async () => { @@ -251,13 +281,22 @@ const settled = async (operation: () => Promise, afterRender: GeneratedRen } }; +export interface RegisterGeneratedRoutesOptions { + /** Runs after every render the server completes (notice delivery follow-up). */ + readonly afterRender?: GeneratedRenderSettled; + /** The warm runtime's lineage registry; tool calls resolve their conversation through it. */ + readonly lineage?: AgentLineageRegistry; + /** The artifact's host, used when the negotiated client name maps to none. */ + readonly lineageHost?: LineageHost; +} + /** Registers the compiled MCP routes on a server, keyed by route kind. */ export const registerGeneratedRoutes = ( server: McpServer, routes: Readonly>, dispatcher: AgentRenderDispatcher, artifactEpoch: string, - afterRender?: GeneratedRenderSettled, + options: RegisterGeneratedRoutesOptions = {}, ): void => { for (const route of Object.values(routes)) { switch (route.kind) { @@ -275,10 +314,10 @@ export const registerGeneratedRoutes = ( route, input, context, - { clientName }, + { clientName, lineage: toolCallLineage(options.lineage, context, route.name, clientName, options.lineageHost) }, ); return attachMcpStructuredContent(rendered.toolResult, rendered.result); - }, afterRender)) as never); + }, options.afterRender)) as never); break; } case 'resource': { @@ -300,7 +339,7 @@ export const registerGeneratedRoutes = ( context, { clientName }, )).result; - }, afterRender)) as never, + }, options.afterRender)) as never, ); break; } @@ -318,7 +357,7 @@ export const registerGeneratedRoutes = ( context, { clientName }, )).result; - }, afterRender)) as never); + }, options.afterRender)) as never); break; default: { const unreachable: never = route.kind; @@ -468,6 +507,7 @@ export const createFlightWorkerHost = ( host: context.host, id, invocation, + lineage: context.lineage, requestInvocation: context.invocation, session: context.session, type: 'render', @@ -515,9 +555,18 @@ export interface CreateGeneratedRouteMcpServerOptions { readonly apps?: readonly GeneratedMcpAppRecord[]; /** Identity every request carries, so a stale worker fails loudly. */ readonly artifactEpoch: string; + /** Releases the lineage registry's durable store when the server closes. */ + readonly disposeLineage?: () => Promise; readonly events?: GeneratedEventRuntimeBinding; /** Renders one invocation to Flight bytes. Closed when the server closes. */ readonly host: GeneratedRouteExecutionHost; + /** + * The runtime-held conversation registry (#host-lineage): subagent + * start/stop and pre-tool events feed it, and every event route and tool + * call reads `request.lineage` from it. Absent registries leave the axis + * `unavailable('not-provided')`. + */ + readonly lineage?: AgentLineageRegistry; readonly notices?: GeneratedNoticeDeliveryBinding; readonly plugin: { readonly name: string; readonly version: string }; readonly routes: Readonly>; @@ -627,6 +676,30 @@ const installNoticeInboxSubscriptions = ( else owed = true; return Promise.resolve(); }; + +const lineageHostFor = (target: string): LineageHost | undefined => + target === 'claude' || target === 'codex' || target === 'cursor' ? target : undefined; + +/** + * Lineage for one hook event. Cloud Cursor agents run no user hooks at all, so + * a `sessionEnd`-less cloud payload can never feed the registry; the portable + * target has no subagent events by contract. + */ +const eventLineage = async ( + registry: AgentLineageRegistry | undefined, + target: string, + event: CanonicalAgentEvent, + native: Readonly>, + idempotencyKey: string, + observedAt: string, +): Promise> => { + const host = lineageHostFor(target); + if (host === undefined) return unavailable('no-subagent-events'); + if (host === 'cursor' && native['is_background_agent'] === true) { + return unavailable('cloud-agent-no-user-hooks'); + } + if (registry === undefined) return unavailable('not-provided'); + return registry.observe({ event, host, idempotencyKey, native, observedAt }); }; const nativeString = ( @@ -657,6 +730,7 @@ const startEventRuntime = async ( dispatcher: AgentRenderDispatcher, host: WarmFlightHost, afterRender: GeneratedRenderSettled | undefined, + registry: AgentLineageRegistry | undefined, ): Promise<{ readonly close: () => Promise }> => { const startedAt = new Date().toISOString(); return events.createEventRuntimeServer({ @@ -686,6 +760,16 @@ const startEventRuntime = async ( ?? (Array.isArray(workspaceRoots) && typeof workspaceRoots[0] === 'string' ? workspaceRoots[0] : undefined); + // The registry sees the event before the route renders, so the route + // observes its own subagent start/stop already applied. + const lineage = await eventLineage( + registry, + target, + event, + request.native, + props.canonical.idempotencyKey, + props.canonical.observedAt, + ); return runAgentRequest({ host: available({ name: target }, 'native'), invocation: { @@ -695,6 +779,7 @@ const startEventRuntime = async ( operationId: `event:${event}`, surface: event, }, + lineage, ...(sessionId === undefined ? {} : { session: available({ sessionId }, 'native') }), signal, ...(workspaceRoot === undefined ? {} : { workspace: available({ root: workspaceRoot }, 'native') }), @@ -746,8 +831,14 @@ export const createGeneratedRouteMcpServer = async ( : installNoticeInboxSubscriptions(server, options.notices); const events = options.events === undefined ? undefined - : await startEventRuntime(options.events, dispatcher, options.host, afterRender); - registerGeneratedRoutes(server, options.routes, dispatcher, options.artifactEpoch, afterRender); + : await startEventRuntime(options.events, dispatcher, options.host, afterRender, options.lineage); + registerGeneratedRoutes(server, options.routes, dispatcher, options.artifactEpoch, { + ...(afterRender === undefined ? {} : { afterRender }), + ...(options.lineage === undefined ? {} : { lineage: options.lineage }), + ...(options.events === undefined || lineageHostFor(options.events.target) === undefined + ? {} + : { lineageHost: lineageHostFor(options.events.target) }), + }); registerGeneratedMcpApps(server, options.apps ?? []); const close = server.close.bind(server); server.close = async (): Promise => { @@ -757,7 +848,8 @@ export const createGeneratedRouteMcpServer = async ( // abandons a notification write still pending rather than waiting on the // client's wire, so a subscriber that stopped reading cannot wedge this // teardown. Whatever fails on the way, the protocol and its transport are - // always closed; the teardown error surfaces once they are. + // always closed; the teardown error surfaces once they are. The lineage + // journal closes after the host, once no render can observe into it. try { try { await events?.close(); @@ -765,7 +857,11 @@ export const createGeneratedRouteMcpServer = async ( try { await options.notices?.close(); } finally { - await options.host.close(); + try { + await options.host.close(); + } finally { + await options.disposeLineage?.(); + } } } } finally { diff --git a/packages/agent-bundle/src/test/mcp.ts b/packages/agent-bundle/src/test/mcp.ts index 868f50527..29e13a1a1 100644 --- a/packages/agent-bundle/src/test/mcp.ts +++ b/packages/agent-bundle/src/test/mcp.ts @@ -20,6 +20,8 @@ import type { AgentStateDriver, AgentStateEventSchemas, } from '@agent-bundle/runtime/state'; +import type { LineageHost } from '@agent-bundle/runtime'; +import type { AgentLineageRegistry } from '@agent-bundle/runtime/lineage'; import type { createGeneratedRuntimeState } from '@agent-bundle/runtime/mount'; import type { AgentNoticeInboxSignaller, AgentNoticePrincipal } from '@agent-bundle/runtime/notices'; import type { ReactNode } from 'react'; @@ -66,6 +68,14 @@ export interface InMemoryMcpSessionOptionsBase< TState = unknown, TEvents extends AgentStateEventSchemas = AgentStateEventSchemas, > { + /** + * A lineage registry the generated server resolves tool calls through, + * exactly as the artifact does; omitted sessions observe `request.lineage` + * as `unavailable('not-provided')`. + */ + readonly lineage?: AgentLineageRegistry; + /** The host vocabulary the registry applies when the in-memory client name maps to none. */ + readonly lineageHost?: LineageHost; readonly manifest?: AgentBundleTestManifest; /** MCP server name. Optional when the project compiled exactly one server. */ readonly server?: string; @@ -386,6 +396,7 @@ export const openInMemoryMcpServer = async < // harness context seam to override forwarded transport identity. actor: transport.actor, host: transport.host, + lineage: transport.lineage, session: transport.session, workspace: transport.workspace, ...context, @@ -436,6 +447,20 @@ export const openInMemoryMcpServer = async < artifactEpoch, host, ...(notices === undefined ? {} : { notices }), + ...(options.lineage === undefined ? {} : { lineage: options.lineage }), + ...(options.lineageHost === undefined + ? {} + : { + events: { + allowedTargets: [options.lineageHost], + artifactEpoch, + createCanonicalEventProps: (() => { throw new Error('in-memory lineage sessions dispatch no events'); }) as never, + createEventRuntimeServer: (async () => ({ close: async () => undefined })) as never, + endpointId: `${artifactEpoch}:in-memory`, + projectEventDocument: (() => undefined) as never, + target: options.lineageHost, + }, + }), plugin: manifest.plugin, routes: routes as never, }); diff --git a/packages/agent-bundle/tests/adapter-capability-states.test.ts b/packages/agent-bundle/tests/adapter-capability-states.test.ts index 3a10b8705..dd87a8ed5 100644 --- a/packages/agent-bundle/tests/adapter-capability-states.test.ts +++ b/packages/agent-bundle/tests/adapter-capability-states.test.ts @@ -1325,6 +1325,38 @@ it('pins dated deferral rows for every explicitly deferred native callback from } }); +it('advertises conversation lineage per host with dated 2026-09-03 evidence', async () => { + const { readFile } = await import('node:fs/promises'); + const rows = ['depth', 'mcp-correlation', 'parent', 'root', 'subagent-events']; + const files = { + claude: 'claude-2.1.250.json', + codex: 'codex-0.147.0.json', + cursor: 'cursor-2026-08-28.json', + portable: 'portable-1.0.0.json', + }; + for (const [host, file] of Object.entries(files)) { + const table = JSON.parse(await readFile(new URL(`../src/adapters/capabilities/${file}`, import.meta.url), 'utf8')) as Record; + const lineage = table.lineage as Record; + expect(Object.keys(lineage).filter((row) => row !== 'cloud').sort()).toEqual(rows); + for (const row of rows) { + const entry = lineage[row]!; + expect(['supported', 'degraded', 'unavailable']).toContain(entry.state); + const dated = entry.state === 'supported' ? entry.evidence?.join(' ') : entry.reason; + expect(dated, `${host} lineage.${row}`).toMatch(/2026-09-03/u); + } + if (host === 'portable') { + expect(Object.values(lineage).every((entry) => entry.state === 'unavailable')).toBe(true); + } else { + // Every hook-bearing host names its subagents; none names a parent on the child's own events. + expect(lineage['subagent-events']!.state).toBe('supported'); + expect(lineage['parent']!.state).toBe('degraded'); + } + // Only Codex resolves MCP calls without a hook window; Cursor cannot correlate natively at all. + expect(lineage['mcp-correlation']!.state).toBe(host === 'cursor' ? 'degraded' : host === 'portable' ? 'unavailable' : 'supported'); + if (host === 'cursor') expect(lineage['cloud']!.state).toBe('unavailable'); + } +}); + it('advertises notice delivery routes per host with dated unavailability (#99 stage 4)', async () => { const { readFile } = await import('node:fs/promises'); const routes = ['current-response', 'directed-push', 'host-toast', 'mcp-inbox', 'mcp-resource-updated', 'next-event']; diff --git a/packages/agent-bundle/tests/entry-shell.test.ts b/packages/agent-bundle/tests/entry-shell.test.ts index afe5437ff..12cb6cb4e 100644 --- a/packages/agent-bundle/tests/entry-shell.test.ts +++ b/packages/agent-bundle/tests/entry-shell.test.ts @@ -230,7 +230,14 @@ it('generates one final-only Flight MCP factory from filesystem routes', () => { expect(source).toContain('createFlightWorkerHost(new URL("./mcp-curator-flight.mjs", import.meta.url), ARTIFACT_EPOCH)'); expect(source).toContain('artifactEpoch: ARTIFACT_EPOCH'); expect(source).toContain('plugin: {"name":"route-fixture","version":"1.2.3"}'); - expect(source).toContain('export default async () => createGeneratedRouteMcpServer('); + expect(source).toContain('export default async () => {'); + expect(source).toContain('return createGeneratedRouteMcpServer({'); + // The lineage registry journals through the sqlite kernel beside project + // state and degrades to memory when the store cannot open (#host-lineage). + expect(source).toContain("from '@agent-bundle/runtime/lineage'"); + expect(source).toContain('createSqliteStateDriver({ root: join(resolve(lineageAnchor), \'state\') })'); + expect(source).toContain('lineage: lineage.registry,'); + expect(source).toContain('disposeLineage: lineage.dispose,'); // The event runtime's modules are aliased into the artifact, so the entry // imports them and hands them to the shared runtime; the wiring itself is // not re-templated here. @@ -365,6 +372,7 @@ it('generates the warm react-server Flight worker separately from the MCP dispat expect(source).toContain( '"hook:event-route:tool-after": Object.freeze({ event: "tool/after", id: "event:tool/after", kind: \'event-route\'', ); + expect(source).toContain("lineage: message.lineage ?? unavailable('not-provided'),"); expect(createHash('sha256').update(source).digest('hex')).toBe( 'e9126849e5ad955dbd1f3d56ccdcb0eabe1293d265f861dd5a10339c1e2a3bfb', ); diff --git a/packages/agent-bundle/tests/event-project.test.ts b/packages/agent-bundle/tests/event-project.test.ts index 0c06717d8..8dbb4a56d 100644 --- a/packages/agent-bundle/tests/event-project.test.ts +++ b/packages/agent-bundle/tests/event-project.test.ts @@ -40,7 +40,10 @@ it('validates native event envelopes with the generated wrapper error contract', expect(validateNativeEventEnvelope(valid, options)).toBe(valid); expect(() => validateNativeEventEnvelope({ ...valid, tool_response: 'not-an-object' }, options)) - .toThrow('Agent Bundle event route error: native tool_response must be an object'); + .toThrow('Agent Bundle event route error: native tool_response must be an object or an array'); + // Claude Code 2.1.257 delivers MCP tool results as a content-block array (2026-09-03 capture). + expect(validateNativeEventEnvelope({ ...valid, tool_response: [{ text: 'ok', type: 'text' }] }, options)) + .toMatchObject({ tool_response: [{ text: 'ok', type: 'text' }] }); expect(() => validateNativeEventEnvelope({ ...valid, hook_event_name: 'BeforeToolUse' }, options)) .toThrow('Agent Bundle event route error: native hook_event_name must equal PostToolUse'); expect(() => validateNativeEventEnvelope([], options)) diff --git a/packages/agent-bundle/tests/generated-route-server.test.ts b/packages/agent-bundle/tests/generated-route-server.test.ts index 1e979ce6a..94fefb1e4 100644 --- a/packages/agent-bundle/tests/generated-route-server.test.ts +++ b/packages/agent-bundle/tests/generated-route-server.test.ts @@ -178,6 +178,7 @@ it('lists and calls a generated filesystem tool through final-only Flight', { re state: 'available', value: { name: 'generated-route-test' }, }, + lineage: { reason: 'not-provided', state: 'unavailable' }, session: { reason: 'not-provided', state: 'unavailable' }, workspace: { source: 'derived', diff --git a/packages/agent-bundle/tests/hooks.test.ts b/packages/agent-bundle/tests/hooks.test.ts index d6668dc17..ee61af15c 100644 --- a/packages/agent-bundle/tests/hooks.test.ts +++ b/packages/agent-bundle/tests/hooks.test.ts @@ -1412,7 +1412,7 @@ it('rejects malformed event-specific native input before calling generated Codex // Codex pins tool_input/tool_response as any JSON value (presence only); // Claude documents both as objects. const toolInputError = target === 'codex' ? 'tool_input is required' : 'tool_input must be an object'; - const toolResponseError = target === 'codex' ? 'tool_response is required' : 'tool_response must be an object'; + const toolResponseError = target === 'codex' ? 'tool_response is required' : 'tool_response must be an object or an array'; await expect(runNativeHook(join(hooksRoot, 'before-tool-check-command-1f5b5818.mjs'), { ...common, hook_event_name: 'PreToolUse', tool_name: 'Bash', tool_use_id: 'use-1', ...(target === 'codex' ? {} : { tool_input: [] }), diff --git a/packages/agent-bundle/tests/lifecycle-replay-routes.test.ts b/packages/agent-bundle/tests/lifecycle-replay-routes.test.ts index a592ea2e1..a6bb09391 100644 --- a/packages/agent-bundle/tests/lifecycle-replay-routes.test.ts +++ b/packages/agent-bundle/tests/lifecycle-replay-routes.test.ts @@ -87,6 +87,7 @@ class RecordingService implements LifecycleReplayRouteService { operationId: 'event:tool/after', surface: 'tool/after', }), + lineage: Object.freeze({ reason: 'not-provided', state: 'unavailable' }), session: Object.freeze({ reason: 'not-provided', state: 'unavailable' }), workspace: Object.freeze({ reason: 'not-provided', state: 'unavailable' }), }), @@ -175,7 +176,7 @@ it('preserves stale and real native-envelope diagnostics at the HTTP boundary', await expect(malformed.json()).resolves.toEqual({ diagnostic: { code: 'AB8211', - message: 'Agent Bundle event route error: native tool_response must be an object', + message: 'Agent Bundle event route error: native tool_response must be an object or an array', }, }); diff --git a/packages/agent-bundle/tests/lifecycle-replay-service.test.ts b/packages/agent-bundle/tests/lifecycle-replay-service.test.ts index e4556972e..68108df56 100644 --- a/packages/agent-bundle/tests/lifecycle-replay-service.test.ts +++ b/packages/agent-bundle/tests/lifecycle-replay-service.test.ts @@ -156,7 +156,7 @@ it('surfaces the real native envelope validator message as a malformed request', source: 'observed', })).rejects.toMatchObject({ code: 'AB8211', - message: 'Agent Bundle event route error: native tool_response must be an object', + message: 'Agent Bundle event route error: native tool_response must be an object or an array', status: 400, }); }); @@ -207,6 +207,11 @@ it('mounts and reports honest receipt provenance for a Workbench replay', async operationId: 'event:tool/after', surface: 'tool/after', }, + lineage: { + source: 'receipt', + state: 'available', + value: { conversation: 'session-1', depth: 0, resolution: 'native', root: 'session-1' }, + }, session: { source: 'receipt', state: 'available', value: { sessionId: 'session-1' } }, workspace: { source: 'receipt', state: 'available', value: { root: '/tmp/lifecycle-replay' } }, }; @@ -219,6 +224,7 @@ it('mounts and reports honest receipt provenance for a Workbench replay', async operationId: 'event:tool/after', surface: 'tool/after', }, + lineage: requestContext.lineage, session: requestContext.session, workspace: requestContext.workspace, }); diff --git a/packages/agent-bundle/tests/packed-stdio-projection.test.ts b/packages/agent-bundle/tests/packed-stdio-projection.test.ts index 5d4670c25..25ecf40b1 100644 --- a/packages/agent-bundle/tests/packed-stdio-projection.test.ts +++ b/packages/agent-bundle/tests/packed-stdio-projection.test.ts @@ -151,6 +151,7 @@ it('serves compiled routes and durable state across packed process restarts', as state: 'available', value: { name: 'agent-bundle-packed-proof' }, }, + lineage: { reason: 'id-not-resolvable', state: 'unavailable' }, session: { reason: 'not-provided', state: 'unavailable' }, workspace: { source: 'derived', diff --git a/packages/agent-bundle/tests/projection/mcp-in-memory.test.ts b/packages/agent-bundle/tests/projection/mcp-in-memory.test.ts index 6de480b73..a1d6efdc0 100644 --- a/packages/agent-bundle/tests/projection/mcp-in-memory.test.ts +++ b/packages/agent-bundle/tests/projection/mcp-in-memory.test.ts @@ -101,6 +101,7 @@ describe('the in-memory MCP projection level', () => { state: 'available', value: { name: 'agent-bundle-in-memory-projection' }, }, + lineage: { reason: 'not-provided', state: 'unavailable' }, session: { reason: 'not-provided', state: 'unavailable' }, workspace: { source: 'derived', diff --git a/packages/agent-bundle/tests/projection/mcp-lineage.test.ts b/packages/agent-bundle/tests/projection/mcp-lineage.test.ts new file mode 100644 index 000000000..aea9e0e03 --- /dev/null +++ b/packages/agent-bundle/tests/projection/mcp-lineage.test.ts @@ -0,0 +1,115 @@ +import { describe, expect, it } from '@rstest/core'; +import { createAgentLineageRegistry } from '@agent-bundle/runtime/lineage'; +import { openInMemoryMcpServer } from 'agent-bundle/test'; + +const root = 'session-root'; +const child = 'agent-child'; + +const observe = ( + registry: ReturnType, + event: string, + native: Record, +) => registry.observe({ event, host: 'claude', idempotencyKey: `${event}:${JSON.stringify(native)}`, native }); + +const callContext = async ( + registry: ReturnType, + meta: Record | undefined, +) => { + await using session = await openInMemoryMcpServer({ lineage: registry, lineageHost: 'claude' }); + const result = await session.client.callTool({ + ...(meta === undefined ? {} : { _meta: meta }), + arguments: {}, + name: 'context', + }); + return (result.structuredContent as { lineage: unknown }).lineage; +}; + +/** + * The generated MCP server and the hook wrappers share one runtime-held + * registry; this level proves the hook→MCP ordering contract observed live + * on 2026-09-03 (pre-tool hook, then tools/call, then post-tool hook) without + * a spawned process. + */ +describe('generated MCP tool calls resolve request.lineage through the runtime registry (mcp-in-memory)', () => { + it('is unresolvable before any pre-tool hook opened the window', async () => { + const registry = createAgentLineageRegistry(); + expect(await callContext(registry, { 'claudecode/toolUseId': 'toolu_1' })).toEqual({ + reason: 'id-not-resolvable', + state: 'unavailable', + }); + }); + + it('resolves a root call from claudecode/toolUseId while the PreToolUse window is open, then closes with PostToolUse', async () => { + const registry = createAgentLineageRegistry(); + await observe(registry, 'session/start', { hook_event_name: 'SessionStart', session_id: root }); + await observe(registry, 'tool/before', { + hook_event_name: 'PreToolUse', + session_id: root, + tool_input: {}, + tool_name: 'mcp__plugin_harness_harness__context', + tool_use_id: 'toolu_1', + }); + + expect(await callContext(registry, { 'claudecode/toolUseId': 'toolu_1' })).toEqual({ + source: 'derived', + state: 'available', + value: { conversation: root, depth: 0, resolution: 'registry', root }, + }); + + await observe(registry, 'tool/after', { + hook_event_name: 'PostToolUse', + session_id: root, + tool_input: {}, + tool_name: 'mcp__plugin_harness_harness__context', + tool_response: [{ text: 'ok', type: 'text' }], + tool_use_id: 'toolu_1', + }); + expect(await callContext(registry, { 'claudecode/toolUseId': 'toolu_1' })).toEqual({ + reason: 'id-not-resolvable', + state: 'unavailable', + }); + }); + + it('places a subagent call under its parent using the registry fed by SubagentStart', async () => { + const registry = createAgentLineageRegistry(); + await observe(registry, 'session/start', { hook_event_name: 'SessionStart', session_id: root }); + await observe(registry, 'tool/before', { + hook_event_name: 'PreToolUse', session_id: root, tool_input: {}, tool_name: 'Agent', tool_use_id: 'toolu_spawn', + }); + await observe(registry, 'agent/start', { + agent_id: child, agent_type: 'general-purpose', hook_event_name: 'SubagentStart', session_id: root, + }); + await observe(registry, 'tool/before', { + agent_id: child, + agent_type: 'general-purpose', + hook_event_name: 'PreToolUse', + session_id: root, + tool_input: {}, + tool_name: 'mcp__plugin_harness_harness__context', + tool_use_id: 'toolu_child_call', + }); + + // Without _meta (Cursor-shaped), the most recent open pre-tool hook naming the tool wins. + expect(await callContext(registry, undefined)).toEqual({ + source: 'derived', + state: 'available', + value: { + conversation: child, + depth: 1, + parent: root, + resolution: 'inferred', + root, + subagent: { id: child, toolCallId: 'toolu_spawn', type: 'general-purpose' }, + }, + }); + expect(await callContext(registry, { 'claudecode/toolUseId': 'toolu_child_call' })).toMatchObject({ + value: { conversation: child, depth: 1, resolution: 'registry' }, + }); + }); + + it('leaves the axis honestly absent when the session has no registry', async () => { + await using session = await openInMemoryMcpServer(); + const result = await session.client.callTool({ arguments: {}, name: 'context' }); + expect((result.structuredContent as { lineage: unknown }).lineage).toEqual({ reason: 'not-provided', state: 'unavailable' }); + }); +}); diff --git a/packages/agent-bundle/tests/route-unit/render-route.test.ts b/packages/agent-bundle/tests/route-unit/render-route.test.ts index 28629c344..bcbc8c557 100644 --- a/packages/agent-bundle/tests/route-unit/render-route.test.ts +++ b/packages/agent-bundle/tests/route-unit/render-route.test.ts @@ -75,16 +75,26 @@ describe('renderRoute through the real renderer', () => { expect(rendered.result).toEqual({ actor: notProvided, host: notProvided, + lineage: notProvided, session: notProvided, workspace: notProvided, }); }); it('preserves injected identity values and their observation sources', async () => { + const lineage = { + conversation: 'agent-child', + depth: 1, + parent: 'route-unit-session', + resolution: 'registry', + root: 'route-unit-session', + subagent: { id: 'agent-child', toolCallId: 'toolu_spawn', type: 'general-purpose' }, + } as const; const rendered = await renderRoute('tool:harness/context', { context: { actor: { source: 'receipt', state: 'available', value: { id: 'actor-route-unit' } }, host: { source: 'native', state: 'available', value: { name: 'route-unit-host' } }, + lineage: { source: 'derived', state: 'available', value: lineage }, session: { source: 'native', state: 'available', value: { sessionId: 'route-unit-session' } }, workspace: { source: 'derived', state: 'available', value: { root: '/tmp/route-unit' } }, }, @@ -93,11 +103,20 @@ describe('renderRoute through the real renderer', () => { expect(rendered.result).toEqual({ actor: { source: 'receipt', state: 'available', value: { id: 'actor-route-unit' } }, host: { source: 'native', state: 'available', value: { name: 'route-unit-host' } }, + lineage: { source: 'derived', state: 'available', value: lineage }, session: { source: 'native', state: 'available', value: { sessionId: 'route-unit-session' } }, workspace: { source: 'derived', state: 'available', value: { root: '/tmp/route-unit' } }, }); }); + it('pins the typed per-host lineage unavailability reasons', async () => { + const rendered = await renderRoute('tool:harness/context', { + context: { lineage: { reason: 'no-shared-runtime', state: 'unavailable' } }, + }); + + expect(rendered.result).toMatchObject({ lineage: { reason: 'no-shared-runtime', state: 'unavailable' } }); + }); + it('does not treat lookalike business input as request identity', async () => { const rendered = await renderRoute('tool:harness/context', { input: { host: 'spoofed-host', session: 'spoofed-session' }, @@ -106,6 +125,7 @@ describe('renderRoute through the real renderer', () => { expect(rendered.result).toEqual({ actor: notProvided, host: notProvided, + lineage: notProvided, session: notProvided, workspace: notProvided, }); diff --git a/packages/rsc-runtime/package.json b/packages/rsc-runtime/package.json index 5ab8589c0..5386c1a21 100644 --- a/packages/rsc-runtime/package.json +++ b/packages/rsc-runtime/package.json @@ -63,6 +63,10 @@ "./mount": { "types": "./dist/mount/index.d.ts", "import": "./dist/mount.js" + }, + "./lineage": { + "types": "./dist/lineage/index.d.ts", + "import": "./dist/lineage.js" } }, "scripts": { diff --git a/packages/rsc-runtime/rslib.config.ts b/packages/rsc-runtime/rslib.config.ts index b79e901f7..e072e6547 100644 --- a/packages/rsc-runtime/rslib.config.ts +++ b/packages/rsc-runtime/rslib.config.ts @@ -64,6 +64,24 @@ export default defineConfig({ entry: { 'notices/inbox-route': './src/notices/inbox-route.ts' }, }, }, + { + ...sharedLib, + // The lineage registry reuses the state entry's kernel (its durable + // journal is an ordinary state definition) and the package root's + // request-context helpers; stateless consumers never load it. + output: { + cleanDistPath: false, + externals: { + '../agent-request.js': './index.js', + '../lineage-native.js': './index.js', + '../state/contract.js': './state.js', + '../state/index.js': './state.js', + }, + }, + source: { + entry: { lineage: './src/lineage/index.ts' }, + }, + }, { ...sharedLib, // The sqlite driver is its own entry so `node:sqlite` (and its diff --git a/packages/rsc-runtime/src/agent-request.ts b/packages/rsc-runtime/src/agent-request.ts index f8949ea58..80438b230 100644 --- a/packages/rsc-runtime/src/agent-request.ts +++ b/packages/rsc-runtime/src/agent-request.ts @@ -52,7 +52,15 @@ export type AgentContextUnavailableReason = | 'not-provided' | 'unsupported-surface' | 'host-omitted' - | 'unauthenticated'; + | 'unauthenticated' + /** The host defines no subagent start/stop events, so no tree can exist. */ + | 'no-subagent-events' + /** The payload carried an id the runtime never saw start (registry cold, or the host omitted the link). */ + | 'id-not-resolvable' + /** Cursor cloud agents run no user hooks, so nothing feeds the registry. */ + | 'cloud-agent-no-user-hooks' + /** The route ran in a standalone hook process with no warm runtime holding the registry. */ + | 'no-shared-runtime'; export type Observed = | { readonly source: ObservedSource; readonly state: 'available'; readonly value: T } @@ -74,6 +82,44 @@ export interface AgentWorkspaceIdentity { readonly root: string; } +/** The subagent a lineage describes when the current conversation is not the root. */ +export interface AgentLineageSubagent { + /** The host's own id for the subagent (Claude/Codex `agent_id`, Cursor `subagent_id`). */ + readonly id: string; + readonly isParallelWorker?: boolean; + /** The parent's tool call that spawned it, when the host names one. */ + readonly toolCallId?: string; + readonly type?: string; +} + +/** + * How the runtime arrived at `parent`/`root`/`depth`: straight from host fields + * (`native`), from the warm runtime's registry fed by subagent start/stop + * events (`registry`), or by ordering inference the host forced on it + * (`inferred`, e.g. Cursor binds a child conversation to the most recent + * pending `subagentStart`). + */ +export type AgentLineageResolution = 'native' | 'registry' | 'inferred'; + +/** + * Where this request sits in the conversation tree (#host-lineage). The shape + * is identical on every surface: events, generated MCP tools, routed CLI, and + * rendered scripts. `conversation` identifies the agent whose activity this is + * — the host session for a root, the subagent id (Claude/Codex) or the child + * conversation id (Cursor) below it. + */ +export interface AgentLineage { + readonly conversation: string; + /** Root is depth 0; each subagent level adds one. */ + readonly depth: number; + /** Turn-shaped id when the host has one: Cursor `generation_id`, Codex `turn_id`, Claude `prompt_id`. */ + readonly generation?: string; + readonly parent?: string; + readonly resolution: AgentLineageResolution; + readonly root: string; + readonly subagent?: AgentLineageSubagent; +} + export interface AgentFilesystemAuthority { readonly roots: readonly string[]; } @@ -154,6 +200,12 @@ export interface AgentRequestContext { readonly session: Observed; readonly actor: Observed; readonly workspace: Observed; + /** + * Conversation lineage resolved by the warm runtime's registry (fed by the + * subagent start/stop event families and pre-tool hooks) or straight from + * host fields; `unavailable` carries the per-host reason. + */ + readonly lineage: Observed; readonly capabilities: AgentRequestCapabilities; readonly progress: AgentProgressReporter; readonly signal: AbortSignal; @@ -191,6 +243,7 @@ export interface AgentRequestInitBase { readonly capabilities?: AgentRequestCapabilities; readonly host?: Observed; readonly invocation: AgentInvocationInput; + readonly lineage?: Observed; /** Optional durable notice authority; omitted projects load no notice code. */ readonly noticeLedger?: AgentNoticeLedger; readonly progress?: AgentProgressReporter; @@ -289,6 +342,7 @@ interface FrozenValues { readonly capabilities: AgentRequestCapabilities; readonly host: Observed; readonly invocation: AgentInvocation; + readonly lineage: Observed; readonly notices: AgentNoticesHandle | undefined; readonly progress: AgentProgressReporter; readonly providers: AgentProviderValues; @@ -360,6 +414,9 @@ const createHandle = (lease: Lease): AgentRequestContext => Object.freeze({ get workspace() { return open(lease).workspace; }, + get lineage() { + return open(lease).lineage; + }, get capabilities() { return open(lease).capabilities; }, @@ -427,6 +484,7 @@ export const runAgentRequest = async ( const actor = snapshotObserved(init.actor ?? unavailable()); const host = snapshotObserved(init.host ?? unavailable()); const invocation = invocationFrom(init.invocation); + const lineage = snapshotObserved(init.lineage ?? unavailable()); const session = snapshotObserved(init.session ?? unavailable()); const signal = init.signal ?? new AbortController().signal; const workspace = snapshotObserved(init.workspace ?? unavailable()); @@ -442,6 +500,7 @@ export const runAgentRequest = async ( capabilities: snapshotCapabilities(init.capabilities ?? emptyCapabilities()), host, invocation, + lineage, notices: noticeLease?.handle, progress: init.progress ?? silentProgress, providers: Object.freeze({ ...(init.providers ?? {}) }), diff --git a/packages/rsc-runtime/src/index.ts b/packages/rsc-runtime/src/index.ts index 1af0f7156..eec62f1f3 100644 --- a/packages/rsc-runtime/src/index.ts +++ b/packages/rsc-runtime/src/index.ts @@ -90,6 +90,10 @@ export { lowerMcpResult } from './lower-mcp.js'; export type { JsonObject, JsonValue } from './lower-mcp.js'; export { createRscRequestContext } from './request-context.js'; export type { AgentRenderInvocation } from './agent-request.js'; +// Registry-free lineage helpers: what a payload proves on its own. The +// registry itself ships behind the './lineage' subpath with the state kernel. +export { lineageCarrier, lineageHostFromClient, resolveNativeLineage } from './lineage-native.js'; +export type { LineageCarrier, LineageHost } from './lineage-native.js'; // Type-only: the state kernel itself ships behind the './state' subpath so // stateless artifacts include none of it (#98). export type { AgentStateHandle, AgentStateLifetime } from './state/contract.js'; diff --git a/packages/rsc-runtime/src/lineage-native.ts b/packages/rsc-runtime/src/lineage-native.ts new file mode 100644 index 000000000..6ff7da89e --- /dev/null +++ b/packages/rsc-runtime/src/lineage-native.ts @@ -0,0 +1,85 @@ +import { available, unavailable, type AgentLineage, type Observed } from './agent-request.js'; + +export type LineageHost = 'claude' | 'codex' | 'cursor'; + +const nativeString = (native: Readonly>, key: string): string | undefined => { + const value = native[key]; + return typeof value === 'string' && value.trim() !== '' ? value : undefined; +}; + +/** Maps a negotiated MCP client name to the host whose lineage vocabulary applies. */ +export const lineageHostFromClient = (clientName: string | undefined): LineageHost | undefined => { + if (clientName === undefined) return undefined; + if (clientName.startsWith('claude')) return 'claude'; + if (clientName.startsWith('codex')) return 'codex'; + if (clientName.startsWith('cursor')) return 'cursor'; + return undefined; +}; + +export interface LineageCarrier { + /** The agent whose activity the payload describes, in the host's own id. */ + readonly conversation: string | undefined; + readonly generation: string | undefined; + /** The root the host names on the payload; Cursor names none on a child's events. */ + readonly root: string | undefined; +} + +/** + * Which conversation a native hook payload speaks for. Observed 2026-09-03 + * (`docs/audits/2026-09-03-host-lineage-matrix.md`): Claude and Codex put the + * subagent in `agent_id` and keep the root in `session_id`; Cursor gives each + * subagent a fresh `conversation_id` and never repeats the root on it. + */ +export const lineageCarrier = ( + host: LineageHost, + native: Readonly>, +): LineageCarrier => { + switch (host) { + case 'claude': + return { + conversation: nativeString(native, 'agent_id') ?? nativeString(native, 'session_id'), + generation: nativeString(native, 'prompt_id'), + root: nativeString(native, 'session_id'), + }; + case 'codex': + return { + conversation: nativeString(native, 'agent_id') ?? nativeString(native, 'session_id'), + generation: nativeString(native, 'turn_id'), + root: nativeString(native, 'session_id'), + }; + case 'cursor': + return { + conversation: nativeString(native, 'conversation_id') ?? nativeString(native, 'session_id'), + generation: nativeString(native, 'generation_id'), + root: undefined, + }; + default: { + const unreachable: never = host; + throw new Error(`Unhandled lineage host ${String(unreachable)}`); + } + } +}; + +/** + * Lineage a standalone hook process can state without the registry: Claude and + * Codex name the root on every payload, so a payload with no `agent_id` is the + * root itself. Anything subagent-shaped — and every Cursor payload, whose + * conversation id says nothing about depth — needs the warm runtime. + */ +export const resolveNativeLineage = ( + host: LineageHost, + native: Readonly>, +): Observed => { + const carrier = lineageCarrier(host, native); + if (host === 'cursor' || carrier.conversation === undefined || carrier.root === undefined) { + return unavailable('no-shared-runtime'); + } + if (carrier.conversation !== carrier.root) return unavailable('no-shared-runtime'); + return available({ + conversation: carrier.root, + depth: 0, + ...(carrier.generation === undefined ? {} : { generation: carrier.generation }), + resolution: 'native', + root: carrier.root, + }, 'native'); +}; diff --git a/packages/rsc-runtime/src/lineage/index.ts b/packages/rsc-runtime/src/lineage/index.ts new file mode 100644 index 000000000..d7fb168d9 --- /dev/null +++ b/packages/rsc-runtime/src/lineage/index.ts @@ -0,0 +1,29 @@ +export { + createAgentLineageRegistry, + type AgentLineageRegistry, + type CreateAgentLineageRegistryOptions, + type LineageEventFamily, + type LineageObservation, + type LineageToolCallQuery, +} from './registry.js'; +export { + lineageCarrier, + lineageHostFromClient, + resolveNativeLineage, + type LineageCarrier, + type LineageHost, +} from '../lineage-native.js'; +export { + AGENT_LINEAGE_STATE_ID, + agentLineageStateDefinition, + LINEAGE_OPEN_CALL_RETENTION, + LINEAGE_PENDING_SPAWN_RETENTION, + LINEAGE_STOPPED_RETENTION, + LineageNodeSchema, + LineageStateSchema, + reduceLineage, + type LineageEvents, + type LineageNode, + type LineageState, + type OpenToolCall, +} from './state.js'; diff --git a/packages/rsc-runtime/src/lineage/registry.ts b/packages/rsc-runtime/src/lineage/registry.ts new file mode 100644 index 000000000..b4fa005a7 --- /dev/null +++ b/packages/rsc-runtime/src/lineage/registry.ts @@ -0,0 +1,345 @@ +import { + available, + unavailable, + type AgentLineage, + type AgentLineageResolution, + type Observed, +} from '../agent-request.js'; +import { lineageCarrier, type LineageHost } from '../lineage-native.js'; +import type { AgentStateStore } from '../state/contract.js'; +import { + initialLineageState, + reduceLineage, + type LineageEvents, + type LineageNode, + type LineageState, + type OpenToolCall, +} from './state.js'; + +/** The canonical event families the registry reacts to; every other family only resolves. */ +export type LineageEventFamily = + | 'agent/start' + | 'agent/stop' + | 'tool/before' + | 'tool/after' + | 'tool/failure' + | (string & {}); + +export interface LineageObservation { + readonly event: LineageEventFamily; + readonly host: LineageHost; + /** Caller-owned dedupe identity for the durable journal (the canonical event idempotency key). */ + readonly idempotencyKey: string; + readonly native: Readonly>; + readonly observedAt?: string; +} + +export interface LineageToolCallQuery { + readonly host: LineageHost | undefined; + /** The MCP request `_meta`, when the transport supplied one. */ + readonly meta?: Readonly> | undefined; + /** The protocol tool name the server registered (`dump`), never the host-prefixed spelling. */ + readonly toolName: string; +} + +export interface AgentLineageRegistry { + /** Feeds the registry with one hook event and resolves the lineage of the conversation that carried it. */ + observe(observation: LineageObservation): Promise>; + /** Resolves the lineage of an MCP tool call from `_meta` or from the open pre-tool hook window. */ + resolveToolCall(query: LineageToolCallQuery): Observed; + /** The current tree, for dumps and the Workbench. */ + snapshot(): LineageState; +} + +export interface CreateAgentLineageRegistryOptions { + /** Durable journal; omitted registries live only in memory. */ + readonly store?: AgentStateStore; +} + +const nativeString = (native: Readonly>, key: string): string | undefined => { + const value = native[key]; + return typeof value === 'string' && value.trim() !== '' ? value : undefined; +}; + +const SPAWN_TOOLS: Readonly boolean>> = Object.freeze({ + claude: (toolName) => toolName === 'Agent' || toolName === 'Task', + codex: (toolName) => toolName.endsWith('spawn_agent'), + cursor: (toolName) => toolName === 'Task', +}); + +const lineageOf = (node: LineageNode, generation: string | undefined, resolution: AgentLineageResolution): AgentLineage => Object.freeze({ + conversation: node.id, + depth: node.depth, + ...(generation === undefined ? {} : { generation }), + ...(node.parent === undefined ? {} : { parent: node.parent }), + resolution, + root: node.root, + ...(node.depth === 0 + ? {} + : { + subagent: Object.freeze({ + id: node.subagentId ?? node.id, + ...(node.isParallelWorker === undefined ? {} : { isParallelWorker: node.isParallelWorker }), + ...(node.toolCallId === undefined ? {} : { toolCallId: node.toolCallId }), + ...(node.type === undefined ? {} : { type: node.type }), + }), + }), +}); + +const rootNode = (conversation: string, generation: string | undefined, startedAt: string): LineageNode => ({ + depth: 0, + ...(generation === undefined ? {} : { generation }), + id: conversation, + root: conversation, + startedAt, +}); + +export const createAgentLineageRegistry = ( + options: CreateAgentLineageRegistryOptions = {}, +): AgentLineageRegistry => { + const { store } = options; + let state: LineageState = initialLineageState; + let hydrated = store === undefined; + let sequence = 0; + + const hydrate = async (): Promise => { + if (hydrated || store === undefined) return; + hydrated = true; + try { + state = (await store.read()).state; + } catch { + // A cold or unreadable journal degrades to in-memory tracking; resolution stays honest through `inferred`. + } + }; + + const dispatch = async ( + name: TName, + payload: Parameters[1]['payload'], + idempotencyKey: string, + ): Promise => { + sequence += 1; + if (store === undefined) { + state = reduceLineage(state, { name, payload }); + return; + } + try { + const committed = await store.dispatch(name, payload as never, { + idempotencyKey: `lineage:${idempotencyKey}:${String(sequence)}`, + }); + state = committed.state; + } catch { + state = reduceLineage(state, { name, payload }); + } + }; + + const nodeFor = (conversation: string | undefined): LineageNode | undefined => + conversation === undefined ? undefined : state.nodes[conversation]; + + /** + * The spawn call that produced the subagent starting now: the most recent + * unclaimed one. Claude keeps the call open across `SubagentStart`; Codex + * closes it first, so the claim window is independent of `openCalls`. + */ + const claimSpawn = async (host: LineageHost, key: string): Promise => { + const spawn = SPAWN_TOOLS[host]; + for (let index = state.pendingSpawns.length - 1; index >= 0; index -= 1) { + const call = state.pendingSpawns[index]!; + if (!spawn(call.toolName)) continue; + await dispatch('spawnClaimed', { toolCallId: call.toolCallId }, `${key}:claim`); + return call; + } + return undefined; + }; + + const ensureRoot = async ( + host: LineageHost, + conversation: string, + generation: string | undefined, + observedAt: string, + key: string, + ): Promise => { + const existing = state.nodes[conversation]; + if (existing !== undefined) return existing; + if (host === 'cursor' && state.pendingChildren.length > 0) { + // A never-seen Cursor conversation while a subagentStart is pending is + // that child speaking for the first time. + const subagentId = state.pendingChildren[0]!; + await dispatch('childBound', { conversation, subagentId }, key); + const bound = state.nodes[conversation]; + if (bound !== undefined) return bound; + } + const node = rootNode(conversation, generation, observedAt); + await dispatch('nodeStarted', node, key); + return node; + }; + + const resolve = ( + host: LineageHost, + native: Readonly>, + fallback: AgentLineageResolution, + ): Observed => { + const carrier = lineageCarrier(host, native); + if (carrier.conversation === undefined) return unavailable('id-not-resolvable'); + const node = nodeFor(carrier.conversation); + if (node === undefined) return unavailable('id-not-resolvable'); + const resolution: AgentLineageResolution = node.depth === 0 && (host !== 'cursor' || state.pendingChildren.length === 0) + ? 'native' + : fallback; + return available(lineageOf(node, carrier.generation, resolution), resolution === 'native' ? 'native' : 'derived'); + }; + + const observeStart = async (observation: LineageObservation, observedAt: string): Promise => { + const { host, native } = observation; + const carrier = lineageCarrier(host, native); + const key = observation.idempotencyKey; + if (host === 'cursor') { + const subagentId = nativeString(native, 'subagent_id') ?? nativeString(native, 'tool_call_id'); + const parentId = nativeString(native, 'parent_conversation_id') ?? carrier.conversation; + if (subagentId === undefined || parentId === undefined) return; + const parent = await ensureRoot(host, parentId, undefined, observedAt, `${key}:parent`); + await dispatch('nodeStarted', { + depth: parent.depth + 1, + id: subagentId, + ...(native['is_parallel_worker'] === undefined ? {} : { isParallelWorker: native['is_parallel_worker'] === true }), + parent: parent.id, + root: parent.root, + startedAt: observedAt, + subagentId, + ...(nativeString(native, 'tool_call_id') === undefined ? {} : { toolCallId: nativeString(native, 'tool_call_id')! }), + ...(nativeString(native, 'subagent_type') === undefined ? {} : { type: nativeString(native, 'subagent_type')! }), + }, key); + return; + } + const agentId = nativeString(native, 'agent_id'); + const root = carrier.root; + if (agentId === undefined || root === undefined) return; + const rootNodeValue = await ensureRoot(host, root, undefined, observedAt, `${key}:root`); + const spawn = await claimSpawn(host, key); + const parent = (spawn === undefined ? undefined : nodeFor(spawn.conversation)) ?? rootNodeValue; + await dispatch('nodeStarted', { + depth: parent.depth + 1, + ...(carrier.generation === undefined ? {} : { generation: carrier.generation }), + id: agentId, + parent: parent.id, + root: rootNodeValue.root, + startedAt: observedAt, + ...(spawn === undefined ? {} : { toolCallId: spawn.toolCallId }), + ...(nativeString(native, 'agent_type') === undefined ? {} : { type: nativeString(native, 'agent_type')! }), + }, key); + }; + + const observeStop = async (observation: LineageObservation, observedAt: string): Promise => { + const { host, native } = observation; + const stopped = host === 'cursor' + ? (() => { + const subagentId = nativeString(native, 'subagent_id'); + if (subagentId === undefined) return undefined; + if (state.nodes[subagentId] !== undefined) return subagentId; + return Object.values(state.nodes).find((node) => node.subagentId === subagentId)?.id; + })() + : nativeString(native, 'agent_id'); + if (stopped === undefined || state.nodes[stopped] === undefined) return; + await dispatch('nodeStopped', { id: stopped, stoppedAt: observedAt }, observation.idempotencyKey); + }; + + const registry: AgentLineageRegistry = { + async observe(observation) { + await hydrate(); + const observedAt = observation.observedAt ?? new Date().toISOString(); + const { event, host, native } = observation; + const carrier = lineageCarrier(host, native); + switch (event) { + case 'agent/start': + await observeStart(observation, observedAt); + break; + case 'agent/stop': + await observeStop(observation, observedAt); + break; + default: + break; + } + // Every other carrier is known or becomes a root; Cursor children bind here. + if (carrier.conversation !== undefined && nodeFor(carrier.conversation) === undefined) { + const rootLike = host === 'cursor' || carrier.conversation === carrier.root; + if (rootLike) await ensureRoot(host, carrier.conversation, carrier.generation, observedAt, `${observation.idempotencyKey}:carrier`); + } + const toolCallId = nativeString(native, 'tool_use_id') ?? nativeString(native, 'tool_call_id'); + const toolName = nativeString(native, 'tool_name'); + if (carrier.conversation !== undefined && toolCallId !== undefined && toolName !== undefined) { + if (event === 'tool/before') { + await dispatch('toolCallOpened', { + conversation: carrier.conversation, + openedAt: observedAt, + ...(SPAWN_TOOLS[host](toolName) ? { spawn: true } : {}), + toolCallId, + toolName, + }, observation.idempotencyKey); + } else if (event === 'tool/after' || event === 'tool/failure') { + await dispatch('toolCallClosed', { conversation: carrier.conversation, toolCallId }, observation.idempotencyKey); + } + } + return resolve(host, native, host === 'cursor' ? 'inferred' : 'registry'); + }, + + resolveToolCall(query) { + const { host, meta, toolName } = query; + if (host === undefined) return unavailable('id-not-resolvable'); + if (host === 'codex') { + const turn = meta?.['x-codex-turn-metadata']; + if (turn !== null && typeof turn === 'object' && !Array.isArray(turn)) { + const record = turn as Readonly>; + const conversation = nativeString(record, 'thread_id'); + const root = nativeString(record, 'session_id'); + if (conversation !== undefined && root !== undefined) { + const parent = nativeString(record, 'parent_thread_id'); + const known = nodeFor(conversation); + const turnId = nativeString(record, 'turn_id'); + const subagentKind = nativeString(record, 'subagent_kind'); + const value: AgentLineage = { + conversation, + depth: known?.depth ?? (parent === undefined ? 0 : (nodeFor(parent)?.depth ?? 0) + 1), + ...(turnId === undefined ? {} : { generation: turnId }), + ...(parent === undefined ? {} : { parent }), + resolution: 'native', + root, + ...(parent === undefined + ? {} + : { subagent: { id: conversation, ...(subagentKind === undefined ? {} : { type: subagentKind }) } }), + }; + return available(value, 'native'); + } + } + } + let call: OpenToolCall | undefined; + const claudeToolUseId = host === 'claude' ? nativeString(meta ?? {}, 'claudecode/toolUseId') : undefined; + if (claudeToolUseId !== undefined) { + call = state.openCalls.find((open) => open.toolCallId === claudeToolUseId); + } + if (call === undefined) { + // The most recent open pre-tool hook naming this tool: `MCP:` on + // Cursor, `mcp____` on Codex, `mcp__plugin_

___` on Claude. + for (let index = state.openCalls.length - 1; index >= 0; index -= 1) { + const candidate = state.openCalls[index]!; + if ( + candidate.toolName === `MCP:${toolName}` + || candidate.toolName.endsWith(`__${toolName}`) + || candidate.toolName === toolName + ) { + call = candidate; + break; + } + } + } + if (call === undefined) return unavailable('id-not-resolvable'); + const node = nodeFor(call.conversation); + if (node === undefined) return unavailable('id-not-resolvable'); + const resolution: AgentLineageResolution = claudeToolUseId !== undefined ? 'registry' : 'inferred'; + return available(lineageOf(node, undefined, resolution), 'derived'); + }, + + snapshot() { + return state; + }, + }; + return Object.freeze(registry); +}; diff --git a/packages/rsc-runtime/src/lineage/state.ts b/packages/rsc-runtime/src/lineage/state.ts new file mode 100644 index 000000000..8a2024a3c --- /dev/null +++ b/packages/rsc-runtime/src/lineage/state.ts @@ -0,0 +1,174 @@ +import { z } from 'zod'; + +import type { AgentStateLifetime } from '../state/contract.js'; +import { defineState } from '../state/index.js'; + +const id = z.string().min(1).max(512); +const timestamp = z.string().min(1).max(64); + +/** One conversation the runtime has seen start: the root, or a subagent below it. */ +export const LineageNodeSchema = z.object({ + /** Root is depth 0. */ + depth: z.number().int().nonnegative(), + /** Codex `turn_id` / Claude `prompt_id` / Cursor `generation_id` at start, when present. */ + generation: id.optional(), + /** The id the node is addressed by on this host (Claude/Codex `agent_id`, Cursor conversation id once bound). */ + id, + isParallelWorker: z.boolean().optional(), + parent: id.optional(), + root: id, + startedAt: timestamp, + stoppedAt: timestamp.optional(), + /** Cursor names the child by its spawning tool call before the child's conversation id is known. */ + subagentId: id.optional(), + toolCallId: id.optional(), + type: id.optional(), +}).strict(); + +/** A pre-tool hook whose post-tool hook has not fired: the correlation window for MCP calls and spawns. */ +export const OpenToolCallSchema = z.object({ + conversation: id, + openedAt: timestamp, + toolCallId: id, + toolName: id, +}).strict(); + +export const LineageStateSchema = z.object({ + /** Keyed by node id. */ + nodes: z.record(id, LineageNodeSchema), + openCalls: z.array(OpenToolCallSchema), + /** Cursor subagent ids whose child conversation has not been observed yet, oldest first. */ + pendingChildren: z.array(id), + /** + * Spawn tool calls (Claude `Agent`/`Task`, Codex `spawn_agent`) not yet + * claimed by a subagent start. Kept apart from `openCalls` because Codex + * closes the spawn call before `SubagentStart` fires. + */ + pendingSpawns: z.array(OpenToolCallSchema), +}).strict(); + +export type LineageNode = z.output; +export type OpenToolCall = z.output; +export type LineageState = z.output; + +export const lineageEventSchemas = { + /** A Cursor child conversation is now known for a pending subagent id: the node moves to its conversation id. */ + childBound: z.object({ conversation: id, subagentId: id }).strict(), + nodeStarted: LineageNodeSchema, + nodeStopped: z.object({ id, stoppedAt: timestamp }).strict(), + /** A subagent start consumed the spawn call that produced it. */ + spawnClaimed: z.object({ toolCallId: id }).strict(), + toolCallClosed: z.object({ conversation: id, toolCallId: id }).strict(), + toolCallOpened: OpenToolCallSchema.extend({ spawn: z.boolean().optional() }).strict(), +} as const; + +export type LineageEvents = typeof lineageEventSchemas; + +/** Stopped nodes retained after the tree is pruned; enough for a dump to explain a finished session. */ +export const LINEAGE_STOPPED_RETENTION = 256; +/** Pre-tool hooks whose post-tool hook never arrived are dropped past this count, oldest first. */ +export const LINEAGE_OPEN_CALL_RETENTION = 512; +/** Spawn calls no subagent start ever claimed are dropped past this count, oldest first. */ +export const LINEAGE_PENDING_SPAWN_RETENTION = 64; + +export const AGENT_LINEAGE_STATE_ID = '@agent-bundle/runtime/agent-lineage/v1'; + +const pruneStopped = (nodes: Record): Record => { + const stopped = Object.values(nodes) + .filter((node) => node.stoppedAt !== undefined) + .sort((left, right) => (left.stoppedAt ?? '').localeCompare(right.stoppedAt ?? '')); + if (stopped.length <= LINEAGE_STOPPED_RETENTION) return nodes; + const evicted = new Set(stopped.slice(0, stopped.length - LINEAGE_STOPPED_RETENTION).map((node) => node.id)); + return Object.fromEntries(Object.entries(nodes).filter(([key]) => !evicted.has(key))); +}; + +export const initialLineageState: LineageState = Object.freeze({ + nodes: {}, + openCalls: [], + pendingChildren: [], + pendingSpawns: [], +}); + +export const reduceLineage = ( + state: LineageState, + event: { readonly name: keyof LineageEvents; readonly payload: unknown }, +): LineageState => { + switch (event.name) { + case 'nodeStarted': { + const node = event.payload as LineageNode; + const nodes = pruneStopped({ ...state.nodes, [node.id]: node }); + return { + ...state, + nodes, + pendingChildren: node.subagentId !== undefined && node.subagentId === node.id + ? [...state.pendingChildren.filter((pending) => pending !== node.id), node.id] + : state.pendingChildren, + }; + } + case 'nodeStopped': { + const { id: nodeId, stoppedAt } = event.payload as { id: string; stoppedAt: string }; + const node = state.nodes[nodeId]; + if (node === undefined) return state; + return { + ...state, + nodes: { ...state.nodes, [nodeId]: { ...node, stoppedAt } }, + pendingChildren: state.pendingChildren.filter((pending) => pending !== nodeId), + }; + } + case 'childBound': { + const { conversation, subagentId } = event.payload as { conversation: string; subagentId: string }; + const pending = state.nodes[subagentId]; + if (pending === undefined) return state; + const { [subagentId]: _moved, ...rest } = state.nodes; + return { + ...state, + nodes: { ...rest, [conversation]: { ...pending, id: conversation } }, + pendingChildren: state.pendingChildren.filter((candidate) => candidate !== subagentId), + }; + } + case 'toolCallOpened': { + const { spawn, ...call } = event.payload as OpenToolCall & { readonly spawn?: boolean }; + const openCalls = [...state.openCalls.filter((open) => open.toolCallId !== call.toolCallId), call]; + const pendingSpawns = spawn === true + ? [...state.pendingSpawns.filter((open) => open.toolCallId !== call.toolCallId), call] + : state.pendingSpawns; + return { + ...state, + openCalls: openCalls.length > LINEAGE_OPEN_CALL_RETENTION + ? openCalls.slice(openCalls.length - LINEAGE_OPEN_CALL_RETENTION) + : openCalls, + pendingSpawns: pendingSpawns.length > LINEAGE_PENDING_SPAWN_RETENTION + ? pendingSpawns.slice(pendingSpawns.length - LINEAGE_PENDING_SPAWN_RETENTION) + : pendingSpawns, + }; + } + case 'toolCallClosed': { + const { toolCallId } = event.payload as { conversation: string; toolCallId: string }; + return { ...state, openCalls: state.openCalls.filter((open) => open.toolCallId !== toolCallId) }; + } + case 'spawnClaimed': { + const { toolCallId } = event.payload as { toolCallId: string }; + return { ...state, pendingSpawns: state.pendingSpawns.filter((open) => open.toolCallId !== toolCallId) }; + } + default: { + const unreachable: never = event.name; + throw new Error(`Unhandled lineage event ${String(unreachable)}`); + } + } +}; + +/** + * The framework-owned durable registry definition. One per plugin install, + * opened by the warm runtime beside the project's own state so a restart of + * the MCP process mid-session does not forget which subagents are alive. + */ +export const agentLineageStateDefinition = (lifetime: AgentStateLifetime = 'workspace-durable') => defineState({ + budgets: { maxStateBytes: 4 * 1_048_576 }, + events: lineageEventSchemas, + id: AGENT_LINEAGE_STATE_ID, + initial: initialLineageState, + lifetime, + reduce: (state, event) => reduceLineage(state, event), + schema: LineageStateSchema, + version: 1, +}); diff --git a/packages/rsc-runtime/src/notices/state.ts b/packages/rsc-runtime/src/notices/state.ts index 2f74b0269..59a7addc1 100644 --- a/packages/rsc-runtime/src/notices/state.ts +++ b/packages/rsc-runtime/src/notices/state.ts @@ -25,7 +25,16 @@ const observed = (value: T) => z.discriminatedUnion('state' value, }).strict(), z.object({ - reason: z.enum(['not-provided', 'unsupported-surface', 'host-omitted', 'unauthenticated']), + reason: z.enum([ + 'not-provided', + 'unsupported-surface', + 'host-omitted', + 'unauthenticated', + 'no-subagent-events', + 'id-not-resolvable', + 'cloud-agent-no-user-hooks', + 'no-shared-runtime', + ]), state: z.literal('unavailable'), }).strict(), ]); diff --git a/packages/rsc-runtime/src/plugin.ts b/packages/rsc-runtime/src/plugin.ts index 11aad0747..478505ae4 100644 --- a/packages/rsc-runtime/src/plugin.ts +++ b/packages/rsc-runtime/src/plugin.ts @@ -18,6 +18,9 @@ export type { AgentInvocation, AgentInvocationInput, AgentInvocationKind, + AgentLineage, + AgentLineageResolution, + AgentLineageSubagent, AgentNetworkAuthority, AgentProcessLifetime, AgentProgressReporter, diff --git a/packages/rsc-runtime/tests/lineage-registry.test.ts b/packages/rsc-runtime/tests/lineage-registry.test.ts new file mode 100644 index 000000000..8fdde7d21 --- /dev/null +++ b/packages/rsc-runtime/tests/lineage-registry.test.ts @@ -0,0 +1,204 @@ +import { readFileSync } from 'node:fs'; +import { resolve } from 'node:path'; + +import { describe, expect, it } from '@rstest/core'; + +import { unavailable } from '../src/agent-request.js'; +import { + agentLineageStateDefinition, + createAgentLineageRegistry, + lineageHostFromClient, + resolveNativeLineage, + type AgentLineageRegistry, + type LineageHost, +} from '../src/lineage/index.js'; +import { createMemoryStateDriver } from '../src/state/index.js'; + +interface FixtureRecord { + readonly event?: { + readonly canonical: { readonly event: string; readonly idempotencyKey: string; readonly observedAt: string }; + readonly native: Readonly>; + }; + readonly kind: 'event' | 'mcp' | 'cli'; + readonly observed?: { readonly client?: { readonly name: string }; readonly mcpReq?: { readonly _meta?: Record }; readonly tool?: string }; +} + +const fixture = (name: string): FixtureRecord[] => readFileSync( + resolve(import.meta.dirname, '../../../fixtures/host-lineage', name), + 'utf8', +).trim().split('\n').map((line) => JSON.parse(line) as FixtureRecord); + +/** Replays a redacted capture the way the warm runtime would: hooks feed, MCP calls resolve. */ +const replay = async ( + host: LineageHost, + records: readonly FixtureRecord[], + registry: AgentLineageRegistry, +) => { + const lineages: { readonly index: number; readonly kind: string; readonly lineage: Awaited>; readonly native?: Readonly> }[] = []; + for (const [position, record] of records.entries()) { + if (record.event !== undefined) { + const lineage = await registry.observe({ + event: record.event.canonical.event, + host, + idempotencyKey: record.event.canonical.idempotencyKey, + native: record.event.native, + observedAt: record.event.canonical.observedAt, + }); + lineages.push({ index: position + 1, kind: record.event.canonical.event, lineage, native: record.event.native }); + } else if (record.kind === 'mcp' && record.observed?.tool !== undefined) { + const lineage = registry.resolveToolCall({ + host: lineageHostFromClient(record.observed.client?.name) ?? host, + meta: record.observed.mcpReq?._meta, + toolName: record.observed.tool, + }); + lineages.push({ index: position + 1, kind: `mcp:${record.observed.tool}`, lineage }); + } + } + return lineages; +}; + +const value = (observed: Awaited>) => { + expect(observed.state).toBe('available'); + return observed.state === 'available' ? observed.value : undefined!; +}; + +describe('lineage registry replaying the 2026-09-03 host captures', () => { + it('Claude 2.1.257: subagent events resolve to their own agent under the root session, nested depth 2, parent inferred from the open Agent call', async () => { + const registry = createAgentLineageRegistry(); + const lineages = await replay('claude', fixture('claude-2.1.257.ndjson'), registry); + const root = 'a7f96472-e9d0-447a-826d-36da9b635fd6'; + + const sessionStart = value(lineages[0]!.lineage); + expect(sessionStart).toMatchObject({ conversation: root, depth: 0, resolution: 'native', root }); + expect(sessionStart.parent).toBeUndefined(); + + const subagentStart = lineages.find((entry) => entry.kind === 'agent/start')!; + expect(value(subagentStart.lineage)).toMatchObject({ + conversation: 'aca96ce761c9f0cea', + depth: 1, + parent: root, + resolution: 'registry', + root, + subagent: { id: 'aca96ce761c9f0cea', toolCallId: 'toolu_mock_5', type: 'general-purpose' }, + }); + + const nestedStart = lineages.filter((entry) => entry.kind === 'agent/start')[1]!; + expect(value(nestedStart.lineage)).toMatchObject({ + conversation: 'ac093bdad0566ffa7', + depth: 2, + parent: 'aca96ce761c9f0cea', + root, + subagent: { toolCallId: 'toolu_mock_10' }, + }); + + const nestedTool = lineages.find((entry) => entry.kind === 'tool/before' && entry.native?.['agent_id'] === 'ac093bdad0566ffa7')!; + expect(value(nestedTool.lineage)).toMatchObject({ conversation: 'ac093bdad0566ffa7', depth: 2, parent: 'aca96ce761c9f0cea', root }); + + // The MCP probe call carries claudecode/toolUseId, which names the open PreToolUse. + const probes = lineages.filter((entry) => entry.kind === 'mcp:probe'); + expect(probes.map((entry) => value(entry.lineage).depth)).toEqual([0, 1, 2]); + expect(value(probes[1]!.lineage)).toMatchObject({ conversation: 'aca96ce761c9f0cea', resolution: 'registry' }); + + const snapshot = registry.snapshot(); + expect(Object.values(snapshot.nodes).filter((node) => node.stoppedAt !== undefined).map((node) => node.id).sort()) + .toEqual(['ac093bdad0566ffa7', 'aca96ce761c9f0cea']); + }); + + it('Codex 0.147.0: MCP _meta resolves lineage natively including parent_thread_id; hooks agree', async () => { + const registry = createAgentLineageRegistry(); + const lineages = await replay('codex', fixture('codex-0.147.0.ndjson'), registry); + const root = '01a06660-110e-7290-8d1c-8ef1b2b68fc2'; + const subagent = '01a06660-8faf-7122-80af-24ba2da81ad7'; + const nested = '01a06661-100a-7ad3-a0f5-b0e6ffdb4b11'; + + const starts = lineages.filter((entry) => entry.kind === 'agent/start'); + expect(value(starts[0]!.lineage)).toMatchObject({ conversation: subagent, depth: 1, parent: root, root, generation: '01a06660-901a-77f1-a660-ac3c549409c0' }); + expect(value(starts[1]!.lineage)).toMatchObject({ conversation: nested, depth: 2, parent: subagent, root }); + + const probes = lineages.filter((entry) => entry.kind === 'mcp:probe'); + expect(probes.map((entry) => value(entry.lineage))).toMatchObject([ + { conversation: root, depth: 0, resolution: 'native', root }, + { conversation: subagent, depth: 1, parent: root, resolution: 'native', root, subagent: { id: subagent, type: 'thread_spawn' } }, + { conversation: nested, depth: 2, parent: subagent, resolution: 'native', root }, + ]); + // The generated dump tool carried no _meta in the capture; the open pre-tool hook still places it. + const dump = lineages.find((entry) => entry.kind === 'mcp:dump')!; + expect(value(dump.lineage)).toMatchObject({ conversation: root, depth: 0, resolution: 'inferred' }); + }); + + it('Cursor 3.18.25: subagentStart binds the next unseen conversation as the child; MCP calls resolve only through the MCP: pre-tool hook', async () => { + const registry = createAgentLineageRegistry(); + const lineages = await replay('cursor', fixture('cursor-3.18.25.ndjson'), registry); + const root = 'b60ae0c1-2f85-4c4d-b3e5-b512f9b06e4c'; + const child = 'bf617dfd-e03d-4d6b-adef-8f97e7df6b71'; + const nested = '46efda32-26ac-4ea1-9c05-b1bff02e5ea0'.slice(0, 8); + + expect(value(lineages[0]!.lineage)).toMatchObject({ conversation: root, depth: 0, root, generation: 'd4b2603b-ebfe-45ee-832d-b30d048defbb' }); + + const childTool = lineages.find((entry) => entry.native?.['conversation_id'] === child)!; + expect(value(childTool.lineage)).toMatchObject({ + conversation: child, + depth: 1, + parent: root, + resolution: 'inferred', + root, + subagent: { isParallelWorker: false, type: 'general-purpose' }, + }); + expect(value(childTool.lineage).subagent?.toolCallId).toMatch(/^call-2ec9530d/u); + + const nestedTool = lineages.find((entry) => String(entry.native?.['conversation_id'] ?? '').startsWith(nested))!; + expect(value(nestedTool.lineage)).toMatchObject({ depth: 2, parent: child, root }); + + // Three probes: from the first subagent, from its nested child, and from + // a third subagent the root spawned afterwards. + const probes = lineages.filter((entry) => entry.kind === 'mcp:probe'); + expect(probes.map((entry) => value(entry.lineage))).toMatchObject([ + { conversation: child, depth: 1, resolution: 'inferred' }, + { depth: 2, parent: child, resolution: 'inferred' }, + { depth: 1, parent: root, resolution: 'inferred' }, + ]); + expect(value(probes[2]!.lineage).conversation).not.toBe(child); + + const stops = lineages.filter((entry) => entry.kind === 'agent/stop'); + expect(stops.length).toBeGreaterThanOrEqual(2); + const stopped = Object.values(registry.snapshot().nodes).filter((node) => node.stoppedAt !== undefined); + expect(stopped.map((node) => node.depth).sort()).toEqual([1, 1, 2]); + }); + + it('persists through the durable state kernel and rehydrates a fresh registry', async () => { + const driver = createMemoryStateDriver({ lifetime: 'process' }); + const definition = agentLineageStateDefinition('process'); + const store = await driver.open(definition); + const first = createAgentLineageRegistry({ store }); + await replay('claude', fixture('claude-2.1.257.ndjson').slice(0, 12), first); + const second = createAgentLineageRegistry({ store }); + const lineage = await second.observe({ + event: 'tool/before', + host: 'claude', + idempotencyKey: 'rehydrated', + native: { agent_id: 'aca96ce761c9f0cea', hook_event_name: 'PreToolUse', session_id: 'a7f96472-e9d0-447a-826d-36da9b635fd6', tool_name: 'Bash', tool_use_id: 'later' }, + }); + expect(value(lineage)).toMatchObject({ conversation: 'aca96ce761c9f0cea', depth: 1, parent: 'a7f96472-e9d0-447a-826d-36da9b635fd6' }); + await store.close(); + await driver.close(); + }); + + it('answers honestly when the registry never saw the subagent start', async () => { + const registry = createAgentLineageRegistry(); + const lineage = await registry.observe({ + event: 'tool/before', + host: 'codex', + idempotencyKey: 'cold', + native: { agent_id: 'unknown-thread', session_id: 'root-thread', tool_name: 'Bash', tool_use_id: 'x' }, + }); + expect(lineage).toEqual(unavailable('id-not-resolvable')); + expect(registry.resolveToolCall({ host: 'cursor', toolName: 'dump' })).toEqual(unavailable('id-not-resolvable')); + expect(registry.resolveToolCall({ host: undefined, toolName: 'dump' })).toEqual(unavailable('id-not-resolvable')); + }); + + it('standalone hooks state only what the payload proves', () => { + expect(resolveNativeLineage('claude', { session_id: 'root' })).toMatchObject({ state: 'available', value: { conversation: 'root', depth: 0, root: 'root' } }); + expect(resolveNativeLineage('claude', { agent_id: 'child', session_id: 'root' })).toEqual(unavailable('no-shared-runtime')); + expect(resolveNativeLineage('cursor', { conversation_id: 'c' })).toEqual(unavailable('no-shared-runtime')); + }); +}); diff --git a/packages/workbench/src/lifecycles/lifecycles-model.ts b/packages/workbench/src/lifecycles/lifecycles-model.ts index 85cba9cd7..07a7a69c5 100644 --- a/packages/workbench/src/lifecycles/lifecycles-model.ts +++ b/packages/workbench/src/lifecycles/lifecycles-model.ts @@ -131,8 +131,30 @@ export const requestRowsFor = (replay: LifecycleReplay): readonly LifecycleDetai observedRow('Session', replay.requestContext.session, ({ sessionId }) => sessionId), observedRow('Actor', replay.requestContext.actor, ({ id }) => id), observedRow('Workspace', replay.requestContext.workspace, ({ root }) => root), + observedRow('Lineage', replay.requestContext.lineage, ({ conversation, depth, resolution }) => + `${conversation} · depth ${String(depth)} · ${resolution}`), ]); +export interface LifecycleLineageNode { + readonly id: string; + readonly role: 'root' | 'ancestor' | 'current'; +} + +/** + * The root-to-current chain a replayed request sits on. A single receipt can + * name at most its root, its parent, and itself; the warm runtime holds the + * rest of the tree. + */ +export const lineageChainFor = (replay: LifecycleReplay): readonly LifecycleLineageNode[] => { + const lineage = replay.requestContext.lineage; + if (lineage.state !== 'available') return Object.freeze([]); + const { conversation, parent, root } = lineage.value; + const chain: LifecycleLineageNode[] = [{ id: root, role: conversation === root ? 'current' : 'root' }]; + if (parent !== undefined && parent !== root && parent !== conversation) chain.push({ id: parent, role: 'ancestor' }); + if (conversation !== root) chain.push({ id: conversation, role: 'current' }); + return Object.freeze(chain.map((node) => Object.freeze(node))); +}; + export const resultDiagnosticsFor = (replay: LifecycleReplay): readonly LifecycleResultDiagnostic[] => Object.freeze([ ...(replay.projectionDiagnostic === undefined ? [] : [Object.freeze({ code: replay.projectionDiagnostic.code, diff --git a/packages/workbench/src/lifecycles/lifecycles-page.css b/packages/workbench/src/lifecycles/lifecycles-page.css index 41a35a78a..4accd3823 100644 --- a/packages/workbench/src/lifecycles/lifecycles-page.css +++ b/packages/workbench/src/lifecycles/lifecycles-page.css @@ -44,3 +44,8 @@ .lifecycle-detail-rows dt { font-size: 11px; font-weight: 750; margin-bottom: 5px; text-transform: uppercase; } .lifecycle-detail-rows dd { font: 12px/1.45 "SFMono-Regular", Consolas, monospace; overflow-wrap: anywhere; } .lifecycle-json { background: #101822; border: 1px solid #25364b; color: #edf3fb; font: 13px/1.55 "SFMono-Regular", Consolas, "Liberation Mono", monospace; margin: 0; max-height: 360px; overflow: auto; padding: 18px; white-space: pre-wrap; word-break: break-word; } +.lifecycle-lineage-tree, .lifecycle-lineage-tree ul { list-style: none; margin: 0; padding-left: 0; } +.lifecycle-lineage-tree ul { border-left: 2px solid #d9dee7; margin-left: 6px; margin-top: 6px; padding-left: 14px; } +.lifecycle-lineage-node code { font-size: 12px; } +.lifecycle-lineage-node span { color: #5b6473; font-size: 11px; margin-left: 8px; text-transform: uppercase; } +.lifecycle-lineage-node--current > code { font-weight: 750; } diff --git a/packages/workbench/src/lifecycles/lifecycles-page.tsx b/packages/workbench/src/lifecycles/lifecycles-page.tsx index ceb82b3a7..520b2cd59 100644 --- a/packages/workbench/src/lifecycles/lifecycles-page.tsx +++ b/packages/workbench/src/lifecycles/lifecycles-page.tsx @@ -16,9 +16,11 @@ import { type LifecycleReplayResult, } from './lifecycle-client.ts'; import { + lineageChainFor, lifecycleReplaySourceFor, lifecyclesViewFor, type LifecycleDetailRow, + type LifecycleLineageNode, type LifecyclesView, type LifecycleSourceMode, } from './lifecycles-model.ts'; @@ -63,6 +65,37 @@ const DetailRows = ({ label, rows }: Readonly<{ ; +const roleLabel = (role: LifecycleLineageNode['role']): string => { + switch (role) { + case 'root': + return 'root'; + case 'ancestor': + return 'parent'; + case 'current': + return 'this request'; + default: { + const unreachable: never = role; + return unreachable; + } + } +}; + +/** The root-to-current chain of the replayed request, one nested level per hop. */ +const LineageTree = ({ chain, reason }: Readonly<{ + readonly chain: readonly LifecycleLineageNode[]; + readonly reason: string | undefined; +}>) =>

+

Conversation lineage

+ {chain.length === 0 + ?

Lineage unavailable · {reason ?? 'not-provided'}

+ :
    + {chain.reduceRight((child, node) =>
  • + {node.id} {roleLabel(node.role)} + {child === undefined ? undefined :
      {child}
    } +
  • , undefined)} +
} +
; + const JsonBlock = ({ empty, label, value }: Readonly<{ readonly empty: string; readonly label: string; @@ -116,6 +149,10 @@ export const LifecycleReplayView = ({ view }: LifecycleReplayViewProps) => { + diff --git a/packages/workbench/src/request-provenance.ts b/packages/workbench/src/request-provenance.ts index 03f8426d4..674a44221 100644 --- a/packages/workbench/src/request-provenance.ts +++ b/packages/workbench/src/request-provenance.ts @@ -5,9 +5,36 @@ import type { RequestContextProvenance } from '../../agent-bundle/src/contracts/ const textSchema = z.string().min(1); const sourceSchema = z.enum(['native', 'receipt', 'derived']); const unavailableSchema = z.strictObject({ - reason: z.enum(['not-provided', 'unsupported-surface', 'host-omitted', 'unauthenticated']), + reason: z.enum([ + 'not-provided', + 'unsupported-surface', + 'host-omitted', + 'unauthenticated', + 'no-subagent-events', + 'id-not-resolvable', + 'cloud-agent-no-user-hooks', + 'no-shared-runtime', + ]), state: z.literal('unavailable'), }); +const availableLineageSchema = z.strictObject({ + source: sourceSchema, + state: z.literal('available'), + value: z.strictObject({ + conversation: textSchema, + depth: z.number().int().nonnegative(), + generation: textSchema.optional(), + parent: textSchema.optional(), + resolution: z.enum(['native', 'registry', 'inferred']), + root: textSchema, + subagent: z.strictObject({ + id: textSchema, + isParallelWorker: z.boolean().optional(), + toolCallId: textSchema.optional(), + type: textSchema.optional(), + }).optional(), + }), +}); const availableHostSchema = z.strictObject({ source: sourceSchema, state: z.literal('available'), @@ -38,6 +65,7 @@ export const requestContextProvenanceSchema: z.ZodType operationId: textSchema.optional(), surface: textSchema.optional(), }), + lineage: z.union([availableLineageSchema, unavailableSchema]), session: z.union([availableSessionSchema, unavailableSchema]), workspace: z.union([availableWorkspaceSchema, unavailableSchema]), }); diff --git a/packages/workbench/tests/fixtures/lifecycles-page-browser-fixture.tsx b/packages/workbench/tests/fixtures/lifecycles-page-browser-fixture.tsx index d111e1e9b..32e7feaea 100644 --- a/packages/workbench/tests/fixtures/lifecycles-page-browser-fixture.tsx +++ b/packages/workbench/tests/fixtures/lifecycles-page-browser-fixture.tsx @@ -103,6 +103,9 @@ const replayFor = (request: LifecycleReplayRequest): LifecycleReplay => { operationId: request.binding.routeId, surface: 'tool/after', }, + lineage: sessionId === undefined + ? { reason: 'no-shared-runtime', state: 'unavailable' } + : { source: 'receipt', state: 'available', value: { conversation: sessionId, depth: 0, resolution: 'native', root: sessionId } }, session: sessionId === undefined ? { reason: 'not-provided', state: 'unavailable' } : { source: 'receipt', state: 'available', value: { sessionId } }, diff --git a/packages/workbench/tests/lifecycle-client.test.ts b/packages/workbench/tests/lifecycle-client.test.ts index 1a3745634..b66d221cf 100644 --- a/packages/workbench/tests/lifecycle-client.test.ts +++ b/packages/workbench/tests/lifecycle-client.test.ts @@ -54,6 +54,7 @@ const replay = { operationId: 'event:tool/after', surface: 'tool/after', }, + lineage: { reason: 'not-provided' as const, state: 'unavailable' as const }, session: { reason: 'not-provided' as const, state: 'unavailable' as const }, workspace: { reason: 'not-provided' as const, state: 'unavailable' as const }, }, @@ -136,6 +137,7 @@ it('posts the exact replay binding, native receipt, and honest source', async () requestContext: { actor: { reason: 'not-provided', state: 'unavailable' }, host: { source: 'receipt', state: 'available', value: { name: 'claude' } }, + lineage: { reason: 'not-provided', state: 'unavailable' }, session: { reason: 'not-provided', state: 'unavailable' }, workspace: { reason: 'not-provided', state: 'unavailable' }, }, diff --git a/packages/workbench/tests/lifecycles-model.test.ts b/packages/workbench/tests/lifecycles-model.test.ts index b0040908d..23d4bfd8b 100644 --- a/packages/workbench/tests/lifecycles-model.test.ts +++ b/packages/workbench/tests/lifecycles-model.test.ts @@ -81,6 +81,7 @@ const replay: LifecycleReplay = { operationId: 'event:tool/after', surface: 'tool/after', }, + lineage: { source: 'receipt', state: 'available', value: { conversation: 'session-1', depth: 0, resolution: 'native', root: 'session-1' } }, session: { source: 'receipt', state: 'available', value: { sessionId: 'session-1' } }, workspace: { source: 'receipt', state: 'available', value: { root: '/workspace' } }, }, @@ -144,6 +145,7 @@ it('derives one correlated replay view with identity, context, and diagnostics', { label: 'Session', value: 'session-1 · receipt' }, { label: 'Actor', value: 'Unavailable · not-provided' }, { label: 'Workspace', value: '/workspace · receipt' }, + { label: 'Lineage', value: 'session-1 · depth 0 · native · receipt' }, ]); expect(view.resultDiagnostics).toEqual([ { code: 'projection.partial', message: 'Optional host field was omitted.', source: 'projection' }, diff --git a/packages/workbench/tests/lifecycles-page.test.ts b/packages/workbench/tests/lifecycles-page.test.ts index 01e71896c..69706bced 100644 --- a/packages/workbench/tests/lifecycles-page.test.ts +++ b/packages/workbench/tests/lifecycles-page.test.ts @@ -72,6 +72,7 @@ const replay: LifecycleReplay = { operationId: 'event:tool/after', surface: 'tool/after', }, + lineage: { reason: 'not-provided', state: 'unavailable' }, session: { reason: 'not-provided', state: 'unavailable' }, workspace: { source: 'receipt', state: 'available', value: { root: '/workspace' } }, }, diff --git a/pnpm-lock.yaml b/pnpm-lock.yaml index 98d867ee6..faad98031 100644 --- a/pnpm-lock.yaml +++ b/pnpm-lock.yaml @@ -115,6 +115,31 @@ importers: specifier: workspace:* version: link:../../packages/agent-bundle + examples/host-test: + dependencies: + '@agent-bundle/runtime': + specifier: workspace:* + version: link:../../packages/rsc-runtime + '@modelcontextprotocol/server': + specifier: 2.0.0 + version: 2.0.0 + react: + specifier: 19.2.8 + version: 19.2.8 + zod: + specifier: 4.5.4 + version: 4.5.4 + devDependencies: + '@rstest/core': + specifier: 0.11.10 + version: 0.11.10 + '@types/react': + specifier: 19.2.18 + version: 19.2.18 + agent-bundle: + specifier: workspace:* + version: link:../../packages/agent-bundle + examples/mcp-app: devDependencies: '@modelcontextprotocol/ext-apps': From 1f829136bb456c6af169e76207e888f81e3cbfc3 Mon Sep 17 00:00:00 2001 From: ScriptedAlchemy Date: Thu, 3 Sep 2026 09:36:38 +0000 Subject: [PATCH 02/20] fix(events): accept any present Claude PostToolUse tool_response (MCP tools deliver a string); probe dump shows lineage; scripted-model Claude capture Live re-capture through the reinstalled probe showed Claude Code 2.1.257 delivers an MCP tool's PostToolUse tool_response as a plain string, so the validator now requires presence only (as it already did for Codex). The Claude fixture is regenerated from that complete capture, the probe's dump renders a lineage column, probe:capture claude --scripted-model runs the real host against a checked-in scripted Messages API, and the Lifecycles e2e asserts the depth-0 lineage row and chain. --- .changeset/request-lineage.md | 2 +- docs/audits/2026-09-03-host-lineage-matrix.md | 12 +- .../artifact/agent-bundle.hooks.json | 1 + .../artifact/agent-bundle.manifest.json | 1 + .../claude/.claude-plugin/marketplace.json | 1 + .../claude/.claude-plugin/plugin.json | 1 + .../artifact/claude/INSTALL.md | 18 + .../assets/release/release-manifest.json | 21 + .../claude/assets/release/risk-register.json | 16 + .../artifact/claude/hooks/hooks.json | 1 + .../session-start-session-start-7ab7e8a5.mjs | 253 + .../claude/scripts/verify-release.mjs | 54 + .../codex/.agents/plugins/marketplace.json | 1 + .../artifact/codex/.codex-plugin/plugin.json | 1 + .../artifact/codex/INSTALL.md | 16 + .../assets/release/release-manifest.json | 21 + .../codex/assets/release/risk-register.json | 16 + .../artifact/codex/hooks/hooks.json | 1 + .../session-start-session-start-7ab7e8a5.mjs | 258 + .../artifact/codex/scripts/verify-release.mjs | 54 + .../artifact/portable/INSTALL.md | 19 + .../assets/release/release-manifest.json | 21 + .../assets/release/risk-register.json | 16 + .../artifact/portable/install.mjs | 80 + .../artifact/portable/plugin.json | 1 + .../artifact/portable/scripts/detect-risk.mjs | 35 + .../portable/scripts/verify-release.mjs | 54 + examples/host-test/probe-note.txt | 1 + examples/host-test/scripts/mock-anthropic.mjs | 159 + examples/host-test/scripts/probe.mjs | 42 +- examples/host-test/src/dump.ts | 16 +- .../mcp-app/artifact/agent-bundle.hooks.json | 1 + .../artifact/agent-bundle.manifest.json | 1 + .../claude/.claude-plugin/marketplace.json | 1 + .../claude/.claude-plugin/plugin.json | 1 + examples/mcp-app/artifact/claude/.mcp.json | 1 + examples/mcp-app/artifact/claude/INSTALL.md | 18 + .../assets/evals/fixtures/status/result.json | 9 + .../mcp-app/artifact/claude/hooks/hooks.json | 1 + .../session-start-session-start-7ab7e8a5.mjs | 253 + .../claude/mcp/mcp-status-073c1634.mjs | 30761 +++++++++++++++ .../claude/scripts/check-service-fixture.mjs | 60 + .../claude/skills/service-readiness/SKILL.md | 33 + .../assets/readiness-report.md | 22 + .../references/status-policy.md | 22 + .../codex/.agents/plugins/marketplace.json | 1 + .../artifact/codex/.codex-plugin/plugin.json | 1 + examples/mcp-app/artifact/codex/.mcp.json | 1 + examples/mcp-app/artifact/codex/INSTALL.md | 16 + .../assets/evals/fixtures/status/result.json | 9 + .../mcp-app/artifact/codex/hooks/hooks.json | 1 + .../session-start-session-start-7ab7e8a5.mjs | 258 + .../codex/mcp/mcp-status-073c1634.mjs | 30761 +++++++++++++++ .../codex/scripts/check-service-fixture.mjs | 60 + .../codex/skills/service-readiness/SKILL.md | 33 + .../assets/readiness-report.md | 22 + .../references/status-policy.md | 22 + examples/mcp-app/artifact/portable/INSTALL.md | 19 + .../assets/evals/fixtures/status/result.json | 9 + .../mcp-app/artifact/portable/install.mjs | 80 + .../artifact/portable/mcp-apps/status.html | 154 + examples/mcp-app/artifact/portable/mcp.json | 1 + .../portable/mcp/mcp-status-073c1634.mjs | 30768 ++++++++++++++++ .../mcp-app/artifact/portable/plugin.json | 1 + .../scripts/check-service-fixture.mjs | 60 + .../skills/service-readiness/SKILL.md | 33 + .../assets/readiness-report.md | 22 + .../references/status-policy.md | 22 + .../artifact/agent-bundle.hooks.json | 1 + .../artifact/agent-bundle.manifest.json | 1 + .../claude/.claude-plugin/marketplace.json | 1 + .../claude/.claude-plugin/plugin.json | 1 + .../skills-starter/artifact/claude/INSTALL.md | 18 + .../claude/skills/dependency-upgrade/SKILL.md | 33 + .../dependency-upgrade/assets/upgrade-plan.md | 21 + .../references/compatibility-checklist.md | 9 + .../claude/skills/incident-triage/SKILL.md | 34 + .../incident-triage/assets/incident-update.md | 9 + .../references/triage-runbook.md | 9 + .../claude/skills/release-review/SKILL.md | 34 + .../release-review/assets/report-template.md | 22 + .../release-review/references/checklist.md | 8 + .../references/release-policy.md | 22 + .../codex/.agents/plugins/marketplace.json | 1 + .../artifact/codex/.codex-plugin/plugin.json | 1 + .../skills-starter/artifact/codex/INSTALL.md | 16 + .../codex/skills/dependency-upgrade/SKILL.md | 33 + .../dependency-upgrade/assets/upgrade-plan.md | 21 + .../references/compatibility-checklist.md | 9 + .../codex/skills/incident-triage/SKILL.md | 34 + .../incident-triage/assets/incident-update.md | 9 + .../references/triage-runbook.md | 9 + .../codex/skills/release-review/SKILL.md | 34 + .../release-review/assets/report-template.md | 22 + .../release-review/references/checklist.md | 8 + .../references/release-policy.md | 22 + .../artifact/portable/INSTALL.md | 19 + .../artifact/portable/install.mjs | 80 + .../artifact/portable/plugin.json | 1 + .../skills/dependency-upgrade/SKILL.md | 33 + .../dependency-upgrade/assets/upgrade-plan.md | 21 + .../references/compatibility-checklist.md | 9 + .../portable/skills/incident-triage/SKILL.md | 34 + .../incident-triage/assets/incident-update.md | 9 + .../references/triage-runbook.md | 9 + .../portable/skills/release-review/SKILL.md | 34 + .../release-review/assets/report-template.md | 22 + .../release-review/references/checklist.md | 8 + .../references/release-policy.md | 22 + fixtures/host-lineage/claude-2.1.257.ndjson | 69 +- .../src/adapters/hook-contract.ts | 4 +- .../agent-bundle/src/events/projection.ts | 16 +- .../agent-bundle/tests/event-project.test.ts | 11 +- packages/agent-bundle/tests/hooks.test.ts | 3 +- .../tests/lifecycle-replay-routes.test.ts | 3 +- .../tests/lifecycle-replay-service.test.ts | 3 +- .../tests/lineage-registry.test.ts | 41 +- .../workbench/tests/lifecycles.e2e.test.ts | 7 + 118 files changed, 95547 insertions(+), 84 deletions(-) create mode 100644 examples/hooks-and-scripts/artifact/agent-bundle.hooks.json create mode 100644 examples/hooks-and-scripts/artifact/agent-bundle.manifest.json create mode 100644 examples/hooks-and-scripts/artifact/claude/.claude-plugin/marketplace.json create mode 100644 examples/hooks-and-scripts/artifact/claude/.claude-plugin/plugin.json create mode 100644 examples/hooks-and-scripts/artifact/claude/INSTALL.md create mode 100644 examples/hooks-and-scripts/artifact/claude/assets/release/release-manifest.json create mode 100644 examples/hooks-and-scripts/artifact/claude/assets/release/risk-register.json create mode 100644 examples/hooks-and-scripts/artifact/claude/hooks/hooks.json create mode 100644 examples/hooks-and-scripts/artifact/claude/hooks/session-start-session-start-7ab7e8a5.mjs create mode 100644 examples/hooks-and-scripts/artifact/claude/scripts/verify-release.mjs create mode 100644 examples/hooks-and-scripts/artifact/codex/.agents/plugins/marketplace.json create mode 100644 examples/hooks-and-scripts/artifact/codex/.codex-plugin/plugin.json create mode 100644 examples/hooks-and-scripts/artifact/codex/INSTALL.md create mode 100644 examples/hooks-and-scripts/artifact/codex/assets/release/release-manifest.json create mode 100644 examples/hooks-and-scripts/artifact/codex/assets/release/risk-register.json create mode 100644 examples/hooks-and-scripts/artifact/codex/hooks/hooks.json create mode 100644 examples/hooks-and-scripts/artifact/codex/hooks/session-start-session-start-7ab7e8a5.mjs create mode 100644 examples/hooks-and-scripts/artifact/codex/scripts/verify-release.mjs create mode 100644 examples/hooks-and-scripts/artifact/portable/INSTALL.md create mode 100644 examples/hooks-and-scripts/artifact/portable/assets/release/release-manifest.json create mode 100644 examples/hooks-and-scripts/artifact/portable/assets/release/risk-register.json create mode 100644 examples/hooks-and-scripts/artifact/portable/install.mjs create mode 100644 examples/hooks-and-scripts/artifact/portable/plugin.json create mode 100644 examples/hooks-and-scripts/artifact/portable/scripts/detect-risk.mjs create mode 100644 examples/hooks-and-scripts/artifact/portable/scripts/verify-release.mjs create mode 100644 examples/host-test/probe-note.txt create mode 100644 examples/host-test/scripts/mock-anthropic.mjs create mode 100644 examples/mcp-app/artifact/agent-bundle.hooks.json create mode 100644 examples/mcp-app/artifact/agent-bundle.manifest.json create mode 100644 examples/mcp-app/artifact/claude/.claude-plugin/marketplace.json create mode 100644 examples/mcp-app/artifact/claude/.claude-plugin/plugin.json create mode 100644 examples/mcp-app/artifact/claude/.mcp.json create mode 100644 examples/mcp-app/artifact/claude/INSTALL.md create mode 100644 examples/mcp-app/artifact/claude/assets/evals/fixtures/status/result.json create mode 100644 examples/mcp-app/artifact/claude/hooks/hooks.json create mode 100644 examples/mcp-app/artifact/claude/hooks/session-start-session-start-7ab7e8a5.mjs create mode 100644 examples/mcp-app/artifact/claude/mcp/mcp-status-073c1634.mjs create mode 100644 examples/mcp-app/artifact/claude/scripts/check-service-fixture.mjs create mode 100644 examples/mcp-app/artifact/claude/skills/service-readiness/SKILL.md create mode 100644 examples/mcp-app/artifact/claude/skills/service-readiness/assets/readiness-report.md create mode 100644 examples/mcp-app/artifact/claude/skills/service-readiness/references/status-policy.md create mode 100644 examples/mcp-app/artifact/codex/.agents/plugins/marketplace.json create mode 100644 examples/mcp-app/artifact/codex/.codex-plugin/plugin.json create mode 100644 examples/mcp-app/artifact/codex/.mcp.json create mode 100644 examples/mcp-app/artifact/codex/INSTALL.md create mode 100644 examples/mcp-app/artifact/codex/assets/evals/fixtures/status/result.json create mode 100644 examples/mcp-app/artifact/codex/hooks/hooks.json create mode 100644 examples/mcp-app/artifact/codex/hooks/session-start-session-start-7ab7e8a5.mjs create mode 100644 examples/mcp-app/artifact/codex/mcp/mcp-status-073c1634.mjs create mode 100644 examples/mcp-app/artifact/codex/scripts/check-service-fixture.mjs create mode 100644 examples/mcp-app/artifact/codex/skills/service-readiness/SKILL.md create mode 100644 examples/mcp-app/artifact/codex/skills/service-readiness/assets/readiness-report.md create mode 100644 examples/mcp-app/artifact/codex/skills/service-readiness/references/status-policy.md create mode 100644 examples/mcp-app/artifact/portable/INSTALL.md create mode 100644 examples/mcp-app/artifact/portable/assets/evals/fixtures/status/result.json create mode 100644 examples/mcp-app/artifact/portable/install.mjs create mode 100644 examples/mcp-app/artifact/portable/mcp-apps/status.html create mode 100644 examples/mcp-app/artifact/portable/mcp.json create mode 100644 examples/mcp-app/artifact/portable/mcp/mcp-status-073c1634.mjs create mode 100644 examples/mcp-app/artifact/portable/plugin.json create mode 100644 examples/mcp-app/artifact/portable/scripts/check-service-fixture.mjs create mode 100644 examples/mcp-app/artifact/portable/skills/service-readiness/SKILL.md create mode 100644 examples/mcp-app/artifact/portable/skills/service-readiness/assets/readiness-report.md create mode 100644 examples/mcp-app/artifact/portable/skills/service-readiness/references/status-policy.md create mode 100644 examples/skills-starter/artifact/agent-bundle.hooks.json create mode 100644 examples/skills-starter/artifact/agent-bundle.manifest.json create mode 100644 examples/skills-starter/artifact/claude/.claude-plugin/marketplace.json create mode 100644 examples/skills-starter/artifact/claude/.claude-plugin/plugin.json create mode 100644 examples/skills-starter/artifact/claude/INSTALL.md create mode 100644 examples/skills-starter/artifact/claude/skills/dependency-upgrade/SKILL.md create mode 100644 examples/skills-starter/artifact/claude/skills/dependency-upgrade/assets/upgrade-plan.md create mode 100644 examples/skills-starter/artifact/claude/skills/dependency-upgrade/references/compatibility-checklist.md create mode 100644 examples/skills-starter/artifact/claude/skills/incident-triage/SKILL.md create mode 100644 examples/skills-starter/artifact/claude/skills/incident-triage/assets/incident-update.md create mode 100644 examples/skills-starter/artifact/claude/skills/incident-triage/references/triage-runbook.md create mode 100644 examples/skills-starter/artifact/claude/skills/release-review/SKILL.md create mode 100644 examples/skills-starter/artifact/claude/skills/release-review/assets/report-template.md create mode 100644 examples/skills-starter/artifact/claude/skills/release-review/references/checklist.md create mode 100644 examples/skills-starter/artifact/claude/skills/release-review/references/release-policy.md create mode 100644 examples/skills-starter/artifact/codex/.agents/plugins/marketplace.json create mode 100644 examples/skills-starter/artifact/codex/.codex-plugin/plugin.json create mode 100644 examples/skills-starter/artifact/codex/INSTALL.md create mode 100644 examples/skills-starter/artifact/codex/skills/dependency-upgrade/SKILL.md create mode 100644 examples/skills-starter/artifact/codex/skills/dependency-upgrade/assets/upgrade-plan.md create mode 100644 examples/skills-starter/artifact/codex/skills/dependency-upgrade/references/compatibility-checklist.md create mode 100644 examples/skills-starter/artifact/codex/skills/incident-triage/SKILL.md create mode 100644 examples/skills-starter/artifact/codex/skills/incident-triage/assets/incident-update.md create mode 100644 examples/skills-starter/artifact/codex/skills/incident-triage/references/triage-runbook.md create mode 100644 examples/skills-starter/artifact/codex/skills/release-review/SKILL.md create mode 100644 examples/skills-starter/artifact/codex/skills/release-review/assets/report-template.md create mode 100644 examples/skills-starter/artifact/codex/skills/release-review/references/checklist.md create mode 100644 examples/skills-starter/artifact/codex/skills/release-review/references/release-policy.md create mode 100644 examples/skills-starter/artifact/portable/INSTALL.md create mode 100644 examples/skills-starter/artifact/portable/install.mjs create mode 100644 examples/skills-starter/artifact/portable/plugin.json create mode 100644 examples/skills-starter/artifact/portable/skills/dependency-upgrade/SKILL.md create mode 100644 examples/skills-starter/artifact/portable/skills/dependency-upgrade/assets/upgrade-plan.md create mode 100644 examples/skills-starter/artifact/portable/skills/dependency-upgrade/references/compatibility-checklist.md create mode 100644 examples/skills-starter/artifact/portable/skills/incident-triage/SKILL.md create mode 100644 examples/skills-starter/artifact/portable/skills/incident-triage/assets/incident-update.md create mode 100644 examples/skills-starter/artifact/portable/skills/incident-triage/references/triage-runbook.md create mode 100644 examples/skills-starter/artifact/portable/skills/release-review/SKILL.md create mode 100644 examples/skills-starter/artifact/portable/skills/release-review/assets/report-template.md create mode 100644 examples/skills-starter/artifact/portable/skills/release-review/references/checklist.md create mode 100644 examples/skills-starter/artifact/portable/skills/release-review/references/release-policy.md diff --git a/.changeset/request-lineage.md b/.changeset/request-lineage.md index 2d7f986c4..da5045596 100644 --- a/.changeset/request-lineage.md +++ b/.changeset/request-lineage.md @@ -3,4 +3,4 @@ 'agent-bundle': patch --- -Add `request.lineage` to `AgentRequestContext` on every surface (event routes, generated MCP tools, routed CLI, rendered scripts): `{ conversation, root, parent?, depth, generation?, subagent?, resolution }` resolved by the new runtime-held agent lineage registry (`@agent-bundle/runtime/lineage`, journaled through the state kernel beside project state) that the `agent/start`/`agent/stop` and `tool/before`/`tool/after` families feed, with hook→MCP correlation from Claude `claudecode/toolUseId`, Codex `x-codex-turn-metadata`, and Cursor's open `MCP:` pre-tool hook. Unavailable lineage carries a typed reason (`no-subagent-events`, `id-not-resolvable`, `cloud-agent-no-user-hooks`, `no-shared-runtime`, `unsupported-surface`, `not-provided`); every pinned capability table gains dated `lineage` rows, the Workbench Lifecycles view shows the lineage axis and chain, `openInMemoryMcpServer` accepts `lineage`/`lineageHost`, and Claude `PostToolUse` hooks now accept the content-block array `tool_response` that MCP tools deliver instead of failing the route. +Add `request.lineage` to `AgentRequestContext` on every surface (event routes, generated MCP tools, routed CLI, rendered scripts): `{ conversation, root, parent?, depth, generation?, subagent?, resolution }` resolved by the new runtime-held agent lineage registry (`@agent-bundle/runtime/lineage`, journaled through the state kernel beside project state) that the `agent/start`/`agent/stop` and `tool/before`/`tool/after` families feed, with hook→MCP correlation from Claude `claudecode/toolUseId`, Codex `x-codex-turn-metadata`, and Cursor's open `MCP:` pre-tool hook. Unavailable lineage carries a typed reason (`no-subagent-events`, `id-not-resolvable`, `cloud-agent-no-user-hooks`, `no-shared-runtime`, `unsupported-surface`, `not-provided`); every pinned capability table gains dated `lineage` rows, the Workbench Lifecycles view shows the lineage axis and chain, `openInMemoryMcpServer` accepts `lineage`/`lineageHost`, and Claude `PostToolUse` hooks now accept the plain-string `tool_response` that MCP tools deliver (any present JSON value, as on Codex) instead of failing the route. diff --git a/docs/audits/2026-09-03-host-lineage-matrix.md b/docs/audits/2026-09-03-host-lineage-matrix.md index b358e794c..09e301ca7 100644 --- a/docs/audits/2026-09-03-host-lineage-matrix.md +++ b/docs/audits/2026-09-03-host-lineage-matrix.md @@ -125,10 +125,12 @@ fires (fixture rows Claude 5→6, Codex 9→10→11, Cursor 81→82→83). | Codex | `mcp__host_test__dump` | `exec-` | `{ progressToken, plugin_id, threadId, "x-codex-turn-metadata": { session_id, thread_id, turn_id, parent_thread_id?, forked_from_thread_id?, thread_source: "user"|"subagent", subagent_kind?, sandbox, workspaces{…git commit…}, model, reasoning_effort, turn_started_at_unix_ms } }` | `codex-mcp-client` 0.147.0 | none | **Yes, fully** — lineage (thread, parent, root) is in `_meta` itself | | Cursor | `MCP:dump` | plain uuid | `{ progressToken }` only | `cursor-vscode` 1.0.0 | none | **No** — only the pre-tool hook (tool name + ordering) can attach a conversation | -Claude's `PostToolUse` for MCP tools delivers `tool_response` as an **array of -content blocks**, not an object; the framework's pinned validator rejected -every such event (`native tool_response must be an object`, confirmed in the -host's `--debug hooks` log). Fixed in this change set. +Claude's `PostToolUse` for MCP tools delivers `tool_response` as a **plain +string** (the tool's text content, here the JSON text of the result), not an +object; the framework's pinned validator rejected every such event (`native +tool_response must be an object`, confirmed in the host's `--debug hooks` log +and by a raw user-level hook that captured the payload verbatim). Fixed in this +change set: presence is now the only host-independent rule, matching Codex. ## 4. Environment variable names seen by plugin processes (names only) @@ -175,7 +177,7 @@ deliver no user identity to hooks or MCP servers. `no-shared-runtime`, `unsupported-surface`). - Hook→MCP correlation: Codex from `_meta`, Claude from `claudecode/toolUseId`, Cursor from the open `MCP:` pre-tool hook. -- Claude `PostToolUse` array `tool_response` accepted. +- Claude `PostToolUse` string `tool_response` (MCP tools) accepted. ## 7. Gaps and host-blocked items diff --git a/examples/hooks-and-scripts/artifact/agent-bundle.hooks.json b/examples/hooks-and-scripts/artifact/agent-bundle.hooks.json new file mode 100644 index 000000000..c41cd4504 --- /dev/null +++ b/examples/hooks-and-scripts/artifact/agent-bundle.hooks.json @@ -0,0 +1 @@ +{"hooks":[{"event":"sessionStart","id":"hook:session-start:session-start:7ab7e8a5","name":"session-start-session-start-7ab7e8a5","path":"claude/hooks/session-start-session-start-7ab7e8a5.mjs","target":"claude"},{"event":"sessionStart","id":"hook:session-start:session-start:7ab7e8a5","name":"session-start-session-start-7ab7e8a5","path":"codex/hooks/session-start-session-start-7ab7e8a5.mjs","target":"codex"}]} diff --git a/examples/hooks-and-scripts/artifact/agent-bundle.manifest.json b/examples/hooks-and-scripts/artifact/agent-bundle.manifest.json new file mode 100644 index 000000000..9fba35420 --- /dev/null +++ b/examples/hooks-and-scripts/artifact/agent-bundle.manifest.json @@ -0,0 +1 @@ +{"agentSkills":{"schemaSha256":"6d06b61e423317421de2295ea1fd0c7b4491bfa36c5b7705c28616dfe76d4047","sourceRevision":"69ef37e9424c0a7ea9dd2293b559e43ec8176379","specification":"https://raw.githubusercontent.com/agentskills/agentskills/69ef37e9424c0a7ea9dd2293b559e43ec8176379/docs/specification.mdx"},"files":[{"bytes":412,"kind":"generated","path":"agent-bundle.hooks.json","sha256":"c085b5d4bc728917cba2d53546cdd9f6b065f9e84a846d31d3e4ccb254f5819a","sourceInputs":["agent-bundle.config.ts"]},{"bytes":287,"kind":"generated","path":"claude/.claude-plugin/marketplace.json","sha256":"f4dff087eb3c84f2b6e4ffeb632a3df21a631b70ad0328811dbaeabd8e29c043","sourceInputs":["agent-bundle.config.ts"]},{"bytes":182,"kind":"generated","path":"claude/.claude-plugin/plugin.json","sha256":"2fa2d83fbdca7ab515bbd11c1cc2dffafedeabc2dc9cd647fb9646c057b31d54","sourceInputs":["agent-bundle.config.ts"]},{"bytes":412,"kind":"copy","path":"claude/assets/release/release-manifest.json","sha256":"5f40663b01a3b359b3df7d5d7f7fbd0b1f703adb4a3b6a55e57dc2bf6d9bfc77","sourceInputs":["release/release-manifest.json"]},{"bytes":370,"kind":"copy","path":"claude/assets/release/risk-register.json","sha256":"aac96ec9112addc32a97c0f35fbda32d8f8104a321f1c2f4d97e10cbed25f0fb","sourceInputs":["release/risk-register.json"]},{"bytes":150,"kind":"generated","path":"claude/hooks/hooks.json","sha256":"8855c477158d687920a5d1da416ee8c980cc305f3adde65488dcef55e8b8da06","sourceInputs":["agent-bundle.config.ts"]},{"bytes":12034,"kind":"bundle","path":"claude/hooks/session-start-session-start-7ab7e8a5.mjs","sha256":"a751afea6c4c452124dc4fbb81e937182939b29a87e686525caa601111befa5b","sourceInputs":["agent-bundle.config.ts","src/hooks/session-start.ts"]},{"bytes":442,"kind":"generated","path":"claude/INSTALL.md","sha256":"0ca977cebb541b89cb7ef9cc47ed66dde2617f8c2beb5a697740ebfc2e4e0a14","sourceInputs":["agent-bundle.config.ts"]},{"bytes":2086,"kind":"bundle","path":"claude/scripts/verify-release.mjs","sha256":"834e07a4cf2669358b4dea1af6cfe57976d085c039f5af1651993d59c64ed15e","sourceInputs":["src/scripts/verify-release.ts"]},{"bytes":264,"kind":"generated","path":"codex/.agents/plugins/marketplace.json","sha256":"eef1222beca7c354075e8da61d0fc50d68180b87da4f884890886868b6b40b89","sourceInputs":["agent-bundle.config.ts"]},{"bytes":534,"kind":"generated","path":"codex/.codex-plugin/plugin.json","sha256":"e20e3a461fe89d8148d1aa53e729605316a6770215f86ec01c08ce7eaa672708","sourceInputs":["agent-bundle.config.ts"]},{"bytes":412,"kind":"copy","path":"codex/assets/release/release-manifest.json","sha256":"5f40663b01a3b359b3df7d5d7f7fbd0b1f703adb4a3b6a55e57dc2bf6d9bfc77","sourceInputs":["release/release-manifest.json"]},{"bytes":370,"kind":"copy","path":"codex/assets/release/risk-register.json","sha256":"aac96ec9112addc32a97c0f35fbda32d8f8104a321f1c2f4d97e10cbed25f0fb","sourceInputs":["release/risk-register.json"]},{"bytes":143,"kind":"generated","path":"codex/hooks/hooks.json","sha256":"ad0e296b15c799f52459488b17f46f7cc3a34e1abf4b9466a178d17a7fdaa605","sourceInputs":["agent-bundle.config.ts"]},{"bytes":12177,"kind":"bundle","path":"codex/hooks/session-start-session-start-7ab7e8a5.mjs","sha256":"99ae56a7e8c1d54a8df94cec252577eb1aef4d16b27e75dbc8ceaf63b6fb318e","sourceInputs":["agent-bundle.config.ts","src/hooks/session-start.ts"]},{"bytes":330,"kind":"generated","path":"codex/INSTALL.md","sha256":"b36d9e71a3d9e39947164524196269ba4084a28f6595558548d5f2639fb171ef","sourceInputs":["agent-bundle.config.ts"]},{"bytes":2086,"kind":"bundle","path":"codex/scripts/verify-release.mjs","sha256":"834e07a4cf2669358b4dea1af6cfe57976d085c039f5af1651993d59c64ed15e","sourceInputs":["src/scripts/verify-release.ts"]},{"bytes":412,"kind":"copy","path":"portable/assets/release/release-manifest.json","sha256":"5f40663b01a3b359b3df7d5d7f7fbd0b1f703adb4a3b6a55e57dc2bf6d9bfc77","sourceInputs":["release/release-manifest.json"]},{"bytes":370,"kind":"copy","path":"portable/assets/release/risk-register.json","sha256":"aac96ec9112addc32a97c0f35fbda32d8f8104a321f1c2f4d97e10cbed25f0fb","sourceInputs":["release/risk-register.json"]},{"bytes":667,"kind":"generated","path":"portable/INSTALL.md","sha256":"9fca655cfae6999fdac7a6562b003dff2353231f936b65791c7859cf7437b5b1","sourceInputs":["agent-bundle.config.ts"]},{"bytes":3311,"kind":"generated","path":"portable/install.mjs","sha256":"3d5bab7f4f63582ed41027cbdd58122cf8aa04436647400639876c264751447f","sourceInputs":["agent-bundle.config.ts"]},{"bytes":186,"kind":"generated","path":"portable/plugin.json","sha256":"7960fb9bcfd13c8bfbf113ac8b742d45f341df6fedf1c91525c421b10f63ad1e","sourceInputs":["agent-bundle.config.ts"]},{"bytes":1443,"kind":"bundle","path":"portable/scripts/detect-risk.mjs","sha256":"d306df52faf5ace3f722a61a529a282a416a862f95fc7af9015b56603a880a77","sourceInputs":["agent-bundle.config.ts","src/scripts/detect-risk.ts"]},{"bytes":2086,"kind":"bundle","path":"portable/scripts/verify-release.mjs","sha256":"834e07a4cf2669358b4dea1af6cfe57976d085c039f5af1651993d59c64ed15e","sourceInputs":["src/scripts/verify-release.ts"]}],"producer":{"name":"agent-bundle","version":"0.1.0"},"project":{"configDigest":"a6b714ebca4e4c048fe437312e4789b0841dccfd8a621cfe513e6a0ae3fc7a4c","configPath":"agent-bundle.config.ts","modelDigest":"c9c2a9a138a4736257fd35f0108d5b702cfd532efee090e77c33bb6b91028b5e","packageName":"@agent-bundle-example/hooks-and-scripts","revision":"32bbeed169b6a21841fbc15abc9fafcdc8bd2bcbeadbd153be1eafe28fe7c0f4","sourceInputs":[{"executable":false,"path":"agent-bundle.config.ts","sha256":"a6b714ebca4e4c048fe437312e4789b0841dccfd8a621cfe513e6a0ae3fc7a4c"},{"executable":false,"path":"package.json","sha256":"974301ada8ea65ced69eb0c43faf5e3206e343b6d76c5f824fbc425820bc1acd"},{"executable":false,"path":"README.md","sha256":"a22188781290ce67939e8dd339bc75b6dd520ded36a02de0b8a161d3a776afa1"},{"executable":false,"path":"release/release-manifest.json","sha256":"5f40663b01a3b359b3df7d5d7f7fbd0b1f703adb4a3b6a55e57dc2bf6d9bfc77"},{"executable":false,"path":"release/risk-register.json","sha256":"aac96ec9112addc32a97c0f35fbda32d8f8104a321f1c2f4d97e10cbed25f0fb"},{"executable":false,"path":"src/hooks/session-start.ts","sha256":"a5cda975fd148cf904b3c0cc5b0a860061ed89acd3704d54427c1313f23668e8"},{"executable":false,"path":"src/scripts/detect-risk.ts","sha256":"3b1d88c26219a410b6b23c019632fa8330ba5421d9294abbe9fc3f5300720370"},{"executable":false,"path":"src/scripts/verify-release.ts","sha256":"af661a44e63f38726d237df8821426884f64386f1e0a9f5c8c369932eac341c3"}]},"runtime":{"node":"22.12.0"},"targets":[{"adapterRevision":"1.22.0","name":"claude","observedVersion":"2.1.250","schemas":[{"name":"hooks","revision":"2.1.250","sha256":"3c6f3e4391f3dca939d75bd0b200ea88e68db939a2cb885d46f0b143293efb84"},{"name":"lsp","revision":"2.1.250","sha256":"c81fd2f57c410f70f8e5c3f84483f5ec1b575ee02802b424977826f757dccd8e"},{"name":"marketplace","revision":"2.1.250","sha256":"4ffa94e8024966e8080b9d3b338c9612bdfa255802a8491b43f74f90427bc988"},{"name":"mcp","revision":"2.1.250","sha256":"76ccf02c7bfe2d57945ba18e84da8d655529bd68b4d692f72bce28238c99067e"},{"name":"monitors","revision":"2.1.250","sha256":"d45abdf7561e4316ba217ce9c2ac84f32e1049622b74abb081693b479a54b48d"},{"name":"plugin","revision":"2.1.250","sha256":"3c9943237da86fd08ae82f698cde36dbef2ecf742098c6961cedf481fe435c12"},{"name":"settings","revision":"2.1.250","sha256":"9e86d8c5e4053e8de0e468d349e2c3dde5834d22d6769372b88570e301700073"},{"name":"theme","revision":"2.1.250","sha256":"721aa9b0bc7c60cd9359343e5c7205ffbdfea82da312f601720c9dfaa2d8cf0d"}]},{"adapterRevision":"1.8.0","name":"codex","observedVersion":"0.147.0","schemas":[{"name":"app","revision":"0.147.0","sha256":"01c720a645e437bf0c4f8c26fd4cb5a13988e5649e4a8562ee23a1d4b7355c6a"},{"name":"hooks","revision":"0.147.0","sha256":"175b859eb8e85bd287d85ee840d97c3f5c2d0dda3223507a796d158e3770eeba"},{"name":"marketplace","revision":"0.147.0","sha256":"fbccce3ade39e1b077fcb440e60260de6e811e8c2d222b2ae0fe8fe47706b470"},{"name":"mcp","revision":"0.147.0","sha256":"75bd50f9fcb85c2e8d43bc132d61c172a02f28ea8bb77389816ae77b14a4257e"},{"name":"plugin","revision":"0.147.0","sha256":"4ad476545c96c83d899c4524dcccd4eb4fe7d3299c307878a0cd46a237f48d58"}]},{"adapterRevision":"1.6.0","name":"portable","observedVersion":"1.0.0","schemas":[{"name":"mcp","revision":"1.0.0","sha256":"6539175bfcdf43085855183e86da40ea94b166547a72b47ae9a0a390516d3acb"},{"name":"plugin","revision":"1.0.0","sha256":"0a4aad95ce337878ad38802ebf0daa3fde76abe3f65400c86bcbb1ec0b3ab883"}]}],"validation":{"artifact":{"status":"passed"},"source":{"status":"passed"},"targets":[{"name":"claude","status":"passed"},{"name":"codex","status":"passed"},{"name":"portable","status":"passed"}]}} diff --git a/examples/hooks-and-scripts/artifact/claude/.claude-plugin/marketplace.json b/examples/hooks-and-scripts/artifact/claude/.claude-plugin/marketplace.json new file mode 100644 index 000000000..2cae8a879 --- /dev/null +++ b/examples/hooks-and-scripts/artifact/claude/.claude-plugin/marketplace.json @@ -0,0 +1 @@ +{"description":"Hook simulation, script traces, logs, and recovery.","name":"hooks-and-scripts-marketplace","owner":{"name":"hooks-and-scripts"},"plugins":[{"description":"Hook simulation, script traces, logs, and recovery.","name":"hooks-and-scripts","source":"./","version":"1.0.0"}]} diff --git a/examples/hooks-and-scripts/artifact/claude/.claude-plugin/plugin.json b/examples/hooks-and-scripts/artifact/claude/.claude-plugin/plugin.json new file mode 100644 index 000000000..38dc8d3b1 --- /dev/null +++ b/examples/hooks-and-scripts/artifact/claude/.claude-plugin/plugin.json @@ -0,0 +1 @@ +{"author":{"name":"hooks-and-scripts"},"description":"Hook simulation, script traces, logs, and recovery.","hooks":"./hooks/hooks.json","name":"hooks-and-scripts","version":"1.0.0"} diff --git a/examples/hooks-and-scripts/artifact/claude/INSTALL.md b/examples/hooks-and-scripts/artifact/claude/INSTALL.md new file mode 100644 index 000000000..ea76a1f93 --- /dev/null +++ b/examples/hooks-and-scripts/artifact/claude/INSTALL.md @@ -0,0 +1,18 @@ +# Install hooks-and-scripts + +Hook simulation, script traces, logs, and recovery. + +Version: `1.0.0` + +Run these commands from this bundle directory. + +## Claude Code + +Claude Code installs this bundle through its local marketplace contract: + +```sh +claude plugin marketplace add ./ +claude plugin install hooks-and-scripts@hooks-and-scripts-marketplace --scope user +``` + +Replace `user` with `project` or `local` when that Claude scope is intended. diff --git a/examples/hooks-and-scripts/artifact/claude/assets/release/release-manifest.json b/examples/hooks-and-scripts/artifact/claude/assets/release/release-manifest.json new file mode 100644 index 000000000..819d86560 --- /dev/null +++ b/examples/hooks-and-scripts/artifact/claude/assets/release/release-manifest.json @@ -0,0 +1,21 @@ +{ + "version": "2.4.0", + "changelog": "CHANGELOG.md#2.4.0", + "artifacts": [ + { + "name": "package", + "path": "dist/agent-bundle-2.4.0.tgz", + "status": "ready" + }, + { + "name": "checksums", + "path": "dist/agent-bundle-2.4.0.sha256", + "status": "ready" + }, + { + "name": "sbom", + "path": "dist/agent-bundle-2.4.0.sbom.json", + "status": "ready" + } + ] +} diff --git a/examples/hooks-and-scripts/artifact/claude/assets/release/risk-register.json b/examples/hooks-and-scripts/artifact/claude/assets/release/risk-register.json new file mode 100644 index 000000000..2295bcc45 --- /dev/null +++ b/examples/hooks-and-scripts/artifact/claude/assets/release/risk-register.json @@ -0,0 +1,16 @@ +{ + "risks": [ + { + "id": "REL-204", + "severity": "high", + "status": "open", + "summary": "Complete the final approval for the release notes before publishing." + }, + { + "id": "REL-198", + "severity": "medium", + "status": "mitigated", + "summary": "Package signing rehearsal is documented in the release runbook." + } + ] +} diff --git a/examples/hooks-and-scripts/artifact/claude/hooks/hooks.json b/examples/hooks-and-scripts/artifact/claude/hooks/hooks.json new file mode 100644 index 000000000..1afdaac5a --- /dev/null +++ b/examples/hooks-and-scripts/artifact/claude/hooks/hooks.json @@ -0,0 +1 @@ +{"hooks":{"SessionStart":[{"hooks":[{"command":"node \"${CLAUDE_PLUGIN_ROOT}/hooks/session-start-session-start-7ab7e8a5.mjs\"","type":"command"}]}]}} diff --git a/examples/hooks-and-scripts/artifact/claude/hooks/session-start-session-start-7ab7e8a5.mjs b/examples/hooks-and-scripts/artifact/claude/hooks/session-start-session-start-7ab7e8a5.mjs new file mode 100644 index 000000000..924ce1681 --- /dev/null +++ b/examples/hooks-and-scripts/artifact/claude/hooks/session-start-session-start-7ab7e8a5.mjs @@ -0,0 +1,253 @@ +// The require scope +var __webpack_require__ = {}; + +// webpack/runtime/define_property_getters +(() => { +__webpack_require__.d = (exports, getters, values) => { + var define = (defs, kind) => { + for(var key in defs) { + if(__webpack_require__.o(defs, key) && !__webpack_require__.o(exports, key)) { + Object.defineProperty(exports, key, { enumerable: true, [kind]: defs[key] }); + } + } + }; + define(getters, "get"); + define(values, "value"); +}; +})(); +// webpack/runtime/has_own_property +(() => { +__webpack_require__.o = (obj, prop) => (Object.prototype.hasOwnProperty.call(obj, prop)) +})(); +// webpack/runtime/make_namespace_object +(() => { +// define __esModule on exports +__webpack_require__.r = (exports) => { + if(typeof Symbol !== 'undefined' && Symbol.toStringTag) { + Object.defineProperty(exports, Symbol.toStringTag, { value: 'Module' }); + } + Object.defineProperty(exports, '__esModule', { value: true }); +}; +})(); + +// NAMESPACE OBJECT: ./src/hooks/session-start.ts +var session_start_namespaceObject = {}; +__webpack_require__.r(session_start_namespaceObject); +__webpack_require__.d(session_start_namespaceObject, { + "default": () => (session_start) }); + + +/* export default */ const session_start = ((event)=>({ + additionalContext: [ + `This release preparation session is active for ${event.sessionId ?? 'this session'} from ${event.source ?? 'an unknown source'}.`, + `Run verify-release from ${event.cwd ?? process.cwd()} to confirm the manifest is ready for packaging.`, + 'Run detect-risk to surface open high-severity release blockers before publishing.' + ].join(' '), + outcome: 'continue' + })); + + +const target = "claude"; +const canonicalEvent = "sessionStart"; +const nativeEvent = "SessionStart"; +const isRecord = (value)=>typeof value === "object" && value !== null && !Array.isArray(value); +const defined = (value)=>Object.fromEntries(Object.entries(value).filter(([, item])=>item !== undefined)); +const decodeClaudeNative = (nativeInput)=>({ + agentId: nativeInput.agent_id, + agentTranscriptPath: nativeInput.agent_transcript_path, + agentType: nativeInput.agent_type, + cwd: nativeInput.cwd, + effort: nativeInput.effort, + hookEventName: nativeInput.hook_event_name, + lastAssistantMessage: nativeInput.last_assistant_message, + model: nativeInput.model, + permissionMode: nativeInput.permission_mode, + promptId: nativeInput.prompt_id, + sessionId: nativeInput.session_id, + source: nativeInput.source, + stopHookActive: nativeInput.stop_hook_active, + toolInput: nativeInput.tool_input, + toolName: nativeInput.tool_name, + toolResponse: nativeInput.tool_response, + toolUseId: nativeInput.tool_use_id, + transcriptPath: nativeInput.transcript_path, + turnId: nativeInput.turn_id + }); +const encodeClaudeNative = (canonicalInput)=>defined({ + hook_event_name: nativeEvent, + agent_id: canonicalInput.agentId, + agent_transcript_path: canonicalInput.agentTranscriptPath, + agent_type: canonicalInput.agentType, + cwd: canonicalInput.cwd, + effort: canonicalInput.effort, + last_assistant_message: canonicalInput.lastAssistantMessage, + model: canonicalInput.model, + permission_mode: canonicalInput.permissionMode, + prompt_id: canonicalInput.promptId, + session_id: canonicalInput.sessionId, + source: canonicalInput.source, + stop_hook_active: canonicalInput.stopHookActive, + tool_input: canonicalInput.toolInput, + tool_name: canonicalInput.toolName, + tool_response: canonicalInput.toolResponse, + tool_use_id: canonicalInput.toolUseId, + transcript_path: canonicalInput.transcriptPath, + turn_id: canonicalInput.turnId + }); +const decodeNative = decodeClaudeNative; +const encodeNative = encodeClaudeNative; +const fail = (message)=>{ + throw new Error(`Agent Bundle hook error: ${message}`); +}; +const validateResult = (result)=>{ + if (result === undefined) return undefined; + if (!isRecord(result)) fail("handler must return void or a result object"); + const allowed = new Set([ + "outcome", + "reason", + "updatedInput", + "additionalContext" + ]); + for (const key of Object.keys(result))if (!allowed.has(key)) fail(`handler result has unsupported field ${key}`); + if (result.outcome !== undefined && ![ + "continue", + "deny", + "stop" + ].includes(result.outcome)) fail("handler result outcome is invalid"); + if (result.reason !== undefined && typeof result.reason !== "string") fail("handler result reason must be a string"); + if (result.additionalContext !== undefined && typeof result.additionalContext !== "string") fail("handler result additionalContext must be a string"); + if (result.updatedInput !== undefined && !isRecord(result.updatedInput)) fail("handler result updatedInput must be an object"); + const supportsDeniedReason = canonicalEvent === "beforeTool" || canonicalEvent === "stop" || canonicalEvent === "agentStop"; + if (result.reason !== undefined && !(result.outcome === "deny" && supportsDeniedReason)) fail("reason is only valid for a denied beforeTool, stop, or agentStop hook"); + if (result.outcome === "deny" && supportsDeniedReason && (typeof result.reason !== "string" || result.reason.trim().length === 0)) fail(`denied ${canonicalEvent} hook requires a nonempty reason`); + if ((canonicalEvent === "sessionStart" || canonicalEvent === "afterTool" || canonicalEvent === "agentStart") && (result.outcome === "deny" || result.outcome === "stop" || result.updatedInput !== undefined)) fail(`${canonicalEvent} cannot deny, stop, or replace input`); + if (canonicalEvent === "beforeTool" && (result.outcome === "stop" || result.outcome === "deny" && result.updatedInput !== undefined)) fail("beforeTool cannot stop or replace input while denying"); + if (canonicalEvent === "stop" && (result.outcome === "stop" || result.updatedInput !== undefined || result.additionalContext !== undefined)) fail("stop only accepts continue or deny with a reason"); + if (canonicalEvent === "agentStop" && (result.outcome === "stop" || result.updatedInput !== undefined)) fail("agentStop cannot stop the parent flow or replace input"); + if (canonicalEvent === "agentStop" && target === "codex" && 0) {} + return result; +}; +const encodeOutput = (result)=>{ + if (result === undefined) return undefined; + if (canonicalEvent === "stop" || canonicalEvent === "agentStop") { + if (result.outcome === "deny") return defined({ + decision: "block", + reason: result.reason + }); + if (canonicalEvent === "agentStop" && target === "claude" && result.additionalContext !== undefined) return { + hookSpecificOutput: { + additionalContext: result.additionalContext, + hookEventName: nativeEvent + } + }; + return undefined; + } + const output = defined({ + additionalContext: result.additionalContext, + hookEventName: nativeEvent, + permissionDecision: canonicalEvent === "beforeTool" ? result.outcome === "deny" ? "deny" : "allow" : undefined, + permissionDecisionReason: canonicalEvent === "beforeTool" && result.outcome === "deny" ? result.reason : undefined, + updatedInput: canonicalEvent === "beforeTool" && result.outcome !== "deny" ? result.updatedInput : undefined + }); + return Object.keys(output).length === 1 && output.hookEventName !== undefined ? undefined : { + hookSpecificOutput: output + }; +}; +const decodeOutput = (nativeOutput)=>{ + if (nativeOutput === undefined) return undefined; + if (canonicalEvent === "stop" || canonicalEvent === "agentStop") { + if (nativeOutput.decision === "block") return defined({ + outcome: "deny", + reason: nativeOutput.reason + }); + if (canonicalEvent === "agentStop" && target === "claude" && isRecord(nativeOutput.hookSpecificOutput)) return defined({ + additionalContext: nativeOutput.hookSpecificOutput.additionalContext, + outcome: "continue" + }); + return undefined; + } + const output = nativeOutput.hookSpecificOutput; + if (!isRecord(output)) fail("native hook output is malformed"); + return defined({ + additionalContext: output.additionalContext, + outcome: output.permissionDecision === "deny" ? "deny" : "continue", + reason: output.permissionDecisionReason, + updatedInput: output.updatedInput + }); +}; +const requireString = (input, field)=>{ + if (typeof input[field] !== "string") fail(`native ${field} must be a string`); +}; +const requireNullableString = (input, field)=>{ + if (input[field] !== null && typeof input[field] !== "string") fail(`native ${field} must be a string or null`); +}; +const validateNativeInput = (input)=>{ + requireString(input, "session_id"); + if (false) {} + else requireString(input, "transcript_path"); + requireString(input, "cwd"); + if (input.hook_event_name !== nativeEvent) fail(`native hook_event_name must equal ${nativeEvent}`); + if (input.prompt_id !== undefined) requireString(input, "prompt_id"); + if (input.permission_mode !== undefined) requireString(input, "permission_mode"); + if (input.model !== undefined) requireString(input, "model"); + if (canonicalEvent === "sessionStart") { + requireString(input, "source"); + return; + } + if (canonicalEvent === "beforeTool" || canonicalEvent === "afterTool") { + requireString(input, "tool_name"); + if (false) {} else if (!isRecord(input.tool_input)) fail(`native ${nativeEvent} tool_input must be an object`); + requireString(input, "tool_use_id"); + if (canonicalEvent === "afterTool") { + if (input.tool_response === undefined) fail("native PostToolUse tool_response is required"); + } + return; + } + if (canonicalEvent === "agentStart" || canonicalEvent === "agentStop") { + requireString(input, "agent_id"); + requireString(input, "agent_type"); + if (false) {} + if (canonicalEvent === "agentStart") return; + if (typeof input.stop_hook_active !== "boolean") fail("native SubagentStop stop_hook_active must be a boolean"); + requireNullableString(input, "agent_transcript_path"); + requireNullableString(input, "last_assistant_message"); + return; + } + if (typeof input.stop_hook_active !== "boolean") fail("native Stop stop_hook_active must be a boolean"); + if (false) {} + else requireString(input, "last_assistant_message"); +}; +const run = async ()=>{ + const handler = Reflect.get(session_start_namespaceObject, "default"); + if (typeof handler !== "function") fail("default export must be a function"); + let raw = ""; + for await (const chunk of process.stdin)raw += chunk; + if (raw.trim().length === 0) fail("stdin must contain exactly one JSON value"); + let input; + try { + input = JSON.parse(raw); + } catch { + fail("stdin must contain exactly one JSON value"); + } + if (!isRecord(input)) fail("stdin JSON value must be an object"); + const simulation = process.env.AGENT_BUNDLE_HOOK_SIMULATION === "1"; + const nativeInput = simulation ? encodeNative(input) : input; + validateNativeInput(nativeInput); + const event = decodeNative(nativeInput); + const result = validateResult(await handler(event, { + nativeEvent: nativeEvent, + nativeInput, + target: target + })); + const nativeOutput = encodeOutput(result); + const output = simulation ? decodeOutput(nativeOutput) : nativeOutput; + if (output !== undefined) process.stdout.write(JSON.stringify(output)); +}; +if (import.meta.main) { + await run().catch((error)=>{ + process.stderr.write(`${error instanceof Error ? error.message : String(error)}\n`); + process.exitCode = 1; + }); +} + +export {}; diff --git a/examples/hooks-and-scripts/artifact/claude/scripts/verify-release.mjs b/examples/hooks-and-scripts/artifact/claude/scripts/verify-release.mjs new file mode 100644 index 000000000..6ac9cd7a9 --- /dev/null +++ b/examples/hooks-and-scripts/artifact/claude/scripts/verify-release.mjs @@ -0,0 +1,54 @@ +import { readFile } from "node:fs/promises"; + + + + + +const requiredArtifacts = [ + 'package', + 'checksums', + 'sbom' +]; +const manifestPath = new URL('../assets/release/release-manifest.json', import.meta.url); +const readManifest = async ()=>JSON.parse(await readFile(manifestPath, 'utf8')); +const validationErrors = (manifest)=>{ + const errors = []; + if (typeof manifest.version !== 'string' || !/^\d+\.\d+\.\d+$/.test(manifest.version)) { + errors.push('version must use major.minor.patch format'); + } + if (typeof manifest.changelog !== 'string' || manifest.changelog.trim().length === 0) { + errors.push('changelog must identify the release notes'); + } + for (const name of requiredArtifacts){ + const artifact = manifest.artifacts?.find((candidate)=>candidate.name === name); + if (artifact === undefined || typeof artifact.path !== 'string' || artifact.path.trim().length === 0 || artifact.status !== 'ready') { + errors.push(`${name} artifact must have a ready path`); + } + } + return errors; +}; +const main = async ()=>{ + try { + const manifest = await readManifest(); + const errors = validationErrors(manifest); + if (errors.length > 0) { + process.stderr.write(`Release manifest is incomplete:\n${errors.map((error)=>`- ${error}`).join('\n')}\n`); + return 1; + } + process.stdout.write(`Release ${manifest.version} is ready for packaging.\n`); + return 0; + } catch (error) { + process.stderr.write(`Unable to verify release manifest: ${error instanceof Error ? error.message : String(error)}\n`); + return 1; + } +}; + + +const verify_release_entry_main = main; +if (typeof verify_release_entry_main !== 'function') { + throw new TypeError('Executable entry must export a main function: ' + "/fast/projects/agent-bundle-worktrees/host-test/examples/hooks-and-scripts/src/scripts/verify-release.ts"); +} +const code = await verify_release_entry_main(process.argv.slice(2)); +if (typeof code === 'number') process.exitCode = code; + +export {}; diff --git a/examples/hooks-and-scripts/artifact/codex/.agents/plugins/marketplace.json b/examples/hooks-and-scripts/artifact/codex/.agents/plugins/marketplace.json new file mode 100644 index 000000000..16e053eae --- /dev/null +++ b/examples/hooks-and-scripts/artifact/codex/.agents/plugins/marketplace.json @@ -0,0 +1 @@ +{"interface":{"displayName":"hooks-and-scripts"},"name":"hooks-and-scripts-marketplace","plugins":[{"category":"Productivity","name":"hooks-and-scripts","policy":{"authentication":"ON_INSTALL","installation":"AVAILABLE"},"source":{"path":"./","source":"local"}}]} diff --git a/examples/hooks-and-scripts/artifact/codex/.codex-plugin/plugin.json b/examples/hooks-and-scripts/artifact/codex/.codex-plugin/plugin.json new file mode 100644 index 000000000..eeee06783 --- /dev/null +++ b/examples/hooks-and-scripts/artifact/codex/.codex-plugin/plugin.json @@ -0,0 +1 @@ +{"author":{"name":"hooks-and-scripts"},"description":"Hook simulation, script traces, logs, and recovery.","hooks":"./hooks/hooks.json","interface":{"capabilities":["hooks"],"category":"Productivity","defaultPrompt":["Help me use hooks-and-scripts."],"developerName":"hooks-and-scripts","displayName":"hooks-and-scripts","longDescription":"Hook simulation, script traces, logs, and recovery.","shortDescription":"Hook simulation, script traces, logs, and recovery."},"name":"hooks-and-scripts","skills":"./skills/","version":"1.0.0"} diff --git a/examples/hooks-and-scripts/artifact/codex/INSTALL.md b/examples/hooks-and-scripts/artifact/codex/INSTALL.md new file mode 100644 index 000000000..97ee12563 --- /dev/null +++ b/examples/hooks-and-scripts/artifact/codex/INSTALL.md @@ -0,0 +1,16 @@ +# Install hooks-and-scripts + +Hook simulation, script traces, logs, and recovery. + +Version: `1.0.0` + +Run these commands from this bundle directory. + +## Codex + +Codex installs this bundle from its local marketplace snapshot: + +```sh +codex plugin marketplace add ./ +codex plugin add hooks-and-scripts@hooks-and-scripts-marketplace +``` diff --git a/examples/hooks-and-scripts/artifact/codex/assets/release/release-manifest.json b/examples/hooks-and-scripts/artifact/codex/assets/release/release-manifest.json new file mode 100644 index 000000000..819d86560 --- /dev/null +++ b/examples/hooks-and-scripts/artifact/codex/assets/release/release-manifest.json @@ -0,0 +1,21 @@ +{ + "version": "2.4.0", + "changelog": "CHANGELOG.md#2.4.0", + "artifacts": [ + { + "name": "package", + "path": "dist/agent-bundle-2.4.0.tgz", + "status": "ready" + }, + { + "name": "checksums", + "path": "dist/agent-bundle-2.4.0.sha256", + "status": "ready" + }, + { + "name": "sbom", + "path": "dist/agent-bundle-2.4.0.sbom.json", + "status": "ready" + } + ] +} diff --git a/examples/hooks-and-scripts/artifact/codex/assets/release/risk-register.json b/examples/hooks-and-scripts/artifact/codex/assets/release/risk-register.json new file mode 100644 index 000000000..2295bcc45 --- /dev/null +++ b/examples/hooks-and-scripts/artifact/codex/assets/release/risk-register.json @@ -0,0 +1,16 @@ +{ + "risks": [ + { + "id": "REL-204", + "severity": "high", + "status": "open", + "summary": "Complete the final approval for the release notes before publishing." + }, + { + "id": "REL-198", + "severity": "medium", + "status": "mitigated", + "summary": "Package signing rehearsal is documented in the release runbook." + } + ] +} diff --git a/examples/hooks-and-scripts/artifact/codex/hooks/hooks.json b/examples/hooks-and-scripts/artifact/codex/hooks/hooks.json new file mode 100644 index 000000000..eb4f61756 --- /dev/null +++ b/examples/hooks-and-scripts/artifact/codex/hooks/hooks.json @@ -0,0 +1 @@ +{"hooks":{"SessionStart":[{"hooks":[{"command":"node \"${PLUGIN_ROOT}/hooks/session-start-session-start-7ab7e8a5.mjs\"","type":"command"}]}]}} diff --git a/examples/hooks-and-scripts/artifact/codex/hooks/session-start-session-start-7ab7e8a5.mjs b/examples/hooks-and-scripts/artifact/codex/hooks/session-start-session-start-7ab7e8a5.mjs new file mode 100644 index 000000000..28a8cb44b --- /dev/null +++ b/examples/hooks-and-scripts/artifact/codex/hooks/session-start-session-start-7ab7e8a5.mjs @@ -0,0 +1,258 @@ +// The require scope +var __webpack_require__ = {}; + +// webpack/runtime/define_property_getters +(() => { +__webpack_require__.d = (exports, getters, values) => { + var define = (defs, kind) => { + for(var key in defs) { + if(__webpack_require__.o(defs, key) && !__webpack_require__.o(exports, key)) { + Object.defineProperty(exports, key, { enumerable: true, [kind]: defs[key] }); + } + } + }; + define(getters, "get"); + define(values, "value"); +}; +})(); +// webpack/runtime/has_own_property +(() => { +__webpack_require__.o = (obj, prop) => (Object.prototype.hasOwnProperty.call(obj, prop)) +})(); +// webpack/runtime/make_namespace_object +(() => { +// define __esModule on exports +__webpack_require__.r = (exports) => { + if(typeof Symbol !== 'undefined' && Symbol.toStringTag) { + Object.defineProperty(exports, Symbol.toStringTag, { value: 'Module' }); + } + Object.defineProperty(exports, '__esModule', { value: true }); +}; +})(); + +// NAMESPACE OBJECT: ./src/hooks/session-start.ts +var session_start_namespaceObject = {}; +__webpack_require__.r(session_start_namespaceObject); +__webpack_require__.d(session_start_namespaceObject, { + "default": () => (session_start) }); + + +/* export default */ const session_start = ((event)=>({ + additionalContext: [ + `This release preparation session is active for ${event.sessionId ?? 'this session'} from ${event.source ?? 'an unknown source'}.`, + `Run verify-release from ${event.cwd ?? process.cwd()} to confirm the manifest is ready for packaging.`, + 'Run detect-risk to surface open high-severity release blockers before publishing.' + ].join(' '), + outcome: 'continue' + })); + + +const target = "codex"; +const canonicalEvent = "sessionStart"; +const nativeEvent = "SessionStart"; +const isRecord = (value)=>typeof value === "object" && value !== null && !Array.isArray(value); +const defined = (value)=>Object.fromEntries(Object.entries(value).filter(([, item])=>item !== undefined)); +const decodeCodexNative = (nativeInput)=>({ + agentId: nativeInput.agent_id, + agentTranscriptPath: nativeInput.agent_transcript_path, + agentType: nativeInput.agent_type, + cwd: nativeInput.cwd, + effort: nativeInput.effort, + hookEventName: nativeInput.hook_event_name, + lastAssistantMessage: nativeInput.last_assistant_message, + model: nativeInput.model, + permissionMode: nativeInput.permission_mode, + promptId: nativeInput.prompt_id, + sessionId: nativeInput.session_id, + source: nativeInput.source, + stopHookActive: nativeInput.stop_hook_active, + toolInput: nativeInput.tool_input, + toolName: nativeInput.tool_name, + toolResponse: nativeInput.tool_response, + toolUseId: nativeInput.tool_use_id, + transcriptPath: nativeInput.transcript_path, + turnId: nativeInput.turn_id + }); +const encodeCodexNative = (canonicalInput)=>defined({ + hook_event_name: nativeEvent, + agent_id: canonicalInput.agentId, + agent_transcript_path: canonicalInput.agentTranscriptPath, + agent_type: canonicalInput.agentType, + cwd: canonicalInput.cwd, + effort: canonicalInput.effort, + last_assistant_message: canonicalInput.lastAssistantMessage, + model: canonicalInput.model, + permission_mode: canonicalInput.permissionMode, + prompt_id: canonicalInput.promptId, + session_id: canonicalInput.sessionId, + source: canonicalInput.source, + stop_hook_active: canonicalInput.stopHookActive, + tool_input: canonicalInput.toolInput, + tool_name: canonicalInput.toolName, + tool_response: canonicalInput.toolResponse, + tool_use_id: canonicalInput.toolUseId, + transcript_path: canonicalInput.transcriptPath, + turn_id: canonicalInput.turnId + }); +const decodeNative = decodeCodexNative; +const encodeNative = encodeCodexNative; +const fail = (message)=>{ + throw new Error(`Agent Bundle hook error: ${message}`); +}; +const validateResult = (result)=>{ + if (result === undefined) return undefined; + if (!isRecord(result)) fail("handler must return void or a result object"); + const allowed = new Set([ + "outcome", + "reason", + "updatedInput", + "additionalContext" + ]); + for (const key of Object.keys(result))if (!allowed.has(key)) fail(`handler result has unsupported field ${key}`); + if (result.outcome !== undefined && ![ + "continue", + "deny", + "stop" + ].includes(result.outcome)) fail("handler result outcome is invalid"); + if (result.reason !== undefined && typeof result.reason !== "string") fail("handler result reason must be a string"); + if (result.additionalContext !== undefined && typeof result.additionalContext !== "string") fail("handler result additionalContext must be a string"); + if (result.updatedInput !== undefined && !isRecord(result.updatedInput)) fail("handler result updatedInput must be an object"); + const supportsDeniedReason = canonicalEvent === "beforeTool" || canonicalEvent === "stop" || canonicalEvent === "agentStop"; + if (result.reason !== undefined && !(result.outcome === "deny" && supportsDeniedReason)) fail("reason is only valid for a denied beforeTool, stop, or agentStop hook"); + if (result.outcome === "deny" && supportsDeniedReason && (typeof result.reason !== "string" || result.reason.trim().length === 0)) fail(`denied ${canonicalEvent} hook requires a nonempty reason`); + if ((canonicalEvent === "sessionStart" || canonicalEvent === "afterTool" || canonicalEvent === "agentStart") && (result.outcome === "deny" || result.outcome === "stop" || result.updatedInput !== undefined)) fail(`${canonicalEvent} cannot deny, stop, or replace input`); + if (canonicalEvent === "beforeTool" && (result.outcome === "stop" || result.outcome === "deny" && result.updatedInput !== undefined)) fail("beforeTool cannot stop or replace input while denying"); + if (canonicalEvent === "stop" && (result.outcome === "stop" || result.updatedInput !== undefined || result.additionalContext !== undefined)) fail("stop only accepts continue or deny with a reason"); + if (canonicalEvent === "agentStop" && (result.outcome === "stop" || result.updatedInput !== undefined)) fail("agentStop cannot stop the parent flow or replace input"); + if (canonicalEvent === "agentStop" && target === "codex" && result.additionalContext !== undefined) fail("Codex SubagentStop does not support additionalContext"); + return result; +}; +const encodeOutput = (result)=>{ + if (result === undefined) return undefined; + if (canonicalEvent === "stop" || canonicalEvent === "agentStop") { + if (result.outcome === "deny") return defined({ + decision: "block", + reason: result.reason + }); + if (canonicalEvent === "agentStop" && target === "claude" && 0) {} + return undefined; + } + const output = defined({ + additionalContext: result.additionalContext, + hookEventName: nativeEvent, + permissionDecision: canonicalEvent === "beforeTool" ? result.outcome === "deny" ? "deny" : "allow" : undefined, + permissionDecisionReason: canonicalEvent === "beforeTool" && result.outcome === "deny" ? result.reason : undefined, + updatedInput: canonicalEvent === "beforeTool" && result.outcome !== "deny" ? result.updatedInput : undefined + }); + return Object.keys(output).length === 1 && output.hookEventName !== undefined ? undefined : { + hookSpecificOutput: output + }; +}; +const decodeOutput = (nativeOutput)=>{ + if (nativeOutput === undefined) return undefined; + if (canonicalEvent === "stop" || canonicalEvent === "agentStop") { + if (nativeOutput.decision === "block") return defined({ + outcome: "deny", + reason: nativeOutput.reason + }); + if (canonicalEvent === "agentStop" && target === "claude" && 0) {} + return undefined; + } + const output = nativeOutput.hookSpecificOutput; + if (!isRecord(output)) fail("native hook output is malformed"); + return defined({ + additionalContext: output.additionalContext, + outcome: output.permissionDecision === "deny" ? "deny" : "continue", + reason: output.permissionDecisionReason, + updatedInput: output.updatedInput + }); +}; +const requireString = (input, field)=>{ + if (typeof input[field] !== "string") fail(`native ${field} must be a string`); +}; +const requireNullableString = (input, field)=>{ + if (input[field] !== null && typeof input[field] !== "string") fail(`native ${field} must be a string or null`); +}; +const validateNativeInput = (input)=>{ + requireString(input, "session_id"); + if (true) requireNullableString(input, "transcript_path"); + else {} + requireString(input, "cwd"); + if (input.hook_event_name !== nativeEvent) fail(`native hook_event_name must equal ${nativeEvent}`); + if (input.prompt_id !== undefined) requireString(input, "prompt_id"); + if (input.permission_mode !== undefined) requireString(input, "permission_mode"); + if (input.model !== undefined) requireString(input, "model"); + if (canonicalEvent === "sessionStart") { + requireString(input, "source"); + return; + } + if (canonicalEvent === "beforeTool" || canonicalEvent === "afterTool") { + requireString(input, "tool_name"); + if (true) { + if (input.tool_input === undefined) fail(`native ${nativeEvent} tool_input is required`); + } else {} + requireString(input, "tool_use_id"); + if (canonicalEvent === "afterTool") { + if (input.tool_response === undefined) fail("native PostToolUse tool_response is required"); + } + return; + } + if (canonicalEvent === "agentStart" || canonicalEvent === "agentStop") { + requireString(input, "agent_id"); + requireString(input, "agent_type"); + if (true) { + requireString(input, "turn_id"); + requireString(input, "model"); + requireString(input, "permission_mode"); + if (![ + "default", + "acceptEdits", + "plan", + "dontAsk", + "bypassPermissions" + ].includes(input.permission_mode)) fail("native permission_mode is invalid"); + } + if (canonicalEvent === "agentStart") return; + if (typeof input.stop_hook_active !== "boolean") fail("native SubagentStop stop_hook_active must be a boolean"); + requireNullableString(input, "agent_transcript_path"); + requireNullableString(input, "last_assistant_message"); + return; + } + if (typeof input.stop_hook_active !== "boolean") fail("native Stop stop_hook_active must be a boolean"); + if (true) requireNullableString(input, "last_assistant_message"); + else {} +}; +const run = async ()=>{ + const handler = Reflect.get(session_start_namespaceObject, "default"); + if (typeof handler !== "function") fail("default export must be a function"); + let raw = ""; + for await (const chunk of process.stdin)raw += chunk; + if (raw.trim().length === 0) fail("stdin must contain exactly one JSON value"); + let input; + try { + input = JSON.parse(raw); + } catch { + fail("stdin must contain exactly one JSON value"); + } + if (!isRecord(input)) fail("stdin JSON value must be an object"); + const simulation = process.env.AGENT_BUNDLE_HOOK_SIMULATION === "1"; + const nativeInput = simulation ? encodeNative(input) : input; + validateNativeInput(nativeInput); + const event = decodeNative(nativeInput); + const result = validateResult(await handler(event, { + nativeEvent: nativeEvent, + nativeInput, + target: target + })); + const nativeOutput = encodeOutput(result); + const output = simulation ? decodeOutput(nativeOutput) : nativeOutput; + if (output !== undefined) process.stdout.write(JSON.stringify(output)); +}; +if (import.meta.main) { + await run().catch((error)=>{ + process.stderr.write(`${error instanceof Error ? error.message : String(error)}\n`); + process.exitCode = 1; + }); +} + +export {}; diff --git a/examples/hooks-and-scripts/artifact/codex/scripts/verify-release.mjs b/examples/hooks-and-scripts/artifact/codex/scripts/verify-release.mjs new file mode 100644 index 000000000..6ac9cd7a9 --- /dev/null +++ b/examples/hooks-and-scripts/artifact/codex/scripts/verify-release.mjs @@ -0,0 +1,54 @@ +import { readFile } from "node:fs/promises"; + + + + + +const requiredArtifacts = [ + 'package', + 'checksums', + 'sbom' +]; +const manifestPath = new URL('../assets/release/release-manifest.json', import.meta.url); +const readManifest = async ()=>JSON.parse(await readFile(manifestPath, 'utf8')); +const validationErrors = (manifest)=>{ + const errors = []; + if (typeof manifest.version !== 'string' || !/^\d+\.\d+\.\d+$/.test(manifest.version)) { + errors.push('version must use major.minor.patch format'); + } + if (typeof manifest.changelog !== 'string' || manifest.changelog.trim().length === 0) { + errors.push('changelog must identify the release notes'); + } + for (const name of requiredArtifacts){ + const artifact = manifest.artifacts?.find((candidate)=>candidate.name === name); + if (artifact === undefined || typeof artifact.path !== 'string' || artifact.path.trim().length === 0 || artifact.status !== 'ready') { + errors.push(`${name} artifact must have a ready path`); + } + } + return errors; +}; +const main = async ()=>{ + try { + const manifest = await readManifest(); + const errors = validationErrors(manifest); + if (errors.length > 0) { + process.stderr.write(`Release manifest is incomplete:\n${errors.map((error)=>`- ${error}`).join('\n')}\n`); + return 1; + } + process.stdout.write(`Release ${manifest.version} is ready for packaging.\n`); + return 0; + } catch (error) { + process.stderr.write(`Unable to verify release manifest: ${error instanceof Error ? error.message : String(error)}\n`); + return 1; + } +}; + + +const verify_release_entry_main = main; +if (typeof verify_release_entry_main !== 'function') { + throw new TypeError('Executable entry must export a main function: ' + "/fast/projects/agent-bundle-worktrees/host-test/examples/hooks-and-scripts/src/scripts/verify-release.ts"); +} +const code = await verify_release_entry_main(process.argv.slice(2)); +if (typeof code === 'number') process.exitCode = code; + +export {}; diff --git a/examples/hooks-and-scripts/artifact/portable/INSTALL.md b/examples/hooks-and-scripts/artifact/portable/INSTALL.md new file mode 100644 index 000000000..0c3c03165 --- /dev/null +++ b/examples/hooks-and-scripts/artifact/portable/INSTALL.md @@ -0,0 +1,19 @@ +# Install hooks-and-scripts + +Hook simulation, script traces, logs, and recovery. + +Version: `1.0.0` + +Run these commands from this bundle directory. + +## Portable Agent Plugin + +Portable is a distribution profile, not a host runtime with one universal install location. +This bundle follows the Agent Plugins open standard (Agent Plugins 1.0.0, https://agent-plugins.org). +Cursor loads this format natively from `~/.cursor/plugins/local/`; restart Cursor or run +`Developer: Reload Window` after copying it. Codex, VS Code, GitHub Copilot, Kiro, and ChatGPT +are also native clients. The bundled installer provides the Cursor local copy: + +```sh +node ./install.mjs +``` diff --git a/examples/hooks-and-scripts/artifact/portable/assets/release/release-manifest.json b/examples/hooks-and-scripts/artifact/portable/assets/release/release-manifest.json new file mode 100644 index 000000000..819d86560 --- /dev/null +++ b/examples/hooks-and-scripts/artifact/portable/assets/release/release-manifest.json @@ -0,0 +1,21 @@ +{ + "version": "2.4.0", + "changelog": "CHANGELOG.md#2.4.0", + "artifacts": [ + { + "name": "package", + "path": "dist/agent-bundle-2.4.0.tgz", + "status": "ready" + }, + { + "name": "checksums", + "path": "dist/agent-bundle-2.4.0.sha256", + "status": "ready" + }, + { + "name": "sbom", + "path": "dist/agent-bundle-2.4.0.sbom.json", + "status": "ready" + } + ] +} diff --git a/examples/hooks-and-scripts/artifact/portable/assets/release/risk-register.json b/examples/hooks-and-scripts/artifact/portable/assets/release/risk-register.json new file mode 100644 index 000000000..2295bcc45 --- /dev/null +++ b/examples/hooks-and-scripts/artifact/portable/assets/release/risk-register.json @@ -0,0 +1,16 @@ +{ + "risks": [ + { + "id": "REL-204", + "severity": "high", + "status": "open", + "summary": "Complete the final approval for the release notes before publishing." + }, + { + "id": "REL-198", + "severity": "medium", + "status": "mitigated", + "summary": "Package signing rehearsal is documented in the release runbook." + } + ] +} diff --git a/examples/hooks-and-scripts/artifact/portable/install.mjs b/examples/hooks-and-scripts/artifact/portable/install.mjs new file mode 100644 index 000000000..8873d4b6a --- /dev/null +++ b/examples/hooks-and-scripts/artifact/portable/install.mjs @@ -0,0 +1,80 @@ +#!/usr/bin/env node +import { createHash } from 'node:crypto'; +import { cp, lstat, mkdir, mkdtemp, readFile, readdir, rename, rm } from 'node:fs/promises'; +import { homedir } from 'node:os'; +import { basename, join, resolve } from 'node:path'; +import { fileURLToPath } from 'node:url'; + +const pluginName = "hooks-and-scripts"; +const pluginVersion = "1.0.0"; +const source = resolve(fileURLToPath(new URL('.', import.meta.url))); +const cursorRoot = join(homedir(), '.cursor'); +const installRoot = join(cursorRoot, 'plugins', 'local'); +const destination = join(installRoot, pluginName); + +const exists = async (path) => { + try { await lstat(path); return true; } + catch (error) { if (error?.code === 'ENOENT') return false; throw error; } +}; + +const treeHash = async (root, prefix = '') => { + const rootMetadata = await lstat(root); + if (rootMetadata.isSymbolicLink() || !rootMetadata.isDirectory()) { + throw new Error('Refusing unsupported filesystem entry ".".'); + } + const hash = createHash('sha256'); + const visit = async (relative) => { + const absolute = join(root, relative); + const metadata = await lstat(absolute); + if (metadata.isSymbolicLink() || (!metadata.isDirectory() && !metadata.isFile())) { + throw new Error(`Refusing unsupported filesystem entry ${JSON.stringify(relative || '.')}.`); + } + if (metadata.isDirectory()) { + for (const name of (await readdir(absolute)).sort()) await visit(join(relative, name)); + return; + } + hash.update(relative.replaceAll('\\', '/')); + hash.update('\0'); + hash.update(await readFile(absolute)); + hash.update('\0'); + }; + for (const name of (await readdir(root)).sort()) await visit(join(prefix, name)); + return hash.digest('hex'); +}; + +const installedVersion = async () => { + for (const manifest of ['.cursor-plugin/plugin.json', 'plugin.json']) { + try { + const value = JSON.parse(await readFile(join(destination, manifest), 'utf8')); + if (typeof value.version === 'string') return value.version; + } catch (error) { if (error?.code !== 'ENOENT') throw error; } + } + return undefined; +}; + +if (!(await exists(cursorRoot)) || !(await lstat(cursorRoot)).isDirectory()) { + throw new Error(`Cursor is not installed in ${cursorRoot}.`); +} +await mkdir(installRoot, { recursive: true }); +if (await exists(destination)) { + const currentVersion = await installedVersion(); + if (currentVersion !== undefined && currentVersion !== pluginVersion) { + throw new Error(`Refusing version collision at ${destination}: found ${currentVersion}, requested ${pluginVersion}.`); + } + if (source === destination || await treeHash(source) === await treeHash(destination)) { + console.log(`Already installed ${pluginName}@${pluginVersion} at ${destination}`); + process.exit(0); + } + throw new Error(`Refusing content collision at ${destination}.`); +} + +const stageParent = await mkdtemp(join(installRoot, `.${basename(destination)}.stage-`)); +const stage = join(stageParent, 'bundle'); +try { + await cp(source, stage, { errorOnExist: true, force: false, recursive: true, verbatimSymlinks: true }); + await treeHash(stage); + await rename(stage, destination); + console.log(`Installed ${pluginName}@${pluginVersion} at ${destination}`); +} finally { + await rm(stageParent, { force: true, recursive: true }); +} diff --git a/examples/hooks-and-scripts/artifact/portable/plugin.json b/examples/hooks-and-scripts/artifact/portable/plugin.json new file mode 100644 index 000000000..2f19512e9 --- /dev/null +++ b/examples/hooks-and-scripts/artifact/portable/plugin.json @@ -0,0 +1 @@ +{"$schema":"https://agent-plugins.org/schemas/1.0.0/plugin.schema.json","description":"Hook simulation, script traces, logs, and recovery.","name":"hooks-and-scripts","version":"1.0.0"} diff --git a/examples/hooks-and-scripts/artifact/portable/scripts/detect-risk.mjs b/examples/hooks-and-scripts/artifact/portable/scripts/detect-risk.mjs new file mode 100644 index 000000000..99bd912f8 --- /dev/null +++ b/examples/hooks-and-scripts/artifact/portable/scripts/detect-risk.mjs @@ -0,0 +1,35 @@ +import { readFile } from "node:fs/promises"; + + + + + +const registerPath = new URL('../assets/release/risk-register.json', import.meta.url); +const main = async ()=>{ + try { + const register = JSON.parse(await readFile(registerPath, 'utf8')); + if (!Array.isArray(register.risks)) throw new Error('risk register must contain a risks array'); + const blockers = register.risks.filter((risk)=>risk.status === 'open' && risk.severity === 'high'); + if (blockers.length === 0) { + process.stdout.write('No open high-severity release risks found.\n'); + return 0; + } + for (const risk of blockers){ + process.stderr.write(`${typeof risk.id === 'string' ? risk.id : 'UNIDENTIFIED'}: ${typeof risk.summary === 'string' ? risk.summary : 'Open high-severity release risk'}\n`); + } + return 2; + } catch (error) { + process.stderr.write(`Unable to detect release risks: ${error instanceof Error ? error.message : String(error)}\n`); + return 1; + } +}; + + +const detect_risk_entry_main = main; +if (typeof detect_risk_entry_main !== 'function') { + throw new TypeError('Executable entry must export a main function: ' + "/fast/projects/agent-bundle-worktrees/host-test/examples/hooks-and-scripts/src/scripts/detect-risk.ts"); +} +const code = await detect_risk_entry_main(process.argv.slice(2)); +if (typeof code === 'number') process.exitCode = code; + +export {}; diff --git a/examples/hooks-and-scripts/artifact/portable/scripts/verify-release.mjs b/examples/hooks-and-scripts/artifact/portable/scripts/verify-release.mjs new file mode 100644 index 000000000..6ac9cd7a9 --- /dev/null +++ b/examples/hooks-and-scripts/artifact/portable/scripts/verify-release.mjs @@ -0,0 +1,54 @@ +import { readFile } from "node:fs/promises"; + + + + + +const requiredArtifacts = [ + 'package', + 'checksums', + 'sbom' +]; +const manifestPath = new URL('../assets/release/release-manifest.json', import.meta.url); +const readManifest = async ()=>JSON.parse(await readFile(manifestPath, 'utf8')); +const validationErrors = (manifest)=>{ + const errors = []; + if (typeof manifest.version !== 'string' || !/^\d+\.\d+\.\d+$/.test(manifest.version)) { + errors.push('version must use major.minor.patch format'); + } + if (typeof manifest.changelog !== 'string' || manifest.changelog.trim().length === 0) { + errors.push('changelog must identify the release notes'); + } + for (const name of requiredArtifacts){ + const artifact = manifest.artifacts?.find((candidate)=>candidate.name === name); + if (artifact === undefined || typeof artifact.path !== 'string' || artifact.path.trim().length === 0 || artifact.status !== 'ready') { + errors.push(`${name} artifact must have a ready path`); + } + } + return errors; +}; +const main = async ()=>{ + try { + const manifest = await readManifest(); + const errors = validationErrors(manifest); + if (errors.length > 0) { + process.stderr.write(`Release manifest is incomplete:\n${errors.map((error)=>`- ${error}`).join('\n')}\n`); + return 1; + } + process.stdout.write(`Release ${manifest.version} is ready for packaging.\n`); + return 0; + } catch (error) { + process.stderr.write(`Unable to verify release manifest: ${error instanceof Error ? error.message : String(error)}\n`); + return 1; + } +}; + + +const verify_release_entry_main = main; +if (typeof verify_release_entry_main !== 'function') { + throw new TypeError('Executable entry must export a main function: ' + "/fast/projects/agent-bundle-worktrees/host-test/examples/hooks-and-scripts/src/scripts/verify-release.ts"); +} +const code = await verify_release_entry_main(process.argv.slice(2)); +if (typeof code === 'number') process.exitCode = code; + +export {}; diff --git a/examples/host-test/probe-note.txt b/examples/host-test/probe-note.txt new file mode 100644 index 000000000..65d6fd4e6 --- /dev/null +++ b/examples/host-test/probe-note.txt @@ -0,0 +1 @@ +host-test diff --git a/examples/host-test/scripts/mock-anthropic.mjs b/examples/host-test/scripts/mock-anthropic.mjs new file mode 100644 index 000000000..3d10a55f4 --- /dev/null +++ b/examples/host-test/scripts/mock-anthropic.mjs @@ -0,0 +1,159 @@ +// A scripted Anthropic Messages API stand-in so a REAL Claude Code process can +// drive the host-test scenario without an account: Claude Code is the host under +// test; only the model is scripted (root: pwd, write, dump, probe, one Agent; +// subagent: pwd, dump, probe, one nested Agent; nested: pwd, probe). Used by +// `probe.mjs capture claude --scripted-model`; standalone usage: +// node mock-anthropic.mjs [logfile] +// then run claude with ANTHROPIC_BASE_URL=http://127.0.0.1: ANTHROPIC_API_KEY=mock. +import { appendFileSync } from 'node:fs'; +import { createServer } from 'node:http'; + +const port = Number(process.argv[2] ?? 8790); +const logFile = process.argv[3]; +const log = (line) => { if (logFile) appendFileSync(logFile, `${line}\n`); }; + +const readBody = (request) => new Promise((resolve) => { + let body = ''; + request.on('data', (chunk) => { body += chunk; }); + request.on('end', () => resolve(body)); +}); + +const textOf = (content) => typeof content === 'string' + ? content + : (content ?? []).map((block) => block.type === 'text' ? block.text : block.type === 'tool_result' ? JSON.stringify(block.content ?? '') : '').join('\n'); + +const role = (messages) => { + const content = messages[0]?.content ?? ''; + const blocks = typeof content === 'string' ? [content] : content.filter((block) => block.type === 'text').map((block) => block.text); + if (blocks.some((text) => text.trimStart().startsWith('NESTED_PROBE_SCENARIO'))) return 'nested'; + if (blocks.some((text) => text.trimStart().startsWith('SUBAGENT_PROBE_SCENARIO'))) return 'subagent'; + if (blocks.some((text) => text.includes('exercising the host-test probe'))) return 'root'; + return 'other'; +}; + +const toolUseCount = (messages) => messages + .filter((message) => message.role === 'assistant' && Array.isArray(message.content)) + .reduce((count, message) => count + message.content.filter((block) => block.type === 'tool_use').length, 0); + +const findTool = (tools, matcher) => tools.find((tool) => matcher(tool.name))?.name; + +const scriptFor = (kind, tools) => { + const bash = findTool(tools, (name) => name === 'Bash'); + const write = findTool(tools, (name) => name === 'Write'); + const dump = findTool(tools, (name) => /host-test__dump$/u.test(name)); + const probe = findTool(tools, (name) => /host-test-raw__probe$/u.test(name)); + const task = findTool(tools, (name) => name === 'Task' || name === 'Agent'); + const step = (name, input) => name === undefined ? undefined : { input, name }; + switch (kind) { + case 'root': + return [ + step(bash, { command: 'pwd' }), + step(write, { content: 'host-test\n', file_path: `${process.env.PROBE_WORKSPACE ?? process.cwd()}/probe-note.txt` }), + step(dump, {}), + step(probe, { note: 'root' }), + step(task, { + description: 'host-test subagent probe', + prompt: 'SUBAGENT_PROBE_SCENARIO: run `pwd`, call the host-test dump tool with {}, call the host-test-raw probe tool with {"note":"subagent"}, spawn a nested subagent with NESTED_PROBE_SCENARIO if you can, then reply with every id you saw.', + subagent_type: 'general-purpose', + }), + ].filter(Boolean); + case 'subagent': + return [ + step(bash, { command: 'pwd' }), + step(dump, {}), + step(probe, { note: 'subagent' }), + step(task, { + description: 'nested host-test probe', + prompt: 'NESTED_PROBE_SCENARIO: run `pwd`, call the host-test-raw probe tool with {"note":"nested"}, then reply with every id you saw.', + subagent_type: 'general-purpose', + }), + ].filter(Boolean); + case 'nested': + return [ + step(bash, { command: 'pwd' }), + step(probe, { note: 'nested' }), + ].filter(Boolean); + default: + return []; + } +}; + +const finalText = (kind) => { + switch (kind) { + case 'root': return 'HOST_TEST_DONE (mock model; see the probe log path in the dump result)'; + case 'subagent': return 'SUBAGENT_DONE: reported every id from the dump and probe results above.'; + case 'nested': return 'NESTED_DONE: reported every id from the probe result above.'; + default: return 'ok'; + } +}; + +const sse = (response, event, data) => { + response.write(`event: ${event}\ndata: ${JSON.stringify(data)}\n\n`); +}; + +let messageCounter = 0; + +const respond = (response, body, stream) => { + const messages = body.messages ?? []; + const kind = role(messages); + const tools = body.tools ?? []; + const script = scriptFor(kind, tools); + const index = toolUseCount(messages); + const next = script[index]; + const id = `msg_mock_${String(++messageCounter).padStart(4, '0')}`; + log(JSON.stringify({ kind, model: body.model, step: index, tool: next?.name ?? 'text', toolCount: tools.length, toolNames: tools.map((tool) => tool.name).filter((name) => /host-test|Task|Agent|Bash|Write/u.test(name)), ...(kind === 'other' ? { first: JSON.stringify(messages[0]?.content).slice(0, 600), system: JSON.stringify(body.system).slice(0, 300) } : {}) })); + const content = next === undefined + ? [{ text: finalText(kind), type: 'text' }] + : [{ id: `toolu_mock_${String(messageCounter)}`, input: next.input, name: next.name, type: 'tool_use' }]; + const stopReason = next === undefined ? 'end_turn' : 'tool_use'; + const message = { + content, + id, + model: body.model, + role: 'assistant', + stop_reason: stopReason, + stop_sequence: null, + type: 'message', + usage: { input_tokens: 10, output_tokens: 10 }, + }; + if (!stream) { + response.writeHead(200, { 'content-type': 'application/json' }); + response.end(JSON.stringify(message)); + return; + } + response.writeHead(200, { 'cache-control': 'no-cache', 'content-type': 'text/event-stream' }); + sse(response, 'message_start', { message: { ...message, content: [], stop_reason: null, usage: { input_tokens: 10, output_tokens: 1 } }, type: 'message_start' }); + const block = content[0]; + if (block.type === 'text') { + sse(response, 'content_block_start', { content_block: { text: '', type: 'text' }, index: 0, type: 'content_block_start' }); + sse(response, 'content_block_delta', { delta: { text: block.text, type: 'text_delta' }, index: 0, type: 'content_block_delta' }); + } else { + sse(response, 'content_block_start', { content_block: { id: block.id, input: {}, name: block.name, type: 'tool_use' }, index: 0, type: 'content_block_start' }); + sse(response, 'content_block_delta', { delta: { partial_json: JSON.stringify(block.input), type: 'input_json_delta' }, index: 0, type: 'content_block_delta' }); + } + sse(response, 'content_block_stop', { index: 0, type: 'content_block_stop' }); + sse(response, 'message_delta', { delta: { stop_reason: stopReason, stop_sequence: null }, type: 'message_delta', usage: { output_tokens: 10 } }); + sse(response, 'message_stop', { type: 'message_stop' }); + response.end(); +}; + +createServer(async (request, response) => { + const url = new URL(request.url ?? '/', 'http://localhost'); + const raw = await readBody(request); + if (url.pathname.endsWith('/messages/count_tokens')) { + response.writeHead(200, { 'content-type': 'application/json' }); + response.end(JSON.stringify({ input_tokens: 100 })); + return; + } + if (url.pathname.endsWith('/v1/messages')) { + let body; + try { body = JSON.parse(raw); } catch { body = {}; } + respond(response, body, body.stream === true); + return; + } + log(JSON.stringify({ other: `${request.method} ${url.pathname}` })); + response.writeHead(404, { 'content-type': 'application/json' }); + response.end(JSON.stringify({ error: { message: `mock: no route for ${url.pathname}`, type: 'not_found_error' }, type: 'error' })); +}).listen(port, '127.0.0.1', () => { + console.log(`mock anthropic listening on http://127.0.0.1:${String(port)}`); +}); diff --git a/examples/host-test/scripts/probe.mjs b/examples/host-test/scripts/probe.mjs index de1cdd3aa..2a2768dd6 100644 --- a/examples/host-test/scripts/probe.mjs +++ b/examples/host-test/scripts/probe.mjs @@ -4,10 +4,10 @@ // uninstall. Nothing here touches the real ~/.claude, ~/.codex, or ~/.cursor. // // node scripts/probe.mjs install [--no-auth] [--root ] -// node scripts/probe.mjs capture [--prompt ] [--model ] [--timeout ] +// node scripts/probe.mjs capture [--prompt ] [--model ] [--timeout ] [--scripted-model] // node scripts/probe.mjs uninstall [--keep-home] // node scripts/probe.mjs status -import { spawnSync } from 'node:child_process'; +import { spawn, spawnSync } from 'node:child_process'; import { copyFileSync, existsSync, mkdirSync, readFileSync, rmSync, statSync, writeFileSync } from 'node:fs'; import { homedir } from 'node:os'; import { dirname, join, resolve } from 'node:path'; @@ -31,6 +31,7 @@ const parseArgs = (argv) => { case '--prompt': flags.prompt = rest[++index]; break; case '--model': flags.model = rest[++index]; break; case '--timeout': flags.timeout = Number(rest[++index]); break; + case '--scripted-model': flags.scriptedModel = true; break; default: throw new Error(`Unknown flag ${flag}`); } } @@ -218,16 +219,43 @@ const scenarioPrompt = () => flags.prompt ?? [ '6. Reply with exactly one final line: HOST_TEST_DONE ', ].join('\n'); +/** + * With --scripted-model the real Claude Code binary talks to a local scripted + * Messages API (scripts/mock-anthropic.mjs) instead of Anthropic, so the hook, + * MCP, and subagent plumbing under test is the host's own while no account is + * needed; the model text in the transcript is then not evidence of anything. + */ const captureClaude = () => { + const scripted = flags.scriptedModel === true; const args = [ - '-p', scenarioPrompt(), + '-p', scripted ? 'You are exercising the host-test probe plugin. Do the scripted steps.' : scenarioPrompt(), '--output-format', 'json', '--dangerously-skip-permissions', - '--model', flags.model ?? 'sonnet', + '--model', flags.model ?? (scripted ? 'claude-sonnet-4-5' : 'sonnet'), ]; - log(`claude ${args.slice(2).join(' ')}`); - const result = run('claude', args, { cwd: paths.workspace, timeout: flags.timeout ?? 900_000 }); - return result; + const port = 8790 + Math.floor(Math.random() * 100); + const mock = scripted + ? spawn(process.execPath, [join(exampleRoot, 'scripts', 'mock-anthropic.mjs'), String(port), join(paths.captures, 'scripted-model.log')], { stdio: 'ignore' }) + : undefined; + const environment = { + ...isolatedEnvironment(), + ...(scripted + ? { + ANTHROPIC_API_KEY: 'scripted-model', + ANTHROPIC_BASE_URL: `http://127.0.0.1:${String(port)}`, + CLAUDE_CODE_DISABLE_NONESSENTIAL_TRAFFIC: '1', + DISABLE_TELEMETRY: '1', + PROBE_WORKSPACE: paths.workspace, + } + : {}), + }; + log(`claude ${args.slice(2).join(' ')}${scripted ? ` (scripted model on 127.0.0.1:${String(port)})` : ''}`); + try { + if (mock !== undefined) spawnSync(process.execPath, ['-e', 'setTimeout(() => process.exit(0), 800)']); + return run('claude', args, { cwd: paths.workspace, env: environment, timeout: flags.timeout ?? 900_000 }); + } finally { + mock?.kill(); + } }; const captureCodex = () => { diff --git a/examples/host-test/src/dump.ts b/examples/host-test/src/dump.ts index 2a392af7b..cc5abb705 100644 --- a/examples/host-test/src/dump.ts +++ b/examples/host-test/src/dump.ts @@ -138,8 +138,8 @@ export const renderDumpMarkdown = (result: DumpResult): string => { : `unavailable (${result.state.reason ?? 'unknown'})`}`, `- Matched: ${String(result.matched)}${result.filter.conversation === undefined ? '' : ` for ${result.filter.conversation}`}`, '', - '| # | kind | event | host | runtime | ids |', - '| --- | --- | --- | --- | --- | --- |', + '| # | kind | event | host | runtime | lineage | ids |', + '| --- | --- | --- | --- | --- | --- | --- |', ]; for (const record of result.records) { const summary = record as Partial> & { readonly ids?: JsonObject }; @@ -147,7 +147,17 @@ export const renderDumpMarkdown = (result: DumpResult): string => { .filter(([key]) => key !== 'cwd' && key !== 'hook_event_name' && key !== 'transcript_path' && key !== 'agent_transcript_path') .map(([key, value]) => `${key}=${String(value)}`) .join(', '); - lines.push(`| ${String(summary.index ?? '')} | ${String(summary.kind ?? '')} | ${String(summary.event ?? summary.nativeEvent ?? '')} | ${String(summary.host ?? '')} | ${String(summary.runtime ?? '')} | ${ids} |`); + lines.push(`| ${String(summary.index ?? '')} | ${String(summary.kind ?? '')} | ${String(summary.event ?? summary.nativeEvent ?? '')} | ${String(summary.host ?? '')} | ${String(summary.runtime ?? '')} | ${renderLineage(summary.lineage)} | ${ids} |`); } return lines.join('\n'); }; + +/** One cell: `depth N · (resolution)` or the typed unavailable reason. */ +export const renderLineage = (lineage: JsonValue | undefined): string => { + if (lineage === undefined || lineage === null || typeof lineage !== 'object' || Array.isArray(lineage)) return 'not recorded'; + const observed = lineage as { readonly state?: string; readonly reason?: string; readonly value?: JsonValue }; + if (observed.state !== 'available') return `unavailable · ${observed.reason ?? 'unknown'}`; + const value = (observed.value ?? {}) as { readonly conversation?: string; readonly depth?: number; readonly parent?: string; readonly resolution?: string; readonly root?: string }; + const parent = value.parent === undefined ? '' : ` ← ${value.parent}`; + return `depth ${String(value.depth ?? '?')} · ${value.conversation ?? '?'}${parent} (${value.resolution ?? '?'})`; +}; diff --git a/examples/mcp-app/artifact/agent-bundle.hooks.json b/examples/mcp-app/artifact/agent-bundle.hooks.json new file mode 100644 index 000000000..c41cd4504 --- /dev/null +++ b/examples/mcp-app/artifact/agent-bundle.hooks.json @@ -0,0 +1 @@ +{"hooks":[{"event":"sessionStart","id":"hook:session-start:session-start:7ab7e8a5","name":"session-start-session-start-7ab7e8a5","path":"claude/hooks/session-start-session-start-7ab7e8a5.mjs","target":"claude"},{"event":"sessionStart","id":"hook:session-start:session-start:7ab7e8a5","name":"session-start-session-start-7ab7e8a5","path":"codex/hooks/session-start-session-start-7ab7e8a5.mjs","target":"codex"}]} diff --git a/examples/mcp-app/artifact/agent-bundle.manifest.json b/examples/mcp-app/artifact/agent-bundle.manifest.json new file mode 100644 index 000000000..949cf5538 --- /dev/null +++ b/examples/mcp-app/artifact/agent-bundle.manifest.json @@ -0,0 +1 @@ +{"agentSkills":{"schemaSha256":"6d06b61e423317421de2295ea1fd0c7b4491bfa36c5b7705c28616dfe76d4047","sourceRevision":"69ef37e9424c0a7ea9dd2293b559e43ec8176379","specification":"https://raw.githubusercontent.com/agentskills/agentskills/69ef37e9424c0a7ea9dd2293b559e43ec8176379/docs/specification.mdx"},"files":[{"bytes":412,"kind":"generated","path":"agent-bundle.hooks.json","sha256":"c085b5d4bc728917cba2d53546cdd9f6b065f9e84a846d31d3e4ccb254f5819a","sourceInputs":["agent-bundle.config.ts"]},{"bytes":353,"kind":"generated","path":"claude/.claude-plugin/marketplace.json","sha256":"e4cf51c12ad7b9c9c78c3ae09e1564bff251152d162cd562247e8f5dca5868a7","sourceInputs":["agent-bundle.config.ts"]},{"bytes":214,"kind":"generated","path":"claude/.claude-plugin/plugin.json","sha256":"20bca77e21ea7fbb9ceb1c1fd0c06b7bd67216a20d8a9922fab5ad8f915e5604","sourceInputs":["agent-bundle.config.ts","src/mcp/status.ts","src/skills/service-readiness/SKILL.md"]},{"bytes":180,"kind":"generated","path":"claude/.mcp.json","sha256":"f7d402486d6d2de1fbbf6d95183a7f16aaed23f1b4b625c4075e3a67d11458aa","sourceInputs":["agent-bundle.config.ts","src/mcp/status.ts"]},{"bytes":231,"kind":"copy","path":"claude/assets/evals/fixtures/status/result.json","sha256":"f9a03542d74a4f7e3ecac0ea161b820f0dcbbdfc4c1db3889401064653bd9811","sourceInputs":["evals/fixtures/status/result.json"]},{"bytes":150,"kind":"generated","path":"claude/hooks/hooks.json","sha256":"8855c477158d687920a5d1da416ee8c980cc305f3adde65488dcef55e8b8da06","sourceInputs":["agent-bundle.config.ts"]},{"bytes":12031,"kind":"bundle","path":"claude/hooks/session-start-session-start-7ab7e8a5.mjs","sha256":"29d109b65676b38ff7c54a26bb90b6346e3dc110ce8a781dfb71be8c0439c4a1","sourceInputs":["agent-bundle.config.ts","src/hooks/session-start.ts"]},{"bytes":472,"kind":"generated","path":"claude/INSTALL.md","sha256":"84f35da9c85137d58c7ea6e458c1794e3396d95e709a2dde0784014ca784bb1b","sourceInputs":["agent-bundle.config.ts"]},{"bytes":1211760,"kind":"bundle","path":"claude/mcp/mcp-status-073c1634.mjs","sha256":"80aa4516620d80e170e0ead5efcf49b7ea910a9dd36fed2a0f8e7f9f3e52c406","sourceInputs":["src/compiler-status-contract.ts","src/mcp/status.ts"]},{"bytes":2328,"kind":"bundle","path":"claude/scripts/check-service-fixture.mjs","sha256":"41067e3d875b6ae452b21ba105d032e3c8ca3eec81463803798a1e9f13b50935","sourceInputs":["agent-bundle.config.ts","src/compiler-status-contract.ts","src/scripts/check-service-fixture.ts"]},{"bytes":528,"kind":"copy","path":"claude/skills/service-readiness/assets/readiness-report.md","sha256":"772e118b18070497c0f589bc4f9b37c71ade5ce59ba4a6904c65b2b724f8714b","sourceInputs":["src/skills/service-readiness/assets/readiness-report.md","src/skills/service-readiness/SKILL.md"]},{"bytes":904,"kind":"copy","path":"claude/skills/service-readiness/references/status-policy.md","sha256":"0319ad5884b291b01433d559429dcdb5d265bc5715b3c7bff734afa257ebef5b","sourceInputs":["src/skills/service-readiness/references/status-policy.md","src/skills/service-readiness/SKILL.md"]},{"bytes":1344,"kind":"copy","path":"claude/skills/service-readiness/SKILL.md","sha256":"de9bebc358e0ba30d769d7e9bad6175251a858efe4e704941f9ef6dc830261f3","sourceInputs":["src/skills/service-readiness/SKILL.md"]},{"bytes":258,"kind":"generated","path":"codex/.agents/plugins/marketplace.json","sha256":"c8b0fe73ece00cbf09fed92e1011d2d5e28211c7e7f4dfa1fddf3fba4c462b0a","sourceInputs":["agent-bundle.config.ts"]},{"bytes":674,"kind":"generated","path":"codex/.codex-plugin/plugin.json","sha256":"8dd1d6259f076f8f62cd35bb7c466c3dec95aeb4433416f4e52202f56673c11e","sourceInputs":["agent-bundle.config.ts","src/mcp/status.ts","src/skills/service-readiness/SKILL.md"]},{"bytes":152,"kind":"generated","path":"codex/.mcp.json","sha256":"62064b39f8cddd0db51b7aa25a688bbff3ae7621376be506ff5d5542b037c9de","sourceInputs":["agent-bundle.config.ts","src/mcp/status.ts"]},{"bytes":231,"kind":"copy","path":"codex/assets/evals/fixtures/status/result.json","sha256":"f9a03542d74a4f7e3ecac0ea161b820f0dcbbdfc4c1db3889401064653bd9811","sourceInputs":["evals/fixtures/status/result.json"]},{"bytes":143,"kind":"generated","path":"codex/hooks/hooks.json","sha256":"ad0e296b15c799f52459488b17f46f7cc3a34e1abf4b9466a178d17a7fdaa605","sourceInputs":["agent-bundle.config.ts"]},{"bytes":12174,"kind":"bundle","path":"codex/hooks/session-start-session-start-7ab7e8a5.mjs","sha256":"c91fb5cdbde27b34f97f9ba62e7b897bf337eda7e2086f98c9f300f6eab89102","sourceInputs":["agent-bundle.config.ts","src/hooks/session-start.ts"]},{"bytes":360,"kind":"generated","path":"codex/INSTALL.md","sha256":"4efefa497a9acdd073703dfc3ff2c81cd5005cea0f777a204a275988193c907f","sourceInputs":["agent-bundle.config.ts"]},{"bytes":1211760,"kind":"bundle","path":"codex/mcp/mcp-status-073c1634.mjs","sha256":"80aa4516620d80e170e0ead5efcf49b7ea910a9dd36fed2a0f8e7f9f3e52c406","sourceInputs":["src/compiler-status-contract.ts","src/mcp/status.ts"]},{"bytes":2328,"kind":"bundle","path":"codex/scripts/check-service-fixture.mjs","sha256":"41067e3d875b6ae452b21ba105d032e3c8ca3eec81463803798a1e9f13b50935","sourceInputs":["agent-bundle.config.ts","src/compiler-status-contract.ts","src/scripts/check-service-fixture.ts"]},{"bytes":528,"kind":"copy","path":"codex/skills/service-readiness/assets/readiness-report.md","sha256":"772e118b18070497c0f589bc4f9b37c71ade5ce59ba4a6904c65b2b724f8714b","sourceInputs":["src/skills/service-readiness/assets/readiness-report.md","src/skills/service-readiness/SKILL.md"]},{"bytes":904,"kind":"copy","path":"codex/skills/service-readiness/references/status-policy.md","sha256":"0319ad5884b291b01433d559429dcdb5d265bc5715b3c7bff734afa257ebef5b","sourceInputs":["src/skills/service-readiness/references/status-policy.md","src/skills/service-readiness/SKILL.md"]},{"bytes":1344,"kind":"copy","path":"codex/skills/service-readiness/SKILL.md","sha256":"de9bebc358e0ba30d769d7e9bad6175251a858efe4e704941f9ef6dc830261f3","sourceInputs":["src/skills/service-readiness/SKILL.md"]},{"bytes":231,"kind":"copy","path":"portable/assets/evals/fixtures/status/result.json","sha256":"f9a03542d74a4f7e3ecac0ea161b820f0dcbbdfc4c1db3889401064653bd9811","sourceInputs":["evals/fixtures/status/result.json"]},{"bytes":701,"kind":"generated","path":"portable/INSTALL.md","sha256":"be9540f5b8012f6a7963532282469fa34119537a7203237fb18fd0b09f1710e3","sourceInputs":["agent-bundle.config.ts"]},{"bytes":3309,"kind":"generated","path":"portable/install.mjs","sha256":"971868b98246361915db7b21461b3cb105cc02bc0c163b70acaef9d89d0f9d6b","sourceInputs":["agent-bundle.config.ts"]},{"bytes":447791,"kind":"bundle","path":"portable/mcp-apps/status.html","sha256":"33d62b8fb201360c8a2493934f8fa23eb799ad87c9c04a01a95cccdfe04e557d","sourceInputs":["agent-bundle.config.ts","views/status-panel.html","views/status-panel.ts"]},{"bytes":242,"kind":"generated","path":"portable/mcp.json","sha256":"79461543b66617388e3ead6b60c90576ee9ed9be17d4e19e2febf58b872e05e3","sourceInputs":["src/mcp/status.ts"]},{"bytes":1674914,"kind":"bundle","path":"portable/mcp/mcp-status-073c1634.mjs","sha256":"65be2e5694b954fd3743e7ca9ceda97071c2d775269a900c6394ed6a0bad9849","sourceInputs":["agent-bundle.config.ts","src/compiler-status-contract.ts","src/mcp/status.ts","views/status-panel.html","views/status-panel.ts"]},{"bytes":220,"kind":"generated","path":"portable/plugin.json","sha256":"e0e8d291a995eece0fdaf1200e86cd06089c219f1c74cbc55241b89e93fa72f3","sourceInputs":["agent-bundle.config.ts"]},{"bytes":2328,"kind":"bundle","path":"portable/scripts/check-service-fixture.mjs","sha256":"41067e3d875b6ae452b21ba105d032e3c8ca3eec81463803798a1e9f13b50935","sourceInputs":["agent-bundle.config.ts","src/compiler-status-contract.ts","src/scripts/check-service-fixture.ts"]},{"bytes":528,"kind":"copy","path":"portable/skills/service-readiness/assets/readiness-report.md","sha256":"772e118b18070497c0f589bc4f9b37c71ade5ce59ba4a6904c65b2b724f8714b","sourceInputs":["src/skills/service-readiness/assets/readiness-report.md","src/skills/service-readiness/SKILL.md"]},{"bytes":904,"kind":"copy","path":"portable/skills/service-readiness/references/status-policy.md","sha256":"0319ad5884b291b01433d559429dcdb5d265bc5715b3c7bff734afa257ebef5b","sourceInputs":["src/skills/service-readiness/references/status-policy.md","src/skills/service-readiness/SKILL.md"]},{"bytes":1344,"kind":"copy","path":"portable/skills/service-readiness/SKILL.md","sha256":"de9bebc358e0ba30d769d7e9bad6175251a858efe4e704941f9ef6dc830261f3","sourceInputs":["src/skills/service-readiness/SKILL.md"]}],"producer":{"name":"agent-bundle","version":"0.1.0"},"project":{"configDigest":"c6ec1f92b7f7f28c7eb485b9ad22b0fdda89ea63e58166a27b9969d0243cef89","configPath":"agent-bundle.config.ts","modelDigest":"8551c2c0a6630de6e3366155442b9919259fbf3331245219ad6e6dc4549069b3","packageName":"@agent-bundle-example/mcp-app","revision":"914a0ee2dcafedf9136a1c3a3885150f98313a6d4035e8c1e9f9e13a86083c13","sourceInputs":[{"executable":false,"path":"agent-bundle.config.ts","sha256":"c6ec1f92b7f7f28c7eb485b9ad22b0fdda89ea63e58166a27b9969d0243cef89"},{"executable":false,"path":"evals/fixtures/status/result.json","sha256":"f9a03542d74a4f7e3ecac0ea161b820f0dcbbdfc4c1db3889401064653bd9811"},{"executable":false,"path":"evals/graders/status-result.ts","sha256":"b846dd661ff5f9af9dd15df7a2208344c13c6153514c9435a585a0caa820ebaf"},{"executable":false,"path":"evals/status.eval.ts","sha256":"ad0f9f1e216aec4684b4b51e337387b893c978e827ae8c5edf2ea41dfdf82207"},{"executable":false,"path":"package.json","sha256":"29ef79c4d6f863920649fd6162611a6344b1e4fd8a068c64229aa321be1d9cc3"},{"executable":false,"path":"README.md","sha256":"35e3f3656ce34c5ed1181917ecebc40d10ec3f121630ade7ff7db7093e2db6df"},{"executable":false,"path":"rstest.browser-app.config.ts","sha256":"e2de9384badc7c4fb6b89ea5b54ed85fd3cacbe9e31162555362d0c89a318557"},{"executable":false,"path":"src/compiler-status-contract.ts","sha256":"ff8484b2ae613abb1cf2f76c70f558733563228570df1c05485a3a04ebffcd59"},{"executable":false,"path":"src/hooks/session-start.ts","sha256":"b856621ec280ed94a8e1dfa0fe065a1ff4d41690ff07be9e148c01b1180fd346"},{"executable":false,"path":"src/mcp/status.ts","sha256":"9116902d7041d30b4c3fcb412b2d83a793975fdac9632648e07dfc85da2a73c1"},{"executable":false,"path":"src/scripts/check-service-fixture.ts","sha256":"32967d447487049c62af2195612ec6f2b5de630753ea2c20b473faf93e804fba"},{"executable":false,"path":"src/skills/service-readiness/assets/readiness-report.md","sha256":"772e118b18070497c0f589bc4f9b37c71ade5ce59ba4a6904c65b2b724f8714b"},{"executable":false,"path":"src/skills/service-readiness/references/status-policy.md","sha256":"0319ad5884b291b01433d559429dcdb5d265bc5715b3c7bff734afa257ebef5b"},{"executable":false,"path":"src/skills/service-readiness/SKILL.md","sha256":"de9bebc358e0ba30d769d7e9bad6175251a858efe4e704941f9ef6dc830261f3"},{"executable":false,"path":"tests/browser-app/status-panel.browser.test.ts","sha256":"a49e632decebd56db42214afc3f1cba8729c24b594935e4b2468e3a2d4ad6695"},{"executable":false,"path":"views/status-panel.html","sha256":"75018093566d7bfdf16dfffcc072d4983e0c2ecd5f40f592e27e571cb3e5a868"},{"executable":false,"path":"views/status-panel.ts","sha256":"3bd3017d4f4d730293b15f386c5949b390bc8bba1ed2c5fd861efed477afefc8"}]},"runtime":{"node":"22.12.0"},"targets":[{"adapterRevision":"1.22.0","name":"claude","observedVersion":"2.1.250","schemas":[{"name":"hooks","revision":"2.1.250","sha256":"3c6f3e4391f3dca939d75bd0b200ea88e68db939a2cb885d46f0b143293efb84"},{"name":"lsp","revision":"2.1.250","sha256":"c81fd2f57c410f70f8e5c3f84483f5ec1b575ee02802b424977826f757dccd8e"},{"name":"marketplace","revision":"2.1.250","sha256":"4ffa94e8024966e8080b9d3b338c9612bdfa255802a8491b43f74f90427bc988"},{"name":"mcp","revision":"2.1.250","sha256":"76ccf02c7bfe2d57945ba18e84da8d655529bd68b4d692f72bce28238c99067e"},{"name":"monitors","revision":"2.1.250","sha256":"d45abdf7561e4316ba217ce9c2ac84f32e1049622b74abb081693b479a54b48d"},{"name":"plugin","revision":"2.1.250","sha256":"3c9943237da86fd08ae82f698cde36dbef2ecf742098c6961cedf481fe435c12"},{"name":"settings","revision":"2.1.250","sha256":"9e86d8c5e4053e8de0e468d349e2c3dde5834d22d6769372b88570e301700073"},{"name":"theme","revision":"2.1.250","sha256":"721aa9b0bc7c60cd9359343e5c7205ffbdfea82da312f601720c9dfaa2d8cf0d"}]},{"adapterRevision":"1.8.0","name":"codex","observedVersion":"0.147.0","schemas":[{"name":"app","revision":"0.147.0","sha256":"01c720a645e437bf0c4f8c26fd4cb5a13988e5649e4a8562ee23a1d4b7355c6a"},{"name":"hooks","revision":"0.147.0","sha256":"175b859eb8e85bd287d85ee840d97c3f5c2d0dda3223507a796d158e3770eeba"},{"name":"marketplace","revision":"0.147.0","sha256":"fbccce3ade39e1b077fcb440e60260de6e811e8c2d222b2ae0fe8fe47706b470"},{"name":"mcp","revision":"0.147.0","sha256":"75bd50f9fcb85c2e8d43bc132d61c172a02f28ea8bb77389816ae77b14a4257e"},{"name":"plugin","revision":"0.147.0","sha256":"4ad476545c96c83d899c4524dcccd4eb4fe7d3299c307878a0cd46a237f48d58"}]},{"adapterRevision":"1.6.0","name":"portable","observedVersion":"1.0.0","schemas":[{"name":"mcp","revision":"1.0.0","sha256":"6539175bfcdf43085855183e86da40ea94b166547a72b47ae9a0a390516d3acb"},{"name":"plugin","revision":"1.0.0","sha256":"0a4aad95ce337878ad38802ebf0daa3fde76abe3f65400c86bcbb1ec0b3ab883"}]}],"validation":{"artifact":{"status":"passed"},"source":{"status":"passed"},"targets":[{"name":"claude","status":"passed"},{"name":"codex","status":"passed"},{"name":"portable","status":"passed"}]}} diff --git a/examples/mcp-app/artifact/claude/.claude-plugin/marketplace.json b/examples/mcp-app/artifact/claude/.claude-plugin/marketplace.json new file mode 100644 index 000000000..d24f68ca5 --- /dev/null +++ b/examples/mcp-app/artifact/claude/.claude-plugin/marketplace.json @@ -0,0 +1 @@ +{"description":"A unified service-readiness assistant with MCP, Skills, Hooks, scripts, and evaluation.","name":"mcp-app-example-marketplace","owner":{"name":"mcp-app-example"},"plugins":[{"description":"A unified service-readiness assistant with MCP, Skills, Hooks, scripts, and evaluation.","name":"mcp-app-example","source":"./","version":"1.0.0"}]} diff --git a/examples/mcp-app/artifact/claude/.claude-plugin/plugin.json b/examples/mcp-app/artifact/claude/.claude-plugin/plugin.json new file mode 100644 index 000000000..3a3e7a43d --- /dev/null +++ b/examples/mcp-app/artifact/claude/.claude-plugin/plugin.json @@ -0,0 +1 @@ +{"author":{"name":"mcp-app-example"},"description":"A unified service-readiness assistant with MCP, Skills, Hooks, scripts, and evaluation.","hooks":"./hooks/hooks.json","name":"mcp-app-example","version":"1.0.0"} diff --git a/examples/mcp-app/artifact/claude/.mcp.json b/examples/mcp-app/artifact/claude/.mcp.json new file mode 100644 index 000000000..a8c317b72 --- /dev/null +++ b/examples/mcp-app/artifact/claude/.mcp.json @@ -0,0 +1 @@ +{"mcpServers":{"status":{"args":["${CLAUDE_PLUGIN_ROOT}/mcp/mcp-status-073c1634.mjs"],"command":"node","env":{"AGENT_BUNDLE_PLUGIN_ROOT":"${CLAUDE_PLUGIN_ROOT}"},"type":"stdio"}}} diff --git a/examples/mcp-app/artifact/claude/INSTALL.md b/examples/mcp-app/artifact/claude/INSTALL.md new file mode 100644 index 000000000..b69cfdbf3 --- /dev/null +++ b/examples/mcp-app/artifact/claude/INSTALL.md @@ -0,0 +1,18 @@ +# Install mcp-app-example + +A unified service-readiness assistant with MCP, Skills, Hooks, scripts, and evaluation. + +Version: `1.0.0` + +Run these commands from this bundle directory. + +## Claude Code + +Claude Code installs this bundle through its local marketplace contract: + +```sh +claude plugin marketplace add ./ +claude plugin install mcp-app-example@mcp-app-example-marketplace --scope user +``` + +Replace `user` with `project` or `local` when that Claude scope is intended. diff --git a/examples/mcp-app/artifact/claude/assets/evals/fixtures/status/result.json b/examples/mcp-app/artifact/claude/assets/evals/fixtures/status/result.json new file mode 100644 index 000000000..a765aa4b5 --- /dev/null +++ b/examples/mcp-app/artifact/claude/assets/evals/fixtures/status/result.json @@ -0,0 +1,9 @@ +{ + "service": "compiler", + "status": "healthy", + "summary": "Compiler service is ready for release.", + "checks": [ + { "label": "Availability", "status": "passing" }, + { "label": "Build queue", "status": "passing" } + ] +} diff --git a/examples/mcp-app/artifact/claude/hooks/hooks.json b/examples/mcp-app/artifact/claude/hooks/hooks.json new file mode 100644 index 000000000..1afdaac5a --- /dev/null +++ b/examples/mcp-app/artifact/claude/hooks/hooks.json @@ -0,0 +1 @@ +{"hooks":{"SessionStart":[{"hooks":[{"command":"node \"${CLAUDE_PLUGIN_ROOT}/hooks/session-start-session-start-7ab7e8a5.mjs\"","type":"command"}]}]}} diff --git a/examples/mcp-app/artifact/claude/hooks/session-start-session-start-7ab7e8a5.mjs b/examples/mcp-app/artifact/claude/hooks/session-start-session-start-7ab7e8a5.mjs new file mode 100644 index 000000000..60c3d473d --- /dev/null +++ b/examples/mcp-app/artifact/claude/hooks/session-start-session-start-7ab7e8a5.mjs @@ -0,0 +1,253 @@ +// The require scope +var __webpack_require__ = {}; + +// webpack/runtime/define_property_getters +(() => { +__webpack_require__.d = (exports, getters, values) => { + var define = (defs, kind) => { + for(var key in defs) { + if(__webpack_require__.o(defs, key) && !__webpack_require__.o(exports, key)) { + Object.defineProperty(exports, key, { enumerable: true, [kind]: defs[key] }); + } + } + }; + define(getters, "get"); + define(values, "value"); +}; +})(); +// webpack/runtime/has_own_property +(() => { +__webpack_require__.o = (obj, prop) => (Object.prototype.hasOwnProperty.call(obj, prop)) +})(); +// webpack/runtime/make_namespace_object +(() => { +// define __esModule on exports +__webpack_require__.r = (exports) => { + if(typeof Symbol !== 'undefined' && Symbol.toStringTag) { + Object.defineProperty(exports, Symbol.toStringTag, { value: 'Module' }); + } + Object.defineProperty(exports, '__esModule', { value: true }); +}; +})(); + +// NAMESPACE OBJECT: ./src/hooks/session-start.ts +var session_start_namespaceObject = {}; +__webpack_require__.r(session_start_namespaceObject); +__webpack_require__.d(session_start_namespaceObject, { + "default": () => (session_start) }); + + +/* export default */ const session_start = ((event)=>({ + additionalContext: [ + `Service readiness session ${event.sessionId ?? 'is active'} from ${event.source ?? 'an unknown source'}.`, + `Use the service-readiness Skill, then run check-service-fixture from ${event.cwd ?? process.cwd()} before release review.`, + 'Use show-status for compiler or payments-api when live service evidence is needed.' + ].join(' '), + outcome: 'continue' + })); + + +const target = "claude"; +const canonicalEvent = "sessionStart"; +const nativeEvent = "SessionStart"; +const isRecord = (value)=>typeof value === "object" && value !== null && !Array.isArray(value); +const defined = (value)=>Object.fromEntries(Object.entries(value).filter(([, item])=>item !== undefined)); +const decodeClaudeNative = (nativeInput)=>({ + agentId: nativeInput.agent_id, + agentTranscriptPath: nativeInput.agent_transcript_path, + agentType: nativeInput.agent_type, + cwd: nativeInput.cwd, + effort: nativeInput.effort, + hookEventName: nativeInput.hook_event_name, + lastAssistantMessage: nativeInput.last_assistant_message, + model: nativeInput.model, + permissionMode: nativeInput.permission_mode, + promptId: nativeInput.prompt_id, + sessionId: nativeInput.session_id, + source: nativeInput.source, + stopHookActive: nativeInput.stop_hook_active, + toolInput: nativeInput.tool_input, + toolName: nativeInput.tool_name, + toolResponse: nativeInput.tool_response, + toolUseId: nativeInput.tool_use_id, + transcriptPath: nativeInput.transcript_path, + turnId: nativeInput.turn_id + }); +const encodeClaudeNative = (canonicalInput)=>defined({ + hook_event_name: nativeEvent, + agent_id: canonicalInput.agentId, + agent_transcript_path: canonicalInput.agentTranscriptPath, + agent_type: canonicalInput.agentType, + cwd: canonicalInput.cwd, + effort: canonicalInput.effort, + last_assistant_message: canonicalInput.lastAssistantMessage, + model: canonicalInput.model, + permission_mode: canonicalInput.permissionMode, + prompt_id: canonicalInput.promptId, + session_id: canonicalInput.sessionId, + source: canonicalInput.source, + stop_hook_active: canonicalInput.stopHookActive, + tool_input: canonicalInput.toolInput, + tool_name: canonicalInput.toolName, + tool_response: canonicalInput.toolResponse, + tool_use_id: canonicalInput.toolUseId, + transcript_path: canonicalInput.transcriptPath, + turn_id: canonicalInput.turnId + }); +const decodeNative = decodeClaudeNative; +const encodeNative = encodeClaudeNative; +const fail = (message)=>{ + throw new Error(`Agent Bundle hook error: ${message}`); +}; +const validateResult = (result)=>{ + if (result === undefined) return undefined; + if (!isRecord(result)) fail("handler must return void or a result object"); + const allowed = new Set([ + "outcome", + "reason", + "updatedInput", + "additionalContext" + ]); + for (const key of Object.keys(result))if (!allowed.has(key)) fail(`handler result has unsupported field ${key}`); + if (result.outcome !== undefined && ![ + "continue", + "deny", + "stop" + ].includes(result.outcome)) fail("handler result outcome is invalid"); + if (result.reason !== undefined && typeof result.reason !== "string") fail("handler result reason must be a string"); + if (result.additionalContext !== undefined && typeof result.additionalContext !== "string") fail("handler result additionalContext must be a string"); + if (result.updatedInput !== undefined && !isRecord(result.updatedInput)) fail("handler result updatedInput must be an object"); + const supportsDeniedReason = canonicalEvent === "beforeTool" || canonicalEvent === "stop" || canonicalEvent === "agentStop"; + if (result.reason !== undefined && !(result.outcome === "deny" && supportsDeniedReason)) fail("reason is only valid for a denied beforeTool, stop, or agentStop hook"); + if (result.outcome === "deny" && supportsDeniedReason && (typeof result.reason !== "string" || result.reason.trim().length === 0)) fail(`denied ${canonicalEvent} hook requires a nonempty reason`); + if ((canonicalEvent === "sessionStart" || canonicalEvent === "afterTool" || canonicalEvent === "agentStart") && (result.outcome === "deny" || result.outcome === "stop" || result.updatedInput !== undefined)) fail(`${canonicalEvent} cannot deny, stop, or replace input`); + if (canonicalEvent === "beforeTool" && (result.outcome === "stop" || result.outcome === "deny" && result.updatedInput !== undefined)) fail("beforeTool cannot stop or replace input while denying"); + if (canonicalEvent === "stop" && (result.outcome === "stop" || result.updatedInput !== undefined || result.additionalContext !== undefined)) fail("stop only accepts continue or deny with a reason"); + if (canonicalEvent === "agentStop" && (result.outcome === "stop" || result.updatedInput !== undefined)) fail("agentStop cannot stop the parent flow or replace input"); + if (canonicalEvent === "agentStop" && target === "codex" && 0) {} + return result; +}; +const encodeOutput = (result)=>{ + if (result === undefined) return undefined; + if (canonicalEvent === "stop" || canonicalEvent === "agentStop") { + if (result.outcome === "deny") return defined({ + decision: "block", + reason: result.reason + }); + if (canonicalEvent === "agentStop" && target === "claude" && result.additionalContext !== undefined) return { + hookSpecificOutput: { + additionalContext: result.additionalContext, + hookEventName: nativeEvent + } + }; + return undefined; + } + const output = defined({ + additionalContext: result.additionalContext, + hookEventName: nativeEvent, + permissionDecision: canonicalEvent === "beforeTool" ? result.outcome === "deny" ? "deny" : "allow" : undefined, + permissionDecisionReason: canonicalEvent === "beforeTool" && result.outcome === "deny" ? result.reason : undefined, + updatedInput: canonicalEvent === "beforeTool" && result.outcome !== "deny" ? result.updatedInput : undefined + }); + return Object.keys(output).length === 1 && output.hookEventName !== undefined ? undefined : { + hookSpecificOutput: output + }; +}; +const decodeOutput = (nativeOutput)=>{ + if (nativeOutput === undefined) return undefined; + if (canonicalEvent === "stop" || canonicalEvent === "agentStop") { + if (nativeOutput.decision === "block") return defined({ + outcome: "deny", + reason: nativeOutput.reason + }); + if (canonicalEvent === "agentStop" && target === "claude" && isRecord(nativeOutput.hookSpecificOutput)) return defined({ + additionalContext: nativeOutput.hookSpecificOutput.additionalContext, + outcome: "continue" + }); + return undefined; + } + const output = nativeOutput.hookSpecificOutput; + if (!isRecord(output)) fail("native hook output is malformed"); + return defined({ + additionalContext: output.additionalContext, + outcome: output.permissionDecision === "deny" ? "deny" : "continue", + reason: output.permissionDecisionReason, + updatedInput: output.updatedInput + }); +}; +const requireString = (input, field)=>{ + if (typeof input[field] !== "string") fail(`native ${field} must be a string`); +}; +const requireNullableString = (input, field)=>{ + if (input[field] !== null && typeof input[field] !== "string") fail(`native ${field} must be a string or null`); +}; +const validateNativeInput = (input)=>{ + requireString(input, "session_id"); + if (false) {} + else requireString(input, "transcript_path"); + requireString(input, "cwd"); + if (input.hook_event_name !== nativeEvent) fail(`native hook_event_name must equal ${nativeEvent}`); + if (input.prompt_id !== undefined) requireString(input, "prompt_id"); + if (input.permission_mode !== undefined) requireString(input, "permission_mode"); + if (input.model !== undefined) requireString(input, "model"); + if (canonicalEvent === "sessionStart") { + requireString(input, "source"); + return; + } + if (canonicalEvent === "beforeTool" || canonicalEvent === "afterTool") { + requireString(input, "tool_name"); + if (false) {} else if (!isRecord(input.tool_input)) fail(`native ${nativeEvent} tool_input must be an object`); + requireString(input, "tool_use_id"); + if (canonicalEvent === "afterTool") { + if (input.tool_response === undefined) fail("native PostToolUse tool_response is required"); + } + return; + } + if (canonicalEvent === "agentStart" || canonicalEvent === "agentStop") { + requireString(input, "agent_id"); + requireString(input, "agent_type"); + if (false) {} + if (canonicalEvent === "agentStart") return; + if (typeof input.stop_hook_active !== "boolean") fail("native SubagentStop stop_hook_active must be a boolean"); + requireNullableString(input, "agent_transcript_path"); + requireNullableString(input, "last_assistant_message"); + return; + } + if (typeof input.stop_hook_active !== "boolean") fail("native Stop stop_hook_active must be a boolean"); + if (false) {} + else requireString(input, "last_assistant_message"); +}; +const run = async ()=>{ + const handler = Reflect.get(session_start_namespaceObject, "default"); + if (typeof handler !== "function") fail("default export must be a function"); + let raw = ""; + for await (const chunk of process.stdin)raw += chunk; + if (raw.trim().length === 0) fail("stdin must contain exactly one JSON value"); + let input; + try { + input = JSON.parse(raw); + } catch { + fail("stdin must contain exactly one JSON value"); + } + if (!isRecord(input)) fail("stdin JSON value must be an object"); + const simulation = process.env.AGENT_BUNDLE_HOOK_SIMULATION === "1"; + const nativeInput = simulation ? encodeNative(input) : input; + validateNativeInput(nativeInput); + const event = decodeNative(nativeInput); + const result = validateResult(await handler(event, { + nativeEvent: nativeEvent, + nativeInput, + target: target + })); + const nativeOutput = encodeOutput(result); + const output = simulation ? decodeOutput(nativeOutput) : nativeOutput; + if (output !== undefined) process.stdout.write(JSON.stringify(output)); +}; +if (import.meta.main) { + await run().catch((error)=>{ + process.stderr.write(`${error instanceof Error ? error.message : String(error)}\n`); + process.exitCode = 1; + }); +} + +export {}; diff --git a/examples/mcp-app/artifact/claude/mcp/mcp-status-073c1634.mjs b/examples/mcp-app/artifact/claude/mcp/mcp-status-073c1634.mjs new file mode 100644 index 000000000..29189bf45 --- /dev/null +++ b/examples/mcp-app/artifact/claude/mcp/mcp-status-073c1634.mjs @@ -0,0 +1,30761 @@ +import node_process from "node:process"; + +// The require scope +var __webpack_require__ = {}; + +// webpack/runtime/define_property_getters +(() => { +__webpack_require__.d = (exports, getters, values) => { + var define = (defs, kind) => { + for(var key in defs) { + if(__webpack_require__.o(defs, key) && !__webpack_require__.o(exports, key)) { + Object.defineProperty(exports, key, { enumerable: true, [kind]: defs[key] }); + } + } + }; + define(getters, "get"); + define(values, "value"); +}; +})(); +// webpack/runtime/has_own_property +(() => { +__webpack_require__.o = (obj, prop) => (Object.prototype.hasOwnProperty.call(obj, prop)) +})(); +// webpack/runtime/make_namespace_object +(() => { +// define __esModule on exports +__webpack_require__.r = (exports) => { + if(typeof Symbol !== 'undefined' && Symbol.toStringTag) { + Object.defineProperty(exports, Symbol.toStringTag, { value: 'Module' }); + } + Object.defineProperty(exports, '__esModule', { value: true }); +}; +})(); + +// NAMESPACE OBJECT: ./src/mcp/status.ts +var status_namespaceObject = {}; +__webpack_require__.r(status_namespaceObject); +__webpack_require__.d(status_namespaceObject, { + createStatusServer: () => (createStatusServer), + "default": () => (mcp_status) }); + + +// NAMESPACE OBJECT: ../../node_modules/.pnpm/@modelcontextprotocol+server@2.0.0/node_modules/@modelcontextprotocol/server/dist/stdio.mjs +var stdio_namespaceObject = {}; +__webpack_require__.r(stdio_namespaceObject); +__webpack_require__.d(stdio_namespaceObject, { + StdioServerTransport: () => (stdio_StdioServerTransport) }); + + +//#region rolldown:runtime +var __create = Object.create; +var __defProp = Object.defineProperty; +var __getOwnPropDesc = Object.getOwnPropertyDescriptor; +var __getOwnPropNames = Object.getOwnPropertyNames; +var __getProtoOf = Object.getPrototypeOf; +var __hasOwnProp = Object.prototype.hasOwnProperty; +var __commonJSMin = (cb, mod) => () => (mod || cb((mod = { exports: {} }).exports, mod), mod.exports); +var __exportAll = (all, symbols) => { + let target = {}; + for (var name in all) { + __defProp(target, name, { + get: all[name], + enumerable: true + }); + } + if (symbols) { + __defProp(target, Symbol.toStringTag, { value: "Module" }); + } + return target; +}; +var __copyProps = (to, from, except, desc) => { + if (from && typeof from === "object" || typeof from === "function") { + for (var keys = __getOwnPropNames(from), i = 0, n = keys.length, key; i < n; i++) { + key = keys[i]; + if (!__hasOwnProp.call(to, key) && key !== except) { + __defProp(to, key, { + get: ((k) => from[k]).bind(null, key), + enumerable: !(desc = __getOwnPropDesc(from, key)) || desc.enumerable + }); + } + } + } + return to; +}; +var __toESM = (mod, isNodeMode, target) => (target = mod != null ? __create(__getProtoOf(mod)) : {}, __copyProps(isNodeMode || !mod || !mod.__esModule ? __defProp(target, "default", { + value: mod, + enumerable: true +}) : target, mod)); + +//#endregion + +//#region ../core-internal/src/validators/dialects.ts +/** +* Canonical `$schema` URIs per supported dialect (http + https variants, trailing-`#` stripped). +*/ +const DRAFT_2020_12_URIS = new Set(["https://json-schema.org/draft/2020-12/schema", "http://json-schema.org/draft/2020-12/schema"]); +const DRAFT_2019_09_URIS = new Set(["https://json-schema.org/draft/2019-09/schema", "http://json-schema.org/draft/2019-09/schema"]); +const DRAFT_07_URIS = new Set(["https://json-schema.org/draft-07/schema", "http://json-schema.org/draft-07/schema"]); +const DRAFT_06_URIS = new Set(["https://json-schema.org/draft-06/schema", "http://json-schema.org/draft-06/schema"]); +/** +* Whether a `$schema` value declares the 2019-09 dialect — the only supported dialect with +* `$recursiveRef`/`$recursiveAnchor`. Non-throwing (unlike {@linkcode declaredDialect}) so +* wire-layer callers can consult it for documents whose dialect may be unsupported. +*/ +function declares2019Dialect($schema) { + return typeof $schema === "string" && DRAFT_2019_09_URIS.has($schema.replace(/#$/, "")); +} +/** +* Classify a schema's declared `$schema` dialect. No `$schema` (or a non-string one) means +* 2020-12. Any other dialect throws a plain `Error` with a clear message rather than letting the +* engine crash on an opaque internal error or silently mis-validate; `remedy` names the calling +* provider's escape hatch in that message. +*/ +function declaredDialect(schema, remedy) { + if (!("$schema" in schema) || typeof schema.$schema !== "string") return "2020-12"; + const declared = schema.$schema.replace(/#$/, ""); + if (DRAFT_2020_12_URIS.has(declared)) return "2020-12"; + if (DRAFT_2019_09_URIS.has(declared)) return "2019-09"; + if (DRAFT_07_URIS.has(declared) || DRAFT_06_URIS.has(declared)) return "draft-7"; + throw new Error(`JSON Schema declares an unsupported dialect ("$schema": "${schema.$schema.slice(0, 200)}"). The default validator supports JSON Schema 2020-12, 2019-09, draft-07, and draft-06; ${remedy}`); +} + +//#endregion + +//# sourceMappingURL=dialects-DoSzNhcb.mjs.map + +// functions +function assertEqual(val) { + return val; +} +function assertNotEqual(val) { + return val; +} +function toZod() { + return (schema) => schema; +} +function assertIs(_arg) { } +function assertNever(_x) { + throw new Error("Unexpected value in exhaustive check"); +} +function assert(_) { } +function getEnumValues(entries) { + const numericValues = Object.values(entries).filter((v) => typeof v === "number"); + const values = Object.entries(entries) + .filter(([k, _]) => numericValues.indexOf(+k) === -1) + .map(([_, v]) => v); + return values; +} +function joinValues(array, separator = "|") { + return array.map((val) => stringifyPrimitive(val)).join(separator); +} +function jsonStringifyReplacer(_, value) { + if (typeof value === "bigint") + return value.toString(); + return value; +} +function util_cached(getter) { + const set = false; + return { + get value() { + if (!set) { + const value = getter(); + Object.defineProperty(this, "value", { value }); + return value; + } + throw new Error("cached value already set"); + }, + }; +} +function nullish(input) { + return input === null || input === undefined; +} +function cleanRegex(source) { + const start = source.startsWith("^") ? 1 : 0; + const end = source.endsWith("$") ? source.length - 1 : source.length; + return source.slice(start, end); +} +function floatSafeRemainder(val, step) { + const ratio = val / step; + const roundedRatio = Math.round(ratio); + // `val` and `step` each round to a double before the division rounds again, so a true decimal multiple's quotient can sit up to 1.5 of these scaled epsilons from the integer. A 1x tolerance therefore rejected 2.03 as a multiple of 0.07; 4x covers the worst case with margin. + const tolerance = 4 * Number.EPSILON * Math.max(Math.abs(ratio), 1); + if (Math.abs(ratio - roundedRatio) < tolerance) + return 0; + return ratio - roundedRatio; +} +const EVALUATING = /* @__PURE__*/ Symbol("evaluating"); +function defineLazy(object, key, getter) { + let value = undefined; + Object.defineProperty(object, key, { + get() { + if (value === EVALUATING) { + // Circular reference detected, return undefined to break the cycle + return undefined; + } + if (value === undefined) { + value = EVALUATING; + value = getter(); + } + return value; + }, + set(v) { + Object.defineProperty(object, key, { + value: v, + // configurable: true, + }); + // object[key] = v; + }, + configurable: true, + }); +} +function objectClone(obj) { + return Object.create(Object.getPrototypeOf(obj), Object.getOwnPropertyDescriptors(obj)); +} +function assignProp(target, prop, value) { + Object.defineProperty(target, prop, { + value, + writable: true, + enumerable: true, + configurable: true, + }); +} +function mergeDefs(...defs) { + const mergedDescriptors = {}; + for (const def of defs) { + const descriptors = Object.getOwnPropertyDescriptors(def); + Object.assign(mergedDescriptors, descriptors); + } + return Object.defineProperties({}, mergedDescriptors); +} +function cloneDef(schema) { + return mergeDefs(schema._zod.def); +} +function getElementAtPath(obj, path) { + if (!path) + return obj; + return path.reduce((acc, key) => acc?.[key], obj); +} +function promiseAllObject(promisesObj) { + const keys = Object.keys(promisesObj); + const promises = keys.map((key) => promisesObj[key]); + return Promise.all(promises).then((results) => { + const resolvedObj = {}; + for (let i = 0; i < keys.length; i++) { + resolvedObj[keys[i]] = results[i]; + } + return resolvedObj; + }); +} +function randomString(length = 10) { + const chars = "abcdefghijklmnopqrstuvwxyz"; + let str = ""; + for (let i = 0; i < length; i++) { + str += chars[Math.floor(Math.random() * chars.length)]; + } + return str; +} +function util_esc(str) { + return JSON.stringify(str); +} +function slugify(input) { + return input + .toLowerCase() + .trim() + .replace(/[^\w\s-]/g, "") + .replace(/[\s_-]+/g, "-") + .replace(/^-+|-+$/g, ""); +} +const captureStackTrace = ("captureStackTrace" in Error ? Error.captureStackTrace : (..._args) => { }); +function util_isObject(data) { + return typeof data === "object" && data !== null && !Array.isArray(data); +} +const util_allowsEval = /* @__PURE__*/ util_cached(() => { + // Skip the probe under `jitless`: strict CSPs report the caught `new Function` as a `securitypolicyviolation` even though the throw is swallowed. + if (globalConfig.jitless) { + return false; + } + // @ts-ignore + if (typeof navigator !== "undefined" && navigator?.userAgent?.includes("Cloudflare")) { + return false; + } + try { + const F = Function; + new F(""); + return true; + } + catch (_) { + return false; + } +}); +function isPlainObject(o) { + if (util_isObject(o) === false) + return false; + // modified constructor + const ctor = o.constructor; + if (ctor === undefined) + return true; + if (typeof ctor !== "function") + return true; + // modified prototype + const prot = ctor.prototype; + if (util_isObject(prot) === false) + return false; + // ctor doesn't have static `isPrototypeOf` + if (Object.prototype.hasOwnProperty.call(prot, "isPrototypeOf") === false) { + return false; + } + return true; +} +function shallowClone(o) { + if (isPlainObject(o)) + return { ...o }; + if (Array.isArray(o)) + return [...o]; + if (o instanceof Map) + return new Map(o); + if (o instanceof Set) + return new Set(o); + return o; +} +function numKeys(data) { + let keyCount = 0; + for (const key in data) { + if (Object.prototype.hasOwnProperty.call(data, key)) { + keyCount++; + } + } + return keyCount; +} +const getParsedType = (data) => { + const t = typeof data; + switch (t) { + case "undefined": + return "undefined"; + case "string": + return "string"; + case "number": + return Number.isNaN(data) ? "nan" : "number"; + case "boolean": + return "boolean"; + case "function": + return "function"; + case "bigint": + return "bigint"; + case "symbol": + return "symbol"; + case "object": + if (Array.isArray(data)) { + return "array"; + } + if (data === null) { + return "null"; + } + if (data.then && typeof data.then === "function" && data.catch && typeof data.catch === "function") { + return "promise"; + } + if (typeof Map !== "undefined" && data instanceof Map) { + return "map"; + } + if (typeof Set !== "undefined" && data instanceof Set) { + return "set"; + } + if (typeof Date !== "undefined" && data instanceof Date) { + return "date"; + } + // @ts-ignore + if (typeof File !== "undefined" && data instanceof File) { + return "file"; + } + return "object"; + default: + throw new Error(`Unknown data type: ${t}`); + } +}; +const propertyKeyTypes = /* @__PURE__*/ new Set(["string", "number", "symbol"]); +const primitiveTypes = /* @__PURE__*/ (/* unused pure expression or super */ null && (new Set([ + "string", + "number", + "bigint", + "boolean", + "symbol", + "undefined", +]))); +function escapeRegex(str) { + return str.replace(/[.*+?^${}()|[\]\\]/g, "\\$&"); +} +// zod-specific utils +function clone(inst, def, params) { + const cl = new inst._zod.constr(def ?? inst._zod.def); + if (!def || params?.parent) + cl._zod.parent = inst; + return cl; +} +function normalizeParams(_params) { + const params = _params; + if (!params) + return {}; + if (typeof params === "string") + return { error: () => params }; + if (params?.message !== undefined) { + if (params?.error !== undefined) + throw new Error("Cannot specify both `message` and `error` params"); + params.error = params.message; + } + delete params.message; + if (typeof params.error === "string") + return { ...params, error: () => params.error }; + return params; +} +function createTransparentProxy(getter) { + let target; + return new Proxy({}, { + get(_, prop, receiver) { + target ?? (target = getter()); + return Reflect.get(target, prop, receiver); + }, + set(_, prop, value, receiver) { + target ?? (target = getter()); + return Reflect.set(target, prop, value, receiver); + }, + has(_, prop) { + target ?? (target = getter()); + return Reflect.has(target, prop); + }, + deleteProperty(_, prop) { + target ?? (target = getter()); + return Reflect.deleteProperty(target, prop); + }, + ownKeys(_) { + target ?? (target = getter()); + return Reflect.ownKeys(target); + }, + getOwnPropertyDescriptor(_, prop) { + target ?? (target = getter()); + return Reflect.getOwnPropertyDescriptor(target, prop); + }, + defineProperty(_, prop, descriptor) { + target ?? (target = getter()); + return Reflect.defineProperty(target, prop, descriptor); + }, + }); +} +function stringifyPrimitive(value) { + if (typeof value === "bigint") + return value.toString() + "n"; + if (typeof value === "string") + return `"${value}"`; + return `${value}`; +} +function optionalKeys(shape) { + return Object.keys(shape).filter((k) => { + return shape[k]._zod.optin !== undefined && shape[k]._zod.optout === "optional"; + }); +} +// Wrapped in a `@__PURE__` IIFE: esbuild never tree-shakes a top-level initializer that contains a member access on `Number`, so the bare object literal survived into every bundle. +const NUMBER_FORMAT_RANGES = /*@__PURE__*/ (() => ({ + safeint: [Number.MIN_SAFE_INTEGER, Number.MAX_SAFE_INTEGER], + int32: [-2147483648, 2147483647], + uint32: [0, 4294967295], + float32: [-3.4028234663852886e38, 3.4028234663852886e38], + float64: [-Number.MAX_VALUE, Number.MAX_VALUE], +}))(); +const BIGINT_FORMAT_RANGES = { + int64: [/* @__PURE__*/ BigInt("-9223372036854775808"), /* @__PURE__*/ BigInt("9223372036854775807")], + uint64: [/* @__PURE__*/ BigInt(0), /* @__PURE__*/ BigInt("18446744073709551615")], +}; +function pick(schema, mask) { + const currDef = schema._zod.def; + const checks = currDef.checks; + const hasChecks = checks && checks.length > 0; + if (hasChecks) { + throw new Error(".pick() cannot be used on object schemas containing refinements"); + } + const def = mergeDefs(schema._zod.def, { + get shape() { + const newShape = {}; + // `for...in` skips symbols, so a symbol in the mask would select nothing + for (const key of Reflect.ownKeys(mask)) { + if (!Object.prototype.hasOwnProperty.call(currDef.shape, key)) { + throw new Error(`Unrecognized key: "${String(key)}"`); + } + if (!mask[key]) + continue; + assignProp(newShape, key, currDef.shape[key]); + } + assignProp(this, "shape", newShape); // self-caching + return newShape; + }, + checks: [], + }); + return clone(schema, def); +} +function omit(schema, mask) { + const currDef = schema._zod.def; + const checks = currDef.checks; + const hasChecks = checks && checks.length > 0; + if (hasChecks) { + throw new Error(".omit() cannot be used on object schemas containing refinements"); + } + const def = mergeDefs(schema._zod.def, { + get shape() { + const newShape = { ...schema._zod.def.shape }; + for (const key of Reflect.ownKeys(mask)) { + if (!Object.prototype.hasOwnProperty.call(currDef.shape, key)) { + throw new Error(`Unrecognized key: "${String(key)}"`); + } + if (!mask[key]) + continue; + delete newShape[key]; + } + assignProp(this, "shape", newShape); // self-caching + return newShape; + }, + checks: [], + }); + return clone(schema, def); +} +function extend(schema, shape) { + if (!isPlainObject(shape)) { + throw new Error("Invalid input to extend: expected a plain object"); + } + const checks = schema._zod.def.checks; + const hasChecks = checks && checks.length > 0; + if (hasChecks) { + // Only throw if new shape overlaps with existing shape. Use getOwnPropertyDescriptor to check key existence without accessing values + const existingShape = schema._zod.def.shape; + for (const key of Reflect.ownKeys(shape)) { + if (Object.getOwnPropertyDescriptor(existingShape, key) !== undefined) { + throw new Error("Cannot overwrite keys on object schemas containing refinements. Use `.safeExtend()` instead."); + } + } + } + const def = mergeDefs(schema._zod.def, { + get shape() { + const _shape = { ...schema._zod.def.shape, ...shape }; + assignProp(this, "shape", _shape); // self-caching + return _shape; + }, + }); + return clone(schema, def); +} +function safeExtend(schema, shape) { + if (!isPlainObject(shape)) { + throw new Error("Invalid input to safeExtend: expected a plain object"); + } + const def = mergeDefs(schema._zod.def, { + get shape() { + const _shape = { ...schema._zod.def.shape, ...shape }; + assignProp(this, "shape", _shape); // self-caching + return _shape; + }, + }); + return clone(schema, def); +} +function merge(a, b) { + if (!b?._zod?.def) { + throw new Error("Invalid input to merge: expected an object schema. To merge a plain shape, use `.extend()`."); + } + if (a._zod.def.checks?.length) { + throw new Error(".merge() cannot be used on object schemas containing refinements. Use .safeExtend() instead."); + } + const def = mergeDefs(a._zod.def, { + get shape() { + const _shape = { ...a._zod.def.shape, ...b._zod.def.shape }; + assignProp(this, "shape", _shape); // self-caching + return _shape; + }, + get catchall() { + return b._zod.def.catchall; + }, + checks: b._zod.def.checks ?? [], + }); + return clone(a, def); +} +function partial(Class, schema, mask, name = "partial") { + const currDef = schema._zod.def; + const checks = currDef.checks; + const hasChecks = checks && checks.length > 0; + if (hasChecks) { + throw new Error(`.${name}() cannot be used on object schemas containing refinements`); + } + const def = mergeDefs(schema._zod.def, { + get shape() { + const oldShape = schema._zod.def.shape; + const shape = { ...oldShape }; + if (mask) { + for (const key of Reflect.ownKeys(mask)) { + if (!Object.prototype.hasOwnProperty.call(oldShape, key)) { + throw new Error(`Unrecognized key: "${String(key)}"`); + } + if (!mask[key]) + continue; + // if (oldShape[key]!._zod.optin === "optional") continue; + shape[key] = Class + ? new Class({ + type: "optional", + innerType: oldShape[key], + }) + : oldShape[key]; + } + } + else { + // the spread copies symbol keys; `for...in` would not reach them + for (const key of Reflect.ownKeys(oldShape)) { + // if (oldShape[key]!._zod.optin === "optional") continue; + shape[key] = Class + ? new Class({ + type: "optional", + innerType: oldShape[key], + }) + : oldShape[key]; + } + } + assignProp(this, "shape", shape); // self-caching + return shape; + }, + checks: [], + }); + return clone(schema, def); +} +function util_required(Class, schema, mask) { + const def = mergeDefs(schema._zod.def, { + get shape() { + const oldShape = schema._zod.def.shape; + const shape = { ...oldShape }; + if (mask) { + for (const key of Reflect.ownKeys(mask)) { + if (!Object.prototype.hasOwnProperty.call(shape, key)) { + throw new Error(`Unrecognized key: "${String(key)}"`); + } + if (!mask[key]) + continue; + // overwrite with non-optional + shape[key] = new Class({ + type: "nonoptional", + innerType: oldShape[key], + }); + } + } + else { + for (const key of Reflect.ownKeys(oldShape)) { + // overwrite with non-optional + shape[key] = new Class({ + type: "nonoptional", + innerType: oldShape[key], + }); + } + } + assignProp(this, "shape", shape); // self-caching + return shape; + }, + }); + return clone(schema, def); +} +// invalid_type | too_big | too_small | invalid_format | not_multiple_of | unrecognized_keys | invalid_union | invalid_key | invalid_element | invalid_value | custom +function aborted(x, startIndex = 0) { + if (x.aborted === true) + return true; + for (let i = startIndex; i < x.issues.length; i++) { + if (x.issues[i]?.continue !== true) { + return true; + } + } + return false; +} +// Checks for explicit abort (continue === false), as opposed to implicit abort (continue === undefined). Used to respect `abort: true` in .refine() even for checks that have a `when` function. +function explicitlyAborted(x, startIndex = 0) { + if (x.aborted === true) + return true; + for (let i = startIndex; i < x.issues.length; i++) { + if (x.issues[i]?.continue === false) { + return true; + } + } + return false; +} +function prefixIssues(path, issues) { + return issues.map((iss) => { + var _a; + (_a = iss).path ?? (_a.path = []); + iss.path.unshift(path); + return iss; + }); +} +function unwrapMessage(message) { + return typeof message === "string" ? message : message?.message; +} +/* A check holds no link back to the schema it is attached to — the same check instance is shared by every clone of that schema — so the owner is stamped onto the issues a check just raised, at the only point where both are in scope. Runs on the failure path only; `start` is the issue count from before the check ran. */ +function attachSchema(issues, start, inst) { + var _a; + for (let i = start; i < issues.length; i++) { + (_a = issues[i]).schema ?? (_a.schema = inst); + } +} +function finalizeIssue(iss, ctx, config) { + var _a; + // A schema that raised an issue itself owns it outright, and outranks any stamp an enclosing check left in `attachSchema`. String formats and z.custom() are schema and check at once, so when they act as a check they defer to that stamp instead. + const traits = iss.inst?._zod?.traits; + if (traits?.has("$ZodType")) { + if (traits.has("$ZodCheck")) + (_a = iss).schema ?? (_a.schema = iss.inst); + else + iss.schema = iss.inst; + } + // Decreasing specificity, first map to return a message wins. `inst` is whatever raised the issue, so a check's own map outranks the owning schema's. + const schemaError = iss.schema !== iss.inst ? iss.schema?._zod.def?.error : undefined; + const message = iss.message + ? iss.message + : (unwrapMessage(iss.inst?._zod.def?.error?.(iss)) ?? + unwrapMessage(schemaError?.(iss)) ?? + unwrapMessage(ctx?.error?.(iss)) ?? + unwrapMessage(config.customError?.(iss)) ?? + unwrapMessage(config.localeError?.(iss)) ?? + "Invalid input"); + const { inst: _inst, schema: _schema, continue: _continue, input: _input, ...rest } = iss; + rest.path ?? (rest.path = []); + rest.message = message; + if (ctx?.reportInput) { + rest.input = _input; + } + return rest; +} +function getSizableOrigin(input) { + if (input instanceof Set) + return "set"; + if (input instanceof Map) + return "map"; + // @ts-ignore + if (input instanceof File) + return "file"; + return "unknown"; +} +const highSurrogate = /[\uD800-\uDBFF]/; +// Code points in `str`: a surrogate pair counts once, a lone surrogate as itself. Hand-rolled because the string iterator allocates and runs ~250x slower on this path; the regex probe exits ~50x quicker for a string with no astral characters. +function codePointLength(str) { + const units = str.length; + if (!highSurrogate.test(str)) + return units; + let count = units; + for (let i = 0; i < units - 1; i++) { + if ((str.charCodeAt(i) & 0xfc00) === 0xd800 && (str.charCodeAt(i + 1) & 0xfc00) === 0xdc00) { + count--; + i++; + } + } + return count; +} +function getLengthableOrigin(input) { + if (Array.isArray(input)) + return "array"; + if (typeof input === "string") + return "string"; + return "unknown"; +} +function parsedType(data) { + const t = typeof data; + switch (t) { + case "number": { + return Number.isNaN(data) ? "nan" : "number"; + } + case "object": { + if (data === null) { + return "null"; + } + if (Array.isArray(data)) { + return "array"; + } + const obj = data; + if (obj && Object.getPrototypeOf(obj) !== Object.prototype && "constructor" in obj && obj.constructor) { + return obj.constructor.name; + } + } + } + return t; +} +function util_issue(...args) { + const [iss, input, inst] = args; + if (typeof iss === "string") { + return { + message: iss, + code: "custom", + input, + inst, + }; + } + return { ...iss }; +} +function cleanEnum(obj) { + return Object.entries(obj) + .filter(([k, _]) => { + // return true if NaN, meaning it's not a number, thus a string key + return Number.isNaN(Number.parseInt(k, 10)); + }) + .map((el) => el[1]); +} +// Codec utility functions +function base64ToUint8Array(base64) { + const binaryString = atob(base64); + const bytes = new Uint8Array(binaryString.length); + for (let i = 0; i < binaryString.length; i++) { + bytes[i] = binaryString.charCodeAt(i); + } + return bytes; +} +function uint8ArrayToBase64(bytes) { + let binaryString = ""; + for (let i = 0; i < bytes.length; i++) { + binaryString += String.fromCharCode(bytes[i]); + } + return btoa(binaryString); +} +function base64urlToUint8Array(base64url) { + const base64 = base64url.replace(/-/g, "+").replace(/_/g, "/"); + const padding = "=".repeat((4 - (base64.length % 4)) % 4); + return base64ToUint8Array(base64 + padding); +} +function uint8ArrayToBase64url(bytes) { + return uint8ArrayToBase64(bytes).replace(/\+/g, "-").replace(/\//g, "_").replace(/=/g, ""); +} +function hexToUint8Array(hex) { + const cleanHex = hex.replace(/^0x/, ""); + if (cleanHex.length % 2 !== 0) { + throw new Error("Invalid hex string length"); + } + const bytes = new Uint8Array(cleanHex.length / 2); + for (let i = 0; i < cleanHex.length; i += 2) { + bytes[i / 2] = Number.parseInt(cleanHex.slice(i, i + 2), 16); + } + return bytes; +} +function uint8ArrayToHex(bytes) { + return Array.from(bytes) + .map((b) => b.toString(16).padStart(2, "0")) + .join(""); +} +// instanceof +class util_Class { + constructor(..._args) { } +} +////////// PROTOTYPE INSTALLERS ////////// +// +// Members live on the prototype and materialize per instance on first read, which keeps own-property count under the step where V8 stops using inline slots. Changing anything here means re-measuring runtime, memory and bundle size together — see "The three axes" in AGENTS.md. +/** + * Installs a trait's members on its prototype. Each value builds that member for the instance on first read; the built value shadows the accessor as an own property, so a detached `const { parse } = schema` keeps working. + * + * Call this from a `proto` initializer, which runs once per prototype — never per instance. + */ +function util_members(proto, table) { + for (const key in table) { + const desc = Object.getOwnPropertyDescriptor(table, key); + // a getter installs as written, so it stays live: `description` reads through to the registry on every access. not enumerable: an object literal's is, and a prototype member never was + if (desc.get) + Object.defineProperty(proto, key, { ...desc, enumerable: false }); + // a method materializes bound on first read, which is what keeps a detached member working: `const opt = schema.optional; opt()` + else + defineBound(proto, key, desc.value); + } +} +/** Shadows a prototype member with an own value, so a getter that builds from the instance runs once. */ +function util_own(inst, key, value, enumerable = true) { + Object.defineProperty(inst, key, { configurable: true, writable: true, enumerable, value }); + return value; +} +/** Like {@link own}, for a member that was never an own data property and has to stay out of `Object.keys`. */ +function hide(inst, key, value) { + return util_own(inst, key, value, false); +} +function defineBound(proto, key, fn) { + Object.defineProperty(proto, key, { + configurable: true, + get() { + // vitest's spyOn calls a prototype getter bare to find the function it wraps, so a nullish receiver answers the raw method + return this == null ? fn : util_own(this, key, fn.bind(this)); + }, + set(value) { + util_own(this, key, value); + }, + }); +} +/** Returns the prototype to install on, or `undefined` if this group is already installed on it. */ +function claim(inst, sentinel) { + const proto = Object.getPrototypeOf(inst); + // Runs on every construction, so `in` rather than the costlier `hasOwnProperty.call`. Sentinels are keys the group itself defines. + return sentinel in proto ? undefined : proto; +} +// The internals whose init chain is installing. A second call for the same one is a derived constructor overriding its base, so it must not construct another schema in between or the override is dropped. +let installing; +// Set while a getter is running, so a value that resolved through a recursion break is not memoized. One shared descriptor shadows the key for the duration, which costs no per-key allocation. +let broke = false; +const breaker = { + configurable: true, + get() { + broke = true; + return undefined; + }, +}; +/** + * Installs a lazily-derived internal on the `_zod` prototype of `inst`'s + * constructor, computed from the internals object itself and cached there on + * first read. One accessor per constructor rather than one per instance. + */ +function defineLazyInternal(inst, key, compute) { + const proto = Object.getPrototypeOf(inst._zod); + if (key in proto && installing !== inst._zod) { + // A repeat construction: everything is installed already. Cleared here so the reference is not held past the first construction of every type. + installing = undefined; + return; + } + installing = inst._zod; + Object.defineProperty(proto, key, { + configurable: true, + get() { + // Shadowed before computing so a re-entrant read from a recursive schema resolves to undefined instead of running the getter again. + Object.defineProperty(this, key, breaker); + const outer = broke; + broke = false; + try { + const value = compute(this); + // A result that resolved through a recursion break is recomputed once the graph is complete; everything else memoizes, undefined included. + if (broke) + delete this[key]; + else + Object.defineProperty(this, key, { configurable: true, writable: true, value }); + broke = broke || outer; + return value; + } + catch (err) { + // A compute that threw memoizes nothing, so a later read runs it again and fails the same way. The shadow goes with it, since leaving it installed would answer undefined for every later read. + delete this[key]; + broke = broke || outer; + throw err; + } + }, + set(value) { + Object.defineProperty(this, key, { configurable: true, writable: true, value }); + }, + }); +} +/** + * Installs `key` on `inst`'s prototype, computed by `make` on first read and cached there as an own + * data property. One accessor per constructor rather than one per instance, because an own accessor + * puts every instance after the first into v8 dictionary mode. The key doubles as the sentinel. + */ +function installLazyProp(inst, key, make, enumerable) { + const proto = claim(inst, key); + if (!proto) + return; + Object.defineProperty(proto, key, { + configurable: true, + get() { + // Shadowed before computing, so a re-entrant read from a self-referential shape resolves to undefined instead of running the getter again. A data property rather than an accessor: an own accessor is the dictionary-mode transition this exists to avoid. + const desc = { configurable: true, writable: true, enumerable, value: undefined }; + Object.defineProperty(this, key, desc); + // a compute that throws leaves the shadow behind, so later reads answer undefined instead of re-throwing; `defineLazy` did the same, and `defineLazyInternal`'s delete-on-catch would cost bytes in every bundle for a case only a throwing user getter reaches + desc.value = make(this); + Object.defineProperty(this, key, desc); + return desc.value; + }, + set(value) { + Object.defineProperty(this, key, { configurable: true, writable: true, enumerable, value }); + }, + }); +} +/** Marks the thunk `_catch` synthesises for a constant catch value. `Function.length` cannot tell that thunk from a user callback — rest and defaulted parameters both report arity 0 — and a user callback reads `ctx.error`, whose issues only finalize correctly against the caller's per-parse error map. Provenance can say what arity cannot. A plain string key rather than `Symbol.for`, whose call at module scope no bundler can prove pure — the same shape that anchored `urlCanParse` into every build. */ +const CONSTANT_CATCH = "~constantCatch"; +/** Wraps a constant catch value in a thunk tagged with {@link CONSTANT_CATCH}. */ +function constantCatch(value) { + const fn = () => value; + fn[CONSTANT_CATCH] = true; + return fn; +} + +var core_a; + +/** A special constant with type `never` */ +const NEVER = /*@__PURE__*/ Object.freeze({ + status: "aborted", +}); +/* Shared descriptor for installing `_zod`; defineProperty reads it + * synchronously, so reusing one object avoids a per-instance allocation. */ +const _zodDesc = { value: undefined, enumerable: false }; +// null where suppressing the capture would be unrecoverable: `parse()` puts the frames back with `captureStackTrace`, so without it the throw would lose its stack. also latched to null once `stackTraceLimit` proves unassignable, which a realm can do at any point by hardening Error +let _E = "captureStackTrace" in Error ? Error : null; +// v8 captures a stack trace inside the Error constructor, which dominates a failed parse; costs only the frames, and parse() restores those. the constructor must RUN: Object.create is cheaper and passes instanceof, but Error.isError and util.types.isNativeError check an internal slot +function newError(Definition) { + const E = _E; + if (E) { + const saved = E.stackTraceLimit; + if (typeof saved === "number") { + try { + E.stackTraceLimit = 0; + } + catch { + _E = null; + return new Definition(); + } + try { + return new Definition(); + } + finally { + E.stackTraceLimit = saved; + } + } + } + return new Definition(); +} +function $constructor(name, initializer, +/** This trait's members, installed once on every prototype that composes it. They cannot be declared in the initializer above: that runs per instance, and the prototype is shared. */ +proto, params) { + // Prototype for this constructor's `_zod` internals. Lazily-derived fields (`values`, `pattern`, `optin`, …) install here once rather than as an accessor on every instance. + const zodProto = {}; + // Assigning the fields in the constructor body is what gives instances in-object slots; building the object literally and reparenting it costs a second allocation and a generic property copy. + function Internals(def) { + this.def = def; + this.constr = _; + this.traits = new Set(); + } + Internals.prototype = zodProto; + const protoMembers = proto; + // One trait's members land on every prototype whose chain composes it, so the answer is per prototype rather than per trait. + const initialized = protoMembers && new WeakSet(); + function init(inst, def) { + if (!inst._zod) { + _zodDesc.value = new Internals(def); + try { + Object.defineProperty(inst, "_zod", _zodDesc); + } + finally { + // Cleared even on throw, so the shared descriptor never leaks one instance's internals into the next. + _zodDesc.value = undefined; + } + } + if (inst._zod.traits.has(name)) { + return; + } + inst._zod.traits.add(name); + initializer(inst, def); + if (initialized) { + // `super(def)` from a user subclass gives `this` a prototype the subclass owns, and installing there would overwrite whatever the subclass declared. `constr` built the instance, so its prototype is the one below the subclass's that should carry the members. A receiver whose chain never reaches that prototype installs on its own, which for a plain object handed straight to `init` means `Object.prototype` — unchanged from before. + const own = Object.getPrototypeOf(inst); + const ctorProto = inst._zod.constr.prototype; + let up = own; + while (up && up !== ctorProto) + up = Object.getPrototypeOf(up); + const target = up ?? own; + if (!initialized.has(target)) { + initialized.add(target); + util_members(target, protoMembers); + } + } + // support prototype modifications; for-in avoids the array allocation of Object.keys on the (usually empty) prototype + const proto = _.prototype; + for (const k in proto) { + if (!Object.prototype.hasOwnProperty.call(proto, k)) + continue; + if (!(k in inst)) { + inst[k] = proto[k].bind(inst); + } + } + } + // doesn't work if Parent has a constructor with arguments + const Parent = params?.Parent ?? Object; + class Definition extends Parent { + } + Object.defineProperty(Definition, "name", { value: name }); + function _(def) { + const inst = params?.Parent ? newError(Definition) : this; + init(inst, def); + const deferred = inst._zod.deferred; + if (deferred) { + for (const fn of deferred) { + fn(); + } + // Released: initializers run once, and the list would otherwise be retained for the schema's lifetime. + inst._zod.deferred = undefined; + } + // Global post-processor hook. Internal: installed by `import "zod/compile"` to enable AOT compilation for every constructed schema. Runs last, once the instance is fully built, because it hands the instance to compile(). The post-processor is expected to be reentrancy-guarded by its own implementation. + const pp = globalThis.__zod_globalConfig?.postProcessor; + if (pp) + pp(inst); + return inst; + } + Object.defineProperty(_, "init", { value: init }); + Object.defineProperty(_, Symbol.hasInstance, { + value: (inst) => { + if (params?.Parent && inst instanceof params.Parent) + return true; + return inst?._zod?.traits?.has(name); + }, + }); + Object.defineProperty(_, "name", { value: name }); + return _; +} +////////////////////////////// UTILITIES /////////////////////////////////////// +const $brand = /*@__PURE__*/ (/* unused pure expression or super */ null && (Symbol("zod_brand"))); +class $ZodAsyncError extends Error { + constructor() { + super(`Encountered Promise during synchronous parse. Use .parseAsync() instead.`); + } +} +class $ZodEncodeError extends Error { + constructor(name) { + super(`Encountered unidirectional transform during encode: ${name}`); + this.name = "ZodEncodeError"; + } +} +(core_a = globalThis).__zod_globalConfig ?? (core_a.__zod_globalConfig = {}); +const globalConfig = globalThis.__zod_globalConfig; +function core_config(newConfig) { + if (newConfig) + Object.assign(globalConfig, newConfig); + return globalConfig; +} + +class $ZodCyclicError extends Error { + constructor() { + super(`Cannot parse a reference cycle that closes through a transform`); + this.name = "ZodCyclicError"; + } +} +/** Keyed off the context object every schema in one parse call already shares. */ +const STATE = "~memo"; +const NO_ISSUES = []; +// Receivers prefix paths in place, so the cache and every hand-out need their own copies. +function cloneIssues(issues) { + return issues.map((iss) => (iss.path ? { ...iss, path: iss.path.slice() } : { ...iss })); +} +const recursive = /*@__PURE__*/ new WeakMap(); +/** Whether this schema's subtree contains a cycle, so one parse can re-enter it. */ +function isRecursive(inst, stack) { + const cached = recursive.get(inst); + if (cached !== undefined) + return cached; + // Relative to the walk in progress, so not cached. + if (stack.has(inst)) + return true; + stack.add(inst); + let result = false; + const check = (child) => { + if (!result && child?._zod && isRecursive(child, stack)) + result = true; + }; + const def = inst._zod.def; + const kind = def.type; + switch (kind) { + case "object": { + // `Reflect.ownKeys` rather than `Object.keys`, so a cycle through a declared symbol key is still seen + for (const key of Reflect.ownKeys(def.shape)) + check(def.shape[key]); + check(def.catchall); + break; + } + case "array": + check(def.element); + break; + case "tuple": + for (const el of def.items) + check(el); + check(def.rest); + break; + case "record": + case "map": + check(def.keyType); + check(def.valueType); + break; + case "set": + check(def.valueType); + break; + case "union": + for (const el of def.options) + check(el); + break; + case "intersection": + check(def.left); + check(def.right); + break; + case "optional": + case "nullable": + case "default": + case "prefault": + case "catch": + case "readonly": + case "nonoptional": + case "promise": + case "success": + check(def.innerType); + break; + case "pipe": + check(def.in); + check(def.out); + break; + case "function": + check(def.input); + check(def.output); + break; + // reading `_zod.innerType` resolves the getter once and caches it + case "lazy": + check(inst._zod.innerType); + break; + // a leaf by choice: `parts` are regex fragments, not data positions + case "template_literal": + // leaves + case "string": + case "number": + case "int": + case "boolean": + case "bigint": + case "symbol": + case "undefined": + case "null": + case "void": + case "never": + case "any": + case "unknown": + case "date": + case "nan": + case "enum": + case "literal": + case "file": + case "transform": + case "custom": + break; + default: { + // a new built-in kind becomes a compile error here + kind; + // a user-defined kind can still hold children, and only its author knows where, so fall back to scanning the def — skipping accessors, since reading one can run user code + for (const key in def) { + const desc = Object.getOwnPropertyDescriptor(def, key); + if (!desc || desc.get) + continue; + const value = desc.value; + if (!value || typeof value !== "object") + continue; + if (value._zod) + check(value); + else if (Array.isArray(value)) + for (const el of value) + check(el); + } + } + } + stack.delete(inst); + recursive.set(inst, result); + return result; +} +/** + * Whether one parse can re-enter this schema, i.e. its subtree contains a cycle. + * Exported for `z.compile`, which refuses to compile such a schema: cycle + * breaking is driven from here off state keyed on the parse context, and a + * generated fast path has no context to key on. + */ +function isRecursiveSchema(inst) { + return isRecursive(inst, new Set()); +} +function bucketFor(state, inst) { + let bucket = state.buckets.get(inst); + if (!bucket) { + bucket = new Map(); + state.buckets.set(inst, bucket); + } + return bucket; +} +// Set immediately before delegating to core and cleared immediately after, so `alloc` registers only for a visit this module is driving. +let handoff; +// Allocated but unfinished entries. `alloc` and the matching pop both happen in the synchronous part of a parse, so they nest even when children are async, and one stack serves every schema. +const memoizer_open = []; +const memoizer_memo = { + alloc(_inst, payload, empty) { + const bucket = handoff; + if (!bucket) + return empty; + handoff = undefined; + const entry = { value: empty, issues: null }; + bucket.set(payload.value, entry); + memoizer_open.push(entry); + return empty; + }, + guard(inst) { + var _a; + (_a = inst._zod).deferred ?? (_a.deferred = []); + inst._zod.deferred.push(() => { + const base = inst._zod.parse; + const wrapped = (payload, ctx) => { + // The value is a placeholder a back-edge is still waiting on, so the cycle closes through this transform. Its output can't exist in time to bind. + if (ctx.direction !== "backward" && isBackEdge(ctx, payload.value)) + throw new $ZodCyclicError(); + return base(payload, ctx); + }; + inst._zod.parse = wrapped; + if (inst._zod.run === base) + inst._zod.run = wrapped; + }); + }, + attach(inst) { + var _a; + let isRecursiveInst; + // `bucket` memoized for one parse; a recursive schema is re-entered many times and its bucket never changes + let lastCtx; + let lastBucket; + // Wraps `parse` in a deferred so it sees the container's final parse. Core's own deferred copies `parse` into `run` when there are no checks, and it ran first, so `run` is patched to match; with checks, `run` reads `parse` dynamically. + (_a = inst._zod).deferred ?? (_a.deferred = []); + inst._zod.deferred.push(() => { + const base = inst._zod.parse; + const wrapped = (payload, ctx) => { + if (isRecursiveInst === undefined) { + isRecursiveInst = isRecursive(inst, new Set()); + if (!isRecursiveInst) { + // Nothing here can ever fire, so take it back out. + inst._zod.parse = base; + if (inst._zod.run === wrapped) + inst._zod.run = base; + return base(payload, ctx); + } + } + const input = payload.value; + if (input === null || typeof input !== "object") + return base(payload, ctx); + let state = ctx[STATE]; + if (!state) { + state = { buckets: new Map(), backEdges: undefined }; + ctx[STATE] = state; + } + let bucket; + if (lastCtx === ctx) { + bucket = lastBucket; + } + else { + bucket = bucketFor(state, inst); + lastCtx = ctx; + lastBucket = bucket; + } + const hit = bucket.get(input); + if (hit) { + payload.value = hit.value; + if (hit.issues) { + if (hit.issues.length) + payload.issues.push(...cloneIssues(hit.issues)); + } + else { + // Still being parsed: its own checks cover it, so skip them here. + payload.memo = true; + state.backEdges ?? (state.backEdges = new Set()); + state.backEdges.add(hit.value); + } + return payload; + } + handoff = bucket; + const depth = memoizer_open.length; + const result = base(payload, ctx); + handoff = undefined; + // A container that rejected its input outright allocated nothing. + const entry = memoizer_open.length > depth ? memoizer_open.pop() : undefined; + // Both paths written out so the sync one allocates no closure. It runs once per node, and capturing here cost more than everything else combined. + if (result instanceof Promise) { + return result.then((r) => { + if (entry) + entry.issues = r.issues.length ? cloneIssues(r.issues) : NO_ISSUES; + return r; + }); + } + if (entry) + entry.issues = result.issues.length ? cloneIssues(result.issues) : NO_ISSUES; + return result; + }; + inst._zod.parse = wrapped; + if (inst._zod.run === base) + inst._zod.run = wrapped; + }); + }, +}; +/** The memoizer that gives containers cycle support. `zod` installs it by default; `zod/mini` opts in with `config({ memoizer: memoizer() })`. */ +function memoizer() { + return memoizer_memo; +} +/** Whether this value is a node a back-edge resolved to before it finished. */ +function isBackEdge(ctx, value) { + const backEdges = ctx[STATE]?.backEdges; + return backEdges !== undefined && value !== null && typeof value === "object" && backEdges.has(value); +} + + +/** + * @deprecated CUID v1 is deprecated by its authors due to information leakage + * (timestamps embedded in the id). Use {@link cuid2} instead. + * See https://github.com/paralleldrive/cuid. + */ +const cuid = /^[cC][0-9a-z]{6,}$/; +const cuid2 = /^[0-9a-z]+$/; +const ulid = /^[0-7][0-9A-HJKMNP-TV-Za-hjkmnp-tv-z]{25}$/; +const xid = /^[0-9a-vA-V]{20}$/; +const ksuid = /^[A-Za-z0-9]{27}$/; +const nanoid = /^[a-zA-Z0-9_-]{21}$/; +function nanoidOfLength(length) { + return new RegExp(`^[a-zA-Z0-9_-]{${length}}$`); +} +/** ISO 8601-1 duration regex. Does not support the 8601-2 extensions like negative durations or fractional/negative components. */ +const duration = /^P(?:(\d+W)|(?!.*W)(?=\d|T\d)(\d+Y)?(\d+M)?(\d+D)?(T(?=\d)(\d+H)?(\d+M)?(\d+([.,]\d+)?S)?)?)$/; +/** Implements ISO 8601-2 extensions like explicit +- prefixes, mixing weeks with other units, and fractional/negative components. */ +const extendedDuration = /^[-+]?P(?!$)(?:(?:[-+]?\d+Y)|(?:[-+]?\d+[.,]\d+Y$))?(?:(?:[-+]?\d+M)|(?:[-+]?\d+[.,]\d+M$))?(?:(?:[-+]?\d+W)|(?:[-+]?\d+[.,]\d+W$))?(?:(?:[-+]?\d+D)|(?:[-+]?\d+[.,]\d+D$))?(?:T(?=[\d+-])(?:(?:[-+]?\d+H)|(?:[-+]?\d+[.,]\d+H$))?(?:(?:[-+]?\d+M)|(?:[-+]?\d+[.,]\d+M$))?(?:[-+]?\d+(?:[.,]\d+)?S)?)??$/; +/** A regex for any UUID-like identifier: 8-4-4-4-12 hex pattern */ +const guid = /^([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})$/; +/** Returns a regex for validating an RFC 9562/4122 UUID. + * + * @param version Optionally specify a version 1-8. If no version is specified, all versions are supported. */ +const uuid = (version) => { + if (!version) + return /^([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)$/; + return new RegExp(`^([0-9a-fA-F]{8}-[0-9a-fA-F]{4}-${version}[0-9a-fA-F]{3}-[89abAB][0-9a-fA-F]{3}-[0-9a-fA-F]{12})$`); +}; +const uuid4 = /*@__PURE__*/ (/* unused pure expression or super */ null && (uuid(4))); +const uuid6 = /*@__PURE__*/ (/* unused pure expression or super */ null && (uuid(6))); +const uuid7 = /*@__PURE__*/ (/* unused pure expression or super */ null && (uuid(7))); +/** Practical email validation */ +const email = /^(?!\.)(?!.*\.\.)([A-Za-z0-9_'+\-\.]*)[A-Za-z0-9_+-]@([A-Za-z0-9][A-Za-z0-9\-]*\.)+[A-Za-z]{2,}$/; +/** Equivalent to the HTML5 input[type=email] validation implemented by browsers. Source: https://developer.mozilla.org/en-US/docs/Web/HTML/Element/input/email */ +const html5Email = /^[a-zA-Z0-9.!#$%&'*+/=?^_`{|}~-]+@[a-zA-Z0-9](?:[a-zA-Z0-9-]{0,61}[a-zA-Z0-9])?(?:\.[a-zA-Z0-9](?:[a-zA-Z0-9-]{0,61}[a-zA-Z0-9])?)*$/; +/** The classic emailregex.com regex for RFC 5322-compliant emails */ +const rfc5322Email = /^(([^<>()\[\]\\.,;:\s@"]+(\.[^<>()\[\]\\.,;:\s@"]+)*)|(".+"))@((\[[0-9]{1,3}\.[0-9]{1,3}\.[0-9]{1,3}\.[0-9]{1,3}])|(([a-zA-Z\-0-9]+\.)+[a-zA-Z]{2,}))$/; +/** A loose regex that allows Unicode characters, enforces length limits, and that's about it. */ +const unicodeEmail = /^[^\s@"]{1,64}@[^\s@]{1,255}$/u; +const idnEmail = (/* unused pure expression or super */ null && (unicodeEmail)); +const browserEmail = /^[a-zA-Z0-9.!#$%&'*+/=?^_`{|}~-]+@[a-zA-Z0-9](?:[a-zA-Z0-9-]{0,61}[a-zA-Z0-9])?(?:\.[a-zA-Z0-9](?:[a-zA-Z0-9-]{0,61}[a-zA-Z0-9])?)*$/; +// from https://thekevinscott.com/emojis-in-javascript/#writing-a-regular-expression +// Single character class, not an alternation: the two properties overlap (U+1F9B0-U+1F9B3), so `(A|B)+` backtracks exponentially on a failed match. +const _emoji = `^[\\p{Extended_Pictographic}\\p{Emoji_Component}]+$`; +function emoji() { + return new RegExp(_emoji, "u"); +} +const ipv4 = /^(?:(?: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])$/; +const regexes_ipv6 = /^(([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}|:))$/; +const mac = (delimiter) => { + const escapedDelim = util.escapeRegex(delimiter ?? ":"); + return new RegExp(`^(?:[0-9A-F]{2}${escapedDelim}){5}[0-9A-F]{2}$|^(?:[0-9a-f]{2}${escapedDelim}){5}[0-9a-f]{2}$`); +}; +const cidrv4 = /^((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])$/; +const cidrv6 = /^(([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}|:))\/(12[0-8]|1[01][0-9]|[1-9]?[0-9])$/; +// https://stackoverflow.com/questions/7860392/determine-if-string-is-in-base64-using-javascript +const regexes_base64 = /^$|^(?:[0-9a-zA-Z+/]{4})*(?:(?:[0-9a-zA-Z+/]{2}==)|(?:[0-9a-zA-Z+/]{3}=))?$/; +const regexes_base64url = /^[A-Za-z0-9_-]*$/; +// based on https://stackoverflow.com/questions/106179/regular-expression-to-match-dns-hostname-or-ip-address +// export const hostname: RegExp = /^([a-zA-Z0-9-]+\.)*[a-zA-Z0-9-]+$/; +const regexes_hostname = /^(?=.{1,253}\.?$)[a-zA-Z0-9](?:[a-zA-Z0-9-]{0,61}[a-zA-Z0-9])?(?:\.[a-zA-Z0-9](?:[-0-9a-zA-Z]{0,61}[0-9a-zA-Z])?)*\.?$/; +const domain = /^(?=.{1,253}$)([a-zA-Z0-9](?:[a-zA-Z0-9-]{0,61}[a-zA-Z0-9])?\.)+[a-zA-Z]{2,63}$/; +const httpProtocol = /^https?$/; +// https://blog.stevenlevithan.com/archives/validate-phone-number#r4-3 (regex sans spaces) E.164: leading digit must be 1-9; total digits (excluding '+') between 7-15 +const e164 = /^\+[1-9]\d{6,14}$/; +// Credit card shape: 12–19 digits, optionally separated by single spaces or single hyphens. ISO/IEC 7812 caps the PAN at 19 digits; 12 is the shortest issued length (Maestro). +const creditCard = /^\d(?:[ -]?\d){11,18}$/; +const dateSource = `(?:(?:\\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])))`; +/** Anchors a pattern source. The interpolation lives here rather than at the call site because + * esbuild will not drop a `@__PURE__` call whose own argument interpolates a variable, but it + * will drop `anchor(dateSource)`. Keeping it inline pinned `date` into every bundle. */ +function regexes_anchor(source) { + return new RegExp(`^${source}$`); +} +const regexes_date = /*@__PURE__*/ regexes_anchor(dateSource); +function timeSource(args) { + const hhmm = `(?:[01]\\d|2[0-3]):[0-5]\\d`; + const regex = typeof args.precision === "number" + ? args.precision === -1 + ? `${hhmm}` + : args.precision === 0 + ? `${hhmm}:[0-5]\\d` + : `${hhmm}:[0-5]\\d\\.\\d{${args.precision}}` + : args.seconds + ? `${hhmm}:[0-5]\\d(?:\\.\\d+)?` + : `${hhmm}(?::[0-5]\\d(?:\\.\\d+)?)?`; + return regex; +} +function regexes_time(args) { + return new RegExp(`^${timeSource(args)}$`); +} +// Adapted from https://stackoverflow.com/a/3143231 +function datetime(args) { + const opts = ["Z"]; + // if (args.offset) opts.push(`([+-]\\d{2}:\\d{2})`); + if (args.offset) + opts.push(`([+-](?:[01]\\d|2[0-3]):[0-5]\\d)`); + // RFC 3339 mandates seconds wherever the time carries a `Z` or an offset, so only the unqualified form `local` adds may omit them + const qualified = `${timeSource({ precision: args.precision, seconds: true })}(?:${opts.join("|")})`; + const timeRegex = args.local ? `${qualified}|${timeSource({ precision: args.precision })}` : qualified; + return new RegExp(`^${dateSource}T(?:${timeRegex})$`); +} +const regexes_string = (params) => { + const regex = params ? `[\\s\\S]{${params?.minimum ?? 0},${params?.maximum ?? ""}}` : `[\\s\\S]*`; + return new RegExp(`^${regex}$`); +}; +const bigint = /^-?\d+n?$/; +const integer = /^-?\d+$/; +const number = /^-?\d+(?:\.\d+)?$/; +const regexes_boolean = /^(?:true|false)$/i; +const _null = /^null$/i; + +const _undefined = /^undefined$/i; + +// regex for string with no uppercase letters +const lowercase = /^[^A-Z]*$/; +// regex for string with no lowercase letters +const uppercase = /^[^a-z]*$/; +// regex for hexadecimal strings (any length) +const regexes_hex = /^[0-9a-fA-F]*$/; +// Hash regexes for different algorithms and encodings +// Helper function to create base64 regex with exact length and padding +function fixedBase64(bodyLength, padding) { + return new RegExp(`^[A-Za-z0-9+/]{${bodyLength}}${padding}$`); +} +// Helper function to create base64url regex with exact length (no padding) +function fixedBase64url(length) { + return new RegExp(`^[A-Za-z0-9_-]{${length}}$`); +} +// MD5 (16 bytes): base64 = 24 chars total (22 + "==") +const md5_hex = /^[0-9a-fA-F]{32}$/; +const md5_base64 = /*@__PURE__*/ (/* unused pure expression or super */ null && (fixedBase64(22, "=="))); +const md5_base64url = /*@__PURE__*/ (/* unused pure expression or super */ null && (fixedBase64url(22))); +// SHA1 (20 bytes): base64 = 28 chars total (27 + "=") +const sha1_hex = /^[0-9a-fA-F]{40}$/; +const sha1_base64 = /*@__PURE__*/ (/* unused pure expression or super */ null && (fixedBase64(27, "="))); +const sha1_base64url = /*@__PURE__*/ (/* unused pure expression or super */ null && (fixedBase64url(27))); +// SHA256 (32 bytes): base64 = 44 chars total (43 + "=") +const sha256_hex = /^[0-9a-fA-F]{64}$/; +const sha256_base64 = /*@__PURE__*/ (/* unused pure expression or super */ null && (fixedBase64(43, "="))); +const sha256_base64url = /*@__PURE__*/ (/* unused pure expression or super */ null && (fixedBase64url(43))); +// SHA384 (48 bytes): base64 = 64 chars total (no padding) +const sha384_hex = /^[0-9a-fA-F]{96}$/; +const sha384_base64 = /*@__PURE__*/ (/* unused pure expression or super */ null && (fixedBase64(64, ""))); +const sha384_base64url = /*@__PURE__*/ (/* unused pure expression or super */ null && (fixedBase64url(64))); +// SHA512 (64 bytes): base64 = 88 chars total (86 + "==") +const sha512_hex = /^[0-9a-fA-F]{128}$/; +const sha512_base64 = /*@__PURE__*/ (/* unused pure expression or super */ null && (fixedBase64(86, "=="))); +const sha512_base64url = /*@__PURE__*/ (/* unused pure expression or super */ null && (fixedBase64url(86))); + +// import { $ZodType } from "./schemas.js"; + + + +const $ZodCheck = /*@__PURE__*/ $constructor("$ZodCheck", (inst, def) => { + var _a; + inst._zod ?? (inst._zod = {}); + inst._zod.def = def; + (_a = inst._zod).onattach ?? (_a.onattach = []); +}); +/** Default `when` for size-based checks: run only on non-nullish values with a `size`. */ +const _whenHasSize = (payload) => { + const val = payload.value; + return !util.nullish(val) && val.size !== undefined; +}; +/** Default `when` for length-based checks: run only on non-nullish values with a `length`. */ +const _whenHasLength = (payload) => { + const val = payload.value; + return !nullish(val) && val.length !== undefined; +}; +const numericOriginMap = { + number: "number", + bigint: "bigint", + object: "date", +}; +const $ZodCheckLessThan = /*@__PURE__*/ $constructor("$ZodCheckLessThan", (inst, def) => { + $ZodCheck.init(inst, def); + const origin = numericOriginMap[typeof def.value]; + inst._zod.onattach.push((inst) => { + const bag = inst._zod.bag; + const curr = (def.inclusive ? bag.maximum : bag.exclusiveMaximum) ?? Number.POSITIVE_INFINITY; + if (def.value < curr) { + if (def.inclusive) + bag.maximum = def.value; + else + bag.exclusiveMaximum = def.value; + } + }); + inst._zod.check = (payload) => { + if (def.inclusive ? payload.value <= def.value : payload.value < def.value) { + return; + } + payload.issues.push({ + origin: numericOriginMap[typeof payload.value] ?? origin, + code: "too_big", + maximum: typeof def.value === "object" ? def.value.getTime() : def.value, + input: payload.value, + inclusive: def.inclusive, + inst, + continue: !def.abort, + }); + }; +}); +const $ZodCheckGreaterThan = /*@__PURE__*/ $constructor("$ZodCheckGreaterThan", (inst, def) => { + $ZodCheck.init(inst, def); + const origin = numericOriginMap[typeof def.value]; + inst._zod.onattach.push((inst) => { + const bag = inst._zod.bag; + const curr = (def.inclusive ? bag.minimum : bag.exclusiveMinimum) ?? Number.NEGATIVE_INFINITY; + if (def.value > curr) { + if (def.inclusive) + bag.minimum = def.value; + else + bag.exclusiveMinimum = def.value; + } + }); + inst._zod.check = (payload) => { + if (def.inclusive ? payload.value >= def.value : payload.value > def.value) { + return; + } + payload.issues.push({ + origin: numericOriginMap[typeof payload.value] ?? origin, + code: "too_small", + minimum: typeof def.value === "object" ? def.value.getTime() : def.value, + input: payload.value, + inclusive: def.inclusive, + inst, + continue: !def.abort, + }); + }; +}); +const $ZodCheckMultipleOf = +/*@__PURE__*/ $constructor("$ZodCheckMultipleOf", (inst, def) => { + $ZodCheck.init(inst, def); + inst._zod.onattach.push((inst) => { + var _a; + (_a = inst._zod.bag).multipleOf ?? (_a.multipleOf = def.value); + }); + inst._zod.check = (payload) => { + if (typeof payload.value !== typeof def.value) + throw new Error("Cannot mix number and bigint in multiple_of check."); + const isMultiple = typeof payload.value === "bigint" + ? // `value % 0n` throws, and nothing is a multiple of zero — the number branch already fails this way via NaN + def.value !== BigInt(0) && payload.value % def.value === BigInt(0) + : floatSafeRemainder(payload.value, def.value) === 0; + if (isMultiple) + return; + payload.issues.push({ + origin: typeof payload.value, + code: "not_multiple_of", + divisor: def.value, + input: payload.value, + inst, + continue: !def.abort, + }); + }; +}); +const $ZodCheckNumberFormat = /*@__PURE__*/ $constructor("$ZodCheckNumberFormat", (inst, def) => { + $ZodCheck.init(inst, def); // no format checks + def.format = def.format || "float64"; + const isInt = def.format?.includes("int"); + const origin = isInt ? "int" : "number"; + const [minimum, maximum] = NUMBER_FORMAT_RANGES[def.format]; + inst._zod.onattach.push((inst) => { + const bag = inst._zod.bag; + bag.format = def.format; + bag.minimum = minimum; + bag.maximum = maximum; + if (isInt) + bag.pattern = integer; + }); + inst._zod.check = (payload) => { + const input = payload.value; + if (isInt) { + if (!Number.isInteger(input)) { + // invalid_format issue + // payload.issues.push({ + // expected: def.format, + // format: def.format, + // code: "invalid_format", + // input, + // inst, + // }); + // invalid_type issue + payload.issues.push({ + expected: origin, + format: def.format, + code: "invalid_type", + continue: false, + input, + inst, + }); + return; + // not_multiple_of issue + // payload.issues.push({ + // code: "not_multiple_of", + // origin: "number", + // input, + // inst, + // divisor: 1, + // }); + } + if (!Number.isSafeInteger(input)) { + if (input > 0) { + // too_big + payload.issues.push({ + input, + code: "too_big", + maximum: Number.MAX_SAFE_INTEGER, + note: "Integers must be within the safe integer range.", + inst, + origin, + inclusive: true, + continue: !def.abort, + }); + } + else { + // too_small + payload.issues.push({ + input, + code: "too_small", + minimum: Number.MIN_SAFE_INTEGER, + note: "Integers must be within the safe integer range.", + inst, + origin, + inclusive: true, + continue: !def.abort, + }); + } + return; + } + } + if (input < minimum) { + payload.issues.push({ + origin: "number", + input, + code: "too_small", + minimum, + inclusive: true, + inst, + continue: !def.abort, + }); + } + if (input > maximum) { + payload.issues.push({ + origin: "number", + input, + code: "too_big", + maximum, + inclusive: true, + inst, + continue: !def.abort, + }); + } + }; +}); +const $ZodCheckBigIntFormat = /*@__PURE__*/ (/* unused pure expression or super */ null && (core.$constructor("$ZodCheckBigIntFormat", (inst, def) => { + $ZodCheck.init(inst, def); // no format checks + const [minimum, maximum] = util.BIGINT_FORMAT_RANGES[def.format]; + inst._zod.onattach.push((inst) => { + const bag = inst._zod.bag; + bag.format = def.format; + bag.minimum = minimum; + bag.maximum = maximum; + }); + inst._zod.check = (payload) => { + const input = payload.value; + if (input < minimum) { + payload.issues.push({ + origin: "bigint", + input, + code: "too_small", + minimum: minimum, + inclusive: true, + inst, + continue: !def.abort, + }); + } + if (input > maximum) { + payload.issues.push({ + origin: "bigint", + input, + code: "too_big", + maximum, + inclusive: true, + inst, + continue: !def.abort, + }); + } + }; +}))); +const $ZodCheckMaxSize = /*@__PURE__*/ (/* unused pure expression or super */ null && (core.$constructor("$ZodCheckMaxSize", (inst, def) => { + var _a; + $ZodCheck.init(inst, def); + (_a = inst._zod.def).when ?? (_a.when = _whenHasSize); + inst._zod.onattach.push((inst) => { + const curr = (inst._zod.bag.maximum ?? Number.POSITIVE_INFINITY); + if (def.maximum < curr) + inst._zod.bag.maximum = def.maximum; + }); + inst._zod.check = (payload) => { + const input = payload.value; + const size = input.size; + if (size <= def.maximum) + return; + payload.issues.push({ + origin: util.getSizableOrigin(input), + code: "too_big", + maximum: def.maximum, + inclusive: true, + input, + inst, + continue: !def.abort, + }); + }; +}))); +const $ZodCheckMinSize = /*@__PURE__*/ (/* unused pure expression or super */ null && (core.$constructor("$ZodCheckMinSize", (inst, def) => { + var _a; + $ZodCheck.init(inst, def); + (_a = inst._zod.def).when ?? (_a.when = _whenHasSize); + inst._zod.onattach.push((inst) => { + const curr = (inst._zod.bag.minimum ?? Number.NEGATIVE_INFINITY); + if (def.minimum > curr) + inst._zod.bag.minimum = def.minimum; + }); + inst._zod.check = (payload) => { + const input = payload.value; + const size = input.size; + if (size >= def.minimum) + return; + payload.issues.push({ + origin: util.getSizableOrigin(input), + code: "too_small", + minimum: def.minimum, + inclusive: true, + input, + inst, + continue: !def.abort, + }); + }; +}))); +const $ZodCheckSizeEquals = /*@__PURE__*/ (/* unused pure expression or super */ null && (core.$constructor("$ZodCheckSizeEquals", (inst, def) => { + var _a; + $ZodCheck.init(inst, def); + (_a = inst._zod.def).when ?? (_a.when = _whenHasSize); + inst._zod.onattach.push((inst) => { + const bag = inst._zod.bag; + bag.minimum = def.size; + bag.maximum = def.size; + bag.size = def.size; + }); + inst._zod.check = (payload) => { + const input = payload.value; + const size = input.size; + if (size === def.size) + return; + const tooBig = size > def.size; + payload.issues.push({ + origin: util.getSizableOrigin(input), + ...(tooBig ? { code: "too_big", maximum: def.size } : { code: "too_small", minimum: def.size }), + inclusive: true, + exact: true, + input: payload.value, + inst, + continue: !def.abort, + }); + }; +}))); +const $ZodCheckMaxLength = /*@__PURE__*/ $constructor("$ZodCheckMaxLength", (inst, def) => { + var _a; + $ZodCheck.init(inst, def); + (_a = inst._zod.def).when ?? (_a.when = _whenHasLength); + inst._zod.onattach.push((inst) => { + const curr = (inst._zod.bag.maximum ?? Number.POSITIVE_INFINITY); + if (def.maximum < curr) + inst._zod.bag.maximum = def.maximum; + }); + inst._zod.check = (payload) => { + const input = payload.value; + const units = input.length; + // Strings are measured in Unicode code points, not UTF-16 units. A code point is at most two units, so a string that already fits in units fits in code points; only an overflow has to be counted. + const length = typeof input === "string" && units > def.maximum ? codePointLength(input) : units; + if (length <= def.maximum) + return; + const origin = getLengthableOrigin(input); + payload.issues.push({ + origin, + code: "too_big", + maximum: def.maximum, + inclusive: true, + input, + inst, + continue: !def.abort, + }); + }; +}); +const $ZodCheckMinLength = /*@__PURE__*/ $constructor("$ZodCheckMinLength", (inst, def) => { + var _a; + $ZodCheck.init(inst, def); + (_a = inst._zod.def).when ?? (_a.when = _whenHasLength); + inst._zod.onattach.push((inst) => { + const curr = (inst._zod.bag.minimum ?? Number.NEGATIVE_INFINITY); + if (def.minimum > curr) + inst._zod.bag.minimum = def.minimum; + }); + inst._zod.check = (payload) => { + const input = payload.value; + const units = input.length; + // A code point is one or two UTF-16 units, so fewer units than the floor can never reach it and twice the floor always clears it. Only in between is the exact count in doubt. + const length = typeof input === "string" && units >= def.minimum && units < def.minimum * 2 + ? codePointLength(input) + : units; + if (length >= def.minimum) + return; + const origin = getLengthableOrigin(input); + payload.issues.push({ + origin, + code: "too_small", + minimum: def.minimum, + inclusive: true, + input, + inst, + continue: !def.abort, + }); + }; +}); +const $ZodCheckLengthEquals = /*@__PURE__*/ $constructor("$ZodCheckLengthEquals", (inst, def) => { + var _a; + $ZodCheck.init(inst, def); + (_a = inst._zod.def).when ?? (_a.when = _whenHasLength); + inst._zod.onattach.push((inst) => { + const bag = inst._zod.bag; + bag.minimum = def.length; + bag.maximum = def.length; + bag.length = def.length; + }); + inst._zod.check = (payload) => { + const input = payload.value; + const units = input.length; + // A code point is one or two UTF-16 units, so outside `[length, length * 2]` units the target is missed either way — and missed in the same direction in both measures. + const length = typeof input === "string" && units >= def.length && units <= def.length * 2 + ? codePointLength(input) + : units; + if (length === def.length) + return; + const origin = getLengthableOrigin(input); + const tooBig = length > def.length; + payload.issues.push({ + origin, + ...(tooBig ? { code: "too_big", maximum: def.length } : { code: "too_small", minimum: def.length }), + inclusive: true, + exact: true, + input: payload.value, + inst, + continue: !def.abort, + }); + }; +}); +const $ZodCheckStringFormat = /*@__PURE__*/ $constructor("$ZodCheckStringFormat", (inst, def) => { + var _a, _b; + $ZodCheck.init(inst, def); + inst._zod.onattach.push((inst) => { + const bag = inst._zod.bag; + bag.format = def.format; + if (def.pattern) { + bag.patterns ?? (bag.patterns = new Set()); + bag.patterns.add(def.pattern); + } + }); + if (def.pattern) + (_a = inst._zod).check ?? (_a.check = (payload) => { + def.pattern.lastIndex = 0; + if (def.pattern.test(payload.value)) + return; + payload.issues.push({ + origin: "string", + code: "invalid_format", + format: def.format, + input: payload.value, + ...(def.pattern ? { pattern: def.pattern.toString() } : {}), + inst, + continue: !def.abort, + }); + }); + else + (_b = inst._zod).check ?? (_b.check = () => { }); +}); +const $ZodCheckRegex = /*@__PURE__*/ $constructor("$ZodCheckRegex", (inst, def) => { + $ZodCheckStringFormat.init(inst, def); + inst._zod.check = (payload) => { + def.pattern.lastIndex = 0; + if (def.pattern.test(payload.value)) + return; + payload.issues.push({ + origin: "string", + code: "invalid_format", + format: "regex", + input: payload.value, + pattern: def.pattern.toString(), + inst, + continue: !def.abort, + }); + }; +}); +const $ZodCheckLowerCase = /*@__PURE__*/ $constructor("$ZodCheckLowerCase", (inst, def) => { + def.pattern ?? (def.pattern = lowercase); + $ZodCheckStringFormat.init(inst, def); +}); +const $ZodCheckUpperCase = /*@__PURE__*/ $constructor("$ZodCheckUpperCase", (inst, def) => { + def.pattern ?? (def.pattern = uppercase); + $ZodCheckStringFormat.init(inst, def); +}); +const $ZodCheckIncludes = /*@__PURE__*/ $constructor("$ZodCheckIncludes", (inst, def) => { + $ZodCheck.init(inst, def); + const escapedRegex = escapeRegex(def.includes); + // `String.prototype.includes(sub, position)` matches `sub` at `position` + // OR LATER, so the pattern must allow at least `position` leading chars + // (`{N,}`), not exactly `position` chars (`{N}`). + const pattern = new RegExp(typeof def.position === "number" ? `^.{${def.position},}${escapedRegex}` : escapedRegex); + def.pattern = pattern; + inst._zod.onattach.push((inst) => { + const bag = inst._zod.bag; + bag.patterns ?? (bag.patterns = new Set()); + bag.patterns.add(pattern); + }); + inst._zod.check = (payload) => { + if (payload.value.includes(def.includes, def.position)) + return; + payload.issues.push({ + origin: "string", + code: "invalid_format", + format: "includes", + includes: def.includes, + input: payload.value, + inst, + continue: !def.abort, + }); + }; +}); +const $ZodCheckStartsWith = /*@__PURE__*/ $constructor("$ZodCheckStartsWith", (inst, def) => { + $ZodCheck.init(inst, def); + const pattern = new RegExp(`^${escapeRegex(def.prefix)}.*`); + def.pattern ?? (def.pattern = pattern); + inst._zod.onattach.push((inst) => { + const bag = inst._zod.bag; + bag.patterns ?? (bag.patterns = new Set()); + bag.patterns.add(pattern); + }); + inst._zod.check = (payload) => { + if (payload.value.startsWith(def.prefix)) + return; + payload.issues.push({ + origin: "string", + code: "invalid_format", + format: "starts_with", + prefix: def.prefix, + input: payload.value, + inst, + continue: !def.abort, + }); + }; +}); +const $ZodCheckEndsWith = /*@__PURE__*/ $constructor("$ZodCheckEndsWith", (inst, def) => { + $ZodCheck.init(inst, def); + const pattern = new RegExp(`.*${escapeRegex(def.suffix)}$`); + def.pattern ?? (def.pattern = pattern); + inst._zod.onattach.push((inst) => { + const bag = inst._zod.bag; + bag.patterns ?? (bag.patterns = new Set()); + bag.patterns.add(pattern); + }); + inst._zod.check = (payload) => { + if (payload.value.endsWith(def.suffix)) + return; + payload.issues.push({ + origin: "string", + code: "invalid_format", + format: "ends_with", + suffix: def.suffix, + input: payload.value, + inst, + continue: !def.abort, + }); + }; +}); +/////////////////////////////////// +///// $ZodCheckProperty ///// +/////////////////////////////////// +function handleCheckPropertyResult(result, payload, property) { + if (result.issues.length) { + payload.issues.push(...util.prefixIssues(property, result.issues)); + } +} +const $ZodCheckProperty = /*@__PURE__*/ (/* unused pure expression or super */ null && (core.$constructor("$ZodCheckProperty", (inst, def) => { + $ZodCheck.init(inst, def); + inst._zod.check = (payload) => { + const result = def.schema._zod.run({ + value: payload.value[def.property], + issues: [], + }, {}); + if (result instanceof Promise) { + return result.then((result) => handleCheckPropertyResult(result, payload, def.property)); + } + handleCheckPropertyResult(result, payload, def.property); + return; + }; +}))); +const $ZodCheckMimeType = /*@__PURE__*/ (/* unused pure expression or super */ null && (core.$constructor("$ZodCheckMimeType", (inst, def) => { + $ZodCheck.init(inst, def); + const mimeSet = new Set(def.mime); + inst._zod.onattach.push((inst) => { + inst._zod.bag.mime = def.mime; + }); + inst._zod.check = (payload) => { + if (mimeSet.has(payload.value.type)) + return; + payload.issues.push({ + code: "invalid_value", + values: def.mime, + input: payload.value.type, + inst, + continue: !def.abort, + }); + }; +}))); +const $ZodCheckOverwrite = /*@__PURE__*/ $constructor("$ZodCheckOverwrite", (inst, def) => { + $ZodCheck.init(inst, def); + inst._zod.check = (payload) => { + payload.value = def.tx(payload.value); + }; +}); + +class Doc { + constructor(args = [], closed = {}) { + this.content = []; + this.indent = 0; + this.args = args; + this.closed = closed; + } + indented(fn) { + this.indent += 1; + fn(this); + this.indent -= 1; + } + write(arg) { + if (typeof arg === "function") { + arg(this, { execution: "sync" }); + arg(this, { execution: "async" }); + return; + } + const content = arg; + const lines = content.split("\n").filter((x) => x); + const minIndent = Math.min(...lines.map((x) => x.length - x.trimStart().length)); + const dedented = lines.map((x) => x.slice(minIndent)).map((x) => " ".repeat(this.indent * 2) + x); + for (const line of dedented) { + this.content.push(line); + } + } + compile() { + const F = Function; + const content = this?.content ?? [``]; + const factory = new F(...Object.keys(this.closed), `return function (${this.args.join(", ")}) {\n${content.join("\n")}\n};`); + return factory(...Object.values(this.closed)); + } +} + + + +/* Computing the message eagerly is expensive (pretty-printed JSON of all + * issues), so defer it until first read. The accessor functions and + * descriptors are shared across instances to keep error construction + * cheap; the computed message is cached on the internals object. The + * setter preserves plain assignment semantics for consumers that + * overwrite `message`. */ +function _getMessage() { + const internals = this._zod; + internals.message ?? (internals.message = JSON.stringify(internals.def, jsonStringifyReplacer, 2)); + return internals.message; +} +function _setMessage(value) { + this._zod.message = value; +} +const _messageDesc = { + get: _getMessage, + set: _setMessage, + enumerable: true, + configurable: true, +}; +const errors_zodDesc = { value: undefined, enumerable: false }; +const _issuesDesc = { value: undefined, enumerable: false }; +/* Prototypes that already carry the lazy `toString`. Seeded with the + * intrinsics so that `init` on a foreign object — it accepts any object — + * can never install an accessor onto a prototype we do not own. */ +const _installedToString = /* @__PURE__ */ new WeakSet([Object.prototype, Error.prototype]); +const errors_initializer = (inst, def) => { + inst.name = "$ZodError"; + errors_zodDesc.value = inst._zod; + Object.defineProperty(inst, "_zod", errors_zodDesc); + _issuesDesc.value = def; + Object.defineProperty(inst, "issues", _issuesDesc); + // Clear the shared slots; a retained `value` pins the last error's issues. + errors_zodDesc.value = undefined; + _issuesDesc.value = undefined; + Object.defineProperty(inst, "message", _messageDesc); + /* `toString` lives as a non-enumerable lazy getter on the shared + * prototype; on first access it caches a per-instance closure so + * detached usage still works. */ + const proto = Object.getPrototypeOf(inst); + if (!_installedToString.has(proto)) { + _installedToString.add(proto); + Object.defineProperty(proto, "toString", { + configurable: true, + enumerable: false, + get() { + const value = () => this.message; + Object.defineProperty(this, "toString", { value, configurable: true, writable: true }); + return value; + }, + set(value) { + Object.defineProperty(this, "toString", { value, configurable: true, writable: true }); + }, + }); + } +}; +const $ZodError = $constructor("$ZodError", errors_initializer); +const $ZodRealError = $constructor("$ZodError", errors_initializer, undefined, { + Parent: Error, +}); +/** Get-or-create `obj[key]` as an own data property. A path segment naming an inherited member + * ("toString", "constructor") would otherwise read through to the prototype, and assigning + * "__proto__" would hit the setter instead of creating a key. */ +function errors_node(obj, key, make) { + if (!Object.prototype.hasOwnProperty.call(obj, key)) { + if (key === "__proto__") { + Object.defineProperty(obj, key, { value: make(), writable: true, enumerable: true, configurable: true }); + } + else { + obj[key] = make(); + } + } + return obj[key]; +} +function flattenError(error, mapper = (issue) => issue.message) { + const fieldErrors = {}; + const formErrors = []; + for (const sub of error.issues) { + if (sub.path.length > 0) { + errors_node(fieldErrors, sub.path[0], () => []).push(mapper(sub)); + } + else { + formErrors.push(mapper(sub)); + } + } + return { formErrors, fieldErrors }; +} +function formatError(error, mapper = (issue) => issue.message) { + const fieldErrors = { _errors: [] }; + const processError = (error, path = []) => { + for (const issue of error.issues) { + if (issue.code === "invalid_union" && issue.errors.length) { + issue.errors.map((issues) => processError({ issues }, [...path, ...issue.path])); + } + else if (issue.code === "invalid_key") { + processError({ issues: issue.issues }, [...path, ...issue.path]); + } + else if (issue.code === "invalid_element") { + processError({ issues: issue.issues }, [...path, ...issue.path]); + } + else { + const fullpath = [...path, ...issue.path]; + if (fullpath.length === 0) { + fieldErrors._errors.push(mapper(issue)); + } + else { + let curr = fieldErrors; + let i = 0; + while (i < fullpath.length) { + const el = fullpath[i]; + const terminal = i === fullpath.length - 1; + // `_errors` is reserved by this legacy format, so merge a matching path segment into the current node instead of treating its array as a child. + if (el === "_errors") { + if (terminal) + curr._errors.push(mapper(issue)); + i++; + continue; + } + // A path element may collide with an inherited property name such as + // "__proto__" or "constructor". Truthiness checks read the prototype + // (so no node is created, then ._errors.push throws), and bracket + // assignment of "__proto__" hits the setter instead of creating an + // own key. Guard the read with hasOwnProperty and create the node + // with defineProperty so any path element becomes a real own key. + if (!Object.prototype.hasOwnProperty.call(curr, el)) { + Object.defineProperty(curr, el, { + value: { _errors: [] }, + enumerable: true, + writable: true, + configurable: true, + }); + } + const node = curr[el]; + if (terminal) { + node._errors.push(mapper(issue)); + } + curr = node; + i++; + } + } + } + } + }; + processError(error); + return fieldErrors; +} +function treeifyError(error, mapper = (issue) => issue.message) { + const result = { errors: [] }; + const processError = (error, path = []) => { + var _a; + for (const issue of error.issues) { + if (issue.code === "invalid_union" && issue.errors.length) { + // regular union error + issue.errors.map((issues) => processError({ issues }, [...path, ...issue.path])); + } + else if (issue.code === "invalid_key") { + processError({ issues: issue.issues }, [...path, ...issue.path]); + } + else if (issue.code === "invalid_element") { + processError({ issues: issue.issues }, [...path, ...issue.path]); + } + else { + const fullpath = [...path, ...issue.path]; + if (fullpath.length === 0) { + result.errors.push(mapper(issue)); + continue; + } + let curr = result; + let i = 0; + while (i < fullpath.length) { + const el = fullpath[i]; + const terminal = i === fullpath.length - 1; + if (typeof el === "string") { + curr.properties ?? (curr.properties = {}); + // el may collide with an inherited property name ("__proto__", + // "constructor", ...); ??= reads the prototype so the node is never + // created and curr.errors.push throws. Guard with hasOwnProperty and + // create the node with defineProperty so "__proto__" becomes a real + // own key rather than invoking the prototype setter. + if (!Object.prototype.hasOwnProperty.call(curr.properties, el)) { + Object.defineProperty(curr.properties, el, { + value: { errors: [] }, + enumerable: true, + writable: true, + configurable: true, + }); + } + curr = curr.properties[el]; + } + else { + curr.items ?? (curr.items = []); + (_a = curr.items)[el] ?? (_a[el] = { errors: [] }); + curr = curr.items[el]; + } + if (terminal) { + curr.errors.push(mapper(issue)); + } + i++; + } + } + } + }; + processError(error); + return result; +} +/** Format a ZodError as a human-readable string in the following form. + * + * From + * + * ```ts + * ZodError { + * issues: [ + * { + * expected: 'string', + * code: 'invalid_type', + * path: [ 'username' ], + * message: 'Invalid input: expected string' + * }, + * { + * expected: 'number', + * code: 'invalid_type', + * path: [ 'favoriteNumbers', 1 ], + * message: 'Invalid input: expected number' + * } + * ]; + * } + * ``` + * + * to + * + * ``` + * username + * ✖ Expected number, received string at "username + * favoriteNumbers[0] + * ✖ Invalid input: expected number + * ``` + */ +function toDotPath(_path) { + const segs = []; + const path = _path.map((seg) => (typeof seg === "object" ? seg.key : seg)); + for (const seg of path) { + if (typeof seg === "number") + segs.push(`[${seg}]`); + else if (typeof seg === "symbol") + segs.push(`[${JSON.stringify(String(seg))}]`); + else if (/[^\w$]/.test(seg)) + segs.push(`[${JSON.stringify(seg)}]`); + else { + if (segs.length) + segs.push("."); + segs.push(seg); + } + } + return segs.join(""); +} +function prettifyError(error) { + const lines = []; + // sort by path length + const issues = [...error.issues].sort((a, b) => (a.path ?? []).length - (b.path ?? []).length); + // Process each issue + for (const issue of issues) { + lines.push(`✖ ${issue.message}`); + if (issue.path?.length) + lines.push(` → at ${toDotPath(issue.path)}`); + } + // Convert Map to formatted string + return lines.join("\n"); +} + + + + +// Always both keys, so the `_params` read site in `_parse` sees one object shape rather than two. +function finalizeParams(callee, params) { + return { callee: params?.callee ?? callee, Err: params?.Err }; +} +const parse_parse = (_Err) => { + const fn = (schema, value, _ctx, _params) => { + const ctx = _ctx ? { ..._ctx, async: false } : { async: false }; + const result = schema._zod.run({ value, issues: [] }, ctx); + if (result instanceof Promise) { + throw new $ZodAsyncError(); + } + if (result.issues.length) { + const e = new (_params?.Err ?? _Err)(result.issues.map((iss) => finalizeIssue(iss, ctx, core_config()))); + captureStackTrace(e, _params?.callee ?? fn); + throw e; + } + return result.value; + }; + return fn; +}; +const core_parse_parse = /* @__PURE__*/ parse_parse($ZodRealError); +const parse_parseAsync = (_Err) => { + const fn = async (schema, value, _ctx, params) => { + const ctx = _ctx ? { ..._ctx, async: true } : { async: true }; + let result = schema._zod.run({ value, issues: [] }, ctx); + if (result instanceof Promise) + result = await result; + if (result.issues.length) { + const e = new (params?.Err ?? _Err)(result.issues.map((iss) => finalizeIssue(iss, ctx, core_config()))); + captureStackTrace(e, params?.callee ?? fn); + throw e; + } + return result.value; + }; + return fn; +}; +const core_parse_parseAsync = /* @__PURE__*/ parse_parseAsync($ZodRealError); +const _safeParse = (_Err) => (schema, value, _ctx) => { + const ctx = _ctx ? { ..._ctx, async: false } : { async: false }; + const result = schema._zod.run({ value, issues: [] }, ctx); + if (result instanceof Promise) { + throw new $ZodAsyncError(); + } + return result.issues.length + ? { + success: false, + error: new (_Err ?? $ZodError)(result.issues.map((iss) => finalizeIssue(iss, ctx, core_config()))), + } + : { success: true, data: result.value }; +}; +const safeParse = /* @__PURE__*/ _safeParse($ZodRealError); +const _safeParseAsync = (_Err) => async (schema, value, _ctx) => { + const ctx = _ctx ? { ..._ctx, async: true } : { async: true }; + let result = schema._zod.run({ value, issues: [] }, ctx); + if (result instanceof Promise) + result = await result; + return result.issues.length + ? { + success: false, + error: new _Err(result.issues.map((iss) => finalizeIssue(iss, ctx, core_config()))), + } + : { success: true, data: result.value }; +}; +const safeParseAsync = /* @__PURE__*/ _safeParseAsync($ZodRealError); +// registry mirrors of the compiler's sentinels, so this module never imports the compiler +const COMPILE_INVALID = /* @__PURE__ */ (/* unused pure expression or super */ null && (Symbol.for("zod.compile.invalid"))); +const COMPILE_FALLBACK = /* @__PURE__ */ (/* unused pure expression or super */ null && (Symbol.for("zod.compile.fallback"))); +// Deliberately tiny, because v8 will not inline a body carrying the fallback's object literals and throw. Everything that is not the compiled happy path lives in validateFallback, and that split is worth ~35% on a compiled schema. +const parse_validate = ((schema, value, _ctx) => { + const validator = schema._zod.bag.validator; + if (validator !== undefined && validator(value) !== COMPILE_INVALID) + return true; + return validateFallback(schema, value, _ctx); +}); +function validateFallback(schema, value, _ctx) { + const ctx = _ctx ? { ..._ctx, async: false } : { async: false }; + const fallbackRun = schema._zod.bag.fallbackRun; + let result; + if (fallbackRun) { + // skip nested fast paths on the fallback, so user callbacks keep the at-most-twice bound + ctx[COMPILE_FALLBACK] = true; + result = fallbackRun({ value, issues: [] }, ctx); + } + else { + result = schema._zod.run({ value, issues: [] }, ctx); + } + if (result instanceof Promise) { + throw new core.$ZodAsyncError(); + } + return result.issues.length === 0; +} +// no fast path: the compiler keeps async parses on the runtime, because a promise-returning callback that is not declared async compiles to a throw +const parse_validateAsync = async (schema, value, _ctx) => { + const ctx = _ctx ? { ..._ctx, async: true } : { async: true }; + let result = schema._zod.run({ value, issues: [] }, ctx); + if (result instanceof Promise) + result = await result; + return result.issues.length === 0; +}; +const parse_encode = (_Err) => { + const parse = parse_parse(_Err); + const fn = (schema, value, _ctx, _params) => { + const ctx = _ctx ? { ..._ctx, direction: "backward" } : { direction: "backward" }; + return parse(schema, value, ctx, finalizeParams(fn, _params)); + }; + return fn; +}; +const encode = /* @__PURE__*/ parse_encode($ZodRealError); +const parse_decode = (_Err) => { + const parse = parse_parse(_Err); + const fn = (schema, value, _ctx, _params) => { + return parse(schema, value, _ctx, finalizeParams(fn, _params)); + }; + return fn; +}; +const decode = /* @__PURE__*/ parse_decode($ZodRealError); +const parse_encodeAsync = (_Err) => { + const parseAsync = parse_parseAsync(_Err); + const fn = async (schema, value, _ctx, _params) => { + const ctx = _ctx ? { ..._ctx, direction: "backward" } : { direction: "backward" }; + return (await parseAsync(schema, value, ctx, finalizeParams(fn, _params))); + }; + return fn; +}; +const encodeAsync = /* @__PURE__*/ parse_encodeAsync($ZodRealError); +const parse_decodeAsync = (_Err) => { + const parseAsync = parse_parseAsync(_Err); + const fn = async (schema, value, _ctx, _params) => { + return await parseAsync(schema, value, _ctx, finalizeParams(fn, _params)); + }; + return fn; +}; +const decodeAsync = /* @__PURE__*/ parse_decodeAsync($ZodRealError); +const _safeEncode = (_Err) => (schema, value, _ctx) => { + const ctx = _ctx ? { ..._ctx, direction: "backward" } : { direction: "backward" }; + return _safeParse(_Err)(schema, value, ctx); +}; +const safeEncode = /* @__PURE__*/ _safeEncode($ZodRealError); +const _safeDecode = (_Err) => (schema, value, _ctx) => { + return _safeParse(_Err)(schema, value, _ctx); +}; +const safeDecode = /* @__PURE__*/ _safeDecode($ZodRealError); +const _safeEncodeAsync = (_Err) => async (schema, value, _ctx) => { + const ctx = _ctx ? { ..._ctx, direction: "backward" } : { direction: "backward" }; + return _safeParseAsync(_Err)(schema, value, ctx); +}; +const safeEncodeAsync = /* @__PURE__*/ _safeEncodeAsync($ZodRealError); +const _safeDecodeAsync = (_Err) => async (schema, value, _ctx) => { + return _safeParseAsync(_Err)(schema, value, _ctx); +}; +const safeDecodeAsync = /* @__PURE__*/ _safeDecodeAsync($ZodRealError); + +const versions_version = { + major: 4, + minor: 5, + patch: 4, +}; + + + + + + + + +const $ZodType = /*@__PURE__*/ $constructor("$ZodType", (inst, def) => { + var _a; + inst ?? (inst = {}); + inst._zod.def = def; // set _def property + inst._zod.bag = inst._zod.bag || {}; // initialize _bag object + inst._zod.version = versions_version; + const defChecks = inst._zod.def.checks; + // if inst is itself a checks.$ZodCheck, run it as a check + const checks = inst._zod.traits.has("$ZodCheck") + ? [inst, ...(defChecks ?? [])] + : defChecks?.length + ? [...defChecks] + : []; + for (const ch of checks) { + for (const fn of ch._zod.onattach) { + fn(inst); + } + } + if (checks.length === 0) { + // deferred initializer inst._zod.parse is not yet defined + (_a = inst._zod).deferred ?? (_a.deferred = []); + inst._zod.deferred?.push(() => { + inst._zod.run = inst._zod.parse; + }); + } + else { + const runChecks = (payload, checks, ctx) => { + if (payload.memo) + return payload; + let isAborted = aborted(payload); + let asyncResult; + for (const ch of checks) { + if (ch._zod.def.when) { + if (explicitlyAborted(payload)) + continue; + const shouldRun = ch._zod.def.when(payload); + if (!shouldRun) + continue; + } + else if (isAborted) { + continue; + } + const currLen = payload.issues.length; + const _ = ch._zod.check(payload); + if (_ instanceof Promise && ctx?.async === false) { + throw new $ZodAsyncError(); + } + if (asyncResult || _ instanceof Promise) { + asyncResult = (asyncResult ?? Promise.resolve()).then(async () => { + await _; + const nextLen = payload.issues.length; + if (nextLen === currLen) + return; + attachSchema(payload.issues, currLen, inst); + if (!isAborted) + isAborted = aborted(payload, currLen); + }); + } + else { + const nextLen = payload.issues.length; + if (nextLen === currLen) + continue; + attachSchema(payload.issues, currLen, inst); + if (!isAborted) + isAborted = aborted(payload, currLen); + } + } + if (asyncResult) { + return asyncResult.then(() => { + return payload; + }); + } + return payload; + }; + const handleCanaryResult = (canary, payload, ctx) => { + // abort if the canary is aborted + if (aborted(canary)) { + canary.aborted = true; + return canary; + } + // run checks first, then + const checkResult = runChecks(payload, checks, ctx); + if (checkResult instanceof Promise) { + if (ctx.async === false) + throw new $ZodAsyncError(); + return checkResult.then((checkResult) => inst._zod.parse(checkResult, ctx)); + } + return inst._zod.parse(checkResult, ctx); + }; + inst._zod.run = (payload, ctx) => { + if (ctx.skipChecks) { + return inst._zod.parse(payload, ctx); + } + if (ctx.direction === "backward") { + // run canary initial pass (no checks) + const canary = inst._zod.parse({ value: payload.value, issues: [] }, { ...ctx, skipChecks: true }); + if (canary instanceof Promise) { + return canary.then((canary) => { + return handleCanaryResult(canary, payload, ctx); + }); + } + return handleCanaryResult(canary, payload, ctx); + } + // forward + const result = inst._zod.parse(payload, ctx); + if (result instanceof Promise) { + if (ctx.async === false) + throw new $ZodAsyncError(); + return result.then((result) => runChecks(result, checks, ctx)); + } + return runChecks(result, checks, ctx); + }; + } +}, { + // Wrappers extend this by installing a richer factory over it; reading it eagerly would defeat the laziness. + get "~standard"() { + return hide(this, "~standard", standardProps(this)); + }, + set "~standard"(value) { + util_own(this, "~standard", value); + }, +}); +/** The Standard Schema surface for `inst`. Shared so wrappers can extend it without forcing it. */ +const toStandardResult = (r) => r.success ? { value: r.data } : { issues: r.error?.issues }; +function standardProps(inst) { + return { + validate: (value) => { + try { + return toStandardResult(safeParse(inst, value)); + } + catch (_) { + return safeParseAsync(inst, value).then(toStandardResult); + } + }, + vendor: "zod", + version: 1, + }; +} + +const $ZodString = /*@__PURE__*/ $constructor("$ZodString", (inst, def) => { + $ZodType.init(inst, def); + inst._zod.pattern = [...(inst?._zod.bag?.patterns ?? [])].pop() ?? regexes_string(inst._zod.bag); + inst._zod.parse = (payload, _) => { + if (def.coerce) + try { + payload.value = String(payload.value); + } + catch (_) { } + if (typeof payload.value === "string") + return payload; + payload.issues.push({ + expected: "string", + code: "invalid_type", + input: payload.value, + inst, + }); + return payload; + }; +}); +const $ZodStringFormat = /*@__PURE__*/ $constructor("$ZodStringFormat", (inst, def) => { + // check initialization must come first + $ZodCheckStringFormat.init(inst, def); + $ZodString.init(inst, def); +}); +const $ZodGUID = /*@__PURE__*/ $constructor("$ZodGUID", (inst, def) => { + def.pattern ?? (def.pattern = guid); + $ZodStringFormat.init(inst, def); +}); +const $ZodUUID = /*@__PURE__*/ $constructor("$ZodUUID", (inst, def) => { + if (def.version) { + const versionMap = { + v1: 1, + v2: 2, + v3: 3, + v4: 4, + v5: 5, + v6: 6, + v7: 7, + v8: 8, + }; + const v = versionMap[def.version]; + if (v === undefined) + throw new Error(`Invalid UUID version: "${def.version}"`); + def.pattern ?? (def.pattern = uuid(v)); + } + else + def.pattern ?? (def.pattern = uuid()); + $ZodStringFormat.init(inst, def); +}); +const $ZodEmail = /*@__PURE__*/ $constructor("$ZodEmail", (inst, def) => { + def.pattern ?? (def.pattern = email); + $ZodStringFormat.init(inst, def); +}); +/** The `://` guard rejected the input before the URL constructor saw it. */ +const URL_BAD_FORMAT = 1; +/** The URL constructor rejected the input. */ +const URL_UNPARSEABLE = 2; +/** Parses a URL for `$ZodURL`, applying the one guard the URL constructor cannot express. Returns the parsed URL, or a code naming the stage that rejected it — the runtime needs that distinction to pick an issue note, and compiled code only needs to know it is not a URL. */ +function parseURLObject(trimmed, def) { + // When normalize is off, require :// for http/https URLs. This prevents strings like "http:example.com" or "https:/path" from being silently accepted + if (!def.normalize && def.protocol?.source === httpProtocol.source && !/^https?:\/\//i.test(trimmed)) { + return URL_BAD_FORMAT; + } + try { + // @ts-ignore + return new URL(trimmed); + } + catch { + return URL_UNPARSEABLE; + } +} +const asciiTabOrNewline = /[\t\n\r]/g; +/** The URL parser deletes every ASCII tab, LF and CR from its input before it parses, so `new URL("https://exa\nmple.com")` reports on `example.com`. Applying the same deletion to the returned value closes the half of that divergence which can move the host; the parser's other rewrite, stripping C0 controls at the edges, cannot. */ +function stripTabAndNewline(value) { + return value.replace(asciiTabOrNewline, ""); +} +function urlHostnameOk(url, hostname) { + hostname.lastIndex = 0; + return hostname.test(url.hostname); +} +function urlProtocolOk(url, protocol) { + protocol.lastIndex = 0; + return protocol.test(url.protocol.endsWith(":") ? url.protocol.slice(0, -1) : url.protocol); +} +const $ZodURL = /*@__PURE__*/ $constructor("$ZodURL", (inst, def) => { + $ZodStringFormat.init(inst, def); + inst._zod.check = (payload) => { + try { + // Trim whitespace from input + const trimmed = payload.value.trim(); + const url = parseURLObject(trimmed, def); + if (url === URL_BAD_FORMAT) { + payload.issues.push({ + code: "invalid_format", + format: "url", + note: "Invalid URL format", + input: payload.value, + inst, + continue: !def.abort, + }); + return; + } + if (url === URL_UNPARSEABLE) { + payload.issues.push({ + code: "invalid_format", + format: "url", + input: payload.value, + inst, + continue: !def.abort, + }); + return; + } + if (def.hostname && !urlHostnameOk(url, def.hostname)) { + payload.issues.push({ + code: "invalid_format", + format: "url", + note: "Invalid hostname", + pattern: def.hostname.source, + input: payload.value, + inst, + continue: !def.abort, + }); + } + if (def.protocol && !urlProtocolOk(url, def.protocol)) { + payload.issues.push({ + code: "invalid_format", + format: "url", + note: "Invalid protocol", + pattern: def.protocol.source, + input: payload.value, + inst, + continue: !def.abort, + }); + } + // Set the output value based on normalize flag + payload.value = def.normalize ? url.href : stripTabAndNewline(trimmed); + return; + } + catch (_) { + payload.issues.push({ + code: "invalid_format", + format: "url", + input: payload.value, + inst, + continue: !def.abort, + }); + } + }; +}); +const $ZodEmoji = /*@__PURE__*/ $constructor("$ZodEmoji", (inst, def) => { + def.pattern ?? (def.pattern = emoji()); + $ZodStringFormat.init(inst, def); +}); +const $ZodNanoID = /*@__PURE__*/ $constructor("$ZodNanoID", (inst, def) => { + if (def.length !== undefined && (!Number.isInteger(def.length) || def.length < 1)) + throw new Error(`Invalid nanoid length: ${def.length}`); + def.pattern ?? (def.pattern = def.length === undefined ? nanoid : nanoidOfLength(def.length)); + $ZodStringFormat.init(inst, def); +}); +/** + * @deprecated CUID v1 is deprecated by its authors due to information leakage + * (timestamps embedded in the id). Use {@link $ZodCUID2} instead. + * See https://github.com/paralleldrive/cuid. + */ +const $ZodCUID = /*@__PURE__*/ $constructor("$ZodCUID", (inst, def) => { + def.pattern ?? (def.pattern = cuid); + $ZodStringFormat.init(inst, def); +}); +const $ZodCUID2 = /*@__PURE__*/ $constructor("$ZodCUID2", (inst, def) => { + def.pattern ?? (def.pattern = cuid2); + $ZodStringFormat.init(inst, def); +}); +const $ZodULID = /*@__PURE__*/ $constructor("$ZodULID", (inst, def) => { + def.pattern ?? (def.pattern = ulid); + $ZodStringFormat.init(inst, def); +}); +const $ZodXID = /*@__PURE__*/ $constructor("$ZodXID", (inst, def) => { + def.pattern ?? (def.pattern = xid); + $ZodStringFormat.init(inst, def); +}); +const $ZodKSUID = /*@__PURE__*/ $constructor("$ZodKSUID", (inst, def) => { + def.pattern ?? (def.pattern = ksuid); + $ZodStringFormat.init(inst, def); +}); +const $ZodISODateTime = /*@__PURE__*/ $constructor("$ZodISODateTime", (inst, def) => { + def.pattern ?? (def.pattern = datetime(def)); + $ZodStringFormat.init(inst, def); + // these two drop the offset or seconds `date-time` requires — on the bag not the def, since `z.string().check(...)` lands the format on a different schema + if (def.local || def.precision === -1) { + inst._zod.bag.laxFormat = true; + inst._zod.onattach.push((s) => { + s._zod.bag.laxFormat = true; + }); + } +}); +const $ZodISODate = /*@__PURE__*/ $constructor("$ZodISODate", (inst, def) => { + def.pattern ?? (def.pattern = regexes_date); + $ZodStringFormat.init(inst, def); +}); +const $ZodISOTime = /*@__PURE__*/ $constructor("$ZodISOTime", (inst, def) => { + def.pattern ?? (def.pattern = regexes_time(def)); + $ZodStringFormat.init(inst, def); +}); +const $ZodISODuration = /*@__PURE__*/ $constructor("$ZodISODuration", (inst, def) => { + def.pattern ?? (def.pattern = duration); + $ZodStringFormat.init(inst, def); +}); +const $ZodIPv4 = /*@__PURE__*/ $constructor("$ZodIPv4", (inst, def) => { + def.pattern ?? (def.pattern = ipv4); + $ZodStringFormat.init(inst, def); + inst._zod.bag.format = `ipv4`; +}); +/** An IPv6 address is written with hex digits, colons and dots, and nothing else. The guard is what makes the check below an IPv6 check: `new URL("http://[...]")` parses an authority, not an address, so `@` and `\` re-delimit it and `"::@1\\"` validates against the host `0.0.0.1`. The URL parser also deletes ASCII tab, LF and CR rather than failing, which is how `"::1\n"` validated as `::1`. */ +const ipv6Alphabet = /^[0-9a-fA-F:.]+$/; +function isValidIPv6(value) { + if (!ipv6Alphabet.test(value)) + return false; + try { + // @ts-ignore + new URL(`http://[${value}]`); + return true; + } + catch { + return false; + } +} +const $ZodIPv6 = /*@__PURE__*/ $constructor("$ZodIPv6", (inst, def) => { + def.pattern ?? (def.pattern = regexes_ipv6); + $ZodStringFormat.init(inst, def); + inst._zod.bag.format = `ipv6`; + inst._zod.check = (payload) => { + if (!isValidIPv6(payload.value)) { + payload.issues.push({ + code: "invalid_format", + format: "ipv6", + input: payload.value, + inst, + continue: !def.abort, + }); + } + }; +}); +const $ZodMAC = /*@__PURE__*/ (/* unused pure expression or super */ null && (core.$constructor("$ZodMAC", (inst, def) => { + def.pattern ?? (def.pattern = regexes.mac(def.delimiter)); + $ZodStringFormat.init(inst, def); + inst._zod.bag.format = `mac`; +}))); +const $ZodCIDRv4 = /*@__PURE__*/ $constructor("$ZodCIDRv4", (inst, def) => { + def.pattern ?? (def.pattern = cidrv4); + $ZodStringFormat.init(inst, def); +}); +function isValidCIDRv6(value) { + const parts = value.split("/"); + if (parts.length !== 2) + return false; + const [address, prefix] = parts; + if (!prefix) + return false; + const prefixNum = Number(prefix); + if (`${prefixNum}` !== prefix) + return false; + if (prefixNum < 0 || prefixNum > 128) + return false; + return isValidIPv6(address); +} +const $ZodCIDRv6 = /*@__PURE__*/ $constructor("$ZodCIDRv6", (inst, def) => { + def.pattern ?? (def.pattern = cidrv6); // not used for validation + $ZodStringFormat.init(inst, def); + inst._zod.check = (payload) => { + if (!isValidCIDRv6(payload.value)) { + payload.issues.push({ + code: "invalid_format", + format: "cidrv6", + input: payload.value, + inst, + continue: !def.abort, + }); + } + }; +}); +////////////////////////////// ZodBase64 ////////////////////////////// +function isValidBase64(data) { + if (data === "") + return true; + // atob ignores whitespace, so reject it up front. + if (/\s/.test(data)) + return false; + if (data.length % 4 !== 0) + return false; + try { + // @ts-ignore + atob(data); + return true; + } + catch { + return false; + } +} +const $ZodBase64 = /*@__PURE__*/ $constructor("$ZodBase64", (inst, def) => { + def.pattern ?? (def.pattern = regexes_base64); + $ZodStringFormat.init(inst, def); + inst._zod.bag.contentEncoding = "base64"; + inst._zod.check = (payload) => { + if (isValidBase64(payload.value)) + return; + payload.issues.push({ + code: "invalid_format", + format: "base64", + input: payload.value, + inst, + continue: !def.abort, + }); + }; +}); +////////////////////////////// ZodBase64 ////////////////////////////// +function isValidBase64URL(data) { + if (!regexes_base64url.test(data)) + return false; + const base64 = data.replace(/[-_]/g, (c) => (c === "-" ? "+" : "/")); + const padded = base64.padEnd(Math.ceil(base64.length / 4) * 4, "="); + return isValidBase64(padded); +} +const $ZodBase64URL = /*@__PURE__*/ $constructor("$ZodBase64URL", (inst, def) => { + def.pattern ?? (def.pattern = regexes_base64url); + $ZodStringFormat.init(inst, def); + inst._zod.bag.contentEncoding = "base64url"; + inst._zod.check = (payload) => { + if (isValidBase64URL(payload.value)) + return; + payload.issues.push({ + code: "invalid_format", + format: "base64url", + input: payload.value, + inst, + continue: !def.abort, + }); + }; +}); +const $ZodE164 = /*@__PURE__*/ $constructor("$ZodE164", (inst, def) => { + def.pattern ?? (def.pattern = e164); + $ZodStringFormat.init(inst, def); +}); +////////////////////////////// ZodCreditCard ////////////////////////////// +const CC_SANITIZE = /[- ]/g; +/** Luhn checksum on a digit-only string. Adapted from valibot (MIT). */ +function isLuhnAlgo(digits) { + let length = digits.length; + let bit = 1; + let sum = 0; + while (length) { + const value = +digits[--length]; + bit ^= 1; + sum += bit ? [0, 2, 4, 6, 8, 1, 3, 5, 7, 9][value] : value; + } + return sum % 10 === 0; +} +function isValidCreditCard(input) { + if (!regexes.creditCard.test(input)) + return false; + return isLuhnAlgo(input.replace(CC_SANITIZE, "")); +} +const $ZodCreditCard = /*@__PURE__*/ (/* unused pure expression or super */ null && (core.$constructor("$ZodCreditCard", (inst, def) => { + // Shape only — the Luhn check below is not expressible as a pattern, so consumers of `pattern` (JSON Schema, template literals) get the length and separator rules alone. + def.pattern ?? (def.pattern = regexes.creditCard); + $ZodStringFormat.init(inst, def); + inst._zod.check = (payload) => { + if (isValidCreditCard(payload.value)) + return; + payload.issues.push({ + code: "invalid_format", + format: "credit_card", + input: payload.value, + inst, + continue: !def.abort, + }); + }; +}))); +////////////////////////////// ZodJWT ////////////////////////////// +function isValidJWT(token, algorithm = null) { + try { + const tokensParts = token.split("."); + if (tokensParts.length !== 3) + return false; + const [header] = tokensParts; + if (!header) + return false; + // @ts-ignore + const parsedHeader = JSON.parse(atob(header)); + if ("typ" in parsedHeader && parsedHeader?.typ !== "JWT") + return false; + if (!parsedHeader.alg) + return false; + if (algorithm && (!("alg" in parsedHeader) || parsedHeader.alg !== algorithm)) + return false; + return true; + } + catch { + return false; + } +} +const $ZodJWT = /*@__PURE__*/ $constructor("$ZodJWT", (inst, def) => { + $ZodStringFormat.init(inst, def); + inst._zod.check = (payload) => { + if (isValidJWT(payload.value, def.alg)) + return; + payload.issues.push({ + code: "invalid_format", + format: "jwt", + input: payload.value, + inst, + continue: !def.abort, + }); + }; +}); +const $ZodCustomStringFormat = /*@__PURE__*/ (/* unused pure expression or super */ null && (core.$constructor("$ZodCustomStringFormat", (inst, def) => { + $ZodStringFormat.init(inst, def); + inst._zod.check = (payload) => { + if (def.fn(payload.value)) + return; + payload.issues.push({ + code: "invalid_format", + format: def.format, + input: payload.value, + inst, + continue: !def.abort, + }); + }; +}))); +const $ZodNumber = /*@__PURE__*/ $constructor("$ZodNumber", (inst, def) => { + $ZodType.init(inst, def); + inst._zod.pattern = inst._zod.bag.pattern ?? number; + inst._zod.parse = (payload, _ctx) => { + if (def.coerce) + try { + payload.value = Number(payload.value); + } + catch (_) { } + const input = payload.value; + if (typeof input === "number" && !Number.isNaN(input) && Number.isFinite(input)) { + return payload; + } + const received = typeof input === "number" + ? Number.isNaN(input) + ? "NaN" + : !Number.isFinite(input) + ? String(input) + : undefined + : undefined; + payload.issues.push({ + expected: "number", + code: "invalid_type", + input, + inst, + ...(received ? { received } : {}), + }); + return payload; + }; +}); +const $ZodNumberFormat = /*@__PURE__*/ $constructor("$ZodNumberFormat", (inst, def) => { + $ZodCheckNumberFormat.init(inst, def); + $ZodNumber.init(inst, def); // no format checks +}); +const $ZodBoolean = /*@__PURE__*/ $constructor("$ZodBoolean", (inst, def) => { + $ZodType.init(inst, def); + inst._zod.pattern = regexes_boolean; + inst._zod.parse = (payload, _ctx) => { + if (def.coerce) + try { + payload.value = Boolean(payload.value); + } + catch (_) { } + const input = payload.value; + if (typeof input === "boolean") + return payload; + payload.issues.push({ + expected: "boolean", + code: "invalid_type", + input, + inst, + }); + return payload; + }; +}); +const $ZodBigInt = /*@__PURE__*/ (/* unused pure expression or super */ null && (core.$constructor("$ZodBigInt", (inst, def) => { + $ZodType.init(inst, def); + inst._zod.pattern = regexes.bigint; + inst._zod.parse = (payload, _ctx) => { + if (def.coerce) + try { + payload.value = BigInt(payload.value); + } + catch (_) { } + if (typeof payload.value === "bigint") + return payload; + payload.issues.push({ + expected: "bigint", + code: "invalid_type", + input: payload.value, + inst, + }); + return payload; + }; +}))); +const $ZodBigIntFormat = /*@__PURE__*/ (/* unused pure expression or super */ null && (core.$constructor("$ZodBigIntFormat", (inst, def) => { + checks.$ZodCheckBigIntFormat.init(inst, def); + $ZodBigInt.init(inst, def); // no format checks +}))); +const $ZodSymbol = /*@__PURE__*/ (/* unused pure expression or super */ null && (core.$constructor("$ZodSymbol", (inst, def) => { + $ZodType.init(inst, def); + inst._zod.parse = (payload, _ctx) => { + const input = payload.value; + if (typeof input === "symbol") + return payload; + payload.issues.push({ + expected: "symbol", + code: "invalid_type", + input, + inst, + }); + return payload; + }; +}))); +const $ZodUndefined = /*@__PURE__*/ (/* unused pure expression or super */ null && (core.$constructor("$ZodUndefined", (inst, def) => { + $ZodType.init(inst, def); + inst._zod.pattern = regexes.undefined; + inst._zod.values = new Set([undefined]); + inst._zod.parse = (payload, _ctx) => { + const input = payload.value; + if (typeof input === "undefined") + return payload; + payload.issues.push({ + expected: "undefined", + code: "invalid_type", + input, + inst, + }); + return payload; + }; +}))); +const $ZodNull = /*@__PURE__*/ $constructor("$ZodNull", (inst, def) => { + $ZodType.init(inst, def); + inst._zod.pattern = _null; + inst._zod.values = new Set([null]); + inst._zod.parse = (payload, _ctx) => { + const input = payload.value; + if (input === null) + return payload; + payload.issues.push({ + expected: "null", + code: "invalid_type", + input, + inst, + }); + return payload; + }; +}); +const $ZodAny = /*@__PURE__*/ $constructor("$ZodAny", (inst, def) => { + $ZodType.init(inst, def); + inst._zod.parse = (payload) => payload; +}); +const $ZodUnknown = /*@__PURE__*/ $constructor("$ZodUnknown", (inst, def) => { + $ZodType.init(inst, def); + inst._zod.parse = (payload) => payload; +}); +const $ZodNever = /*@__PURE__*/ $constructor("$ZodNever", (inst, def) => { + $ZodType.init(inst, def); + inst._zod.parse = (payload, _ctx) => { + payload.issues.push({ + expected: "never", + code: "invalid_type", + input: payload.value, + inst, + }); + return payload; + }; +}); +const $ZodVoid = /*@__PURE__*/ (/* unused pure expression or super */ null && (core.$constructor("$ZodVoid", (inst, def) => { + $ZodType.init(inst, def); + inst._zod.parse = (payload, _ctx) => { + const input = payload.value; + if (typeof input === "undefined") + return payload; + payload.issues.push({ + expected: "void", + code: "invalid_type", + input, + inst, + }); + return payload; + }; +}))); +const $ZodDate = /*@__PURE__*/ (/* unused pure expression or super */ null && (core.$constructor("$ZodDate", (inst, def) => { + $ZodType.init(inst, def); + inst._zod.parse = (payload, _ctx) => { + if (def.coerce) { + try { + payload.value = new Date(payload.value); + } + catch (_err) { } + } + const input = payload.value; + const isDate = input instanceof Date; + const isValidDate = isDate && !Number.isNaN(input.getTime()); + if (isValidDate) + return payload; + payload.issues.push({ + expected: "date", + code: "invalid_type", + input, + ...(isDate ? { received: "Invalid Date" } : {}), + inst, + }); + return payload; + }; +}))); +function handleArrayResult(result, final, index) { + if (result.issues.length) { + final.issues.push(...prefixIssues(index, result.issues)); + } + final.value[index] = result.value; +} +const $ZodArray = /*@__PURE__*/ $constructor("$ZodArray", (inst, def) => { + $ZodType.init(inst, def); + const memo = globalConfig.memoizer; + memo?.attach(inst); + inst._zod.parse = (payload, ctx) => { + const input = payload.value; + if (!Array.isArray(input)) { + payload.issues.push({ + expected: "array", + code: "invalid_type", + input, + inst, + }); + return payload; + } + payload.value = memo ? memo.alloc(inst, payload, Array(input.length), ctx) : Array(input.length); + const proms = []; + for (let i = 0; i < input.length; i++) { + const item = input[i]; + const result = def.element._zod.run({ + value: item, + issues: [], + }, ctx); + if (result instanceof Promise) { + proms.push(result.then((result) => handleArrayResult(result, payload, i))); + } + else { + handleArrayResult(result, payload, i); + } + } + if (proms.length) { + return Promise.all(proms).then(() => payload); + } + return payload; //handleArrayResultsAsync(parseResults, final); + }; +}); +function handlePropertyResult(result, final, key, input, optin, optout) { + const isPresent = key in input; + const isOptionalOut = optout === "optional"; + // The middle rung means "absence permitted, nothing supplied in its place", so an absent key contributes nothing — whatever the schema made of `undefined` is invented, not substituted. Only `optional` reaches this with a value: `defaulted` substitutes, and a schema that isn't optional-out has to keep the key. + if (!isPresent && isOptionalOut && optin === "optional") { + return; + } + if (result.issues.length) { + // For optional-in/out schemas, ignore errors on absent keys. + if (optin !== undefined && isOptionalOut && !isPresent) { + return; + } + final.issues.push(...prefixIssues(key, result.issues)); + } + if (!isPresent && optin === undefined) { + if (!result.issues.length) { + final.issues.push({ + code: "invalid_type", + expected: "nonoptional", + input: undefined, + path: [key], + }); + } + return; + } + if (result.value === undefined) { + if (isPresent) { + final.value[key] = undefined; + } + } + else { + final.value[key] = result.value; + } +} +// one shared instance; a fresh [] per schema cost 56 bytes retained +const NO_SYMBOL_KEYS = []; +function normalizeDef(def) { + const keys = Object.keys(def.shape); + const ownSymbols = Object.getOwnPropertySymbols(def.shape); + const symbolKeys = ownSymbols.length ? ownSymbols : NO_SYMBOL_KEYS; + // aliases `keys` when there are no symbols, so a string-only shape keeps one array + const allKeys = symbolKeys.length ? [...keys, ...symbolKeys] : keys; + for (const k of allKeys) { + if (!def.shape?.[k]?._zod?.traits?.has("$ZodType")) { + throw new Error(`Invalid element at key "${String(k)}": expected a Zod schema`); + } + } + const okeys = optionalKeys(def.shape); + return { + ...def, + allKeys, + symbolKeys, + // string-only: handleCatchall matches it against `for...in`, which never yields a symbol + keySet: new Set(keys), + numKeys: keys.length, + optionalKeys: new Set(okeys), + }; +} +function handleCatchall(proms, input, payload, ctx, def, inst) { + const unrecognized = []; + const keySet = def.keySet; + const _catchall = def.catchall._zod; + const t = _catchall.def.type; + const optin = _catchall.optin; + const optout = _catchall.optout; + for (const key in input) { + // Must precede the __proto__ branch: a declared key is not unrecognized, even though the shape loop deliberately strips __proto__ from the parsed output. + if (keySet.has(key)) + continue; + // Don't copy an undeclared __proto__ into the result; assignment to a plain {} would replace the result prototype. But in strict mode it is still an unknown key, so report it before skipping. + if (key === "__proto__") { + if (t === "never") + unrecognized.push(key); + continue; + } + if (t === "never") { + unrecognized.push(key); + continue; + } + const r = _catchall.run({ value: input[key], issues: [] }, ctx); + if (r instanceof Promise) { + proms.push(r.then((r) => handlePropertyResult(r, payload, key, input, optin, optout))); + } + else { + handlePropertyResult(r, payload, key, input, optin, optout); + } + } + if (unrecognized.length) { + payload.issues.push({ + code: "unrecognized_keys", + keys: unrecognized, + input, + inst, + // Describes the shape of the input, not the validity of the parsed value, so it never aborts. The parse still fails; the schema's own checks just get to run first, and an enclosing intersection can reconcile the key against a sibling operand. + continue: true, + }); + } + if (!proms.length) + return payload; + return Promise.all(proms).then(() => { + return payload; + }); +} +// Whichever object a def's `shape` currently answers from: the one the caller passed until the first read, the frozen copy after it. Keyed by def, so a def rebuilt by a builder is simply absent rather than inheriting the source's. Read its keys with `Object.keys`, which does not invoke them — that is what lets a discriminated union check its discriminator without resolving an option whose getters reference the union being constructed. +const propShapes = new WeakMap(); +const $ZodObject = /*@__PURE__*/ $constructor("$ZodObject", (inst, def) => { + // requires cast because technically $ZodObject doesn't extend + $ZodType.init(inst, def); + // const sh = def.shape; + const desc = Object.getOwnPropertyDescriptor(def, "shape"); + if (!desc?.get) { + const sh = def.shape; + propShapes.set(def, sh); + Object.defineProperty(def, "shape", { + get: () => { + const newSh = { ...sh }; + Object.defineProperty(def, "shape", { + value: newSh, + }); + propShapes.set(def, newSh); + return newSh; + }, + }); + } + const _normalized = util_cached(() => normalizeDef(def)); + defineLazyInternal(inst, "propValues", (zod) => { + const shape = zod.def.shape; + const propValues = {}; + for (const key in shape) { + const field = shape[key]._zod; + if (field.values) { + if (!Object.prototype.hasOwnProperty.call(propValues, key)) { + assignProp(propValues, key, new Set()); + } + for (const v of field.values) + propValues[key].add(v); + // An omittable slot reads back as undefined at a discriminator lookup, so it has to claim undefined: two options that can both omit the key are not discriminable on it. + if (field.optin !== undefined) + propValues[key].add(undefined); + } + } + return propValues; + }); + const isObject = util_isObject; + const catchall = def.catchall; + let value; + const memo = globalConfig.memoizer; + memo?.attach(inst); + inst._zod.parse = (payload, ctx) => { + value ?? (value = _normalized.value); + const input = payload.value; + if (!isObject(input)) { + payload.issues.push({ + expected: "object", + code: "invalid_type", + input, + inst, + }); + return payload; + } + payload.value = memo ? memo.alloc(inst, payload, {}, ctx) : {}; + const proms = []; + const shape = value.shape; + for (const key of value.allKeys) { + if (key === "__proto__") + continue; + const el = shape[key]; + const optin = el._zod.optin; + const optout = el._zod.optout; + const r = el._zod.run({ value: input[key], issues: [] }, ctx); + if (r instanceof Promise) { + proms.push(r.then((r) => handlePropertyResult(r, payload, key, input, optin, optout))); + } + else { + handlePropertyResult(r, payload, key, input, optin, optout); + } + } + if (!catchall) { + return proms.length ? Promise.all(proms).then(() => payload) : payload; + } + return handleCatchall(proms, input, payload, ctx, _normalized.value, inst); + }; +}); +const $ZodObjectJIT = /*@__PURE__*/ $constructor("$ZodObjectJIT", (inst, def) => { + // requires cast because technically $ZodObject doesn't extend + $ZodObject.init(inst, def); + const superParse = inst._zod.parse; + const _normalized = util_cached(() => normalizeDef(def)); + const memo = globalConfig.memoizer; + const generateFastpass = (shape) => { + const normalized = _normalized.value; + const syms = normalized.symbolKeys; + // a symbol has no source literal, so it is read as `syms[i]` off the closed-over scope + const doc = new Doc(["payload", "ctx"], { shape, inst, memo, syms }); + const parseStr = (k) => `shape[${k}]._zod.run({ value: input[${k}], issues: [] }, ctx)`; + // Prefixes in place, like util.prefixIssues does for every interpreted path. + const prefixStr = (id, k) => ` + for (let i = 0; i < ${id}.issues.length; i++) { + const iss = ${id}.issues[i]; + iss.path = iss.path ? [${k}, ...iss.path] : [${k}]; + payload.issues.push(iss); + }`; + doc.write(`const input = payload.value;`); + const ids = Object.create(null); + let counter = 0; + for (const key of normalized.allKeys) { + ids[key] = `key_${counter++}`; + } + // A: preserve key order { + doc.write(memo ? `const newResult = memo.alloc(inst, payload, {}, ctx);` : `const newResult = {};`); + for (const key of normalized.allKeys) { + if (key === "__proto__") + continue; + const id = ids[key]; + const k = typeof key === "symbol" ? `syms[${syms.indexOf(key)}]` : util_esc(key); + const isPresent = `${k} in input`; + const schema = shape[key]; + const optin = schema?._zod?.optin; + const isOptionalIn = optin !== undefined; + const isOptionalOut = schema?._zod?.optout === "optional"; + doc.write(`const ${id} = ${parseStr(k)};`); + if (isOptionalIn && isOptionalOut) { + // For optional-in/out schemas, ignore errors on absent keys — and, like the interpreted path, drop the value produced alongside them. The middle rung goes further: it permits absence without supplying anything in its place, so an absent key contributes nothing at all. + const assign = optin === "optional" ? `${id}_present` : `${id}.value !== undefined || ${id}_present`; + doc.write(` + const ${id}_present = ${isPresent}; + if (!${id}.issues.length || ${id}_present) { + if (${id}.issues.length) {${prefixStr(id, k)} + } + + if (${assign}) { + newResult[${k}] = ${id}.value; + } + } + + `); + } + else if (!isOptionalIn) { + doc.write(` + const ${id}_present = ${isPresent}; + if (${id}.issues.length) {${prefixStr(id, k)} + } + if (!${id}_present && !${id}.issues.length) { + payload.issues.push({ + code: "invalid_type", + expected: "nonoptional", + input: undefined, + path: [${k}] + }); + } + + if (${id}_present) { + newResult[${k}] = ${id}.value; + } + + `); + } + else { + doc.write(` + if (${id}.issues.length) {${prefixStr(id, k)} + } + + if (${id}.value === undefined) { + if (${isPresent}) { + newResult[${k}] = undefined; + } + } else { + newResult[${k}] = ${id}.value; + } + + `); + } + } + doc.write(`payload.value = newResult;`); + doc.write(`return payload;`); + // closing `shape` in is what pays: turbofan specializes the parser against that one shape object, so every `shape[k]._zod.run` folds to a known callee. as a parameter it stays a generic load and measures 13% slower even with the forwarding frame gone + return doc.compile(); + }; + let fastpass; + const isObject = util_isObject; + const jit = !globalConfig.jitless; + const allowsEval = util_allowsEval; + const fastEnabled = jit && allowsEval.value; // && !def.catchall; + const catchall = def.catchall; + let value; + inst._zod.parse = (payload, ctx) => { + value ?? (value = _normalized.value); + const input = payload.value; + if (!isObject(input)) { + payload.issues.push({ + expected: "object", + code: "invalid_type", + input, + inst, + }); + return payload; + } + if (jit && fastEnabled && ctx?.async === false && ctx.jitless !== true) { + // always synchronous + if (!fastpass) + fastpass = generateFastpass(def.shape); + payload = fastpass(payload, ctx); + if (!catchall) + return payload; + return handleCatchall([], input, payload, ctx, value, inst); + } + return superParse(payload, ctx); + }; +}); +function handleUnionResults(results, final, inst, ctx) { + for (const result of results) { + if (result.issues.length === 0) { + final.value = result.value; + return final; + } + } + const nonaborted = results.filter((r) => !aborted(r)); + if (nonaborted.length === 1) { + final.value = nonaborted[0].value; + return nonaborted[0]; + } + final.issues.push({ + code: "invalid_union", + input: final.value, + inst, + errors: results.map((result) => result.issues.map((iss) => finalizeIssue(iss, ctx, core_config()))), + }); + return final; +} +const $ZodUnion = /*@__PURE__*/ $constructor("$ZodUnion", (inst, def) => { + $ZodType.init(inst, def); + defineLazyInternal(inst, "optin", (zod) => zod.def.options.some((o) => o._zod.optin === "defaulted") + ? "defaulted" + : zod.def.options.some((o) => o._zod.optin !== undefined) + ? "optional" + : undefined); + defineLazyInternal(inst, "optout", (zod) => zod.def.options.some((o) => o._zod.optout === "optional") ? "optional" : undefined); + defineLazyInternal(inst, "values", (zod) => { + if (zod.def.options.every((o) => o._zod.values)) { + return new Set(zod.def.options.flatMap((option) => Array.from(option._zod.values))); + } + return undefined; + }); + defineLazyInternal(inst, "pattern", (zod) => { + if (zod.def.options.every((o) => o._zod.pattern)) { + const patterns = zod.def.options.map((o) => o._zod.pattern); + return new RegExp(`^(${patterns.map((p) => cleanRegex(p.source)).join("|")})$`); + } + return undefined; + }); + const first = def.options.length === 1 ? def.options[0]._zod.run : null; + inst._zod.parse = (payload, ctx) => { + if (first) { + return first(payload, ctx); + } + let async = false; + const results = []; + for (const option of def.options) { + const result = option._zod.run({ + value: payload.value, + issues: [], + }, ctx); + if (result instanceof Promise) { + results.push(result); + async = true; + } + else { + if (result.issues.length === 0) + return result; + results.push(result); + } + } + if (!async) + return handleUnionResults(results, payload, inst, ctx); + return Promise.all(results).then((results) => { + return handleUnionResults(results, payload, inst, ctx); + }); + }; +}); +function handleExclusiveUnionResults(results, final, inst, ctx) { + const matches = []; + for (let i = 0; i < results.length; i++) { + if (results[i].issues.length === 0) + matches.push(i); + } + if (matches.length === 1) { + final.value = results[matches[0]].value; + return final; + } + if (matches.length === 0) { + // No matches - same as regular union + final.issues.push({ + code: "invalid_union", + input: final.value, + inst, + errors: results.map((result) => result.issues.map((iss) => util.finalizeIssue(iss, ctx, core.config()))), + }); + } + else { + // Multiple matches - exclusive union failure + final.issues.push({ + code: "invalid_union", + input: final.value, + inst, + errors: [], + inclusive: false, + matches, + }); + } + return final; +} +const $ZodXor = /*@__PURE__*/ (/* unused pure expression or super */ null && (core.$constructor("$ZodXor", (inst, def) => { + $ZodUnion.init(inst, def); + def.inclusive = false; + const first = def.options.length === 1 ? def.options[0]._zod.run : null; + inst._zod.parse = (payload, ctx) => { + if (first) { + return first(payload, ctx); + } + let async = false; + const results = []; + for (const option of def.options) { + const result = option._zod.run({ + value: payload.value, + issues: [], + }, ctx); + if (result instanceof Promise) { + results.push(result); + async = true; + } + else { + results.push(result); + } + } + if (!async) + return handleExclusiveUnionResults(results, payload, inst, ctx); + return Promise.all(results).then((results) => { + return handleExclusiveUnionResults(results, payload, inst, ctx); + }); + }; +}))); +/** Returns the option of `union` whose discriminator claims `value`. */ +function getDiscriminatedOption(union, value) { + const internals = union._zod; + let map = internals.bag.optionsMap; + if (!map) { + map = new Map(); + const { options, discriminator } = internals.def; + for (const option of options) { + // First declaration wins, matching the order the parse path resolves a duplicate in. + for (const v of option._zod.propValues?.[discriminator] ?? []) + if (!map.has(v)) + map.set(v, option); + } + internals.bag.optionsMap = map; + } + return map.get(value); +} +const $ZodDiscriminatedUnion = +/*@__PURE__*/ +$constructor("$ZodDiscriminatedUnion", (inst, def) => { + def.inclusive = false; + $ZodUnion.init(inst, def); + const _super = inst._zod.parse; + defineLazyInternal(inst, "propValues", (zod) => { + const propValues = {}; + for (const option of zod.def.options) { + const pv = option._zod.propValues; + if (!pv || Object.keys(pv).length === 0) + throw new Error(`Invalid discriminated union option at index "${zod.def.options.indexOf(option)}"`); + for (const [k, v] of Object.entries(pv)) { + if (!Object.prototype.hasOwnProperty.call(propValues, k)) { + assignProp(propValues, k, new Set()); + } + for (const val of v) { + propValues[k].add(val); + } + } + } + return propValues; + }); + // Checked now rather than in the lookup map below, so an option that lacks the discriminator fails at the `discriminatedUnion` call instead of on the first object parsed. Options whose shape cannot be enumerated without resolving it — pipes, lazies, and objects rebuilt by a builder such as `.extend()` — are left to the map. + def.options.forEach((option, i) => { + const propShape = propShapes.get(option._zod.def); + if (propShape && !Object.prototype.hasOwnProperty.call(propShape, def.discriminator)) { + throw new Error(`Invalid discriminated union option at index "${i}"`); + } + }); + const disc = util_cached(() => { + const opts = def.options; + const map = new Map(); + for (const o of opts) { + const values = o._zod.propValues?.[def.discriminator]; + if (!values || values.size === 0) + throw new Error(`Invalid discriminated union option at index "${def.options.indexOf(o)}"`); + for (const v of values) { + if (map.has(v)) { + throw new Error(`Duplicate discriminator value "${String(v)}"`); + } + map.set(v, o); + } + } + return map; + }); + inst._zod.parse = (payload, ctx) => { + const input = payload.value; + if (!util_isObject(input)) { + payload.issues.push({ + code: "invalid_type", + expected: "object", + input, + inst, + }); + return payload; + } + const opt = disc.value.get(input?.[def.discriminator]); + if (opt) { + return opt._zod.run(payload, ctx); + } + // Fall back to union matching when the fast discriminator path fails: + // - explicitly enabled via unionFallback, or + // - during backward direction (encode), since codec-based discriminators have different values in forward vs backward directions + if (def.unionFallback || ctx.direction === "backward") { + return _super(payload, ctx); + } + // no matching discriminator + payload.issues.push({ + code: "invalid_union", + errors: [], + note: "No matching discriminator", + discriminator: def.discriminator, + options: Array.from(disc.value.keys()), + input, + path: [def.discriminator], + inst, + }); + return payload; + }; +}); +const $ZodIntersection = /*@__PURE__*/ $constructor("$ZodIntersection", (inst, def) => { + $ZodType.init(inst, def); + inst._zod.parse = (payload, ctx) => { + const input = payload.value; + const left = def.left._zod.run({ value: input, issues: [] }, ctx); + const right = def.right._zod.run({ value: input, issues: [] }, ctx); + const async = left instanceof Promise || right instanceof Promise; + if (async) { + return Promise.all([left, right]).then(([left, right]) => { + return handleIntersectionResults(payload, left, right); + }); + } + return handleIntersectionResults(payload, left, right); + }; +}); +function schemas_mergeValues(a, b) { + // const aType = parse.t(a); + // const bType = parse.t(b); + if (a === b) { + return { valid: true, data: a }; + } + if (a instanceof Date && b instanceof Date && +a === +b) { + return { valid: true, data: a }; + } + if (isPlainObject(a) && isPlainObject(b)) { + const bKeys = Object.keys(b); + const sharedKeys = Object.keys(a).filter((key) => bKeys.indexOf(key) !== -1); + const newObj = { ...a, ...b }; + if (Object.prototype.hasOwnProperty.call(newObj, "__proto__")) + delete newObj.__proto__; + for (const key of sharedKeys) { + if (key === "__proto__") + continue; + const sharedValue = schemas_mergeValues(a[key], b[key]); + if (!sharedValue.valid) { + return { + valid: false, + mergeErrorPath: [key, ...sharedValue.mergeErrorPath], + }; + } + newObj[key] = sharedValue.data; + } + return { valid: true, data: newObj }; + } + if (Array.isArray(a) && Array.isArray(b)) { + if (a.length !== b.length) { + return { valid: false, mergeErrorPath: [] }; + } + const newArray = []; + for (let index = 0; index < a.length; index++) { + const itemA = a[index]; + const itemB = b[index]; + const sharedValue = schemas_mergeValues(itemA, itemB); + if (!sharedValue.valid) { + return { + valid: false, + mergeErrorPath: [index, ...sharedValue.mergeErrorPath], + }; + } + newArray.push(sharedValue.data); + } + return { valid: true, data: newArray }; + } + return { valid: false, mergeErrorPath: [] }; +} +function handleIntersectionResults(result, left, right) { + // Track which side(s) reject each key. A key rejection is reported only when BOTH sides reject it, so a key owned by one branch survives the other's key schema. strictObject reports these as unrecognized_keys; a record with an open key schema reports one invalid_key per key. + const unrecKeys = new Map(); + let unrecIssue; + const keyIssues = new Map(); + const collect = (iss, side) => { + let keys; + if (iss.code === "unrecognized_keys" && !iss.path?.length) { + unrecIssue ?? (unrecIssue = iss); + keys = iss.keys; + } + else if (iss.code === "invalid_key" && iss.origin === "record" && iss.path?.length === 1) { + const k = String(iss.path[0]); + if (!keyIssues.has(k)) + keyIssues.set(k, iss); + keys = [k]; + } + else { + return false; + } + for (const k of keys) { + if (!unrecKeys.has(k)) + unrecKeys.set(k, {}); + unrecKeys.get(k)[side] = true; + } + return true; + }; + for (const iss of left.issues) { + if (!collect(iss, "l")) + result.issues.push(iss); + } + for (const iss of right.issues) { + if (!collect(iss, "r")) + result.issues.push(iss); + } + // Report only keys rejected by BOTH sides + const bothKeys = [...unrecKeys].filter(([, f]) => f.l && f.r).map(([k]) => k); + if (bothKeys.length) { + const aggregated = unrecIssue ? bothKeys.filter((k) => unrecIssue.keys.includes(k)) : []; + if (aggregated.length) + result.issues.push({ ...unrecIssue, keys: aggregated }); + for (const k of bothKeys) { + if (!aggregated.includes(k) && keyIssues.has(k)) + result.issues.push(keyIssues.get(k)); + } + } + const merged = schemas_mergeValues(left.value, right.value); + if (!merged.valid) { + if (aborted(result)) + return result; + throw new Error(`Unmergable intersection. Error path: ` + `${JSON.stringify(merged.mergeErrorPath)}`); + } + result.value = merged.data; + return result; +} +const $ZodTuple = /*@__PURE__*/ (/* unused pure expression or super */ null && (core.$constructor("$ZodTuple", (inst, def) => { + $ZodType.init(inst, def); + const items = def.items; + const memo = core.globalConfig.memoizer; + memo?.attach(inst); + inst._zod.parse = (payload, ctx) => { + const input = payload.value; + if (!Array.isArray(input)) { + payload.issues.push({ + input, + inst, + expected: "tuple", + code: "invalid_type", + }); + return payload; + } + payload.value = memo ? memo.alloc(inst, payload, [], ctx) : []; + const proms = []; + const optinStart = getTupleOptStart(items, "optin"); + const optoutStart = getTupleOptStart(items, "optout"); + if (!def.rest) { + if (input.length < optinStart) { + payload.issues.push({ + code: "too_small", + minimum: optinStart, + inclusive: true, + input, + inst, + origin: "array", + }); + return payload; + } + if (input.length > items.length) { + payload.issues.push({ + code: "too_big", + maximum: items.length, + inclusive: true, + input, + inst, + origin: "array", + }); + } + } + // Run every item in parallel, collecting results into an indexed array. The post-processing in `handleTupleResults` walks them in order so it can decide whether an absent optional-output error can truncate the tail or must be reported to preserve required output. + const itemResults = new Array(items.length); + for (let i = 0; i < items.length; i++) { + const r = items[i]._zod.run({ value: input[i], issues: [] }, ctx); + if (r instanceof Promise) { + proms.push(r.then((rr) => { + itemResults[i] = rr; + })); + } + else { + itemResults[i] = r; + } + } + if (def.rest) { + let i = items.length - 1; + const rest = input.slice(items.length); + for (const el of rest) { + i++; + const result = def.rest._zod.run({ value: el, issues: [] }, ctx); + if (result instanceof Promise) { + proms.push(result.then((r) => handleTupleResult(r, payload, i))); + } + else { + handleTupleResult(result, payload, i); + } + } + } + if (proms.length) { + return Promise.all(proms).then(() => handleTupleResults(itemResults, payload, items, input, optoutStart)); + } + return handleTupleResults(itemResults, payload, items, input, optoutStart); + }; +}))); +function getTupleOptStart(items, key) { + for (let i = items.length - 1; i >= 0; i--) { + // optin is a three-rung ladder so any rung above `undefined` permits an absent slot; optout stays two-valued. + const omittable = key === "optin" ? items[i]._zod.optin !== undefined : items[i]._zod.optout === "optional"; + if (!omittable) + return i + 1; + } + return 0; +} +function handleTupleResult(result, final, index) { + if (result.issues.length) { + final.issues.push(...util.prefixIssues(index, result.issues)); + } + final.value[index] = result.value; +} +function handleTupleResults(itemResults, final, items, input, optoutStart) { + // Walk results in order. Mirror $ZodObject's swallow-on-absent-optional rule, but only after `optoutStart`: the first index where the output tuple tail can be absent. + for (let i = 0; i < items.length; i++) { + const r = itemResults[i]; + const isPresent = i < input.length; + // The array analog of `handlePropertyResult`'s absent-key early return: the middle rung permits absence without supplying anything in its place, so the tail truncates here instead of materializing whatever the item made of `undefined`. + if (!isPresent && i >= optoutStart && items[i]._zod.optin === "optional") { + final.value.length = i; + break; + } + if (r.issues.length) { + if (!isPresent && i >= optoutStart) { + final.value.length = i; + break; + } + final.issues.push(...util.prefixIssues(i, r.issues)); + } + final.value[i] = r.value; + } + // Drop trailing slots that produced `undefined` for absent input + // (the array analog of an absent optional key on an object). The + // `i >= input.length` floor is critical: an explicit `undefined` + // *inside* the input must be preserved even when the schema is + // optional-out (e.g. `z.string().or(z.undefined())` accepting an + // explicit undefined value). + for (let i = final.value.length - 1; i >= input.length; i--) { + if (items[i]._zod.optout === "optional" && final.value[i] === undefined) { + final.value.length = i; + } + else { + break; + } + } + return final; +} +const $ZodRecord = /*@__PURE__*/ $constructor("$ZodRecord", (inst, def) => { + $ZodType.init(inst, def); + const memo = globalConfig.memoizer; + memo?.attach(inst); + inst._zod.parse = (payload, ctx) => { + const input = payload.value; + if (!isPlainObject(input)) { + payload.issues.push({ + expected: "record", + code: "invalid_type", + input, + inst, + }); + return payload; + } + const proms = []; + const values = def.keyType._zod.values; + if (values && !def.partial) { + payload.value = memo ? memo.alloc(inst, payload, {}, ctx) : {}; + const recordKeys = new Set(); + for (const key of values) { + if (typeof key === "string" || typeof key === "number" || typeof key === "symbol") { + recordKeys.add(typeof key === "number" ? key.toString() : key); + // A declared __proto__ is stripped but is not an unrecognized key. + if (key === "__proto__") + continue; + const keyResult = def.keyType._zod.run({ value: key, issues: [] }, ctx); + if (keyResult instanceof Promise) { + throw new Error("Async schemas not supported in object keys currently"); + } + if (keyResult.issues.length) { + payload.issues.push({ + code: "invalid_key", + origin: "record", + issues: keyResult.issues.map((iss) => finalizeIssue(iss, ctx, core_config())), + input: key, + path: [key], + inst, + }); + continue; + } + const outKey = keyResult.value; + if (outKey === "__proto__") + continue; + const result = def.valueType._zod.run({ value: input[key], issues: [] }, ctx); + if (result instanceof Promise) { + proms.push(result.then((result) => { + if (result.issues.length) { + payload.issues.push(...prefixIssues(key, result.issues)); + } + payload.value[outKey] = result.value; + })); + } + else { + if (result.issues.length) { + payload.issues.push(...prefixIssues(key, result.issues)); + } + payload.value[outKey] = result.value; + } + } + } + let unrecognized; + for (const key in input) { + if (!recordKeys.has(key)) { + if (def.mode === "loose") { + // skip __proto__ so it can't replace the result prototype via the assignment setter on the plain {} we build into + if (key === "__proto__") + continue; + payload.value[key] = input[key]; + } + else { + unrecognized = unrecognized ?? []; + unrecognized.push(key); + } + } + } + if (unrecognized && unrecognized.length > 0) { + payload.issues.push({ + code: "unrecognized_keys", + input, + inst, + keys: unrecognized, + continue: true, + }); + } + } + else { + payload.value = memo ? memo.alloc(inst, payload, {}, ctx) : {}; + // An enumerable key schema declares which keys the record owns, so a key outside the set is unrecognized. A non-enumerable one (regex, refine) is a constraint every key must satisfy, so a failing key is invalid. Only the former is reconcilable against the other side of an intersection. + let unrecognized; + // Reflect.ownKeys for Symbol-key support; filter non-enumerable to match z.object() + for (const key of Reflect.ownKeys(input)) { + if (key === "__proto__") + continue; + if (!Object.prototype.propertyIsEnumerable.call(input, key)) + continue; + let keyResult = def.keyType._zod.run({ value: key, issues: [] }, ctx); + if (keyResult instanceof Promise) { + throw new Error("Async schemas not supported in object keys currently"); + } + // Numeric string fallback: if key is a numeric string and failed, retry with Number(key). This handles z.number(), z.literal([1, 2, 3]), and unions containing numeric literals + const checkNumericKey = typeof key === "string" && number.test(key) && keyResult.issues.length; + if (checkNumericKey) { + const retryResult = def.keyType._zod.run({ value: Number(key), issues: [] }, ctx); + if (retryResult instanceof Promise) { + throw new Error("Async schemas not supported in object keys currently"); + } + if (retryResult.issues.length === 0) { + keyResult = retryResult; + } + } + if (keyResult.issues.length) { + if (def.mode === "loose") { + // Pass through unchanged + payload.value[key] = input[key]; + } + else if (values) { + unrecognized = unrecognized ?? []; + unrecognized.push(key); + } + else { + // Default "strict" behavior: error on invalid key + payload.issues.push({ + code: "invalid_key", + origin: "record", + issues: keyResult.issues.map((iss) => finalizeIssue(iss, ctx, core_config())), + input: key, + path: [key], + inst, + }); + } + continue; + } + // the guard above tests the raw input key, but the key schema can normalize an ordinary key into __proto__; re-check the key we actually write under + const outKey = keyResult.value; + if (outKey === "__proto__") + continue; + const result = def.valueType._zod.run({ value: input[key], issues: [] }, ctx); + if (result instanceof Promise) { + proms.push(result.then((result) => { + if (result.issues.length) { + payload.issues.push(...prefixIssues(key, result.issues)); + } + payload.value[outKey] = result.value; + })); + } + else { + if (result.issues.length) { + payload.issues.push(...prefixIssues(key, result.issues)); + } + payload.value[outKey] = result.value; + } + } + if (unrecognized && unrecognized.length > 0) { + payload.issues.push({ + code: "unrecognized_keys", + input, + inst, + keys: unrecognized, + continue: true, + }); + } + } + if (proms.length) { + return Promise.all(proms).then(() => payload); + } + return payload; + }; +}); +const $ZodMap = /*@__PURE__*/ (/* unused pure expression or super */ null && (core.$constructor("$ZodMap", (inst, def) => { + $ZodType.init(inst, def); + const memo = core.globalConfig.memoizer; + memo?.attach(inst); + inst._zod.parse = (payload, ctx) => { + const input = payload.value; + if (!(input instanceof Map)) { + payload.issues.push({ + expected: "map", + code: "invalid_type", + input, + inst, + }); + return payload; + } + const proms = []; + payload.value = memo ? memo.alloc(inst, payload, new Map(), ctx) : new Map(); + for (const [key, value] of input) { + const keyResult = def.keyType._zod.run({ value: key, issues: [] }, ctx); + const valueResult = def.valueType._zod.run({ value: value, issues: [] }, ctx); + if (keyResult instanceof Promise || valueResult instanceof Promise) { + proms.push(Promise.all([keyResult, valueResult]).then(([keyResult, valueResult]) => { + handleMapResult(keyResult, valueResult, payload, key, input, inst, ctx); + })); + } + else { + handleMapResult(keyResult, valueResult, payload, key, input, inst, ctx); + } + } + if (proms.length) + return Promise.all(proms).then(() => payload); + return payload; + }; +}))); +function handleMapResult(keyResult, valueResult, final, key, input, inst, ctx) { + if (keyResult.issues.length) { + if (util.propertyKeyTypes.has(typeof key)) { + final.issues.push(...util.prefixIssues(key, keyResult.issues)); + } + else { + final.issues.push({ + code: "invalid_key", + origin: "map", + input, + inst, + issues: keyResult.issues.map((iss) => util.finalizeIssue(iss, ctx, core.config())), + }); + } + } + if (valueResult.issues.length) { + if (util.propertyKeyTypes.has(typeof key)) { + final.issues.push(...util.prefixIssues(key, valueResult.issues)); + } + else { + final.issues.push({ + origin: "map", + code: "invalid_element", + input, + inst, + key: key, + issues: valueResult.issues.map((iss) => util.finalizeIssue(iss, ctx, core.config())), + }); + } + } + final.value.set(keyResult.value, valueResult.value); +} +const $ZodSet = /*@__PURE__*/ (/* unused pure expression or super */ null && (core.$constructor("$ZodSet", (inst, def) => { + $ZodType.init(inst, def); + const memo = core.globalConfig.memoizer; + memo?.attach(inst); + inst._zod.parse = (payload, ctx) => { + const input = payload.value; + if (!(input instanceof Set)) { + payload.issues.push({ + input, + inst, + expected: "set", + code: "invalid_type", + }); + return payload; + } + const proms = []; + payload.value = memo ? memo.alloc(inst, payload, new Set(), ctx) : new Set(); + for (const item of input) { + const result = def.valueType._zod.run({ value: item, issues: [] }, ctx); + if (result instanceof Promise) { + proms.push(result.then((result) => handleSetResult(result, payload))); + } + else + handleSetResult(result, payload); + } + if (proms.length) + return Promise.all(proms).then(() => payload); + return payload; + }; +}))); +function handleSetResult(result, final) { + if (result.issues.length) { + final.issues.push(...result.issues); + } + final.value.add(result.value); +} +const $ZodEnum = /*@__PURE__*/ $constructor("$ZodEnum", (inst, def) => { + $ZodType.init(inst, def); + const values = getEnumValues(def.entries); + const valuesSet = new Set(values); + inst._zod.values = valuesSet; + const patternValues = values.filter((k) => propertyKeyTypes.has(typeof k)); + // unmatchable fallback, RE2-safe: an empty alternation would compile to /^()$/, which matches "" + inst._zod.pattern = new RegExp(patternValues.length ? `^(${patternValues.map((o) => escapeRegex(o.toString())).join("|")})$` : "^[^\\s\\S]$"); + inst._zod.parse = (payload, _ctx) => { + const input = payload.value; + if (valuesSet.has(input)) { + return payload; + } + payload.issues.push({ + code: "invalid_value", + values, + input, + inst, + }); + return payload; + }; +}); +const $ZodLiteral = /*@__PURE__*/ $constructor("$ZodLiteral", (inst, def) => { + $ZodType.init(inst, def); + const values = new Set(def.values); + inst._zod.values = values; + // unmatchable fallback, RE2-safe: an empty alternation would compile to /^()$/, which matches "" + inst._zod.pattern = new RegExp(def.values.length + ? `^(${def.values + .map((o) => (typeof o === "string" ? escapeRegex(o) : o ? escapeRegex(o.toString()) : String(o))) + .join("|")})$` + : "^[^\\s\\S]$"); + inst._zod.parse = (payload, _ctx) => { + const input = payload.value; + if (values.has(input)) { + return payload; + } + payload.issues.push({ + code: "invalid_value", + values: def.values, + input, + inst, + }); + return payload; + }; +}); +const $ZodFile = /*@__PURE__*/ (/* unused pure expression or super */ null && (core.$constructor("$ZodFile", (inst, def) => { + $ZodType.init(inst, def); + inst._zod.parse = (payload, _ctx) => { + const input = payload.value; + // @ts-ignore + if (input instanceof File) + return payload; + payload.issues.push({ + expected: "file", + code: "invalid_type", + input, + inst, + }); + return payload; + }; +}))); +const $ZodTransform = /*@__PURE__*/ $constructor("$ZodTransform", (inst, def) => { + $ZodType.init(inst, def); + inst._zod.optin = "optional"; + globalConfig.memoizer?.guard(inst); + inst._zod.parse = (payload, ctx) => { + if (ctx.direction === "backward") { + throw new $ZodEncodeError(inst.constructor.name); + } + const _out = def.transform(payload.value, payload); + if (ctx.async) { + const output = _out instanceof Promise ? _out : Promise.resolve(_out); + return output.then((output) => { + payload.value = output; + return payload; + }); + } + if (_out instanceof Promise) { + throw new $ZodAsyncError(); + } + payload.value = _out; + return payload; + }; +}); +function handleOptionalResult(payload, result) { + // A substituting schema that still failed has no usable answer; yield undefined. Its issues are simply dropped: it ran on a payload of its own, so there is no shared array to truncate and nothing of the caller's to lose with it. + payload.value = result.issues.length ? undefined : result.value; + return payload; +} +const $ZodOptional = /*@__PURE__*/ $constructor("$ZodOptional", (inst, def) => { + $ZodType.init(inst, def); + // .optional() propagates absence rather than substituting for it, so a defaulted inner keeps its rung. + defineLazyInternal(inst, "optin", (zod) => zod.def.innerType._zod.optin === "defaulted" ? "defaulted" : "optional"); + inst._zod.optout = "optional"; + defineLazyInternal(inst, "values", (zod) => { + const values = zod.def.innerType._zod.values; + return values ? new Set([...values, undefined]) : undefined; + }); + defineLazyInternal(inst, "pattern", (zod) => { + const pattern = zod.def.innerType._zod.pattern; + return pattern ? new RegExp(`^(${cleanRegex(pattern.source)})?$`) : undefined; + }); + inst._zod.parse = (payload, ctx) => { + if (payload.value === undefined) { + // Only the top rung substitutes a value for absence; everything else leaves it intact, which is what .optional() means. + if (def.innerType._zod.optin !== "defaulted") + return payload; + // Its own payload, for the same reason $ZodCatch gets one: a pipe forwards an unrecognized key through the caller's issues array, and this must not read that as the substituting schema failing and drop it. + const result = def.innerType._zod.run({ value: payload.value, issues: [] }, ctx); + if (result instanceof Promise) + return result.then((result) => handleOptionalResult(payload, result)); + return handleOptionalResult(payload, result); + } + return def.innerType._zod.run(payload, ctx); + }; +}); +const $ZodExactOptional = /*@__PURE__*/ $constructor("$ZodExactOptional", (inst, def) => { + // Call parent init - inherits optin/optout = "optional" + $ZodOptional.init(inst, def); + // Override values/pattern to NOT add undefined + defineLazyInternal(inst, "values", (zod) => zod.def.innerType._zod.values); + defineLazyInternal(inst, "pattern", (zod) => zod.def.innerType._zod.pattern); + // Override parse to just delegate (no undefined handling) + inst._zod.parse = (payload, ctx) => { + return def.innerType._zod.run(payload, ctx); + }; +}); +const $ZodNullable = /*@__PURE__*/ $constructor("$ZodNullable", (inst, def) => { + $ZodType.init(inst, def); + defineLazyInternal(inst, "optin", (zod) => zod.def.innerType._zod.optin); + defineLazyInternal(inst, "optout", (zod) => zod.def.innerType._zod.optout); + defineLazyInternal(inst, "pattern", (zod) => { + const pattern = zod.def.innerType._zod.pattern; + return pattern ? new RegExp(`^(${cleanRegex(pattern.source)}|null)$`) : undefined; + }); + defineLazyInternal(inst, "values", (zod) => { + return zod.def.innerType._zod.values ? new Set([...zod.def.innerType._zod.values, null]) : undefined; + }); + inst._zod.parse = (payload, ctx) => { + // Forward direction (decode): allow null to pass through + if (payload.value === null) + return payload; + return def.innerType._zod.run(payload, ctx); + }; +}); +const $ZodDefault = /*@__PURE__*/ $constructor("$ZodDefault", (inst, def) => { + $ZodType.init(inst, def); + // inst._zod.qin = "true"; + inst._zod.optin = "defaulted"; + defineLazyInternal(inst, "values", (zod) => zod.def.innerType._zod.values); + inst._zod.parse = (payload, ctx) => { + if (ctx.direction === "backward") { + return def.innerType._zod.run(payload, ctx); + } + // Forward direction (decode): apply defaults for undefined input + if (payload.value === undefined) { + payload.value = def.defaultValue; + /** + * $ZodDefault returns the default value immediately in forward direction. + * It doesn't pass the default value into the validator ("prefault"). There's no reason to pass the default value through validation. The validity of the default is enforced by TypeScript statically. Otherwise, it's the responsibility of the user to ensure the default is valid. In the case of pipes with divergent in/out types, you can specify the default on the `in` schema of your ZodPipe to set a "prefault" for the pipe. */ + return payload; + } + // Forward direction: continue with default handling + const result = def.innerType._zod.run(payload, ctx); + if (result instanceof Promise) { + return result.then((result) => handleDefaultResult(result, def)); + } + return handleDefaultResult(result, def); + }; +}); +function handleDefaultResult(payload, def) { + if (payload.value === undefined) { + payload.value = def.defaultValue; + } + return payload; +} +const $ZodPrefault = /*@__PURE__*/ $constructor("$ZodPrefault", (inst, def) => { + $ZodType.init(inst, def); + inst._zod.optin = "defaulted"; + defineLazyInternal(inst, "values", (zod) => zod.def.innerType._zod.values); + inst._zod.parse = (payload, ctx) => { + if (ctx.direction === "backward") { + return def.innerType._zod.run(payload, ctx); + } + // Forward direction (decode): apply prefault for undefined input + if (payload.value === undefined) { + payload.value = def.defaultValue; + } + return def.innerType._zod.run(payload, ctx); + }; +}); +const $ZodNonOptional = /*@__PURE__*/ $constructor("$ZodNonOptional", (inst, def) => { + $ZodType.init(inst, def); + defineLazyInternal(inst, "values", (zod) => { + const v = zod.def.innerType._zod.values; + return v ? new Set([...v].filter((x) => x !== undefined)) : undefined; + }); + inst._zod.parse = (payload, ctx) => { + const result = def.innerType._zod.run(payload, ctx); + if (result instanceof Promise) { + return result.then((result) => handleNonOptionalResult(result, inst)); + } + return handleNonOptionalResult(result, inst); + }; +}); +function handleNonOptionalResult(payload, inst) { + if (!payload.issues.length && payload.value === undefined) { + payload.issues.push({ + code: "invalid_type", + expected: "nonoptional", + input: payload.value, + inst, + }); + } + return payload; +} +const $ZodSuccess = /*@__PURE__*/ (/* unused pure expression or super */ null && (core.$constructor("$ZodSuccess", (inst, def) => { + $ZodType.init(inst, def); + inst._zod.parse = (payload, ctx) => { + if (ctx.direction === "backward") { + throw new core.$ZodEncodeError("ZodSuccess"); + } + const result = def.innerType._zod.run(payload, ctx); + if (result instanceof Promise) { + return result.then((result) => { + payload.value = result.issues.length === 0; + return payload; + }); + } + payload.value = result.issues.length === 0; + return payload; + }; +}))); +function handleCatchResult(payload, result, def, ctx) { + if (!result.issues.length) { + payload.value = result.value; + // The value carries up, so the flag describing it has to carry with it: a back-edge into a node still being parsed must not be frozen by an enclosing readonly, and its checks belong to the node itself. Guarded so the ordinary case adds no own property. + if (result.memo) + payload.memo = true; + return payload; + } + // Spread the inner's own payload, not ours: `value` has to stay the input the catch was handed, and the inner ran on a payload of its own so its issues are already private to this call. + payload.value = def.catchValue({ + ...result, + value: payload.value, + error: { + issues: result.issues.map((iss) => finalizeIssue(iss, ctx, core_config())), + }, + input: payload.value, + }); + return payload; +} +const $ZodCatch = /*@__PURE__*/ $constructor("$ZodCatch", (inst, def) => { + $ZodType.init(inst, def); + defineLazyInternal(inst, "optin", (zod) => zod.def.innerType._zod.optin === "defaulted" ? "defaulted" : "optional"); + defineLazyInternal(inst, "optout", (zod) => zod.def.innerType._zod.optout); + defineLazyInternal(inst, "values", (zod) => zod.def.innerType._zod.values); + inst._zod.parse = (payload, ctx) => { + if (ctx.direction === "backward") { + return def.innerType._zod.run(payload, ctx); + } + // Forward direction (decode): apply catch logic + const result = def.innerType._zod.run({ value: payload.value, issues: [] }, ctx); + if (result instanceof Promise) { + return result.then((result) => handleCatchResult(payload, result, def, ctx)); + } + return handleCatchResult(payload, result, def, ctx); + }; +}); +const $ZodNaN = /*@__PURE__*/ (/* unused pure expression or super */ null && (core.$constructor("$ZodNaN", (inst, def) => { + $ZodType.init(inst, def); + inst._zod.parse = (payload, _ctx) => { + if (typeof payload.value !== "number" || !Number.isNaN(payload.value)) { + payload.issues.push({ + input: payload.value, + inst, + expected: "nan", + code: "invalid_type", + }); + return payload; + } + return payload; + }; +}))); +const $ZodPipe = /*@__PURE__*/ $constructor("$ZodPipe", (inst, def) => { + $ZodType.init(inst, def); + defineLazyInternal(inst, "values", (zod) => zod.def.in._zod.values); + defineLazyInternal(inst, "optin", (zod) => zod.def.in._zod.optin); + defineLazyInternal(inst, "optout", (zod) => zod.def.out._zod.optout); + defineLazyInternal(inst, "propValues", (zod) => zod.def.in._zod.propValues); + inst._zod.parse = (payload, ctx) => { + if (ctx.direction === "backward") { + const right = def.out._zod.run(payload, ctx); + if (right instanceof Promise) { + return right.then((right) => handlePipeResult(right, def.in, ctx)); + } + return handlePipeResult(right, def.in, ctx); + } + const left = def.in._zod.run(payload, ctx); + if (left instanceof Promise) { + return left.then((left) => handlePipeResult(left, def.out, ctx)); + } + return handlePipeResult(left, def.out, ctx); + }; +}); +function handlePipeResult(left, next, ctx) { + // Any issue stops the pipe, so a failing refinement never feeds its transform. An unrecognized key is the exception: it describes the input's extra properties, not the value being piped, and an enclosing intersection may yet reconcile it. + if (left.issues.some((iss) => iss.code !== "unrecognized_keys")) { + // prevent further checks + left.aborted = true; + return left; + } + return next._zod.run({ value: left.value, issues: left.issues }, ctx); +} +const $ZodCodec = /*@__PURE__*/ (/* unused pure expression or super */ null && (core.$constructor("$ZodCodec", (inst, def) => { + $ZodType.init(inst, def); + util.defineLazyInternal(inst, "values", (zod) => zod.def.in._zod.values); + util.defineLazyInternal(inst, "optin", (zod) => zod.def.in._zod.optin); + util.defineLazyInternal(inst, "optout", (zod) => zod.def.out._zod.optout); + util.defineLazyInternal(inst, "propValues", (zod) => zod.def.in._zod.propValues); + inst._zod.parse = (payload, ctx) => { + const direction = ctx.direction || "forward"; + if (direction === "forward") { + const left = def.in._zod.run(payload, ctx); + if (left instanceof Promise) { + return left.then((left) => handleCodecAResult(left, def, ctx)); + } + return handleCodecAResult(left, def, ctx); + } + else { + const right = def.out._zod.run(payload, ctx); + if (right instanceof Promise) { + return right.then((right) => handleCodecAResult(right, def, ctx)); + } + return handleCodecAResult(right, def, ctx); + } + }; +}))); +function handleCodecAResult(result, def, ctx) { + if (result.issues.length) { + // prevent further checks + result.aborted = true; + return result; + } + const direction = ctx.direction || "forward"; + if (direction === "forward") { + const transformed = def.transform(result.value, result); + if (transformed instanceof Promise) { + return transformed.then((value) => handleCodecTxResult(result, value, def.out, ctx)); + } + return handleCodecTxResult(result, transformed, def.out, ctx); + } + else { + const transformed = def.reverseTransform(result.value, result); + if (transformed instanceof Promise) { + return transformed.then((value) => handleCodecTxResult(result, value, def.in, ctx)); + } + return handleCodecTxResult(result, transformed, def.in, ctx); + } +} +function handleCodecTxResult(left, value, nextSchema, ctx) { + // Check if transform added any issues + if (left.issues.length) { + left.aborted = true; + return left; + } + return nextSchema._zod.run({ value, issues: left.issues }, ctx); +} +const $ZodPreprocess = /*@__PURE__*/ $constructor("$ZodPreprocess", (inst, def) => { + $ZodPipe.init(inst, def); +}); +const $ZodReadonly = /*@__PURE__*/ $constructor("$ZodReadonly", (inst, def) => { + $ZodType.init(inst, def); + defineLazyInternal(inst, "propValues", (zod) => zod.def.innerType._zod.propValues); + defineLazyInternal(inst, "values", (zod) => zod.def.innerType._zod.values); + defineLazyInternal(inst, "optin", (zod) => zod.def.innerType?._zod?.optin); + defineLazyInternal(inst, "optout", (zod) => zod.def.innerType?._zod?.optout); + inst._zod.parse = (payload, ctx) => { + if (ctx.direction === "backward") { + return def.innerType._zod.run(payload, ctx); + } + const result = def.innerType._zod.run(payload, ctx); + if (result instanceof Promise) { + return result.then(handleReadonlyResult); + } + return handleReadonlyResult(result); + }; +}); +function handleReadonlyResult(payload) { + // A repeat visit hands back a node that is still being built; freezing it here would make the rest of its keys fail to assign. + if (!payload.memo) + payload.value = Object.freeze(payload.value); + return payload; +} +const $ZodTemplateLiteral = /*@__PURE__*/ (/* unused pure expression or super */ null && (core.$constructor("$ZodTemplateLiteral", (inst, def) => { + $ZodType.init(inst, def); + const regexParts = []; + for (const part of def.parts) { + if (typeof part === "object" && part !== null) { + // is Zod schema + if (!part._zod.pattern) { + // if (!source) + throw new Error(`Invalid template literal part, no pattern found: ${[...part._zod.traits].shift()}`); + } + const source = part._zod.pattern instanceof RegExp ? part._zod.pattern.source : part._zod.pattern; + if (!source) + throw new Error(`Invalid template literal part: ${part._zod.traits}`); + const start = source.startsWith("^") ? 1 : 0; + const end = source.endsWith("$") ? source.length - 1 : source.length; + regexParts.push(source.slice(start, end)); + } + else if (part === null || util.primitiveTypes.has(typeof part)) { + regexParts.push(util.escapeRegex(`${part}`)); + } + else { + throw new Error(`Invalid template literal part: ${part}`); + } + } + inst._zod.pattern = new RegExp(`^${regexParts.join("")}$`); + inst._zod.parse = (payload, _ctx) => { + if (typeof payload.value !== "string") { + payload.issues.push({ + input: payload.value, + inst, + expected: "string", + code: "invalid_type", + }); + return payload; + } + inst._zod.pattern.lastIndex = 0; + if (!inst._zod.pattern.test(payload.value)) { + payload.issues.push({ + input: payload.value, + inst, + code: "invalid_format", + format: def.format ?? "template_literal", + pattern: inst._zod.pattern.source, + }); + return payload; + } + return payload; + }; +}))); +const $ZodFunction = /*@__PURE__*/ (/* unused pure expression or super */ null && (core.$constructor("$ZodFunction", (inst, def) => { + $ZodType.init(inst, def); + // Defined, not assigned: the classic prototype exposes `_def` as a getter with no setter. + Object.defineProperty(inst, "_def", { value: def }); + inst._zod.def = def; + inst.implement = (func) => { + if (typeof func !== "function") { + throw new Error("implement() must be called with a function"); + } + // Defined inline so the closure stays anonymous: binding it to a `const` first names it, which costs 256 bytes per implemented function. + return Object.defineProperty(function (...args) { + const parsedArgs = inst._def.input ? parse(inst._def.input, args) : args; + const result = Reflect.apply(func, this, parsedArgs); + if (inst._def.output) { + return parse(inst._def.output, result); + } + return result; + }, "_zod", { value: inst._zod, enumerable: false }); + }; + inst.implementAsync = (func) => { + if (typeof func !== "function") { + throw new Error("implementAsync() must be called with a function"); + } + return Object.defineProperty(async function (...args) { + const parsedArgs = inst._def.input ? await parseAsync(inst._def.input, args) : args; + const result = await Reflect.apply(func, this, parsedArgs); + if (inst._def.output) { + return await parseAsync(inst._def.output, result); + } + return result; + }, "_zod", { value: inst._zod, enumerable: false }); + }; + inst._zod.parse = (payload, _ctx) => { + if (typeof payload.value !== "function") { + payload.issues.push({ + code: "invalid_type", + expected: "function", + input: payload.value, + inst, + }); + return payload; + } + // Check if output is a promise type to determine if we should use async implementation + const hasPromiseOutput = inst._def.output && inst._def.output._zod.def.type === "promise"; + if (hasPromiseOutput) { + payload.value = inst.implementAsync(payload.value); + } + else { + payload.value = inst.implement(payload.value); + } + return payload; + }; + inst.input = (...args) => { + const F = inst.constructor; + if (Array.isArray(args[0])) { + return new F({ + type: "function", + input: new $ZodTuple({ + type: "tuple", + items: args[0], + rest: args[1], + }), + output: inst._def.output, + }); + } + return new F({ + type: "function", + input: args[0], + output: inst._def.output, + }); + }; + inst.output = (output) => { + const F = inst.constructor; + return new F({ + type: "function", + input: inst._def.input, + output, + }); + }; + return inst; +}))); +const $ZodPromise = /*@__PURE__*/ (/* unused pure expression or super */ null && (core.$constructor("$ZodPromise", (inst, def) => { + $ZodType.init(inst, def); + inst._zod.parse = (payload, ctx) => { + return Promise.resolve(payload.value).then((inner) => def.innerType._zod.run({ value: inner, issues: [] }, ctx)); + }; +}))); +const $ZodLazy = /*@__PURE__*/ $constructor("$ZodLazy", (inst, def) => { + $ZodType.init(inst, def); + // Cache the resolved inner type on the shared `def` so all clones of this lazy (e.g. via `.describe()`/`.meta()`) share the same inner instance, preserving identity for cycle detection on recursive schemas. + defineLazy(inst._zod, "innerType", () => { + const d = def; + if (!d._cachedInner) + d._cachedInner = def.getter(); + return d._cachedInner; + }); + defineLazyInternal(inst, "pattern", (zod) => zod.innerType?._zod?.pattern); + defineLazyInternal(inst, "propValues", (zod) => zod.innerType?._zod?.propValues); + defineLazyInternal(inst, "optin", (zod) => zod.innerType?._zod?.optin ?? undefined); + defineLazyInternal(inst, "optout", (zod) => zod.innerType?._zod?.optout ?? undefined); + inst._zod.parse = (payload, ctx) => { + const inner = inst._zod.innerType; + return inner._zod.run(payload, ctx); + }; +}); +const $ZodCustom = /*@__PURE__*/ $constructor("$ZodCustom", (inst, def) => { + $ZodCheck.init(inst, def); + $ZodType.init(inst, def); + inst._zod.parse = (payload, _) => { + return payload; + }; + inst._zod.check = (payload) => { + const input = payload.value; + const r = def.fn(input); + if (r instanceof Promise) { + return r.then((r) => handleRefineResult(r, payload, input, inst)); + } + handleRefineResult(r, payload, input, inst); + return; + }; +}); +function handleRefineResult(result, payload, input, inst) { + if (!result) { + const _iss = { + code: "custom", + input, + inst, // incorporates params.error into issue reporting + path: [...(inst._zod.def.path ?? [])], // incorporates params.error into issue reporting + continue: !inst._zod.def.abort, + // params: inst._zod.def.params, + }; + if (inst._zod.def.params) + _iss.params = inst._zod.def.params; + payload.issues.push(util_issue(_iss)); + } +} + +var registries_a; +const $output = /*@__PURE__*/ (/* unused pure expression or super */ null && (Symbol("ZodOutput"))); +const $input = /*@__PURE__*/ (/* unused pure expression or super */ null && (Symbol("ZodInput"))); +class $ZodRegistry { + constructor() { + this._map = new WeakMap(); + this._idmap = new Map(); + } + add(schema, ..._meta) { + const meta = _meta[0]; + this._map.set(schema, meta); + if (meta && typeof meta === "object" && "id" in meta) { + this._idmap.set(meta.id, schema); + } + return this; + } + clear() { + this._map = new WeakMap(); + this._idmap = new Map(); + return this; + } + remove(schema) { + const meta = this._map.get(schema); + if (meta && typeof meta === "object" && "id" in meta) { + this._idmap.delete(meta.id); + } + this._map.delete(schema); + return this; + } + get(schema) { + // return this._map.get(schema) as any; + // inherit metadata + const p = schema._zod.parent; + if (p) { + const pm = { ...(this.get(p) ?? {}) }; + delete pm.id; // do not inherit id + const f = { ...pm, ...this._map.get(schema) }; + return Object.keys(f).length ? f : undefined; + } + return this._map.get(schema); + } + has(schema) { + return this._map.has(schema); + } +} +// registries +function registries_registry() { + return new $ZodRegistry(); +} +(registries_a = globalThis).__zod_globalRegistry ?? (registries_a.__zod_globalRegistry = registries_registry()); +const globalRegistry = globalThis.__zod_globalRegistry; + + + + + +// @__NO_SIDE_EFFECTS__ +function _string(Class, params) { + return new Class({ + type: "string", + ...normalizeParams(params), + }); +} +// @__NO_SIDE_EFFECTS__ +function _coercedString(Class, params) { + return new Class({ + type: "string", + coerce: true, + ...util.normalizeParams(params), + }); +} +// @__NO_SIDE_EFFECTS__ +function _email(Class, params) { + return new Class({ + type: "string", + format: "email", + check: "string_format", + abort: false, + ...normalizeParams(params), + }); +} +// @__NO_SIDE_EFFECTS__ +function _guid(Class, params) { + return new Class({ + type: "string", + format: "guid", + check: "string_format", + abort: false, + ...normalizeParams(params), + }); +} +// @__NO_SIDE_EFFECTS__ +function _uuid(Class, params) { + return new Class({ + type: "string", + format: "uuid", + check: "string_format", + abort: false, + ...normalizeParams(params), + }); +} +// @__NO_SIDE_EFFECTS__ +function _uuidv4(Class, params) { + return new Class({ + type: "string", + format: "uuid", + check: "string_format", + abort: false, + version: "v4", + ...normalizeParams(params), + }); +} +// @__NO_SIDE_EFFECTS__ +function _uuidv6(Class, params) { + return new Class({ + type: "string", + format: "uuid", + check: "string_format", + abort: false, + version: "v6", + ...normalizeParams(params), + }); +} +// @__NO_SIDE_EFFECTS__ +function _uuidv7(Class, params) { + return new Class({ + type: "string", + format: "uuid", + check: "string_format", + abort: false, + version: "v7", + ...normalizeParams(params), + }); +} +// @__NO_SIDE_EFFECTS__ +function _url(Class, params) { + return new Class({ + type: "string", + format: "url", + check: "string_format", + abort: false, + ...normalizeParams(params), + }); +} +// @__NO_SIDE_EFFECTS__ +function api_emoji(Class, params) { + return new Class({ + type: "string", + format: "emoji", + check: "string_format", + abort: false, + ...normalizeParams(params), + }); +} +// @__NO_SIDE_EFFECTS__ +function _nanoid(Class, params) { + return new Class({ + type: "string", + format: "nanoid", + check: "string_format", + abort: false, + ...normalizeParams(params), + }); +} +/** + * @deprecated CUID v1 is deprecated by its authors due to information leakage + * (timestamps embedded in the id). Use {@link _cuid2} instead. + * See https://github.com/paralleldrive/cuid. + */ +// @__NO_SIDE_EFFECTS__ +function _cuid(Class, params) { + return new Class({ + type: "string", + format: "cuid", + check: "string_format", + abort: false, + ...normalizeParams(params), + }); +} +// @__NO_SIDE_EFFECTS__ +function _cuid2(Class, params) { + return new Class({ + type: "string", + format: "cuid2", + check: "string_format", + abort: false, + ...normalizeParams(params), + }); +} +// @__NO_SIDE_EFFECTS__ +function _ulid(Class, params) { + return new Class({ + type: "string", + format: "ulid", + check: "string_format", + abort: false, + ...normalizeParams(params), + }); +} +// @__NO_SIDE_EFFECTS__ +function _xid(Class, params) { + return new Class({ + type: "string", + format: "xid", + check: "string_format", + abort: false, + ...normalizeParams(params), + }); +} +// @__NO_SIDE_EFFECTS__ +function _ksuid(Class, params) { + return new Class({ + type: "string", + format: "ksuid", + check: "string_format", + abort: false, + ...normalizeParams(params), + }); +} +// @__NO_SIDE_EFFECTS__ +function _ipv4(Class, params) { + return new Class({ + type: "string", + format: "ipv4", + check: "string_format", + abort: false, + ...normalizeParams(params), + }); +} +// @__NO_SIDE_EFFECTS__ +function _ipv6(Class, params) { + return new Class({ + type: "string", + format: "ipv6", + check: "string_format", + abort: false, + ...normalizeParams(params), + }); +} +// @__NO_SIDE_EFFECTS__ +function _mac(Class, params) { + return new Class({ + type: "string", + format: "mac", + check: "string_format", + abort: false, + ...util.normalizeParams(params), + }); +} +// @__NO_SIDE_EFFECTS__ +function _cidrv4(Class, params) { + return new Class({ + type: "string", + format: "cidrv4", + check: "string_format", + abort: false, + ...normalizeParams(params), + }); +} +// @__NO_SIDE_EFFECTS__ +function _cidrv6(Class, params) { + return new Class({ + type: "string", + format: "cidrv6", + check: "string_format", + abort: false, + ...normalizeParams(params), + }); +} +// @__NO_SIDE_EFFECTS__ +function _base64(Class, params) { + return new Class({ + type: "string", + format: "base64", + check: "string_format", + abort: false, + ...normalizeParams(params), + }); +} +// @__NO_SIDE_EFFECTS__ +function _base64url(Class, params) { + return new Class({ + type: "string", + format: "base64url", + check: "string_format", + abort: false, + ...normalizeParams(params), + }); +} +// @__NO_SIDE_EFFECTS__ +function _e164(Class, params) { + return new Class({ + type: "string", + format: "e164", + check: "string_format", + abort: false, + ...normalizeParams(params), + }); +} +// @__NO_SIDE_EFFECTS__ +function _creditCard(Class, params) { + return new Class({ + type: "string", + format: "credit_card", + check: "string_format", + abort: false, + ...util.normalizeParams(params), + }); +} +// @__NO_SIDE_EFFECTS__ +function _jwt(Class, params) { + return new Class({ + type: "string", + format: "jwt", + check: "string_format", + abort: false, + ...normalizeParams(params), + }); +} +const TimePrecision = (/* unused pure expression or super */ null && ({ + Any: null, + Minute: -1, + Second: 0, + Millisecond: 3, + Microsecond: 6, +})); +// @__NO_SIDE_EFFECTS__ +function _isoDateTime(Class, params) { + return new Class({ + type: "string", + format: "datetime", + check: "string_format", + offset: false, + local: false, + precision: null, + ...normalizeParams(params), + }); +} +// @__NO_SIDE_EFFECTS__ +function _isoDate(Class, params) { + return new Class({ + type: "string", + format: "date", + check: "string_format", + ...normalizeParams(params), + }); +} +// @__NO_SIDE_EFFECTS__ +function _isoTime(Class, params) { + return new Class({ + type: "string", + format: "time", + check: "string_format", + precision: null, + ...normalizeParams(params), + }); +} +// @__NO_SIDE_EFFECTS__ +function _isoDuration(Class, params) { + return new Class({ + type: "string", + format: "duration", + check: "string_format", + ...normalizeParams(params), + }); +} +// @__NO_SIDE_EFFECTS__ +function _number(Class, params) { + return new Class({ + type: "number", + checks: [], + ...normalizeParams(params), + }); +} +// @__NO_SIDE_EFFECTS__ +function _coercedNumber(Class, params) { + return new Class({ + type: "number", + coerce: true, + checks: [], + ...normalizeParams(params), + }); +} +// @__NO_SIDE_EFFECTS__ +function _int(Class, params) { + return new Class({ + type: "number", + check: "number_format", + abort: false, + format: "safeint", + ...normalizeParams(params), + }); +} +// @__NO_SIDE_EFFECTS__ +function _float32(Class, params) { + return new Class({ + type: "number", + check: "number_format", + abort: false, + format: "float32", + ...util.normalizeParams(params), + }); +} +// @__NO_SIDE_EFFECTS__ +function _float64(Class, params) { + return new Class({ + type: "number", + check: "number_format", + abort: false, + format: "float64", + ...util.normalizeParams(params), + }); +} +// @__NO_SIDE_EFFECTS__ +function _int32(Class, params) { + return new Class({ + type: "number", + check: "number_format", + abort: false, + format: "int32", + ...util.normalizeParams(params), + }); +} +// @__NO_SIDE_EFFECTS__ +function _uint32(Class, params) { + return new Class({ + type: "number", + check: "number_format", + abort: false, + format: "uint32", + ...util.normalizeParams(params), + }); +} +// @__NO_SIDE_EFFECTS__ +function _boolean(Class, params) { + return new Class({ + type: "boolean", + ...normalizeParams(params), + }); +} +// @__NO_SIDE_EFFECTS__ +function _coercedBoolean(Class, params) { + return new Class({ + type: "boolean", + coerce: true, + ...util.normalizeParams(params), + }); +} +// @__NO_SIDE_EFFECTS__ +function _bigint(Class, params) { + return new Class({ + type: "bigint", + ...util.normalizeParams(params), + }); +} +// @__NO_SIDE_EFFECTS__ +function _coercedBigint(Class, params) { + return new Class({ + type: "bigint", + coerce: true, + ...util.normalizeParams(params), + }); +} +// @__NO_SIDE_EFFECTS__ +function _int64(Class, params) { + return new Class({ + type: "bigint", + check: "bigint_format", + abort: false, + format: "int64", + ...util.normalizeParams(params), + }); +} +// @__NO_SIDE_EFFECTS__ +function _uint64(Class, params) { + return new Class({ + type: "bigint", + check: "bigint_format", + abort: false, + format: "uint64", + ...util.normalizeParams(params), + }); +} +// @__NO_SIDE_EFFECTS__ +function _symbol(Class, params) { + return new Class({ + type: "symbol", + ...util.normalizeParams(params), + }); +} +// @__NO_SIDE_EFFECTS__ +function api_undefined(Class, params) { + return new Class({ + type: "undefined", + ...util.normalizeParams(params), + }); +} +// @__NO_SIDE_EFFECTS__ +function api_null(Class, params) { + return new Class({ + type: "null", + ...normalizeParams(params), + }); +} +// @__NO_SIDE_EFFECTS__ +function _any(Class) { + return new Class({ + type: "any", + }); +} +// @__NO_SIDE_EFFECTS__ +function _unknown(Class) { + return new Class({ + type: "unknown", + }); +} +// @__NO_SIDE_EFFECTS__ +function _never(Class, params) { + return new Class({ + type: "never", + ...normalizeParams(params), + }); +} +// @__NO_SIDE_EFFECTS__ +function _void(Class, params) { + return new Class({ + type: "void", + ...util.normalizeParams(params), + }); +} +// @__NO_SIDE_EFFECTS__ +function _date(Class, params) { + return new Class({ + type: "date", + ...util.normalizeParams(params), + }); +} +// @__NO_SIDE_EFFECTS__ +function _coercedDate(Class, params) { + return new Class({ + type: "date", + coerce: true, + ...util.normalizeParams(params), + }); +} +// @__NO_SIDE_EFFECTS__ +function _nan(Class, params) { + return new Class({ + type: "nan", + ...util.normalizeParams(params), + }); +} +// @__NO_SIDE_EFFECTS__ +function _lt(value, params) { + return new $ZodCheckLessThan({ + check: "less_than", + ...normalizeParams(params), + value, + inclusive: false, + }); +} +// @__NO_SIDE_EFFECTS__ +function _lte(value, params) { + return new $ZodCheckLessThan({ + check: "less_than", + ...normalizeParams(params), + value, + inclusive: true, + }); +} + +// @__NO_SIDE_EFFECTS__ +function _gt(value, params) { + return new $ZodCheckGreaterThan({ + check: "greater_than", + ...normalizeParams(params), + value, + inclusive: false, + }); +} +// @__NO_SIDE_EFFECTS__ +function _gte(value, params) { + return new $ZodCheckGreaterThan({ + check: "greater_than", + ...normalizeParams(params), + value, + inclusive: true, + }); +} + +// @__NO_SIDE_EFFECTS__ +function _positive(params) { + return _gt(0, params); +} +// negative +// @__NO_SIDE_EFFECTS__ +function _negative(params) { + return _lt(0, params); +} +// nonpositive +// @__NO_SIDE_EFFECTS__ +function _nonpositive(params) { + return _lte(0, params); +} +// nonnegative +// @__NO_SIDE_EFFECTS__ +function _nonnegative(params) { + return _gte(0, params); +} +// @__NO_SIDE_EFFECTS__ +function _multipleOf(value, params) { + return new $ZodCheckMultipleOf({ + check: "multiple_of", + ...normalizeParams(params), + value, + }); +} +// @__NO_SIDE_EFFECTS__ +function _maxSize(maximum, params) { + return new checks.$ZodCheckMaxSize({ + check: "max_size", + ...util.normalizeParams(params), + maximum, + }); +} +// @__NO_SIDE_EFFECTS__ +function _minSize(minimum, params) { + return new checks.$ZodCheckMinSize({ + check: "min_size", + ...util.normalizeParams(params), + minimum, + }); +} +// @__NO_SIDE_EFFECTS__ +function _size(size, params) { + return new checks.$ZodCheckSizeEquals({ + check: "size_equals", + ...util.normalizeParams(params), + size, + }); +} +// @__NO_SIDE_EFFECTS__ +function _maxLength(maximum, params) { + const ch = new $ZodCheckMaxLength({ + check: "max_length", + ...normalizeParams(params), + maximum, + }); + return ch; +} +// @__NO_SIDE_EFFECTS__ +function _minLength(minimum, params) { + return new $ZodCheckMinLength({ + check: "min_length", + ...normalizeParams(params), + minimum, + }); +} +// @__NO_SIDE_EFFECTS__ +function _length(length, params) { + return new $ZodCheckLengthEquals({ + check: "length_equals", + ...normalizeParams(params), + length, + }); +} +// @__NO_SIDE_EFFECTS__ +function _regex(pattern, params) { + return new $ZodCheckRegex({ + check: "string_format", + format: "regex", + ...normalizeParams(params), + pattern, + }); +} +// @__NO_SIDE_EFFECTS__ +function _lowercase(params) { + return new $ZodCheckLowerCase({ + check: "string_format", + format: "lowercase", + ...normalizeParams(params), + }); +} +// @__NO_SIDE_EFFECTS__ +function _uppercase(params) { + return new $ZodCheckUpperCase({ + check: "string_format", + format: "uppercase", + ...normalizeParams(params), + }); +} +// @__NO_SIDE_EFFECTS__ +function _includes(includes, params) { + return new $ZodCheckIncludes({ + check: "string_format", + format: "includes", + ...normalizeParams(params), + includes, + }); +} +// @__NO_SIDE_EFFECTS__ +function _startsWith(prefix, params) { + return new $ZodCheckStartsWith({ + check: "string_format", + format: "starts_with", + ...normalizeParams(params), + prefix, + }); +} +// @__NO_SIDE_EFFECTS__ +function _endsWith(suffix, params) { + return new $ZodCheckEndsWith({ + check: "string_format", + format: "ends_with", + ...normalizeParams(params), + suffix, + }); +} +// @__NO_SIDE_EFFECTS__ +function _property(property, schema, params) { + return new checks.$ZodCheckProperty({ + check: "property", + property, + schema, + ...util.normalizeParams(params), + }); +} +// @__NO_SIDE_EFFECTS__ +function _properties(shape) { + return Object.entries(shape).map(([property, schema]) => new checks.$ZodCheckProperty({ check: "property", property, schema })); +} +// @__NO_SIDE_EFFECTS__ +function _mime(types, params) { + return new checks.$ZodCheckMimeType({ + check: "mime_type", + mime: types, + ...util.normalizeParams(params), + }); +} +// @__NO_SIDE_EFFECTS__ +function _overwrite(tx) { + return new $ZodCheckOverwrite({ + check: "overwrite", + tx, + }); +} +// normalize +// @__NO_SIDE_EFFECTS__ +function _normalize(form) { + return _overwrite((input) => input.normalize(form)); +} +// trim +// @__NO_SIDE_EFFECTS__ +function _trim() { + return _overwrite((input) => input.trim()); +} +// toLowerCase +// @__NO_SIDE_EFFECTS__ +function _toLowerCase() { + return _overwrite((input) => input.toLowerCase()); +} +// toUpperCase +// @__NO_SIDE_EFFECTS__ +function _toUpperCase() { + return _overwrite((input) => input.toUpperCase()); +} +// slugify +// @__NO_SIDE_EFFECTS__ +function _slugify() { + return _overwrite((input) => slugify(input)); +} +// @__NO_SIDE_EFFECTS__ +function _array(Class, element, params) { + return new Class({ + type: "array", + element, + // get element() { + // return element; + // }, + ...normalizeParams(params), + }); +} +// @__NO_SIDE_EFFECTS__ +function _union(Class, options, params) { + return new Class({ + type: "union", + options, + ...util.normalizeParams(params), + }); +} +function _xor(Class, options, params) { + return new Class({ + type: "union", + options, + inclusive: false, + ...util.normalizeParams(params), + }); +} +// @__NO_SIDE_EFFECTS__ +function _discriminatedUnion(Class, discriminator, options, params) { + return new Class({ + type: "union", + options: options, + discriminator, + ...util.normalizeParams(params), + }); +} +// @__NO_SIDE_EFFECTS__ +function _intersection(Class, left, right) { + return new Class({ + type: "intersection", + left, + right, + }); +} +// export function _tuple( +// Class: util.SchemaClass, +// items: [], +// params?: string | $ZodTupleParams +// ): schemas.$ZodTuple<[], null>; +// @__NO_SIDE_EFFECTS__ +function _tuple(Class, items, _paramsOrRest, _params) { + const hasRest = _paramsOrRest instanceof schemas.$ZodType; + const params = hasRest ? _params : _paramsOrRest; + const rest = hasRest ? _paramsOrRest : null; + return new Class({ + type: "tuple", + items, + rest, + ...util.normalizeParams(params), + }); +} +// @__NO_SIDE_EFFECTS__ +function _record(Class, keyType, valueType, params) { + return new Class({ + type: "record", + keyType, + valueType, + ...util.normalizeParams(params), + }); +} +// @__NO_SIDE_EFFECTS__ +function _map(Class, keyType, valueType, params) { + return new Class({ + type: "map", + keyType, + valueType, + ...util.normalizeParams(params), + }); +} +// @__NO_SIDE_EFFECTS__ +function _set(Class, valueType, params) { + return new Class({ + type: "set", + valueType, + ...util.normalizeParams(params), + }); +} +// @__NO_SIDE_EFFECTS__ +function _enum(Class, values, params) { + const entries = Array.isArray(values) ? Object.fromEntries(values.map((v) => [v, v])) : values; + // if (Array.isArray(values)) { + // for (const value of values) { + // entries[value] = value; + // } + // } else { + // Object.assign(entries, values); + // } + // const entries: util.EnumLike = {}; + // for (const val of values) { + // entries[val] = val; + // } + return new Class({ + type: "enum", + entries, + ...util.normalizeParams(params), + }); +} +// @__NO_SIDE_EFFECTS__ +/** @deprecated This API has been merged into `z.enum()`. Use `z.enum()` instead. + * + * ```ts + * enum Colors { red, green, blue } + * z.enum(Colors); + * ``` + */ +function _nativeEnum(Class, entries, params) { + return new Class({ + type: "enum", + entries, + ...util.normalizeParams(params), + }); +} +// @__NO_SIDE_EFFECTS__ +function _literal(Class, value, params) { + return new Class({ + type: "literal", + values: Array.isArray(value) ? value : [value], + ...util.normalizeParams(params), + }); +} +// @__NO_SIDE_EFFECTS__ +function _file(Class, params) { + return new Class({ + type: "file", + ...util.normalizeParams(params), + }); +} +// @__NO_SIDE_EFFECTS__ +function _transform(Class, fn) { + return new Class({ + type: "transform", + transform: fn, + }); +} +// @__NO_SIDE_EFFECTS__ +function _optional(Class, innerType) { + return new Class({ + type: "optional", + innerType, + }); +} +// @__NO_SIDE_EFFECTS__ +function _nullable(Class, innerType) { + return new Class({ + type: "nullable", + innerType, + }); +} +// @__NO_SIDE_EFFECTS__ +function _default(Class, innerType, defaultValue) { + return new Class({ + type: "default", + innerType, + get defaultValue() { + return typeof defaultValue === "function" ? defaultValue() : util.shallowClone(defaultValue); + }, + }); +} +// @__NO_SIDE_EFFECTS__ +function _nonoptional(Class, innerType, params) { + return new Class({ + type: "nonoptional", + innerType, + ...util.normalizeParams(params), + }); +} +// @__NO_SIDE_EFFECTS__ +function _success(Class, innerType) { + return new Class({ + type: "success", + innerType, + }); +} +// @__NO_SIDE_EFFECTS__ +function _catch(Class, innerType, catchValue) { + return new Class({ + type: "catch", + innerType, + catchValue: (typeof catchValue === "function" ? catchValue : util.constantCatch(catchValue)), + }); +} +// @__NO_SIDE_EFFECTS__ +function _pipe(Class, in_, out) { + return new Class({ + type: "pipe", + in: in_, + out, + }); +} +// @__NO_SIDE_EFFECTS__ +function _readonly(Class, innerType) { + return new Class({ + type: "readonly", + innerType, + }); +} +// @__NO_SIDE_EFFECTS__ +function _templateLiteral(Class, parts, params) { + return new Class({ + type: "template_literal", + parts, + ...util.normalizeParams(params), + }); +} +// @__NO_SIDE_EFFECTS__ +function _lazy(Class, getter) { + return new Class({ + type: "lazy", + getter, + }); +} +// @__NO_SIDE_EFFECTS__ +function _promise(Class, innerType) { + return new Class({ + type: "promise", + innerType, + }); +} +// @__NO_SIDE_EFFECTS__ +function _custom(Class, fn, _params) { + const norm = util.normalizeParams(_params); + norm.abort ?? (norm.abort = true); // default to abort:false + const schema = new Class({ + type: "custom", + check: "custom", + fn: fn, + ...norm, + }); + return schema; +} +// same as _custom but defaults to abort:false +// @__NO_SIDE_EFFECTS__ +function _refine(Class, fn, _params) { + const schema = new Class({ + type: "custom", + check: "custom", + fn: fn, + ...normalizeParams(_params), + }); + return schema; +} +// @__NO_SIDE_EFFECTS__ +function _superRefine(fn, params) { + const ch = _check((payload) => { + payload.addIssue = (issue) => { + if (typeof issue === "string") { + payload.issues.push(util_issue(issue, payload.value, ch._zod.def)); + } + else { + // for Zod 3 backwards compatibility + const _issue = issue; + if (_issue.fatal) + _issue.continue = false; + _issue.code ?? (_issue.code = "custom"); + if (!("input" in _issue)) + _issue.input = payload.value; + _issue.inst ?? (_issue.inst = ch); + _issue.continue ?? (_issue.continue = !ch._zod.def.abort); // abort is always undefined, so this is always true... + payload.issues.push(util_issue(_issue)); + } + }; + return fn(payload.value, payload); + }, params); + return ch; +} +// @__NO_SIDE_EFFECTS__ +function _check(fn, params) { + const ch = new $ZodCheck({ + check: "custom", + ...normalizeParams(params), + }); + ch._zod.check = fn; + return ch; +} +// @__NO_SIDE_EFFECTS__ +function describe(description) { + const ch = new $ZodCheck({ check: "describe" }); + ch._zod.onattach = [ + (inst) => { + const existing = globalRegistry.get(inst) ?? {}; + globalRegistry.add(inst, { ...existing, description }); + }, + ]; + ch._zod.check = () => { }; // no-op check + return ch; +} +// @__NO_SIDE_EFFECTS__ +function api_meta(metadata) { + const ch = new $ZodCheck({ check: "meta" }); + ch._zod.onattach = [ + (inst) => { + const existing = globalRegistry.get(inst) ?? {}; + globalRegistry.add(inst, { ...existing, ...metadata }); + }, + ]; + ch._zod.check = () => { }; // no-op check + return ch; +} +// @__NO_SIDE_EFFECTS__ +function _stringbool(Classes, _params) { + const params = util.normalizeParams(_params); + let truthyArray = params.truthy ?? ["true", "1", "yes", "on", "y", "enabled"]; + let falsyArray = params.falsy ?? ["false", "0", "no", "off", "n", "disabled"]; + if (params.case !== "sensitive") { + truthyArray = truthyArray.map((v) => (typeof v === "string" ? v.toLowerCase() : v)); + falsyArray = falsyArray.map((v) => (typeof v === "string" ? v.toLowerCase() : v)); + } + const truthySet = new Set(truthyArray); + const falsySet = new Set(falsyArray); + const _Codec = Classes.Codec ?? schemas.$ZodCodec; + const _Boolean = Classes.Boolean ?? schemas.$ZodBoolean; + const _String = Classes.String ?? schemas.$ZodString; + const stringSchema = new _String({ type: "string", error: params.error }); + const booleanSchema = new _Boolean({ type: "boolean", error: params.error }); + const codec = new _Codec({ + type: "pipe", + in: stringSchema, + out: booleanSchema, + transform: ((input, payload) => { + let data = input; + if (params.case !== "sensitive") + data = data.toLowerCase(); + if (truthySet.has(data)) { + return true; + } + else if (falsySet.has(data)) { + return false; + } + else { + payload.issues.push({ + code: "invalid_value", + expected: "stringbool", + values: [...truthySet, ...falsySet], + input: payload.value, + inst: codec, + continue: false, + }); + return {}; + } + }), + reverseTransform: ((input, _payload) => { + if (input === true) { + return truthyArray[0] || "true"; + } + else { + return falsyArray[0] || "false"; + } + }), + error: params.error, + }); + codec._zod.bag.truthy = truthyArray; + codec._zod.bag.falsy = falsyArray; + codec._zod.bag.case = params.case ?? "insensitive"; + return codec; +} +// @__NO_SIDE_EFFECTS__ +function _stringFormat(Class, format, fnOrRegex, _params = {}) { + const params = util.normalizeParams(_params); + const def = { + check: "string_format", + type: "string", + format, + fn: typeof fnOrRegex === "function" ? fnOrRegex : (val) => fnOrRegex.test(val), + ...params, + }; + if (fnOrRegex instanceof RegExp) { + def.pattern = fnOrRegex; + } + const inst = new Class(def); + return inst; +} + + + +function assignProps(target, ...sources) { + for (const source of sources) { + for (const key of Reflect.ownKeys(source)) { + if (Object.prototype.propertyIsEnumerable.call(source, key)) { + assignProp(target, key, source[key]); + } + } + } + return target; +} +// function initializeContext(inputs: JSONSchemaGeneratorParams): ToJSONSchemaContext { +// return { +// processor: inputs.processor, +// metadataRegistry: inputs.metadata ?? globalRegistry, +// target: inputs.target ?? "draft-2020-12", +// unrepresentable: inputs.unrepresentable ?? "throw", +// }; +// } +function initializeContext(params) { + // Normalize target: convert old non-hyphenated versions to hyphenated versions + let target = params?.target ?? "draft-2020-12"; + if (target === "draft-4") + target = "draft-04"; + if (target === "draft-7") + target = "draft-07"; + return { + processors: params.processors ?? {}, + metadataRegistry: params?.metadata ?? globalRegistry, + target, + unrepresentable: params?.unrepresentable ?? "throw", + override: params?.override ?? (() => { }), + io: params?.io ?? "output", + counter: 0, + seen: new Map(), + sharedDefsExtractedFor: undefined, + sharedEmitDoneFor: undefined, + cycles: params?.cycles ?? "ref", + reused: params?.reused ?? "inline", + intersections: [], + deferred: [], + external: params?.external ?? undefined, + }; +} +/** + * Applies the `unrepresentable` setting at a site that has no JSON Schema equivalent. Throws + * `message` unless the setting (or the handler's return value) says otherwise. Returns `true` if a + * custom JSON Schema was written into `json`, in which case the caller must not write its own. + */ +function handleUnrepresentable(schema, ctx, json, params, message) { + const result = typeof ctx.unrepresentable === "function" + ? ctx.unrepresentable({ zodSchema: schema, path: params.path, message }) + : ctx.unrepresentable; + if (result === "any") + return false; + if (result === undefined || result === "throw") + throw new Error(message); + Object.assign(json, result); + return true; +} +function to_json_schema_process(schema, ctx, _params = { path: [], schemaPath: [] }) { + var _a; + const def = schema._zod.def; + // check for schema in seens + const seen = ctx.seen.get(schema); + if (seen) { + seen.count++; + // check if cycle + const isCycle = _params.schemaPath.includes(schema); + if (isCycle) { + seen.cycle = _params.path; + } + return seen.schema; + } + // initialize + const result = { schema: {}, count: 1, cycle: undefined, path: _params.path }; + ctx.seen.set(schema, result); + ctx.sharedDefsExtractedFor = undefined; + ctx.sharedEmitDoneFor = undefined; + // custom method overrides default behavior + const overrideSchema = schema._zod.toJSONSchema?.(); + if (overrideSchema) { + result.schema = overrideSchema; + } + else { + const params = { + ..._params, + schemaPath: [..._params.schemaPath, schema], + path: _params.path, + }; + if (schema._zod.processJSONSchema) { + schema._zod.processJSONSchema(ctx, result.schema, params); + } + else { + const _json = result.schema; + const processor = ctx.processors[def.type]; + if (!processor) { + throw new Error(`[toJSONSchema]: Non-representable type encountered: ${def.type}`); + } + processor(schema, ctx, _json, params); + } + const parent = schema._zod.parent; + if (parent) { + // Also set ref if processor didn't (for inheritance) + if (!result.ref) + result.ref = parent; + to_json_schema_process(parent, ctx, params); + ctx.seen.get(parent).isParent = true; + } + } + // metadata + const meta = ctx.metadataRegistry.get(schema); + if (meta) + assignProps(result.schema, meta); + if (ctx.io === "input" && isTransforming(schema)) { + // examples/defaults only apply to output type of pipe + delete result.schema.examples; + delete result.schema.default; + } + // set prefault as default + if (ctx.io === "input" && "_prefault" in result.schema) + (_a = result.schema).default ?? (_a.default = result.schema._prefault); + delete result.schema._prefault; + // pulling fresh from ctx.seen in case it was overwritten + const _result = ctx.seen.get(schema); + return _result.schema; +} +// Escape a reference token for use in a JSON Pointer fragment (RFC 6901): `~` becomes `~0` and `/` becomes `~1`. The `~` replacement must run first. +function encodeJSONPointerSegment(segment) { + return segment.replace(/~/g, "~0").replace(/\//g, "~1"); +} +function extractDefs(ctx, schema +// params: EmitParams +) { + // iterate over seen map; + const root = ctx.seen.get(schema); + if (!root) + throw new Error("Unprocessed schema. This is a bug in Zod."); + // With `external` set, every registered schema resolves through the external branch of `makeURI`, so the root branch below produces the same ref the external branch would — this pass is identical whichever schema it is called with, and only needs to run once. + if (ctx.external && ctx.sharedDefsExtractedFor === ctx.external) + return; + // Track ids to detect duplicates across different schemas + const idToSchema = new Map(); + for (const entry of ctx.seen.entries()) { + const id = ctx.metadataRegistry.get(entry[0])?.id; + if (id) { + const existing = idToSchema.get(id); + if (existing && existing !== entry[0]) { + throw new Error(`Duplicate schema id "${id}" detected during JSON Schema conversion. Two different schemas cannot share the same id when converted together.`); + } + idToSchema.set(id, entry[0]); + } + } + // returns a ref to the schema defId will be empty if the ref points to an external schema (or #) + const makeURI = (entry) => { + // comparing the seen objects because sometimes multiple schemas map to the same seen object. e.g. lazy + // external is configured + const defsSegment = ctx.target === "draft-2020-12" ? "$defs" : "definitions"; + if (ctx.external) { + const externalId = ctx.external.registry.get(entry[0])?.id; // ?? "__shared";// `__schema${ctx.counter++}`; + // check if schema is in the external registry + const uriGenerator = ctx.external.uri ?? ((id) => id); + if (externalId) { + return { ref: uriGenerator(externalId) }; + } + // otherwise, add to __shared + const id = entry[1].defId ?? entry[1].schema.id ?? `schema${ctx.counter++}`; + entry[1].defId = id; // set defId so it will be reused if needed + return { defId: id, ref: `${uriGenerator("__shared")}#/${defsSegment}/${encodeJSONPointerSegment(id)}` }; + } + const uriPrefix = `#`; + const defUriPrefix = `${uriPrefix}/${defsSegment}/`; + // an id-less root has nowhere to be extracted to, so it stays inline and self-references as `#` + if (entry[1] === root && !entry[1].schema.id) { + return { ref: uriPrefix }; + } + // self-contained schema + const defId = entry[1].schema.id ?? `__schema${ctx.counter++}`; + return { defId, ref: defUriPrefix + encodeJSONPointerSegment(defId) }; + }; + // stored cached version in `def` property remove all properties, set $ref + const extractToDef = (entry) => { + // if the schema is already a reference, do not extract it + if (entry[1].schema.$ref) { + return; + } + const seen = entry[1]; + const { ref, defId } = makeURI(entry); + seen.def = { ...seen.schema }; + // defId won't be set if the schema is a reference to an external schema or if the schema is the root schema + if (defId) + seen.defId = defId; + // wipe away all properties except $ref + const schema = seen.schema; + for (const key in schema) { + delete schema[key]; + } + schema.$ref = ref; + }; + // throw on cycles + // break cycles + if (ctx.cycles === "throw") { + for (const entry of ctx.seen.entries()) { + const seen = entry[1]; + if (seen.cycle) { + throw new Error("Cycle detected: " + + `#/${seen.cycle?.join("/")}/` + + '\n\nSet the `cycles` parameter to `"ref"` to resolve cyclical schemas with defs.'); + } + } + } + // extract schemas into $defs + for (const entry of ctx.seen.entries()) { + const seen = entry[1]; + // convert root schema to # $ref + if (schema === entry[0]) { + extractToDef(entry); // this has special handling for the root schema + continue; + } + // extract schemas that are in the external registry + if (ctx.external) { + const ext = ctx.external.registry.get(entry[0])?.id; + if (schema !== entry[0] && ext) { + extractToDef(entry); + continue; + } + } + // extract schemas with `id` meta + const id = ctx.metadataRegistry.get(entry[0])?.id; + if (id) { + extractToDef(entry); + continue; + } + // break cycles + if (seen.cycle) { + // any + extractToDef(entry); + continue; + } + // extract reused schemas + if (seen.count > 1) { + if (ctx.reused === "ref") { + extractToDef(entry); + // biome-ignore lint: + continue; + } + } + } + if (ctx.external) + ctx.sharedDefsExtractedFor = ctx.external; +} +/** Rewrites `anyOf: [{type: "a"}, {type: "b"}]` to `type: ["a", "b"]`, which every JSON Schema draft treats as equivalent and most consumers render far better for the nullable case. Only branches that are a bare type assertion qualify — anything carrying a constraint, `$ref`, `const` or metadata is left alone. Runs after `flattenRef`, so a branch an override decorated or `$defs` extraction turned into a `$ref` is no longer bare and correctly stays in `anyOf`. `oneOf` is excluded: `integer` and `number` overlap, so "exactly one" and "at least one" are not the same there. OpenAPI 3.0 is excluded: its `type` must be a single string. */ +function compactTypeUnion(schema) { + const options = schema.anyOf; + if (!Array.isArray(options) || options.length === 0 || schema.type !== undefined) + return; + const types = []; + for (const option of options) { + if (!option || typeof option !== "object") + return; + // A branch that is itself a compactible union folds into this one — nested `anyOf` and a flat `type` array say the same thing. Compacting it first also makes the result independent of the order this pass walks the seen map in. + compactTypeUnion(option); + const keys = Object.keys(option); + if (keys.length !== 1 || keys[0] !== "type") + return; + const type = option.type; + for (const member of Array.isArray(type) ? type : [type]) { + if (typeof member !== "string") + return; + if (!types.includes(member)) + types.push(member); + } + } + delete schema.anyOf; + // A `type` array must be non-empty and unique (metaschema); a single member is spelled as a bare string. + schema.type = types.length === 1 ? types[0] : types; +} +/** Keywords `foldIntersection` knows how to combine. Anything else — `$ref`, `patternProperties`, + * an annotation like `description` — makes a member unfoldable, so a constraint this does not + * understand leaves the `allOf` alone instead of being silently dropped or misattributed. */ +const FOLDABLE_KEYS = new Set(["type", "properties", "required", "additionalProperties"]); +const UNION_KEYS = ["oneOf", "anyOf"]; +/** A member's constraint on a key it does not declare itself. A `catchall` states one; `false`, an absent `additionalProperties`, and the empty schema a loose object emits state nothing. */ +function undeclaredConstraint(member) { + const extra = member.additionalProperties; + if (extra === undefined || extra === false || typeof extra !== "object" || extra === null) + return null; + return Object.keys(extra).length ? extra : null; +} +/** Combines object members into the single object they describe together, or returns `null` if any of them carries a keyword outside {@link FOLDABLE_KEYS}. */ +function foldObjects(members) { + const objects = []; + for (const member of members) { + // A boolean subschema is legal JSON Schema and carries no keywords to fold. + if (typeof member !== "object" || member.type !== "object") + return null; + for (const key in member) { + if (!FOLDABLE_KEYS.has(key)) + return null; + } + objects.push(member); + } + const properties = {}; + const required = new Set(); + for (const object of objects) { + for (const key in object.properties) { + // `in` would report a `__proto__` key as already present via the prototype chain and skip it. + if (Object.prototype.hasOwnProperty.call(properties, key)) + continue; + // Every member constrains this key: the ones that declare it say how, and a `catchall` member constrains it too even though it does not name it. The key has to satisfy all of them, which is the same intersection one level down. + const parts = []; + for (const other of objects) { + const part = other.properties?.[key] ?? undeclaredConstraint(other); + if (part === null || part === undefined) + continue; + if (!parts.some((seen) => JSON.stringify(seen) === JSON.stringify(part))) + parts.push(part); + } + const merged = parts.length === 1 + ? parts[0] + : (foldObjects(parts) ?? { allOf: parts }); + assignProp(properties, key, merged); + } + for (const key of object.required ?? []) + required.add(key); + } + const folded = { type: "object", properties }; + if (required.size) + folded.required = [...required]; + // A key no member declares is rejected only when every member rejects it, so the fold is closed only when every member is. Otherwise it carries whatever the `catchall` members demand of such a key. + if (objects.every((object) => object.additionalProperties === false)) { + folded.additionalProperties = false; + } + else { + const constraints = []; + for (const object of objects) { + const constraint = undeclaredConstraint(object); + if (constraint && !constraints.some((seen) => JSON.stringify(seen) === JSON.stringify(constraint))) + constraints.push(constraint); + } + if (constraints.length === 1) + folded.additionalProperties = constraints[0]; + else if (constraints.length > 1) + folded.additionalProperties = { allOf: constraints }; + } + return folded; +} +/** `additionalProperties` in an `allOf` member sees only that member's own `properties`, so two + * closed object members reject each other's keys and the schema validates nothing. Zod's parser + * pools the key sets instead — `handleIntersectionResults` reports a key as unrecognized only when + * *every* side rejects it — so the emitted schema has to pool them too, and folding the members + * into one object is the encoding that says so on every target. + * + * This runs from `finalize`, after `extractDefs`, which is what keeps it clear of the `$ref` + * machinery: a member extracted into `$defs` is already a `$ref` by now and declines to fold, so it + * keeps its reference and its own closedness rather than being inlined as a stale copy. */ +function foldIntersection(json) { + const allOf = json.allOf; + if (!Array.isArray(allOf) || allOf.length < 2) + return; + // An `override` runs before this pass and may have written object keywords onto the intersection itself. Those are deliberate, so decline rather than overwrite them. + for (const key of FOLDABLE_KEYS) + if (key in json) + return; + // An intersection distributes over a union: `A & (X | Y)` is `(A & X) | (A & Y)`. Only the first union is distributed over; a second one stays among the members every branch folds against, where it fails the object check and declines the whole intersection rather than multiplying out. + const unions = allOf.filter((m) => UNION_KEYS.some((k) => Array.isArray(m[k]))); + let folded = null; + if (!unions.length) { + folded = foldObjects(allOf); + } + else { + const union = unions[0]; + const keyword = UNION_KEYS.find((k) => Array.isArray(union[k])); + if (Object.keys(union).length !== 1) + return; + const rest = allOf.filter((m) => m !== union); + const branches = union[keyword].map((branch) => foldObjects([...rest, branch])); + if (branches.some((b) => !b)) + return; + folded = { [keyword]: branches }; + } + if (!folded) + return; + delete json.allOf; + assignProps(json, folded); +} +function finalize(ctx, schema) { + const root = ctx.seen.get(schema); + if (!root) + throw new Error("Unprocessed schema. This is a bug in Zod."); + // flatten refs - inherit properties from parent schemas + const flattenRef = (zodSchema) => { + const seen = ctx.seen.get(zodSchema); + // already processed + if (seen.ref === null) + return; + const schema = seen.def ?? seen.schema; + const _cached = { ...schema }; + const ref = seen.ref; + seen.ref = null; // prevent infinite recursion + if (ref) { + flattenRef(ref); + const refSeen = ctx.seen.get(ref); + const refSchema = refSeen.schema; + // merge referenced schema into current + if (refSchema.$ref && (ctx.target === "draft-07" || ctx.target === "draft-04" || ctx.target === "openapi-3.0")) { + // older drafts can't combine $ref with other properties + schema.allOf = schema.allOf ?? []; + schema.allOf.push(refSchema); + } + else { + assignProps(schema, refSchema); + } + // restore child's own properties (child wins) + assignProps(schema, _cached); + const isParentRef = zodSchema._zod.parent === ref; + // For parent chain, child is a refinement - remove parent-only properties + if (isParentRef) { + for (const key in schema) { + if (key === "$ref" || key === "allOf") + continue; + if (!(key in _cached)) { + delete schema[key]; + } + } + } + // When ref was extracted to $defs, remove properties that match the definition + if (refSchema.$ref && refSeen.def) { + for (const key in schema) { + if (key === "$ref" || key === "allOf") + continue; + if (key in refSeen.def && JSON.stringify(schema[key]) === JSON.stringify(refSeen.def[key])) { + delete schema[key]; + } + } + } + } + // If parent was extracted (has $ref), propagate $ref to this schema. This handles cases like: readonly().meta({id}).describe() where processor sets ref to innerType but parent should be referenced + const parent = zodSchema._zod.parent; + if (parent && parent !== ref) { + // Ensure parent is processed first so its def has inherited properties + flattenRef(parent); + const parentSeen = ctx.seen.get(parent); + if (parentSeen?.schema.$ref) { + schema.$ref = parentSeen.schema.$ref; + // De-duplicate with parent's definition + if (parentSeen.def) { + for (const key in schema) { + if (key === "$ref" || key === "allOf") + continue; + if (key in parentSeen.def && JSON.stringify(schema[key]) === JSON.stringify(parentSeen.def[key])) { + delete schema[key]; + } + } + } + } + } + // execute overrides + ctx.override({ + zodSchema: zodSchema, + jsonSchema: schema, + path: seen.path ?? [], + }); + }; + // Flattening walks the whole map and clears each `ref` as it goes, so a second call over the same map is a no-op scan. Skip it outright once it has run for a registry conversion. + if (!ctx.external || ctx.sharedEmitDoneFor !== ctx.external) { + for (const entry of [...ctx.seen.entries()].reverse()) { + flattenRef(entry[0]); + } + if (ctx.target !== "openapi-3.0") { + for (const entry of ctx.seen.entries()) { + compactTypeUnion(entry[1].def ?? entry[1].schema); + } + } + for (const rewrite of ctx.deferred) + rewrite(); + // After flattening, every member that was extracted is a `$ref`, so the fold sees the final shape. A schema that inherits an intersection — through `z.lazy`, or any `ref` chain — holds the same `allOf` array, so fold by array identity to catch every copy. + if (ctx.intersections.length) { + const carriers = new Map(); + for (const seen of ctx.seen.values()) { + for (const json of [seen.schema, seen.def]) { + const allOf = json?.allOf; + if (!Array.isArray(allOf)) + continue; + const existing = carriers.get(allOf); + if (existing) + existing.push(json); + else + carriers.set(allOf, [json]); + } + } + for (const allOf of ctx.intersections) { + for (const json of carriers.get(allOf) ?? []) + foldIntersection(json); + } + } + } + const result = {}; + if (ctx.target === "draft-2020-12") { + result.$schema = "https://json-schema.org/draft/2020-12/schema"; + } + else if (ctx.target === "draft-07") { + result.$schema = "http://json-schema.org/draft-07/schema#"; + } + else if (ctx.target === "draft-04") { + result.$schema = "http://json-schema.org/draft-04/schema#"; + } + else if (ctx.target === "openapi-3.0") { + // OpenAPI 3.0 schema objects should not include a $schema property + } + else { + // Arbitrary string values are allowed but won't have a $schema property set + } + if (ctx.external?.uri) { + const id = ctx.external.registry.get(schema)?.id; + if (!id) + throw new Error("Schema is missing an `id` property"); + result.$id = ctx.external.uri(id); + } + // when the root was extracted into $defs, `root.schema` is the `$ref` wrapper and `root.def` is the body that now lives under $defs + assignProps(result, root.defId ? root.schema : (root.def ?? root.schema)); + // The `id` in `.meta()` is a Zod-specific registration tag used to extract schemas into $defs — it is not user-facing JSON Schema metadata. Strip it from the output body where it would otherwise leak. The id is preserved implicitly via the $defs key (and via $ref paths). + const rootMetaId = ctx.metadataRegistry.get(schema)?.id; + if (rootMetaId !== undefined && result.id === rootMetaId) + delete result.id; + // build defs object. With `external`, `defs` is the shared object every schema writes into, so the same entries are reassigned on every call. Without it, `defs` is fresh per call and must be rebuilt. + const defs = ctx.external?.defs ?? {}; + if (!ctx.external || ctx.sharedEmitDoneFor !== ctx.external) { + for (const entry of ctx.seen.entries()) { + const seen = entry[1]; + if (seen.def && seen.defId) { + if (seen.def.id === seen.defId) + delete seen.def.id; + assignProp(defs, seen.defId, seen.def); + } + } + } + if (ctx.external) + ctx.sharedEmitDoneFor = ctx.external; + // set definitions in result + if (ctx.external) { + } + else { + if (Object.keys(defs).length > 0) { + if (ctx.target === "draft-2020-12") { + result.$defs = defs; + } + else { + result.definitions = defs; + } + } + } + try { + // this "finalizes" this schema and ensures all cycles are removed each call to finalize() is functionally independent though the seen map is shared + const finalized = JSON.parse(JSON.stringify(result)); + Object.defineProperty(finalized, "~standard", { + value: { + ...schema["~standard"], + jsonSchema: { + input: createStandardJSONSchemaMethod(schema, "input", ctx.processors), + output: createStandardJSONSchemaMethod(schema, "output", ctx.processors), + }, + }, + enumerable: false, + writable: false, + }); + return finalized; + } + catch (_err) { + throw new Error("Error converting schema to JSON."); + } +} +function isTransforming(_schema, _ctx) { + const ctx = _ctx ?? { seen: new Set() }; + if (ctx.seen.has(_schema)) + return false; + ctx.seen.add(_schema); + const def = _schema._zod.def; + if (def.type === "transform") + return true; + if (def.type === "array") + return isTransforming(def.element, ctx); + if (def.type === "set") + return isTransforming(def.valueType, ctx); + if (def.type === "lazy") + return isTransforming(def.getter(), ctx); + if (def.type === "promise" || + def.type === "optional" || + def.type === "nonoptional" || + def.type === "nullable" || + def.type === "readonly" || + def.type === "default" || + def.type === "prefault" || + def.type === "catch") { + return isTransforming(def.innerType, ctx); + } + if (def.type === "intersection") { + return isTransforming(def.left, ctx) || isTransforming(def.right, ctx); + } + if (def.type === "record" || def.type === "map") { + return isTransforming(def.keyType, ctx) || isTransforming(def.valueType, ctx); + } + if (def.type === "pipe") { + if (_schema._zod.traits.has("$ZodCodec")) + return true; + return isTransforming(def.in, ctx) || isTransforming(def.out, ctx); + } + if (def.type === "object") { + for (const key in def.shape) { + if (isTransforming(def.shape[key], ctx)) + return true; + } + return false; + } + if (def.type === "union") { + for (const option of def.options) { + if (isTransforming(option, ctx)) + return true; + } + return false; + } + if (def.type === "tuple") { + for (const item of def.items) { + if (isTransforming(item, ctx)) + return true; + } + if (def.rest && isTransforming(def.rest, ctx)) + return true; + return false; + } + return false; +} +/** + * Creates a toJSONSchema method for a schema instance. + * This encapsulates the logic of initializing context, processing, extracting defs, and finalizing. + */ +const createToJSONSchemaMethod = (schema, processors = {}) => (params) => { + const ctx = initializeContext({ ...params, processors }); + to_json_schema_process(schema, ctx); + extractDefs(ctx, schema); + return finalize(ctx, schema); +}; +const createStandardJSONSchemaMethod = (schema, io, processors = {}) => (params) => { + const { libraryOptions, target } = params ?? {}; + const ctx = initializeContext({ ...(libraryOptions ?? {}), target, io, processors }); + to_json_schema_process(schema, ctx); + extractDefs(ctx, schema); + return finalize(ctx, schema); +}; + + + + +const formatMap = { + guid: "uuid", + url: "uri", + datetime: "date-time", + json_string: "json-string", + regex: "", // do not set +}; +// ==================== SIMPLE TYPE PROCESSORS ==================== +const stringProcessor = (schema, ctx, _json, _params) => { + const json = _json; + json.type = "string"; + const { minimum, maximum, format, patterns, contentEncoding, laxFormat } = schema._zod + .bag; + if (typeof minimum === "number") + json.minLength = minimum; + if (typeof maximum === "number") + json.maxLength = maximum; + // custom pattern overrides format + if (format) { + json.format = formatMap[format] ?? format; + if (json.format === "") + delete json.format; // empty format is not valid + // `z.iso.time()` is never full-time, and `laxFormat` carries the datetime shapes that also accept what their keyword forbids + if (format === "time" || laxFormat) { + delete json.format; + } + } + if (contentEncoding) + json.contentEncoding = contentEncoding; + if (patterns && patterns.size > 0) { + const patternList = [...patterns]; + if (patternList.length === 1) + json.pattern = patternList[0].source; + else if (patternList.length > 1) { + json.allOf = [ + ...patternList.map((regex) => ({ + ...(ctx.target === "draft-07" || ctx.target === "draft-04" || ctx.target === "openapi-3.0" + ? { type: "string" } + : {}), + pattern: regex.source, + })), + ]; + } + } +}; +const numberProcessor = (schema, ctx, _json, params) => { + const json = _json; + const { minimum, maximum, format, multipleOf, exclusiveMaximum, exclusiveMinimum } = schema._zod.bag; + if (typeof format === "string" && format.includes("int")) + json.type = "integer"; + else + json.type = "number"; + // when both minimum and exclusiveMinimum exist, pick the more restrictive one + const exMin = typeof exclusiveMinimum === "number" && exclusiveMinimum >= (minimum ?? Number.NEGATIVE_INFINITY); + const exMax = typeof exclusiveMaximum === "number" && exclusiveMaximum <= (maximum ?? Number.POSITIVE_INFINITY); + const legacy = ctx.target === "draft-04" || ctx.target === "openapi-3.0"; + if (exMin) { + if (legacy) { + json.minimum = exclusiveMinimum; + json.exclusiveMinimum = true; + } + else { + json.exclusiveMinimum = exclusiveMinimum; + } + } + else if (typeof minimum === "number") { + json.minimum = minimum; + } + if (exMax) { + if (legacy) { + json.maximum = exclusiveMaximum; + json.exclusiveMaximum = true; + } + else { + json.exclusiveMaximum = exclusiveMaximum; + } + } + else if (typeof maximum === "number") { + json.maximum = maximum; + } + if (typeof multipleOf === "number") { + // JSON Schema requires a divisor strictly greater than zero, and a non-finite one does not survive JSON at all. A negative divisor accepts exactly what its absolute value accepts, so it still maps; zero, NaN and Infinity have no keyword form. + if (Number.isFinite(multipleOf) && multipleOf !== 0) + json.multipleOf = Math.abs(multipleOf); + else + handleUnrepresentable(schema, ctx, json, params, `A multipleOf divisor of ${multipleOf} cannot be represented in JSON Schema`); + } +}; +const booleanProcessor = (_schema, _ctx, json, _params) => { + json.type = "boolean"; +}; +const bigintProcessor = (schema, ctx, json, params) => { + handleUnrepresentable(schema, ctx, json, params, "BigInt cannot be represented in JSON Schema"); +}; +const symbolProcessor = (schema, ctx, json, params) => { + handleUnrepresentable(schema, ctx, json, params, "Symbols cannot be represented in JSON Schema"); +}; +const nullProcessor = (_schema, ctx, json, _params) => { + if (ctx.target === "openapi-3.0") { + json.type = "string"; + json.nullable = true; + json.enum = [null]; + } + else { + json.type = "null"; + } +}; +const undefinedProcessor = (schema, ctx, json, params) => { + handleUnrepresentable(schema, ctx, json, params, "Undefined cannot be represented in JSON Schema"); +}; +const voidProcessor = (schema, ctx, json, params) => { + handleUnrepresentable(schema, ctx, json, params, "Void cannot be represented in JSON Schema"); +}; +const neverProcessor = (_schema, _ctx, json, _params) => { + json.not = {}; +}; +const anyProcessor = (_schema, _ctx, _json, _params) => { + // empty schema accepts anything +}; +const unknownProcessor = (_schema, _ctx, _json, _params) => { + // empty schema accepts anything +}; +const dateProcessor = (schema, ctx, json, params) => { + handleUnrepresentable(schema, ctx, json, params, "Date cannot be represented in JSON Schema"); +}; +const enumProcessor = (schema, _ctx, json, _params) => { + const def = schema._zod.def; + const values = getEnumValues(def.entries); + // an empty enum accepts nothing, same as z.never() + if (values.length === 0) { + json.not = {}; + return; + } + // Number enums can have both string and number values + if (values.every((v) => typeof v === "number")) + json.type = "number"; + if (values.every((v) => typeof v === "string")) + json.type = "string"; + json.enum = values; +}; +const literalProcessor = (schema, ctx, json, params) => { + const def = schema._zod.def; + // a literal with no values accepts nothing, same as z.never() + if (def.values.length === 0) { + json.not = {}; + return; + } + const vals = []; + for (const val of def.values) { + if (val === undefined) { + // a custom schema replaces the whole literal, so there is nothing left to accumulate + if (handleUnrepresentable(schema, ctx, json, params, "Literal `undefined` cannot be represented in JSON Schema")) + return; + // otherwise do not add to vals + } + else if (typeof val === "bigint") { + if (handleUnrepresentable(schema, ctx, json, params, "BigInt literals cannot be represented in JSON Schema")) + return; + vals.push(Number(val)); + } + else { + vals.push(val); + } + } + if (vals.length === 0) { + // do nothing (an undefined literal was stripped) + } + else if (vals.length === 1) { + const val = vals[0]; + json.type = val === null ? "null" : typeof val; + if (ctx.target === "draft-04" || ctx.target === "openapi-3.0") { + json.enum = [val]; + } + else { + json.const = val; + } + } + else { + if (vals.every((v) => typeof v === "number")) + json.type = "number"; + if (vals.every((v) => typeof v === "string")) + json.type = "string"; + if (vals.every((v) => typeof v === "boolean")) + json.type = "boolean"; + if (vals.every((v) => v === null)) + json.type = "null"; + json.enum = vals; + } +}; +const nanProcessor = (schema, ctx, json, params) => { + handleUnrepresentable(schema, ctx, json, params, "NaN cannot be represented in JSON Schema"); +}; +const templateLiteralProcessor = (schema, _ctx, json, _params) => { + const _json = json; + const pattern = schema._zod.pattern; + if (!pattern) + throw new Error("Pattern not found in template literal"); + _json.type = "string"; + _json.pattern = pattern.source; +}; +const fileProcessor = (schema, _ctx, json, _params) => { + const _json = json; + const file = { + type: "string", + format: "binary", + contentEncoding: "binary", + }; + const { minimum, maximum, mime } = schema._zod.bag; + if (minimum !== undefined) + file.minLength = minimum; + if (maximum !== undefined) + file.maxLength = maximum; + if (mime) { + if (mime.length === 1) { + file.contentMediaType = mime[0]; + Object.assign(_json, file); + } + else { + Object.assign(_json, file); // shared props at root + _json.anyOf = mime.map((m) => ({ contentMediaType: m })); // only contentMediaType differs + } + } + else { + Object.assign(_json, file); + } +}; +const successProcessor = (_schema, _ctx, json, _params) => { + json.type = "boolean"; +}; +const customProcessor = (schema, ctx, json, params) => { + handleUnrepresentable(schema, ctx, json, params, "Custom types cannot be represented in JSON Schema"); +}; +const functionProcessor = (schema, ctx, json, params) => { + handleUnrepresentable(schema, ctx, json, params, "Function types cannot be represented in JSON Schema"); +}; +const transformProcessor = (schema, ctx, json, params) => { + handleUnrepresentable(schema, ctx, json, params, "Transforms cannot be represented in JSON Schema"); +}; +const mapProcessor = (schema, ctx, json, params) => { + handleUnrepresentable(schema, ctx, json, params, "Map cannot be represented in JSON Schema"); +}; +const setProcessor = (schema, ctx, json, params) => { + handleUnrepresentable(schema, ctx, json, params, "Set cannot be represented in JSON Schema"); +}; +// ==================== COMPOSITE TYPE PROCESSORS ==================== +const arrayProcessor = (schema, ctx, _json, params) => { + const json = _json; + const def = schema._zod.def; + const { minimum, maximum } = schema._zod.bag; + if (typeof minimum === "number") + json.minItems = minimum; + if (typeof maximum === "number") + json.maxItems = maximum; + json.type = "array"; + json.items = to_json_schema_process(def.element, ctx, { + ...params, + path: [...params.path, "items"], + }); +}; +// Transform and catch set `optin = "optional"` at runtime so the parser lets them observe an +// absent key, but their declared input type stays required. An input JSON Schema describes the +// declared type, so resolve past them to the schema that actually carries the optionality. +// Used by both `objectProcessor` (for `required`) and `tupleProcessor` (for `minItems`); see +// wiki/optionality.md, "The JSON Schema emitter reads the *static* value". +function inputOptin(schema) { + const def = schema._zod.def; + if (def.type === "pipe" && def.in._zod.traits.has("$ZodTransform")) { + return inputOptin(def.out); + } + if (def.type === "catch") { + return inputOptin(def.innerType); + } + return schema._zod.optin; +} +const objectProcessor = (schema, ctx, _json, params) => { + const json = _json; + const def = schema._zod.def; + const shape = def.shape; + // dropping it while still emitting `additionalProperties: false` would emit a schema that rejects data this one requires + const symbolKeys = Object.getOwnPropertySymbols(shape); + if (symbolKeys.length && + handleUnrepresentable(schema, ctx, json, params, "Symbol keys cannot be represented in JSON Schema")) { + return; + } + json.type = "object"; + json.properties = {}; + for (const key in shape) { + // assignProp so a __proto__ key becomes an own property instead of hitting the inherited setter on the plain {} we build into + assignProp(json.properties, key, to_json_schema_process(shape[key], ctx, { + ...params, + path: [...params.path, "properties", key], + })); + } + // required keys + const allKeys = new Set(Object.keys(shape)); + const requiredKeys = new Set([...allKeys].filter((key) => { + const field = def.shape[key]; + if (ctx.io === "input") { + return inputOptin(field) === undefined; + } + else { + return field._zod.optout === undefined; + } + })); + if (requiredKeys.size > 0) { + json.required = Array.from(requiredKeys); + } + // catchall + if (def.catchall?._zod.def.type === "never") { + // strict + json.additionalProperties = false; + } + else if (!def.catchall) { + // regular + if (ctx.io === "output") + json.additionalProperties = false; + } + else if (def.catchall) { + json.additionalProperties = to_json_schema_process(def.catchall, ctx, { + ...params, + path: [...params.path, "additionalProperties"], + }); + } +}; +const unionProcessor = (schema, ctx, json, params) => { + const def = schema._zod.def; + // Exclusive unions (inclusive === false) use oneOf (exactly one match) instead of anyOf (one or more matches). This includes both z.xor() and discriminated unions + const isExclusive = def.inclusive === false; + const options = def.options.map((x, i) => to_json_schema_process(x, ctx, { + ...params, + path: [...params.path, isExclusive ? "oneOf" : "anyOf", i], + })); + if (isExclusive) { + json.oneOf = options; + } + else { + json.anyOf = options; + } +}; +const intersectionProcessor = (schema, ctx, json, params) => { + const def = schema._zod.def; + const a = to_json_schema_process(def.left, ctx, { + ...params, + path: [...params.path, "allOf", 0], + }); + const b = to_json_schema_process(def.right, ctx, { + ...params, + path: [...params.path, "allOf", 1], + }); + const isSimpleIntersection = (val) => "allOf" in val && Object.keys(val).length === 1; + const allOf = [ + ...(isSimpleIntersection(a) ? a.allOf : [a]), + ...(isSimpleIntersection(b) ? b.allOf : [b]), + ]; + json.allOf = allOf; + // Recorded innermost first, so a nested intersection has already folded by the time this one is considered. The array is the handle rather than the schema, because a wrapper that inherits this schema shares the same array; `finalize` folds every object holding it. See `foldIntersection`. + ctx.intersections.push(allOf); +}; +const tupleProcessor = (schema, ctx, _json, params) => { + const json = _json; + const def = schema._zod.def; + json.type = "array"; + const prefixPath = ctx.target === "draft-2020-12" ? "prefixItems" : "items"; + const restPath = ctx.target === "draft-2020-12" ? "items" : ctx.target === "openapi-3.0" ? "items" : "additionalItems"; + const prefixItems = def.items.map((x, i) => to_json_schema_process(x, ctx, { + ...params, + path: [...params.path, prefixPath, i], + })); + const rest = def.rest + ? to_json_schema_process(def.rest, ctx, { + ...params, + path: [...params.path, restPath, ...(ctx.target === "openapi-3.0" ? [def.items.length] : [])], + }) + : null; + let minItems = def.items.length; + while (minItems > 0) { + const item = def.items[minItems - 1]; + const optional = ctx.io === "input" ? inputOptin(item) !== undefined : item._zod.optout === "optional"; + if (!optional) + break; + minItems--; + } + const maxItems = def.items.length; + const isClosed = !def.rest; + if (ctx.target === "draft-2020-12") { + json.prefixItems = prefixItems; + if (isClosed) { + json.items = false; + } + else if (rest) { + json.items = rest; + } + if (minItems > 0) + json.minItems = minItems; + if (isClosed) + json.maxItems = maxItems; + } + else if (ctx.target === "openapi-3.0") { + json.items = { + anyOf: prefixItems, + }; + if (rest) { + json.items.anyOf.push(rest); + } + if (minItems > 0) + json.minItems = minItems; + if (isClosed) + json.maxItems = maxItems; + } + else { + json.items = prefixItems; + if (isClosed) { + json.additionalItems = false; + } + else if (rest) { + json.additionalItems = rest; + } + if (minItems > 0) + json.minItems = minItems; + if (isClosed) + json.maxItems = maxItems; + } + // explicit user-defined length checks take precedence + const { minimum, maximum } = schema._zod.bag; + if (typeof minimum === "number") + json.minItems = minimum; + if (typeof maximum === "number") + json.maxItems = maximum; +}; +/** JSON object keys are always strings, so a numeric record key schema is re-expressed over the + * numeric-string form the record parser matches. Deferred to `finalize`, after the flatten: a key + * behind a wrapper only carries its own `type` before then, and a union key only has its branches. + * + * A numeric bound cannot apply to a property name, so `minimum` and its siblings are dropped rather + * than carried over: keeping them beside `type: "string"` reproduces the match-nothing schema this + * exists to fix. A key that carries one therefore emits wider than the record parses — `z.record(z.number().min(5), V)` + * accepts `"3"` — which is the deliberate trade, since throwing on it would reject an ordinary schema + * outright. */ +function stringifyKeyNames(bySchema, json, visited) { + // an extracted key that rewrites cannot go on sharing its definition — the string form a key position needs is not the number form every other reference wants — so it inlines. One that does not rewrite keeps the `$ref`. + if (json.$ref) { + // a recursive key holds its own reference inside its definition, so a node already on the path is left alone rather than resolved again + if (visited.has(json)) + return json; + visited.add(json); + const def = bySchema.get(json)?.def; + if (!def) + return json; + const inlined = stringifyKeyNames(bySchema, def, visited); + return inlined === def ? json : inlined; + } + for (const keyword of ["anyOf", "oneOf"]) { + const branches = json[keyword]; + if (!Array.isArray(branches)) + continue; + const mapped = branches.map((branch) => stringifyKeyNames(bySchema, branch, visited)); + // rebuilding regardless would detach a key that had nothing to re-express, dropping its `$ref` and leaking the internal `id` + if (mapped.some((branch, i) => branch !== branches[i])) + json = { ...json, [keyword]: mapped }; + } + // a member that already admits a string leaves the key unconstrained, so the node's own type re-expresses only when every member is numeric + const types = Array.isArray(json.type) ? json.type : [json.type]; + const numericType = !types.includes("string") && types.some((t) => t === "number" || t === "integer"); + // a heterogeneous key carries no type at all, so its numeric members are caught here instead + const values = json.enum ?? (json.const !== undefined ? [json.const] : undefined); + if (!numericType && !values?.some((v) => typeof v === "number")) + return json; + const { minimum, maximum, exclusiveMinimum, exclusiveMaximum, multipleOf, format, id, ...rest } = json; + if (rest.enum) + rest.enum = rest.enum.map((v) => (typeof v === "number" ? String(v) : v)); + else if (typeof rest.const === "number") + rest.const = String(rest.const); + // a heterogeneous key keeps its absent type: the stringified members already say what a key may be + if (!numericType) + return rest; + rest.type = "string"; + if (!values) + rest.pattern = (types.includes("number") ? number : integer).source; + return rest; +} +/** Every record of one conversion, so the carriers are found in a single pass rather than once per record. */ +const pendingRecords = new WeakMap(); +function rewriteKeyNames(ctx) { + // an extracted key is resolved by the object `extractToDef` left in its place, so the map is built once rather than searched per reference. `_zod.toJSONSchema` can hand the same object to two schemas, so the first entry carrying a body wins, as a search would have found it. + const bySchema = new Map(); + for (const entry of ctx.seen.values()) { + if (entry.def && !bySchema.has(entry.schema)) + bySchema.set(entry.schema, entry); + } + const rewrites = new Map(); + for (const record of pendingRecords.get(ctx) ?? []) { + const seen = ctx.seen.get(record); + const names = (seen?.def ?? seen?.schema)?.propertyNames; + if (!names || names === true || rewrites.has(names)) + continue; + const rewritten = stringifyKeyNames(bySchema, names, new Set()); + if (rewritten !== names) + rewrites.set(names, rewritten); + } + if (!rewrites.size) + return; + // the flatten has already copied each record's own properties onto every wrapper by reference, and an extracted body is another such copy, so every carrier holding a rewritten key is updated together + for (const entry of ctx.seen.values()) { + for (const carrier of [entry.schema, entry.def]) { + const rewritten = carrier && rewrites.get(carrier.propertyNames); + if (rewritten) + carrier.propertyNames = rewritten; + } + } +} +const recordProcessor = (schema, ctx, _json, params) => { + const json = _json; + const def = schema._zod.def; + json.type = "object"; + // For looseRecord with regex patterns, use patternProperties. This correctly represents "only validate keys matching the pattern" semantics and composes well with allOf (intersections) + const keyType = def.keyType; + const keyBag = keyType._zod.bag; + const patterns = keyBag?.patterns; + if (def.mode === "loose" && patterns && patterns.size > 0) { + // Use patternProperties for looseRecord with regex patterns + const valueSchema = to_json_schema_process(def.valueType, ctx, { + ...params, + path: [...params.path, "patternProperties", "*"], + }); + json.patternProperties = {}; + for (const pattern of patterns) { + assignProp(json.patternProperties, pattern.source, valueSchema); + } + } + else { + // Default behavior: use propertyNames + additionalProperties + if (ctx.target === "draft-07" || ctx.target === "draft-2020-12") { + json.propertyNames = to_json_schema_process(def.keyType, ctx, { + ...params, + path: [...params.path, "propertyNames"], + }); + let pending = pendingRecords.get(ctx); + if (!pending) { + pending = []; + pendingRecords.set(ctx, pending); + ctx.deferred.push(() => rewriteKeyNames(ctx)); + } + pending.push(schema); + } + json.additionalProperties = to_json_schema_process(def.valueType, ctx, { + ...params, + path: [...params.path, "additionalProperties"], + }); + } + // Add required for keys with discrete values (enum, literal, etc.) + const keyValues = keyType._zod.values; + // Every key shares one value schema, so an optional-in value makes the whole key set omittable on input. Output keeps them: the exhaustive branch assigns every key, even one whose value came back undefined. + const omittableOnInput = ctx.io === "input" && inputOptin(def.valueType) !== undefined; + if (keyValues && !def.partial && !omittableOnInput) { + const validKeyValues = [...keyValues].filter((v) => typeof v === "string" || typeof v === "number"); + if (validKeyValues.length > 0) { + json.required = validKeyValues.map(String); + } + } +}; +const nullableProcessor = (schema, ctx, json, params) => { + const def = schema._zod.def; + const inner = to_json_schema_process(def.innerType, ctx, params); + const seen = ctx.seen.get(schema); + if (ctx.target === "openapi-3.0") { + seen.ref = def.innerType; + json.nullable = true; + } + else { + json.anyOf = [inner, { type: "null" }]; + } +}; +const nonoptionalProcessor = (schema, ctx, _json, params) => { + const def = schema._zod.def; + to_json_schema_process(def.innerType, ctx, params); + const seen = ctx.seen.get(schema); + seen.ref = def.innerType; +}; +/** Round-trips a default value through JSON so the emitted schema is guaranteed to be valid JSON. + * A BigInt has no reliable encoding, so it goes through `unrepresentable` like any other + * unrepresentable value. Returns a sentinel when the caller must not write a default of its own. */ +const UNREPRESENTABLE_DEFAULT = Symbol(); +function serializeDefaultValue(value, schema, ctx, json, params) { + let unrepresentable = false; + const serialized = JSON.stringify(value, (_, val) => { + if (typeof val !== "bigint") + return val; + unrepresentable = true; + return null; + }); + if (!unrepresentable) + return JSON.parse(serialized); + handleUnrepresentable(schema, ctx, json, params, "BigInt defaults cannot be represented in JSON Schema"); + return UNREPRESENTABLE_DEFAULT; +} +const defaultProcessor = (schema, ctx, json, params) => { + const def = schema._zod.def; + to_json_schema_process(def.innerType, ctx, params); + const seen = ctx.seen.get(schema); + seen.ref = def.innerType; + const value = serializeDefaultValue(def.defaultValue, schema, ctx, json, params); + if (value !== UNREPRESENTABLE_DEFAULT) + json.default = value; +}; +const prefaultProcessor = (schema, ctx, json, params) => { + const def = schema._zod.def; + to_json_schema_process(def.innerType, ctx, params); + const seen = ctx.seen.get(schema); + seen.ref = def.innerType; + if (ctx.io !== "input") + return; + const value = serializeDefaultValue(def.defaultValue, schema, ctx, json, params); + if (value !== UNREPRESENTABLE_DEFAULT) + json._prefault = value; +}; +const catchProcessor = (schema, ctx, json, params) => { + const def = schema._zod.def; + to_json_schema_process(def.innerType, ctx, params); + const seen = ctx.seen.get(schema); + seen.ref = def.innerType; + let catchValue; + try { + catchValue = def.catchValue(undefined); + } + catch { + handleUnrepresentable(schema, ctx, json, params, "Dynamic catch values are not supported in JSON Schema"); + return; + } + json.default = catchValue; +}; +const pipeProcessor = (schema, ctx, _json, params) => { + const def = schema._zod.def; + const inIsTransform = def.in._zod.traits.has("$ZodTransform"); + const innerType = ctx.io === "input" ? (inIsTransform ? def.out : def.in) : def.out; + to_json_schema_process(innerType, ctx, params); + const seen = ctx.seen.get(schema); + seen.ref = innerType; +}; +const readonlyProcessor = (schema, ctx, json, params) => { + const def = schema._zod.def; + to_json_schema_process(def.innerType, ctx, params); + const seen = ctx.seen.get(schema); + seen.ref = def.innerType; + json.readOnly = true; +}; +const promiseProcessor = (schema, ctx, _json, params) => { + const def = schema._zod.def; + to_json_schema_process(def.innerType, ctx, params); + const seen = ctx.seen.get(schema); + seen.ref = def.innerType; +}; +const optionalProcessor = (schema, ctx, _json, params) => { + const def = schema._zod.def; + to_json_schema_process(def.innerType, ctx, params); + const seen = ctx.seen.get(schema); + seen.ref = def.innerType; +}; +const lazyProcessor = (schema, ctx, _json, params) => { + const innerType = schema._zod.innerType; + to_json_schema_process(innerType, ctx, params); + const seen = ctx.seen.get(schema); + seen.ref = innerType; +}; +// ==================== ALL PROCESSORS ==================== +const allProcessors = { + string: stringProcessor, + number: numberProcessor, + boolean: booleanProcessor, + bigint: bigintProcessor, + symbol: symbolProcessor, + null: nullProcessor, + undefined: undefinedProcessor, + void: voidProcessor, + never: neverProcessor, + any: anyProcessor, + unknown: unknownProcessor, + date: dateProcessor, + enum: enumProcessor, + literal: literalProcessor, + nan: nanProcessor, + template_literal: templateLiteralProcessor, + file: fileProcessor, + success: successProcessor, + custom: customProcessor, + function: functionProcessor, + transform: transformProcessor, + map: mapProcessor, + set: setProcessor, + array: arrayProcessor, + object: objectProcessor, + union: unionProcessor, + intersection: intersectionProcessor, + tuple: tupleProcessor, + record: recordProcessor, + nullable: nullableProcessor, + nonoptional: nonoptionalProcessor, + default: defaultProcessor, + prefault: prefaultProcessor, + catch: catchProcessor, + pipe: pipeProcessor, + readonly: readonlyProcessor, + promise: promiseProcessor, + optional: optionalProcessor, + lazy: lazyProcessor, +}; +function toJSONSchema(input, params) { + if ("_idmap" in input) { + // Registry case + const registry = input; + const ctx = initializeContext({ ...params, processors: allProcessors }); + const defs = {}; + // First pass: process all schemas to build the seen map + for (const entry of registry._idmap.entries()) { + const [_, schema] = entry; + to_json_schema_process(schema, ctx); + } + const schemas = {}; + const external = { + registry, + uri: params?.uri, + defs, + }; + // Update the context with external configuration + ctx.external = external; + // Second pass: emit each schema + for (const entry of registry._idmap.entries()) { + const [key, schema] = entry; + extractDefs(ctx, schema); + assignProp(schemas, key, finalize(ctx, schema)); + } + if (Object.keys(defs).length > 0) { + const defsSegment = ctx.target === "draft-2020-12" ? "$defs" : "definitions"; + schemas.__shared = { + [defsSegment]: defs, + }; + } + return { schemas }; + } + // Single schema case + const ctx = initializeContext({ ...params, processors: allProcessors }); + to_json_schema_process(input, ctx); + extractDefs(ctx, input); + return finalize(ctx, input); +} + + +const en_error = () => { + const Sizable = { + string: { unit: "characters", verb: "to have" }, + file: { unit: "bytes", verb: "to have" }, + array: { unit: "items", verb: "to have" }, + set: { unit: "items", verb: "to have" }, + map: { unit: "entries", verb: "to have" }, + }; + function getSizing(origin) { + return Sizable[origin] ?? null; + } + const FormatDictionary = { + 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", + credit_card: "credit card number", + jwt: "JWT", + template_literal: "input", + }; + // type names: missing keys = do not translate (use raw value via ?? fallback) + const TypeDictionary = { + // Compatibility: "nan" -> "NaN" for display + nan: "NaN", + // All other type names omitted - they fall back to raw values via ?? operator + }; + function getTypeName(type, input) { + if (type === "number" && typeof input === "number" && !Number.isFinite(input)) { + return String(input); + } + return TypeDictionary[type] ?? type; + } + return (issue) => { + switch (issue.code) { + case "invalid_type": { + const expected = getTypeName(issue.expected); + const receivedType = parsedType(issue.input); + const received = getTypeName(receivedType, issue.input); + return `Invalid input: expected ${expected}, received ${received}`; + } + case "invalid_value": + if (issue.values.length === 1) + return `Invalid input: expected ${stringifyPrimitive(issue.values[0])}`; + return `Invalid option: expected one of ${joinValues(issue.values, "|")}`; + case "too_big": { + const adj = issue.exact ? "exactly " : issue.inclusive ? "<=" : "<"; + const sizing = getSizing(issue.origin); + if (sizing) + return `Too big: expected ${issue.origin ?? "value"} to have ${adj}${issue.maximum.toString()} ${sizing.unit ?? "elements"}`; + return `Too big: expected ${issue.origin ?? "value"} to be ${adj}${issue.maximum.toString()}`; + } + case "too_small": { + const adj = issue.exact ? "exactly " : issue.inclusive ? ">=" : ">"; + const sizing = getSizing(issue.origin); + if (sizing) { + return `Too small: expected ${issue.origin} to have ${adj}${issue.minimum.toString()} ${sizing.unit}`; + } + return `Too small: expected ${issue.origin} to be ${adj}${issue.minimum.toString()}`; + } + case "invalid_format": { + const _issue = issue; + if (_issue.format === "starts_with") { + return `Invalid string: must start with "${_issue.prefix}"`; + } + if (_issue.format === "ends_with") + return `Invalid string: must end with "${_issue.suffix}"`; + if (_issue.format === "includes") + return `Invalid string: must include "${_issue.includes}"`; + if (_issue.format === "regex") + return `Invalid string: must match pattern ${_issue.pattern}`; + return `Invalid ${FormatDictionary[_issue.format] ?? issue.format}`; + } + case "not_multiple_of": + return `Invalid number: must be a multiple of ${issue.divisor}`; + case "unrecognized_keys": + return `Unrecognized key${issue.keys.length > 1 ? "s" : ""}: ${joinValues(issue.keys, ", ")}`; + case "invalid_key": + return `Invalid key in ${issue.origin}`; + case "invalid_union": + if (issue.options && Array.isArray(issue.options) && issue.options.length > 0) { + const opts = issue.options.map((o) => `'${o}'`).join(" | "); + return `Invalid discriminator value. Expected ${opts}`; + } + if (issue.inclusive === false) { + return "Invalid input: more than one option matched"; + } + return "Invalid input"; + case "invalid_element": + return `Invalid value in ${issue.origin}`; + default: + return `Invalid input`; + } + }; +}; +/* export default */ function en() { + return { + localeError: en_error(), + }; +} + + + + +/* Prototypes that already carry the lazy helper methods. Seeded with the + * intrinsics so that `init` on a foreign object — it accepts any object — + * can never install an accessor onto a prototype we do not own. */ +const _installedErrorProtos = /* @__PURE__ */ new WeakSet([Object.prototype, Error.prototype]); +/* Helper methods live as non-enumerable lazy getters on the shared + * prototype instead of own properties on every instance. On first + * access the getter allocates the per-instance closure and caches it + * as a non-enumerable own property, so detached usage still works and + * the allocation only happens for methods actually touched. */ +function _lazyMethod(proto, key, make) { + Object.defineProperty(proto, key, { + configurable: true, + enumerable: false, + get() { + const value = make(this); + Object.defineProperty(this, key, { value, configurable: true, writable: true }); + return value; + }, + set(value) { + Object.defineProperty(this, key, { value, configurable: true, writable: true }); + }, + }); +} +const classic_errors_initializer = (inst, issues) => { + $ZodError.init(inst, issues); + inst.name = "ZodError"; + const proto = Object.getPrototypeOf(inst); + if (_installedErrorProtos.has(proto)) + return; + _installedErrorProtos.add(proto); + _lazyMethod(proto, "format", (self) => (mapper) => formatError(self, mapper)); + _lazyMethod(proto, "flatten", (self) => (mapper) => flattenError(self, mapper)); + _lazyMethod(proto, "addIssue", (self) => (issue) => { + self.issues.push(issue); + self.message = JSON.stringify(self.issues, jsonStringifyReplacer, 2); + }); + _lazyMethod(proto, "addIssues", (self) => (issues) => { + self.issues.push(...issues); + self.message = JSON.stringify(self.issues, jsonStringifyReplacer, 2); + }); + Object.defineProperty(proto, "isEmpty", { + configurable: true, + enumerable: false, + get() { + return this.issues.length === 0; + }, + }); +}; +const ZodError = /*@__PURE__*/ (/* unused pure expression or super */ null && (core.$constructor("ZodError", classic_errors_initializer))); +const ZodRealError = /*@__PURE__*/ $constructor("ZodError", classic_errors_initializer, undefined, { + Parent: Error, +}); +// /** @deprecated Use `z.core.$ZodErrorMapCtx` instead. */ +// export type ErrorMapCtx = core.$ZodErrorMapCtx; + + + +const classic_parse_parse = /* @__PURE__ */ parse_parse(ZodRealError); +const classic_parse_parseAsync = /* @__PURE__ */ parse_parseAsync(ZodRealError); +const parse_safeParse = /* @__PURE__ */ _safeParse(ZodRealError); +const parse_safeParseAsync = /* @__PURE__ */ _safeParseAsync(ZodRealError); + +// Codec functions +const classic_parse_encode = /* @__PURE__ */ parse_encode(ZodRealError); +const classic_parse_decode = /* @__PURE__ */ parse_decode(ZodRealError); +const classic_parse_encodeAsync = /* @__PURE__ */ parse_encodeAsync(ZodRealError); +const classic_parse_decodeAsync = /* @__PURE__ */ parse_decodeAsync(ZodRealError); +const parse_safeEncode = /* @__PURE__ */ _safeEncode(ZodRealError); +const parse_safeDecode = /* @__PURE__ */ _safeDecode(ZodRealError); +const parse_safeEncodeAsync = /* @__PURE__ */ _safeEncodeAsync(ZodRealError); +const parse_safeDecodeAsync = /* @__PURE__ */ _safeDecodeAsync(ZodRealError); + + + + + + + + +// Register English as the default locale on first ZodType construction. Hooked into the `ZodType` `$constructor` (rather than a top-level `config(en())` in `external.ts`) so bundlers honoring `sideEffects: false` can't tree-shake it out — see #5953, #5725. An explicit `z.config(z.locales.xx())` call wins regardless of order, since this only sets the default when none is present. +function _ensureDefaultLocale() { + if (!globalConfig.localeError) + core_config(en()); +} +// the default memoizer is read by the core container init, which runs before `ZodType.init`, so each container calls this first +function _ensureDefaultMemoizer() { + if (!globalConfig.memoizer) + core_config({ memoizer: memoizer() }); +} +const ZodType = /*@__PURE__*/ $constructor("ZodType", (inst, def) => { + _ensureDefaultLocale(); + $ZodType.init(inst, def); + inst.def = def; + inst.type = def.type; + return inst; +}, { + check(...chks) { + const def = this.def; + return this.clone(mergeDefs(def, { + checks: [ + ...(def.checks ?? []), + ...chks.map((ch) => typeof ch === "function" ? { _zod: { check: ch, def: { check: "custom" }, onattach: [] } } : ch), + ], + }), { parent: true }); + }, + with(...chks) { + return this.check(...chks); + }, + clone(def, params) { + return clone(this, def, params); + }, + brand() { + return this; + }, + register(reg, meta) { + reg.add(this, meta); + return this; + }, + refine(check, params) { + return this.check(refine(check, params)); + }, + superRefine(refinement, params) { + return this.check(superRefine(refinement, params)); + }, + overwrite(fn) { + return this.check(_overwrite(fn)); + }, + optional() { + return schemas_optional(this); + }, + exactOptional() { + return exactOptional(this); + }, + nullable() { + return nullable(this); + }, + nullish() { + return schemas_optional(nullable(this)); + }, + nonoptional(params) { + return nonoptional(this, params); + }, + array() { + return schemas_array(this); + }, + or(arg) { + return schemas_union([this, arg]); + }, + and(arg) { + return intersection(this, arg); + }, + transform(tx) { + return pipe(this, transform(tx)); + }, + default(d) { + return schemas_default(this, d); + }, + prefault(d) { + return prefault(this, d); + }, + catch(params) { + return schemas_catch(this, params); + }, + pipe(target) { + return pipe(this, target); + }, + readonly() { + return readonly(this); + }, + describe(description) { + const cl = this.clone(); + globalRegistry.add(cl, { description }); + return cl; + }, + meta(...args) { + // overloaded: meta() returns the registered metadata, meta(data) returns a clone with `data` registered. The mapped type picks up the second overload, so we accept variadic any-args and return `any` to satisfy both at runtime. + if (args.length === 0) + return globalRegistry.get(this); + const cl = this.clone(); + globalRegistry.add(cl, args[0]); + return cl; + }, + isOptional() { + return this.safeParse(undefined).success; + }, + isNullable() { + return this.safeParse(null).success; + }, + apply(fn, ...args) { + return args.length === 0 ? fn(this) : fn(this, ...args); + }, + // Overrides core's `~standard` to add `jsonSchema`. Must stay a prototype entry: redefining it per instance demotes instances to dictionary mode. + get "~standard"() { + return hide(this, "~standard", { + ...standardProps(this), + jsonSchema: { + input: createStandardJSONSchemaMethod(this, "input"), + output: createStandardJSONSchemaMethod(this, "output"), + }, + }); + }, + set "~standard"(value) { + util_own(this, "~standard", value); + }, + parse: function _parse(data, params) { + return classic_parse_parse(this, data, params, { callee: _parse }); + }, + parseAsync: async function _parseAsync(data, params) { + return await classic_parse_parseAsync(this, data, params, { callee: _parseAsync }); + }, + safeParse(data, params) { + return parse_safeParse(this, data, params); + }, + async safeParseAsync(data, params) { + return parse_safeParseAsync(this, data, params); + }, + // `spa` is an alias: same function object as `safeParseAsync`, as before. + get spa() { + return this?.safeParseAsync; + }, + set spa(value) { + util_own(this, "spa", value); + }, + encode: function _encode(data, params) { + return classic_parse_encode(this, data, params, { callee: _encode }); + }, + decode: function _decode(data, params) { + return classic_parse_decode(this, data, params, { callee: _decode }); + }, + encodeAsync: async function _encodeAsync(data, params) { + return await classic_parse_encodeAsync(this, data, params, { callee: _encodeAsync }); + }, + decodeAsync: async function _decodeAsync(data, params) { + return await classic_parse_decodeAsync(this, data, params, { callee: _decodeAsync }); + }, + safeEncode(data, params) { + return parse_safeEncode(this, data, params); + }, + safeDecode(data, params) { + return parse_safeDecode(this, data, params); + }, + async safeEncodeAsync(data, params) { + return parse_safeEncodeAsync(this, data, params); + }, + async safeDecodeAsync(data, params) { + return parse_safeDecodeAsync(this, data, params); + }, + toJSONSchema(params) { + return createToJSONSchemaMethod(this, {})(params); + }, + // Reads through to the registry on every access, so it must not cache. + get description() { + return globalRegistry.get(this)?.description; + }, + // No setter: `schema._def = x` throws, as it did when `_def` was a non-writable own property. + get _def() { + return this._zod.def; + }, +}); +/** @internal */ +const _ZodString = /*@__PURE__*/ $constructor("_ZodString", (inst, def) => { + $ZodString.init(inst, def); + ZodType.init(inst, def); + inst._zod.processJSONSchema = (ctx, json, params) => stringProcessor(inst, ctx, json, params); + const bag = inst._zod.bag; + inst.format = bag.format ?? null; + inst.minLength = bag.minimum ?? null; + inst.maxLength = bag.maximum ?? null; +}, { + regex(...args) { + return this.check(_regex(...args)); + }, + includes(...args) { + return this.check(_includes(...args)); + }, + startsWith(...args) { + return this.check(_startsWith(...args)); + }, + endsWith(...args) { + return this.check(_endsWith(...args)); + }, + min(...args) { + return this.check(_minLength(...args)); + }, + max(...args) { + return this.check(_maxLength(...args)); + }, + length(...args) { + return this.check(_length(...args)); + }, + nonempty(...args) { + return this.check(_minLength(1, ...args)); + }, + lowercase(params) { + return this.check(_lowercase(params)); + }, + uppercase(params) { + return this.check(_uppercase(params)); + }, + trim() { + return this.check(_trim()); + }, + normalize(...args) { + return this.check(_normalize(...args)); + }, + toLowerCase() { + return this.check(_toLowerCase()); + }, + toUpperCase() { + return this.check(_toUpperCase()); + }, + slugify() { + return this.check(_slugify()); + }, +}); +const ZodString = /*@__PURE__*/ $constructor("ZodString", (inst, def) => { + $ZodString.init(inst, def); + _ZodString.init(inst, def); +}, { + email(params) { + return this.check(_email(ZodEmail, params)); + }, + url(params) { + return this.check(_url(ZodURL, params)); + }, + jwt(params) { + return this.check(_jwt(ZodJWT, params)); + }, + emoji(params) { + return this.check(api_emoji(ZodEmoji, params)); + }, + guid(params) { + return this.check(_guid(ZodGUID, params)); + }, + uuid(params) { + return this.check(_uuid(ZodUUID, params)); + }, + uuidv4(params) { + return this.check(_uuidv4(ZodUUID, params)); + }, + uuidv6(params) { + return this.check(_uuidv6(ZodUUID, params)); + }, + uuidv7(params) { + return this.check(_uuidv7(ZodUUID, params)); + }, + nanoid(params) { + return this.check(_nanoid(ZodNanoID, params)); + }, + cuid(params) { + return this.check(_cuid(ZodCUID, params)); + }, + cuid2(params) { + return this.check(_cuid2(ZodCUID2, params)); + }, + ulid(params) { + return this.check(_ulid(ZodULID, params)); + }, + base64(params) { + return this.check(_base64(ZodBase64, params)); + }, + base64url(params) { + return this.check(_base64url(ZodBase64URL, params)); + }, + xid(params) { + return this.check(_xid(ZodXID, params)); + }, + ksuid(params) { + return this.check(_ksuid(ZodKSUID, params)); + }, + ipv4(params) { + return this.check(_ipv4(ZodIPv4, params)); + }, + ipv6(params) { + return this.check(_ipv6(ZodIPv6, params)); + }, + cidrv4(params) { + return this.check(_cidrv4(ZodCIDRv4, params)); + }, + cidrv6(params) { + return this.check(_cidrv6(ZodCIDRv6, params)); + }, + e164(params) { + return this.check(_e164(ZodE164, params)); + }, + datetime(params) { + return this.check(_isoDateTime(ZodISODateTime, params)); + }, + date(params) { + return this.check(_isoDate(ZodISODate, params)); + }, + time(params) { + return this.check(_isoTime(schemas_ZodISOTime, params)); + }, + duration(params) { + return this.check(_isoDuration(schemas_ZodISODuration, params)); + }, +}); +function schemas_string(params) { + return _string(ZodString, params); +} +const ZodStringFormat = /*@__PURE__*/ $constructor("ZodStringFormat", (inst, def) => { + $ZodStringFormat.init(inst, def); + _ZodString.init(inst, def); +}); +const ZodISODateTime = /*@__PURE__*/ $constructor("ZodISODateTime", (inst, def) => { + $ZodISODateTime.init(inst, def); + ZodStringFormat.init(inst, def); +}); +const ZodISODate = /*@__PURE__*/ $constructor("ZodISODate", (inst, def) => { + $ZodISODate.init(inst, def); + ZodStringFormat.init(inst, def); +}); +const schemas_ZodISOTime = /*@__PURE__*/ $constructor("ZodISOTime", (inst, def) => { + $ZodISOTime.init(inst, def); + ZodStringFormat.init(inst, def); +}); +const schemas_ZodISODuration = /*@__PURE__*/ $constructor("ZodISODuration", (inst, def) => { + $ZodISODuration.init(inst, def); + ZodStringFormat.init(inst, def); +}); +const ZodEmail = /*@__PURE__*/ $constructor("ZodEmail", (inst, def) => { + // ZodStringFormat.init(inst, def); + $ZodEmail.init(inst, def); + ZodStringFormat.init(inst, def); +}); +function schemas_email(params) { + return _email(ZodEmail, params); +} +const ZodGUID = /*@__PURE__*/ $constructor("ZodGUID", (inst, def) => { + // ZodStringFormat.init(inst, def); + $ZodGUID.init(inst, def); + ZodStringFormat.init(inst, def); +}); +function schemas_guid(params) { + return core._guid(ZodGUID, params); +} +const ZodUUID = /*@__PURE__*/ $constructor("ZodUUID", (inst, def) => { + // ZodStringFormat.init(inst, def); + $ZodUUID.init(inst, def); + ZodStringFormat.init(inst, def); +}); +function schemas_uuid(params) { + return core._uuid(ZodUUID, params); +} +function uuidv4(params) { + return core._uuidv4(ZodUUID, params); +} +// ZodUUIDv6 +function uuidv6(params) { + return core._uuidv6(ZodUUID, params); +} +// ZodUUIDv7 +function uuidv7(params) { + return core._uuidv7(ZodUUID, params); +} +const ZodURL = /*@__PURE__*/ $constructor("ZodURL", (inst, def) => { + // ZodStringFormat.init(inst, def); + $ZodURL.init(inst, def); + ZodStringFormat.init(inst, def); +}); +function schemas_url(params) { + return _url(ZodURL, params); +} +function httpUrl(params) { + return core._url(ZodURL, { + protocol: core.regexes.httpProtocol, + hostname: core.regexes.domain, + ...util.normalizeParams(params), + }); +} +const ZodEmoji = /*@__PURE__*/ $constructor("ZodEmoji", (inst, def) => { + // ZodStringFormat.init(inst, def); + $ZodEmoji.init(inst, def); + ZodStringFormat.init(inst, def); +}); +function schemas_emoji(params) { + return core._emoji(ZodEmoji, params); +} +const ZodNanoID = /*@__PURE__*/ $constructor("ZodNanoID", (inst, def) => { + // ZodStringFormat.init(inst, def); + $ZodNanoID.init(inst, def); + ZodStringFormat.init(inst, def); +}); +function schemas_nanoid(params) { + return core._nanoid(ZodNanoID, params); +} +/** + * @deprecated CUID v1 is deprecated by its authors due to information leakage + * (timestamps embedded in the id). Use {@link ZodCUID2} instead. + * See https://github.com/paralleldrive/cuid. + */ +const ZodCUID = /*@__PURE__*/ $constructor("ZodCUID", (inst, def) => { + // ZodStringFormat.init(inst, def); + $ZodCUID.init(inst, def); + ZodStringFormat.init(inst, def); +}); +/** + * Validates a CUID v1 string. + * + * @deprecated CUID v1 is deprecated by its authors due to information leakage + * (timestamps embedded in the id). Use {@link cuid2 | `z.cuid2()`} instead. + * See https://github.com/paralleldrive/cuid. + */ +function schemas_cuid(params) { + return core._cuid(ZodCUID, params); +} +const ZodCUID2 = /*@__PURE__*/ $constructor("ZodCUID2", (inst, def) => { + // ZodStringFormat.init(inst, def); + $ZodCUID2.init(inst, def); + ZodStringFormat.init(inst, def); +}); +function schemas_cuid2(params) { + return core._cuid2(ZodCUID2, params); +} +const ZodULID = /*@__PURE__*/ $constructor("ZodULID", (inst, def) => { + // ZodStringFormat.init(inst, def); + $ZodULID.init(inst, def); + ZodStringFormat.init(inst, def); +}); +function schemas_ulid(params) { + return core._ulid(ZodULID, params); +} +const ZodXID = /*@__PURE__*/ $constructor("ZodXID", (inst, def) => { + // ZodStringFormat.init(inst, def); + $ZodXID.init(inst, def); + ZodStringFormat.init(inst, def); +}); +function schemas_xid(params) { + return core._xid(ZodXID, params); +} +const ZodKSUID = /*@__PURE__*/ $constructor("ZodKSUID", (inst, def) => { + // ZodStringFormat.init(inst, def); + $ZodKSUID.init(inst, def); + ZodStringFormat.init(inst, def); +}); +function schemas_ksuid(params) { + return core._ksuid(ZodKSUID, params); +} +const ZodIPv4 = /*@__PURE__*/ $constructor("ZodIPv4", (inst, def) => { + // ZodStringFormat.init(inst, def); + $ZodIPv4.init(inst, def); + ZodStringFormat.init(inst, def); +}); +function schemas_ipv4(params) { + return core._ipv4(ZodIPv4, params); +} +const ZodMAC = /*@__PURE__*/ (/* unused pure expression or super */ null && (core.$constructor("ZodMAC", (inst, def) => { + // ZodStringFormat.init(inst, def); + core.$ZodMAC.init(inst, def); + ZodStringFormat.init(inst, def); +}))); +function schemas_mac(params) { + return core._mac(ZodMAC, params); +} +const ZodIPv6 = /*@__PURE__*/ $constructor("ZodIPv6", (inst, def) => { + // ZodStringFormat.init(inst, def); + $ZodIPv6.init(inst, def); + ZodStringFormat.init(inst, def); +}); +function schemas_ipv6(params) { + return core._ipv6(ZodIPv6, params); +} +const ZodCIDRv4 = /*@__PURE__*/ $constructor("ZodCIDRv4", (inst, def) => { + $ZodCIDRv4.init(inst, def); + ZodStringFormat.init(inst, def); +}); +function schemas_cidrv4(params) { + return core._cidrv4(ZodCIDRv4, params); +} +const ZodCIDRv6 = /*@__PURE__*/ $constructor("ZodCIDRv6", (inst, def) => { + $ZodCIDRv6.init(inst, def); + ZodStringFormat.init(inst, def); +}); +function schemas_cidrv6(params) { + return core._cidrv6(ZodCIDRv6, params); +} +const ZodBase64 = /*@__PURE__*/ $constructor("ZodBase64", (inst, def) => { + // ZodStringFormat.init(inst, def); + $ZodBase64.init(inst, def); + ZodStringFormat.init(inst, def); +}); +function schemas_base64(params) { + return core._base64(ZodBase64, params); +} +const ZodBase64URL = /*@__PURE__*/ $constructor("ZodBase64URL", (inst, def) => { + // ZodStringFormat.init(inst, def); + $ZodBase64URL.init(inst, def); + ZodStringFormat.init(inst, def); +}); +function schemas_base64url(params) { + return core._base64url(ZodBase64URL, params); +} +const ZodE164 = /*@__PURE__*/ $constructor("ZodE164", (inst, def) => { + // ZodStringFormat.init(inst, def); + $ZodE164.init(inst, def); + ZodStringFormat.init(inst, def); +}); +function schemas_e164(params) { + return core._e164(ZodE164, params); +} +const ZodCreditCard = /*@__PURE__*/ (/* unused pure expression or super */ null && (core.$constructor("ZodCreditCard", (inst, def) => { + core.$ZodCreditCard.init(inst, def); + ZodStringFormat.init(inst, def); +}))); +function schemas_creditCard(params) { + return core._creditCard(ZodCreditCard, params); +} +const ZodJWT = /*@__PURE__*/ $constructor("ZodJWT", (inst, def) => { + // ZodStringFormat.init(inst, def); + $ZodJWT.init(inst, def); + ZodStringFormat.init(inst, def); +}); +function jwt(params) { + return core._jwt(ZodJWT, params); +} +const ZodCustomStringFormat = /*@__PURE__*/ (/* unused pure expression or super */ null && (core.$constructor("ZodCustomStringFormat", (inst, def) => { + // ZodStringFormat.init(inst, def); + core.$ZodCustomStringFormat.init(inst, def); + ZodStringFormat.init(inst, def); +}))); +function stringFormat(format, fnOrRegex, _params = {}) { + return core._stringFormat(ZodCustomStringFormat, format, fnOrRegex, _params); +} +function schemas_hostname(_params) { + return core._stringFormat(ZodCustomStringFormat, "hostname", core.regexes.hostname, _params); +} +function schemas_hex(_params) { + return core._stringFormat(ZodCustomStringFormat, "hex", core.regexes.hex, _params); +} +function schemas_hash(alg, params) { + const enc = params?.enc ?? "hex"; + const format = `${alg}_${enc}`; + const regex = core.regexes[format]; + if (!regex) + throw new Error(`Unrecognized hash format: ${format}`); + return core._stringFormat(ZodCustomStringFormat, format, regex, params); +} +const ZodNumber = /*@__PURE__*/ $constructor("ZodNumber", (inst, def) => { + $ZodNumber.init(inst, def); + ZodType.init(inst, def); + inst._zod.processJSONSchema = (ctx, json, params) => numberProcessor(inst, ctx, json, params); + const bag = inst._zod.bag; + inst.minValue = + Math.max(bag.minimum ?? Number.NEGATIVE_INFINITY, bag.exclusiveMinimum ?? Number.NEGATIVE_INFINITY) ?? null; + inst.maxValue = + Math.min(bag.maximum ?? Number.POSITIVE_INFINITY, bag.exclusiveMaximum ?? Number.POSITIVE_INFINITY) ?? null; + inst.isInt = (bag.format ?? "").includes("int") || Number.isSafeInteger(bag.multipleOf ?? 0.5); + inst.isFinite = true; + inst.format = bag.format ?? null; +}, { + gt(value, params) { + return this.check(_gt(value, params)); + }, + gte(value, params) { + return this.check(_gte(value, params)); + }, + min(value, params) { + return this.check(_gte(value, params)); + }, + lt(value, params) { + return this.check(_lt(value, params)); + }, + lte(value, params) { + return this.check(_lte(value, params)); + }, + max(value, params) { + return this.check(_lte(value, params)); + }, + int(params) { + return this.check(schemas_int(params)); + }, + safe(params) { + return this.check(schemas_int(params)); + }, + positive(params) { + return this.check(_gt(0, params)); + }, + nonnegative(params) { + return this.check(_gte(0, params)); + }, + negative(params) { + return this.check(_lt(0, params)); + }, + nonpositive(params) { + return this.check(_lte(0, params)); + }, + multipleOf(value, params) { + return this.check(_multipleOf(value, params)); + }, + step(value, params) { + return this.check(_multipleOf(value, params)); + }, + finite() { + return this; + }, +}); +function schemas_number(params) { + return _number(ZodNumber, params); +} +const ZodNumberFormat = /*@__PURE__*/ $constructor("ZodNumberFormat", (inst, def) => { + $ZodNumberFormat.init(inst, def); + ZodNumber.init(inst, def); +}); +function schemas_int(params) { + return _int(ZodNumberFormat, params); +} +function float32(params) { + return core._float32(ZodNumberFormat, params); +} +function float64(params) { + return core._float64(ZodNumberFormat, params); +} +function int32(params) { + return core._int32(ZodNumberFormat, params); +} +function uint32(params) { + return core._uint32(ZodNumberFormat, params); +} +const ZodBoolean = /*@__PURE__*/ $constructor("ZodBoolean", (inst, def) => { + $ZodBoolean.init(inst, def); + ZodType.init(inst, def); + inst._zod.processJSONSchema = (ctx, json, params) => booleanProcessor(inst, ctx, json, params); +}); +function schemas_boolean(params) { + return _boolean(ZodBoolean, params); +} +const ZodBigInt = /*@__PURE__*/ (/* unused pure expression or super */ null && (core.$constructor("ZodBigInt", (inst, def) => { + core.$ZodBigInt.init(inst, def); + ZodType.init(inst, def); + inst._zod.processJSONSchema = (ctx, json, params) => processors.bigintProcessor(inst, ctx, json, params); + const bag = inst._zod.bag; + inst.minValue = bag.minimum ?? null; + inst.maxValue = bag.maximum ?? null; + inst.format = bag.format ?? null; +}, { + gte(value, params) { + return this.check(checks.gte(value, params)); + }, + min(value, params) { + return this.check(checks.gte(value, params)); + }, + gt(value, params) { + return this.check(checks.gt(value, params)); + }, + lt(value, params) { + return this.check(checks.lt(value, params)); + }, + lte(value, params) { + return this.check(checks.lte(value, params)); + }, + max(value, params) { + return this.check(checks.lte(value, params)); + }, + positive(params) { + return this.check(checks.gt(BigInt(0), params)); + }, + negative(params) { + return this.check(checks.lt(BigInt(0), params)); + }, + nonpositive(params) { + return this.check(checks.lte(BigInt(0), params)); + }, + nonnegative(params) { + return this.check(checks.gte(BigInt(0), params)); + }, + multipleOf(value, params) { + return this.check(checks.multipleOf(value, params)); + }, +}))); +function schemas_bigint(params) { + return core._bigint(ZodBigInt, params); +} +const ZodBigIntFormat = /*@__PURE__*/ (/* unused pure expression or super */ null && (core.$constructor("ZodBigIntFormat", (inst, def) => { + core.$ZodBigIntFormat.init(inst, def); + ZodBigInt.init(inst, def); +}))); +function int64(params) { + return core._int64(ZodBigIntFormat, params); +} +function uint64(params) { + return core._uint64(ZodBigIntFormat, params); +} +const ZodSymbol = /*@__PURE__*/ (/* unused pure expression or super */ null && (core.$constructor("ZodSymbol", (inst, def) => { + core.$ZodSymbol.init(inst, def); + ZodType.init(inst, def); + inst._zod.processJSONSchema = (ctx, json, params) => processors.symbolProcessor(inst, ctx, json, params); +}))); +function symbol(params) { + return core._symbol(ZodSymbol, params); +} +const ZodUndefined = /*@__PURE__*/ (/* unused pure expression or super */ null && (core.$constructor("ZodUndefined", (inst, def) => { + core.$ZodUndefined.init(inst, def); + ZodType.init(inst, def); + inst._zod.processJSONSchema = (ctx, json, params) => processors.undefinedProcessor(inst, ctx, json, params); +}))); +function schemas_undefined(params) { + return core._undefined(ZodUndefined, params); +} + +const ZodNull = /*@__PURE__*/ $constructor("ZodNull", (inst, def) => { + $ZodNull.init(inst, def); + ZodType.init(inst, def); + inst._zod.processJSONSchema = (ctx, json, params) => nullProcessor(inst, ctx, json, params); +}); +function schemas_null(params) { + return api_null(ZodNull, params); +} + +const ZodAny = /*@__PURE__*/ $constructor("ZodAny", (inst, def) => { + $ZodAny.init(inst, def); + ZodType.init(inst, def); + inst._zod.processJSONSchema = (ctx, json, params) => anyProcessor(inst, ctx, json, params); +}); +function any() { + return _any(ZodAny); +} +const ZodUnknown = /*@__PURE__*/ $constructor("ZodUnknown", (inst, def) => { + $ZodUnknown.init(inst, def); + ZodType.init(inst, def); + inst._zod.processJSONSchema = (ctx, json, params) => unknownProcessor(inst, ctx, json, params); +}); +function unknown() { + return _unknown(ZodUnknown); +} +const ZodNever = /*@__PURE__*/ $constructor("ZodNever", (inst, def) => { + $ZodNever.init(inst, def); + ZodType.init(inst, def); + inst._zod.processJSONSchema = (ctx, json, params) => neverProcessor(inst, ctx, json, params); +}); +function never(params) { + return _never(ZodNever, params); +} +const ZodVoid = /*@__PURE__*/ (/* unused pure expression or super */ null && (core.$constructor("ZodVoid", (inst, def) => { + core.$ZodVoid.init(inst, def); + ZodType.init(inst, def); + inst._zod.processJSONSchema = (ctx, json, params) => processors.voidProcessor(inst, ctx, json, params); +}))); +function schemas_void(params) { + return core._void(ZodVoid, params); +} + +const ZodDate = /*@__PURE__*/ (/* unused pure expression or super */ null && (core.$constructor("ZodDate", (inst, def) => { + core.$ZodDate.init(inst, def); + ZodType.init(inst, def); + inst._zod.processJSONSchema = (ctx, json, params) => processors.dateProcessor(inst, ctx, json, params); + inst.min = (value, params) => inst.check(checks.gte(value, params)); + inst.max = (value, params) => inst.check(checks.lte(value, params)); + const c = inst._zod.bag; + inst.minDate = c.minimum ? new Date(c.minimum) : null; + inst.maxDate = c.maximum ? new Date(c.maximum) : null; +}))); +function schemas_date(params) { + return core._date(ZodDate, params); +} +const ZodArray = /*@__PURE__*/ $constructor("ZodArray", (inst, def) => { + _ensureDefaultMemoizer(); + $ZodArray.init(inst, def); + ZodType.init(inst, def); + inst._zod.processJSONSchema = (ctx, json, params) => arrayProcessor(inst, ctx, json, params); + inst.element = def.element; +}, { + min(n, params) { + return this.check(_minLength(n, params)); + }, + nonempty(params) { + return this.check(_minLength(1, params)); + }, + max(n, params) { + return this.check(_maxLength(n, params)); + }, + length(n, params) { + return this.check(_length(n, params)); + }, + unwrap() { + return this.element; + }, +}); +function schemas_array(element, params) { + return _array(ZodArray, element, params); +} +// .keyof +function keyof(schema) { + const shape = schema._zod.def.shape; + return schemas_enum(Object.keys(shape)); +} +const ZodObject = /*@__PURE__*/ $constructor("ZodObject", (inst, def) => { + _ensureDefaultMemoizer(); + $ZodObjectJIT.init(inst, def); + ZodType.init(inst, def); + inst._zod.processJSONSchema = (ctx, json, params) => objectProcessor(inst, ctx, json, params); + installLazyProp(inst, "shape", (self) => self._zod.def.shape, false); +}, { + keyof() { + return schemas_enum(Object.keys(this._zod.def.shape)); + }, + catchall(catchall) { + return this.clone({ ...this._zod.def, catchall: catchall }); + }, + passthrough() { + return this.clone({ ...this._zod.def, catchall: unknown() }); + }, + loose() { + return this.clone({ ...this._zod.def, catchall: unknown() }); + }, + strict() { + return this.clone({ ...this._zod.def, catchall: never() }); + }, + strip() { + return this.clone({ ...this._zod.def, catchall: undefined }); + }, + extend(incoming) { + return extend(this, incoming); + }, + safeExtend(incoming) { + return safeExtend(this, incoming); + }, + merge(other) { + return merge(this, other); + }, + pick(mask) { + return pick(this, mask); + }, + omit(mask) { + return omit(this, mask); + }, + partial(...args) { + return partial(ZodOptional, this, args[0]); + }, + exactPartial(...args) { + return partial(ZodExactOptional, this, args[0], "exactPartial"); + }, + required(...args) { + return util_required(ZodNonOptional, this, args[0]); + }, +}); +function schemas_object(shape, params) { + const def = { + type: "object", + shape: shape ?? {}, + ...normalizeParams(params), + }; + return new ZodObject(def); +} +// strictObject +function strictObject(shape, params) { + return new ZodObject({ + type: "object", + shape, + catchall: never(), + ...util.normalizeParams(params), + }); +} +// looseObject +function looseObject(shape, params) { + return new ZodObject({ + type: "object", + shape, + catchall: unknown(), + ...normalizeParams(params), + }); +} +const ZodUnion = /*@__PURE__*/ $constructor("ZodUnion", (inst, def) => { + $ZodUnion.init(inst, def); + ZodType.init(inst, def); + inst._zod.processJSONSchema = (ctx, json, params) => unionProcessor(inst, ctx, json, params); + inst.options = def.options; +}); +function schemas_union(options, params) { + return new ZodUnion({ + type: "union", + options: options, + ...normalizeParams(params), + }); +} +const ZodXor = /*@__PURE__*/ (/* unused pure expression or super */ null && (core.$constructor("ZodXor", (inst, def) => { + ZodUnion.init(inst, def); + core.$ZodXor.init(inst, def); + inst._zod.processJSONSchema = (ctx, json, params) => processors.unionProcessor(inst, ctx, json, params); + inst.options = def.options; +}))); +/** Creates an exclusive union (XOR) where exactly one option must match. + * Unlike regular unions that succeed when any option matches, xor fails if + * zero or more than one option matches the input. */ +function xor(options, params) { + return new ZodXor({ + type: "union", + options: options, + inclusive: false, + ...util.normalizeParams(params), + }); +} +const ZodDiscriminatedUnion = /*@__PURE__*/ $constructor("ZodDiscriminatedUnion", (inst, def) => { + ZodUnion.init(inst, def); + $ZodDiscriminatedUnion.init(inst, def); +}); +function discriminatedUnion(discriminator, options, params) { + // const [options, params] = args; + return new ZodDiscriminatedUnion({ + type: "union", + options: options, + discriminator, + ...normalizeParams(params), + }); +} +const ZodIntersection = /*@__PURE__*/ $constructor("ZodIntersection", (inst, def) => { + $ZodIntersection.init(inst, def); + ZodType.init(inst, def); + inst._zod.processJSONSchema = (ctx, json, params) => intersectionProcessor(inst, ctx, json, params); +}); +function intersection(left, right) { + return new ZodIntersection({ + type: "intersection", + left: left, + right: right, + }); +} +const ZodTuple = /*@__PURE__*/ (/* unused pure expression or super */ null && (core.$constructor("ZodTuple", (inst, def) => { + _ensureDefaultMemoizer(); + core.$ZodTuple.init(inst, def); + ZodType.init(inst, def); + inst._zod.processJSONSchema = (ctx, json, params) => processors.tupleProcessor(inst, ctx, json, params); +}, { + rest(rest) { + return this.clone({ + ...this._zod.def, + rest: rest, + }); + }, + partial() { + const def = this._zod.def; + // a refinement was authored against the full arity; partialing would run it on a shorter array + if (def.checks?.length) + throw new Error(".partial() cannot be used on tuple schemas containing refinements"); + return this.clone({ + ...def, + items: def.items.map((item) => new ZodOptional({ type: "optional", innerType: item })), + }); + }, +}))); +function tuple(items, _paramsOrRest, _params) { + const hasRest = _paramsOrRest instanceof core.$ZodType; + const params = hasRest ? _params : _paramsOrRest; + const rest = hasRest ? _paramsOrRest : null; + return new ZodTuple({ + type: "tuple", + items: items, + rest, + ...util.normalizeParams(params), + }); +} +const ZodRecord = /*@__PURE__*/ $constructor("ZodRecord", (inst, def) => { + _ensureDefaultMemoizer(); + $ZodRecord.init(inst, def); + ZodType.init(inst, def); + inst._zod.processJSONSchema = (ctx, json, params) => recordProcessor(inst, ctx, json, params); + inst.keyType = def.keyType; + inst.valueType = def.valueType; +}); +function schemas_record(keyType, valueType, params) { + // v3-compat: z.record(valueType, params?) — defaults keyType to z.string() + if (!valueType || !valueType._zod) { + return new ZodRecord({ + type: "record", + keyType: schemas_string(), + valueType: keyType, + ...normalizeParams(valueType), + }); + } + return new ZodRecord({ + type: "record", + keyType, + valueType: valueType, + ...normalizeParams(params), + }); +} +// type alksjf = core.output; +function partialRecord(keyType, valueType, params) { + return new ZodRecord({ + type: "record", + keyType, + valueType: valueType, + ...util.normalizeParams(params), + partial: true, + }); +} +function looseRecord(keyType, valueType, params) { + return new ZodRecord({ + type: "record", + keyType, + valueType: valueType, + mode: "loose", + ...util.normalizeParams(params), + }); +} +const ZodMap = /*@__PURE__*/ (/* unused pure expression or super */ null && (core.$constructor("ZodMap", (inst, def) => { + _ensureDefaultMemoizer(); + core.$ZodMap.init(inst, def); + ZodType.init(inst, def); + inst._zod.processJSONSchema = (ctx, json, params) => processors.mapProcessor(inst, ctx, json, params); + inst.keyType = def.keyType; + inst.valueType = def.valueType; + inst.min = (...args) => inst.check(core._minSize(...args)); + inst.nonempty = (params) => inst.check(core._minSize(1, params)); + inst.max = (...args) => inst.check(core._maxSize(...args)); + inst.size = (...args) => inst.check(core._size(...args)); +}))); +function schemas_map(keyType, valueType, params) { + return new ZodMap({ + type: "map", + keyType: keyType, + valueType: valueType, + ...util.normalizeParams(params), + }); +} +const ZodSet = /*@__PURE__*/ (/* unused pure expression or super */ null && (core.$constructor("ZodSet", (inst, def) => { + _ensureDefaultMemoizer(); + core.$ZodSet.init(inst, def); + ZodType.init(inst, def); + inst._zod.processJSONSchema = (ctx, json, params) => processors.setProcessor(inst, ctx, json, params); + inst.min = (...args) => inst.check(core._minSize(...args)); + inst.nonempty = (params) => inst.check(core._minSize(1, params)); + inst.max = (...args) => inst.check(core._maxSize(...args)); + inst.size = (...args) => inst.check(core._size(...args)); +}))); +function schemas_set(valueType, params) { + return new ZodSet({ + type: "set", + valueType: valueType, + ...util.normalizeParams(params), + }); +} +const ZodEnum = /*@__PURE__*/ $constructor("ZodEnum", (inst, def) => { + $ZodEnum.init(inst, def); + ZodType.init(inst, def); + inst._zod.processJSONSchema = (ctx, json, params) => enumProcessor(inst, ctx, json, params); + inst.enum = def.entries; + inst.options = Object.values(def.entries); + const keys = new Set(Object.keys(def.entries)); + inst.extract = (values, params) => { + const newEntries = {}; + for (const value of values) { + if (keys.has(value)) { + newEntries[value] = def.entries[value]; + } + else + throw new Error(`Key ${value} not found in enum`); + } + return new ZodEnum({ + ...def, + checks: [], + ...normalizeParams(params), + entries: newEntries, + }); + }; + inst.exclude = (values, params) => { + const newEntries = { ...def.entries }; + for (const value of values) { + if (keys.has(value)) { + delete newEntries[value]; + } + else + throw new Error(`Key ${value} not found in enum`); + } + return new ZodEnum({ + ...def, + checks: [], + ...normalizeParams(params), + entries: newEntries, + }); + }; +}); +function schemas_enum(values, params) { + const entries = Array.isArray(values) ? Object.fromEntries(values.map((v) => [v, v])) : values; + return new ZodEnum({ + type: "enum", + entries, + ...normalizeParams(params), + }); +} + +/** @deprecated This API has been merged into `z.enum()`. Use `z.enum()` instead. + * + * ```ts + * enum Colors { red, green, blue } + * z.enum(Colors); + * ``` + */ +function nativeEnum(entries, params) { + return new ZodEnum({ + type: "enum", + entries, + ...util.normalizeParams(params), + }); +} +const ZodLiteral = /*@__PURE__*/ $constructor("ZodLiteral", (inst, def) => { + $ZodLiteral.init(inst, def); + ZodType.init(inst, def); + inst._zod.processJSONSchema = (ctx, json, params) => literalProcessor(inst, ctx, json, params); + inst.values = new Set(def.values); + Object.defineProperty(inst, "value", { + get() { + if (def.values.length > 1) { + throw new Error("This schema contains multiple valid literal values. Use `.values` instead."); + } + return def.values[0]; + }, + }); +}); +function literal(value, params) { + return new ZodLiteral({ + type: "literal", + values: Array.isArray(value) ? value : [value], + ...normalizeParams(params), + }); +} +const ZodFile = /*@__PURE__*/ (/* unused pure expression or super */ null && (core.$constructor("ZodFile", (inst, def) => { + core.$ZodFile.init(inst, def); + ZodType.init(inst, def); + inst._zod.processJSONSchema = (ctx, json, params) => processors.fileProcessor(inst, ctx, json, params); + inst.min = (size, params) => inst.check(core._minSize(size, params)); + inst.max = (size, params) => inst.check(core._maxSize(size, params)); + inst.mime = (types, params) => inst.check(core._mime(Array.isArray(types) ? types : [types], params)); +}))); +function schemas_file(params) { + return core._file(ZodFile, params); +} +const ZodTransform = /*@__PURE__*/ $constructor("ZodTransform", (inst, def) => { + _ensureDefaultMemoizer(); + $ZodTransform.init(inst, def); + ZodType.init(inst, def); + inst._zod.processJSONSchema = (ctx, json, params) => transformProcessor(inst, ctx, json, params); + inst._zod.parse = (payload, _ctx) => { + if (_ctx.direction === "backward") { + throw new $ZodEncodeError(inst.constructor.name); + } + payload.addIssue = (issue) => { + if (typeof issue === "string") { + payload.issues.push(util_issue(issue, payload.value, def)); + } + else { + // for Zod 3 backwards compatibility + const _issue = issue; + if (_issue.fatal) + _issue.continue = false; + _issue.code ?? (_issue.code = "custom"); + if (!("input" in _issue)) + _issue.input = payload.value; + _issue.inst ?? (_issue.inst = inst); + // _issue.continue ??= true; + payload.issues.push(util_issue(_issue)); + } + }; + const output = def.transform(payload.value, payload); + if (output instanceof Promise) { + return output.then((output) => { + payload.value = output; + return payload; + }); + } + payload.value = output; + return payload; + }; +}); +function transform(fn) { + return new ZodTransform({ + type: "transform", + transform: fn, + }); +} +const ZodOptional = /*@__PURE__*/ $constructor("ZodOptional", (inst, def) => { + $ZodOptional.init(inst, def); + ZodType.init(inst, def); + inst._zod.processJSONSchema = (ctx, json, params) => optionalProcessor(inst, ctx, json, params); + inst.unwrap = () => inst._zod.def.innerType; +}); +function schemas_optional(innerType) { + return new ZodOptional({ + type: "optional", + innerType: innerType, + }); +} +const ZodExactOptional = /*@__PURE__*/ $constructor("ZodExactOptional", (inst, def) => { + $ZodExactOptional.init(inst, def); + ZodType.init(inst, def); + inst._zod.processJSONSchema = (ctx, json, params) => optionalProcessor(inst, ctx, json, params); + inst.unwrap = () => inst._zod.def.innerType; +}); +function exactOptional(innerType) { + return new ZodExactOptional({ + type: "optional", + innerType: innerType, + }); +} +const ZodNullable = /*@__PURE__*/ $constructor("ZodNullable", (inst, def) => { + $ZodNullable.init(inst, def); + ZodType.init(inst, def); + inst._zod.processJSONSchema = (ctx, json, params) => nullableProcessor(inst, ctx, json, params); + inst.unwrap = () => inst._zod.def.innerType; +}); +function nullable(innerType) { + return new ZodNullable({ + type: "nullable", + innerType: innerType, + }); +} +// nullish +function schemas_nullish(innerType) { + return schemas_optional(nullable(innerType)); +} +const ZodDefault = /*@__PURE__*/ $constructor("ZodDefault", (inst, def) => { + $ZodDefault.init(inst, def); + ZodType.init(inst, def); + inst._zod.processJSONSchema = (ctx, json, params) => defaultProcessor(inst, ctx, json, params); + inst.unwrap = () => inst._zod.def.innerType; + inst.removeDefault = inst.unwrap; +}); +function schemas_default(innerType, defaultValue) { + return new ZodDefault({ + type: "default", + innerType: innerType, + get defaultValue() { + return typeof defaultValue === "function" ? defaultValue() : shallowClone(defaultValue); + }, + }); +} +const ZodPrefault = /*@__PURE__*/ $constructor("ZodPrefault", (inst, def) => { + $ZodPrefault.init(inst, def); + ZodType.init(inst, def); + inst._zod.processJSONSchema = (ctx, json, params) => prefaultProcessor(inst, ctx, json, params); + inst.unwrap = () => inst._zod.def.innerType; +}); +function prefault(innerType, defaultValue) { + return new ZodPrefault({ + type: "prefault", + innerType: innerType, + get defaultValue() { + return typeof defaultValue === "function" ? defaultValue() : shallowClone(defaultValue); + }, + }); +} +const ZodNonOptional = /*@__PURE__*/ $constructor("ZodNonOptional", (inst, def) => { + $ZodNonOptional.init(inst, def); + ZodType.init(inst, def); + inst._zod.processJSONSchema = (ctx, json, params) => nonoptionalProcessor(inst, ctx, json, params); + inst.unwrap = () => inst._zod.def.innerType; +}); +function nonoptional(innerType, params) { + return new ZodNonOptional({ + type: "nonoptional", + innerType: innerType, + ...normalizeParams(params), + }); +} +const ZodSuccess = /*@__PURE__*/ (/* unused pure expression or super */ null && (core.$constructor("ZodSuccess", (inst, def) => { + core.$ZodSuccess.init(inst, def); + ZodType.init(inst, def); + inst._zod.processJSONSchema = (ctx, json, params) => processors.successProcessor(inst, ctx, json, params); + inst.unwrap = () => inst._zod.def.innerType; +}))); +function success(innerType) { + return new ZodSuccess({ + type: "success", + innerType: innerType, + }); +} +const ZodCatch = /*@__PURE__*/ $constructor("ZodCatch", (inst, def) => { + $ZodCatch.init(inst, def); + ZodType.init(inst, def); + inst._zod.processJSONSchema = (ctx, json, params) => catchProcessor(inst, ctx, json, params); + inst.unwrap = () => inst._zod.def.innerType; + inst.removeCatch = inst.unwrap; +}); +function schemas_catch(innerType, catchValue) { + return new ZodCatch({ + type: "catch", + innerType: innerType, + catchValue: (typeof catchValue === "function" ? catchValue : constantCatch(catchValue)), + }); +} + +const ZodNaN = /*@__PURE__*/ (/* unused pure expression or super */ null && (core.$constructor("ZodNaN", (inst, def) => { + core.$ZodNaN.init(inst, def); + ZodType.init(inst, def); + inst._zod.processJSONSchema = (ctx, json, params) => processors.nanProcessor(inst, ctx, json, params); +}))); +function nan(params) { + return core._nan(ZodNaN, params); +} +const ZodPipe = /*@__PURE__*/ $constructor("ZodPipe", (inst, def) => { + $ZodPipe.init(inst, def); + ZodType.init(inst, def); + inst._zod.processJSONSchema = (ctx, json, params) => pipeProcessor(inst, ctx, json, params); + inst.in = def.in; + inst.out = def.out; +}); +function pipe(in_, out) { + return new ZodPipe({ + type: "pipe", + in: in_, + out: out, + // ...util.normalizeParams(params), + }); +} +const ZodCodec = /*@__PURE__*/ (/* unused pure expression or super */ null && (core.$constructor("ZodCodec", (inst, def) => { + ZodPipe.init(inst, def); + core.$ZodCodec.init(inst, def); +}))); +function schemas_codec(in_, out, params) { + return new ZodCodec({ + type: "pipe", + in: in_, + out: out, + transform: params.decode, + reverseTransform: params.encode, + }); +} +function invertCodec(codec) { + const def = codec._zod.def; + return new ZodCodec({ + type: "pipe", + in: def.out, + out: def.in, + transform: def.reverseTransform, + reverseTransform: def.transform, + }); +} +const ZodPreprocess = /*@__PURE__*/ $constructor("ZodPreprocess", (inst, def) => { + ZodPipe.init(inst, def); + $ZodPreprocess.init(inst, def); +}); +const ZodReadonly = /*@__PURE__*/ $constructor("ZodReadonly", (inst, def) => { + $ZodReadonly.init(inst, def); + ZodType.init(inst, def); + inst._zod.processJSONSchema = (ctx, json, params) => readonlyProcessor(inst, ctx, json, params); + inst.unwrap = () => inst._zod.def.innerType; +}); +function readonly(innerType) { + return new ZodReadonly({ + type: "readonly", + innerType: innerType, + }); +} +const ZodTemplateLiteral = /*@__PURE__*/ (/* unused pure expression or super */ null && (core.$constructor("ZodTemplateLiteral", (inst, def) => { + core.$ZodTemplateLiteral.init(inst, def); + ZodType.init(inst, def); + inst._zod.processJSONSchema = (ctx, json, params) => processors.templateLiteralProcessor(inst, ctx, json, params); +}))); +function templateLiteral(parts, params) { + return new ZodTemplateLiteral({ + type: "template_literal", + parts, + ...util.normalizeParams(params), + }); +} +const ZodLazy = /*@__PURE__*/ $constructor("ZodLazy", (inst, def) => { + $ZodLazy.init(inst, def); + ZodType.init(inst, def); + inst._zod.processJSONSchema = (ctx, json, params) => lazyProcessor(inst, ctx, json, params); + inst.unwrap = () => inst._zod.def.getter(); +}); +function lazy(getter) { + return new ZodLazy({ + type: "lazy", + getter: getter, + }); +} +const ZodPromise = /*@__PURE__*/ (/* unused pure expression or super */ null && (core.$constructor("ZodPromise", (inst, def) => { + core.$ZodPromise.init(inst, def); + ZodType.init(inst, def); + inst._zod.processJSONSchema = (ctx, json, params) => processors.promiseProcessor(inst, ctx, json, params); + inst.unwrap = () => inst._zod.def.innerType; +}))); +function schemas_promise(innerType) { + return new ZodPromise({ + type: "promise", + innerType: innerType, + }); +} +const ZodFunction = /*@__PURE__*/ (/* unused pure expression or super */ null && (core.$constructor("ZodFunction", (inst, def) => { + core.$ZodFunction.init(inst, def); + ZodType.init(inst, def); + inst._zod.processJSONSchema = (ctx, json, params) => processors.functionProcessor(inst, ctx, json, params); +}))); +function _function(params) { + return new ZodFunction({ + type: "function", + input: Array.isArray(params?.input) ? tuple(params?.input) : (params?.input ?? schemas_array(unknown())), + output: params?.output ?? unknown(), + }); +} + +const ZodCustom = /*@__PURE__*/ $constructor("ZodCustom", (inst, def) => { + $ZodCustom.init(inst, def); + ZodType.init(inst, def); + inst._zod.processJSONSchema = (ctx, json, params) => customProcessor(inst, ctx, json, params); +}); +// custom checks +function schemas_check(fn) { + const ch = new core.$ZodCheck({ + check: "custom", + // ...util.normalizeParams(params), + }); + ch._zod.check = fn; + return ch; +} +function custom(fn, _params) { + return core._custom(ZodCustom, fn ?? (() => true), _params); +} +function refine(fn, _params = {}) { + return _refine(ZodCustom, fn, _params); +} +// superRefine +function superRefine(fn, params) { + return _superRefine(fn, params); +} +// Re-export describe and meta from core +const schemas_describe = describe; +const schemas_meta = api_meta; +function _instanceof(cls, params = {}) { + const inst = new ZodCustom({ + type: "custom", + check: "custom", + fn: (data) => data instanceof cls, + abort: true, + ...util.normalizeParams(params), + }); + inst._zod.bag.Class = cls; + // Override check to emit invalid_type instead of custom + inst._zod.check = (payload) => { + if (!(payload.value instanceof cls)) { + payload.issues.push({ + code: "invalid_type", + expected: cls.name, + input: payload.value, + inst, + path: [...(inst._zod.def.path ?? [])], + }); + } + }; + return inst; +} + +// stringbool +const stringbool = (...args) => core._stringbool({ + Codec: ZodCodec, + Boolean: ZodBoolean, + String: ZodString, +}, ...args); +function schemas_json(params) { + const jsonSchema = lazy(() => { + return schemas_union([schemas_string(params), schemas_number(), schemas_boolean(), schemas_null(), schemas_array(jsonSchema), schemas_record(schemas_string(), jsonSchema)]); + }); + return jsonSchema; +} +// preprocess +function preprocess(fn, schema) { + return new ZodPreprocess({ + type: "pipe", + in: transform(fn), + out: schema, + }); +} + + + + +function iso_datetime(params) { + return _isoDateTime(ZodISODateTime, params); +} +function iso_date(params) { + return _isoDate(ZodISODate, params); +} +function iso_time(params) { + return core._isoTime(ZodISOTime, params); +} +function iso_duration(params) { + return core._isoDuration(ZodISODuration, params); +} + +// Zod 3 compat layer + +/** @deprecated Use the raw string literal codes instead, e.g. "invalid_type". */ +const ZodIssueCode = { + 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", +}; + +/** @deprecated Use `z.config(params)` instead. */ +function setErrorMap(map) { + core.config({ + customError: map, + }); +} +/** @deprecated Use `z.config()` instead. */ +function getErrorMap() { + return core.config().customError; +} +/** @deprecated Do not use. Stub definition, only included for zod-to-json-schema compatibility. */ +var compat_ZodFirstPartyTypeKind; +(function (ZodFirstPartyTypeKind) { +})(compat_ZodFirstPartyTypeKind || (compat_ZodFirstPartyTypeKind = {})); + + + +function coerce_string(params) { + return core._coercedString(schemas.ZodString, params); +} +function coerce_number(params) { + return _coercedNumber(ZodNumber, params); +} +function coerce_boolean(params) { + return core._coercedBoolean(schemas.ZodBoolean, params); +} +function coerce_bigint(params) { + return core._coercedBigint(schemas.ZodBigInt, params); +} +function coerce_date(params) { + return core._coercedDate(schemas.ZodDate, params); +} + + + +//#region src/constants.ts +const LATEST_PROTOCOL_VERSION = "2025-11-25"; +const auth_CUe6YdwF_DEFAULT_NEGOTIATED_PROTOCOL_VERSION = "2025-03-26"; +const auth_CUe6YdwF_SUPPORTED_PROTOCOL_VERSIONS = [ + LATEST_PROTOCOL_VERSION, + "2025-06-18", + "2025-03-26", + "2024-11-05", + "2024-10-07" +]; +/** +* `_meta` key associating a message with a 2025-11-25 task. +* +* @deprecated 2025-11-25 wire vocabulary with no SDK runtime; kept importable for interoperability only. +*/ +const RELATED_TASK_META_KEY = "io.modelcontextprotocol/related-task"; +/** +* `_meta` key carrying the MCP protocol version governing a request. +* +* For the HTTP transport, the value must match the `MCP-Protocol-Version` header. +*/ +const auth_CUe6YdwF_PROTOCOL_VERSION_META_KEY = "io.modelcontextprotocol/protocolVersion"; +/** +* `_meta` key identifying the client software making a request. +* +* Clients SHOULD include it on every request; the value is self-reported and +* intended for display, logging, and debugging — servers should not rely on +* it for behavior or security decisions. +*/ +const auth_CUe6YdwF_CLIENT_INFO_META_KEY = "io.modelcontextprotocol/clientInfo"; +/** +* `_meta` key identifying the server software producing a response. +* +* Servers SHOULD include it on every response; the value is self-reported and +* intended for display, logging, and debugging — clients should not rely on +* it for behavior or security decisions. +*/ +const auth_CUe6YdwF_SERVER_INFO_META_KEY = "io.modelcontextprotocol/serverInfo"; +/** +* `_meta` key carrying the client's capabilities for a request. +* +* Capabilities are declared per request rather than once at initialization; +* servers must not infer capabilities from prior requests. +*/ +const auth_CUe6YdwF_CLIENT_CAPABILITIES_META_KEY = "io.modelcontextprotocol/clientCapabilities"; +/** +* `_meta` key carrying the JSON-RPC ID of the `subscriptions/listen` request +* that opened the stream a notification was delivered on. +* +* Stamped by the server on every notification delivered via a +* `subscriptions/listen` stream (including the leading +* `notifications/subscriptions/acknowledged`); on stdio, where all messages +* share one channel, clients use it to correlate notifications with their +* originating subscription. The value is the listen request's JSON-RPC ID +* verbatim. +*/ +const auth_CUe6YdwF_SUBSCRIPTION_ID_META_KEY = "io.modelcontextprotocol/subscriptionId"; +/** +* `_meta` key carrying the desired log level for a request. +* +* When absent, the server must not send `notifications/message` notifications +* for the request. +* +* @deprecated Deprecated as of protocol version 2026-07-28 (SEP-2577); remains +* in the specification for at least twelve months. +*/ +const LOG_LEVEL_META_KEY = "io.modelcontextprotocol/logLevel"; +/** +* `_meta` key carrying W3C Trace Context for distributed tracing (SEP-414). +* +* When present, the value MUST follow the W3C `traceparent` header format, +* e.g. `00-4bf92f3577b34da6a3ce929d0e0e4736-00f067aa0ba902b7-01`. +* +* @see https://www.w3.org/TR/trace-context/#traceparent-header +*/ +const TRACEPARENT_META_KEY = "traceparent"; +/** +* `_meta` key carrying vendor-specific trace state for distributed tracing (SEP-414). +* +* When present, the value MUST follow the W3C `tracestate` header format, +* e.g. `vendor1=value1,vendor2=value2`. +* +* @see https://www.w3.org/TR/trace-context/#tracestate-header +*/ +const TRACESTATE_META_KEY = "tracestate"; +/** +* `_meta` key carrying cross-cutting propagation values for distributed tracing (SEP-414). +* +* When present, the value MUST follow the W3C Baggage header format, +* e.g. `userId=alice,serverRegion=us-east-1`. +* +* @see https://www.w3.org/TR/baggage/ +*/ +const BAGGAGE_META_KEY = "baggage"; +const JSONRPC_VERSION = "2.0"; +const PARSE_ERROR = (/* unused pure expression or super */ null && (-32700)); +const INVALID_REQUEST = (/* unused pure expression or super */ null && (-32600)); +const METHOD_NOT_FOUND = (/* unused pure expression or super */ null && (-32601)); +const INVALID_PARAMS = (/* unused pure expression or super */ null && (-32602)); +const INTERNAL_ERROR = (/* unused pure expression or super */ null && (-32603)); + +//#endregion +//#region src/schemas.ts +const JSONValueSchema = lazy(() => schemas_union([ + schemas_string(), + schemas_number(), + schemas_boolean(), + schemas_null(), + schemas_record(schemas_string(), JSONValueSchema), + schemas_array(JSONValueSchema) +])); +const JSONObjectSchema = schemas_record(schemas_string(), JSONValueSchema); +const JSONArraySchema = schemas_array(JSONValueSchema); +/** +* A progress token, used to associate progress notifications with the original request. +*/ +const ProgressTokenSchema = schemas_union([schemas_string(), schemas_number().int()]); +/** +* An opaque token used to represent a cursor for pagination. +*/ +const CursorSchema = schemas_string(); +/** @deprecated 2025-11-25 wire vocabulary with no SDK runtime; kept importable for interoperability only. */ +const TaskMetadataSchema = schemas_object({ ttl: schemas_number().optional() }); +/** +* Metadata for associating messages with a task. +* Include this in the `_meta` field under the key `io.modelcontextprotocol/related-task`. +* +* @deprecated 2025-11-25 wire vocabulary with no SDK runtime; kept importable for interoperability only. +*/ +const RelatedTaskMetadataSchema = schemas_object({ taskId: schemas_string() }); +const RequestMetaSchema = looseObject({ + progressToken: ProgressTokenSchema.optional(), + [RELATED_TASK_META_KEY]: RelatedTaskMetadataSchema.optional() +}); +/** +* Common params for any request. +*/ +const BaseRequestParamsSchema = schemas_object({ _meta: RequestMetaSchema.optional() }); +/** +* Common params for any task-augmented request. +* +* @deprecated 2025-11-25 wire vocabulary with no SDK runtime; kept importable for interoperability only. +*/ +const auth_CUe6YdwF_TaskAugmentedRequestParamsSchema = BaseRequestParamsSchema.extend({ task: TaskMetadataSchema.optional() }); +const RequestSchema = schemas_object({ + method: schemas_string(), + params: BaseRequestParamsSchema.loose().optional() +}); +const NotificationsParamsSchema = schemas_object({ _meta: RequestMetaSchema.optional() }); +const NotificationSchema = schemas_object({ + method: schemas_string(), + params: NotificationsParamsSchema.loose().optional() +}); +/** +* The contents of a result's `_meta` field (the 2026-07-28 `ResultMetaObject`). +* Loose — implementation-specific keys pass through. +* +* The serverInfo key identifies the server software producing the response +* (servers SHOULD include it on every response; the value is self-reported +* and intended for display, logging, and debugging). The getter defers the +* `ImplementationSchema` reference, which is declared later in this file. +*/ +const ResultMetaObjectSchema = looseObject({ get [auth_CUe6YdwF_SERVER_INFO_META_KEY]() { + return ImplementationSchema.optional().catch(void 0); +} }); +const ResultSchema = looseObject({ _meta: ResultMetaObjectSchema.optional() }); +/** +* A uniquely identifying ID for a request in JSON-RPC. +*/ +const RequestIdSchema = schemas_union([schemas_string(), schemas_number().int()]); +/** +* A request that expects a response. +*/ +const JSONRPCRequestSchema = schemas_object({ + jsonrpc: literal(JSONRPC_VERSION), + id: RequestIdSchema, + ...RequestSchema.shape +}).strict(); +/** +* A notification which does not expect a response. +*/ +const JSONRPCNotificationSchema = schemas_object({ + jsonrpc: literal(JSONRPC_VERSION), + ...NotificationSchema.shape +}).strict(); +/** +* A successful (non-error) response to a request. +*/ +const JSONRPCResultResponseSchema = schemas_object({ + jsonrpc: literal(JSONRPC_VERSION), + id: RequestIdSchema, + result: ResultSchema +}).strict(); +/** +* A response to a request that indicates an error occurred. +*/ +const JSONRPCErrorResponseSchema = schemas_object({ + jsonrpc: literal(JSONRPC_VERSION), + id: RequestIdSchema.optional(), + error: schemas_object({ + code: schemas_number().int(), + message: schemas_string(), + data: unknown().optional() + }) +}).strict(); +const auth_CUe6YdwF_JSONRPCMessageSchema = schemas_union([ + JSONRPCRequestSchema, + JSONRPCNotificationSchema, + JSONRPCResultResponseSchema, + JSONRPCErrorResponseSchema +]); +const auth_CUe6YdwF_JSONRPCResponseSchema = schemas_union([JSONRPCResultResponseSchema, JSONRPCErrorResponseSchema]); +/** +* A response that indicates success but carries no data. +*/ +const EmptyResultSchema = ResultSchema.strict(); +const CancelledNotificationParamsSchema = NotificationsParamsSchema.extend({ + requestId: RequestIdSchema.optional(), + reason: schemas_string().optional() +}); +/** +* This notification can be sent by either side to indicate that it is cancelling a previously-issued request. +* +* The request SHOULD still be in-flight, but due to communication latency, it is always possible that this notification MAY arrive after the request has already finished. +* +* This notification indicates that the result will be unused, so any associated processing SHOULD cease. +* +* A client MUST NOT attempt to cancel its {@linkcode InitializeRequest | initialize} request. +*/ +const CancelledNotificationSchema = NotificationSchema.extend({ + method: literal("notifications/cancelled"), + params: CancelledNotificationParamsSchema +}); +/** +* Icon schema for use in {@link Tool | tools}, {@link Prompt | prompts}, {@link Resource | resources}, and {@link Implementation | implementations}. +*/ +const IconSchema = schemas_object({ + src: schemas_string(), + mimeType: schemas_string().optional(), + sizes: schemas_array(schemas_string()).optional(), + theme: schemas_enum(["light", "dark"]).optional() +}); +/** +* Base schema to add `icons` property. +* +*/ +const IconsSchema = schemas_object({ icons: schemas_array(IconSchema).optional() }); +/** +* Base metadata interface for common properties across {@link Resource | resources}, {@link Tool | tools}, {@link Prompt | prompts}, and {@link Implementation | implementations}. +*/ +const BaseMetadataSchema = schemas_object({ + name: schemas_string(), + title: schemas_string().optional() +}); +/** +* Describes the name and version of an MCP implementation. +*/ +const ImplementationSchema = BaseMetadataSchema.extend({ + ...BaseMetadataSchema.shape, + ...IconsSchema.shape, + version: schemas_string(), + websiteUrl: schemas_string().optional(), + description: schemas_string().optional() +}); +const auth_CUe6YdwF_FormElicitationCapabilitySchema = intersection(schemas_object({ applyDefaults: schemas_boolean().optional() }), JSONObjectSchema); +const auth_CUe6YdwF_ElicitationCapabilitySchema = preprocess((value) => { + if (value && typeof value === "object" && !Array.isArray(value) && Object.keys(value).length === 0) return { form: {} }; + return value; +}, intersection(schemas_object({ + form: auth_CUe6YdwF_FormElicitationCapabilitySchema.optional(), + url: JSONObjectSchema.optional() +}), JSONObjectSchema.optional())); +/** +* Task capabilities for clients, indicating which request types support task creation. +* +* @deprecated 2025-11-25 wire vocabulary with no SDK runtime; kept importable for interoperability only. +*/ +const ClientTasksCapabilitySchema = looseObject({ + list: JSONObjectSchema.optional(), + cancel: JSONObjectSchema.optional(), + requests: looseObject({ + sampling: looseObject({ createMessage: JSONObjectSchema.optional() }).optional(), + elicitation: looseObject({ create: JSONObjectSchema.optional() }).optional() + }).optional() +}); +/** +* Task capabilities for servers, indicating which request types support task creation. +* +* @deprecated 2025-11-25 wire vocabulary with no SDK runtime; kept importable for interoperability only. +*/ +const ServerTasksCapabilitySchema = looseObject({ + list: JSONObjectSchema.optional(), + cancel: JSONObjectSchema.optional(), + requests: looseObject({ tools: looseObject({ call: JSONObjectSchema.optional() }).optional() }).optional() +}); +/** +* Capabilities a client may support. Known capabilities are defined here, in this schema, but this is not a closed set: any client can define its own, additional capabilities. +*/ +const ClientCapabilitiesSchema = schemas_object({ + experimental: schemas_record(schemas_string(), JSONObjectSchema).optional(), + sampling: schemas_object({ + context: JSONObjectSchema.optional(), + tools: JSONObjectSchema.optional() + }).optional(), + elicitation: auth_CUe6YdwF_ElicitationCapabilitySchema.optional(), + roots: schemas_object({ listChanged: schemas_boolean().optional() }).optional(), + tasks: ClientTasksCapabilitySchema.optional(), + extensions: schemas_record(schemas_string(), JSONObjectSchema).optional() +}); +const InitializeRequestParamsSchema = BaseRequestParamsSchema.extend({ + protocolVersion: schemas_string(), + capabilities: ClientCapabilitiesSchema, + clientInfo: ImplementationSchema +}); +/** +* This request is sent from the client to the server when it first connects, asking it to begin initialization. +*/ +const auth_CUe6YdwF_InitializeRequestSchema = RequestSchema.extend({ + method: literal("initialize"), + params: InitializeRequestParamsSchema +}); +/** +* Capabilities that a server may support. Known capabilities are defined here, in this schema, but this is not a closed set: any server can define its own, additional capabilities. +*/ +const ServerCapabilitiesSchema = schemas_object({ + experimental: schemas_record(schemas_string(), JSONObjectSchema).optional(), + logging: JSONObjectSchema.optional(), + completions: JSONObjectSchema.optional(), + prompts: schemas_object({ listChanged: schemas_boolean().optional() }).optional(), + resources: schemas_object({ + subscribe: schemas_boolean().optional(), + listChanged: schemas_boolean().optional() + }).optional(), + tools: schemas_object({ listChanged: schemas_boolean().optional() }).optional(), + tasks: ServerTasksCapabilitySchema.optional(), + extensions: schemas_record(schemas_string(), JSONObjectSchema).optional() +}); +/** +* After receiving an initialize request from the client, the server sends this response. +*/ +const InitializeResultSchema = ResultSchema.extend({ + protocolVersion: schemas_string(), + capabilities: ServerCapabilitiesSchema, + serverInfo: ImplementationSchema, + instructions: schemas_string().optional() +}); +/** +* This notification is sent from the client to the server after initialization has finished. +*/ +const auth_CUe6YdwF_InitializedNotificationSchema = NotificationSchema.extend({ + method: literal("notifications/initialized"), + params: NotificationsParamsSchema.optional() +}); +/** +* A request from the client asking the server to advertise its supported protocol +* versions, capabilities, and other metadata (protocol revision 2026-07-28). Servers +* MUST implement `server/discover`. Clients MAY call it but are not required to — +* version negotiation can also happen inline via the per-request `_meta` envelope. +*/ +const DiscoverRequestSchema = RequestSchema.extend({ + method: literal("server/discover"), + params: BaseRequestParamsSchema.optional() +}); +/** +* The result returned by the server for a `server/discover` request. +*/ +const DiscoverResultSchema = ResultSchema.extend({ + supportedVersions: schemas_array(schemas_string()), + capabilities: ServerCapabilitiesSchema, + instructions: schemas_string().optional() +}); +/** +* A ping, issued by either the server or the client, to check that the other party is still alive. The receiver must promptly respond, or else may be disconnected. +*/ +const PingRequestSchema = RequestSchema.extend({ + method: literal("ping"), + params: BaseRequestParamsSchema.optional() +}); +const ProgressSchema = schemas_object({ + progress: schemas_number(), + total: schemas_optional(schemas_number()), + message: schemas_optional(schemas_string()) +}); +const ProgressNotificationParamsSchema = schemas_object({ + ...NotificationsParamsSchema.shape, + ...ProgressSchema.shape, + progressToken: ProgressTokenSchema +}); +/** +* An out-of-band notification used to inform the receiver of a progress update for a long-running request. +* +* @category notifications/progress +*/ +const ProgressNotificationSchema = NotificationSchema.extend({ + method: literal("notifications/progress"), + params: ProgressNotificationParamsSchema +}); +const PaginatedRequestParamsSchema = BaseRequestParamsSchema.extend({ cursor: CursorSchema.optional() }); +const PaginatedRequestSchema = RequestSchema.extend({ params: PaginatedRequestParamsSchema.optional() }); +const PaginatedResultSchema = ResultSchema.extend({ nextCursor: CursorSchema.optional() }); +/** +* The contents of a specific resource or sub-resource. +*/ +const ResourceContentsSchema = schemas_object({ + uri: schemas_string(), + mimeType: schemas_optional(schemas_string()), + _meta: schemas_record(schemas_string(), unknown()).optional() +}); +const TextResourceContentsSchema = ResourceContentsSchema.extend({ text: schemas_string() }); +/** +* A Zod schema for validating Base64 strings that is more performant and +* robust for very large inputs than the default regex-based check. It avoids +* stack overflows by using the native `atob` function for validation. +*/ +const auth_CUe6YdwF_Base64Schema = schemas_string().refine((val) => { + try { + atob(val); + return true; + } catch { + return false; + } +}, { message: "Invalid Base64 string" }); +const BlobResourceContentsSchema = ResourceContentsSchema.extend({ blob: auth_CUe6YdwF_Base64Schema }); +/** +* The sender or recipient of messages and data in a conversation. +*/ +const RoleSchema = schemas_enum(["user", "assistant"]); +/** +* Optional annotations providing clients additional context about a resource. +*/ +const AnnotationsSchema = schemas_object({ + audience: schemas_array(RoleSchema).optional(), + priority: schemas_number().min(0).max(1).optional(), + lastModified: iso_datetime({ offset: true }).optional() +}); +/** +* A known resource that the server is capable of reading. +*/ +const ResourceSchema = schemas_object({ + ...BaseMetadataSchema.shape, + ...IconsSchema.shape, + uri: schemas_string(), + description: schemas_optional(schemas_string()), + mimeType: schemas_optional(schemas_string()), + size: schemas_optional(schemas_number()), + annotations: AnnotationsSchema.optional(), + _meta: schemas_optional(looseObject({})) +}); +/** +* A template description for resources available on the server. +*/ +const ResourceTemplateSchema = schemas_object({ + ...BaseMetadataSchema.shape, + ...IconsSchema.shape, + uriTemplate: schemas_string(), + description: schemas_optional(schemas_string()), + mimeType: schemas_optional(schemas_string()), + annotations: AnnotationsSchema.optional(), + _meta: schemas_optional(looseObject({})) +}); +/** +* Sent from the client to request a list of resources the server has. +*/ +const ListResourcesRequestSchema = PaginatedRequestSchema.extend({ method: literal("resources/list") }); +/** +* The server's response to a {@linkcode ListResourcesRequest | resources/list} request from the client. +*/ +const ListResourcesResultSchema = PaginatedResultSchema.extend({ resources: schemas_array(ResourceSchema) }); +/** +* Sent from the client to request a list of resource templates the server has. +*/ +const ListResourceTemplatesRequestSchema = PaginatedRequestSchema.extend({ method: literal("resources/templates/list") }); +/** +* The server's response to a {@linkcode ListResourceTemplatesRequest | resources/templates/list} request from the client. +*/ +const ListResourceTemplatesResultSchema = PaginatedResultSchema.extend({ resourceTemplates: schemas_array(ResourceTemplateSchema) }); +const ResourceRequestParamsSchema = BaseRequestParamsSchema.extend({ uri: schemas_string() }); +/** +* Parameters for a {@linkcode ReadResourceRequest | resources/read} request. +*/ +const ReadResourceRequestParamsSchema = ResourceRequestParamsSchema; +/** +* Sent from the client to the server, to read a specific resource URI. +*/ +const ReadResourceRequestSchema = RequestSchema.extend({ + method: literal("resources/read"), + params: ReadResourceRequestParamsSchema +}); +/** +* The server's response to a {@linkcode ReadResourceRequest | resources/read} request from the client. +*/ +const ReadResourceResultSchema = ResultSchema.extend({ contents: schemas_array(schemas_union([TextResourceContentsSchema, BlobResourceContentsSchema])) }); +/** +* An optional notification from the server to the client, informing it that the list of resources it can read from has changed. This may be issued by servers without any previous subscription from the client. +*/ +const ResourceListChangedNotificationSchema = NotificationSchema.extend({ + method: literal("notifications/resources/list_changed"), + params: NotificationsParamsSchema.optional() +}); +const SubscribeRequestParamsSchema = ResourceRequestParamsSchema; +/** +* Sent from the client to request `resources/updated` notifications from the server whenever a particular resource changes. +*/ +const SubscribeRequestSchema = RequestSchema.extend({ + method: literal("resources/subscribe"), + params: SubscribeRequestParamsSchema +}); +const UnsubscribeRequestParamsSchema = ResourceRequestParamsSchema; +/** +* Sent from the client to request cancellation of {@linkcode ResourceUpdatedNotification | resources/updated} notifications from the server. This should follow a previous {@linkcode SubscribeRequest | resources/subscribe} request. +*/ +const UnsubscribeRequestSchema = RequestSchema.extend({ + method: literal("resources/unsubscribe"), + params: UnsubscribeRequestParamsSchema +}); +/** +* The set of notification types a client opts in to on a `subscriptions/listen` +* request. Each type is opt-in; the server MUST NOT send a notification type +* the client has not explicitly requested here. +*/ +const SubscriptionFilterSchema = schemas_object({ + toolsListChanged: schemas_boolean().optional(), + promptsListChanged: schemas_boolean().optional(), + resourcesListChanged: schemas_boolean().optional(), + resourceSubscriptions: schemas_array(schemas_string()).optional() +}); +const SubscriptionsListenRequestParamsSchema = BaseRequestParamsSchema.extend({ notifications: SubscriptionFilterSchema }); +/** +* Sent from the client to open a long-lived channel for receiving notifications +* outside the context of a specific request (protocol revision 2026-07-28). +* Replaces the previous HTTP GET endpoint and `resources/subscribe`. +*/ +const SubscriptionsListenRequestSchema = RequestSchema.extend({ + method: literal("subscriptions/listen"), + params: SubscriptionsListenRequestParamsSchema +}); +const SubscriptionsAcknowledgedNotificationParamsSchema = NotificationsParamsSchema.extend({ notifications: SubscriptionFilterSchema }); +/** +* Sent by the server as the first message on a `subscriptions/listen` stream +* to acknowledge that the subscription has been established and report which +* notification types it agreed to honor (protocol revision 2026-07-28). +*/ +const SubscriptionsAcknowledgedNotificationSchema = NotificationSchema.extend({ + method: literal("notifications/subscriptions/acknowledged"), + params: SubscriptionsAcknowledgedNotificationParamsSchema +}); +/** +* `_meta` for a {@linkcode SubscriptionsListenResult}: the listen request's +* JSON-RPC ID under the canonical subscription-id key (mirroring the same key +* on every notification delivered on the stream). Extends +* {@linkcode ResultMetaObjectSchema}, so the optional serverInfo key is typed +* here too. +*/ +const SubscriptionsListenResultMetaSchema = ResultMetaObjectSchema.extend({ [auth_CUe6YdwF_SUBSCRIPTION_ID_META_KEY]: RequestIdSchema }); +/** +* The response to a `subscriptions/listen` request, signalling that the +* subscription has ended gracefully (for example, during server shutdown). +* Because the listen stream is long-lived, this result is sent only when the +* server tears the subscription down; an abrupt transport close carries no +* response. The result body is otherwise empty. +*/ +const SubscriptionsListenResultSchema = ResultSchema.extend({ _meta: SubscriptionsListenResultMetaSchema }); +/** +* Parameters for a {@linkcode ResourceUpdatedNotification | notifications/resources/updated} notification. +*/ +const ResourceUpdatedNotificationParamsSchema = NotificationsParamsSchema.extend({ uri: schemas_string() }); +/** +* A notification from the server to the client, informing it that a resource has changed and may need to be read again. This should only be sent if the client previously sent a {@linkcode SubscribeRequest | resources/subscribe} request. +*/ +const ResourceUpdatedNotificationSchema = NotificationSchema.extend({ + method: literal("notifications/resources/updated"), + params: ResourceUpdatedNotificationParamsSchema +}); +/** +* Describes an argument that a prompt can accept. +*/ +const PromptArgumentSchema = schemas_object({ + name: schemas_string(), + description: schemas_optional(schemas_string()), + required: schemas_optional(schemas_boolean()) +}); +/** +* A prompt or prompt template that the server offers. +*/ +const PromptSchema = schemas_object({ + ...BaseMetadataSchema.shape, + ...IconsSchema.shape, + description: schemas_optional(schemas_string()), + arguments: schemas_optional(schemas_array(PromptArgumentSchema)), + _meta: schemas_optional(looseObject({})) +}); +/** +* Sent from the client to request a list of prompts and prompt templates the server has. +*/ +const ListPromptsRequestSchema = PaginatedRequestSchema.extend({ method: literal("prompts/list") }); +/** +* The server's response to a {@linkcode ListPromptsRequest | prompts/list} request from the client. +*/ +const ListPromptsResultSchema = PaginatedResultSchema.extend({ prompts: schemas_array(PromptSchema) }); +/** +* Parameters for a {@linkcode GetPromptRequest | prompts/get} request. +*/ +const GetPromptRequestParamsSchema = BaseRequestParamsSchema.extend({ + name: schemas_string(), + arguments: schemas_record(schemas_string(), schemas_string()).optional() +}); +/** +* Used by the client to get a prompt provided by the server. +*/ +const GetPromptRequestSchema = RequestSchema.extend({ + method: literal("prompts/get"), + params: GetPromptRequestParamsSchema +}); +/** +* Text provided to or from an LLM. +*/ +const TextContentSchema = schemas_object({ + type: literal("text"), + text: schemas_string(), + annotations: AnnotationsSchema.optional(), + _meta: schemas_record(schemas_string(), unknown()).optional() +}); +/** +* An image provided to or from an LLM. +*/ +const ImageContentSchema = schemas_object({ + type: literal("image"), + data: auth_CUe6YdwF_Base64Schema, + mimeType: schemas_string(), + annotations: AnnotationsSchema.optional(), + _meta: schemas_record(schemas_string(), unknown()).optional() +}); +/** +* Audio content provided to or from an LLM. +*/ +const AudioContentSchema = schemas_object({ + type: literal("audio"), + data: auth_CUe6YdwF_Base64Schema, + mimeType: schemas_string(), + annotations: AnnotationsSchema.optional(), + _meta: schemas_record(schemas_string(), unknown()).optional() +}); +/** +* A tool call request from an assistant (LLM). +* Represents the assistant's request to use a tool. +* +* @deprecated Deprecated as of protocol version 2026-07-28 (SEP-2577); remains +* in the specification for at least twelve months. Migrate to calling LLM +* provider APIs directly. +*/ +const ToolUseContentSchema = schemas_object({ + type: literal("tool_use"), + name: schemas_string(), + id: schemas_string(), + input: schemas_record(schemas_string(), unknown()), + _meta: schemas_record(schemas_string(), unknown()).optional() +}); +/** +* The contents of a resource, embedded into a prompt or tool call result. +*/ +const EmbeddedResourceSchema = schemas_object({ + type: literal("resource"), + resource: schemas_union([TextResourceContentsSchema, BlobResourceContentsSchema]), + annotations: AnnotationsSchema.optional(), + _meta: schemas_record(schemas_string(), unknown()).optional() +}); +/** +* A resource that the server is capable of reading, included in a prompt or tool call result. +* +* Note: resource links returned by tools are not guaranteed to appear in the results of {@linkcode ListResourcesRequest | resources/list} requests. +*/ +const ResourceLinkSchema = ResourceSchema.extend({ type: literal("resource_link") }); +/** +* A content block that can be used in prompts and tool results. +*/ +const ContentBlockSchema = schemas_union([ + TextContentSchema, + ImageContentSchema, + AudioContentSchema, + ResourceLinkSchema, + EmbeddedResourceSchema +]); +/** +* Describes a message returned as part of a prompt. +*/ +const PromptMessageSchema = schemas_object({ + role: RoleSchema, + content: ContentBlockSchema +}); +/** +* The server's response to a {@linkcode GetPromptRequest | prompts/get} request from the client. +*/ +const GetPromptResultSchema = ResultSchema.extend({ + description: schemas_string().optional(), + messages: schemas_array(PromptMessageSchema) +}); +/** +* An optional notification from the server to the client, informing it that the list of prompts it offers has changed. This may be issued by servers without any previous subscription from the client. +*/ +const PromptListChangedNotificationSchema = NotificationSchema.extend({ + method: literal("notifications/prompts/list_changed"), + params: NotificationsParamsSchema.optional() +}); +/** +* Additional properties describing a `Tool` to clients. +* +* NOTE: all properties in {@linkcode ToolAnnotations} are **hints**. +* They are not guaranteed to provide a faithful description of +* tool behavior (including descriptive properties like `title`). +* +* Clients should never make tool use decisions based on `ToolAnnotations` +* received from untrusted servers. +*/ +const ToolAnnotationsSchema = schemas_object({ + title: schemas_string().optional(), + readOnlyHint: schemas_boolean().optional(), + destructiveHint: schemas_boolean().optional(), + idempotentHint: schemas_boolean().optional(), + openWorldHint: schemas_boolean().optional() +}); +/** +* Execution-related properties for a tool. +*/ +const ToolExecutionSchema = schemas_object({ taskSupport: schemas_enum([ + "required", + "optional", + "forbidden" +]).optional() }); +/** +* Definition for a tool the client can call. +*/ +const ToolSchema = schemas_object({ + ...BaseMetadataSchema.shape, + ...IconsSchema.shape, + description: schemas_string().optional(), + inputSchema: schemas_object({ + type: literal("object"), + properties: schemas_record(schemas_string(), JSONValueSchema).optional(), + required: schemas_array(schemas_string()).optional() + }).catchall(unknown()), + outputSchema: looseObject({ $schema: schemas_string().optional() }).optional(), + annotations: ToolAnnotationsSchema.optional(), + execution: ToolExecutionSchema.optional(), + _meta: schemas_record(schemas_string(), unknown()).optional() +}); +/** +* Sent from the client to request a list of tools the server has. +*/ +const ListToolsRequestSchema = PaginatedRequestSchema.extend({ method: literal("tools/list") }); +/** +* The server's response to a {@linkcode ListToolsRequest | tools/list} request from the client. +*/ +const ListToolsResultSchema = PaginatedResultSchema.extend({ tools: schemas_array(ToolSchema) }); +/** +* The server's response to a tool call. +*/ +const auth_CUe6YdwF_CallToolResultSchema = ResultSchema.extend({ + content: schemas_array(ContentBlockSchema).default([]), + structuredContent: unknown().optional(), + isError: schemas_boolean().optional() +}); +/** +* {@linkcode CallToolResultSchema} extended with backwards compatibility to protocol version 2024-10-07. +*/ +const CompatibilityCallToolResultSchema = auth_CUe6YdwF_CallToolResultSchema.or(ResultSchema.extend({ toolResult: unknown() })); +/** +* Parameters for a `tools/call` request. +*/ +const CallToolRequestParamsSchema = auth_CUe6YdwF_TaskAugmentedRequestParamsSchema.extend({ + name: schemas_string(), + arguments: schemas_record(schemas_string(), unknown()).optional() +}); +/** +* Used by the client to invoke a tool provided by the server. +*/ +const CallToolRequestSchema = RequestSchema.extend({ + method: literal("tools/call"), + params: CallToolRequestParamsSchema +}); +/** +* An optional notification from the server to the client, informing it that the list of tools it offers has changed. This may be issued by servers without any previous subscription from the client. +*/ +const ToolListChangedNotificationSchema = NotificationSchema.extend({ + method: literal("notifications/tools/list_changed"), + params: NotificationsParamsSchema.optional() +}); +/** +* Base schema for list changed subscription options (without callback). +* Used internally for Zod validation of `autoRefresh` and `debounceMs`. +*/ +const ListChangedOptionsBaseSchema = schemas_object({ + autoRefresh: schemas_boolean().default(true), + debounceMs: schemas_number().int().nonnegative().default(300) +}); +/** +* The severity of a log message. +* +* @deprecated Deprecated as of protocol version 2026-07-28 (SEP-2577); remains +* in the specification for at least twelve months. Migrate to stderr logging +* (STDIO servers) or OpenTelemetry. +*/ +const LoggingLevelSchema = schemas_enum([ + "debug", + "info", + "notice", + "warning", + "error", + "critical", + "alert", + "emergency" +]); +/** +* Parameters for a `logging/setLevel` request. +* +* @deprecated Deprecated as of protocol version 2026-07-28 (SEP-2577); remains +* in the specification for at least twelve months. Migrate to stderr logging +* (STDIO servers) or OpenTelemetry. +*/ +const SetLevelRequestParamsSchema = BaseRequestParamsSchema.extend({ level: LoggingLevelSchema }); +/** +* A request from the client to the server, to enable or adjust logging. +* +* @deprecated Deprecated as of protocol version 2026-07-28 (SEP-2577); remains +* in the specification for at least twelve months. Migrate to stderr logging +* (STDIO servers) or OpenTelemetry. +*/ +const SetLevelRequestSchema = RequestSchema.extend({ + method: literal("logging/setLevel"), + params: SetLevelRequestParamsSchema +}); +/** +* Parameters for a `notifications/message` notification. +* +* @deprecated Deprecated as of protocol version 2026-07-28 (SEP-2577); remains +* in the specification for at least twelve months. Migrate to stderr logging +* (STDIO servers) or OpenTelemetry. +*/ +const LoggingMessageNotificationParamsSchema = NotificationsParamsSchema.extend({ + level: LoggingLevelSchema, + logger: schemas_string().optional(), + data: unknown() +}); +/** +* Notification of a log message passed from server to client. If no `logging/setLevel` request has been sent from the client, the server MAY decide which messages to send automatically. +* +* @deprecated Deprecated as of protocol version 2026-07-28 (SEP-2577); remains +* in the specification for at least twelve months. Migrate to stderr logging +* (STDIO servers) or OpenTelemetry. +*/ +const LoggingMessageNotificationSchema = NotificationSchema.extend({ + method: literal("notifications/message"), + params: LoggingMessageNotificationParamsSchema +}); +/** +* Hints to use for model selection. +* +* @deprecated Deprecated as of protocol version 2026-07-28 (SEP-2577); remains +* in the specification for at least twelve months. Migrate to calling LLM +* provider APIs directly. +*/ +const ModelHintSchema = schemas_object({ name: schemas_string().optional() }); +/** +* The server's preferences for model selection, requested of the client during sampling. +* +* @deprecated Deprecated as of protocol version 2026-07-28 (SEP-2577); remains +* in the specification for at least twelve months. Migrate to calling LLM +* provider APIs directly. +*/ +const ModelPreferencesSchema = schemas_object({ + hints: schemas_array(ModelHintSchema).optional(), + costPriority: schemas_number().min(0).max(1).optional(), + speedPriority: schemas_number().min(0).max(1).optional(), + intelligencePriority: schemas_number().min(0).max(1).optional() +}); +/** +* Controls tool usage behavior in sampling requests. +* +* @deprecated Deprecated as of protocol version 2026-07-28 (SEP-2577); remains +* in the specification for at least twelve months. Migrate to calling LLM +* provider APIs directly. +*/ +const ToolChoiceSchema = schemas_object({ mode: schemas_enum([ + "auto", + "required", + "none" +]).optional() }); +/** +* The result of a tool execution, provided by the user (server). +* Represents the outcome of invoking a tool requested via `ToolUseContent`. +* +* @deprecated Deprecated as of protocol version 2026-07-28 (SEP-2577); remains +* in the specification for at least twelve months. Migrate to calling LLM +* provider APIs directly. +*/ +const ToolResultContentSchema = schemas_object({ + type: literal("tool_result"), + toolUseId: schemas_string().describe("The unique identifier for the corresponding tool call."), + content: schemas_array(ContentBlockSchema), + structuredContent: unknown().optional(), + isError: schemas_boolean().optional(), + _meta: schemas_record(schemas_string(), unknown()).optional() +}); +/** +* Basic content types for sampling responses (without tool use). +* Used for backwards-compatible {@linkcode CreateMessageResult} when tools are not used. +* +* @deprecated Deprecated as of protocol version 2026-07-28 (SEP-2577); remains +* in the specification for at least twelve months. Migrate to calling LLM +* provider APIs directly. +*/ +const SamplingContentSchema = discriminatedUnion("type", [ + TextContentSchema, + ImageContentSchema, + AudioContentSchema +]); +/** +* Content block types allowed in sampling messages. +* This includes text, image, audio, tool use requests, and tool results. +* +* @deprecated Deprecated as of protocol version 2026-07-28 (SEP-2577); remains +* in the specification for at least twelve months. Migrate to calling LLM +* provider APIs directly. +*/ +const SamplingMessageContentBlockSchema = discriminatedUnion("type", [ + TextContentSchema, + ImageContentSchema, + AudioContentSchema, + ToolUseContentSchema, + ToolResultContentSchema +]); +/** +* Describes a message issued to or received from an LLM API. +* +* @deprecated Deprecated as of protocol version 2026-07-28 (SEP-2577); remains +* in the specification for at least twelve months. Migrate to calling LLM +* provider APIs directly. +*/ +const SamplingMessageSchema = schemas_object({ + role: RoleSchema, + content: schemas_union([SamplingMessageContentBlockSchema, schemas_array(SamplingMessageContentBlockSchema)]), + _meta: schemas_record(schemas_string(), unknown()).optional() +}); +/** +* Parameters for a `sampling/createMessage` request. +* +* @deprecated Deprecated as of protocol version 2026-07-28 (SEP-2577); remains +* in the specification for at least twelve months. Migrate to calling LLM +* provider APIs directly. +*/ +const CreateMessageRequestParamsSchema = auth_CUe6YdwF_TaskAugmentedRequestParamsSchema.extend({ + messages: schemas_array(SamplingMessageSchema), + modelPreferences: ModelPreferencesSchema.optional(), + systemPrompt: schemas_string().optional(), + includeContext: schemas_enum([ + "none", + "thisServer", + "allServers" + ]).optional(), + temperature: schemas_number().optional(), + maxTokens: schemas_number().int(), + stopSequences: schemas_array(schemas_string()).optional(), + metadata: JSONObjectSchema.optional(), + tools: schemas_array(ToolSchema).optional(), + toolChoice: ToolChoiceSchema.optional() +}); +/** +* A request from the server to sample an LLM via the client. The client has full discretion over which model to select. The client should also inform the user before beginning sampling, to allow them to inspect the request (human in the loop) and decide whether to approve it. +* +* @deprecated Deprecated as of protocol version 2026-07-28 (SEP-2577); remains +* in the specification for at least twelve months. Migrate to calling LLM +* provider APIs directly. +*/ +const CreateMessageRequestSchema = RequestSchema.extend({ + method: literal("sampling/createMessage"), + params: CreateMessageRequestParamsSchema +}); +/** +* The client's response to a `sampling/create_message` request from the server. +* This is the backwards-compatible version that returns single content (no arrays). +* Used when the request does not include tools. +* +* @deprecated Deprecated as of protocol version 2026-07-28 (SEP-2577); remains +* in the specification for at least twelve months. Migrate to calling LLM +* provider APIs directly. +*/ +const CreateMessageResultSchema = ResultSchema.extend({ + model: schemas_string(), + stopReason: schemas_optional(schemas_enum([ + "endTurn", + "stopSequence", + "maxTokens" + ]).or(schemas_string())), + role: RoleSchema, + content: SamplingContentSchema +}); +/** +* The client's response to a `sampling/create_message` request when tools were provided. +* This version supports array content for tool use flows. +* +* @deprecated Deprecated as of protocol version 2026-07-28 (SEP-2577); remains +* in the specification for at least twelve months. Migrate to calling LLM +* provider APIs directly. +*/ +const CreateMessageResultWithToolsSchema = ResultSchema.extend({ + model: schemas_string(), + stopReason: schemas_optional(schemas_enum([ + "endTurn", + "stopSequence", + "maxTokens", + "toolUse" + ]).or(schemas_string())), + role: RoleSchema, + content: schemas_union([SamplingMessageContentBlockSchema, schemas_array(SamplingMessageContentBlockSchema)]) +}); +/** +* Primitive schema definition for boolean fields. +*/ +const BooleanSchemaSchema = schemas_object({ + type: literal("boolean"), + title: schemas_string().optional(), + description: schemas_string().optional(), + default: schemas_boolean().optional() +}); +/** +* Primitive schema definition for string fields. +*/ +const StringSchemaSchema = schemas_object({ + type: literal("string"), + title: schemas_string().optional(), + description: schemas_string().optional(), + minLength: schemas_number().optional(), + maxLength: schemas_number().optional(), + format: schemas_enum([ + "email", + "uri", + "date", + "date-time" + ]).optional(), + default: schemas_string().optional() +}); +/** +* Primitive schema definition for number fields. +*/ +const NumberSchemaSchema = schemas_object({ + type: schemas_enum(["number", "integer"]), + title: schemas_string().optional(), + description: schemas_string().optional(), + minimum: schemas_number().optional(), + maximum: schemas_number().optional(), + default: schemas_number().optional() +}); +/** +* Schema for single-selection enumeration without display titles for options. +*/ +const UntitledSingleSelectEnumSchemaSchema = schemas_object({ + type: literal("string"), + title: schemas_string().optional(), + description: schemas_string().optional(), + enum: schemas_array(schemas_string()), + default: schemas_string().optional() +}); +/** +* Schema for single-selection enumeration with display titles for each option. +*/ +const TitledSingleSelectEnumSchemaSchema = schemas_object({ + type: literal("string"), + title: schemas_string().optional(), + description: schemas_string().optional(), + oneOf: schemas_array(schemas_object({ + const: schemas_string(), + title: schemas_string() + })), + default: schemas_string().optional() +}); +/** +* Use {@linkcode TitledSingleSelectEnumSchema} instead. +* This interface will be removed in a future version. +*/ +const LegacyTitledEnumSchemaSchema = schemas_object({ + type: literal("string"), + title: schemas_string().optional(), + description: schemas_string().optional(), + enum: schemas_array(schemas_string()), + enumNames: schemas_array(schemas_string()).optional(), + default: schemas_string().optional() +}); +const SingleSelectEnumSchemaSchema = schemas_union([UntitledSingleSelectEnumSchemaSchema, TitledSingleSelectEnumSchemaSchema]); +/** +* Schema for multiple-selection enumeration without display titles for options. +*/ +const UntitledMultiSelectEnumSchemaSchema = schemas_object({ + type: literal("array"), + title: schemas_string().optional(), + description: schemas_string().optional(), + minItems: schemas_number().optional(), + maxItems: schemas_number().optional(), + items: schemas_object({ + type: literal("string"), + enum: schemas_array(schemas_string()) + }), + default: schemas_array(schemas_string()).optional() +}); +/** +* Schema for multiple-selection enumeration with display titles for each option. +*/ +const TitledMultiSelectEnumSchemaSchema = schemas_object({ + type: literal("array"), + title: schemas_string().optional(), + description: schemas_string().optional(), + minItems: schemas_number().optional(), + maxItems: schemas_number().optional(), + items: schemas_object({ anyOf: schemas_array(schemas_object({ + const: schemas_string(), + title: schemas_string() + })) }), + default: schemas_array(schemas_string()).optional() +}); +/** +* Combined schema for multiple-selection enumeration +*/ +const MultiSelectEnumSchemaSchema = schemas_union([UntitledMultiSelectEnumSchemaSchema, TitledMultiSelectEnumSchemaSchema]); +/** +* Primitive schema definition for enum fields. +*/ +const EnumSchemaSchema = schemas_union([ + LegacyTitledEnumSchemaSchema, + SingleSelectEnumSchemaSchema, + MultiSelectEnumSchemaSchema +]); +/** +* Union of all primitive schema definitions. +*/ +const PrimitiveSchemaDefinitionSchema = schemas_union([ + EnumSchemaSchema, + BooleanSchemaSchema, + StringSchemaSchema, + NumberSchemaSchema +]); +/** +* Parameters for an `elicitation/create` request for form-based elicitation. +*/ +const ElicitRequestFormParamsSchema = auth_CUe6YdwF_TaskAugmentedRequestParamsSchema.extend({ + mode: literal("form").optional(), + message: schemas_string(), + requestedSchema: schemas_object({ + type: literal("object"), + properties: schemas_record(schemas_string(), PrimitiveSchemaDefinitionSchema), + required: schemas_array(schemas_string()).optional() + }).catchall(unknown()) +}); +/** +* Parameters for an {@linkcode ElicitRequest | elicitation/create} request for URL-based elicitation. +*/ +const ElicitRequestURLParamsSchema = auth_CUe6YdwF_TaskAugmentedRequestParamsSchema.extend({ + mode: literal("url"), + message: schemas_string(), + elicitationId: schemas_string(), + url: schemas_string().url() +}); +/** +* The parameters for a request to elicit additional information from the user via the client. +*/ +const ElicitRequestParamsSchema = schemas_union([ElicitRequestFormParamsSchema, ElicitRequestURLParamsSchema]); +/** +* A request from the server to elicit user input via the client. +* The client should present the message and form fields to the user (form mode) +* or navigate to a URL (URL mode). +*/ +const ElicitRequestSchema = RequestSchema.extend({ + method: literal("elicitation/create"), + params: ElicitRequestParamsSchema +}); +/** +* Parameters for a {@linkcode ElicitationCompleteNotification | notifications/elicitation/complete} notification. +* +* @deprecated Removed from the spec by #2891 (2026-07-28). The client learns the outcome +* of an out-of-band interaction by retrying the original request; no server-initiated +* completion signal exists in the 2026-07-28 revision. Kept here for the 2025-era flow +* only. The 2026-07-28 wire codec excludes this notification. +* @category notifications/elicitation/complete +*/ +const ElicitationCompleteNotificationParamsSchema = NotificationsParamsSchema.extend({ elicitationId: schemas_string() }); +/** +* A notification from the server to the client, informing it of a completion of an out-of-band elicitation request. +* +* @deprecated Removed from the spec by #2891 (2026-07-28). The client learns the outcome +* of an out-of-band interaction by retrying the original request; no server-initiated +* completion signal exists in the 2026-07-28 revision. Kept here for the 2025-era flow +* only. The 2026-07-28 wire codec excludes this notification. +* @category notifications/elicitation/complete +*/ +const ElicitationCompleteNotificationSchema = NotificationSchema.extend({ + method: literal("notifications/elicitation/complete"), + params: ElicitationCompleteNotificationParamsSchema +}); +/** +* The client's response to an {@linkcode ElicitRequest | elicitation/create} request from the server. +*/ +const ElicitResultSchema = ResultSchema.extend({ + action: schemas_enum([ + "accept", + "decline", + "cancel" + ]), + content: preprocess((val) => val === null ? void 0 : val, schemas_record(schemas_string(), schemas_union([ + schemas_string(), + schemas_number(), + schemas_boolean(), + schemas_array(schemas_string()) + ])).optional()) +}); +/** +* A reference to a resource or resource template definition. +*/ +const ResourceTemplateReferenceSchema = schemas_object({ + type: literal("ref/resource"), + uri: schemas_string() +}); +/** +* Identifies a prompt. +*/ +const PromptReferenceSchema = schemas_object({ + type: literal("ref/prompt"), + name: schemas_string() +}); +/** +* Parameters for a {@linkcode CompleteRequest | completion/complete} request. +*/ +const CompleteRequestParamsSchema = BaseRequestParamsSchema.extend({ + ref: schemas_union([PromptReferenceSchema, ResourceTemplateReferenceSchema]), + argument: schemas_object({ + name: schemas_string(), + value: schemas_string() + }), + context: schemas_object({ arguments: schemas_record(schemas_string(), schemas_string()).optional() }).optional() +}); +/** +* A request from the client to the server, to ask for completion options. +*/ +const CompleteRequestSchema = RequestSchema.extend({ + method: literal("completion/complete"), + params: CompleteRequestParamsSchema +}); +/** +* The server's response to a {@linkcode CompleteRequest | completion/complete} request +*/ +const CompleteResultSchema = ResultSchema.extend({ completion: looseObject({ + values: schemas_array(schemas_string()).max(100), + total: schemas_optional(schemas_number().int()), + hasMore: schemas_optional(schemas_boolean()) +}) }); +/** +* Represents a root directory or file that the server can operate on. +* +* @deprecated Deprecated as of protocol version 2026-07-28 (SEP-2577); remains +* in the specification for at least twelve months. Migrate to passing paths via +* tool parameters, resource URIs, or configuration. +*/ +const RootSchema = schemas_object({ + uri: schemas_string().startsWith("file://"), + name: schemas_string().optional(), + _meta: schemas_record(schemas_string(), unknown()).optional() +}); +/** +* Sent from the server to request a list of root URIs from the client. +* +* @deprecated Deprecated as of protocol version 2026-07-28 (SEP-2577); remains +* in the specification for at least twelve months. Migrate to passing paths via +* tool parameters, resource URIs, or configuration. +*/ +const ListRootsRequestSchema = RequestSchema.extend({ + method: literal("roots/list"), + params: BaseRequestParamsSchema.optional() +}); +/** +* The client's response to a `roots/list` request from the server. +* +* @deprecated Deprecated as of protocol version 2026-07-28 (SEP-2577); remains +* in the specification for at least twelve months. Migrate to passing paths via +* tool parameters, resource URIs, or configuration. +*/ +const ListRootsResultSchema = ResultSchema.extend({ roots: schemas_array(RootSchema) }); +/** +* A notification from the client to the server, informing it that the list of roots has changed. +* +* @deprecated Deprecated as of protocol version 2026-07-28 (SEP-2577); remains +* in the specification for at least twelve months. Migrate to passing paths via +* tool parameters, resource URIs, or configuration. +*/ +const RootsListChangedNotificationSchema = NotificationSchema.extend({ + method: literal("notifications/roots/list_changed"), + params: NotificationsParamsSchema.optional() +}); +/** +* Task creation parameters, used to ask that the server create a task to represent a request. +* +* @deprecated 2025-11-25 wire vocabulary with no SDK runtime; kept importable for interoperability only. +*/ +const TaskCreationParamsSchema = looseObject({ + ttl: schemas_number().optional(), + pollInterval: schemas_number().optional() +}); +/** +* The status of a task. +* +* @deprecated 2025-11-25 wire vocabulary with no SDK runtime; kept importable for interoperability only. +*/ +const TaskStatusSchema = schemas_enum([ + "working", + "input_required", + "completed", + "failed", + "cancelled" +]); +/** +* A pollable state object associated with a request. +* +* @deprecated 2025-11-25 wire vocabulary with no SDK runtime; kept importable for interoperability only. +*/ +const TaskSchema = schemas_object({ + taskId: schemas_string(), + status: TaskStatusSchema, + ttl: schemas_union([schemas_number(), schemas_null()]), + createdAt: schemas_string(), + lastUpdatedAt: schemas_string(), + pollInterval: schemas_optional(schemas_number()), + statusMessage: schemas_optional(schemas_string()) +}); +/** +* Result returned when a task is created, containing the task data wrapped in a `task` field. +* +* @deprecated 2025-11-25 wire vocabulary with no SDK runtime; kept importable for interoperability only. +*/ +const CreateTaskResultSchema = ResultSchema.extend({ task: TaskSchema }); +/** +* Parameters for task status notification. +* +* @deprecated 2025-11-25 wire vocabulary with no SDK runtime; kept importable for interoperability only. +*/ +const TaskStatusNotificationParamsSchema = NotificationsParamsSchema.merge(TaskSchema); +/** +* A notification sent when a task's status changes. +* +* @deprecated 2025-11-25 wire vocabulary with no SDK runtime; kept importable for interoperability only. +*/ +const TaskStatusNotificationSchema = NotificationSchema.extend({ + method: literal("notifications/tasks/status"), + params: TaskStatusNotificationParamsSchema +}); +/** +* A request to get the state of a specific task. +* +* @deprecated 2025-11-25 wire vocabulary with no SDK runtime; kept importable for interoperability only. +*/ +const GetTaskRequestSchema = RequestSchema.extend({ + method: literal("tasks/get"), + params: BaseRequestParamsSchema.extend({ taskId: schemas_string() }) +}); +/** +* The response to a {@linkcode GetTaskRequest | tasks/get} request. +* +* @deprecated 2025-11-25 wire vocabulary with no SDK runtime; kept importable for interoperability only. +*/ +const GetTaskResultSchema = ResultSchema.merge(TaskSchema); +/** +* A request to get the result of a specific task. +* +* @deprecated 2025-11-25 wire vocabulary with no SDK runtime; kept importable for interoperability only. +*/ +const GetTaskPayloadRequestSchema = RequestSchema.extend({ + method: literal("tasks/result"), + params: BaseRequestParamsSchema.extend({ taskId: schemas_string() }) +}); +/** +* The response to a `tasks/result` request. +* The structure matches the result type of the original request. +* For example, a {@linkcode CallToolRequest | tools/call} task would return the `CallToolResult` structure. +* +* +* @deprecated 2025-11-25 wire vocabulary with no SDK runtime; kept importable for interoperability only. +*/ +const GetTaskPayloadResultSchema = ResultSchema.loose(); +/** +* A request to list tasks. +* +* @deprecated 2025-11-25 wire vocabulary with no SDK runtime; kept importable for interoperability only. +*/ +const ListTasksRequestSchema = PaginatedRequestSchema.extend({ method: literal("tasks/list") }); +/** +* The response to a {@linkcode ListTasksRequest | tasks/list} request. +* +* @deprecated 2025-11-25 wire vocabulary with no SDK runtime; kept importable for interoperability only. +*/ +const ListTasksResultSchema = PaginatedResultSchema.extend({ tasks: schemas_array(TaskSchema) }); +/** +* A request to cancel a specific task. +* +* @deprecated 2025-11-25 wire vocabulary with no SDK runtime; kept importable for interoperability only. +*/ +const CancelTaskRequestSchema = RequestSchema.extend({ + method: literal("tasks/cancel"), + params: BaseRequestParamsSchema.extend({ taskId: schemas_string() }) +}); +/** +* The response to a {@linkcode CancelTaskRequest | tasks/cancel} request. +* +* @deprecated 2025-11-25 wire vocabulary with no SDK runtime; kept importable for interoperability only. +*/ +const CancelTaskResultSchema = ResultSchema.merge(TaskSchema); +const ClientRequestSchema = schemas_union([ + PingRequestSchema, + auth_CUe6YdwF_InitializeRequestSchema, + DiscoverRequestSchema, + CompleteRequestSchema, + SetLevelRequestSchema, + GetPromptRequestSchema, + ListPromptsRequestSchema, + ListResourcesRequestSchema, + ListResourceTemplatesRequestSchema, + ReadResourceRequestSchema, + SubscribeRequestSchema, + UnsubscribeRequestSchema, + SubscriptionsListenRequestSchema, + CallToolRequestSchema, + ListToolsRequestSchema +]); +const ClientNotificationSchema = schemas_union([ + CancelledNotificationSchema, + ProgressNotificationSchema, + auth_CUe6YdwF_InitializedNotificationSchema, + RootsListChangedNotificationSchema +]); +const ClientResultSchema = schemas_union([ + EmptyResultSchema, + CreateMessageResultSchema, + CreateMessageResultWithToolsSchema, + ElicitResultSchema, + ListRootsResultSchema +]); +const ServerRequestSchema = schemas_union([ + PingRequestSchema, + CreateMessageRequestSchema, + ElicitRequestSchema, + ListRootsRequestSchema +]); +const ServerNotificationSchema = schemas_union([ + CancelledNotificationSchema, + ProgressNotificationSchema, + LoggingMessageNotificationSchema, + ResourceUpdatedNotificationSchema, + ResourceListChangedNotificationSchema, + ToolListChangedNotificationSchema, + PromptListChangedNotificationSchema, + SubscriptionsAcknowledgedNotificationSchema, + ElicitationCompleteNotificationSchema +]); +const ServerResultSchema = schemas_union([ + EmptyResultSchema, + InitializeResultSchema, + DiscoverResultSchema, + CompleteResultSchema, + GetPromptResultSchema, + ListPromptsResultSchema, + ListResourcesResultSchema, + ListResourceTemplatesResultSchema, + ReadResourceResultSchema, + auth_CUe6YdwF_CallToolResultSchema, + ListToolsResultSchema, + SubscriptionsListenResultSchema +]); + +//#endregion +//#region src/auth.ts +/** +* Reusable URL validation that disallows `javascript:` scheme +*/ +const SafeUrlSchema = schemas_url().superRefine((val, ctx) => { + if (!URL.canParse(val)) { + ctx.addIssue({ + code: ZodIssueCode.custom, + message: "URL must be parseable", + fatal: true + }); + return NEVER; + } +}).refine((url) => { + const u = new URL(url); + return u.protocol !== "javascript:" && u.protocol !== "data:" && u.protocol !== "vbscript:"; +}, { message: "URL cannot use javascript:, data:, or vbscript: scheme" }); +/** +* RFC 9728 OAuth Protected Resource Metadata +*/ +const OAuthProtectedResourceMetadataSchema = looseObject({ + resource: schemas_string().url(), + authorization_servers: schemas_array(SafeUrlSchema).optional(), + jwks_uri: schemas_string().url().optional(), + scopes_supported: schemas_array(schemas_string()).optional(), + bearer_methods_supported: schemas_array(schemas_string()).optional(), + resource_signing_alg_values_supported: schemas_array(schemas_string()).optional(), + resource_name: schemas_string().optional(), + resource_documentation: schemas_string().optional(), + resource_policy_uri: schemas_string().url().optional(), + resource_tos_uri: schemas_string().url().optional(), + tls_client_certificate_bound_access_tokens: schemas_boolean().optional(), + authorization_details_types_supported: schemas_array(schemas_string()).optional(), + dpop_signing_alg_values_supported: schemas_array(schemas_string()).optional(), + dpop_bound_access_tokens_required: schemas_boolean().optional() +}); +/** +* RFC 8414 OAuth 2.0 Authorization Server Metadata +*/ +const OAuthMetadataSchema = looseObject({ + issuer: schemas_string(), + authorization_endpoint: SafeUrlSchema, + token_endpoint: SafeUrlSchema, + registration_endpoint: SafeUrlSchema.optional(), + scopes_supported: schemas_array(schemas_string()).optional(), + response_types_supported: schemas_array(schemas_string()), + response_modes_supported: schemas_array(schemas_string()).optional(), + grant_types_supported: schemas_array(schemas_string()).optional(), + token_endpoint_auth_methods_supported: schemas_array(schemas_string()).optional(), + token_endpoint_auth_signing_alg_values_supported: schemas_array(schemas_string()).optional(), + service_documentation: SafeUrlSchema.optional(), + revocation_endpoint: SafeUrlSchema.optional(), + revocation_endpoint_auth_methods_supported: schemas_array(schemas_string()).optional(), + revocation_endpoint_auth_signing_alg_values_supported: schemas_array(schemas_string()).optional(), + introspection_endpoint: schemas_string().optional(), + introspection_endpoint_auth_methods_supported: schemas_array(schemas_string()).optional(), + introspection_endpoint_auth_signing_alg_values_supported: schemas_array(schemas_string()).optional(), + code_challenge_methods_supported: schemas_array(schemas_string()).optional(), + client_id_metadata_document_supported: schemas_boolean().optional(), + authorization_response_iss_parameter_supported: schemas_boolean().optional().catch(void 0) +}); +/** +* OpenID Connect Discovery 1.0 Provider Metadata +* +* @see https://openid.net/specs/openid-connect-discovery-1_0.html#ProviderMetadata +*/ +const OpenIdProviderMetadataSchema = looseObject({ + issuer: schemas_string(), + authorization_endpoint: SafeUrlSchema, + token_endpoint: SafeUrlSchema, + userinfo_endpoint: SafeUrlSchema.optional(), + jwks_uri: SafeUrlSchema, + registration_endpoint: SafeUrlSchema.optional(), + scopes_supported: schemas_array(schemas_string()).optional(), + response_types_supported: schemas_array(schemas_string()), + response_modes_supported: schemas_array(schemas_string()).optional(), + grant_types_supported: schemas_array(schemas_string()).optional(), + acr_values_supported: schemas_array(schemas_string()).optional(), + subject_types_supported: schemas_array(schemas_string()), + id_token_signing_alg_values_supported: schemas_array(schemas_string()), + id_token_encryption_alg_values_supported: schemas_array(schemas_string()).optional(), + id_token_encryption_enc_values_supported: schemas_array(schemas_string()).optional(), + userinfo_signing_alg_values_supported: schemas_array(schemas_string()).optional(), + userinfo_encryption_alg_values_supported: schemas_array(schemas_string()).optional(), + userinfo_encryption_enc_values_supported: schemas_array(schemas_string()).optional(), + request_object_signing_alg_values_supported: schemas_array(schemas_string()).optional(), + request_object_encryption_alg_values_supported: schemas_array(schemas_string()).optional(), + request_object_encryption_enc_values_supported: schemas_array(schemas_string()).optional(), + token_endpoint_auth_methods_supported: schemas_array(schemas_string()).optional(), + token_endpoint_auth_signing_alg_values_supported: schemas_array(schemas_string()).optional(), + display_values_supported: schemas_array(schemas_string()).optional(), + claim_types_supported: schemas_array(schemas_string()).optional(), + claims_supported: schemas_array(schemas_string()).optional(), + service_documentation: schemas_string().optional(), + claims_locales_supported: schemas_array(schemas_string()).optional(), + ui_locales_supported: schemas_array(schemas_string()).optional(), + claims_parameter_supported: schemas_boolean().optional(), + request_parameter_supported: schemas_boolean().optional(), + request_uri_parameter_supported: schemas_boolean().optional(), + require_request_uri_registration: schemas_boolean().optional(), + op_policy_uri: SafeUrlSchema.optional(), + op_tos_uri: SafeUrlSchema.optional(), + client_id_metadata_document_supported: schemas_boolean().optional(), + authorization_response_iss_parameter_supported: schemas_boolean().optional().catch(void 0) +}); +/** +* OpenID Connect Discovery metadata that may include OAuth 2.0 fields +* This schema represents the real-world scenario where OIDC providers +* return a mix of OpenID Connect and OAuth 2.0 metadata fields +*/ +const OpenIdProviderDiscoveryMetadataSchema = schemas_object({ + ...OpenIdProviderMetadataSchema.shape, + ...OAuthMetadataSchema.pick({ code_challenge_methods_supported: true }).shape +}); +/** +* OAuth 2.1 token response +*/ +const OAuthTokensSchema = schemas_object({ + access_token: schemas_string(), + id_token: schemas_string().optional(), + token_type: schemas_string(), + expires_in: coerce_number().optional(), + scope: schemas_string().optional(), + refresh_token: schemas_string().optional() +}).strip(); +/** +* RFC 8693 §2.2.1 Token Exchange response for ID-JAG tokens. +* +* `token_type` is intentionally optional: per RFC 8693 §2.2.1 it is informational when +* the issued token is not an access token, and per RFC 6749 §5.1 it is case-insensitive, +* so strict checking rejects conformant IdPs. +*/ +const IdJagTokenExchangeResponseSchema = schemas_object({ + issued_token_type: literal("urn:ietf:params:oauth:token-type:id-jag"), + access_token: schemas_string(), + token_type: schemas_string().optional(), + expires_in: schemas_number().optional(), + scope: schemas_string().optional() +}).strip(); +/** +* OAuth 2.1 error response +*/ +const OAuthErrorResponseSchema = schemas_object({ + error: schemas_string(), + error_description: schemas_string().optional(), + error_uri: schemas_string().optional() +}); +/** +* Optional version of {@linkcode SafeUrlSchema} that allows empty string for backward compatibility on `tos_uri` and `logo_uri` +*/ +const OptionalSafeUrlSchema = SafeUrlSchema.optional().or(literal("").transform(() => void 0)); +/** +* RFC 7591 OAuth 2.0 Dynamic Client Registration metadata +*/ +const OAuthClientMetadataSchema = schemas_object({ + redirect_uris: schemas_array(SafeUrlSchema), + token_endpoint_auth_method: schemas_string().optional(), + grant_types: schemas_array(schemas_string()).optional(), + response_types: schemas_array(schemas_string()).optional(), + application_type: schemas_string().optional(), + client_name: schemas_string().optional(), + client_uri: SafeUrlSchema.optional(), + logo_uri: OptionalSafeUrlSchema, + scope: schemas_string().optional(), + contacts: schemas_array(schemas_string()).optional(), + tos_uri: OptionalSafeUrlSchema, + policy_uri: schemas_string().optional(), + jwks_uri: SafeUrlSchema.optional(), + jwks: any().optional(), + software_id: schemas_string().optional(), + software_version: schemas_string().optional(), + software_statement: schemas_string().optional() +}).strip(); +/** +* RFC 7591 OAuth 2.0 Dynamic Client Registration client information +*/ +const OAuthClientInformationSchema = schemas_object({ + client_id: schemas_string(), + client_secret: schemas_string().optional(), + client_id_issued_at: schemas_number().optional(), + client_secret_expires_at: schemas_number().optional() +}).strip(); +/** +* RFC 7591 OAuth 2.0 Dynamic Client Registration full response (client information plus metadata) +*/ +const OAuthClientInformationFullSchema = OAuthClientMetadataSchema.merge(OAuthClientInformationSchema); +/** +* RFC 7591 OAuth 2.0 Dynamic Client Registration error response +*/ +const OAuthClientRegistrationErrorSchema = schemas_object({ + error: schemas_string(), + error_description: schemas_string().optional() +}).strip(); +/** +* RFC 7009 OAuth 2.0 Token Revocation request +*/ +const OAuthTokenRevocationRequestSchema = schemas_object({ + token: schemas_string(), + token_type_hint: schemas_string().optional() +}).strip(); + +//#endregion + +//# sourceMappingURL=auth-CUe6YdwF.mjs.map + + + + + + + + +//#region ../core-internal/src/errors/crossBundleBrand.ts +/** +* Cross-bundle `instanceof` support for the SDK error classes. +* +* `@modelcontextprotocol/client` and `@modelcontextprotocol/server` each bundle their +* own copy of `core-internal`, so an error constructed by one package fails a +* prototype-identity `instanceof` against the same class re-exported by the other — +* exactly the check a dual-role process (gateway, host, in-process test) writes. +* +* Instead of prototype identity, branded classes stamp every instance with the brand +* strings of its class chain under a registry symbol (`Symbol.for`, shared across +* bundles and realms), and resolve `instanceof` via `Symbol.hasInstance` against the +* brand set. Ordinary prototype-based `instanceof` is kept as a fallback so behavior +* is unchanged for anything unbranded. +* +* A class participates by defining an **own** `mcpBrand` static (via a `static {}` +* block, so nothing reaches the declaration files — a declared `protected static` +* field would make the constructor types nominally incompatible across the bundled +* copies) and (for hierarchy roots) installing {@linkcode brandedHasInstance} as +* `Symbol.hasInstance`. User-defined subclasses that do not declare their own brand +* keep plain prototype semantics — a foreign base-class instance never satisfies +* `instanceof UserSubclass`. +* +* Prior art — the same stamp-and-hook shape ships at scale elsewhere: Node core +* (stream.Writable since 2017, Console via a marker symbol, diagnostics_channel), +* undici's whole error hierarchy (vendored into Node as fetch), googleapis/gaxios +* (GaxiosError, Symbol.for marker), AWS SDK v3's ServiceException (which pairs a +* Symbol.hasInstance override with a static isInstance guard, as we do), and zod v4 +* (Symbol.hasInstance on every schema class for cross-version interop). +* +* Contract notes: +* - Participation criterion: **every error class exported from a public package that +* callers are documented to `instanceof` must be branded.** The per-package +* errorBrandConformance tests walk the export surfaces and fail naming any +* exported Error subclass that has not opted in. +* - Brands assert **identity, not shape**: brand strings are version-less, so an +* instance from one SDK version matches the class of another. Members added to a +* branded class in a later version may be absent on a matched instance — read +* fields defensively, and treat branded classes as additive-only. The escape +* hatch when a release must break a branded class's read contract: change that +* class's brand string in the same release, which cleanly severs cross-version +* matching for that class. The per-package brand pins make the rename +* deliberate: errorSurfacePins.test.ts owns the core-internal brands, and each +* package's errorBrandConformance test pins its package-local ones. +* - Cross-bundle matching requires **both** copies to be at or after the release +* that introduced branding; against an older copy, behavior degrades to plain +* prototype `instanceof` in both directions. +* - A consumer re-bundling the SDK with property mangling (`mangle.props`) would +* break the brand statics; default esbuild/webpack/terser settings do not. +*/ +/** Registry symbol — identical across bundled copies and realms. */ +const BRANDS = Symbol.for("mcp.sdk.errorBrands"); +/** +* Stamp `instance` with the brand of every class in `ctor`'s chain that declares an +* own `mcpBrand`. Call once from the hierarchy root's constructor with `new.target` — +* subclasses inherit the stamping without touching their constructors. +* +* Constructor-time only: never stamp arbitrary objects. A stamped non-instance would +* satisfy `instanceof` while lacking the prototype members (getters like `.status`) +* that callers reach for after the check. +*/ +function stampErrorBrands(instance, ctor) { + const brands = /* @__PURE__ */ new Set(); + let current = ctor; + while (typeof current === "function") { + const brand = current.mcpBrand; + if (Object.prototype.hasOwnProperty.call(current, "mcpBrand") && typeof brand === "string") brands.add(brand); + current = Object.getPrototypeOf(current); + } + if (brands.size === 0) return; + Object.defineProperty(instance, BRANDS, { + value: brands, + enumerable: false, + configurable: true + }); +} +/** +* `Symbol.hasInstance` implementation for branded hierarchy roots. Matches when the +* value carries the **own** brand of the class being tested against (cross-bundle +* path), falling back to ordinary prototype-based `instanceof` otherwise. +*/ +function brandedHasInstance(cls, value) { + try { + if (typeof value === "object" && value !== null && Object.prototype.hasOwnProperty.call(cls, "mcpBrand") && typeof cls.mcpBrand === "string" && Object.prototype.hasOwnProperty.call(value, BRANDS)) { + const carried = value[BRANDS]; + if (carried && typeof carried.has === "function" && carried.has(cls.mcpBrand)) return true; + } + } catch {} + return Function.prototype[Symbol.hasInstance].call(cls, value); +} + +//#endregion +//#region ../core-internal/src/auth/errors.ts +/** +* OAuth error codes as defined by {@link https://datatracker.ietf.org/doc/html/rfc6749#section-5.2 | RFC 6749} +* and extensions. +*/ +let src_CX2iR2pK_OAuthErrorCode = /* @__PURE__ */ (/* unused pure expression or super */ null && (function(OAuthErrorCode$1) { + /** + * The request is missing a required parameter, includes an invalid parameter value, + * includes a parameter more than once, or is otherwise malformed. + */ + OAuthErrorCode$1["InvalidRequest"] = "invalid_request"; + /** + * Client authentication failed (e.g., unknown client, no client authentication included, + * or unsupported authentication method). + */ + OAuthErrorCode$1["InvalidClient"] = "invalid_client"; + /** + * The provided authorization grant or refresh token is invalid, expired, revoked, + * does not match the redirection URI used in the authorization request, or was issued to another client. + */ + OAuthErrorCode$1["InvalidGrant"] = "invalid_grant"; + /** + * The authenticated client is not authorized to use this authorization grant type. + */ + OAuthErrorCode$1["UnauthorizedClient"] = "unauthorized_client"; + /** + * The authorization grant type is not supported by the authorization server. + */ + OAuthErrorCode$1["UnsupportedGrantType"] = "unsupported_grant_type"; + /** + * The requested scope is invalid, unknown, malformed, or exceeds the scope granted by the resource owner. + */ + OAuthErrorCode$1["InvalidScope"] = "invalid_scope"; + /** + * The resource owner or authorization server denied the request. + */ + OAuthErrorCode$1["AccessDenied"] = "access_denied"; + /** + * The authorization server encountered an unexpected condition that prevented it from fulfilling the request. + */ + OAuthErrorCode$1["ServerError"] = "server_error"; + /** + * The authorization server is currently unable to handle the request due to temporary overloading or maintenance. + */ + OAuthErrorCode$1["TemporarilyUnavailable"] = "temporarily_unavailable"; + /** + * The authorization server does not support obtaining an authorization code using this method. + */ + OAuthErrorCode$1["UnsupportedResponseType"] = "unsupported_response_type"; + /** + * The authorization server does not support the requested token type. + */ + OAuthErrorCode$1["UnsupportedTokenType"] = "unsupported_token_type"; + /** + * The access token provided is expired, revoked, malformed, or invalid for other reasons. + */ + OAuthErrorCode$1["InvalidToken"] = "invalid_token"; + /** + * The HTTP method used is not allowed for this endpoint. (Custom, non-standard error) + */ + OAuthErrorCode$1["MethodNotAllowed"] = "method_not_allowed"; + /** + * Rate limit exceeded. (Custom, non-standard error based on RFC 6585) + */ + OAuthErrorCode$1["TooManyRequests"] = "too_many_requests"; + /** + * The client metadata is invalid. (Custom error for dynamic client registration - RFC 7591) + */ + OAuthErrorCode$1["InvalidClientMetadata"] = "invalid_client_metadata"; + /** + * The value of one or more redirection URIs is invalid. (Dynamic client registration - RFC 7591 §3.2.2) + */ + OAuthErrorCode$1["InvalidRedirectUri"] = "invalid_redirect_uri"; + /** + * The request requires higher privileges than provided by the access token. + */ + OAuthErrorCode$1["InsufficientScope"] = "insufficient_scope"; + /** + * The requested resource is invalid, missing, unknown, or malformed. (Custom error for resource indicators - RFC 8707) + */ + OAuthErrorCode$1["InvalidTarget"] = "invalid_target"; + return OAuthErrorCode$1; +}({}))); +/** +* OAuth error class for all OAuth-related errors. +*/ +var src_CX2iR2pK_OAuthError = class OAuthError extends Error { + static { + Object.defineProperty(this, "mcpBrand", { value: "mcp.OAuthError" }); + } + static [Symbol.hasInstance](value) { + return brandedHasInstance(this, value); + } + /** + * Brand-based type guard: equivalent to `value instanceof this`, as an + * explicit static predicate (the axios/AWS-SDK `isInstance` style). Reads + * the caller's own brand via `this`, so every branded subclass gets a + * correctly-scoped guard by inheritance. Must be invoked on the class — + * in callback position write `v => SdkError.isInstance(v)`, not + * `.filter(SdkError.isInstance)` (detached calls throw rather than + * silently matching nothing). + */ + static isInstance(value) { + 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 brandedHasInstance(this, value); + } + constructor(code, message, errorUri) { + super(message); + this.code = code; + this.errorUri = errorUri; + this.name = "OAuthError"; + stampErrorBrands(this, new.target); + } + /** + * Converts the error to a standard OAuth error response object. + */ + toResponseObject() { + const response = { + error: this.code, + error_description: this.message + }; + if (this.errorUri) response.error_uri = this.errorUri; + return response; + } + /** + * Creates an {@linkcode OAuthError} from an OAuth error response. + */ + static fromResponse(response) { + return new OAuthError(response.error, response.error_description ?? response.error, response.error_uri); + } +}; + +//#endregion +//#region ../core-internal/src/errors/sdkErrors.ts +/** +* Error codes for SDK errors (local errors that never cross the wire). +* Unlike {@linkcode ProtocolErrorCode} which uses numeric JSON-RPC codes, `SdkErrorCode` uses +* descriptive string values for better developer experience. +* +* These errors are thrown locally by the SDK and are never serialized as +* JSON-RPC error responses. +*/ +let src_CX2iR2pK_SdkErrorCode = /* @__PURE__ */ function(SdkErrorCode$1) { + /** Transport is not connected */ + SdkErrorCode$1["NotConnected"] = "NOT_CONNECTED"; + /** Transport is already connected */ + SdkErrorCode$1["AlreadyConnected"] = "ALREADY_CONNECTED"; + /** Protocol is not initialized */ + SdkErrorCode$1["NotInitialized"] = "NOT_INITIALIZED"; + /** Required capability is not supported by the remote side */ + SdkErrorCode$1["CapabilityNotSupported"] = "CAPABILITY_NOT_SUPPORTED"; + /** Request timed out waiting for response */ + SdkErrorCode$1["RequestTimeout"] = "REQUEST_TIMEOUT"; + /** Connection was closed */ + SdkErrorCode$1["ConnectionClosed"] = "CONNECTION_CLOSED"; + /** Failed to send message */ + SdkErrorCode$1["SendFailed"] = "SEND_FAILED"; + /** Response result failed local schema validation */ + SdkErrorCode$1["InvalidResult"] = "INVALID_RESULT"; + /** + * The response carried a `resultType` discriminator (protocol revision + * 2026-07-28) naming a result kind this client cannot consume yet, e.g. + * `input_required`. The kind is carried in `data.resultType`. + */ + SdkErrorCode$1["UnsupportedResultType"] = "UNSUPPORTED_RESULT_TYPE"; + /** + * The multi-round-trip auto-fulfilment driver exhausted its round cap + * (`inputRequired.maxRounds`) without the server returning a complete + * result. `data.rounds` carries the cap that was hit and + * `data.lastResult` carries the last `input_required` payload received + * (`{ inputRequests, requestState? }`), so callers can inspect or resume + * the flow manually. + */ + SdkErrorCode$1["InputRequiredRoundsExceeded"] = "INPUT_REQUIRED_ROUNDS_EXCEEDED"; + /** + * The auto-aggregating no-`cursor` `listTools()` / `listPrompts()` / + * `listResources()` / `listResourceTemplates()` walk hit the + * `ClientOptions.listMaxPages` cap without the server's pagination + * converging. `data.method` carries the list verb and + * `data.listMaxPages` the cap that was hit; raise the cap or fall back to + * explicit per-page `{ cursor }` calls. + */ + SdkErrorCode$1["ListPaginationExceeded"] = "LIST_PAGINATION_EXCEEDED"; + /** + * The spec method being sent does not exist on the negotiated protocol + * version's wire era (e.g. `tasks/get` toward a 2026-07-28 peer, or + * `server/discover` toward a 2025-era peer). Raised locally, before + * anything reaches the transport. The method and era are carried in + * `data.method` / `data.era`. + */ + SdkErrorCode$1["MethodNotSupportedByProtocolVersion"] = "METHOD_NOT_SUPPORTED_BY_PROTOCOL_VERSION"; + /** + * Protocol-era negotiation at connect time failed without producing either a + * usable modern (2026-07-28+) era or a definitive legacy fallback signal — + * e.g. the negotiation mode forbids falling back (`pin`), the probe hit a + * network failure, or the server answered the probe with a 5xx (a typed + * connect error, never an era verdict). + * + * Negotiation-phase only: this code is never used once an era is + * established. Auth walls never carry it: a 401/403 rejecting the probe + * uses {@linkcode ClientHttpAuthentication} / {@linkcode ClientHttpForbidden} + * instead, so era-recovery flows keyed on this code (e.g. cached-verdict + * gateways) can never persist a verdict for an unauthorized exchange. + */ + SdkErrorCode$1["EraNegotiationFailed"] = "ERA_NEGOTIATION_FAILED"; + SdkErrorCode$1["ClientHttpNotImplemented"] = "CLIENT_HTTP_NOT_IMPLEMENTED"; + /** + * HTTP 401 authentication failure: the transport's re-auth retry still got + * 401 (`Server returned 401 after re-authentication`), or the version + * negotiation probe was rejected 401 with no `authProvider` configured + * (`Version negotiation failed: the server requires authorization (HTTP 401)`). + * Carried on an {@linkcode SdkHttpError} with `status: 401`. + */ + SdkErrorCode$1["ClientHttpAuthentication"] = "CLIENT_HTTP_AUTHENTICATION"; + /** + * HTTP 403 denial: the step-up re-authorization retry limit was reached, + * or the version negotiation probe was rejected 403 + * (`Version negotiation failed: the server denied access (HTTP 403)`). + * Carried on an {@linkcode SdkHttpError} with `status: 403`. + */ + SdkErrorCode$1["ClientHttpForbidden"] = "CLIENT_HTTP_FORBIDDEN"; + SdkErrorCode$1["ClientHttpUnexpectedContent"] = "CLIENT_HTTP_UNEXPECTED_CONTENT"; + SdkErrorCode$1["ClientHttpFailedToOpenStream"] = "CLIENT_HTTP_FAILED_TO_OPEN_STREAM"; + SdkErrorCode$1["ClientHttpFailedToTerminateSession"] = "CLIENT_HTTP_FAILED_TO_TERMINATE_SESSION"; + return SdkErrorCode$1; +}({}); +/** +* SDK errors are local errors that never cross the wire. +* They are distinct from {@linkcode ProtocolError} which represents JSON-RPC protocol errors +* that are serialized and sent as error responses. +* +* @example +* ```ts source="./sdkErrors.examples.ts#SdkError_basicUsage" +* try { +* // Throwing an SDK error +* throw new SdkError(SdkErrorCode.NotConnected, 'Transport is not connected'); +* } catch (error) { +* // Checking error type by code +* if (error instanceof SdkError && error.code === SdkErrorCode.RequestTimeout) { +* // Handle timeout +* } +* } +* ``` +*/ +var src_CX2iR2pK_SdkError = class extends Error { + static { + Object.defineProperty(this, "mcpBrand", { value: "mcp.SdkError" }); + } + static [Symbol.hasInstance](value) { + return brandedHasInstance(this, value); + } + /** + * Brand-based type guard: equivalent to `value instanceof this`, as an + * explicit static predicate (the axios/AWS-SDK `isInstance` style). Reads + * the caller's own brand via `this`, so every branded subclass gets a + * correctly-scoped guard by inheritance. Must be invoked on the class — + * in callback position write `v => SdkError.isInstance(v)`, not + * `.filter(SdkError.isInstance)` (detached calls throw rather than + * silently matching nothing). + */ + static isInstance(value) { + 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 brandedHasInstance(this, value); + } + constructor(code, message, data) { + super(message); + this.code = code; + this.data = data; + this.name = "SdkError"; + stampErrorBrands(this, new.target); + } +}; +/** +* An {@linkcode SdkError} subclass for HTTP transport failures. +* +* Thrown by the streamable HTTP transport when the server responds with a +* non-OK status code. Narrows {@linkcode SdkError.data | data} to +* {@linkcode SdkHttpErrorData} so consumers can inspect the HTTP status +* without unsafe casting. +* +* @example +* ```ts source="./sdkErrors.examples.ts#SdkHttpError_basicUsage" +* if (error instanceof SdkHttpError) { +* console.log(error.status); // number +* console.log(error.statusText); // string | undefined +* } +* ``` +*/ +var SdkHttpError = class extends src_CX2iR2pK_SdkError { + static { + Object.defineProperty(this, "mcpBrand", { value: "mcp.SdkHttpError" }); + } + constructor(code, message, data) { + super(code, message, data); + this.name = "SdkHttpError"; + } + get status() { + return this.data.status; + } + get statusText() { + return this.data.statusText; + } +}; + +//#endregion +//#region ../core-internal/src/shared/authUtils.ts +/** +* Utilities for handling OAuth resource URIs. +*/ +/** +* Converts a server URL to a resource URL by removing the fragment. +* {@link https://datatracker.ietf.org/doc/html/rfc8707#section-2 | RFC 8707 section 2} +* states that resource URIs "MUST NOT include a fragment component". +* Keeps everything else unchanged (scheme, domain, port, path, query). +*/ +function resourceUrlFromServerUrl(url) { + const resourceURL = typeof url === "string" ? new URL(url) : new URL(url.href); + resourceURL.hash = ""; + return resourceURL; +} +/** +* Checks if a requested resource URL matches a configured resource URL. +* A requested resource matches if it has the same scheme, domain, port, +* and its path starts with the configured resource's path. +* +* @param options - The options object +* @param options.requestedResource - The resource URL being requested +* @param options.configuredResource - The resource URL that has been configured +* @returns true if the requested resource matches the configured resource, false otherwise +*/ +function checkResourceAllowed({ requestedResource, configuredResource }) { + const requested = typeof requestedResource === "string" ? new URL(requestedResource) : new URL(requestedResource.href); + const configured = typeof configuredResource === "string" ? new URL(configuredResource) : new URL(configuredResource.href); + if (requested.origin !== configured.origin) return false; + if (requested.pathname.length < configured.pathname.length) return false; + const requestedPath = requested.pathname.endsWith("/") ? requested.pathname : requested.pathname + "/"; + const configuredPath = configured.pathname.endsWith("/") ? configured.pathname : configured.pathname + "/"; + return requestedPath.startsWith(configuredPath); +} + +//#endregion +//#region ../core-internal/src/shared/clientCapabilityRequirements.ts +/** +* Inbound request methods whose processing structurally requires a client +* capability, keyed by method, valued by the capabilities required. +* +* Currently empty: none of the request methods served on the 2026-07-28 +* registry unconditionally requires a client capability. Entries appear here +* when such methods exist — for example requests whose handling embeds +* elicitation or sampling input requests (the input-request engine), or +* opt-in subscription delivery. Handler-conditional requirements (a specific +* tool that needs sampling) are not expressible as a static method table and +* are enforced at the point the requirement arises instead. +*/ +const REQUIRED_CLIENT_CAPABILITIES_BY_METHOD = (/* unused pure expression or super */ null && ({})); +/** +* The client capabilities a request method structurally requires, or +* `undefined` when the method has no static requirement. +*/ +function src_CX2iR2pK_requiredClientCapabilitiesForRequest(method) { + return Object.hasOwn(REQUIRED_CLIENT_CAPABILITIES_BY_METHOD, method) ? REQUIRED_CLIENT_CAPABILITIES_BY_METHOD[method] : void 0; +} +function isPlainObject$7(value) { + return value !== null && typeof value === "object" && !Array.isArray(value); +} +/** +* Whether a required nested member counts as declared even though it is not +* spelled out: a bare `elicitation: {}` declaration (no mode sub-capability at +* all) is read as form support — the pre-mode (2025) meaning of a bare +* declaration — so an `elicitation.form` requirement treats it as satisfied. +* Declaring any mode explicitly (for example `elicitation: { url: {} }`) +* removes the implication. +*/ +function isImpliedCapabilityMember(capability, member, declaredValue) { + return capability === "elicitation" && member === "form" && declaredValue["form"] === void 0 && declaredValue["url"] === void 0; +} +/** +* The client capabilities an embedded multi-round-trip input request requires +* (call site 2 — the outbound input-request leg): a server MUST NOT send an +* `inputRequests` kind the request's declared client capabilities do not +* cover. Returns `undefined` for entries whose method is not one of the +* embedded input-request kinds (those are a server bug handled separately, +* not a capability question). +* +* The requirement is mode-aware where the capability is: URL-mode elicitation +* requires `elicitation.url`; form-mode (or mode-omitted) elicitation requires +* `elicitation.form` (modes are sub-capabilities, and a server MUST NOT send a +* mode the client did not declare); sampling with `tools`/`toolChoice` +* requires `sampling.tools`. A bare `elicitation: {}` declaration satisfies +* the form requirement — see {@linkcode missingClientCapabilities}. +*/ +function requiredClientCapabilitiesForInputRequest(entry) { + switch (entry.method) { + case "elicitation/create": + if (entry.params?.["mode"] === "url") return { elicitation: { url: {} } }; + return { elicitation: { form: {} } }; + case "sampling/createMessage": { + const params = entry.params; + if (params !== void 0 && (params["tools"] !== void 0 || params["toolChoice"] !== void 0)) return { sampling: { tools: {} } }; + return { sampling: {} }; + } + case "roots/list": return { roots: {} }; + default: return; + } +} +/** +* Computes the subset of `required` client capabilities the client did not +* declare. Returns `undefined` when every required capability is declared; +* otherwise returns an object in the `ClientCapabilities` shape containing +* exactly the missing capabilities (suitable for +* `data.requiredCapabilities` on the `-32021` error). +* +* A capability counts as declared when its top-level key is present on the +* declared capabilities; when the requirement names nested members (for +* example `elicitation: { url: {} }`), each named member must also be present +* under the declared capability. One lenient reading applies: a bare +* `elicitation: {}` declaration (no mode sub-capability at all) counts as +* declaring `elicitation.form` — the pre-mode (2025) meaning of a bare +* declaration. An absent or empty `declared` value means +* nothing is declared — every required capability is missing (the structural +* clean-refusal posture for sessions with no per-request capability view). +*/ +function src_CX2iR2pK_missingClientCapabilities(required, declared) { + const missing = {}; + for (const [capability, requirement] of Object.entries(required)) { + if (requirement === void 0) continue; + const declaredValue = declared === void 0 ? void 0 : declared[capability]; + if (declaredValue === void 0) { + missing[capability] = requirement; + continue; + } + if (isPlainObject$7(requirement) && isPlainObject$7(declaredValue)) { + const missingMembers = {}; + for (const [member, memberRequirement] of Object.entries(requirement)) if (memberRequirement !== void 0 && declaredValue[member] === void 0 && !isImpliedCapabilityMember(capability, member, declaredValue)) missingMembers[member] = memberRequirement; + if (Object.keys(missingMembers).length > 0) missing[capability] = missingMembers; + } + } + return Object.keys(missing).length > 0 ? missing : void 0; +} + +//#endregion +//#region ../core-internal/src/shared/protocolEras.ts +/** +* The first protocol revision of the modern (2026-07-28) era. Revision identifiers +* are ISO dates, so lexicographic comparison orders them chronologically. +*/ +const FIRST_MODERN_PROTOCOL_VERSION = "2026-07-28"; +/** +* Modern-era protocol revisions this SDK can negotiate via `server/discover`. +* Deliberately separate from {@linkcode SUPPORTED_PROTOCOL_VERSIONS} (the legacy +* `initialize` list), so adding a revision here can never leak a modern version +* string into a 2025-era handshake. Internal — not part of the public API surface. +*/ +const src_CX2iR2pK_SUPPORTED_MODERN_PROTOCOL_VERSIONS = (/* unused pure expression or super */ null && ([FIRST_MODERN_PROTOCOL_VERSION])); +/** Whether the given protocol revision belongs to the modern (2026-07-28+) era. */ +function isModernProtocolVersion(version) { + return version >= FIRST_MODERN_PROTOCOL_VERSION; +} +/** The legacy-era (pre-2026-07-28) subset of a supported-versions list, in the list's own preference order. */ +function legacyProtocolVersions(versions) { + return versions.filter((version) => !isModernProtocolVersion(version)); +} +/** The modern-era (2026-07-28+) subset of a supported-versions list, in the list's own preference order. */ +function modernProtocolVersions(versions) { + return versions.filter((version) => isModernProtocolVersion(version)); +} + +//#endregion +//#region ../core-internal/src/wire/textFallback.ts +/** +* SEP-2106 §4.3 TextContent auto-append, era-agnostic, called from BOTH +* codecs' {@link WireCodec.projectCallToolResult}: when `structuredContent` +* is a non-object value (array/primitive/`null`) and the handler authored no +* `type:'text'` block, append `{type:'text', text: JSON.stringify(value)}`. +* Object-shaped (or absent) `structuredContent` returns the same reference. +* +* Leaf module: imported by both era codec modules, so it must NOT import from +* `./codec.js` (which value-imports the rev codecs at top level — that would +* make a runtime cycle and a TDZ hazard for entries that evaluate a rev codec +* module first). +*/ +function appendTextFallbackForNonObject(result) { + const sc = result.structuredContent; + if (sc === void 0) return result; + if (!(typeof sc !== "object" || sc === null || Array.isArray(sc))) return result; + if (result.content?.some((c) => c.type === "text") ?? false) return result; + return { + ...result, + content: [...result.content ?? [], { + type: "text", + text: JSON.stringify(sc) + }] + }; +} + +//#endregion +//#region ../core-internal/src/wire/resultFamilies.ts +/** +* Result-family keys that must never default into a `{content: []}` tools/call +* success. Shared by the 2025 wire-seam schema and server normalization. +* Leaf module (like `textFallback.ts`): imported by registry/server paths, so +* it must NOT import from `./codec.js` — that would close a runtime cycle. +*/ +const TOOL_RESULT_FOREIGN_FAMILY_KEYS = [ + "task", + "inputRequests", + "requestState" +]; +/** +* Single owner of the v1-parity ruling: a plain-object tool result without `content` (and +* without foreign-family keys) gains `content: []`. Shared by the 2025 wire seam and server-side handler normalization. +*/ +function normalizeContentlessToolResult(value) { + if (value === null || typeof value !== "object" || Array.isArray(value) || value.content !== void 0 || TOOL_RESULT_FOREIGN_FAMILY_KEYS.some((key) => key in value)) return value; + return { + ...value, + content: [] + }; +} + +//#endregion +//#region ../core-internal/src/wire/rev2025-11-25/buildSchemas.ts +/** +* Complete frozen 2025-11-25 wire schemas. Self-contained — no imports from +* the public/neutral types/schemas.ts. The neutral layer is the public-API +* superset and is free to evolve (e.g., SEP-2106 widening); this file is the +* 2025 wire-parse contract (Q10-L2 byte-identity) and is BEHAVIOR-FROZEN. +* +* This is the era's complete frozen wire-parse contract — both the 2025-only +* delta (the deprecated task family, the era role unions) AND frozen copies of +* every era-shared shape (Tool, CallToolResult, Initialize*, ContentBlock, +* prompts/resources/completion/elicitation, …). The 2026-era codec +* (`wire/rev2026-07-28/`) is symmetrically self-contained in the same way. +* +* The 2025-only delta (the task message surface, restored types-only by #2248 +* for interop with task-capable 2025 peers) is parsed ONLY through this era's +* registry; the deprecated Task* schemas also live (marked `@deprecated`) in +* the neutral schema layer so the public types stay nameable without a +* cross-layer import — nameability is constant, runtime availability is +* version-keyed — but appear in no API signature. Q1 increment 2 — deletions +* are physical: the +* 2026-era REGISTRY has no Task* methods (its frozen building-block copies do +* carry the deprecated Task* sub-schemas by composition — soft contamination, +* tracked for anchor-exactness adjudication). +* +* The only cross-layer dependency is `import type { JSONObject, JSONValue }` +* from the neutral types barrel — pure structural type aliases with no parse +* behavior. No runtime schema is shared with the neutral layer. +*/ +function build$1() { + const JSONValueSchema$1 = lazy(() => schemas_union([ + schemas_string(), + schemas_number(), + schemas_boolean(), + schemas_null(), + schemas_record(schemas_string(), JSONValueSchema$1), + schemas_array(JSONValueSchema$1) + ])); + const JSONObjectSchema$1 = schemas_record(schemas_string(), JSONValueSchema$1); + /** + * A progress token, used to associate progress notifications with the original request. + */ + const ProgressTokenSchema$1 = schemas_union([schemas_string(), schemas_number().int()]); + /** + * An opaque token used to represent a cursor for pagination. + */ + const CursorSchema$1 = schemas_string(); + /** @deprecated 2025-11-25 wire vocabulary with no SDK runtime; kept importable for interoperability only. */ + const TaskMetadataSchema$1 = schemas_object({ ttl: schemas_number().optional() }); + /** + * Metadata for associating messages with a task. + * Include this in the `_meta` field under the key `io.modelcontextprotocol/related-task`. + * + * @deprecated 2025-11-25 wire vocabulary with no SDK runtime; kept importable for interoperability only. + */ + const RelatedTaskMetadataSchema$1 = schemas_object({ taskId: schemas_string() }); + const RequestMetaSchema$1 = looseObject({ + progressToken: ProgressTokenSchema$1.optional(), + "io.modelcontextprotocol/related-task": RelatedTaskMetadataSchema$1.optional() + }); + /** + * Common params for any request. + */ + const BaseRequestParamsSchema$1 = schemas_object({ _meta: RequestMetaSchema$1.optional() }); + /** + * Common params for any task-augmented request. + * + * @deprecated 2025-11-25 wire vocabulary with no SDK runtime; kept importable for interoperability only. + */ + const TaskAugmentedRequestParamsSchema$1 = BaseRequestParamsSchema$1.extend({ task: TaskMetadataSchema$1.optional() }); + const RequestSchema$1 = schemas_object({ + method: schemas_string(), + params: BaseRequestParamsSchema$1.loose().optional() + }); + const NotificationsParamsSchema$1 = schemas_object({ _meta: RequestMetaSchema$1.optional() }); + const NotificationSchema$1 = schemas_object({ + method: schemas_string(), + params: NotificationsParamsSchema$1.loose().optional() + }); + const ResultSchema$1 = looseObject({ _meta: RequestMetaSchema$1.optional() }); + /** + * A uniquely identifying ID for a request in JSON-RPC. + */ + const RequestIdSchema$1 = schemas_union([schemas_string(), schemas_number().int()]); + /** + * A response that indicates success but carries no data. + */ + const EmptyResultSchema$1 = ResultSchema$1.strict(); + const CancelledNotificationParamsSchema$1 = NotificationsParamsSchema$1.extend({ + requestId: RequestIdSchema$1.optional(), + reason: schemas_string().optional() + }); + /** + * This notification can be sent by either side to indicate that it is cancelling a previously-issued request. + * + * The request SHOULD still be in-flight, but due to communication latency, it is always possible that this notification MAY arrive after the request has already finished. + * + * This notification indicates that the result will be unused, so any associated processing SHOULD cease. + * + * A client MUST NOT attempt to cancel its {@linkcode InitializeRequest | initialize} request. + */ + const CancelledNotificationSchema$1 = NotificationSchema$1.extend({ + method: literal("notifications/cancelled"), + params: CancelledNotificationParamsSchema$1 + }); + /** + * Icon schema for use in {@link Tool | tools}, {@link Prompt | prompts}, {@link Resource | resources}, and {@link Implementation | implementations}. + */ + const IconSchema$1 = schemas_object({ + src: schemas_string(), + mimeType: schemas_string().optional(), + sizes: schemas_array(schemas_string()).optional(), + theme: schemas_enum(["light", "dark"]).optional() + }); + /** + * Base schema to add `icons` property. + * + */ + const IconsSchema$1 = schemas_object({ icons: schemas_array(IconSchema$1).optional() }); + /** + * Base metadata interface for common properties across {@link Resource | resources}, {@link Tool | tools}, {@link Prompt | prompts}, and {@link Implementation | implementations}. + */ + const BaseMetadataSchema$1 = schemas_object({ + name: schemas_string(), + title: schemas_string().optional() + }); + /** + * Describes the name and version of an MCP implementation. + */ + const ImplementationSchema$1 = BaseMetadataSchema$1.extend({ + ...BaseMetadataSchema$1.shape, + ...IconsSchema$1.shape, + version: schemas_string(), + websiteUrl: schemas_string().optional(), + description: schemas_string().optional() + }); + const FormElicitationCapabilitySchema = intersection(schemas_object({ applyDefaults: schemas_boolean().optional() }), JSONObjectSchema$1); + const ElicitationCapabilitySchema = preprocess((value) => { + if (value && typeof value === "object" && !Array.isArray(value) && Object.keys(value).length === 0) return { form: {} }; + return value; + }, intersection(schemas_object({ + form: FormElicitationCapabilitySchema.optional(), + url: JSONObjectSchema$1.optional() + }), JSONObjectSchema$1.optional())); + /** + * Task capabilities for clients, indicating which request types support task creation. + * + * @deprecated 2025-11-25 wire vocabulary with no SDK runtime; kept importable for interoperability only. + */ + const ClientTasksCapabilitySchema$1 = looseObject({ + list: JSONObjectSchema$1.optional(), + cancel: JSONObjectSchema$1.optional(), + requests: looseObject({ + sampling: looseObject({ createMessage: JSONObjectSchema$1.optional() }).optional(), + elicitation: looseObject({ create: JSONObjectSchema$1.optional() }).optional() + }).optional() + }); + /** + * Task capabilities for servers, indicating which request types support task creation. + * + * @deprecated 2025-11-25 wire vocabulary with no SDK runtime; kept importable for interoperability only. + */ + const ServerTasksCapabilitySchema$1 = looseObject({ + list: JSONObjectSchema$1.optional(), + cancel: JSONObjectSchema$1.optional(), + requests: looseObject({ tools: looseObject({ call: JSONObjectSchema$1.optional() }).optional() }).optional() + }); + /** + * Capabilities a client may support. Known capabilities are defined here, in this schema, but this is not a closed set: any client can define its own, additional capabilities. + */ + const ClientCapabilitiesSchema$1 = schemas_object({ + experimental: schemas_record(schemas_string(), JSONObjectSchema$1).optional(), + sampling: schemas_object({ + context: JSONObjectSchema$1.optional(), + tools: JSONObjectSchema$1.optional() + }).optional(), + elicitation: ElicitationCapabilitySchema.optional(), + roots: schemas_object({ listChanged: schemas_boolean().optional() }).optional(), + tasks: ClientTasksCapabilitySchema$1.optional(), + extensions: schemas_record(schemas_string(), JSONObjectSchema$1).optional() + }); + const InitializeRequestParamsSchema$1 = BaseRequestParamsSchema$1.extend({ + protocolVersion: schemas_string(), + capabilities: ClientCapabilitiesSchema$1, + clientInfo: ImplementationSchema$1 + }); + /** + * This request is sent from the client to the server when it first connects, asking it to begin initialization. + */ + const InitializeRequestSchema$1 = RequestSchema$1.extend({ + method: literal("initialize"), + params: InitializeRequestParamsSchema$1 + }); + /** + * Capabilities that a server may support. Known capabilities are defined here, in this schema, but this is not a closed set: any server can define its own, additional capabilities. + */ + const ServerCapabilitiesSchema$1 = schemas_object({ + experimental: schemas_record(schemas_string(), JSONObjectSchema$1).optional(), + logging: JSONObjectSchema$1.optional(), + completions: JSONObjectSchema$1.optional(), + prompts: schemas_object({ listChanged: schemas_boolean().optional() }).optional(), + resources: schemas_object({ + subscribe: schemas_boolean().optional(), + listChanged: schemas_boolean().optional() + }).optional(), + tools: schemas_object({ listChanged: schemas_boolean().optional() }).optional(), + tasks: ServerTasksCapabilitySchema$1.optional(), + extensions: schemas_record(schemas_string(), JSONObjectSchema$1).optional() + }); + /** + * After receiving an initialize request from the client, the server sends this response. + */ + const InitializeResultSchema$1 = ResultSchema$1.extend({ + protocolVersion: schemas_string(), + capabilities: ServerCapabilitiesSchema$1, + serverInfo: ImplementationSchema$1, + instructions: schemas_string().optional() + }); + /** + * This notification is sent from the client to the server after initialization has finished. + */ + const InitializedNotificationSchema$1 = NotificationSchema$1.extend({ + method: literal("notifications/initialized"), + params: NotificationsParamsSchema$1.optional() + }); + /** + * A ping, issued by either the server or the client, to check that the other party is still alive. The receiver must promptly respond, or else may be disconnected. + */ + const PingRequestSchema$1 = RequestSchema$1.extend({ + method: literal("ping"), + params: BaseRequestParamsSchema$1.optional() + }); + const ProgressSchema$1 = schemas_object({ + progress: schemas_number(), + total: schemas_optional(schemas_number()), + message: schemas_optional(schemas_string()) + }); + const ProgressNotificationParamsSchema$1 = schemas_object({ + ...NotificationsParamsSchema$1.shape, + ...ProgressSchema$1.shape, + progressToken: ProgressTokenSchema$1 + }); + /** + * An out-of-band notification used to inform the receiver of a progress update for a long-running request. + * + * @category notifications/progress + */ + const ProgressNotificationSchema$1 = NotificationSchema$1.extend({ + method: literal("notifications/progress"), + params: ProgressNotificationParamsSchema$1 + }); + const PaginatedRequestParamsSchema$1 = BaseRequestParamsSchema$1.extend({ cursor: CursorSchema$1.optional() }); + const PaginatedRequestSchema$1 = RequestSchema$1.extend({ params: PaginatedRequestParamsSchema$1.optional() }); + const PaginatedResultSchema$1 = ResultSchema$1.extend({ nextCursor: CursorSchema$1.optional() }); + /** + * The contents of a specific resource or sub-resource. + */ + const ResourceContentsSchema$1 = schemas_object({ + uri: schemas_string(), + mimeType: schemas_optional(schemas_string()), + _meta: schemas_record(schemas_string(), unknown()).optional() + }); + const TextResourceContentsSchema$1 = ResourceContentsSchema$1.extend({ text: schemas_string() }); + /** + * A Zod schema for validating Base64 strings that is more performant and + * robust for very large inputs than the default regex-based check. It avoids + * stack overflows by using the native `atob` function for validation. + */ + const Base64Schema = schemas_string().refine((val) => { + try { + atob(val); + return true; + } catch { + return false; + } + }, { message: "Invalid Base64 string" }); + const BlobResourceContentsSchema$1 = ResourceContentsSchema$1.extend({ blob: Base64Schema }); + /** + * The sender or recipient of messages and data in a conversation. + */ + const RoleSchema$1 = schemas_enum(["user", "assistant"]); + /** + * Optional annotations providing clients additional context about a resource. + */ + const AnnotationsSchema$1 = schemas_object({ + audience: schemas_array(RoleSchema$1).optional(), + priority: schemas_number().min(0).max(1).optional(), + lastModified: iso_datetime({ offset: true }).optional() + }); + /** + * A known resource that the server is capable of reading. + */ + const ResourceSchema$1 = schemas_object({ + ...BaseMetadataSchema$1.shape, + ...IconsSchema$1.shape, + uri: schemas_string(), + description: schemas_optional(schemas_string()), + mimeType: schemas_optional(schemas_string()), + size: schemas_optional(schemas_number()), + annotations: AnnotationsSchema$1.optional(), + _meta: schemas_optional(looseObject({})) + }); + /** + * A template description for resources available on the server. + */ + const ResourceTemplateSchema$1 = schemas_object({ + ...BaseMetadataSchema$1.shape, + ...IconsSchema$1.shape, + uriTemplate: schemas_string(), + description: schemas_optional(schemas_string()), + mimeType: schemas_optional(schemas_string()), + annotations: AnnotationsSchema$1.optional(), + _meta: schemas_optional(looseObject({})) + }); + /** + * Sent from the client to request a list of resources the server has. + */ + const ListResourcesRequestSchema$1 = PaginatedRequestSchema$1.extend({ method: literal("resources/list") }); + /** + * The server's response to a {@linkcode ListResourcesRequest | resources/list} request from the client. + */ + const ListResourcesResultSchema$1 = PaginatedResultSchema$1.extend({ resources: schemas_array(ResourceSchema$1) }); + /** + * Sent from the client to request a list of resource templates the server has. + */ + const ListResourceTemplatesRequestSchema$1 = PaginatedRequestSchema$1.extend({ method: literal("resources/templates/list") }); + /** + * The server's response to a {@linkcode ListResourceTemplatesRequest | resources/templates/list} request from the client. + */ + const ListResourceTemplatesResultSchema$1 = PaginatedResultSchema$1.extend({ resourceTemplates: schemas_array(ResourceTemplateSchema$1) }); + const ResourceRequestParamsSchema$1 = BaseRequestParamsSchema$1.extend({ uri: schemas_string() }); + /** + * Parameters for a {@linkcode ReadResourceRequest | resources/read} request. + */ + const ReadResourceRequestParamsSchema$1 = ResourceRequestParamsSchema$1; + /** + * Sent from the client to the server, to read a specific resource URI. + */ + const ReadResourceRequestSchema$1 = RequestSchema$1.extend({ + method: literal("resources/read"), + params: ReadResourceRequestParamsSchema$1 + }); + /** + * The server's response to a {@linkcode ReadResourceRequest | resources/read} request from the client. + */ + const ReadResourceResultSchema$1 = ResultSchema$1.extend({ contents: schemas_array(schemas_union([TextResourceContentsSchema$1, BlobResourceContentsSchema$1])) }); + /** + * An optional notification from the server to the client, informing it that the list of resources it can read from has changed. This may be issued by servers without any previous subscription from the client. + */ + const ResourceListChangedNotificationSchema$1 = NotificationSchema$1.extend({ + method: literal("notifications/resources/list_changed"), + params: NotificationsParamsSchema$1.optional() + }); + const SubscribeRequestParamsSchema$1 = ResourceRequestParamsSchema$1; + /** + * Sent from the client to request `resources/updated` notifications from the server whenever a particular resource changes. + */ + const SubscribeRequestSchema$1 = RequestSchema$1.extend({ + method: literal("resources/subscribe"), + params: SubscribeRequestParamsSchema$1 + }); + const UnsubscribeRequestParamsSchema$1 = ResourceRequestParamsSchema$1; + /** + * Sent from the client to request cancellation of {@linkcode ResourceUpdatedNotification | resources/updated} notifications from the server. This should follow a previous {@linkcode SubscribeRequest | resources/subscribe} request. + */ + const UnsubscribeRequestSchema$1 = RequestSchema$1.extend({ + method: literal("resources/unsubscribe"), + params: UnsubscribeRequestParamsSchema$1 + }); + /** + * Parameters for a {@linkcode ResourceUpdatedNotification | notifications/resources/updated} notification. + */ + const ResourceUpdatedNotificationParamsSchema$1 = NotificationsParamsSchema$1.extend({ uri: schemas_string() }); + /** + * A notification from the server to the client, informing it that a resource has changed and may need to be read again. This should only be sent if the client previously sent a {@linkcode SubscribeRequest | resources/subscribe} request. + */ + const ResourceUpdatedNotificationSchema$1 = NotificationSchema$1.extend({ + method: literal("notifications/resources/updated"), + params: ResourceUpdatedNotificationParamsSchema$1 + }); + /** + * Describes an argument that a prompt can accept. + */ + const PromptArgumentSchema$1 = schemas_object({ + name: schemas_string(), + description: schemas_optional(schemas_string()), + required: schemas_optional(schemas_boolean()) + }); + /** + * A prompt or prompt template that the server offers. + */ + const PromptSchema$1 = schemas_object({ + ...BaseMetadataSchema$1.shape, + ...IconsSchema$1.shape, + description: schemas_optional(schemas_string()), + arguments: schemas_optional(schemas_array(PromptArgumentSchema$1)), + _meta: schemas_optional(looseObject({})) + }); + /** + * Sent from the client to request a list of prompts and prompt templates the server has. + */ + const ListPromptsRequestSchema$1 = PaginatedRequestSchema$1.extend({ method: literal("prompts/list") }); + /** + * The server's response to a {@linkcode ListPromptsRequest | prompts/list} request from the client. + */ + const ListPromptsResultSchema$1 = PaginatedResultSchema$1.extend({ prompts: schemas_array(PromptSchema$1) }); + /** + * Parameters for a {@linkcode GetPromptRequest | prompts/get} request. + */ + const GetPromptRequestParamsSchema$1 = BaseRequestParamsSchema$1.extend({ + name: schemas_string(), + arguments: schemas_record(schemas_string(), schemas_string()).optional() + }); + /** + * Used by the client to get a prompt provided by the server. + */ + const GetPromptRequestSchema$1 = RequestSchema$1.extend({ + method: literal("prompts/get"), + params: GetPromptRequestParamsSchema$1 + }); + /** + * Text provided to or from an LLM. + */ + const TextContentSchema$1 = schemas_object({ + type: literal("text"), + text: schemas_string(), + annotations: AnnotationsSchema$1.optional(), + _meta: schemas_record(schemas_string(), unknown()).optional() + }); + /** + * An image provided to or from an LLM. + */ + const ImageContentSchema$1 = schemas_object({ + type: literal("image"), + data: Base64Schema, + mimeType: schemas_string(), + annotations: AnnotationsSchema$1.optional(), + _meta: schemas_record(schemas_string(), unknown()).optional() + }); + /** + * Audio content provided to or from an LLM. + */ + const AudioContentSchema$1 = schemas_object({ + type: literal("audio"), + data: Base64Schema, + mimeType: schemas_string(), + annotations: AnnotationsSchema$1.optional(), + _meta: schemas_record(schemas_string(), unknown()).optional() + }); + /** + * A tool call request from an assistant (LLM). + * Represents the assistant's request to use a tool. + * + * @deprecated Deprecated as of protocol version 2026-07-28 (SEP-2577); remains + * in the specification for at least twelve months. Migrate to calling LLM + * provider APIs directly. + */ + const ToolUseContentSchema$1 = schemas_object({ + type: literal("tool_use"), + name: schemas_string(), + id: schemas_string(), + input: schemas_record(schemas_string(), unknown()), + _meta: schemas_record(schemas_string(), unknown()).optional() + }); + /** + * The contents of a resource, embedded into a prompt or tool call result. + */ + const EmbeddedResourceSchema$1 = schemas_object({ + type: literal("resource"), + resource: schemas_union([TextResourceContentsSchema$1, BlobResourceContentsSchema$1]), + annotations: AnnotationsSchema$1.optional(), + _meta: schemas_record(schemas_string(), unknown()).optional() + }); + /** + * A resource that the server is capable of reading, included in a prompt or tool call result. + * + * Note: resource links returned by tools are not guaranteed to appear in the results of {@linkcode ListResourcesRequest | resources/list} requests. + */ + const ResourceLinkSchema$1 = ResourceSchema$1.extend({ type: literal("resource_link") }); + /** + * A content block that can be used in prompts and tool results. + */ + const ContentBlockSchema$1 = schemas_union([ + TextContentSchema$1, + ImageContentSchema$1, + AudioContentSchema$1, + ResourceLinkSchema$1, + EmbeddedResourceSchema$1 + ]); + /** + * Describes a message returned as part of a prompt. + */ + const PromptMessageSchema$1 = schemas_object({ + role: RoleSchema$1, + content: ContentBlockSchema$1 + }); + /** + * The server's response to a {@linkcode GetPromptRequest | prompts/get} request from the client. + */ + const GetPromptResultSchema$1 = ResultSchema$1.extend({ + description: schemas_string().optional(), + messages: schemas_array(PromptMessageSchema$1) + }); + /** + * An optional notification from the server to the client, informing it that the list of prompts it offers has changed. This may be issued by servers without any previous subscription from the client. + */ + const PromptListChangedNotificationSchema$1 = NotificationSchema$1.extend({ + method: literal("notifications/prompts/list_changed"), + params: NotificationsParamsSchema$1.optional() + }); + /** + * Additional properties describing a `Tool` to clients. + * + * NOTE: all properties in {@linkcode ToolAnnotations} are **hints**. + * They are not guaranteed to provide a faithful description of + * tool behavior (including descriptive properties like `title`). + * + * Clients should never make tool use decisions based on `ToolAnnotations` + * received from untrusted servers. + */ + const ToolAnnotationsSchema$1 = schemas_object({ + title: schemas_string().optional(), + readOnlyHint: schemas_boolean().optional(), + destructiveHint: schemas_boolean().optional(), + idempotentHint: schemas_boolean().optional(), + openWorldHint: schemas_boolean().optional() + }); + /** + * Execution-related properties for a tool. + */ + const ToolExecutionSchema$1 = schemas_object({ taskSupport: schemas_enum([ + "required", + "optional", + "forbidden" + ]).optional() }); + /** + * Definition for a tool the client can call. + */ + const ToolSchema$1 = schemas_object({ + ...BaseMetadataSchema$1.shape, + ...IconsSchema$1.shape, + description: schemas_string().optional(), + inputSchema: schemas_object({ + type: literal("object"), + properties: schemas_record(schemas_string(), JSONValueSchema$1).optional(), + required: schemas_array(schemas_string()).optional() + }).catchall(unknown()), + outputSchema: schemas_object({ + type: literal("object"), + properties: schemas_record(schemas_string(), JSONValueSchema$1).optional(), + required: schemas_array(schemas_string()).optional() + }).catchall(unknown()).optional(), + annotations: ToolAnnotationsSchema$1.optional(), + execution: ToolExecutionSchema$1.optional(), + _meta: schemas_record(schemas_string(), unknown()).optional() + }); + /** + * Sent from the client to request a list of tools the server has. + */ + const ListToolsRequestSchema$1 = PaginatedRequestSchema$1.extend({ method: literal("tools/list") }); + /** + * The server's response to a {@linkcode ListToolsRequest | tools/list} request from the client. + */ + const ListToolsResultSchema$1 = PaginatedResultSchema$1.extend({ tools: schemas_array(ToolSchema$1) }); + /** + * The server's response to a tool call. + */ + const CallToolResultSchema$1 = ResultSchema$1.extend({ + content: schemas_array(ContentBlockSchema$1), + structuredContent: schemas_record(schemas_string(), unknown()).optional(), + isError: schemas_boolean().optional() + }); + /** + * Parameters for a `tools/call` request. + */ + const CallToolRequestParamsSchema$1 = TaskAugmentedRequestParamsSchema$1.extend({ + name: schemas_string(), + arguments: schemas_record(schemas_string(), unknown()).optional() + }); + /** + * Used by the client to invoke a tool provided by the server. + */ + const CallToolRequestSchema$1 = RequestSchema$1.extend({ + method: literal("tools/call"), + params: CallToolRequestParamsSchema$1 + }); + /** + * An optional notification from the server to the client, informing it that the list of tools it offers has changed. This may be issued by servers without any previous subscription from the client. + */ + const ToolListChangedNotificationSchema$1 = NotificationSchema$1.extend({ + method: literal("notifications/tools/list_changed"), + params: NotificationsParamsSchema$1.optional() + }); + /** + * The severity of a log message. + * + * @deprecated Deprecated as of protocol version 2026-07-28 (SEP-2577); remains + * in the specification for at least twelve months. Migrate to stderr logging + * (STDIO servers) or OpenTelemetry. + */ + const LoggingLevelSchema$1 = schemas_enum([ + "debug", + "info", + "notice", + "warning", + "error", + "critical", + "alert", + "emergency" + ]); + /** + * Parameters for a `logging/setLevel` request. + * + * @deprecated Deprecated as of protocol version 2026-07-28 (SEP-2577); remains + * in the specification for at least twelve months. Migrate to stderr logging + * (STDIO servers) or OpenTelemetry. + */ + const SetLevelRequestParamsSchema$1 = BaseRequestParamsSchema$1.extend({ level: LoggingLevelSchema$1 }); + /** + * A request from the client to the server, to enable or adjust logging. + * + * @deprecated Deprecated as of protocol version 2026-07-28 (SEP-2577); remains + * in the specification for at least twelve months. Migrate to stderr logging + * (STDIO servers) or OpenTelemetry. + */ + const SetLevelRequestSchema$1 = RequestSchema$1.extend({ + method: literal("logging/setLevel"), + params: SetLevelRequestParamsSchema$1 + }); + /** + * Parameters for a `notifications/message` notification. + * + * @deprecated Deprecated as of protocol version 2026-07-28 (SEP-2577); remains + * in the specification for at least twelve months. Migrate to stderr logging + * (STDIO servers) or OpenTelemetry. + */ + const LoggingMessageNotificationParamsSchema$1 = NotificationsParamsSchema$1.extend({ + level: LoggingLevelSchema$1, + logger: schemas_string().optional(), + data: unknown() + }); + /** + * Notification of a log message passed from server to client. If no `logging/setLevel` request has been sent from the client, the server MAY decide which messages to send automatically. + * + * @deprecated Deprecated as of protocol version 2026-07-28 (SEP-2577); remains + * in the specification for at least twelve months. Migrate to stderr logging + * (STDIO servers) or OpenTelemetry. + */ + const LoggingMessageNotificationSchema$1 = NotificationSchema$1.extend({ + method: literal("notifications/message"), + params: LoggingMessageNotificationParamsSchema$1 + }); + /** + * Hints to use for model selection. + * + * @deprecated Deprecated as of protocol version 2026-07-28 (SEP-2577); remains + * in the specification for at least twelve months. Migrate to calling LLM + * provider APIs directly. + */ + const ModelHintSchema$1 = schemas_object({ name: schemas_string().optional() }); + /** + * The server's preferences for model selection, requested of the client during sampling. + * + * @deprecated Deprecated as of protocol version 2026-07-28 (SEP-2577); remains + * in the specification for at least twelve months. Migrate to calling LLM + * provider APIs directly. + */ + const ModelPreferencesSchema$1 = schemas_object({ + hints: schemas_array(ModelHintSchema$1).optional(), + costPriority: schemas_number().min(0).max(1).optional(), + speedPriority: schemas_number().min(0).max(1).optional(), + intelligencePriority: schemas_number().min(0).max(1).optional() + }); + /** + * Controls tool usage behavior in sampling requests. + * + * @deprecated Deprecated as of protocol version 2026-07-28 (SEP-2577); remains + * in the specification for at least twelve months. Migrate to calling LLM + * provider APIs directly. + */ + const ToolChoiceSchema$1 = schemas_object({ mode: schemas_enum([ + "auto", + "required", + "none" + ]).optional() }); + /** + * The result of a tool execution, provided by the user (server). + * Represents the outcome of invoking a tool requested via `ToolUseContent`. + * + * @deprecated Deprecated as of protocol version 2026-07-28 (SEP-2577); remains + * in the specification for at least twelve months. Migrate to calling LLM + * provider APIs directly. + */ + const ToolResultContentSchema$1 = schemas_object({ + type: literal("tool_result"), + toolUseId: schemas_string().describe("The unique identifier for the corresponding tool call."), + content: schemas_array(ContentBlockSchema$1), + structuredContent: schemas_object({}).loose().optional(), + isError: schemas_boolean().optional(), + _meta: schemas_record(schemas_string(), unknown()).optional() + }); + /** + * Basic content types for sampling responses (without tool use). + * Used for backwards-compatible {@linkcode CreateMessageResult} when tools are not used. + * + * @deprecated Deprecated as of protocol version 2026-07-28 (SEP-2577); remains + * in the specification for at least twelve months. Migrate to calling LLM + * provider APIs directly. + */ + const SamplingContentSchema$1 = discriminatedUnion("type", [ + TextContentSchema$1, + ImageContentSchema$1, + AudioContentSchema$1 + ]); + /** + * Content block types allowed in sampling messages. + * This includes text, image, audio, tool use requests, and tool results. + * + * @deprecated Deprecated as of protocol version 2026-07-28 (SEP-2577); remains + * in the specification for at least twelve months. Migrate to calling LLM + * provider APIs directly. + */ + const SamplingMessageContentBlockSchema$1 = discriminatedUnion("type", [ + TextContentSchema$1, + ImageContentSchema$1, + AudioContentSchema$1, + ToolUseContentSchema$1, + ToolResultContentSchema$1 + ]); + /** + * Describes a message issued to or received from an LLM API. + * + * @deprecated Deprecated as of protocol version 2026-07-28 (SEP-2577); remains + * in the specification for at least twelve months. Migrate to calling LLM + * provider APIs directly. + */ + const SamplingMessageSchema$1 = schemas_object({ + role: RoleSchema$1, + content: schemas_union([SamplingMessageContentBlockSchema$1, schemas_array(SamplingMessageContentBlockSchema$1)]), + _meta: schemas_record(schemas_string(), unknown()).optional() + }); + /** + * Parameters for a `sampling/createMessage` request. + * + * @deprecated Deprecated as of protocol version 2026-07-28 (SEP-2577); remains + * in the specification for at least twelve months. Migrate to calling LLM + * provider APIs directly. + */ + const CreateMessageRequestParamsSchema$1 = TaskAugmentedRequestParamsSchema$1.extend({ + messages: schemas_array(SamplingMessageSchema$1), + modelPreferences: ModelPreferencesSchema$1.optional(), + systemPrompt: schemas_string().optional(), + includeContext: schemas_enum([ + "none", + "thisServer", + "allServers" + ]).optional(), + temperature: schemas_number().optional(), + maxTokens: schemas_number().int(), + stopSequences: schemas_array(schemas_string()).optional(), + metadata: JSONObjectSchema$1.optional(), + tools: schemas_array(ToolSchema$1).optional(), + toolChoice: ToolChoiceSchema$1.optional() + }); + /** + * A request from the server to sample an LLM via the client. The client has full discretion over which model to select. The client should also inform the user before beginning sampling, to allow them to inspect the request (human in the loop) and decide whether to approve it. + * + * @deprecated Deprecated as of protocol version 2026-07-28 (SEP-2577); remains + * in the specification for at least twelve months. Migrate to calling LLM + * provider APIs directly. + */ + const CreateMessageRequestSchema$1 = RequestSchema$1.extend({ + method: literal("sampling/createMessage"), + params: CreateMessageRequestParamsSchema$1 + }); + /** + * The client's response to a `sampling/create_message` request from the server. + * This is the backwards-compatible version that returns single content (no arrays). + * Used when the request does not include tools. + * + * @deprecated Deprecated as of protocol version 2026-07-28 (SEP-2577); remains + * in the specification for at least twelve months. Migrate to calling LLM + * provider APIs directly. + */ + const CreateMessageResultSchema$1 = ResultSchema$1.extend({ + model: schemas_string(), + stopReason: schemas_optional(schemas_enum([ + "endTurn", + "stopSequence", + "maxTokens" + ]).or(schemas_string())), + role: RoleSchema$1, + content: SamplingContentSchema$1 + }); + /** + * The client's response to a `sampling/create_message` request when tools were provided. + * This version supports array content for tool use flows. + * + * @deprecated Deprecated as of protocol version 2026-07-28 (SEP-2577); remains + * in the specification for at least twelve months. Migrate to calling LLM + * provider APIs directly. + */ + const CreateMessageResultWithToolsSchema$1 = ResultSchema$1.extend({ + model: schemas_string(), + stopReason: schemas_optional(schemas_enum([ + "endTurn", + "stopSequence", + "maxTokens", + "toolUse" + ]).or(schemas_string())), + role: RoleSchema$1, + content: schemas_union([SamplingMessageContentBlockSchema$1, schemas_array(SamplingMessageContentBlockSchema$1)]) + }); + /** + * Primitive schema definition for boolean fields. + */ + const BooleanSchemaSchema$1 = schemas_object({ + type: literal("boolean"), + title: schemas_string().optional(), + description: schemas_string().optional(), + default: schemas_boolean().optional() + }); + /** + * Primitive schema definition for string fields. + */ + const StringSchemaSchema$1 = schemas_object({ + type: literal("string"), + title: schemas_string().optional(), + description: schemas_string().optional(), + minLength: schemas_number().optional(), + maxLength: schemas_number().optional(), + format: schemas_enum([ + "email", + "uri", + "date", + "date-time" + ]).optional(), + default: schemas_string().optional() + }); + /** + * Primitive schema definition for number fields. + */ + const NumberSchemaSchema$1 = schemas_object({ + type: schemas_enum(["number", "integer"]), + title: schemas_string().optional(), + description: schemas_string().optional(), + minimum: schemas_number().optional(), + maximum: schemas_number().optional(), + default: schemas_number().optional() + }); + /** + * Schema for single-selection enumeration without display titles for options. + */ + const UntitledSingleSelectEnumSchemaSchema$1 = schemas_object({ + type: literal("string"), + title: schemas_string().optional(), + description: schemas_string().optional(), + enum: schemas_array(schemas_string()), + default: schemas_string().optional() + }); + /** + * Schema for single-selection enumeration with display titles for each option. + */ + const TitledSingleSelectEnumSchemaSchema$1 = schemas_object({ + type: literal("string"), + title: schemas_string().optional(), + description: schemas_string().optional(), + oneOf: schemas_array(schemas_object({ + const: schemas_string(), + title: schemas_string() + })), + default: schemas_string().optional() + }); + /** + * Use {@linkcode TitledSingleSelectEnumSchema} instead. + * This interface will be removed in a future version. + */ + const LegacyTitledEnumSchemaSchema$1 = schemas_object({ + type: literal("string"), + title: schemas_string().optional(), + description: schemas_string().optional(), + enum: schemas_array(schemas_string()), + enumNames: schemas_array(schemas_string()).optional(), + default: schemas_string().optional() + }); + const SingleSelectEnumSchemaSchema$1 = schemas_union([UntitledSingleSelectEnumSchemaSchema$1, TitledSingleSelectEnumSchemaSchema$1]); + /** + * Schema for multiple-selection enumeration without display titles for options. + */ + const UntitledMultiSelectEnumSchemaSchema$1 = schemas_object({ + type: literal("array"), + title: schemas_string().optional(), + description: schemas_string().optional(), + minItems: schemas_number().optional(), + maxItems: schemas_number().optional(), + items: schemas_object({ + type: literal("string"), + enum: schemas_array(schemas_string()) + }), + default: schemas_array(schemas_string()).optional() + }); + /** + * Schema for multiple-selection enumeration with display titles for each option. + */ + const TitledMultiSelectEnumSchemaSchema$1 = schemas_object({ + type: literal("array"), + title: schemas_string().optional(), + description: schemas_string().optional(), + minItems: schemas_number().optional(), + maxItems: schemas_number().optional(), + items: schemas_object({ anyOf: schemas_array(schemas_object({ + const: schemas_string(), + title: schemas_string() + })) }), + default: schemas_array(schemas_string()).optional() + }); + /** + * Combined schema for multiple-selection enumeration + */ + const MultiSelectEnumSchemaSchema$1 = schemas_union([UntitledMultiSelectEnumSchemaSchema$1, TitledMultiSelectEnumSchemaSchema$1]); + /** + * Primitive schema definition for enum fields. + */ + const EnumSchemaSchema$1 = schemas_union([ + LegacyTitledEnumSchemaSchema$1, + SingleSelectEnumSchemaSchema$1, + MultiSelectEnumSchemaSchema$1 + ]); + /** + * Union of all primitive schema definitions. + */ + const PrimitiveSchemaDefinitionSchema$1 = schemas_union([ + EnumSchemaSchema$1, + BooleanSchemaSchema$1, + StringSchemaSchema$1, + NumberSchemaSchema$1 + ]); + /** + * Parameters for an `elicitation/create` request for form-based elicitation. + */ + const ElicitRequestFormParamsSchema$1 = TaskAugmentedRequestParamsSchema$1.extend({ + mode: literal("form").optional(), + message: schemas_string(), + requestedSchema: schemas_object({ + type: literal("object"), + properties: schemas_record(schemas_string(), PrimitiveSchemaDefinitionSchema$1), + required: schemas_array(schemas_string()).optional() + }).catchall(unknown()) + }); + /** + * Parameters for an {@linkcode ElicitRequest | elicitation/create} request for URL-based elicitation. + */ + const ElicitRequestURLParamsSchema$1 = TaskAugmentedRequestParamsSchema$1.extend({ + mode: literal("url"), + message: schemas_string(), + elicitationId: schemas_string(), + url: schemas_string().url() + }); + /** + * The parameters for a request to elicit additional information from the user via the client. + */ + const ElicitRequestParamsSchema$1 = schemas_union([ElicitRequestFormParamsSchema$1, ElicitRequestURLParamsSchema$1]); + /** + * A request from the server to elicit user input via the client. + * The client should present the message and form fields to the user (form mode) + * or navigate to a URL (URL mode). + */ + const ElicitRequestSchema$1 = RequestSchema$1.extend({ + method: literal("elicitation/create"), + params: ElicitRequestParamsSchema$1 + }); + /** + * Parameters for a {@linkcode ElicitationCompleteNotification | notifications/elicitation/complete} notification. + * + * @category notifications/elicitation/complete + */ + const ElicitationCompleteNotificationParamsSchema$1 = NotificationsParamsSchema$1.extend({ elicitationId: schemas_string() }); + /** + * A notification from the server to the client, informing it of a completion of an out-of-band elicitation request. + * + * @category notifications/elicitation/complete + */ + const ElicitationCompleteNotificationSchema$1 = NotificationSchema$1.extend({ + method: literal("notifications/elicitation/complete"), + params: ElicitationCompleteNotificationParamsSchema$1 + }); + /** + * The client's response to an {@linkcode ElicitRequest | elicitation/create} request from the server. + */ + const ElicitResultSchema$1 = ResultSchema$1.extend({ + action: schemas_enum([ + "accept", + "decline", + "cancel" + ]), + content: preprocess((val) => val === null ? void 0 : val, schemas_record(schemas_string(), schemas_union([ + schemas_string(), + schemas_number(), + schemas_boolean(), + schemas_array(schemas_string()) + ])).optional()) + }); + /** + * A reference to a resource or resource template definition. + */ + const ResourceTemplateReferenceSchema$1 = schemas_object({ + type: literal("ref/resource"), + uri: schemas_string() + }); + /** + * Identifies a prompt. + */ + const PromptReferenceSchema$1 = schemas_object({ + type: literal("ref/prompt"), + name: schemas_string() + }); + /** + * Parameters for a {@linkcode CompleteRequest | completion/complete} request. + */ + const CompleteRequestParamsSchema$1 = BaseRequestParamsSchema$1.extend({ + ref: schemas_union([PromptReferenceSchema$1, ResourceTemplateReferenceSchema$1]), + argument: schemas_object({ + name: schemas_string(), + value: schemas_string() + }), + context: schemas_object({ arguments: schemas_record(schemas_string(), schemas_string()).optional() }).optional() + }); + /** + * A request from the client to the server, to ask for completion options. + */ + const CompleteRequestSchema$1 = RequestSchema$1.extend({ + method: literal("completion/complete"), + params: CompleteRequestParamsSchema$1 + }); + /** + * The server's response to a {@linkcode CompleteRequest | completion/complete} request + */ + const CompleteResultSchema$1 = ResultSchema$1.extend({ completion: looseObject({ + values: schemas_array(schemas_string()).max(100), + total: schemas_optional(schemas_number().int()), + hasMore: schemas_optional(schemas_boolean()) + }) }); + /** + * Represents a root directory or file that the server can operate on. + * + * @deprecated Deprecated as of protocol version 2026-07-28 (SEP-2577); remains + * in the specification for at least twelve months. Migrate to passing paths via + * tool parameters, resource URIs, or configuration. + */ + const RootSchema$1 = schemas_object({ + uri: schemas_string().startsWith("file://"), + name: schemas_string().optional(), + _meta: schemas_record(schemas_string(), unknown()).optional() + }); + /** + * Sent from the server to request a list of root URIs from the client. + * + * @deprecated Deprecated as of protocol version 2026-07-28 (SEP-2577); remains + * in the specification for at least twelve months. Migrate to passing paths via + * tool parameters, resource URIs, or configuration. + */ + const ListRootsRequestSchema$1 = RequestSchema$1.extend({ + method: literal("roots/list"), + params: BaseRequestParamsSchema$1.optional() + }); + /** + * The client's response to a `roots/list` request from the server. + * + * @deprecated Deprecated as of protocol version 2026-07-28 (SEP-2577); remains + * in the specification for at least twelve months. Migrate to passing paths via + * tool parameters, resource URIs, or configuration. + */ + const ListRootsResultSchema$1 = ResultSchema$1.extend({ roots: schemas_array(RootSchema$1) }); + /** + * A notification from the client to the server, informing it that the list of roots has changed. + * + * @deprecated Deprecated as of protocol version 2026-07-28 (SEP-2577); remains + * in the specification for at least twelve months. Migrate to passing paths via + * tool parameters, resource URIs, or configuration. + */ + const RootsListChangedNotificationSchema$1 = NotificationSchema$1.extend({ + method: literal("notifications/roots/list_changed"), + params: NotificationsParamsSchema$1.optional() + }); + /** + * Task creation parameters, used to ask that the server create a task to represent a request. + * + * @deprecated 2025-11-25 wire vocabulary with no SDK runtime; kept importable for interoperability only. + */ + const TaskCreationParamsSchema$1 = looseObject({ + ttl: schemas_number().optional(), + pollInterval: schemas_number().optional() + }); + /** + * The status of a task. + * + * @deprecated 2025-11-25 wire vocabulary with no SDK runtime; kept importable for interoperability only. + */ + const TaskStatusSchema$1 = schemas_enum([ + "working", + "input_required", + "completed", + "failed", + "cancelled" + ]); + /** + * A pollable state object associated with a request. + * + * @deprecated 2025-11-25 wire vocabulary with no SDK runtime; kept importable for interoperability only. + */ + const TaskSchema$1 = schemas_object({ + taskId: schemas_string(), + status: TaskStatusSchema$1, + ttl: schemas_union([schemas_number(), schemas_null()]), + createdAt: schemas_string(), + lastUpdatedAt: schemas_string(), + pollInterval: schemas_optional(schemas_number()), + statusMessage: schemas_optional(schemas_string()) + }); + /** + * Result returned when a task is created, containing the task data wrapped in a `task` field. + * + * @deprecated 2025-11-25 wire vocabulary with no SDK runtime; kept importable for interoperability only. + */ + const CreateTaskResultSchema$1 = ResultSchema$1.extend({ task: TaskSchema$1 }); + /** + * Parameters for task status notification. + * + * @deprecated 2025-11-25 wire vocabulary with no SDK runtime; kept importable for interoperability only. + */ + const TaskStatusNotificationParamsSchema$1 = NotificationsParamsSchema$1.merge(TaskSchema$1); + /** + * A notification sent when a task's status changes. + * + * @deprecated 2025-11-25 wire vocabulary with no SDK runtime; kept importable for interoperability only. + */ + const TaskStatusNotificationSchema$1 = NotificationSchema$1.extend({ + method: literal("notifications/tasks/status"), + params: TaskStatusNotificationParamsSchema$1 + }); + /** + * A request to get the state of a specific task. + * + * @deprecated 2025-11-25 wire vocabulary with no SDK runtime; kept importable for interoperability only. + */ + const GetTaskRequestSchema$1 = RequestSchema$1.extend({ + method: literal("tasks/get"), + params: BaseRequestParamsSchema$1.extend({ taskId: schemas_string() }) + }); + /** + * The response to a {@linkcode GetTaskRequest | tasks/get} request. + * + * @deprecated 2025-11-25 wire vocabulary with no SDK runtime; kept importable for interoperability only. + */ + const GetTaskResultSchema$1 = ResultSchema$1.merge(TaskSchema$1); + /** + * A request to get the result of a specific task. + * + * @deprecated 2025-11-25 wire vocabulary with no SDK runtime; kept importable for interoperability only. + */ + const GetTaskPayloadRequestSchema$1 = RequestSchema$1.extend({ + method: literal("tasks/result"), + params: BaseRequestParamsSchema$1.extend({ taskId: schemas_string() }) + }); + /** + * The response to a `tasks/result` request. + * The structure matches the result type of the original request. + * For example, a {@linkcode CallToolRequest | tools/call} task would return the `CallToolResult` structure. + * + * + * @deprecated 2025-11-25 wire vocabulary with no SDK runtime; kept importable for interoperability only. + */ + const GetTaskPayloadResultSchema$1 = ResultSchema$1.loose(); + /** + * A request to list tasks. + * + * @deprecated 2025-11-25 wire vocabulary with no SDK runtime; kept importable for interoperability only. + */ + const ListTasksRequestSchema$1 = PaginatedRequestSchema$1.extend({ method: literal("tasks/list") }); + /** + * The response to a {@linkcode ListTasksRequest | tasks/list} request. + * + * @deprecated 2025-11-25 wire vocabulary with no SDK runtime; kept importable for interoperability only. + */ + const ListTasksResultSchema$1 = PaginatedResultSchema$1.extend({ tasks: schemas_array(TaskSchema$1) }); + /** + * A request to cancel a specific task. + * + * @deprecated 2025-11-25 wire vocabulary with no SDK runtime; kept importable for interoperability only. + */ + const CancelTaskRequestSchema$1 = RequestSchema$1.extend({ + method: literal("tasks/cancel"), + params: BaseRequestParamsSchema$1.extend({ taskId: schemas_string() }) + }); + return { + JSONValueSchema: JSONValueSchema$1, + JSONObjectSchema: JSONObjectSchema$1, + ProgressTokenSchema: ProgressTokenSchema$1, + CursorSchema: CursorSchema$1, + TaskMetadataSchema: TaskMetadataSchema$1, + RelatedTaskMetadataSchema: RelatedTaskMetadataSchema$1, + RequestMetaSchema: RequestMetaSchema$1, + BaseRequestParamsSchema: BaseRequestParamsSchema$1, + TaskAugmentedRequestParamsSchema: TaskAugmentedRequestParamsSchema$1, + RequestSchema: RequestSchema$1, + NotificationsParamsSchema: NotificationsParamsSchema$1, + NotificationSchema: NotificationSchema$1, + ResultSchema: ResultSchema$1, + RequestIdSchema: RequestIdSchema$1, + EmptyResultSchema: EmptyResultSchema$1, + CancelledNotificationParamsSchema: CancelledNotificationParamsSchema$1, + CancelledNotificationSchema: CancelledNotificationSchema$1, + IconSchema: IconSchema$1, + IconsSchema: IconsSchema$1, + BaseMetadataSchema: BaseMetadataSchema$1, + ImplementationSchema: ImplementationSchema$1, + ClientTasksCapabilitySchema: ClientTasksCapabilitySchema$1, + ServerTasksCapabilitySchema: ServerTasksCapabilitySchema$1, + ClientCapabilitiesSchema: ClientCapabilitiesSchema$1, + InitializeRequestParamsSchema: InitializeRequestParamsSchema$1, + InitializeRequestSchema: InitializeRequestSchema$1, + ServerCapabilitiesSchema: ServerCapabilitiesSchema$1, + InitializeResultSchema: InitializeResultSchema$1, + InitializedNotificationSchema: InitializedNotificationSchema$1, + PingRequestSchema: PingRequestSchema$1, + ProgressSchema: ProgressSchema$1, + ProgressNotificationParamsSchema: ProgressNotificationParamsSchema$1, + ProgressNotificationSchema: ProgressNotificationSchema$1, + PaginatedRequestParamsSchema: PaginatedRequestParamsSchema$1, + PaginatedRequestSchema: PaginatedRequestSchema$1, + PaginatedResultSchema: PaginatedResultSchema$1, + ResourceContentsSchema: ResourceContentsSchema$1, + TextResourceContentsSchema: TextResourceContentsSchema$1, + BlobResourceContentsSchema: BlobResourceContentsSchema$1, + RoleSchema: RoleSchema$1, + AnnotationsSchema: AnnotationsSchema$1, + ResourceSchema: ResourceSchema$1, + ResourceTemplateSchema: ResourceTemplateSchema$1, + ListResourcesRequestSchema: ListResourcesRequestSchema$1, + ListResourcesResultSchema: ListResourcesResultSchema$1, + ListResourceTemplatesRequestSchema: ListResourceTemplatesRequestSchema$1, + ListResourceTemplatesResultSchema: ListResourceTemplatesResultSchema$1, + ResourceRequestParamsSchema: ResourceRequestParamsSchema$1, + ReadResourceRequestParamsSchema: ReadResourceRequestParamsSchema$1, + ReadResourceRequestSchema: ReadResourceRequestSchema$1, + ReadResourceResultSchema: ReadResourceResultSchema$1, + ResourceListChangedNotificationSchema: ResourceListChangedNotificationSchema$1, + SubscribeRequestParamsSchema: SubscribeRequestParamsSchema$1, + SubscribeRequestSchema: SubscribeRequestSchema$1, + UnsubscribeRequestParamsSchema: UnsubscribeRequestParamsSchema$1, + UnsubscribeRequestSchema: UnsubscribeRequestSchema$1, + ResourceUpdatedNotificationParamsSchema: ResourceUpdatedNotificationParamsSchema$1, + ResourceUpdatedNotificationSchema: ResourceUpdatedNotificationSchema$1, + PromptArgumentSchema: PromptArgumentSchema$1, + PromptSchema: PromptSchema$1, + ListPromptsRequestSchema: ListPromptsRequestSchema$1, + ListPromptsResultSchema: ListPromptsResultSchema$1, + GetPromptRequestParamsSchema: GetPromptRequestParamsSchema$1, + GetPromptRequestSchema: GetPromptRequestSchema$1, + TextContentSchema: TextContentSchema$1, + ImageContentSchema: ImageContentSchema$1, + AudioContentSchema: AudioContentSchema$1, + ToolUseContentSchema: ToolUseContentSchema$1, + EmbeddedResourceSchema: EmbeddedResourceSchema$1, + ResourceLinkSchema: ResourceLinkSchema$1, + ContentBlockSchema: ContentBlockSchema$1, + PromptMessageSchema: PromptMessageSchema$1, + GetPromptResultSchema: GetPromptResultSchema$1, + PromptListChangedNotificationSchema: PromptListChangedNotificationSchema$1, + ToolAnnotationsSchema: ToolAnnotationsSchema$1, + ToolExecutionSchema: ToolExecutionSchema$1, + ToolSchema: ToolSchema$1, + ListToolsRequestSchema: ListToolsRequestSchema$1, + ListToolsResultSchema: ListToolsResultSchema$1, + CallToolResultSchema: CallToolResultSchema$1, + CallToolRequestParamsSchema: CallToolRequestParamsSchema$1, + CallToolRequestSchema: CallToolRequestSchema$1, + ToolListChangedNotificationSchema: ToolListChangedNotificationSchema$1, + LoggingLevelSchema: LoggingLevelSchema$1, + SetLevelRequestParamsSchema: SetLevelRequestParamsSchema$1, + SetLevelRequestSchema: SetLevelRequestSchema$1, + LoggingMessageNotificationParamsSchema: LoggingMessageNotificationParamsSchema$1, + LoggingMessageNotificationSchema: LoggingMessageNotificationSchema$1, + ModelHintSchema: ModelHintSchema$1, + ModelPreferencesSchema: ModelPreferencesSchema$1, + ToolChoiceSchema: ToolChoiceSchema$1, + ToolResultContentSchema: ToolResultContentSchema$1, + SamplingContentSchema: SamplingContentSchema$1, + SamplingMessageContentBlockSchema: SamplingMessageContentBlockSchema$1, + SamplingMessageSchema: SamplingMessageSchema$1, + CreateMessageRequestParamsSchema: CreateMessageRequestParamsSchema$1, + CreateMessageRequestSchema: CreateMessageRequestSchema$1, + CreateMessageResultSchema: CreateMessageResultSchema$1, + CreateMessageResultWithToolsSchema: CreateMessageResultWithToolsSchema$1, + BooleanSchemaSchema: BooleanSchemaSchema$1, + StringSchemaSchema: StringSchemaSchema$1, + NumberSchemaSchema: NumberSchemaSchema$1, + UntitledSingleSelectEnumSchemaSchema: UntitledSingleSelectEnumSchemaSchema$1, + TitledSingleSelectEnumSchemaSchema: TitledSingleSelectEnumSchemaSchema$1, + LegacyTitledEnumSchemaSchema: LegacyTitledEnumSchemaSchema$1, + SingleSelectEnumSchemaSchema: SingleSelectEnumSchemaSchema$1, + UntitledMultiSelectEnumSchemaSchema: UntitledMultiSelectEnumSchemaSchema$1, + TitledMultiSelectEnumSchemaSchema: TitledMultiSelectEnumSchemaSchema$1, + MultiSelectEnumSchemaSchema: MultiSelectEnumSchemaSchema$1, + EnumSchemaSchema: EnumSchemaSchema$1, + PrimitiveSchemaDefinitionSchema: PrimitiveSchemaDefinitionSchema$1, + ElicitRequestFormParamsSchema: ElicitRequestFormParamsSchema$1, + ElicitRequestURLParamsSchema: ElicitRequestURLParamsSchema$1, + ElicitRequestParamsSchema: ElicitRequestParamsSchema$1, + ElicitRequestSchema: ElicitRequestSchema$1, + ElicitationCompleteNotificationParamsSchema: ElicitationCompleteNotificationParamsSchema$1, + ElicitationCompleteNotificationSchema: ElicitationCompleteNotificationSchema$1, + ElicitResultSchema: ElicitResultSchema$1, + ResourceTemplateReferenceSchema: ResourceTemplateReferenceSchema$1, + PromptReferenceSchema: PromptReferenceSchema$1, + CompleteRequestParamsSchema: CompleteRequestParamsSchema$1, + CompleteRequestSchema: CompleteRequestSchema$1, + CompleteResultSchema: CompleteResultSchema$1, + RootSchema: RootSchema$1, + ListRootsRequestSchema: ListRootsRequestSchema$1, + ListRootsResultSchema: ListRootsResultSchema$1, + RootsListChangedNotificationSchema: RootsListChangedNotificationSchema$1, + TaskCreationParamsSchema: TaskCreationParamsSchema$1, + TaskStatusSchema: TaskStatusSchema$1, + TaskSchema: TaskSchema$1, + CreateTaskResultSchema: CreateTaskResultSchema$1, + TaskStatusNotificationParamsSchema: TaskStatusNotificationParamsSchema$1, + TaskStatusNotificationSchema: TaskStatusNotificationSchema$1, + GetTaskRequestSchema: GetTaskRequestSchema$1, + GetTaskResultSchema: GetTaskResultSchema$1, + GetTaskPayloadRequestSchema: GetTaskPayloadRequestSchema$1, + GetTaskPayloadResultSchema: GetTaskPayloadResultSchema$1, + ListTasksRequestSchema: ListTasksRequestSchema$1, + ListTasksResultSchema: ListTasksResultSchema$1, + CancelTaskRequestSchema: CancelTaskRequestSchema$1, + CancelTaskResultSchema: ResultSchema$1.merge(TaskSchema$1), + ClientRequestSchema: schemas_union([ + PingRequestSchema$1, + InitializeRequestSchema$1, + CompleteRequestSchema$1, + SetLevelRequestSchema$1, + GetPromptRequestSchema$1, + ListPromptsRequestSchema$1, + ListResourcesRequestSchema$1, + ListResourceTemplatesRequestSchema$1, + ReadResourceRequestSchema$1, + SubscribeRequestSchema$1, + UnsubscribeRequestSchema$1, + CallToolRequestSchema$1, + ListToolsRequestSchema$1, + GetTaskRequestSchema$1, + GetTaskPayloadRequestSchema$1, + ListTasksRequestSchema$1, + CancelTaskRequestSchema$1 + ]), + ClientNotificationSchema: schemas_union([ + CancelledNotificationSchema$1, + ProgressNotificationSchema$1, + InitializedNotificationSchema$1, + RootsListChangedNotificationSchema$1, + TaskStatusNotificationSchema$1 + ]), + ClientResultSchema: schemas_union([ + EmptyResultSchema$1, + CreateMessageResultSchema$1, + CreateMessageResultWithToolsSchema$1, + ElicitResultSchema$1, + ListRootsResultSchema$1, + GetTaskResultSchema$1, + ListTasksResultSchema$1, + CreateTaskResultSchema$1 + ]), + ServerRequestSchema: schemas_union([ + PingRequestSchema$1, + CreateMessageRequestSchema$1, + ElicitRequestSchema$1, + ListRootsRequestSchema$1, + GetTaskRequestSchema$1, + GetTaskPayloadRequestSchema$1, + ListTasksRequestSchema$1, + CancelTaskRequestSchema$1 + ]), + ServerNotificationSchema: schemas_union([ + CancelledNotificationSchema$1, + ProgressNotificationSchema$1, + LoggingMessageNotificationSchema$1, + ResourceUpdatedNotificationSchema$1, + ResourceListChangedNotificationSchema$1, + ToolListChangedNotificationSchema$1, + PromptListChangedNotificationSchema$1, + TaskStatusNotificationSchema$1, + ElicitationCompleteNotificationSchema$1 + ]), + ServerResultSchema: schemas_union([ + EmptyResultSchema$1, + InitializeResultSchema$1, + CompleteResultSchema$1, + GetPromptResultSchema$1, + ListPromptsResultSchema$1, + ListResourcesResultSchema$1, + ListResourceTemplatesResultSchema$1, + ReadResourceResultSchema$1, + CallToolResultSchema$1, + ListToolsResultSchema$1, + GetTaskResultSchema$1, + ListTasksResultSchema$1, + CreateTaskResultSchema$1 + ]), + CallToolResultWireSchema: unknown().superRefine((value, ctx) => { + if (typeof value !== "object" || value === null || Array.isArray(value) || value.content !== void 0) return; + for (const key of TOOL_RESULT_FOREIGN_FAMILY_KEYS) if (key in value) { + ctx.addIssue({ + code: "custom", + message: `content is required when the body carries '${key}' — another result family cannot default into an empty tools/call success` + }); + return; + } + }).transform(normalizeContentlessToolResult).pipe(CallToolResultSchema$1) + }; +} +let memo$1; +/** +* Builds the era wire-schema set on first call and returns the same object +* thereafter. Module evaluation stays construction-free so importing the +* era codec/registry costs nothing until the first validation actually +* needs a schema; the registry, the codec, and the eager `schemas.ts` +* shim all pull through this memo, so reference identity holds across +* every consumer. +*/ +function buildSchemas2025() { + return memo$1 ??= build$1(); +} + +//#endregion +//#region ../core-internal/src/wire/rev2025-11-25/legacyWrap.ts +/** +* SEP-2106 legacy `outputSchema` wrap helpers (2025-era projection only). +* +* The neutral / 2026-07-28 model lets a tool's `outputSchema` carry any JSON +* Schema root. The 2025-11-25 wire shape requires `type:'object'` at the root, +* so when an era-blind handler advertises a non-object root, the 2025 codec's +* `encodeResult('tools/list', …)` projects it down to +* `{type:'object', properties:{result:}, required:['result']}`, and +* `projectCallToolResult` wraps the matching `structuredContent` as +* `{result:}`. The 2026 codec's projections are the identity. +* +* These helpers are wire-layer property — they exist so the projection can +* live behind {@link WireCodec.encodeResult} / {@link WireCodec.projectCallToolResult} +* and never be re-derived in shared/ or server-side code. +*/ +/** +* Whether a JSON Schema's root is non-object: either an explicit non-object +* `type`, or a typeless root such as `{anyOf:[…]}`. Object-shaped typeless +* roots that the schema-conversion layer can prove are objects are stamped +* `type:'object'` upstream, so they reach this predicate as object roots. +*/ +function isNonObjectJsonSchemaRoot(json) { + return json["type"] !== "object"; +} +/** +* Keyword-position keys whose values are instance data (not subschemas). A +* `{$ref:…}` appearing inside one is a literal value, not a JSON Pointer to +* rewrite. Only consulted when the current object is in keyword position — +* a PROPERTY named `default`/`const` (under `properties`/`$defs`/…) is a name +* position whose value IS a subschema and is recursed into. +*/ +const REF_REWRITE_DATA_POSITION_KEYS = new Set([ + "const", + "enum", + "default", + "examples" +]); +/** +* Keyword-position keys whose value is a name→subschema map. Entries inside +* such a map are in NAME position: their keys are author-chosen property +* names (which may collide with JSON Schema keywords), their values are +* subschemas to recurse into. +*/ +const REF_REWRITE_NAME_MAP_KEYS = new Set([ + "properties", + "patternProperties", + "$defs", + "definitions", + "dependentSchemas", + "dependencies" +]); +/** +* Whether a subtree's `$id` establishes a new resolution base. A fragment-only +* `$id` (`"#item"`, the draft-07/06 spelling of 2020-12's `$anchor`) does not +* change the RFC 3986 base URI — same-document pointers inside still resolve +* against the document root and must be rewritten. +*/ +function establishesNewBase(id) { + return id !== void 0 && !(typeof id === "string" && id.startsWith("#")); +} +/** +* Wrap a non-object output schema in the 2025-era envelope: +* `{type:'object', properties:{result:}, required:['result']}`. +* +* Same-document `$ref` / `$dynamicRef` JSON Pointers inside the natural schema +* (e.g. `#/properties/foo` produced by zod for de-duplicated/recursive types) +* are rewritten to account for the new `#/properties/result` root: bare `#` → +* `#/properties/result`, `#/…` → `#/properties/result/…`. Cross-document refs +* (anything not starting with `#`) are left untouched. +* +* The rewrite is position-aware: data-valued keywords +* (`const`/`enum`/`default`/`examples`) in keyword position are NOT descended +* into; the same names appearing as property names under +* `properties`/`patternProperties`/`$defs`/`definitions`/`dependentSchemas`/ +* `dependencies` ARE descended into (they're subschemas). The rewrite is also +* `$id`-scoped: if the natural root carries a base-establishing `$id` no +* pointer is rewritten (same-document refs inside resolve against the embedded +* `$id` base, not the wrapper root), and any subtree that establishes its own +* `$id` is left untouched for the same reason. Fragment-only `$id` (`"#item"`, +* draft-07's anchor spelling) does not establish a base and IS descended into. +*/ +function wrapOutputSchemaForLegacy(natural) { + const $schema = typeof natural["$schema"] === "string" ? natural["$schema"] : void 0; + if (establishesNewBase(natural["$id"])) return { + ...$schema !== void 0 && { $schema }, + type: "object", + properties: { result: natural }, + required: ["result"] + }; + const convertRecursiveRefs = declares2019Dialect(natural["$schema"]) && natural["$recursiveAnchor"] !== true; + const rewriteRefs = (node, parentIsNameMap) => { + if (Array.isArray(node)) return node.map((item) => rewriteRefs(item, false)); + if (node === null || typeof node !== "object") return node; + if (!parentIsNameMap && establishesNewBase(node["$id"])) return node; + const out = {}; + let convertedRecursion = false; + for (const [k, v] of Object.entries(node)) if (parentIsNameMap) out[k] = rewriteRefs(v, false); + else if ((k === "$ref" || k === "$dynamicRef") && typeof v === "string") out[k] = v === "#" ? "#/properties/result" : v.startsWith("#/") ? `#/properties/result${v.slice(1)}` : v; + else if (k === "$recursiveRef" && v === "#" && convertRecursiveRefs) convertedRecursion = true; + else if (REF_REWRITE_DATA_POSITION_KEYS.has(k)) out[k] = v; + else if (REF_REWRITE_NAME_MAP_KEYS.has(k)) out[k] = rewriteRefs(v, true); + else out[k] = rewriteRefs(v, false); + if (convertedRecursion) if ("$ref" in out) out["allOf"] = [...Array.isArray(out["allOf"]) ? out["allOf"] : [], { $ref: "#/properties/result" }]; + else out["$ref"] = "#/properties/result"; + return out; + }; + return { + ...$schema !== void 0 && { $schema }, + type: "object", + properties: { result: rewriteRefs(natural, false) }, + required: ["result"] + }; +} + +//#endregion +//#region ../core-internal/src/wire/rev2025-11-25/registry.ts +const requestMethodKeys$1 = { + 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 +}; +const notificationMethodKeys$1 = { + "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 +}; +const resultMethodKeys = { + 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 +}; +let maps$1; +function registryMaps() { + if (maps$1) return maps$1; + const s = buildSchemas2025(); + maps$1 = { + requestSchemas: { + ping: s.PingRequestSchema, + initialize: s.InitializeRequestSchema, + "completion/complete": s.CompleteRequestSchema, + "logging/setLevel": s.SetLevelRequestSchema, + "prompts/get": s.GetPromptRequestSchema, + "prompts/list": s.ListPromptsRequestSchema, + "resources/list": s.ListResourcesRequestSchema, + "resources/templates/list": s.ListResourceTemplatesRequestSchema, + "resources/read": s.ReadResourceRequestSchema, + "resources/subscribe": s.SubscribeRequestSchema, + "resources/unsubscribe": s.UnsubscribeRequestSchema, + "tools/call": s.CallToolRequestSchema, + "tools/list": s.ListToolsRequestSchema, + "tasks/get": s.GetTaskRequestSchema, + "tasks/result": s.GetTaskPayloadRequestSchema, + "tasks/list": s.ListTasksRequestSchema, + "tasks/cancel": s.CancelTaskRequestSchema, + "sampling/createMessage": s.CreateMessageRequestSchema, + "elicitation/create": s.ElicitRequestSchema, + "roots/list": s.ListRootsRequestSchema + }, + notificationSchemas: { + "notifications/cancelled": s.CancelledNotificationSchema, + "notifications/progress": s.ProgressNotificationSchema, + "notifications/initialized": s.InitializedNotificationSchema, + "notifications/roots/list_changed": s.RootsListChangedNotificationSchema, + "notifications/tasks/status": s.TaskStatusNotificationSchema, + "notifications/message": s.LoggingMessageNotificationSchema, + "notifications/resources/updated": s.ResourceUpdatedNotificationSchema, + "notifications/resources/list_changed": s.ResourceListChangedNotificationSchema, + "notifications/tools/list_changed": s.ToolListChangedNotificationSchema, + "notifications/prompts/list_changed": s.PromptListChangedNotificationSchema, + "notifications/elicitation/complete": s.ElicitationCompleteNotificationSchema + }, + resultSchemas: { + ping: s.EmptyResultSchema, + initialize: s.InitializeResultSchema, + "completion/complete": s.CompleteResultSchema, + "logging/setLevel": s.EmptyResultSchema, + "prompts/get": s.GetPromptResultSchema, + "prompts/list": s.ListPromptsResultSchema, + "resources/list": s.ListResourcesResultSchema, + "resources/templates/list": s.ListResourceTemplatesResultSchema, + "resources/read": s.ReadResourceResultSchema, + "resources/subscribe": s.EmptyResultSchema, + "resources/unsubscribe": s.EmptyResultSchema, + "tools/call": s.CallToolResultWireSchema, + "tools/list": s.ListToolsResultSchema, + "sampling/createMessage": s.CreateMessageResultWithToolsSchema, + "elicitation/create": s.ElicitResultSchema, + "roots/list": s.ListRootsResultSchema + } + }; + return maps$1; +} +/** +* Forces the lazy registry maps (and, through them, the era's schema memo). +* Warm-up hook for `preloadSchemas()` — no-op once the maps exist. +*/ +function warmRegistryMaps2025() { + registryMaps(); +} +/** The 2025-era request-method set (registry membership = the deletion story). */ +function hasRequestMethod2025(method) { + return Object.prototype.hasOwnProperty.call(requestMethodKeys$1, method); +} +/** The 2025-era notification-method set. */ +function hasNotificationMethod2025(method) { + return Object.prototype.hasOwnProperty.call(notificationMethodKeys$1, method); +} +/** Result-map membership: exactly the era's typed-method subset (no task entries, no 2026-only methods). */ +function hasResultMethod(method) { + return Object.prototype.hasOwnProperty.call(resultMethodKeys, method); +} +function getResultSchema(method) { + return hasResultMethod(method) ? registryMaps().resultSchemas[method] : void 0; +} +function getRequestSchema(method) { + return hasRequestMethod2025(method) ? registryMaps().requestSchemas[method] : void 0; +} +function getNotificationSchema(method) { + return hasNotificationMethod2025(method) ? registryMaps().notificationSchemas[method] : void 0; +} +/** Registry method lists (for the spec-method universe and the CI registry-diff oracle). */ +const rev2025RequestMethods = Object.keys(requestMethodKeys$1); +const rev2025NotificationMethods = Object.keys(notificationMethodKeys$1); + +//#endregion +//#region ../core-internal/src/wire/rev2025-11-25/codec.ts +function isPlainObject$6(value) { + return value !== null && typeof value === "object" && !Array.isArray(value); +} +/** Tri-state wrap of an optional Zod schema lookup (the function-only contract). */ +function triState$1(schema, raw) { + if (schema === void 0) return { + ok: false, + reason: "not-in-era" + }; + const parsed = schema.safeParse(raw); + return parsed.success ? { + ok: true, + value: parsed.data + } : { + ok: false, + reason: "invalid", + message: String(parsed.error) + }; +} +const NOT_IN_ERA$1 = { + ok: false, + reason: "not-in-era" +}; +/** Whether a `tools/list` entry advertises a non-object `outputSchema` root that needs the SEP-2106 legacy wrap. */ +function toolNeedsLegacyWrap(t) { + return isPlainObject$6(t) && isPlainObject$6(t["outputSchema"]) && isNonObjectJsonSchemaRoot(t["outputSchema"]); +} +/** The wire→neutral trust boundary: a decoded 2025-era wire result is adopted as the neutral `Result` here (the module's single deliberate assertion). */ +function toNeutralResult(value) { + return value; +} +const rev2025Codec = { + era: "2025-11-25", + hasRequestMethod: hasRequestMethod2025, + hasNotificationMethod: hasNotificationMethod2025, + validateRequest: (method, raw) => triState$1(getRequestSchema(method), raw), + validateResult: (method, raw) => triState$1(getResultSchema(method), raw), + validateNotification: (method, raw) => triState$1(getNotificationSchema(method), raw), + hasInputRequestMethod: () => false, + validateInputRequest: () => NOT_IN_ERA$1, + validateInputResponse: () => NOT_IN_ERA$1, + samplingResultVariant: ((hasTools, raw) => { + const s = buildSchemas2025(); + return triState$1(hasTools ? s.CreateMessageResultWithToolsSchema : s.CreateMessageResultSchema, raw); + }), + outboundEnvelope: (_material) => void 0, + validateEnvelopeMeta: (_meta) => [], + projectCallToolResult(result, advertisedOutputSchema) { + const withText = appendTextFallbackForNonObject(result); + const sc = withText.structuredContent; + if (sc === void 0) return withText; + const valueIsNonObject = typeof sc !== "object" || sc === null || Array.isArray(sc); + const schemaWrapped = advertisedOutputSchema !== void 0 && isNonObjectJsonSchemaRoot(advertisedOutputSchema); + if (!valueIsNonObject && !schemaWrapped) return withText; + return { + ...withText, + structuredContent: { result: sc } + }; + }, + decodeResult(_method, raw) { + if (isPlainObject$6(raw) && "resultType" in raw) { + const stripped = { ...raw }; + delete stripped["resultType"]; + return { + kind: "complete", + result: toNeutralResult(stripped) + }; + } + return { + kind: "complete", + result: toNeutralResult(raw) + }; + }, + encodeResult(method, result) { + if (method !== "tools/list") return result; + const tools = result.tools; + if (!Array.isArray(tools) || !tools.some((t) => toolNeedsLegacyWrap(t))) return result; + return { + ...result, + tools: tools.map((t) => toolNeedsLegacyWrap(t) ? { + ...t, + outputSchema: wrapOutputSchemaForLegacy(t.outputSchema) + } : t) + }; + }, + encodeErrorCode: (code) => code === -32002 ? -32602 : code, + checkInboundEnvelope: (_material) => void 0 +}; + +//#endregion +//#region ../core-internal/src/wire/rev2026-07-28/buildSchemas.ts +/** +* 2026-era wire schemas (protocol revision 2026-07-28). +* +* Fully self-contained — no runtime imports from types/schemas.ts. The +* neutral types/schemas.ts layer is the public-API superset and is free to +* evolve; this file is the 2026 wire-parse contract and is BEHAVIOR-FROZEN +* against the 2026-07-28 anchor. Every era-shared building block (content +* blocks, resources, prompts, capabilities, notifications, …) that the wire +* shapes compose is a frozen LOCAL copy — verbatim from the neutral layer at +* the point this revision was sealed, dependencies first. The only cross-layer +* dependency is `import type { JSONObject, JSONValue }` from the neutral types +* barrel — pure structural type aliases with no parse behavior. +* +* This module is the only place the per-request `_meta` envelope is modeled. +* The envelope is wire-only vocabulary: the protocol layer lifts it off +* inbound requests before any handler runs and surfaces it at +* `ctx.mcpReq.envelope`; the 2026-era codec enforces its requiredness at +* dispatch time (`checkInboundEnvelope`) - the former neutral-schema JSDoc +* deferral ("enforced per request at dispatch time, not here") is now +* discharged by that codec step. +* +* No 2025-era traffic ever touches this module, so requiredness here is +* bare and spec-exact (the shared-schema `.catch` hazards do not apply). +* +* SPEC-CURRENCY RE-SEAL (2026-07-17): the 2026-07-28 revision was re-sealed +* upstream by spec PR #3002 (commit 71e30695, merged 2026-07-15 — after the +* previous anchor pin f68d864a): the envelope's `clientInfo` demoted from +* required to SHOULD, and `DiscoverResult.serverInfo` moved from the result +* body to the new `ResultMetaObject` key +* `_meta['io.modelcontextprotocol/serverInfo']` (optional on every result). +* The shapes below are the re-sealed anchor, exactly — no pre-#3002 shape is +* modeled anywhere (per ruling: the final revision is the only 2026-07-28). +*/ +function build() { + const JSONValueSchema$1 = lazy(() => schemas_union([ + schemas_string(), + schemas_number(), + schemas_boolean(), + schemas_null(), + schemas_record(schemas_string(), JSONValueSchema$1), + schemas_array(JSONValueSchema$1) + ])); + const JSONObjectSchema$1 = schemas_record(schemas_string(), JSONValueSchema$1); + /** + * A progress token, used to associate progress notifications with the original request. + */ + const ProgressTokenSchema$1 = schemas_union([schemas_string(), schemas_number().int()]); + /** + * An opaque token used to represent a cursor for pagination. + */ + const CursorSchema$1 = schemas_string(); + /** + * A uniquely identifying ID for a request in JSON-RPC. + */ + const RequestIdSchema$1 = schemas_union([schemas_string(), schemas_number().int()]); + /** + * The sender or recipient of messages and data in a conversation. + */ + const RoleSchema$1 = schemas_enum(["user", "assistant"]); + /** + * The severity of a log message. + */ + const LoggingLevelSchema$1 = schemas_enum([ + "debug", + "info", + "notice", + "warning", + "error", + "critical", + "alert", + "emergency" + ]); + /** + * A Zod schema for validating Base64 strings that is more performant and + * robust for very large inputs than the default regex-based check. It avoids + * stack overflows by using the native `atob` function for validation. + */ + const Base64Schema = schemas_string().refine((val) => { + try { + atob(val); + return true; + } catch { + return false; + } + }, { message: "Invalid Base64 string" }); + /** @deprecated 2025-11-25 wire vocabulary with no SDK runtime; kept importable for interoperability only. */ + const TaskMetadataSchema$1 = schemas_object({ ttl: schemas_number().optional() }); + /** @deprecated 2025-11-25 wire vocabulary with no SDK runtime; kept importable for interoperability only. */ + const RelatedTaskMetadataSchema$1 = schemas_object({ taskId: schemas_string() }); + const RequestMetaSchema$1 = looseObject({ + progressToken: ProgressTokenSchema$1.optional(), + "io.modelcontextprotocol/related-task": RelatedTaskMetadataSchema$1.optional() + }); + const BaseRequestParamsSchema$1 = schemas_object({ _meta: RequestMetaSchema$1.optional() }); + /** @deprecated 2025-11-25 wire vocabulary with no SDK runtime; kept importable for interoperability only. */ + const TaskAugmentedRequestParamsSchema$1 = BaseRequestParamsSchema$1.extend({ task: TaskMetadataSchema$1.optional() }); + const NotificationsParamsSchema$1 = schemas_object({ _meta: RequestMetaSchema$1.optional() }); + const NotificationSchema$1 = schemas_object({ + method: schemas_string(), + params: NotificationsParamsSchema$1.loose().optional() + }); + const IconSchema$1 = schemas_object({ + src: schemas_string(), + mimeType: schemas_string().optional(), + sizes: schemas_array(schemas_string()).optional(), + theme: schemas_enum(["light", "dark"]).optional() + }); + const IconsSchema$1 = schemas_object({ icons: schemas_array(IconSchema$1).optional() }); + const BaseMetadataSchema$1 = schemas_object({ + name: schemas_string(), + title: schemas_string().optional() + }); + const ImplementationSchema$1 = BaseMetadataSchema$1.extend({ + ...BaseMetadataSchema$1.shape, + ...IconsSchema$1.shape, + version: schemas_string(), + websiteUrl: schemas_string().optional(), + description: schemas_string().optional() + }); + const FormElicitationCapabilitySchema = intersection(schemas_object({ applyDefaults: schemas_boolean().optional() }), JSONObjectSchema$1); + const ElicitationCapabilitySchema = preprocess((value) => { + if (value && typeof value === "object" && !Array.isArray(value) && Object.keys(value).length === 0) return { form: {} }; + return value; + }, intersection(schemas_object({ + form: FormElicitationCapabilitySchema.optional(), + url: JSONObjectSchema$1.optional() + }), JSONObjectSchema$1.optional())); + /** @deprecated 2025-11-25 wire vocabulary with no SDK runtime; kept importable for interoperability only. */ + const ClientTasksCapabilitySchema$1 = looseObject({ + list: JSONObjectSchema$1.optional(), + cancel: JSONObjectSchema$1.optional(), + requests: looseObject({ + sampling: looseObject({ createMessage: JSONObjectSchema$1.optional() }).optional(), + elicitation: looseObject({ create: JSONObjectSchema$1.optional() }).optional() + }).optional() + }); + /** @deprecated 2025-11-25 wire vocabulary with no SDK runtime; kept importable for interoperability only. */ + const ServerTasksCapabilitySchema$1 = looseObject({ + list: JSONObjectSchema$1.optional(), + cancel: JSONObjectSchema$1.optional(), + requests: looseObject({ tools: looseObject({ call: JSONObjectSchema$1.optional() }).optional() }).optional() + }); + const ClientCapabilitiesSchema$1 = schemas_object({ + experimental: schemas_record(schemas_string(), JSONObjectSchema$1).optional(), + sampling: schemas_object({ + context: JSONObjectSchema$1.optional(), + tools: JSONObjectSchema$1.optional() + }).optional(), + elicitation: ElicitationCapabilitySchema.optional(), + roots: schemas_object({ listChanged: schemas_boolean().optional() }).optional(), + tasks: ClientTasksCapabilitySchema$1.optional(), + extensions: schemas_record(schemas_string(), JSONObjectSchema$1).optional() + }); + const ServerCapabilitiesSchema$1 = schemas_object({ + experimental: schemas_record(schemas_string(), JSONObjectSchema$1).optional(), + logging: JSONObjectSchema$1.optional(), + completions: JSONObjectSchema$1.optional(), + prompts: schemas_object({ listChanged: schemas_boolean().optional() }).optional(), + resources: schemas_object({ + subscribe: schemas_boolean().optional(), + listChanged: schemas_boolean().optional() + }).optional(), + tools: schemas_object({ listChanged: schemas_boolean().optional() }).optional(), + tasks: ServerTasksCapabilitySchema$1.optional(), + extensions: schemas_record(schemas_string(), JSONObjectSchema$1).optional() + }); + const ProgressSchema$1 = schemas_object({ + progress: schemas_number(), + total: schemas_optional(schemas_number()), + message: schemas_optional(schemas_string()) + }); + const ProgressNotificationParamsSchema$1 = schemas_object({ + ...NotificationsParamsSchema$1.shape, + ...ProgressSchema$1.shape, + progressToken: ProgressTokenSchema$1 + }); + const ProgressNotificationSchema$1 = NotificationSchema$1.extend({ + method: literal("notifications/progress"), + params: ProgressNotificationParamsSchema$1 + }); + const LoggingMessageNotificationParamsSchema$1 = NotificationsParamsSchema$1.extend({ + level: LoggingLevelSchema$1, + logger: schemas_string().optional(), + data: unknown() + }); + const LoggingMessageNotificationSchema$1 = NotificationSchema$1.extend({ + method: literal("notifications/message"), + params: LoggingMessageNotificationParamsSchema$1 + }); + const ResourceContentsSchema$1 = schemas_object({ + uri: schemas_string(), + mimeType: schemas_optional(schemas_string()), + _meta: schemas_record(schemas_string(), unknown()).optional() + }); + const TextResourceContentsSchema$1 = ResourceContentsSchema$1.extend({ text: schemas_string() }); + const BlobResourceContentsSchema$1 = ResourceContentsSchema$1.extend({ blob: Base64Schema }); + const AnnotationsSchema$1 = schemas_object({ + audience: schemas_array(RoleSchema$1).optional(), + priority: schemas_number().min(0).max(1).optional(), + lastModified: iso_datetime({ offset: true }).optional() + }); + const ResourceSchema$1 = schemas_object({ + ...BaseMetadataSchema$1.shape, + ...IconsSchema$1.shape, + uri: schemas_string(), + description: schemas_optional(schemas_string()), + mimeType: schemas_optional(schemas_string()), + size: schemas_optional(schemas_number()), + annotations: AnnotationsSchema$1.optional(), + _meta: schemas_optional(looseObject({})) + }); + const ResourceTemplateSchema$1 = schemas_object({ + ...BaseMetadataSchema$1.shape, + ...IconsSchema$1.shape, + uriTemplate: schemas_string(), + description: schemas_optional(schemas_string()), + mimeType: schemas_optional(schemas_string()), + annotations: AnnotationsSchema$1.optional(), + _meta: schemas_optional(looseObject({})) + }); + const ResourceListChangedNotificationSchema$1 = NotificationSchema$1.extend({ + method: literal("notifications/resources/list_changed"), + params: NotificationsParamsSchema$1.optional() + }); + const ResourceUpdatedNotificationParamsSchema$1 = NotificationsParamsSchema$1.extend({ uri: schemas_string() }); + const ResourceUpdatedNotificationSchema$1 = NotificationSchema$1.extend({ + method: literal("notifications/resources/updated"), + params: ResourceUpdatedNotificationParamsSchema$1 + }); + const PromptArgumentSchema$1 = schemas_object({ + name: schemas_string(), + description: schemas_optional(schemas_string()), + required: schemas_optional(schemas_boolean()) + }); + const PromptSchema$1 = schemas_object({ + ...BaseMetadataSchema$1.shape, + ...IconsSchema$1.shape, + description: schemas_optional(schemas_string()), + arguments: schemas_optional(schemas_array(PromptArgumentSchema$1)), + _meta: schemas_optional(looseObject({})) + }); + const PromptListChangedNotificationSchema$1 = NotificationSchema$1.extend({ + method: literal("notifications/prompts/list_changed"), + params: NotificationsParamsSchema$1.optional() + }); + const TextContentSchema$1 = schemas_object({ + type: literal("text"), + text: schemas_string(), + annotations: AnnotationsSchema$1.optional(), + _meta: schemas_record(schemas_string(), unknown()).optional() + }); + const ImageContentSchema$1 = schemas_object({ + type: literal("image"), + data: Base64Schema, + mimeType: schemas_string(), + annotations: AnnotationsSchema$1.optional(), + _meta: schemas_record(schemas_string(), unknown()).optional() + }); + const AudioContentSchema$1 = schemas_object({ + type: literal("audio"), + data: Base64Schema, + mimeType: schemas_string(), + annotations: AnnotationsSchema$1.optional(), + _meta: schemas_record(schemas_string(), unknown()).optional() + }); + const ToolUseContentSchema$1 = schemas_object({ + type: literal("tool_use"), + name: schemas_string(), + id: schemas_string(), + input: schemas_record(schemas_string(), unknown()), + _meta: schemas_record(schemas_string(), unknown()).optional() + }); + const EmbeddedResourceSchema$1 = schemas_object({ + type: literal("resource"), + resource: schemas_union([TextResourceContentsSchema$1, BlobResourceContentsSchema$1]), + annotations: AnnotationsSchema$1.optional(), + _meta: schemas_record(schemas_string(), unknown()).optional() + }); + const ResourceLinkSchema$1 = ResourceSchema$1.extend({ type: literal("resource_link") }); + const ContentBlockSchema$1 = schemas_union([ + TextContentSchema$1, + ImageContentSchema$1, + AudioContentSchema$1, + ResourceLinkSchema$1, + EmbeddedResourceSchema$1 + ]); + const PromptMessageSchema$1 = schemas_object({ + role: RoleSchema$1, + content: ContentBlockSchema$1 + }); + const ToolAnnotationsSchema$1 = schemas_object({ + title: schemas_string().optional(), + readOnlyHint: schemas_boolean().optional(), + destructiveHint: schemas_boolean().optional(), + idempotentHint: schemas_boolean().optional(), + openWorldHint: schemas_boolean().optional() + }); + const ToolListChangedNotificationSchema$1 = NotificationSchema$1.extend({ + method: literal("notifications/tools/list_changed"), + params: NotificationsParamsSchema$1.optional() + }); + const ModelHintSchema$1 = schemas_object({ name: schemas_string().optional() }); + const ModelPreferencesSchema$1 = schemas_object({ + hints: schemas_array(ModelHintSchema$1).optional(), + costPriority: schemas_number().min(0).max(1).optional(), + speedPriority: schemas_number().min(0).max(1).optional(), + intelligencePriority: schemas_number().min(0).max(1).optional() + }); + const ToolChoiceSchema$1 = schemas_object({ mode: schemas_enum([ + "auto", + "required", + "none" + ]).optional() }); + const BooleanSchemaSchema$1 = schemas_object({ + type: literal("boolean"), + title: schemas_string().optional(), + description: schemas_string().optional(), + default: schemas_boolean().optional() + }); + const StringSchemaSchema$1 = schemas_object({ + type: literal("string"), + title: schemas_string().optional(), + description: schemas_string().optional(), + minLength: schemas_number().optional(), + maxLength: schemas_number().optional(), + format: schemas_enum([ + "email", + "uri", + "date", + "date-time" + ]).optional(), + default: schemas_string().optional() + }); + const NumberSchemaSchema$1 = schemas_object({ + type: schemas_enum(["number", "integer"]), + title: schemas_string().optional(), + description: schemas_string().optional(), + minimum: schemas_number().optional(), + maximum: schemas_number().optional(), + default: schemas_number().optional() + }); + const UntitledSingleSelectEnumSchemaSchema$1 = schemas_object({ + type: literal("string"), + title: schemas_string().optional(), + description: schemas_string().optional(), + enum: schemas_array(schemas_string()), + default: schemas_string().optional() + }); + const TitledSingleSelectEnumSchemaSchema$1 = schemas_object({ + type: literal("string"), + title: schemas_string().optional(), + description: schemas_string().optional(), + oneOf: schemas_array(schemas_object({ + const: schemas_string(), + title: schemas_string() + })), + default: schemas_string().optional() + }); + const LegacyTitledEnumSchemaSchema$1 = schemas_object({ + type: literal("string"), + title: schemas_string().optional(), + description: schemas_string().optional(), + enum: schemas_array(schemas_string()), + enumNames: schemas_array(schemas_string()).optional(), + default: schemas_string().optional() + }); + const SingleSelectEnumSchemaSchema$1 = schemas_union([UntitledSingleSelectEnumSchemaSchema$1, TitledSingleSelectEnumSchemaSchema$1]); + const UntitledMultiSelectEnumSchemaSchema$1 = schemas_object({ + type: literal("array"), + title: schemas_string().optional(), + description: schemas_string().optional(), + minItems: schemas_number().optional(), + maxItems: schemas_number().optional(), + items: schemas_object({ + type: literal("string"), + enum: schemas_array(schemas_string()) + }), + default: schemas_array(schemas_string()).optional() + }); + const TitledMultiSelectEnumSchemaSchema$1 = schemas_object({ + type: literal("array"), + title: schemas_string().optional(), + description: schemas_string().optional(), + minItems: schemas_number().optional(), + maxItems: schemas_number().optional(), + items: schemas_object({ anyOf: schemas_array(schemas_object({ + const: schemas_string(), + title: schemas_string() + })) }), + default: schemas_array(schemas_string()).optional() + }); + const MultiSelectEnumSchemaSchema$1 = schemas_union([UntitledMultiSelectEnumSchemaSchema$1, TitledMultiSelectEnumSchemaSchema$1]); + const EnumSchemaSchema$1 = schemas_union([ + LegacyTitledEnumSchemaSchema$1, + SingleSelectEnumSchemaSchema$1, + MultiSelectEnumSchemaSchema$1 + ]); + const PrimitiveSchemaDefinitionSchema$1 = schemas_union([ + EnumSchemaSchema$1, + BooleanSchemaSchema$1, + StringSchemaSchema$1, + NumberSchemaSchema$1 + ]); + const ElicitRequestFormParamsSchema$1 = TaskAugmentedRequestParamsSchema$1.extend({ + mode: literal("form").optional(), + message: schemas_string(), + requestedSchema: schemas_object({ + type: literal("object"), + properties: schemas_record(schemas_string(), PrimitiveSchemaDefinitionSchema$1), + required: schemas_array(schemas_string()).optional() + }).catchall(unknown()) + }); + const ResourceTemplateReferenceSchema$1 = schemas_object({ + type: literal("ref/resource"), + uri: schemas_string() + }); + const PromptReferenceSchema$1 = schemas_object({ + type: literal("ref/prompt"), + name: schemas_string() + }); + const RootSchema$1 = schemas_object({ + uri: schemas_string().startsWith("file://"), + name: schemas_string().optional(), + _meta: schemas_record(schemas_string(), unknown()).optional() + }); + const sharedClientCapabilityShape = ClientCapabilitiesSchema$1.shape; + const ClientCapabilities2026Schema = schemas_object({ + experimental: sharedClientCapabilityShape.experimental, + sampling: sharedClientCapabilityShape.sampling, + elicitation: sharedClientCapabilityShape.elicitation, + roots: sharedClientCapabilityShape.roots, + extensions: sharedClientCapabilityShape.extensions + }); + const sharedServerCapabilityShape = ServerCapabilitiesSchema$1.shape; + const ServerCapabilities2026Schema = schemas_object({ + experimental: sharedServerCapabilityShape.experimental, + logging: sharedServerCapabilityShape.logging, + completions: sharedServerCapabilityShape.completions, + prompts: sharedServerCapabilityShape.prompts, + resources: sharedServerCapabilityShape.resources, + tools: sharedServerCapabilityShape.tools, + extensions: sharedServerCapabilityShape.extensions + }); + /** + * The per-request `_meta` envelope carried by every request under protocol revision + * 2026-07-28: the protocol version governing the request, the client implementation + * info, and the client's capabilities — declared per request rather than once at + * initialization — plus the optional log-level opt-in. + * + * This schema models the complete envelope on its own (loose: foreign keys + * pass through - the lift extracts exactly the reserved keys, so enforcement + * never sees extension material). Requiredness is enforced per request at + * dispatch time by the 2026-era codec's `checkInboundEnvelope` step. + */ + const RequestMetaEnvelopeSchema = looseObject({ + progressToken: ProgressTokenSchema$1.optional(), + [auth_CUe6YdwF_PROTOCOL_VERSION_META_KEY]: schemas_string(), + [auth_CUe6YdwF_CLIENT_INFO_META_KEY]: ImplementationSchema$1.optional(), + [auth_CUe6YdwF_CLIENT_CAPABILITIES_META_KEY]: ClientCapabilities2026Schema, + [LOG_LEVEL_META_KEY]: LoggingLevelSchema$1.optional() + }); + /** 2026-era Tool: anchor-exact — no `execution` (deleted vocabulary). */ + const ToolSchema$1 = schemas_object({ + ...BaseMetadataSchema$1.shape, + ...IconsSchema$1.shape, + description: schemas_string().optional(), + inputSchema: looseObject({ + $schema: schemas_string().optional(), + type: literal("object") + }), + outputSchema: looseObject({ $schema: schemas_string().optional() }).optional(), + annotations: ToolAnnotationsSchema$1.optional(), + _meta: schemas_record(schemas_string(), unknown()).optional() + }); + /** 2026-era ToolResultContent (anchor-exact: `structuredContent?: unknown`). */ + const ToolResultContentSchema$1 = schemas_object({ + type: literal("tool_result"), + toolUseId: schemas_string(), + content: schemas_array(ContentBlockSchema$1), + structuredContent: unknown().optional(), + isError: schemas_boolean().optional(), + _meta: schemas_record(schemas_string(), unknown()).optional() + }); + /** 2026-era sampling content union (composes the forked tool-result shape). */ + const SamplingMessageContentBlockSchema$1 = schemas_union([ + TextContentSchema$1, + ImageContentSchema$1, + AudioContentSchema$1, + ToolUseContentSchema$1, + ToolResultContentSchema$1 + ]); + /** 2026-era SamplingMessage (anchor-exact: single block or array). */ + const SamplingMessageSchema$1 = schemas_object({ + role: RoleSchema$1, + content: schemas_union([SamplingMessageContentBlockSchema$1, schemas_array(SamplingMessageContentBlockSchema$1)]), + _meta: schemas_record(schemas_string(), unknown()).optional() + }); + /** Open union per the anchor: 'complete' | 'input_required' | string. */ + const ResultTypeSchema = schemas_string(); + /** + * Result `_meta` (anchor `ResultMetaObject`, added by spec PR #3002): + * loose, with the serverInfo key typed when present; the outbound stamp + * is the encode contract's `stampServerInfoMeta` step. + */ + const ResultMetaSchema = looseObject({ [auth_CUe6YdwF_SERVER_INFO_META_KEY]: ImplementationSchema$1.optional().catch(void 0) }); + const wireMeta = ResultMetaSchema.optional(); + function wireResult(shape) { + return looseObject({ + _meta: wireMeta, + resultType: ResultTypeSchema.default("complete"), + ...shape + }); + } + const ResultSchema$1 = wireResult({}); + const PaginatedResultSchema$1 = wireResult({ nextCursor: CursorSchema$1.optional() }); + const CallToolResultSchema$1 = wireResult({ + content: schemas_array(ContentBlockSchema$1), + structuredContent: unknown().optional(), + isError: schemas_boolean().optional() + }); + const ListToolsResultSchema$1 = wireResult({ + ttlMs: schemas_number().int().min(0), + cacheScope: schemas_enum(["public", "private"]), + tools: schemas_array(ToolSchema$1), + nextCursor: CursorSchema$1.optional() + }); + const ListPromptsResultSchema$1 = wireResult({ + ttlMs: schemas_number().int().min(0), + cacheScope: schemas_enum(["public", "private"]), + prompts: schemas_array(PromptSchema$1), + nextCursor: CursorSchema$1.optional() + }); + const GetPromptResultSchema$1 = wireResult({ + description: schemas_string().optional(), + messages: schemas_array(PromptMessageSchema$1) + }); + const ListResourcesResultSchema$1 = wireResult({ + ttlMs: schemas_number().int().min(0), + cacheScope: schemas_enum(["public", "private"]), + resources: schemas_array(ResourceSchema$1), + nextCursor: CursorSchema$1.optional() + }); + const ListResourceTemplatesResultSchema$1 = wireResult({ + ttlMs: schemas_number().int().min(0), + cacheScope: schemas_enum(["public", "private"]), + resourceTemplates: schemas_array(ResourceTemplateSchema$1), + nextCursor: CursorSchema$1.optional() + }); + const ReadResourceResultSchema$1 = wireResult({ + ttlMs: schemas_number().int().min(0), + cacheScope: schemas_enum(["public", "private"]), + contents: schemas_array(schemas_union([TextResourceContentsSchema$1, BlobResourceContentsSchema$1])) + }); + const CompleteResultSchema$1 = wireResult({ completion: schemas_object({ + values: schemas_array(schemas_string()).max(100), + total: schemas_number().int().optional(), + hasMore: schemas_boolean().optional() + }).loose() }); + /** CacheableResult (SEP-2549): ttlMs and cacheScope REQUIRED per the anchor. */ + const CacheableResultSchema = wireResult({ + ttlMs: schemas_number().int().min(0), + cacheScope: schemas_enum(["public", "private"]) + }); + const DiscoverResultSchema$1 = wireResult({ + ttlMs: schemas_number().int().min(0).catch(0), + cacheScope: schemas_enum(["public", "private"]).catch("private"), + supportedVersions: schemas_array(schemas_string()), + capabilities: ServerCapabilities2026Schema, + instructions: schemas_string().optional() + }); + /** 2026-era CreateMessageRequestParams (anchor-exact: forked SamplingMessage/Tool, no task augmentation). */ + const CreateMessageRequestParamsSchema$1 = schemas_object({ + messages: schemas_array(SamplingMessageSchema$1), + modelPreferences: ModelPreferencesSchema$1.optional(), + systemPrompt: schemas_string().optional(), + includeContext: schemas_enum([ + "none", + "thisServer", + "allServers" + ]).optional(), + temperature: schemas_number().optional(), + maxTokens: schemas_number().int(), + stopSequences: schemas_array(schemas_string()).optional(), + metadata: JSONObjectSchema$1.optional(), + tools: schemas_array(ToolSchema$1).optional(), + toolChoice: ToolChoiceSchema$1.optional() + }); + /** 2026-era embedded sampling request (de-JSON-RPC'd). */ + const CreateMessageRequestSchema$1 = schemas_object({ + method: literal("sampling/createMessage"), + params: CreateMessageRequestParamsSchema$1 + }); + /** + * 2026-era embedded roots listing request (de-JSON-RPC'd). Embedded input + * requests do NOT carry the per-request `_meta` envelope on this revision — + * the anchor declares a bare optional `_meta` on `params`. + */ + const ListRootsRequestSchema$1 = schemas_object({ + method: literal("roots/list"), + params: schemas_object({ _meta: schemas_record(schemas_string(), unknown()).optional() }).optional() + }); + /** 2026-era embedded sampling response (anchor-exact: extends the forked SamplingMessage). */ + const CreateMessageResultSchema$1 = schemas_object({ + ...SamplingMessageSchema$1.shape, + model: schemas_string(), + stopReason: schemas_string().optional() + }); + /** 2026-era embedded roots listing response (anchor-exact: bare `roots` array). */ + const ListRootsResultSchema$1 = schemas_object({ roots: schemas_array(RootSchema$1) }); + /** 2026-era embedded elicitation response (anchor-exact: bare result, restricted content value types). */ + const ElicitResultSchema$1 = schemas_object({ + action: schemas_enum([ + "accept", + "decline", + "cancel" + ]), + content: schemas_record(schemas_string(), schemas_union([ + schemas_string(), + schemas_number(), + schemas_boolean(), + schemas_array(schemas_string()) + ])).optional() + }); + /** + * 2026-era URL-mode elicitation params (anchor-exact fork): the draft removed + * `elicitationId` (and the `notifications/elicitation/complete` channel it + * keyed) — the shared schema keeps the field because it is required on the + * frozen 2025-11-25 revision. + */ + const ElicitRequestURLParamsSchema$1 = schemas_object({ + mode: literal("url"), + message: schemas_string(), + url: schemas_string().url() + }); + /** 2026-era elicitation params (form mode is revision-identical; URL mode is the fork above). */ + const ElicitRequestParamsSchema$1 = schemas_union([ElicitRequestFormParamsSchema$1, ElicitRequestURLParamsSchema$1]); + /** 2026-era embedded elicitation request (de-JSON-RPC'd; see the URL-mode fork above). */ + const ElicitRequestSchema$1 = schemas_object({ + method: literal("elicitation/create"), + params: ElicitRequestParamsSchema$1 + }); + /** A single embedded input request (one of the three demoted server→client requests). */ + const InputRequestSchema = schemas_union([ + CreateMessageRequestSchema$1, + ListRootsRequestSchema$1, + ElicitRequestSchema$1 + ]); + /** A single embedded input response — the BARE result union (never a `{method, result}` wrapper). */ + const InputResponseSchema = schemas_union([ + CreateMessageResultSchema$1, + ListRootsResultSchema$1, + ElicitResultSchema$1 + ]); + /** Map of embedded input requests, keyed by server-assigned identifiers. */ + const InputRequestsSchema = schemas_record(schemas_string(), InputRequestSchema); + /** Map of embedded input responses, keyed by the corresponding request identifiers. */ + const InputResponsesSchema = schemas_record(schemas_string(), InputResponseSchema); + /** + * The wire InputRequiredResult: `resultType: 'input_required'` plus at least + * one of `inputRequests` / `requestState` (the at-least-one rule is enforced + * at the server seam, not by this parse shape). + */ + const InputRequiredResultSchema = wireResult({ + inputRequests: InputRequestsSchema.optional(), + requestState: schemas_string().optional() + }); + /** The retry-channel members carried by client-initiated requests on this revision. */ + const retryParamsShape = { + inputResponses: InputResponsesSchema.optional(), + requestState: schemas_string().optional() + }; + /** Anchor InputResponseRequestParams: the retry channel on top of the required request `_meta` envelope. */ + const InputResponseRequestParamsSchema = schemas_object({ + _meta: RequestMetaEnvelopeSchema, + ...retryParamsShape + }); + /** Post-lift request `_meta` (progressToken + extension keys; loose). */ + const DispatchRequestMetaSchema = looseObject({ progressToken: ProgressTokenSchema$1.optional() }); + function wireRequest(method, paramsShape) { + return schemas_object({ + method: literal(method), + params: schemas_object({ + _meta: RequestMetaEnvelopeSchema, + ...paramsShape + }) + }); + } + function dispatchRequest(method, paramsShape) { + return schemas_object({ + method: literal(method), + params: schemas_object({ + _meta: DispatchRequestMetaSchema.optional(), + ...paramsShape + }).optional() + }); + } + const callToolParamsShape = { + name: schemas_string(), + arguments: schemas_record(schemas_string(), unknown()).optional(), + ...retryParamsShape + }; + const paginatedParamsShape = { cursor: CursorSchema$1.optional() }; + const CallToolRequestSchema$1 = wireRequest("tools/call", callToolParamsShape); + const ListToolsRequestSchema$1 = wireRequest("tools/list", paginatedParamsShape); + const ListPromptsRequestSchema$1 = wireRequest("prompts/list", paginatedParamsShape); + const GetPromptRequestSchema$1 = wireRequest("prompts/get", { + name: schemas_string(), + arguments: schemas_record(schemas_string(), schemas_string()).optional(), + ...retryParamsShape + }); + const ListResourcesRequestSchema$1 = wireRequest("resources/list", paginatedParamsShape); + const ListResourceTemplatesRequestSchema$1 = wireRequest("resources/templates/list", paginatedParamsShape); + const ReadResourceRequestSchema$1 = wireRequest("resources/read", { + uri: schemas_string(), + ...retryParamsShape + }); + const completeParamsShape = { + ref: schemas_union([PromptReferenceSchema$1, ResourceTemplateReferenceSchema$1]), + argument: schemas_object({ + name: schemas_string(), + value: schemas_string() + }), + context: schemas_object({ arguments: schemas_record(schemas_string(), schemas_string()).optional() }).optional() + }; + const CompleteRequestSchema$1 = wireRequest("completion/complete", completeParamsShape); + const DiscoverRequestSchema$1 = wireRequest("server/discover", {}); + /** Anchor SubscriptionFilter (2026-only). */ + const SubscriptionFilterSchema$1 = schemas_object({ + toolsListChanged: schemas_boolean().optional(), + promptsListChanged: schemas_boolean().optional(), + resourcesListChanged: schemas_boolean().optional(), + resourceSubscriptions: schemas_array(schemas_string()).optional() + }); + const subscriptionsListenParamsShape = { notifications: SubscriptionFilterSchema$1 }; + const SubscriptionsListenRequestSchema$1 = wireRequest("subscriptions/listen", subscriptionsListenParamsShape); + /** + * Anchor SubscriptionsListenResultMeta — required subscriptionId stamp on + * the graceful-close result. Extends `ResultMetaObject` since spec PR + * #3002 (composed, so the serverInfo key and its leniency stay single-sourced). + */ + const SubscriptionsListenResultMetaSchema$1 = ResultMetaSchema.extend({ "io.modelcontextprotocol/subscriptionId": RequestIdSchema$1 }); + /** + * Anchor SubscriptionsListenResult (2026-only). The empty `subscriptions/listen` + * response signalling that the subscription has ended gracefully (server + * shutdown). An abrupt transport close carries no response — the client treats + * stream-close-without-result as a disconnect. + */ + const SubscriptionsListenResultSchema$1 = looseObject({ + _meta: SubscriptionsListenResultMetaSchema$1, + resultType: ResultTypeSchema.default("complete") + }); + /** Dispatch (post-lift) request schemas, keyed by method — registry-internal. */ + const dispatchRequestSchemas = { + "tools/call": dispatchRequest("tools/call", callToolParamsShape), + "tools/list": dispatchRequest("tools/list", paginatedParamsShape), + "prompts/get": dispatchRequest("prompts/get", { + name: schemas_string(), + arguments: schemas_record(schemas_string(), schemas_string()).optional() + }), + "prompts/list": dispatchRequest("prompts/list", paginatedParamsShape), + "resources/list": dispatchRequest("resources/list", paginatedParamsShape), + "resources/templates/list": dispatchRequest("resources/templates/list", paginatedParamsShape), + "resources/read": dispatchRequest("resources/read", { uri: schemas_string() }), + "completion/complete": dispatchRequest("completion/complete", completeParamsShape), + "server/discover": dispatchRequest("server/discover", {}), + "subscriptions/listen": dispatchRequest("subscriptions/listen", subscriptionsListenParamsShape) + }; + /** Dispatch (post-lift) result schemas, keyed by method — what the funnel + * validates AFTER `decodeResult` consumed `resultType`. */ + function liftedResult(shape) { + return looseObject({ + _meta: wireMeta, + ...shape + }); + } + const dispatchResultSchemas = { + "tools/call": liftedResult({ + content: schemas_array(ContentBlockSchema$1), + structuredContent: unknown().optional(), + isError: schemas_boolean().optional() + }), + "tools/list": liftedResult({ + ttlMs: schemas_number().int().min(0), + cacheScope: schemas_enum(["public", "private"]), + tools: schemas_array(ToolSchema$1), + nextCursor: CursorSchema$1.optional() + }), + "prompts/get": liftedResult({ + description: schemas_string().optional(), + messages: schemas_array(PromptMessageSchema$1) + }), + "prompts/list": liftedResult({ + ttlMs: schemas_number().int().min(0), + cacheScope: schemas_enum(["public", "private"]), + prompts: schemas_array(PromptSchema$1), + nextCursor: CursorSchema$1.optional() + }), + "resources/list": liftedResult({ + ttlMs: schemas_number().int().min(0), + cacheScope: schemas_enum(["public", "private"]), + resources: schemas_array(ResourceSchema$1), + nextCursor: CursorSchema$1.optional() + }), + "resources/templates/list": liftedResult({ + ttlMs: schemas_number().int().min(0), + cacheScope: schemas_enum(["public", "private"]), + resourceTemplates: schemas_array(ResourceTemplateSchema$1), + nextCursor: CursorSchema$1.optional() + }), + "resources/read": liftedResult({ + ttlMs: schemas_number().int().min(0), + cacheScope: schemas_enum(["public", "private"]), + contents: schemas_array(schemas_union([TextResourceContentsSchema$1, BlobResourceContentsSchema$1])) + }), + "completion/complete": liftedResult({ completion: schemas_object({ + values: schemas_array(schemas_string()).max(100), + total: schemas_number().int().optional(), + hasMore: schemas_boolean().optional() + }).loose() }), + "server/discover": liftedResult({ + ttlMs: schemas_number().int().min(0).catch(0), + cacheScope: schemas_enum(["public", "private"]).catch("private"), + supportedVersions: schemas_array(schemas_string()), + capabilities: ServerCapabilities2026Schema, + instructions: schemas_string().optional() + }), + "subscriptions/listen": liftedResult({}) + }; + /** + * Notification `_meta` (anchor `NotificationMetaObject`): loose, with the + * subscriptions/listen demux key typed when present. Only the anchor-exact + * SHAPE is modeled here — listen delivery itself (filter gating, demux, + * teardown) is #14 scope and not implemented by this module. + */ + const NotificationMetaSchema = looseObject({ "io.modelcontextprotocol/subscriptionId": RequestIdSchema$1.optional() }); + /** Anchor SubscriptionsAcknowledgedNotification (2026-only). */ + const SubscriptionsAcknowledgedNotificationSchema$1 = schemas_object({ + method: literal("notifications/subscriptions/acknowledged"), + params: schemas_object({ + _meta: NotificationMetaSchema.optional(), + notifications: SubscriptionFilterSchema$1 + }) + }); + /** + * 2026-era `notifications/cancelled` params (anchor-exact fork): `requestId` + * is REQUIRED on this revision — the shared schema keeps it optional because + * the frozen 2025-11-25 shape declares it optional (task cancellation goes + * through `tasks/cancel` there). Requiredness is bare because no 2025-era + * traffic touches this module. + */ + const CancelledNotificationParamsSchema$1 = schemas_object({ + _meta: NotificationMetaSchema.optional(), + requestId: RequestIdSchema$1, + reason: schemas_string().optional() + }); + /** 2026-era `notifications/cancelled` (see the params fork above). */ + const CancelledNotificationSchema$1 = schemas_object({ + method: literal("notifications/cancelled"), + params: CancelledNotificationParamsSchema$1 + }); + const notificationSchemas2026 = { + "notifications/cancelled": CancelledNotificationSchema$1, + "notifications/progress": ProgressNotificationSchema$1, + "notifications/message": LoggingMessageNotificationSchema$1, + "notifications/resources/updated": ResourceUpdatedNotificationSchema$1, + "notifications/resources/list_changed": ResourceListChangedNotificationSchema$1, + "notifications/tools/list_changed": ToolListChangedNotificationSchema$1, + "notifications/prompts/list_changed": PromptListChangedNotificationSchema$1, + "notifications/subscriptions/acknowledged": SubscriptionsAcknowledgedNotificationSchema$1 + }; + const wireResultResponse = (result) => schemas_object({ + jsonrpc: literal("2.0"), + id: schemas_union([schemas_string(), schemas_number().int()]), + result + }).strict(); + return { + JSONValueSchema: JSONValueSchema$1, + JSONObjectSchema: JSONObjectSchema$1, + ProgressTokenSchema: ProgressTokenSchema$1, + CursorSchema: CursorSchema$1, + RequestIdSchema: RequestIdSchema$1, + RoleSchema: RoleSchema$1, + LoggingLevelSchema: LoggingLevelSchema$1, + TaskMetadataSchema: TaskMetadataSchema$1, + RelatedTaskMetadataSchema: RelatedTaskMetadataSchema$1, + RequestMetaSchema: RequestMetaSchema$1, + BaseRequestParamsSchema: BaseRequestParamsSchema$1, + TaskAugmentedRequestParamsSchema: TaskAugmentedRequestParamsSchema$1, + NotificationsParamsSchema: NotificationsParamsSchema$1, + NotificationSchema: NotificationSchema$1, + IconSchema: IconSchema$1, + IconsSchema: IconsSchema$1, + BaseMetadataSchema: BaseMetadataSchema$1, + ImplementationSchema: ImplementationSchema$1, + ClientTasksCapabilitySchema: ClientTasksCapabilitySchema$1, + ServerTasksCapabilitySchema: ServerTasksCapabilitySchema$1, + ClientCapabilitiesSchema: ClientCapabilitiesSchema$1, + ServerCapabilitiesSchema: ServerCapabilitiesSchema$1, + ProgressSchema: ProgressSchema$1, + ProgressNotificationParamsSchema: ProgressNotificationParamsSchema$1, + ProgressNotificationSchema: ProgressNotificationSchema$1, + LoggingMessageNotificationParamsSchema: LoggingMessageNotificationParamsSchema$1, + LoggingMessageNotificationSchema: LoggingMessageNotificationSchema$1, + ResourceContentsSchema: ResourceContentsSchema$1, + TextResourceContentsSchema: TextResourceContentsSchema$1, + BlobResourceContentsSchema: BlobResourceContentsSchema$1, + AnnotationsSchema: AnnotationsSchema$1, + ResourceSchema: ResourceSchema$1, + ResourceTemplateSchema: ResourceTemplateSchema$1, + ResourceListChangedNotificationSchema: ResourceListChangedNotificationSchema$1, + ResourceUpdatedNotificationParamsSchema: ResourceUpdatedNotificationParamsSchema$1, + ResourceUpdatedNotificationSchema: ResourceUpdatedNotificationSchema$1, + PromptArgumentSchema: PromptArgumentSchema$1, + PromptSchema: PromptSchema$1, + PromptListChangedNotificationSchema: PromptListChangedNotificationSchema$1, + TextContentSchema: TextContentSchema$1, + ImageContentSchema: ImageContentSchema$1, + AudioContentSchema: AudioContentSchema$1, + ToolUseContentSchema: ToolUseContentSchema$1, + EmbeddedResourceSchema: EmbeddedResourceSchema$1, + ResourceLinkSchema: ResourceLinkSchema$1, + ContentBlockSchema: ContentBlockSchema$1, + PromptMessageSchema: PromptMessageSchema$1, + ToolAnnotationsSchema: ToolAnnotationsSchema$1, + ToolListChangedNotificationSchema: ToolListChangedNotificationSchema$1, + ModelHintSchema: ModelHintSchema$1, + ModelPreferencesSchema: ModelPreferencesSchema$1, + ToolChoiceSchema: ToolChoiceSchema$1, + BooleanSchemaSchema: BooleanSchemaSchema$1, + StringSchemaSchema: StringSchemaSchema$1, + NumberSchemaSchema: NumberSchemaSchema$1, + UntitledSingleSelectEnumSchemaSchema: UntitledSingleSelectEnumSchemaSchema$1, + TitledSingleSelectEnumSchemaSchema: TitledSingleSelectEnumSchemaSchema$1, + LegacyTitledEnumSchemaSchema: LegacyTitledEnumSchemaSchema$1, + SingleSelectEnumSchemaSchema: SingleSelectEnumSchemaSchema$1, + UntitledMultiSelectEnumSchemaSchema: UntitledMultiSelectEnumSchemaSchema$1, + TitledMultiSelectEnumSchemaSchema: TitledMultiSelectEnumSchemaSchema$1, + MultiSelectEnumSchemaSchema: MultiSelectEnumSchemaSchema$1, + EnumSchemaSchema: EnumSchemaSchema$1, + PrimitiveSchemaDefinitionSchema: PrimitiveSchemaDefinitionSchema$1, + ElicitRequestFormParamsSchema: ElicitRequestFormParamsSchema$1, + ResourceTemplateReferenceSchema: ResourceTemplateReferenceSchema$1, + PromptReferenceSchema: PromptReferenceSchema$1, + RootSchema: RootSchema$1, + ClientCapabilities2026Schema, + ServerCapabilities2026Schema, + RequestMetaEnvelopeSchema, + ToolSchema: ToolSchema$1, + ToolResultContentSchema: ToolResultContentSchema$1, + SamplingMessageContentBlockSchema: SamplingMessageContentBlockSchema$1, + SamplingMessageSchema: SamplingMessageSchema$1, + ResultTypeSchema, + ResultMetaSchema, + ResultSchema: ResultSchema$1, + PaginatedResultSchema: PaginatedResultSchema$1, + CallToolResultSchema: CallToolResultSchema$1, + ListToolsResultSchema: ListToolsResultSchema$1, + ListPromptsResultSchema: ListPromptsResultSchema$1, + GetPromptResultSchema: GetPromptResultSchema$1, + ListResourcesResultSchema: ListResourcesResultSchema$1, + ListResourceTemplatesResultSchema: ListResourceTemplatesResultSchema$1, + ReadResourceResultSchema: ReadResourceResultSchema$1, + CompleteResultSchema: CompleteResultSchema$1, + CacheableResultSchema, + DiscoverResultSchema: DiscoverResultSchema$1, + CreateMessageRequestParamsSchema: CreateMessageRequestParamsSchema$1, + CreateMessageRequestSchema: CreateMessageRequestSchema$1, + ListRootsRequestSchema: ListRootsRequestSchema$1, + CreateMessageResultSchema: CreateMessageResultSchema$1, + ListRootsResultSchema: ListRootsResultSchema$1, + ElicitResultSchema: ElicitResultSchema$1, + ElicitRequestURLParamsSchema: ElicitRequestURLParamsSchema$1, + ElicitRequestParamsSchema: ElicitRequestParamsSchema$1, + ElicitRequestSchema: ElicitRequestSchema$1, + InputRequestSchema, + InputResponseSchema, + InputRequestsSchema, + InputResponsesSchema, + InputRequiredResultSchema, + InputResponseRequestParamsSchema, + CallToolRequestSchema: CallToolRequestSchema$1, + ListToolsRequestSchema: ListToolsRequestSchema$1, + ListPromptsRequestSchema: ListPromptsRequestSchema$1, + GetPromptRequestSchema: GetPromptRequestSchema$1, + ListResourcesRequestSchema: ListResourcesRequestSchema$1, + ListResourceTemplatesRequestSchema: ListResourceTemplatesRequestSchema$1, + ReadResourceRequestSchema: ReadResourceRequestSchema$1, + CompleteRequestSchema: CompleteRequestSchema$1, + DiscoverRequestSchema: DiscoverRequestSchema$1, + SubscriptionFilterSchema: SubscriptionFilterSchema$1, + SubscriptionsListenRequestSchema: SubscriptionsListenRequestSchema$1, + SubscriptionsListenResultMetaSchema: SubscriptionsListenResultMetaSchema$1, + SubscriptionsListenResultSchema: SubscriptionsListenResultSchema$1, + dispatchRequestSchemas, + dispatchResultSchemas, + NotificationMetaSchema, + SubscriptionsAcknowledgedNotificationSchema: SubscriptionsAcknowledgedNotificationSchema$1, + CancelledNotificationParamsSchema: CancelledNotificationParamsSchema$1, + CancelledNotificationSchema: CancelledNotificationSchema$1, + notificationSchemas2026, + JSONRPCResultResponseSchema: wireResultResponse(ResultSchema$1), + CallToolResultResponseSchema: wireResultResponse(schemas_union([CallToolResultSchema$1, InputRequiredResultSchema])), + ListToolsResultResponseSchema: wireResultResponse(ListToolsResultSchema$1), + ListPromptsResultResponseSchema: wireResultResponse(ListPromptsResultSchema$1), + GetPromptResultResponseSchema: wireResultResponse(schemas_union([GetPromptResultSchema$1, InputRequiredResultSchema])), + ListResourcesResultResponseSchema: wireResultResponse(ListResourcesResultSchema$1), + ListResourceTemplatesResultResponseSchema: wireResultResponse(ListResourceTemplatesResultSchema$1), + ReadResourceResultResponseSchema: wireResultResponse(schemas_union([ReadResourceResultSchema$1, InputRequiredResultSchema])), + CompleteResultResponseSchema: wireResultResponse(CompleteResultSchema$1), + DiscoverResultResponseSchema: wireResultResponse(DiscoverResultSchema$1) + }; +} +let src_CX2iR2pK_memo; +/** +* Builds the era wire-schema set on first call and returns the same object +* thereafter. Module evaluation stays construction-free so importing the +* era codec/registry costs nothing until the first validation actually +* needs a schema; the registry, the codec, and the eager `schemas.ts` +* shim all pull through this memo, so reference identity holds across +* every consumer. +*/ +function buildSchemas2026() { + return src_CX2iR2pK_memo ??= build(); +} + +//#endregion +//#region ../core-internal/src/shared/resultCacheHints.ts +/** +* The operations whose results are cacheable on the 2026-07-28 revision (the +* `CacheableResult` extenders). This list is closed: no other operation's +* result ever receives cache fields from the SDK. +*/ +const CACHEABLE_RESULT_METHODS = [ + "tools/list", + "prompts/list", + "resources/list", + "resources/templates/list", + "resources/read", + "server/discover" +]; +/** Whether the given method's result is cacheable on the 2026-07-28 revision. */ +function isCacheableResultMethod(method) { + return CACHEABLE_RESULT_METHODS.includes(method); +} +/** +* The symbol-keyed carrier for a configured cache hint on a result object. +* Symbol properties are invisible to JSON serialization, so the carrier can be +* attached era-blind: only the 2026-era encode seam consumes it. +*/ +const RESULT_CACHE_HINT_FALLBACK = Symbol("modelcontextprotocol.resultCacheHintFallback"); +/** +* Attaches a configured cache hint to a result as the encode-time fallback. +* Returns the result unchanged when there is nothing to attach. When a more +* specific hint is already attached, the two hints are combined per field +* (most-specific-author-wins for each of `ttlMs` and `cacheScope`): the +* per-registration hint attached by the feature layer keeps every field it +* sets, and the server-level per-operation hint only fills the fields the +* more specific hint leaves unset. +*/ +function attachCacheHintFallback(result, hint) { + if (hint === void 0) return result; + const attached = result[RESULT_CACHE_HINT_FALLBACK]; + if (attached === void 0) return { + ...result, + [RESULT_CACHE_HINT_FALLBACK]: hint + }; + const merged = {}; + const ttlMs = attached.ttlMs ?? hint.ttlMs; + if (ttlMs !== void 0) merged.ttlMs = ttlMs; + const cacheScope = attached.cacheScope ?? hint.cacheScope; + if (cacheScope !== void 0) merged.cacheScope = cacheScope; + return { + ...result, + [RESULT_CACHE_HINT_FALLBACK]: merged + }; +} +/** Reads the configured cache-hint fallback attached to a result, if any. */ +function cacheHintFallbackOf(result) { + return result[RESULT_CACHE_HINT_FALLBACK]; +} +/** +* Whether a value is a valid `ttlMs`: a non-negative safe integer. Safe +* integers are required because the wire schemas validate `ttlMs` as an +* integer within `Number.MIN_SAFE_INTEGER`/`Number.MAX_SAFE_INTEGER`; a value +* outside that range is treated as invalid here so it falls through to the +* next author instead of being emitted and rejected downstream. +*/ +function isValidCacheTtlMs(value) { + return typeof value === "number" && Number.isSafeInteger(value) && value >= 0; +} +/** Whether a value is a valid `cacheScope`. */ +function isValidCacheScope(value) { + return value === "public" || value === "private"; +} +/** +* Validates a configured cache hint at configuration time. Throws a +* `RangeError` naming the offending field, so misconfiguration fails at +* startup/registration rather than silently degrading at encode time. +*/ +function assertValidCacheHint(hint, context) { + if (hint.ttlMs !== void 0 && !isValidCacheTtlMs(hint.ttlMs)) throw new RangeError(`Invalid cache hint for ${context}: ttlMs must be a non-negative safe integer (got ${String(hint.ttlMs)})`); + if (hint.cacheScope !== void 0 && !isValidCacheScope(hint.cacheScope)) throw new RangeError(`Invalid cache hint for ${context}: cacheScope must be 'public' or 'private' (got ${String(hint.cacheScope)})`); +} + +//#endregion +//#region ../core-internal/src/types/enums.ts +/** +* Error codes for protocol errors that cross the wire as JSON-RPC error responses. +* These follow the JSON-RPC specification and MCP-specific extensions. +*/ +let src_CX2iR2pK_ProtocolErrorCode = /* @__PURE__ */ function(ProtocolErrorCode$1) { + ProtocolErrorCode$1[ProtocolErrorCode$1["ParseError"] = -32700] = "ParseError"; + ProtocolErrorCode$1[ProtocolErrorCode$1["InvalidRequest"] = -32600] = "InvalidRequest"; + ProtocolErrorCode$1[ProtocolErrorCode$1["MethodNotFound"] = -32601] = "MethodNotFound"; + ProtocolErrorCode$1[ProtocolErrorCode$1["InvalidParams"] = -32602] = "InvalidParams"; + ProtocolErrorCode$1[ProtocolErrorCode$1["InternalError"] = -32603] = "InternalError"; + /** + * Resource not found. + * + * Receive-tolerated only: the SDK never EMITS `-32002` — `resources/read` + * misses answer `-32602` (Invalid Params) on every protocol revision per + * the 2026-07-28 spec MUST, and a handler-thrown `-32002` is mapped to + * `-32602` at the era encode seam. The member stays importable so clients + * can recognise `-32002` from peers built on earlier SDK releases (the + * spec's "clients SHOULD also accept `-32002`" backwards-compatibility + * clause). Throw `ResourceNotFoundError` instead. + */ + ProtocolErrorCode$1[ProtocolErrorCode$1["ResourceNotFound"] = -32002] = "ResourceNotFound"; + /** + * Processing the request requires a capability the client did not declare + * in the request's `clientCapabilities` (protocol revision 2026-07-28). + */ + ProtocolErrorCode$1[ProtocolErrorCode$1["MissingRequiredClientCapability"] = -32021] = "MissingRequiredClientCapability"; + /** + * The request's protocol version is unknown to the server or unsupported + * by it (protocol revision 2026-07-28). + */ + ProtocolErrorCode$1[ProtocolErrorCode$1["UnsupportedProtocolVersion"] = -32022] = "UnsupportedProtocolVersion"; + ProtocolErrorCode$1[ProtocolErrorCode$1["UrlElicitationRequired"] = -32042] = "UrlElicitationRequired"; + return ProtocolErrorCode$1; +}({}); + +//#endregion +//#region ../core-internal/src/types/errors.ts +/** +* Protocol errors are JSON-RPC errors that cross the wire as error responses. +* They use numeric error codes from the {@linkcode ProtocolErrorCode} enum. +* +* `instanceof` on this class (and its subclasses) is brand-matched, so it works +* across separately bundled copies of the SDK — e.g. an error constructed by +* `@modelcontextprotocol/client` matches the class re-exported by +* `@modelcontextprotocol/server` in the same process. +*/ +var src_CX2iR2pK_ProtocolError = class ProtocolError extends Error { + static { + Object.defineProperty(this, "mcpBrand", { value: "mcp.ProtocolError" }); + } + static [Symbol.hasInstance](value) { + return brandedHasInstance(this, value); + } + /** + * Brand-based type guard: equivalent to `value instanceof this`, as an + * explicit static predicate (the axios/AWS-SDK `isInstance` style). Reads + * the caller's own brand via `this`, so every branded subclass gets a + * correctly-scoped guard by inheritance. Must be invoked on the class — + * in callback position write `v => SdkError.isInstance(v)`, not + * `.filter(SdkError.isInstance)` (detached calls throw rather than + * silently matching nothing). + */ + static isInstance(value) { + 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 brandedHasInstance(this, value); + } + constructor(code, message, data) { + super(message); + this.code = code; + this.data = data; + this.name = "ProtocolError"; + stampErrorBrands(this, new.target); + } + /** + * Factory method to create the appropriate error type based on the error code and data + */ + static fromError(code, message, data) { + if (code === src_CX2iR2pK_ProtocolErrorCode.UrlElicitationRequired && data) { + const errorData = data; + if (errorData.elicitations) return new UrlElicitationRequiredError(errorData.elicitations, message); + } + if (code === src_CX2iR2pK_ProtocolErrorCode.UnsupportedProtocolVersion && data) { + const errorData = data; + if (Array.isArray(errorData.supported) && typeof errorData.requested === "string") return new src_CX2iR2pK_UnsupportedProtocolVersionError({ + supported: errorData.supported, + requested: errorData.requested + }, message); + } + if (code === src_CX2iR2pK_ProtocolErrorCode.InvalidParams || code === src_CX2iR2pK_ProtocolErrorCode.ResourceNotFound) { + const errorData = data; + if (typeof errorData?.uri === "string" && (code === src_CX2iR2pK_ProtocolErrorCode.ResourceNotFound || Object.keys(errorData).length === 1)) return new ResourceNotFoundError(errorData.uri, message); + } + if (code === src_CX2iR2pK_ProtocolErrorCode.MissingRequiredClientCapability && data) { + const errorData = data; + if (errorData.requiredCapabilities !== null && typeof errorData.requiredCapabilities === "object" && !Array.isArray(errorData.requiredCapabilities)) return new src_CX2iR2pK_MissingRequiredClientCapabilityError({ requiredCapabilities: errorData.requiredCapabilities }, message); + } + return new ProtocolError(code, message, data); + } +}; +/** +* Error type for a `resources/read` miss: the requested resource does not +* exist. The wire code is `-32602` (Invalid Params) on every protocol +* revision — the spec MUST for revision 2026-07-28, and the value the v1.x +* SDK has always emitted on earlier revisions. The error data echoes the +* requested URI. +* +* Recognise this error by checking `error.data` is exactly `{ uri: string }` +* (a `-32602` whose data carries `uri` and nothing else is resource-not-found; +* any other `-32602` is an ordinary Invalid Params). For backwards compatibility, clients should also +* accept `-32002` as resource not found — earlier SDK builds emitted that +* code, and {@linkcode ProtocolError.fromError} reconstructs this class for +* either code **when `error.data` carries `uri`** (a bare `-32002` without +* `data.uri` stays a generic {@linkcode ProtocolError}). `instanceof` checks +* are brand-matched and work across separately bundled copies of the SDK. +*/ +var ResourceNotFoundError = class extends src_CX2iR2pK_ProtocolError { + static { + Object.defineProperty(this, "mcpBrand", { value: "mcp.ResourceNotFoundError" }); + } + constructor(uri, message = `Resource not found: ${uri}`) { + super(src_CX2iR2pK_ProtocolErrorCode.InvalidParams, message, { uri }); + } + /** The URI that was requested and not found. */ + get uri() { + return this.data.uri; + } +}; +/** +* Specialized error type when a tool requires a URL mode elicitation. +* This makes it nicer for the client to handle since there is specific data to work with instead of just a code to check against. +*/ +var UrlElicitationRequiredError = class extends src_CX2iR2pK_ProtocolError { + static { + Object.defineProperty(this, "mcpBrand", { value: "mcp.UrlElicitationRequiredError" }); + } + constructor(elicitations, message = `URL elicitation${elicitations.length > 1 ? "s" : ""} required`) { + super(src_CX2iR2pK_ProtocolErrorCode.UrlElicitationRequired, message, { elicitations }); + } + get elicitations() { + return this.data?.elicitations ?? []; + } +}; +/** +* Error type for the `-32022` UnsupportedProtocolVersion protocol error (protocol +* revision 2026-07-28): the request's protocol version is unknown to the server or +* unsupported by it. +* +* The error data lists the protocol versions the receiver supports (`supported`), +* so the sender can choose a mutually supported version and retry, and echoes the +* version that was requested (`requested`). +*/ +var src_CX2iR2pK_UnsupportedProtocolVersionError = class extends src_CX2iR2pK_ProtocolError { + static { + Object.defineProperty(this, "mcpBrand", { value: "mcp.UnsupportedProtocolVersionError" }); + } + constructor(data, message = `Unsupported protocol version: ${data.requested}`) { + super(src_CX2iR2pK_ProtocolErrorCode.UnsupportedProtocolVersion, message, data); + } + /** + * Protocol versions the receiver supports. + */ + get supported() { + return this.data.supported; + } + /** + * The protocol version that was requested. + */ + get requested() { + return this.data.requested; + } +}; +/** +* Error type for the `-32021` MissingRequiredClientCapability protocol error +* (protocol revision 2026-07-28): processing the request requires a capability +* the client did not declare in the request's `clientCapabilities`. +* +* The error data lists the missing capabilities (`requiredCapabilities`) in +* the `ClientCapabilities` shape, so the client can see exactly what it would +* have to declare for the request to be served. On HTTP, the response status +* is `400 Bad Request`. +* +* Recognize this error by its code and `data.requiredCapabilities`, or by +* `instanceof` — checks are brand-matched and work across separately bundled +* copies of the SDK. +*/ +var src_CX2iR2pK_MissingRequiredClientCapabilityError = class extends src_CX2iR2pK_ProtocolError { + static { + Object.defineProperty(this, "mcpBrand", { value: "mcp.MissingRequiredClientCapabilityError" }); + } + constructor(data, message = `Missing required client capabilities: ${Object.keys(data.requiredCapabilities).join(", ")}`) { + super(src_CX2iR2pK_ProtocolErrorCode.MissingRequiredClientCapability, message, data); + } + /** + * The capabilities the server requires from the client to process the + * request (only the missing capabilities are listed). + */ + get requiredCapabilities() { + return this.data.requiredCapabilities; + } +}; + +//#endregion +//#region ../core-internal/src/wire/rev2026-07-28/encodeContract.ts +/** The default cache policy when neither the handler nor configuration provides one. */ +const DEFAULT_CACHE_TTL_MS = 0; +const DEFAULT_CACHE_SCOPE = "private"; +/** +* Request methods whose spec result vocabulary goes beyond `'complete'` on the +* 2026-07-28 revision: their results may be `input_required` (multi +* round-trip requests), so a handler-provided `resultType` passes through the +* stamp untouched. `subscriptions/listen` is NOT in this set: it never emits +* a JSON-RPC result — termination is stream close (HTTP) or +* `notifications/cancelled` (stdio) per the spec. +*/ +const EXTENDED_RESULT_TYPE_METHODS = [ + "tools/call", + "prompts/get", + "resources/read" +]; +/** +* Step 1 of the encode contract: ensure the outbound result carries the +* required `resultType` discriminator. +* +* - No handler-provided value → stamp `'complete'`. +* - Handler-provided `'complete'` → kept as-is. +* - Handler-provided non-`'complete'` value on a method whose vocabulary +* allows it ({@linkcode EXTENDED_RESULT_TYPE_METHODS}) → passes through. +* The value is forwarded verbatim — the wire vocabulary is an open union and +* the SDK does not validate the string, so emitting a `resultType` the +* negotiated revision does not define is the handler author's +* responsibility. +* - Handler-provided non-`'complete'` value on any other method → internal +* error (loud): the value would be mis-typed on the wire, and silently +* rewriting it would hide a server bug. +*/ +function stampResultType(method, result) { + const provided = result["resultType"]; + if (provided === void 0) return { + ...result, + resultType: "complete" + }; + if (provided === "complete") return result; + if (EXTENDED_RESULT_TYPE_METHODS.includes(method)) return result; + throw new src_CX2iR2pK_ProtocolError(src_CX2iR2pK_ProtocolErrorCode.InternalError, `Handler for ${method} returned resultType '${String(provided)}', but results of ${method} only support 'complete' on protocol revision 2026-07-28`); +} +/** +* Step 2 of the encode contract: fill the required `ttlMs`/`cacheScope` fields +* on cacheable results. +* +* Applies only when the (post-stamp) `resultType` is `'complete'` and the +* method is one of the cacheable operations; everything else is returned +* untouched apart from removing the configured-hint carrier. Field resolution +* is per field, most specific author first: a valid handler-returned value, +* then the configured cache hint attached by the server layer, then the +* defaults. Handler-returned values are validated at encode time (`ttlMs` +* must be a non-negative integer, `cacheScope` must be `'public'` or +* `'private'`); invalid values are ignored rather than emitted. +*/ +function fillCacheFields(method, result) { + const fallback = cacheHintFallbackOf(result); + if (result["resultType"] !== "complete" || !isCacheableResultMethod(method)) return fallback === void 0 ? result : stripCacheHintFallback(result); + const provided = result; + const ttlMs = isValidCacheTtlMs(provided["ttlMs"]) ? provided["ttlMs"] : resolveTtlMs(fallback); + const cacheScope = isValidCacheScope(provided["cacheScope"]) ? provided["cacheScope"] : resolveCacheScope(fallback); + const filled = { + ...provided, + ttlMs, + cacheScope + }; + delete filled[RESULT_CACHE_HINT_FALLBACK]; + return filled; +} +function isPlainObject$5(value) { + return value !== null && typeof value === "object" && !Array.isArray(value); +} +/** +* Step 3 of the encode contract: stamp the server's identity into the +* result's `_meta` under `io.modelcontextprotocol/serverInfo` (spec PR #3002: +* servers SHOULD include it on every response). +* +* - No `serverInfo` supplied (a client instance, or a hand-constructed +* protocol object) → identity function. +* - The result's `_meta` already carries the key → kept as-is (the handler +* is the more specific author; mirrors the cache-fill resolution order). +* - A present-but-non-object `_meta` (a dynamic-caller bug) → kept as-is: +* the stamp never rewrites handler material, and the malformed value fails +* loudly at the peer instead of being silently replaced here. +* - Otherwise → the key is added, preserving any other `_meta` entries. +* +* Runs for every result regardless of `resultType`: the anchor types +* `Result._meta` as `ResultMetaObject` on all results, `input_required` +* included. +*/ +function stampServerInfoMeta(result, serverInfo) { + if (serverInfo === void 0) return result; + const meta = result["_meta"]; + if (meta === void 0) return { + ...result, + _meta: { [auth_CUe6YdwF_SERVER_INFO_META_KEY]: serverInfo } + }; + if (!isPlainObject$5(meta)) return result; + if (meta[auth_CUe6YdwF_SERVER_INFO_META_KEY] !== void 0) return result; + return { + ...result, + _meta: { + ...meta, + [auth_CUe6YdwF_SERVER_INFO_META_KEY]: serverInfo + } + }; +} +function resolveTtlMs(fallback) { + return fallback !== void 0 && isValidCacheTtlMs(fallback.ttlMs) ? fallback.ttlMs : DEFAULT_CACHE_TTL_MS; +} +function resolveCacheScope(fallback) { + return fallback !== void 0 && isValidCacheScope(fallback.cacheScope) ? fallback.cacheScope : DEFAULT_CACHE_SCOPE; +} +function stripCacheHintFallback(result) { + const copy = { ...result }; + delete copy[RESULT_CACHE_HINT_FALLBACK]; + return copy; +} + +//#endregion +//#region ../core-internal/src/wire/rev2026-07-28/inputRequired.ts +/** +* In-band input-request vocabulary of the 2026-07-28 revision (SEP-2322 +* multi round-trip requests), dispatch view. +* +* The three former server→client wire requests (`elicitation/create`, +* `sampling/createMessage`, `roots/list`) are NOT wire request methods on +* this revision — they are demoted to de-JSON-RPC'd payloads embedded in an +* `input_required` result. The multi-round-trip driver dispatches those +* embedded payloads to the client's registered handlers through the normal +* handler machinery, and these are the schemas that dispatch parses them +* with: lenient where the anchor's wire-true artifacts are strict (an +* embedded request never carries the per-request `_meta` envelope), exact +* where the vocabulary forks (the sampling shapes compose the forked +* SamplingMessage/Tool payloads). +* +* Registry membership is intentionally NOT granted here — these methods stay +* absent from the 2026-era request registry (a peer sending one as a wire +* request still gets −32601 by absence). Only the codec's +* `inputRequestSchema`/`inputResponseSchema` accessors expose them. +*/ +/** The embedded input-request methods of the 2026-07-28 revision. */ +const INPUT_REQUEST_METHODS_2026 = [ + "elicitation/create", + "sampling/createMessage", + "roots/list" +]; +let maps; +function inputSchemaMaps() { + if (maps) return maps; + const s = buildSchemas2026(); + maps = { + request: { + "elicitation/create": schemas_object({ + method: literal("elicitation/create"), + params: s.ElicitRequestParamsSchema + }), + "sampling/createMessage": schemas_object({ + method: literal("sampling/createMessage"), + params: s.CreateMessageRequestParamsSchema + }), + "roots/list": schemas_object({ + method: literal("roots/list"), + params: looseObject({}).optional() + }) + }, + response: { + "elicitation/create": s.ElicitResultSchema, + "sampling/createMessage": s.CreateMessageResultSchema, + "roots/list": s.ListRootsResultSchema + } + }; + return maps; +} +/** +* Forces the lazy embedded-request maps (and, through them, the era's schema +* memo). Warm-up hook for `preloadSchemas()` — no-op once the maps exist. +*/ +function warmInputSchemaMaps2026() { + inputSchemaMaps(); +} +function isInputRequestMethod2026(method) { + return INPUT_REQUEST_METHODS_2026.includes(method); +} +function getInputRequestSchema2026(method) { + return isInputRequestMethod2026(method) ? inputSchemaMaps().request[method] : void 0; +} +function getInputResponseSchema2026(method) { + return isInputRequestMethod2026(method) ? inputSchemaMaps().response[method] : void 0; +} + +//#endregion +//#region ../core-internal/src/wire/rev2026-07-28/registry.ts +const requestMethodKeys = { + "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 +}; +const notificationMethodKeys = { + "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 +}; +/** The 2026-era request-method set (registry membership = the deletion story). */ +function hasRequestMethod2026(method) { + return Object.prototype.hasOwnProperty.call(requestMethodKeys, method); +} +/** The 2026-era notification-method set. */ +function hasNotificationMethod2026(method) { + return Object.prototype.hasOwnProperty.call(notificationMethodKeys, method); +} +/** Result-map membership (same key set as the request map on this era). */ +function hasResultMethod2026(method) { + return Object.prototype.hasOwnProperty.call(requestMethodKeys, method); +} +function getRequestSchema2026(method) { + return hasRequestMethod2026(method) ? buildSchemas2026().dispatchRequestSchemas[method] : void 0; +} +function getResultSchema2026(method) { + return hasResultMethod2026(method) ? buildSchemas2026().dispatchResultSchemas[method] : void 0; +} +function getNotificationSchema2026(method) { + return hasNotificationMethod2026(method) ? buildSchemas2026().notificationSchemas2026[method] : void 0; +} +/** Registry method lists (for the spec-method universe and the CI registry-diff oracle). */ +const rev2026RequestMethods = Object.keys(requestMethodKeys); +const rev2026NotificationMethods = Object.keys(notificationMethodKeys); + +//#endregion +//#region ../core-internal/src/wire/rev2026-07-28/codec.ts +function isPlainObject$4(value) { + return value !== null && typeof value === "object" && !Array.isArray(value); +} +/** Tri-state wrap of an optional Zod schema lookup (the function-only contract). */ +function triState(schema, raw) { + if (schema === void 0) return { + ok: false, + reason: "not-in-era" + }; + const parsed = schema.safeParse(raw); + return parsed.success ? { + ok: true, + value: parsed.data + } : { + ok: false, + reason: "invalid", + message: String(parsed.error) + }; +} +const NOT_IN_ERA = { + ok: false, + reason: "not-in-era" +}; +/** +* The reserved `_meta` keys an envelope must carry on this era (in reporting +* order). `clientInfo` is NOT here: spec PR #3002 demoted it to SHOULD, so a +* request without it is accepted (a present-but-malformed value still fails +* the envelope schema parse below). +*/ +const REQUIRED_ENVELOPE_KEYS = [auth_CUe6YdwF_PROTOCOL_VERSION_META_KEY, auth_CUe6YdwF_CLIENT_CAPABILITIES_META_KEY]; +/** Strip the known deleted-field set from an outbound result (Q1-SD3 iii). */ +function enforceDeletedFields(method, result) { + let next = result; + let copied = false; + const copy = () => { + if (!copied) { + next = { ...next }; + copied = true; + } + return next; + }; + const tools = result.tools; + if (method === "tools/list" && Array.isArray(tools) && tools.some((tool) => isPlainObject$4(tool) && "execution" in tool)) copy().tools = tools.map((tool) => { + if (!isPlainObject$4(tool) || !("execution" in tool)) return tool; + const rest = { ...tool }; + delete rest["execution"]; + return rest; + }); + const capabilities = result.capabilities; + if (isPlainObject$4(capabilities) && "tasks" in capabilities) { + const rest = { ...capabilities }; + delete rest["tasks"]; + copy().capabilities = rest; + } + return next; +} +const rev2026Codec = { + era: "2026-07-28", + hasRequestMethod: hasRequestMethod2026, + hasNotificationMethod: hasNotificationMethod2026, + hasInputRequestMethod: (method) => getInputRequestSchema2026(method) !== void 0, + validateRequest: (method, raw) => triState(getRequestSchema2026(method), raw), + validateResult: (method, raw) => triState(getResultSchema2026(method), raw), + validateNotification: (method, raw) => triState(getNotificationSchema2026(method), raw), + validateInputRequest: (method, raw) => triState(getInputRequestSchema2026(method), raw), + validateInputResponse: (method, raw) => triState(getInputResponseSchema2026(method), raw), + samplingResultVariant: () => NOT_IN_ERA, + outboundEnvelope(material) { + return { + [auth_CUe6YdwF_PROTOCOL_VERSION_META_KEY]: material.protocolVersion, + [auth_CUe6YdwF_CLIENT_INFO_META_KEY]: material.clientInfo, + [auth_CUe6YdwF_CLIENT_CAPABILITIES_META_KEY]: material.clientCapabilities, + ...material.logLevel !== void 0 && { [LOG_LEVEL_META_KEY]: material.logLevel } + }; + }, + validateEnvelopeMeta(meta) { + const issues = []; + for (const key of REQUIRED_ENVELOPE_KEYS) if (!(key in meta)) issues.push({ + key, + problem: "missing" + }); + const parsed = buildSchemas2026().RequestMetaEnvelopeSchema.safeParse(meta); + if (!parsed.success) for (const issue of parsed.error.issues) { + const path = issue.path.map(String); + const key = path.length > 0 ? path.join(".") : "_meta"; + if (path.length === 1 && issues.some((existing) => existing.key === key && existing.problem === "missing")) continue; + issues.push({ + key, + problem: issue.message + }); + } + return issues; + }, + projectCallToolResult: (result) => appendTextFallbackForNonObject(result), + inputRequestSchema: getInputRequestSchema2026, + decodeResult(method, raw) { + if (!isPlainObject$4(raw)) return { + kind: "invalid", + error: new src_CX2iR2pK_SdkError(src_CX2iR2pK_SdkErrorCode.InvalidResult, `Invalid result for ${method}: not an object`, { method }) + }; + const rawResultType = raw["resultType"]; + if (rawResultType === void 0) return { + kind: "invalid", + error: new src_CX2iR2pK_SdkError(src_CX2iR2pK_SdkErrorCode.InvalidResult, `Invalid result for ${method}: missing required resultType — servers implementing protocol revision 2026-07-28 MUST include it (the absent-means-complete bridge applies only to earlier-revision servers)`, { + method, + violation: "missing-resultType" + }) + }; + if (typeof rawResultType !== "string") return { + kind: "invalid", + error: new src_CX2iR2pK_SdkError(src_CX2iR2pK_SdkErrorCode.InvalidResult, `Invalid result for ${method}: non-string resultType`, { + method, + resultType: rawResultType + }) + }; + if (rawResultType === "input_required") { + const rawInputRequests = raw["inputRequests"]; + const inputRequests = isPlainObject$4(rawInputRequests) ? rawInputRequests : {}; + const requestState = raw["requestState"]; + if (Object.keys(inputRequests).length === 0 && typeof requestState !== "string") return { + kind: "invalid", + error: new src_CX2iR2pK_SdkError(src_CX2iR2pK_SdkErrorCode.InvalidResult, `Invalid result for ${method}: input_required carries neither inputRequests nor requestState (every input_required result must include at least one of the two)`, { + method, + violation: "input-required-missing-both" + }) + }; + return { + kind: "input_required", + inputRequests, + ...typeof requestState === "string" && { requestState } + }; + } + if (rawResultType !== "complete") return { + kind: "invalid", + error: new src_CX2iR2pK_SdkError(src_CX2iR2pK_SdkErrorCode.UnsupportedResultType, `Unsupported result type '${rawResultType}' for ${method}`, { + resultType: rawResultType, + method + }) + }; + const wireResultSchemas = getWireResultSchemas(); + const wireSchema = Object.hasOwn(wireResultSchemas, method) ? wireResultSchemas[method] : void 0; + if (wireSchema !== void 0) { + const parsed = wireSchema.safeParse(raw); + if (!parsed.success) return { + kind: "invalid", + error: new src_CX2iR2pK_SdkError(src_CX2iR2pK_SdkErrorCode.InvalidResult, `Invalid result for ${method}: ${parsed.error}`, { method }) + }; + } + const lifted = { ...raw }; + delete lifted["resultType"]; + return { + kind: "complete", + result: lifted + }; + }, + encodeResult(method, result, serverInfo) { + return stampServerInfoMeta(fillCacheFields(method, stampResultType(method, enforceDeletedFields(method, result))), serverInfo); + }, + encodeErrorCode: (code) => code === -32002 ? -32602 : code, + checkInboundEnvelope(material) { + if (material.envelope === void 0) return "Request is missing the required _meta envelope for protocol revision 2026-07-28 (io.modelcontextprotocol/protocolVersion, io.modelcontextprotocol/clientCapabilities)"; + const parsed = buildSchemas2026().RequestMetaEnvelopeSchema.safeParse(material.envelope); + if (!parsed.success) return `Invalid _meta envelope for protocol revision 2026-07-28: ${parsed.error.issues.map((issue) => issue.message).join("; ")}`; + } +}; +/** Wire-true result wrappers consulted by decode step 2, keyed by method — +* built once through the era's schema memo on the first decode. */ +let wireResultSchemasMemo; +function getWireResultSchemas() { + if (wireResultSchemasMemo) return wireResultSchemasMemo; + const s = buildSchemas2026(); + wireResultSchemasMemo = { + "tools/call": s.CallToolResultSchema, + "tools/list": s.ListToolsResultSchema, + "prompts/get": s.GetPromptResultSchema, + "prompts/list": s.ListPromptsResultSchema, + "resources/list": s.ListResourcesResultSchema, + "resources/templates/list": s.ListResourceTemplatesResultSchema, + "resources/read": s.ReadResourceResultSchema, + "completion/complete": s.CompleteResultSchema, + "server/discover": s.DiscoverResultSchema + }; + return wireResultSchemasMemo; +} +/** +* Forces the lazy wire-result wrapper map (and, through it, the era's schema +* memo). Warm-up hook for `preloadSchemas()` — no-op once the map exists. +*/ +function warmWireResultSchemas2026() { + getWireResultSchemas(); +} + +//#endregion +//#region ../core-internal/src/wire/codec.ts +/** +* The modern wire revision literal. Internal only — deliberately NOT a public +* constant (G-D2-4: no public modern-version constant ships before era-aware +* list semantics exist). +*/ +const src_CX2iR2pK_MODERN_WIRE_REVISION = "2026-07-28"; +/** +* Era resolution, many-to-one (Q1-SD1): every modern-era revision +* (`>= 2026-07-28`) → the 2026-era codec; every legacy revision (the five +* `SUPPORTED_PROTOCOL_VERSIONS`) and `undefined`/unknown → the 2025-era +* codec (the DV-13 default posture — hand-constructed instances and +* unclassified traffic are legacy-era). This is the same era predicate the +* rest of the SDK uses ({@link isModernProtocolVersion}); a pinned modern +* revision other than the literal '2026-07-28' must still resolve modern. +*/ +function src_CX2iR2pK_codecForVersion(version) { + return version !== void 0 && isModernProtocolVersion(version) ? rev2026Codec : rev2025Codec; +} +/** +* The wire era an edge classification names (Q2 — produced at the +* transport/entry edge; this layer only CONSUMES it). The dispatch funnel no +* longer resolves a codec FROM the classification: era is instance state, and +* a classified inbound message is VALIDATED against the instance era — a +* mismatch is an entry/routing error, never a per-message era switch. The +* exact `revision` wins over the coarse era flag when both are present. +*/ +function classifiedWireEra(classification) { + if (classification.revision !== void 0) return src_CX2iR2pK_codecForVersion(classification.revision).era; + return classification.era === "modern" ? rev2026Codec.era : rev2025Codec.era; +} +/** +* The derived spec-method universe: the union of every codec registry. A +* method in this set is era-gated at dispatch and send time; a method outside +* it is a consumer-owned extension method (era-blind, schema-explicit). +* Derived from the registries — never hand-curated (the LEGACY_ONLY_METHODS +* table class is exactly what registry membership replaces). +*/ +function isSpecRequestMethod(method) { + return ALL_CODECS.some((codec) => codec.hasRequestMethod(method)); +} +function isSpecNotificationMethod(method) { + return ALL_CODECS.some((codec) => codec.hasNotificationMethod(method)); +} +const ALL_CODECS = [rev2025Codec, rev2026Codec]; + +//#endregion +//#region ../core-internal/src/shared/envelope.ts +/** +* Per-request `_meta` envelope claim helpers (protocol revision 2026-07-28). +* +* Pure, value-returning helpers used by the inbound HTTP classifier +* (`classifyInboundRequest`): claim detection and envelope validation with +* self-identifying issues. The envelope schema itself stays the wire layer's +* single source of truth (`RequestMetaEnvelopeSchema`); this module only maps +* its outcomes into the shapes the validation ladder emits. +* +* Claim detection is deliberately narrow: a message claims the 2026-07-28 +* envelope mechanism if and only if the reserved protocol-version `_meta` key +* is present in `params._meta`. Other reserved keys (client info, client +* capabilities, log level), a bare `progressToken`, or unrelated keys under +* the `io.modelcontextprotocol/` prefix do NOT constitute a claim on their +* own — but once the claim key is present, a malformed envelope is a +* validation error, never a silent fall back to legacy handling. +* +* The wire-exact envelope schema, the required-key set, and the per-key issue +* mapping live in the wire layer (the 2026-era codec's `validateEnvelopeMeta`). +* This module never reaches into a per-revision wire module directly. +*/ +function isPlainObject$3(value) { + return value !== null && typeof value === "object" && !Array.isArray(value); +} +/** The `_meta` object of a message's params, when present. */ +function src_CX2iR2pK_requestMetaOf(params) { + if (!isPlainObject$3(params)) return void 0; + const meta = params["_meta"]; + return isPlainObject$3(meta) ? meta : void 0; +} +/** +* Whether a message's params carry the per-request envelope claim: the +* reserved protocol-version `_meta` key is present (regardless of whether the +* rest of the envelope is valid — validation is a separate, later step). +*/ +function src_CX2iR2pK_hasEnvelopeClaim(params) { + const meta = src_CX2iR2pK_requestMetaOf(params); + return meta !== void 0 && PROTOCOL_VERSION_META_KEY in meta; +} +/** +* The protocol version named by a message's envelope claim, when the claim is +* present and carries a string value. A present claim with a non-string value +* still counts as a claim ({@linkcode hasEnvelopeClaim}); it surfaces as a +* validation issue instead of a version. +*/ +function src_CX2iR2pK_envelopeClaimVersion(params) { + const value = src_CX2iR2pK_requestMetaOf(params)?.[PROTOCOL_VERSION_META_KEY]; + return typeof value === "string" ? value : void 0; +} +/** +* Validates a request's `_meta` object as a 2026-07-28 per-request envelope +* and reports problems as self-identifying issues (which key, what problem). +* +* Returns an empty array when the envelope is valid. Missing required keys are +* reported first (as `problem: 'missing'`), then schema violations inside +* present keys, in a stable order. +*/ +function src_CX2iR2pK_validateEnvelopeMeta(meta) { + return src_CX2iR2pK_codecForVersion(src_CX2iR2pK_MODERN_WIRE_REVISION).validateEnvelopeMeta(meta); +} + +//#endregion +//#region ../core-internal/src/types/schemas.ts +var schemas_exports = /* @__PURE__ */ __exportAll({ + AnnotationsSchema: () => AnnotationsSchema, + AudioContentSchema: () => AudioContentSchema, + BaseMetadataSchema: () => BaseMetadataSchema, + BaseRequestParamsSchema: () => BaseRequestParamsSchema, + BlobResourceContentsSchema: () => BlobResourceContentsSchema, + BooleanSchemaSchema: () => BooleanSchemaSchema, + CallToolRequestParamsSchema: () => CallToolRequestParamsSchema, + CallToolRequestSchema: () => CallToolRequestSchema, + CallToolResultSchema: () => auth_CUe6YdwF_CallToolResultSchema, + CancelTaskRequestSchema: () => CancelTaskRequestSchema, + CancelTaskResultSchema: () => CancelTaskResultSchema, + CancelledNotificationParamsSchema: () => CancelledNotificationParamsSchema, + CancelledNotificationSchema: () => CancelledNotificationSchema, + ClientCapabilitiesSchema: () => ClientCapabilitiesSchema, + ClientNotificationSchema: () => ClientNotificationSchema, + ClientRequestSchema: () => ClientRequestSchema, + ClientResultSchema: () => ClientResultSchema, + ClientTasksCapabilitySchema: () => ClientTasksCapabilitySchema, + CompatibilityCallToolResultSchema: () => CompatibilityCallToolResultSchema, + CompleteRequestParamsSchema: () => CompleteRequestParamsSchema, + CompleteRequestSchema: () => CompleteRequestSchema, + CompleteResultSchema: () => CompleteResultSchema, + ContentBlockSchema: () => ContentBlockSchema, + CreateMessageRequestParamsSchema: () => CreateMessageRequestParamsSchema, + CreateMessageRequestSchema: () => CreateMessageRequestSchema, + CreateMessageResultSchema: () => CreateMessageResultSchema, + CreateMessageResultWithToolsSchema: () => CreateMessageResultWithToolsSchema, + CreateTaskResultSchema: () => CreateTaskResultSchema, + CursorSchema: () => CursorSchema, + DiscoverRequestSchema: () => DiscoverRequestSchema, + DiscoverResultSchema: () => DiscoverResultSchema, + ElicitRequestFormParamsSchema: () => ElicitRequestFormParamsSchema, + ElicitRequestParamsSchema: () => ElicitRequestParamsSchema, + ElicitRequestSchema: () => ElicitRequestSchema, + ElicitRequestURLParamsSchema: () => ElicitRequestURLParamsSchema, + ElicitResultSchema: () => ElicitResultSchema, + ElicitationCompleteNotificationParamsSchema: () => ElicitationCompleteNotificationParamsSchema, + ElicitationCompleteNotificationSchema: () => ElicitationCompleteNotificationSchema, + EmbeddedResourceSchema: () => EmbeddedResourceSchema, + EmptyResultSchema: () => EmptyResultSchema, + EnumSchemaSchema: () => EnumSchemaSchema, + GetPromptRequestParamsSchema: () => GetPromptRequestParamsSchema, + GetPromptRequestSchema: () => GetPromptRequestSchema, + GetPromptResultSchema: () => GetPromptResultSchema, + GetTaskPayloadRequestSchema: () => GetTaskPayloadRequestSchema, + GetTaskPayloadResultSchema: () => GetTaskPayloadResultSchema, + GetTaskRequestSchema: () => GetTaskRequestSchema, + GetTaskResultSchema: () => GetTaskResultSchema, + IconSchema: () => IconSchema, + IconsSchema: () => IconsSchema, + ImageContentSchema: () => ImageContentSchema, + ImplementationSchema: () => ImplementationSchema, + InitializeRequestParamsSchema: () => InitializeRequestParamsSchema, + InitializeRequestSchema: () => auth_CUe6YdwF_InitializeRequestSchema, + InitializeResultSchema: () => InitializeResultSchema, + InitializedNotificationSchema: () => auth_CUe6YdwF_InitializedNotificationSchema, + JSONArraySchema: () => JSONArraySchema, + JSONObjectSchema: () => JSONObjectSchema, + JSONRPCErrorResponseSchema: () => JSONRPCErrorResponseSchema, + JSONRPCMessageSchema: () => auth_CUe6YdwF_JSONRPCMessageSchema, + JSONRPCNotificationSchema: () => JSONRPCNotificationSchema, + JSONRPCRequestSchema: () => JSONRPCRequestSchema, + JSONRPCResponseSchema: () => auth_CUe6YdwF_JSONRPCResponseSchema, + JSONRPCResultResponseSchema: () => JSONRPCResultResponseSchema, + JSONValueSchema: () => JSONValueSchema, + LegacyTitledEnumSchemaSchema: () => LegacyTitledEnumSchemaSchema, + ListChangedOptionsBaseSchema: () => ListChangedOptionsBaseSchema, + ListPromptsRequestSchema: () => ListPromptsRequestSchema, + ListPromptsResultSchema: () => ListPromptsResultSchema, + ListResourceTemplatesRequestSchema: () => ListResourceTemplatesRequestSchema, + ListResourceTemplatesResultSchema: () => ListResourceTemplatesResultSchema, + ListResourcesRequestSchema: () => ListResourcesRequestSchema, + ListResourcesResultSchema: () => ListResourcesResultSchema, + ListRootsRequestSchema: () => ListRootsRequestSchema, + ListRootsResultSchema: () => ListRootsResultSchema, + ListTasksRequestSchema: () => ListTasksRequestSchema, + ListTasksResultSchema: () => ListTasksResultSchema, + ListToolsRequestSchema: () => ListToolsRequestSchema, + ListToolsResultSchema: () => ListToolsResultSchema, + LoggingLevelSchema: () => LoggingLevelSchema, + LoggingMessageNotificationParamsSchema: () => LoggingMessageNotificationParamsSchema, + LoggingMessageNotificationSchema: () => LoggingMessageNotificationSchema, + ModelHintSchema: () => ModelHintSchema, + ModelPreferencesSchema: () => ModelPreferencesSchema, + MultiSelectEnumSchemaSchema: () => MultiSelectEnumSchemaSchema, + NotificationSchema: () => NotificationSchema, + NotificationsParamsSchema: () => NotificationsParamsSchema, + NumberSchemaSchema: () => NumberSchemaSchema, + PaginatedRequestParamsSchema: () => PaginatedRequestParamsSchema, + PaginatedRequestSchema: () => PaginatedRequestSchema, + PaginatedResultSchema: () => PaginatedResultSchema, + PingRequestSchema: () => PingRequestSchema, + PrimitiveSchemaDefinitionSchema: () => PrimitiveSchemaDefinitionSchema, + ProgressNotificationParamsSchema: () => ProgressNotificationParamsSchema, + ProgressNotificationSchema: () => ProgressNotificationSchema, + ProgressSchema: () => ProgressSchema, + ProgressTokenSchema: () => ProgressTokenSchema, + PromptArgumentSchema: () => PromptArgumentSchema, + PromptListChangedNotificationSchema: () => PromptListChangedNotificationSchema, + PromptMessageSchema: () => PromptMessageSchema, + PromptReferenceSchema: () => PromptReferenceSchema, + PromptSchema: () => PromptSchema, + ReadResourceRequestParamsSchema: () => ReadResourceRequestParamsSchema, + ReadResourceRequestSchema: () => ReadResourceRequestSchema, + ReadResourceResultSchema: () => ReadResourceResultSchema, + RelatedTaskMetadataSchema: () => RelatedTaskMetadataSchema, + RequestIdSchema: () => RequestIdSchema, + RequestMetaSchema: () => RequestMetaSchema, + RequestSchema: () => RequestSchema, + ResourceContentsSchema: () => ResourceContentsSchema, + ResourceLinkSchema: () => ResourceLinkSchema, + ResourceListChangedNotificationSchema: () => ResourceListChangedNotificationSchema, + ResourceRequestParamsSchema: () => ResourceRequestParamsSchema, + ResourceSchema: () => ResourceSchema, + ResourceTemplateReferenceSchema: () => ResourceTemplateReferenceSchema, + ResourceTemplateSchema: () => ResourceTemplateSchema, + ResourceUpdatedNotificationParamsSchema: () => ResourceUpdatedNotificationParamsSchema, + ResourceUpdatedNotificationSchema: () => ResourceUpdatedNotificationSchema, + ResultMetaObjectSchema: () => ResultMetaObjectSchema, + ResultSchema: () => ResultSchema, + RoleSchema: () => RoleSchema, + RootSchema: () => RootSchema, + RootsListChangedNotificationSchema: () => RootsListChangedNotificationSchema, + SamplingContentSchema: () => SamplingContentSchema, + SamplingMessageContentBlockSchema: () => SamplingMessageContentBlockSchema, + SamplingMessageSchema: () => SamplingMessageSchema, + ServerCapabilitiesSchema: () => ServerCapabilitiesSchema, + ServerNotificationSchema: () => ServerNotificationSchema, + ServerRequestSchema: () => ServerRequestSchema, + ServerResultSchema: () => ServerResultSchema, + ServerTasksCapabilitySchema: () => ServerTasksCapabilitySchema, + SetLevelRequestParamsSchema: () => SetLevelRequestParamsSchema, + SetLevelRequestSchema: () => SetLevelRequestSchema, + SingleSelectEnumSchemaSchema: () => SingleSelectEnumSchemaSchema, + StringSchemaSchema: () => StringSchemaSchema, + SubscribeRequestParamsSchema: () => SubscribeRequestParamsSchema, + SubscribeRequestSchema: () => SubscribeRequestSchema, + SubscriptionFilterSchema: () => SubscriptionFilterSchema, + SubscriptionsAcknowledgedNotificationParamsSchema: () => SubscriptionsAcknowledgedNotificationParamsSchema, + SubscriptionsAcknowledgedNotificationSchema: () => SubscriptionsAcknowledgedNotificationSchema, + SubscriptionsListenRequestParamsSchema: () => SubscriptionsListenRequestParamsSchema, + SubscriptionsListenRequestSchema: () => SubscriptionsListenRequestSchema, + SubscriptionsListenResultMetaSchema: () => SubscriptionsListenResultMetaSchema, + SubscriptionsListenResultSchema: () => SubscriptionsListenResultSchema, + TaskAugmentedRequestParamsSchema: () => auth_CUe6YdwF_TaskAugmentedRequestParamsSchema, + TaskCreationParamsSchema: () => TaskCreationParamsSchema, + TaskMetadataSchema: () => TaskMetadataSchema, + TaskSchema: () => TaskSchema, + TaskStatusNotificationParamsSchema: () => TaskStatusNotificationParamsSchema, + TaskStatusNotificationSchema: () => TaskStatusNotificationSchema, + TaskStatusSchema: () => TaskStatusSchema, + TextContentSchema: () => TextContentSchema, + TextResourceContentsSchema: () => TextResourceContentsSchema, + TitledMultiSelectEnumSchemaSchema: () => TitledMultiSelectEnumSchemaSchema, + TitledSingleSelectEnumSchemaSchema: () => TitledSingleSelectEnumSchemaSchema, + ToolAnnotationsSchema: () => ToolAnnotationsSchema, + ToolChoiceSchema: () => ToolChoiceSchema, + ToolExecutionSchema: () => ToolExecutionSchema, + ToolListChangedNotificationSchema: () => ToolListChangedNotificationSchema, + ToolResultContentSchema: () => ToolResultContentSchema, + ToolSchema: () => ToolSchema, + ToolUseContentSchema: () => ToolUseContentSchema, + UnsubscribeRequestParamsSchema: () => UnsubscribeRequestParamsSchema, + UnsubscribeRequestSchema: () => UnsubscribeRequestSchema, + UntitledMultiSelectEnumSchemaSchema: () => UntitledMultiSelectEnumSchemaSchema, + UntitledSingleSelectEnumSchemaSchema: () => UntitledSingleSelectEnumSchemaSchema +}); + +//#endregion +//#region ../core-internal/src/types/guards.ts +/** +* Validates and parses an unknown value as a JSON-RPC message. +* +* Use this to validate incoming messages in custom transport implementations. +* Throws if the value does not conform to the JSON-RPC message schema. +* +* @param value - The value to validate (typically a parsed JSON object). +* @returns The validated {@linkcode JSONRPCMessage}. +* @throws If validation fails. +*/ +function parseJSONRPCMessage(value) { + return JSONRPCMessageSchema.parse(value); +} +const src_CX2iR2pK_isJSONRPCRequest = (value) => JSONRPCRequestSchema.safeParse(value).success; +const src_CX2iR2pK_isJSONRPCNotification = (value) => JSONRPCNotificationSchema.safeParse(value).success; +/** +* Checks if a value is a valid {@linkcode JSONRPCResultResponse}. +* @param value - The value to check. +* +* @returns True if the value is a valid {@linkcode JSONRPCResultResponse}, false otherwise. +*/ +const src_CX2iR2pK_isJSONRPCResultResponse = (value) => JSONRPCResultResponseSchema.safeParse(value).success; +/** +* Checks if a value is a valid {@linkcode JSONRPCErrorResponse}. +* @param value - The value to check. +* +* @returns True if the value is a valid {@linkcode JSONRPCErrorResponse}, false otherwise. +*/ +const src_CX2iR2pK_isJSONRPCErrorResponse = (value) => JSONRPCErrorResponseSchema.safeParse(value).success; +/** +* Checks if a value is a valid {@linkcode JSONRPCResponse} (either a result or error response). +* @param value - The value to check. +* +* @returns True if the value is a valid {@linkcode JSONRPCResponse}, false otherwise. +*/ +const isJSONRPCResponse = (value) => JSONRPCResponseSchema.safeParse(value).success; +/** +* Checks if a value is a valid {@linkcode CallToolResult}. +* +* This is a consumer-side VALUE check against the neutral model, not a wire +* validator: a raw wire object that additionally carries wire-only members +* (e.g. `resultType`) still passes through the loose index signature. Use a +* transport-level parse to validate raw wire traffic. +* +* @param value - The value to check. +* +* @returns True if the value is a valid {@linkcode CallToolResult}, false otherwise. +*/ +const isCallToolResult = (value) => { + if (typeof value !== "object" || value === null || value.content === void 0) return false; + return CallToolResultSchema.safeParse(value).success; +}; +/** +* Checks whether a value is an input-required result (protocol revision +* 2026-07-28): the multi-round-trip return shape discriminated by +* `resultType: 'input_required'`. +* +* This is a discriminator check, not a full validator — the at-least-one rule +* (`inputRequests` or `requestState`) is enforced by the `inputRequired()` +* builder and re-checked by the server seam for hand-built values. +* +* @param value - The value to check. +* @returns True if the value carries the `input_required` discriminator. +*/ +const isInputRequiredResult = (value) => typeof value === "object" && value !== null && !Array.isArray(value) && value.resultType === "input_required"; +/** +* Checks if a value is a valid {@linkcode TaskAugmentedRequestParams}. +* @param value - The value to check. +* +* @returns True if the value is a valid {@linkcode TaskAugmentedRequestParams}, false otherwise. +* +* @deprecated Recognizes 2025-11-25 task wire vocabulary, which has no SDK +* runtime; kept importable for interoperability only. +*/ +const isTaskAugmentedRequestParams = (value) => TaskAugmentedRequestParamsSchema.safeParse(value).success; +const src_CX2iR2pK_isInitializeRequest = (value) => InitializeRequestSchema.safeParse(value).success; +const isInitializedNotification = (value) => InitializedNotificationSchema.safeParse(value).success; +function assertCompleteRequestPrompt(request) { + if (request.params.ref.type !== "ref/prompt") throw new TypeError(`Expected CompleteRequestPrompt, but got ${request.params.ref.type}`); +} +function assertCompleteRequestResourceTemplate(request) { + if (request.params.ref.type !== "ref/resource") throw new TypeError(`Expected CompleteRequestResourceTemplate, but got ${request.params.ref.type}`); +} + +//#endregion +//#region ../core-internal/src/shared/mcpParamHeaders.ts +/** The fixed prefix every custom-parameter header carries. */ +const MCP_PARAM_HEADER_PREFIX = "Mcp-Param-"; +/** The schema-extension property name a tool's `inputSchema` carries. */ +const X_MCP_HEADER_KEY = "x-mcp-header"; +/** +* RFC 9110 §5.1 `token` syntax (`1*tchar`). Rejects empty, space, control +* characters (including CR/LF), and the listed delimiters. +*/ +const RFC9110_TOKEN = /^[!#$%&'*+\-.^_`|~0-9A-Za-z]+$/; +/** +* JSON Schema `type` values the spec admits on an `x-mcp-header` property. +* +* The spec text names `integer`, `string`, `boolean` and explicitly excludes +* `number`. The published conformance referee at the pinned release ships its +* `http-custom-headers` scenario with two `type: "number"` `x-mcp-header` +* parameters and expects the client to mirror them, so `number` is accepted +* here so that the conformance gate passes; the discrepancy is tracked +* upstream. Everything else (`object`, `array`, `null`, absent) is rejected. +*/ +const PERMITTED_X_MCP_HEADER_TYPES = new Set([ + "string", + "integer", + "boolean", + "number" +]); +/** +* Scan a tool's JSON-serialized `inputSchema` for `x-mcp-header` declarations +* and validate every constraint the spec places on them. Returns either the +* collected declarations (possibly empty) or the first violated constraint. +* +* The walk descends through `properties` at any depth (the spec's "any nesting +* depth" clause). The static-reachability MUST is enforced as a structural +* sweep: every position the chain MUST NOT pass through (`items`/ +* `additionalProperties`, `oneOf`/`anyOf`/`allOf`/`not`, `if`/`then`/`else`, +* `$defs`, `$ref` targets within `$defs`) is visited too, and an +* `x-mcp-header` found anywhere on that path invalidates the schema — "an +* annotation anywhere else makes the tool definition invalid". +*/ +function src_CX2iR2pK_scanXMcpHeaderDeclarations(inputSchema) { + const declarations = []; + const seenLower = /* @__PURE__ */ new Map(); + const visit = (node, path, reachable) => { + if (node === null || typeof node !== "object") return void 0; + const schema = node; + if (X_MCP_HEADER_KEY in schema) { + if (!reachable || path.length === 0) return `${pathName(path)}: x-mcp-header is only permitted on properties statically reachable via a chain of 'properties' keys (not under items, additionalProperties, oneOf/anyOf/allOf/not, if/then/else, or $ref)`; + const raw = schema[X_MCP_HEADER_KEY]; + if (typeof raw !== "string" || raw.length === 0) return `${pathName(path)}: x-mcp-header MUST be a non-empty string`; + if (!RFC9110_TOKEN.test(raw)) return `${pathName(path)}: x-mcp-header '${raw}' is not a valid RFC 9110 token (no spaces, control characters or HTTP delimiters)`; + const type = typeof schema.type === "string" ? schema.type : void 0; + if (type === void 0 || !PERMITTED_X_MCP_HEADER_TYPES.has(type)) return `${pathName(path)}: x-mcp-header is only permitted on primitive-typed properties (string, integer, boolean); got ${type ?? ""}`; + const lower = raw.toLowerCase(); + const prior = seenLower.get(lower); + if (prior !== void 0) return `x-mcp-header '${raw}' is not case-insensitively unique (also declared as '${prior}')`; + seenLower.set(lower, raw); + declarations.push({ + path, + headerName: raw, + type + }); + } + const properties = schema.properties; + if (properties !== null && typeof properties === "object") for (const [key, child] of Object.entries(properties)) { + const fault$1 = visit(child, [...path, key], reachable); + if (fault$1 !== void 0) return fault$1; + } + for (const k of NON_REACHABLE_SUBSCHEMA_KEYWORDS) { + const sub = schema[k]; + if (sub === void 0) continue; + const branches = Array.isArray(sub) ? sub : sub !== null && typeof sub === "object" && OBJECT_VALUED_SUBSCHEMA_KEYWORDS.has(k) ? Object.values(sub) : [sub]; + for (const branch of branches) { + const fault$1 = visit(branch, [...path, `<${k}>`], false); + if (fault$1 !== void 0) return fault$1; + } + } + }; + const fault = visit(inputSchema, [], true); + return fault === void 0 ? { + valid: true, + declarations + } : { + valid: false, + reason: fault + }; +} +/** +* JSON Schema keywords whose subschemas the SEP-2243 static-reachability +* constraint excludes from the `properties`-only chain. An `x-mcp-header` +* found under any of these invalidates the tool definition. +*/ +const NON_REACHABLE_SUBSCHEMA_KEYWORDS = [ + "items", + "prefixItems", + "contains", + "additionalProperties", + "unevaluatedProperties", + "unevaluatedItems", + "propertyNames", + "patternProperties", + "dependentSchemas", + "oneOf", + "anyOf", + "allOf", + "not", + "if", + "then", + "else", + "$defs", + "definitions" +]; +/** +* Subschema-carrying keywords whose value is a `name → subschema` object +* (not a single subschema or array of subschemas). The visit branches over +* `Object.values()` for these. +*/ +const OBJECT_VALUED_SUBSCHEMA_KEYWORDS = new Set([ + "patternProperties", + "dependentSchemas", + "$defs", + "definitions" +]); +function pathName(path) { + return path.length === 0 ? "" : path.join("."); +} +const BASE64_SENTINEL_PREFIX = "=?base64?"; +const BASE64_SENTINEL_SUFFIX = "?="; +const BASE64_CANONICAL = /^(?:[A-Za-z0-9+/]{4})*(?:[A-Za-z0-9+/]{2}==|[A-Za-z0-9+/]{3}=)?$/; +const CANONICAL_DECIMAL = /^-?\d+(\.\d+)?$/; +/** +* Convert a primitive argument value to its string representation per the +* spec's type-conversion rules: strings pass through, integers and numbers +* become their decimal string, booleans become lowercase `'true'` / `'false'`. +* Non-finite numbers and integers outside the safe range are refused (the +* caller treats `undefined` as "do not emit a header for this value"). +*/ +function mcpParamPrimitiveToString(value) { + if (typeof value === "string") return value; + if (typeof value === "boolean") return value ? "true" : "false"; + if (typeof value === "number") { + if (!Number.isFinite(value)) return void 0; + if (Number.isInteger(value) && !Number.isSafeInteger(value)) return void 0; + return String(value); + } +} +function base64ToUtf8(b64) { + const bin = atob(b64); + const bytes = new Uint8Array(bin.length); + for (let i = 0; i < bin.length; i++) bytes[i] = bin.codePointAt(i); + return new TextDecoder("utf-8", { fatal: true }).decode(bytes); +} +/** +* Decode an `Mcp-Param-*` header value: when it carries the Base64 sentinel, +* the payload is decoded as UTF-8; otherwise the value is returned as-is. +* Returns `undefined` when the sentinel is present but the payload is not +* canonical Base64 (or not valid UTF-8) — the spec requires servers to reject +* such values. +*/ +function decodeMcpParamValue(value) { + if (!(value.startsWith(BASE64_SENTINEL_PREFIX) && value.endsWith(BASE64_SENTINEL_SUFFIX))) return value; + const b64 = value.slice(9, value.length - 2); + if (!BASE64_CANONICAL.test(b64)) return void 0; + try { + return base64ToUtf8(b64); + } catch { + return; + } +} +function valueAtPath(root, path) { + let node = root; + for (const key of path) { + if (node === null || typeof node !== "object") return void 0; + node = node[key]; + } + return node; +} +/** +* The header/body comparison the server performs at tool-resolution time. +* +* For each `x-mcp-header` declaration on the named tool: when the body +* `arguments` carries a value, the matching `Mcp-Param-{Name}` header MUST be +* present and decode to an equal value; when the body value is `null` or +* absent the server MUST NOT expect the header (a present header is ignored). +* A sentinel-carrying header whose payload is not canonical Base64 / valid +* UTF-8 is rejected as invalid characters. +* +* Integer-typed declarations are compared numerically (the spec's SHOULD — +* `42.0` and `42` are equal); everything else is compared as decoded strings. +* +* Returns `undefined` when every check passes, or an +* {@linkcode InboundLadderRejection} carrying the same `-32020` +* (`HeaderMismatch`) shape the inbound classifier emits for the +* standard-header cross-checks — `400 Bad Request` with the disagreeing pair +* in `data.mismatch`. +*/ +function src_CX2iR2pK_validateMcpParamHeaders(declarations, args, headers) { + for (const decl of declarations) { + const headerKey = `${MCP_PARAM_HEADER_PREFIX}${decl.headerName}`; + const headerValue = headers.get(headerKey); + const bodyRaw = valueAtPath(args, decl.path); + if (bodyRaw === void 0 || bodyRaw === null) continue; + const bodyString = mcpParamPrimitiveToString(bodyRaw); + if (bodyString === void 0) continue; + if (headerValue === null) return paramHeaderMismatchRejection("param-header-missing", headerKey, `the body carries ${pathName(decl.path)}=${JSON.stringify(bodyRaw)} but the ${headerKey} header is absent`); + const decoded = decodeMcpParamValue(headerValue); + if (decoded === void 0) return paramHeaderMismatchRejection("param-header-invalid-encoding", headerKey, `the ${headerKey} header carries an invalid Base64 sentinel value`); + if (!((decl.type === "integer" || decl.type === "number") && CANONICAL_DECIMAL.test(decoded) && typeof bodyRaw === "number" ? Number(decoded) === bodyRaw : decoded === bodyString)) return paramHeaderMismatchRejection("param-header-mismatch", headerKey, `the ${headerKey} header decodes to ${JSON.stringify(decoded)} but the body carries ${pathName(decl.path)}=${JSON.stringify(bodyRaw)}`); + } +} +/** +* Build the `-32020` (`HeaderMismatch`) rejection for an `Mcp-Param-*` +* disagreement. Same shape as the inbound classifier's standard-header +* cross-check mismatch (HTTP `400`, `data.mismatch` naming the disagreeing +* pair, `settled: true`); only the rung differs because this check runs at the +* pre-dispatch step against a known tool's schema rather than at the edge. +*/ +function paramHeaderMismatchRejection(cell, header, body) { + return { + kind: "reject", + rung: "param-header-validation", + cell, + httpStatus: 400, + code: HEADER_MISMATCH_ERROR_CODE, + message: `Bad Request: the request headers and body disagree: ${body}`, + data: { mismatch: { + header, + body + } }, + settled: true + }; +} + +//#endregion +//#region ../core-internal/src/shared/inboundClassification.ts +/** +* Inbound HTTP request classification and the inbound validation ladder +* (protocol revision 2026-07-28). +* +* `classifyInboundRequest` is the body-primary era predicate for an HTTP +* entry that serves both protocol eras on one endpoint. It is evaluated +* exactly once, at the entry boundary, on the already-parsed request body: +* +* - `initialize` is a legacy-era request by definition (the modern era has no +* `initialize` handshake) — unless it carries a valid envelope claim naming +* a modern revision, in which case the claim wins and the request is +* classified like any other enveloped request (the modern era then answers +* it with method-not-found, exactly like every other method it does not +* define). +* - A request whose `params._meta` carries the reserved protocol-version key +* claims the per-request envelope mechanism and classifies into the era the +* named revision belongs to (a malformed envelope behind a present claim is +* a validation error, never a silent fall back to legacy handling). +* - A request without a claim is legacy-era traffic. +* - The `MCP-Protocol-Version` header is a cross-check only: it never +* upgrades or downgrades a body-derived classification, and a disagreement +* between header and body is an explicit ladder outcome. +* - Notifications carry no envelope claim of their own under the current +* spec, so for notification POSTs without a body claim the modern header is +* determinative; the `Mcp-Method` header is validated against the body when +* the message classifies modern and is never enforced on legacy traffic. +* A notification that does carry a claim is treated body-primary like a +* request, and a malformed claim is rejected the same way a request's +* malformed claim is — never silently resolved against the header. +* The notification-POST header cross-checks here are an SDK-defensive +* posture, not a spec requirement: the spec leaves header rules for posted +* notifications undefined (core client notifications do not occur over +* Streamable HTTP); applying the request rules symmetrically is what an +* ecosystem custom-notification POST expects, and the −32020 cells stay +* passing for them. +* - `GET`/`DELETE` (and any other non-`POST` method) are body-less 2025-era +* session operations: the modern era is `POST`-only, so they are routed to +* legacy serving when it is configured and rejected otherwise. +* - Array (batch) bodies are classified element-wise: an array containing a +* modern-claiming or invalid element is rejected, an all-legacy array is +* legacy traffic unchanged, and a single-element array is still an array. +* +* The classifier returns plain values (it never throws and never touches a +* transport): a routing outcome (`legacy`/`modern`) or a ladder rejection +* carrying the JSON-RPC error to emit and the HTTP status to emit it with. +* Legacy routing outcomes deliberately carry NO `MessageClassification` — +* legacy and hand-wired traffic is never classified, which keeps its +* dispatch behavior byte-identical to today's. +* +* Error codes for the modern-path rejection cells follow the published +* conformance suite (and the spec text it asserts): +* +* - A header/body cross-check mismatch (the `MCP-Protocol-Version` header +* disagreeing with the body, or the `Mcp-Method` header disagreeing with the +* body method) is rejected with `-32020` (`HeaderMismatch`) on HTTP 400. +* - A request whose protocol-version header names a modern revision but whose +* body carries no `_meta` envelope claim — including an envelope present but +* missing the required protocol-version key — is rejected with `-32602` +* (invalid params) naming the missing key(s), on HTTP 400. +* +* Should a future spec revision or conformance release change these +* assignments, the affected cells are re-derived against that release; the +* `settled` flag on {@linkcode InboundLadderRejection} stays available to mark +* a cell provisional again while such a change is in flight. +*/ +/** +* The error code emitted for header/body cross-check mismatches: the +* `MCP-Protocol-Version` header disagreeing with the body's envelope claim (or +* with the body's classification), and the `Mcp-Method` header disagreeing +* with the body method. +* +* `-32020` is the draft schema's `HEADER_MISMATCH` constant (the SEP-2243 +* `HeaderMismatch` code; the spec requires HTTP 400 for it), as also asserted +* by the published conformance suite for header-validation failures. It has no +* {@linkcode ProtocolErrorCode} member because it is not part of the 2025-era +* wire vocabulary; the validation ladder is its only emitter. +*/ +const HEADER_MISMATCH_ERROR_CODE = -32020; +/** +* The inbound validation ladder, expressed as data rather than control flow. +* +* The edge rungs are evaluated by {@linkcode classifyInboundRequest}; the +* dispatch rungs are evaluated by the protocol layer once the classified +* message is injected into a per-request server instance (the era registry +* gate, the envelope requiredness check, and per-method params validation). +* The client-capability rung is evaluated by the HTTP entry itself, +* pre-dispatch, on the validated envelope the classifier produced — see that +* rung's rationale for the ordering caveat. The order is the precedence: a +* request that fails several rungs is answered by the earliest one. +*/ +const INBOUND_VALIDATION_LADDER = [ + { + 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: [src_CX2iR2pK_ProtocolErrorCode.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: [HEADER_MISMATCH_ERROR_CODE, src_CX2iR2pK_ProtocolErrorCode.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: [src_CX2iR2pK_ProtocolErrorCode.InvalidParams], + conformance: ["server-stateless"], + rationale: "A present envelope claim with a malformed envelope — and a missing envelope on a request whose protocol-version header names a modern revision — 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: [src_CX2iR2pK_ProtocolErrorCode.MethodNotFound], + conformance: ["server-stateless"], + rationale: "Method existence outranks parameter validity: a method absent from the negotiated revision’s 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: [src_CX2iR2pK_ProtocolErrorCode.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: [HEADER_MISMATCH_ERROR_CODE], + conformance: ["http-header-validation"], + rationale: "SEP-2243 standard `Mcp-Method` / `Mcp-Name` headers — presence, sentinel decoding, and `Mcp-Name` ↔ body cross-check — are validated by the HTTP entry on a modern-classified request after the supported-revision gate and before dispatch. The classifier’s 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–6) are consulted." + }, + { + rung: "client-capabilities", + order: 8, + evaluatedAt: "pre-dispatch", + codes: [src_CX2iR2pK_ProtocolErrorCode.MissingRequiredClientCapability], + conformance: ["server-stateless"], + rationale: "The capability requirement is checked by the HTTP entry, pre-dispatch, against the validated envelope the classifier produced — 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: [HEADER_MISMATCH_ERROR_CODE], + conformance: ["http-custom-header-server-validation"], + rationale: "SEP-2243 `Mcp-Param-*` headers are validated against the named tool’s `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." + } +]; +/** +* HTTP status for ladder-originated JSON-RPC error codes. +* +* Keyed on origin, not on the bare code: this table only applies to errors +* the ladder (or a pre-handler protocol gate) produced. Errors produced by +* request handlers — whatever their code — stay in-band on HTTP 200, and are +* never mapped to an HTTP status by this table; in particular `-32603` and +* domain-specific codes never become a blanket 500. The single exception is +* `MissingRequiredClientCapability` (-32021) — see +* {@linkcode httpStatusForErrorCode}. +* +* `-32602` (invalid params) deliberately has NO entry: the only invalid-params +* rejection that maps to HTTP 400 is the classifier's own envelope rung +* short-circuit, which carries its HTTP status directly. A dispatch- or +* handler-produced invalid-params error is always in-band. +*/ +const src_CX2iR2pK_LADDER_ERROR_HTTP_STATUS = { + [src_CX2iR2pK_ProtocolErrorCode.ParseError]: 400, + [src_CX2iR2pK_ProtocolErrorCode.InvalidRequest]: 400, + [src_CX2iR2pK_ProtocolErrorCode.MethodNotFound]: 404, + [src_CX2iR2pK_ProtocolErrorCode.UnsupportedProtocolVersion]: 400, + [src_CX2iR2pK_ProtocolErrorCode.MissingRequiredClientCapability]: 400, + [HEADER_MISMATCH_ERROR_CODE]: 400 +}; +/** +* The HTTP status to answer a JSON-RPC error with, keyed on the error's +* origin. `in-band` errors (anything produced by a request handler) are +* HTTP 200 — the JSON-RPC error response is the payload, not an HTTP +* failure — with ONE exception: `MissingRequiredClientCapability` (-32021), +* whose 400 the spec mandates on the error itself with no origin condition, +* and which the SDK genuinely produces after dispatch (the `input_required` +* capability gate). A handler relaying some downstream peer's `-32020`/`-32022` +* is NOT that peer's spec error and stays in-band like every other handler +* code. `ladder` errors map through {@linkcode LADDER_ERROR_HTTP_STATUS}. +* +* The per-request transport intentionally does NOT delegate to this function: +* its `?? 400` ladder fallback is only correct for entry-gate codes known to +* the table, and would wrongly map dispatch-window errors outside it (a +* window `-32602` must stay in-band on 200). The transport indexes the table +* directly; keep the two in agreement when editing either. +*/ +function src_CX2iR2pK_httpStatusForErrorCode(code, origin) { + if (origin === "in-band") return code === src_CX2iR2pK_ProtocolErrorCode.MissingRequiredClientCapability ? 400 : 200; + return src_CX2iR2pK_LADDER_ERROR_HTTP_STATUS[code] ?? 400; +} +function src_CX2iR2pK_rejection(rung, cell, httpStatus, error, settled) { + return { + kind: "reject", + rung, + cell, + httpStatus, + code: error.code, + message: error.message, + ...error.data !== void 0 && { data: error.data }, + settled + }; +} +function crossCheckMismatch(cell, header, body, rung = "era-classification") { + return src_CX2iR2pK_rejection(rung, cell, 400, new src_CX2iR2pK_ProtocolError(HEADER_MISMATCH_ERROR_CODE, `Bad Request: the request headers and body disagree: ${body}`, { mismatch: { + header, + body + } }), true); +} +/** +* The methods whose body carries a `params.name` / `params.uri` value the +* `Mcp-Name` header must mirror, and which body field supplies it (SEP-2243 +* § Standard Request Headers, `Required For` column). +*/ +const MCP_NAME_HEADER_SOURCE = (/* unused pure expression or super */ null && ({ + "tools/call": "name", + "prompts/get": "name", + "resources/read": "uri" +})); +/** Strip RFC 9110 optional whitespace (SP / HTAB) around a field value in linear time. */ +function stripHttpOws(value) { + let start = 0; + while (start < value.length) { + const code = value.codePointAt(start); + if (code !== 9 && code !== 32) break; + start += 1; + } + let end = value.length; + while (end > start) { + const code = value.codePointAt(end - 1); + if (code !== 9 && code !== 32) break; + end -= 1; + } + return start === 0 && end === value.length ? value : value.slice(start, end); +} +/** +* SEP-2243 standard-header server-side validation, evaluated by the HTTP +* entry on a modern-classified request immediately after +* {@linkcode classifyInboundRequest} returns a modern route. +* +* Returns the `-32020` (`HeaderMismatch`) ladder rejection (HTTP `400`, +* `standard-header-validation` rung — the same shape +* {@linkcode classifyInboundRequest} already emits on the edge +* `era-classification` rung for the `MCP-Protocol-Version` and +* `Mcp-Method` *mismatch* cells) when: +* +* - the required `Mcp-Method` header is absent; +* - the required `Mcp-Name` header is absent on a `tools/call`, +* `prompts/get`, or `resources/read` request whose body carries the +* `params.name` / `params.uri` value the header mirrors; +* - the `Mcp-Name` header carries an invalid `=?base64?…?=` sentinel; or +* - the (decoded) `Mcp-Name` value disagrees with the body's +* `params.name` / `params.uri`. +* +* Returns `undefined` (pass) for notifications (the spec table reads +* "All requests"), for methods that have no `Mcp-Name` source, and when the +* headers agree with the body. Never enforced on legacy traffic — the entry +* only calls this on a modern route. +* +* Kept separate from {@linkcode classifyInboundRequest} so that a body-only +* call to the classifier (no headers passed) keeps routing a modern request +* unchanged: the classifier remains a pure body-primary router, and this +* function is the presence/`Mcp-Name` half of the standard-header rung the +* entry layers on top. +*/ +function src_CX2iR2pK_validateStandardRequestHeaders(request, route) { + if (route.messageKind !== "request") return; + const method = route.message.method; + if (request.mcpMethodHeader === void 0) return crossCheckMismatch("method-header-missing", "(missing)", `the body names method ${method} but the required Mcp-Method header is absent`, "standard-header-validation"); + const sourceField = Object.hasOwn(MCP_NAME_HEADER_SOURCE, method) ? MCP_NAME_HEADER_SOURCE[method] : void 0; + if (sourceField === void 0) return; + const sourceValue = route.message.params?.[sourceField]; + const bodyValue = typeof sourceValue === "string" ? sourceValue : void 0; + if (request.mcpNameHeader === void 0) { + if (bodyValue === void 0) return; + return crossCheckMismatch("name-header-missing", "(missing)", `the body carries params.${sourceField}="${bodyValue}" but the required Mcp-Name header is absent`, "standard-header-validation"); + } + const normalizedNameHeader = stripHttpOws(request.mcpNameHeader); + const decoded = decodeMcpParamValue(normalizedNameHeader); + if (decoded === void 0) return crossCheckMismatch("name-header-invalid-encoding", normalizedNameHeader, "the Mcp-Name header carries an invalid Base64 sentinel value", "standard-header-validation"); + if (bodyValue !== void 0 && decoded !== bodyValue) return crossCheckMismatch("name-header-mismatch", normalizedNameHeader, `the body carries params.${sourceField}="${bodyValue}" but the Mcp-Name header names "${decoded}"`, "standard-header-validation"); +} +function isPlainObject$2(value) { + return value !== null && typeof value === "object" && !Array.isArray(value); +} +function classificationForClaim(claimedVersion) { + if (claimedVersion === void 0) return { era: "modern" }; + return { + era: isModernProtocolVersion(claimedVersion) ? "modern" : "legacy", + revision: claimedVersion + }; +} +/** +* Whether a request's params carry a per-request envelope claim that is both +* well-formed and names a modern protocol revision. +* +* Used by the `initialize` precedence rule: only such a claim overrides the +* `initialize` ⇒ legacy-handshake classification — a request carrying a valid +* modern envelope is a modern request regardless of its method name, and the +* modern era then answers `initialize` exactly like any other method it does +* not define (method-not-found). A malformed claim, or one naming a pre-2026 +* revision, keeps the legacy-handshake routing unchanged. +* +* Exported on the core internal barrel for the stdio serving entry, which +* applies the same precedence rule to a connection's opening message; not +* public API. +*/ +function src_CX2iR2pK_carriesValidModernEnvelopeClaim(params) { + if (!src_CX2iR2pK_hasEnvelopeClaim(params)) return false; + const claimedVersion = src_CX2iR2pK_envelopeClaimVersion(params); + if (claimedVersion === void 0 || !isModernProtocolVersion(claimedVersion)) return false; + const meta = src_CX2iR2pK_requestMetaOf(params); + return meta !== void 0 && src_CX2iR2pK_validateEnvelopeMeta(meta).length === 0; +} +function classifyBatch(body) { + if (body.length === 0) return src_CX2iR2pK_rejection("jsonrpc-shape", "empty-batch", 400, new src_CX2iR2pK_ProtocolError(src_CX2iR2pK_ProtocolErrorCode.InvalidRequest, "Bad Request: empty JSON-RPC batch"), true); + for (const element of body) { + if (src_CX2iR2pK_hasEnvelopeClaim(isPlainObject$2(element) ? element["params"] : void 0)) return src_CX2iR2pK_rejection("jsonrpc-shape", "batch-with-modern-element", 400, new src_CX2iR2pK_ProtocolError(src_CX2iR2pK_ProtocolErrorCode.InvalidRequest, "Bad Request: JSON-RPC batches may not contain requests for protocol revision 2026-07-28 or later"), true); + if (!(src_CX2iR2pK_isJSONRPCRequest(element) || src_CX2iR2pK_isJSONRPCNotification(element) || src_CX2iR2pK_isJSONRPCResultResponse(element) || src_CX2iR2pK_isJSONRPCErrorResponse(element))) return src_CX2iR2pK_rejection("jsonrpc-shape", "batch-with-invalid-element", 400, new src_CX2iR2pK_ProtocolError(src_CX2iR2pK_ProtocolErrorCode.InvalidRequest, "Bad Request: JSON-RPC batch contains an invalid message"), true); + } + return { + kind: "legacy", + reason: "batch" + }; +} +function classifyRequestBody(request, body) { + const params = body.params; + const method = body.method; + const headerVersion = request.protocolVersionHeader; + const headerNamesModern = headerVersion !== void 0 && isModernProtocolVersion(headerVersion); + if (method === "initialize" && !src_CX2iR2pK_carriesValidModernEnvelopeClaim(params)) { + if (headerNamesModern) return crossCheckMismatch("initialize-with-modern-header", headerVersion, "an initialize request (legacy handshake) was sent with a modern MCP-Protocol-Version header"); + const requestedVersion = isPlainObject$2(params) && typeof params["protocolVersion"] === "string" ? params["protocolVersion"] : void 0; + return { + kind: "legacy", + reason: "initialize", + ...requestedVersion !== void 0 && { requestedVersion } + }; + } + if (src_CX2iR2pK_hasEnvelopeClaim(params)) { + const meta = src_CX2iR2pK_requestMetaOf(params); + const firstIssue = (meta === void 0 ? [] : src_CX2iR2pK_validateEnvelopeMeta(meta))[0]; + if (firstIssue !== void 0) return src_CX2iR2pK_rejection("envelope", "envelope-invalid", 400, new src_CX2iR2pK_ProtocolError(src_CX2iR2pK_ProtocolErrorCode.InvalidParams, `Invalid _meta envelope for protocol revision 2026-07-28: ${firstIssue.key}: ${firstIssue.problem}`, { envelope: firstIssue }), true); + const claimedVersion = src_CX2iR2pK_envelopeClaimVersion(params); + if (headerVersion !== void 0 && claimedVersion !== void 0 && headerVersion !== claimedVersion) return crossCheckMismatch("header-body-version-mismatch", headerVersion, `the body envelope names protocol version ${claimedVersion} but the MCP-Protocol-Version header names ${headerVersion}`); + if (request.mcpMethodHeader !== void 0 && request.mcpMethodHeader !== method) return crossCheckMismatch("method-header-mismatch", request.mcpMethodHeader, `the body names method ${method} but the Mcp-Method header names ${request.mcpMethodHeader}`); + return { + kind: "modern", + messageKind: "request", + message: body, + classification: classificationForClaim(claimedVersion) + }; + } + if (headerNamesModern) { + const meta = src_CX2iR2pK_requestMetaOf(params); + const missingFromEnvelope = src_CX2iR2pK_validateEnvelopeMeta(meta ?? {}).filter((issue) => issue.problem === "missing").map((issue) => issue.key); + const missing = meta === void 0 ? ["_meta"] : missingFromEnvelope.length > 0 ? missingFromEnvelope : [PROTOCOL_VERSION_META_KEY]; + return src_CX2iR2pK_rejection("envelope", "modern-header-without-claim", 400, new src_CX2iR2pK_ProtocolError(src_CX2iR2pK_ProtocolErrorCode.InvalidParams, `Invalid params: the MCP-Protocol-Version header names protocol revision ${headerVersion}, but the request is missing the required per-request envelope key(s): ${missing.join(", ")}`, { envelope: { missing } }), true); + } + return { + kind: "legacy", + reason: "no-claim", + ...headerVersion !== void 0 && { requestedVersion: headerVersion } + }; +} +function classifyNotificationBody(request, body) { + const params = body.params; + const method = body.method; + const headerVersion = request.protocolVersionHeader; + const headerNamesModern = headerVersion !== void 0 && isModernProtocolVersion(headerVersion); + if (src_CX2iR2pK_hasEnvelopeClaim(params)) { + const claimedVersion = src_CX2iR2pK_envelopeClaimVersion(params); + if (claimedVersion === void 0) { + const meta = src_CX2iR2pK_requestMetaOf(params); + const claimIssue = (meta === void 0 ? [] : src_CX2iR2pK_validateEnvelopeMeta(meta)).find((issue) => issue.key === PROTOCOL_VERSION_META_KEY) ?? { + key: PROTOCOL_VERSION_META_KEY, + problem: "expected a protocol version string" + }; + return src_CX2iR2pK_rejection("envelope", "notification-envelope-invalid", 400, new src_CX2iR2pK_ProtocolError(src_CX2iR2pK_ProtocolErrorCode.InvalidParams, `Invalid _meta envelope for protocol revision 2026-07-28: ${claimIssue.key}: ${claimIssue.problem}`, { envelope: claimIssue }), true); + } + if (headerVersion !== void 0 && headerVersion !== claimedVersion) return crossCheckMismatch("notification-header-body-version-mismatch", headerVersion, `the notification envelope names protocol version ${claimedVersion} but the MCP-Protocol-Version header names ${headerVersion}`); + const classification = classificationForClaim(claimedVersion); + if (classification.era === "modern" && request.mcpMethodHeader !== void 0 && request.mcpMethodHeader !== method) return crossCheckMismatch("notification-method-header-mismatch", request.mcpMethodHeader, `the notification body names method ${method} but the Mcp-Method header names ${request.mcpMethodHeader}`); + return { + kind: "modern", + messageKind: "notification", + message: body, + classification + }; + } + if (headerNamesModern) { + if (request.mcpMethodHeader !== void 0 && request.mcpMethodHeader !== method) return crossCheckMismatch("notification-method-header-mismatch", request.mcpMethodHeader, `the notification body names method ${method} but the Mcp-Method header names ${request.mcpMethodHeader}`); + return { + kind: "modern", + messageKind: "notification", + message: body, + classification: { + era: "modern", + revision: headerVersion + } + }; + } + return { + kind: "legacy", + reason: "notification", + ...headerVersion !== void 0 && { requestedVersion: headerVersion } + }; +} +/** +* Classifies one inbound HTTP request for dual-era serving. +* +* The body-primary predicate, evaluated once at the entry boundary: see the +* module documentation for the rules. Returns a routing outcome (`legacy` or +* `modern`) or a ladder rejection; it never throws. +*/ +function src_CX2iR2pK_classifyInboundRequest(request) { + request = { + ...request, + ...request.protocolVersionHeader !== void 0 && { protocolVersionHeader: stripHttpOws(request.protocolVersionHeader) }, + ...request.mcpMethodHeader !== void 0 && { mcpMethodHeader: stripHttpOws(request.mcpMethodHeader) }, + ...request.mcpNameHeader !== void 0 && { mcpNameHeader: stripHttpOws(request.mcpNameHeader) } + }; + if (request.httpMethod.toUpperCase() !== "POST") return { + kind: "legacy", + reason: "http-method" + }; + const body = request.body; + if (Array.isArray(body)) return classifyBatch(body); + if (src_CX2iR2pK_isJSONRPCResultResponse(body) || src_CX2iR2pK_isJSONRPCErrorResponse(body)) return { + kind: "legacy", + reason: "response" + }; + if (isPlainObject$2(body) && src_CX2iR2pK_isJSONRPCRequest(body)) return classifyRequestBody(request, body); + if (isPlainObject$2(body) && src_CX2iR2pK_isJSONRPCNotification(body)) return classifyNotificationBody(request, body); + return src_CX2iR2pK_rejection("jsonrpc-shape", "invalid-json-rpc-body", 400, new src_CX2iR2pK_ProtocolError(src_CX2iR2pK_ProtocolErrorCode.InvalidRequest, "Bad Request: the request body is not a valid JSON-RPC message"), true); +} +/** +* The rejection a modern-only endpoint (no legacy serving configured) +* answers a legacy-classified request with. +* +* - Envelope-less requests (including `initialize`) are answered with the +* unsupported-protocol-version error carrying the endpoint's supported +* versions and echoing the version the request named (when it named one — +* `requested` is omitted rather than fabricated when the request named no +* version at all), so a legacy client can discover what the endpoint serves +* from the error alone. +* - Posted responses and batch arrays are invalid requests on the modern era. +* - Non-`POST` methods are not allowed. +* - Legacy-classified notifications return `undefined`: the caller answers +* 202 with no body and does not dispatch the notification (accept-and-drop). +*/ +function src_CX2iR2pK_modernOnlyStrictRejection(route, supportedVersions) { + switch (route.reason) { + case "http-method": return src_CX2iR2pK_rejection("http-method", "modern-only-method-not-allowed", 405, new src_CX2iR2pK_ProtocolError(-32e3, "Method not allowed."), true); + case "batch": return src_CX2iR2pK_rejection("jsonrpc-shape", "modern-only-batch-not-supported", 400, new src_CX2iR2pK_ProtocolError(src_CX2iR2pK_ProtocolErrorCode.InvalidRequest, "Bad Request: JSON-RPC batches are not supported by this endpoint"), true); + case "response": return src_CX2iR2pK_rejection("jsonrpc-shape", "modern-only-response-post", 400, new src_CX2iR2pK_ProtocolError(src_CX2iR2pK_ProtocolErrorCode.InvalidRequest, "Bad Request: JSON-RPC responses cannot be posted to this endpoint"), true); + case "notification": return; + case "initialize": + case "no-claim": { + const requested = route.requestedVersion; + return src_CX2iR2pK_rejection("era-classification", "modern-only-missing-envelope", 400, requested === void 0 ? new src_CX2iR2pK_ProtocolError(src_CX2iR2pK_ProtocolErrorCode.UnsupportedProtocolVersion, "Unsupported protocol version: the request did not name a protocol version", { supported: [...supportedVersions] }) : new src_CX2iR2pK_UnsupportedProtocolVersionError({ + supported: [...supportedVersions], + requested + }), true); + } + } +} + +//#endregion +//#region ../core-internal/src/util/schema.ts +/** +* Internal Zod schema utilities for protocol handling. +* These are used internally by the SDK for protocol message validation. +*/ +/** +* Parses data against a Zod schema (synchronous). +* Returns a discriminated union with success/error. +*/ +function parseSchema(schema, data) { + return parse_safeParse(schema, data); +} +/** +* Union of the declared shape keys across several Zod object schemas. +*/ +function shapeKeys(schemas) { + return new Set(schemas.flatMap((schema) => Object.keys(schema.shape))); +} + +//#endregion +//#region ../core-internal/src/util/standardSchema.ts +/** +* Standard Schema utilities for user-provided schemas. +* Supports Zod v4, Valibot, ArkType, and other Standard Schema implementations. +* @see https://standardschema.dev +*/ +function isStandardSchema(schema) { + if (schema == null) return false; + const schemaType = typeof schema; + if (schemaType !== "object" && schemaType !== "function") return false; + if (!("~standard" in schema)) return false; + return typeof schema["~standard"]?.validate === "function"; +} +let warnedZodFallback = false; +/** JSON Schema draft targeted by every conversion; shared so pattern references above stay in lockstep. */ +const JSON_SCHEMA_CONVERSION_TARGET = "draft-2020-12"; +/** +* Converts a StandardSchema to JSON Schema for use as an MCP tool/prompt schema. +* +* MCP requires `type: "object"` at the root of tool `inputSchema` and prompt +* argument schemas; `outputSchema` may have any JSON Schema root (SEP-2106). +* Zod's discriminated unions emit `{oneOf: [...]}` without a top-level `type`, +* so for `io: 'input'` this function defaults `type` to `"object"` when absent +* and throws on an explicit non-object `type` (e.g. `z.string()`). For +* `io: 'output'` a non-object root is returned as-is; the `"object"` default is +* applied only when the root is provably object-shaped. +*/ +function standardSchemaToJsonSchema(schema, io = "input") { + const std = schema["~standard"]; + let result; + if (std.jsonSchema) result = std.jsonSchema[io]({ target: JSON_SCHEMA_CONVERSION_TARGET }); + else if (std.vendor === "zod") { + if (!("_zod" in schema)) 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()."); + if (!warnedZodFallback) { + warnedZodFallback = true; + 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."); + } + result = toJSONSchema(schema, { + target: JSON_SCHEMA_CONVERSION_TARGET, + io + }); + } else throw new Error(`Schema library "${std.vendor}" does not implement StandardJSONSchemaV1 (\`~standard.jsonSchema\`). Upgrade to a version that does, or wrap your JSON Schema with fromJsonSchema().`); + if (io === "output") { + if (result.type !== void 0) return result; + return isProvablyObjectShapedRoot(result) ? { + type: "object", + ...result + } : result; + } + if (result.type !== void 0 && result.type !== "object") throw new Error(`MCP tool and prompt schemas must describe objects (got type: ${JSON.stringify(result.type)}). Wrap your schema in z.object({...}) or equivalent.`); + return { + type: "object", + ...result + }; +} +/** +* A typeless JSON Schema root is "provably object-shaped" when either it carries object keywords +* directly (`properties`/`patternProperties`/`additionalProperties`/`required`), or it is a +* composition (`oneOf`/`anyOf`/`allOf`) whose every member is itself `type:'object'` or recursively +* provably object-shaped (e.g. a nested `discriminatedUnion`). `$ref` is not followed. Used to +* decide whether stamping `type:'object'` is safe (redundant-but-valid) versus self-contradictory. +*/ +function isProvablyObjectShapedRoot(schema) { + if ("properties" in schema || "patternProperties" in schema || "additionalProperties" in schema || "required" in schema) return true; + for (const key of [ + "oneOf", + "anyOf", + "allOf" + ]) { + const members = schema[key]; + if (Array.isArray(members) && members.length > 0) return members.every((m) => m !== null && typeof m === "object" && (m.type === "object" || isProvablyObjectShapedRoot(m))); + } + return false; +} +function formatIssue(issue) { + if (!issue.path?.length) return issue.message; + return `${issue.path.map((p) => String(typeof p === "object" ? p.key : p)).join(".")}: ${issue.message}`; +} +async function validateStandardSchema(schema, data) { + const result = await schema["~standard"].validate(data); + if (result.issues && result.issues.length > 0) return { + success: false, + error: result.issues.map((i) => formatIssue(i)).join(", ") + }; + return { + success: true, + data: result.value + }; +} +function zodEmittedPattern(schema) { + const jsonSchema = toJSONSchema(schema, { + target: JSON_SCHEMA_CONVERSION_TARGET, + io: "input" + }); + return typeof jsonSchema.pattern === "string" ? jsonSchema.pattern : void 0; +} +const DATETIME_FRACTION_DIGITS = /\\\.\\d\{(\d+)\}/; +function datetimeReferenceSchemas(pattern) { + const fractionDigits = DATETIME_FRACTION_DIGITS.exec(pattern); + const precisions = [ + void 0, + -1, + 0 + ]; + if (fractionDigits) precisions.push(Number(fractionDigits[1])); + return [false, true].flatMap((local) => [false, true].flatMap((offset) => precisions.map((precision) => iso_datetime({ + local, + offset, + precision + })))); +} +function referencePatternsForFormat(format, pattern) { + let referenceSchemas; + switch (format) { + case "email": + referenceSchemas = [schemas_email()]; + break; + case "uri": + referenceSchemas = [schemas_url()]; + break; + case "date": + referenceSchemas = [iso_date()]; + break; + case "date-time": + referenceSchemas = datetimeReferenceSchemas(pattern); + break; + } + return new Set(referenceSchemas.map((schema) => zodEmittedPattern(schema)).filter((emitted) => emitted !== void 0)); +} +/** Whether `pattern` is the library's own realization of `format` (droppable) rather than a user customization. */ +function isLibraryFormatPattern(format, pattern, vendor) { + if (vendor !== "zod") return true; + return referencePatternsForFormat(format, pattern).has(pattern); +} +function promptArgumentsFromStandardSchema(schema) { + const jsonSchema = standardSchemaToJsonSchema(schema, "input"); + const properties = jsonSchema.properties || {}; + const required = jsonSchema.required || []; + return Object.entries(properties).map(([name, prop]) => ({ + name, + description: prop?.description, + required: required.includes(name) + })); +} + +//#endregion +//#region ../core-internal/src/shared/elicitation.ts +function isJsonObject(value) { + return typeof value === "object" && value !== null && !Array.isArray(value); +} +function convertStandardElicitationSchema(schema) { + try { + return standardSchemaToJsonSchema(schema, "input"); + } catch (error) { + const detail = error instanceof Error ? error.message : String(error); + throw new src_CX2iR2pK_ProtocolError(src_CX2iR2pK_ProtocolErrorCode.InvalidParams, `Elicitation requestedSchema must describe an object with flat primitive properties: ${detail}`); + } +} +const ANNOTATION_ONLY_JSON_SCHEMA_KEYWORDS = new Set([ + "$comment", + "deprecated", + "description", + "examples", + "readOnly", + "title", + "writeOnly" +]); +function isAnnotationOnlyJsonSchemaKeyword(key) { + return ANNOTATION_ONLY_JSON_SCHEMA_KEYWORDS.has(key) || key.startsWith("x-"); +} +const ROOT_KEYS = new Set(["$schema", ...Object.keys(ElicitRequestFormParamsSchema.shape.requestedSchema.shape)]); +const PROPERTY_KEYS_BY_TYPE = { + string: shapeKeys([ + StringSchemaSchema, + UntitledSingleSelectEnumSchemaSchema, + TitledSingleSelectEnumSchemaSchema, + LegacyTitledEnumSchemaSchema + ]), + number: shapeKeys([NumberSchemaSchema]), + integer: shapeKeys([NumberSchemaSchema]), + boolean: shapeKeys([BooleanSchemaSchema]), + array: shapeKeys([UntitledMultiSelectEnumSchemaSchema, TitledMultiSelectEnumSchemaSchema]) +}; +const SUPPORTED_STRING_FORMATS = new Set(StringSchemaSchema.shape.format.unwrap().options); +/** Walks one property node: keeps grammar keys, drops the library format pattern, rejects unknown constraints. */ +function walkProperty(node, path, vendor, unsupported) { + if (!isJsonObject(node)) return node; + const allowedKeys = typeof node.type === "string" && Object.hasOwn(PROPERTY_KEYS_BY_TYPE, node.type) ? PROPERTY_KEYS_BY_TYPE[node.type] : void 0; + if (allowedKeys === void 0) return node; + const pruned = {}; + for (const [key, value] of Object.entries(node)) if (allowedKeys.has(key) || isAnnotationOnlyJsonSchemaKeyword(key)) pruned[key] = value; + else if (key === "pattern" && node.type === "string" && typeof node.format === "string") { + if (!SUPPORTED_STRING_FORMATS.has(node.format)) pruned[key] = value; + else if (typeof value !== "string" || !isLibraryFormatPattern(node.format, value, vendor)) unsupported.push(`${path}.${key}`); + } else unsupported.push(`${path}.${key}`); + return pruned; +} +/** Walks the schema root: keeps the spec root keys, drops annotations, rejects the rest. */ +function walkRequestedSchema(converted, vendor) { + const pruned = {}; + const unsupported = []; + for (const [key, value] of Object.entries(converted)) if (key === "properties" && isJsonObject(value)) pruned[key] = Object.fromEntries(Object.entries(value).map(([name, node]) => [name, walkProperty(node, `properties.${name}`, vendor, unsupported)])); + else if (ROOT_KEYS.has(key)) pruned[key] = value; + else if (!isAnnotationOnlyJsonSchemaKeyword(key)) unsupported.push(key); + if (unsupported.length > 0) throw new src_CX2iR2pK_ProtocolError(src_CX2iR2pK_ProtocolErrorCode.InvalidParams, `Elicitation requestedSchema contains unsupported JSON Schema constraint(s) after Standard Schema conversion: ${unsupported.join(", ")}`); + return pruned; +} +/** Names the properties that fail value validation, instead of surfacing a raw union dump. */ +function describeUnsupportedProperties(pruned, fallback) { + if (!isJsonObject(pruned.properties)) return fallback; + const offenders = Object.entries(pruned.properties).filter(([, node]) => !parseSchema(PrimitiveSchemaDefinitionSchema, node).success).map(([name]) => `properties.${name}`); + return offenders.length > 0 ? offenders.join(", ") : fallback; +} +function findDroppedConstraintPaths(original, parsed, path = "") { + if (Array.isArray(original) && Array.isArray(parsed)) return original.flatMap((item, index) => findDroppedConstraintPaths(item, parsed[index], `${path}[${index}]`)); + if (!isJsonObject(original) || !isJsonObject(parsed)) return []; + return Object.entries(original).flatMap(([key, value]) => { + const childPath = path ? `${path}.${key}` : key; + if (!Object.prototype.hasOwnProperty.call(parsed, key)) return isAnnotationOnlyJsonSchemaKeyword(key) ? [] : [childPath]; + return findDroppedConstraintPaths(value, parsed[key], childPath); + }); +} +/** Converts an authoring-friendly elicitation input into its wire-ready form. */ +function normalizeElicitInputParams(input) { + if (!isStandardSchema(input.requestedSchema)) return { + ...input, + mode: "form", + requestedSchema: input.requestedSchema + }; + const vendor = input.requestedSchema["~standard"].vendor; + const pruned = walkRequestedSchema(convertStandardElicitationSchema(input.requestedSchema), vendor); + const parsed = parseSchema(ElicitRequestFormParamsSchema.shape.requestedSchema, pruned); + if (!parsed.success) throw new src_CX2iR2pK_ProtocolError(src_CX2iR2pK_ProtocolErrorCode.InvalidParams, `Elicitation requestedSchema only supports flat primitive properties (string, number, integer, boolean, and string enums): ${describeUnsupportedProperties(pruned, parsed.error.message)}`); + const droppedConstraints = findDroppedConstraintPaths(pruned, parsed.data); + if (droppedConstraints.length > 0) throw new src_CX2iR2pK_ProtocolError(src_CX2iR2pK_ProtocolErrorCode.InvalidParams, `Elicitation requestedSchema contains unsupported JSON Schema constraint(s) after Standard Schema conversion: ${droppedConstraints.join(", ")}`); + const danglingRequired = (parsed.data.required ?? []).filter((key) => !Object.prototype.hasOwnProperty.call(parsed.data.properties, key)); + if (danglingRequired.length > 0) throw new src_CX2iR2pK_ProtocolError(src_CX2iR2pK_ProtocolErrorCode.InvalidParams, `Elicitation requestedSchema lists required properties that are not defined in properties: ${danglingRequired.join(", ")}`); + return { + ...input, + mode: "form", + requestedSchema: parsed.data + }; +} + +//#endregion +//#region ../core-internal/src/shared/inputRequired.ts +/** +* Authoring helpers for multi-round-trip requests (protocol revision +* 2026-07-28). +* +* A handler for one of the multi-round-trip methods (`tools/call`, +* `prompts/get`, `resources/read`) requests additional client input by +* returning an {@linkcode InputRequiredResult} instead of a final result. The +* helpers here build that return value and its embedded requests as NEUTRAL +* values; only the 2026-07-28 wire codec maps them to/from the wire. The +* 2025-era codec has no input-required vocabulary — on a 2025-era request the +* server's legacy shim (on by default) fulfils the embedded requests as real +* server→client requests and re-enters the handler, so the same return shape +* serves both eras; `ServerOptions.inputRequired.legacyShim: false` restores +* the pre-shim loud failure. +* +* There is no nominal brand: `resultType: 'input_required'` is the +* discriminator, and hand-built result literals are equally legal — the +* server seam re-checks the at-least-one rule for them. +*/ +function buildInputRequired(spec) { + const hasInputRequests = spec.inputRequests !== void 0 && Object.keys(spec.inputRequests).length > 0; + const hasRequestState = typeof spec.requestState === "string"; + if (!hasInputRequests && !hasRequestState) 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", + ...spec.inputRequests !== void 0 && { inputRequests: spec.inputRequests }, + ...spec.requestState !== void 0 && { requestState: spec.requestState } + }; +} +/** +* Builder for the input-required return value of multi-round-trip handlers, +* with per-kind constructors for the embedded requests +* (`inputRequired.elicit`, `inputRequired.elicitUrl`, +* `inputRequired.createMessage`, `inputRequired.listRoots`). +* +* @example Write-once tool requesting confirmation +* ```ts +* server.registerTool('deploy', { inputSchema: z.object({ env: z.string() }) }, async ({ env }, ctx) => { +* const confirmed = acceptedContent<{ confirm: boolean }>(ctx.mcpReq.inputResponses, 'confirm'); +* if (!confirmed) { +* return inputRequired({ +* inputRequests: { +* confirm: inputRequired.elicit({ +* message: `Deploy to ${env}?`, +* requestedSchema: { type: 'object', properties: { confirm: { type: 'boolean' } }, required: ['confirm'] } +* }) +* } +* }); +* } +* return { content: [{ type: 'text', text: `deployed to ${env}` }] }; +* }); +* ``` +*/ +const inputRequired = Object.assign(buildInputRequired, { + elicit(params) { + try { + return { + method: "elicitation/create", + params: normalizeElicitInputParams(params) + }; + } catch (error) { + throw error instanceof src_CX2iR2pK_ProtocolError ? new TypeError(error.message, { cause: error }) : error; + } + }, + elicitUrl(params) { + return { + method: "elicitation/create", + params: { + ...params, + mode: "url" + } + }; + }, + createMessage(params) { + return { + method: "sampling/createMessage", + params + }; + }, + listRoots() { + return { method: "roots/list" }; + } +}); +function acceptedContent(responses, key, schema) { + const view = inputResponse(responses, key); + if (view.kind !== "elicit" || view.action !== "accept" || view.content === void 0) return void 0; + if (schema === void 0) return view.content; + const outcome = schema["~standard"].validate(view.content); + if (outcome instanceof Promise) throw new TypeError("acceptedContent(responses, key, schema) requires a synchronously-validating schema"); + return outcome.issues === void 0 ? outcome.value : void 0; +} +/** +* Reads one entry of a retried request's `inputResponses` +* (`ctx.mcpReq.inputResponses`) as a discriminated view, covering +* decline/cancel detection and the non-elicitation response kinds that +* {@linkcode acceptedContent} does not surface. +* +* The values arrive from the client and are not re-validated here — treat +* them as untrusted input (validate elicitation content with the +* schema-aware {@linkcode acceptedContent} overload where it matters). +*/ +function inputResponse(responses, key) { + if (responses === void 0 || typeof responses !== "object" || responses === null) return { kind: "missing" }; + const entry = responses[key]; + if (entry === null || typeof entry !== "object" || Array.isArray(entry)) return { kind: "missing" }; + const candidate = entry; + if (candidate["action"] === "accept" || candidate["action"] === "decline" || candidate["action"] === "cancel") { + const content = candidate["content"]; + return { + kind: "elicit", + action: candidate["action"], + ...content !== null && typeof content === "object" && !Array.isArray(content) && { content } + }; + } + if (Array.isArray(candidate["roots"])) return { + kind: "roots", + roots: candidate["roots"] + }; + if (typeof candidate["role"] === "string" && candidate["content"] !== void 0) return { + kind: "sampling", + result: candidate + }; + return { kind: "missing" }; +} + +//#endregion +//#region ../core-internal/src/shared/inputRequiredDriver.ts +/** +* The multi-round-trip auto-fulfilment driver (protocol revision 2026-07-28). +* +* When a request to one of the multi-round-trip methods comes back as +* `input_required`, the driver fulfils the embedded input requests by +* dispatching them to the client's already-registered handlers (elicitation, +* sampling, roots — one generic engine, no per-feature API), then retries the +* original request with the collected `inputResponses` and a byte-exact echo +* of `requestState`, on a fresh request id, until the server returns a +* complete result or the round cap is exhausted. +* +* The driver is a LAYER OVER THE MANUAL PATH: each retry is issued with the +* same primitive a manual caller uses (`allowInputRequired` semantics — the +* retry hands back the next `input_required` payload instead of recursing), +* so the loop, the cap, and the pacing live in one place and disabling +* auto-fulfilment (`inputRequired.autoFulfill: false`) simply skips this +* module. Timeouts ride the EXISTING knobs: the per-leg `timeout` applies to +* every wire leg unchanged, and `maxTotalTimeout` bounds the whole flow by +* shrinking the budget passed to each leg — no new timer system. +*/ +/** +* Fixed pacing applied before retrying a requestState-only (load-shedding) +* leg — a leg that carries no embedded input requests, so nothing slows the +* loop down naturally. Counted in the same round cap. +*/ +const REQUEST_STATE_ONLY_LEG_PACING_MS = 250; +/** +* The message both multi-round-trip loops emit when the round cap is +* exhausted — the client driver as a typed error, the server-side legacy +* shim as its per-family failure. One formatter so the texts cannot drift +* (hosts and models read the tool-result copy verbatim). +*/ +function inputRequiredRoundsExceededMessage(method, maxRounds) { + return `Multi-round-trip request '${method}' still required input after ${maxRounds} rounds (inputRequired.maxRounds)`; +} +/** +* Abortable delay: resolves after `ms`, or rejects with the signal's reason +* (wrapped in an `SdkError` when it isn't already one) if the signal aborts +* first. Aborting after resolution is a no-op. Shared with the server-side +* legacy shim (the pacing semantics must match per era). +*/ +function sleep(ms, signal) { + return new Promise((resolve, reject) => { + if (signal?.aborted) { + reject(signal.reason instanceof src_CX2iR2pK_SdkError ? signal.reason : new src_CX2iR2pK_SdkError(src_CX2iR2pK_SdkErrorCode.RequestTimeout, String(signal.reason))); + return; + } + const timer = setTimeout(() => { + signal?.removeEventListener("abort", onAbort); + resolve(); + }, ms); + const onAbort = () => { + clearTimeout(timer); + reject(signal?.reason instanceof src_CX2iR2pK_SdkError ? signal.reason : new src_CX2iR2pK_SdkError(src_CX2iR2pK_SdkErrorCode.RequestTimeout, String(signal?.reason))); + }; + signal?.addEventListener("abort", onAbort, { once: true }); + }); +} +/** +* A per-round abort linked to the caller's signal: the embedded sibling +* dispatches share it, so the first failure (or a caller abort) cancels the +* others instead of leaving them running. Shared with the server-side legacy +* shim (the abort-linkage semantics must match per era). +*/ +function linkedRoundAbort(outer) { + const controller = new AbortController(); + const onOuterAbort = () => controller.abort(outer?.reason); + outer?.addEventListener("abort", onOuterAbort, { once: true }); + if (outer?.aborted) controller.abort(outer.reason); + return { + signal: controller.signal, + abort: (reason) => controller.abort(reason), + dispose: () => outer?.removeEventListener("abort", onOuterAbort) + }; +} + +//#endregion +//#region ../core-internal/src/types/specTypeSchema.ts +/** +* Explicit allowlist of protocol Zod schemas that correspond to a public spec type in `types.ts`. +* +* This intentionally excludes internal helper schemas exported from `schemas.ts` that have no +* matching public type (e.g. `ListChangedOptionsBaseSchema`, `BaseRequestParamsSchema`, +* `NotificationsParamsSchema`, `ClientTasksCapabilitySchema`, `ServerTasksCapabilitySchema`). +* Keeping the list explicit means new public spec types must be added here deliberately, and +* internals never leak into `SpecTypeName`. +* +* `ResourceTemplateSchema` is included; its public type is exported as `ResourceTemplateType` +* (the bare name collides with the server package's `ResourceTemplate` class), so +* `SpecTypes['ResourceTemplate']` is structurally equal to `ResourceTemplateType` rather than to +* a type literally named `ResourceTemplate`. +*/ +const SPEC_SCHEMA_KEYS = [ + "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" +]; +const authSchemas = { + IdJagTokenExchangeResponseSchema: IdJagTokenExchangeResponseSchema, + OAuthClientInformationFullSchema: OAuthClientInformationFullSchema, + OAuthClientInformationSchema: OAuthClientInformationSchema, + OAuthClientMetadataSchema: OAuthClientMetadataSchema, + OAuthClientRegistrationErrorSchema: OAuthClientRegistrationErrorSchema, + OAuthErrorResponseSchema: OAuthErrorResponseSchema, + OAuthMetadataSchema: OAuthMetadataSchema, + OAuthProtectedResourceMetadataSchema: OAuthProtectedResourceMetadataSchema, + OAuthTokenRevocationRequestSchema: OAuthTokenRevocationRequestSchema, + OAuthTokensSchema: OAuthTokensSchema, + OpenIdProviderDiscoveryMetadataSchema: OpenIdProviderDiscoveryMetadataSchema, + OpenIdProviderMetadataSchema: OpenIdProviderMetadataSchema +}; +const _specTypeSchemas = {}; +const _isSpecType = {}; +function register(key, schema) { + const name = key.slice(0, -6); + _specTypeSchemas[name] = schema; + _isSpecType[name] = (v) => schema.safeParse(v).success; +} +for (const key of SPEC_SCHEMA_KEYS) register(key, schemas_exports[key]); +for (const [key, schema] of Object.entries(authSchemas)) register(key, schema); +/** +* Runtime validators for every MCP spec type, keyed by type name. +* +* Use this when you need to validate a spec-defined shape at a boundary the SDK does not own, for +* example an extension's custom-method payload that embeds a `CallToolResult`, or a value read from +* storage that should be a `Tool`. +* +* Each entry implements the Standard Schema interface, so it composes with any +* Standard-Schema-aware library. For a simple boolean check, use {@linkcode isSpecType} instead. +* +* @example +* ```ts source="./specTypeSchema.examples.ts#specTypeSchemas_basicUsage" +* const result = specTypeSchemas.CallToolResult['~standard'].validate(untrusted); +* if (result.issues === undefined) { +* // result.value is CallToolResult +* } +* ``` +*/ +const specTypeSchemas = Object.freeze(_specTypeSchemas); +/** +* Type predicates for every MCP spec type, keyed by type name. +* +* Returns `true` if the value satisfies the schema's input type (`z.input<>`, before defaults and +* transforms are applied), and narrows to that input type. For schemas with `.default()` or +* `.preprocess()`, this may accept values that do not structurally match the named output type; +* for example `isSpecType.CallToolResult({})` is `true` because `content` has a default. Use +* `specTypeSchemas.X['~standard'].validate(value)` when you need the validated output value. +* +* Each guard is a standalone function, so it can be passed directly as a callback. +* +* @example +* ```ts source="./specTypeSchema.examples.ts#isSpecType_basicUsage" +* if (isSpecType.ContentBlock(value)) { +* // value is ContentBlock +* } +* +* const blocks = mixed.filter(isSpecType.ContentBlock); +* ``` +*/ +const isSpecType = Object.freeze(_isSpecType); + +//#endregion +//#region ../core-internal/src/wire/bootstrap.ts +function bootstrapOutboundCodec(method) { + switch (method) { + case "initialize": + case "notifications/initialized": return src_CX2iR2pK_codecForVersion(void 0); + case "server/discover": return src_CX2iR2pK_codecForVersion(src_CX2iR2pK_MODERN_WIRE_REVISION); + default: return; + } +} + +//#endregion +//#region ../core-internal/src/shared/protocol.ts +/** +* The default request timeout, in milliseconds. +*/ +const DEFAULT_REQUEST_TIMEOUT_MSEC = 6e4; +/** +* The reserved per-request `_meta` envelope keys (protocol revision +* 2026-07-28). The protocol layer lifts these out of inbound `_meta` before +* handlers run and surfaces them at `ctx.mcpReq.envelope` — they are +* wire-level bookkeeping, not handler material. +*/ +const RESERVED_ENVELOPE_META_KEYS = [ + auth_CUe6YdwF_PROTOCOL_VERSION_META_KEY, + auth_CUe6YdwF_CLIENT_INFO_META_KEY, + auth_CUe6YdwF_CLIENT_CAPABILITIES_META_KEY, + LOG_LEVEL_META_KEY +]; +/** +* Top-level params members carrying multi-round-trip driver material +* (protocol revision 2026-07-28). The spec reserves these names on +* client-initiated REQUESTS only — notification params keep them untouched +* (a vendor notification may legitimately use the same names). +*/ +const RETRY_PARAMS_KEYS = ["inputResponses", "requestState"]; +/** +* Lift wire-only material out of an inbound message so handlers see exactly +* the 2025-era shape, and surface it for the protocol layer (requests: via +* `ctx.mcpReq`). What counts as wire-only depends on the message kind: the +* reserved envelope `_meta` keys are reserved on every message, while the +* multi-round-trip retry fields (`inputResponses`/`requestState`) are +* reserved on client-initiated requests only — so notifications get only the +* envelope lift, and their top-level params stay untouched. Messages without +* wire-only material are returned unchanged (same reference). +*/ +function liftWireOnlyMaterial(message, kind) { + const params = message.params; + if (!isPlainObject$1(params)) return { + message, + lifted: {} + }; + const meta = params._meta; + const envelopeKeys = isPlainObject$1(meta) ? RESERVED_ENVELOPE_META_KEYS.filter((key) => key in meta) : []; + const retryKeys = kind === "request" ? RETRY_PARAMS_KEYS.filter((key) => key in params) : []; + if (envelopeKeys.length === 0 && retryKeys.length === 0) return { + message, + lifted: {} + }; + const lifted = {}; + const nextParams = { ...params }; + if (envelopeKeys.length > 0 && isPlainObject$1(meta)) { + const envelope = {}; + const nextMeta = { ...meta }; + for (const key of envelopeKeys) { + envelope[key] = meta[key]; + delete nextMeta[key]; + } + lifted.envelope = envelope; + if (Object.keys(nextMeta).length > 0) nextParams._meta = nextMeta; + else delete nextParams._meta; + } + for (const key of retryKeys) { + if (key === "inputResponses") lifted.inputResponses = nextParams[key]; + if (key === "requestState") lifted.requestState = nextParams[key]; + delete nextParams[key]; + } + return { + message: { + ...message, + params: nextParams + }, + lifted + }; +} +/** +* Standard Schema adapter over the era codec's `validateResult` function (the +* function-only WireCodec contract exposes no schema objects). Used by the +* spec-method `request()` overload so the request funnel keeps a single +* `StandardSchemaV1`-shaped validation seam for both spec and explicit-schema +* paths. +* +* Returns `undefined` when the method has no result entry on this era's +* registry — the caller maps that to the synchronous "pass a result schema" +* TypeError, exactly matching the pre-function-only behavior the +* typedMapAlignment suite pins (the result map deliberately excludes the +* `tasks/*` methods, so the spec-method overload refuses them up front). +*/ +function codecResultValidator(codec, method) { + const probe = codec.validateResult(method, void 0); + if (!probe.ok && probe.reason === "not-in-era") return void 0; + return { "~standard": { + version: 1, + vendor: "mcp-wire-codec", + validate(value) { + const outcome = codec.validateResult(method, value); + if (outcome.ok) return { value: outcome.value }; + return { issues: [{ message: outcome.reason === "invalid" ? outcome.message : `not-in-era: ${method}` }] }; + } + } }; +} +/** +* Builds the `ctx.mcpReq.requestState` accessor for a resolved value. The +* `as T` below is the one place {@linkcode RequestStateAccessor}'s +* caller-asserted typing is implemented — no implementation can produce an +* arbitrary `T` from a runtime value honestly. +*/ +function requestStateAccessor(value) { + return () => value; +} +/** Shared no-state accessor: the common case allocates nothing per request. */ +const NO_REQUEST_STATE = requestStateAccessor(void 0); +/** +* Returns a context whose `requestState` accessor reads the given value — +* how the server seam hands a verify hook's decoded payload (or the legacy +* shim's per-round echo) to the handler without mutating the original +* context. +*/ +function withRequestStateValue(ctx, value) { + return { + ...ctx, + mcpReq: { + ...ctx.mcpReq, + requestState: requestStateAccessor(value) + } + }; +} +let writeNegotiatedProtocolVersion; +/** +* Package-internal write channel for a {@linkcode Protocol} instance's +* negotiated protocol version, for callers outside the class hierarchy: +* tests and the (future) modern-era server entry that marks a factory +* instance modern at binding time. Exported on the core internal barrel +* only — never public API. +*/ +function src_CX2iR2pK_setNegotiatedProtocolVersion(instance, version) { + writeNegotiatedProtocolVersion(instance, version); +} +/** +* Implements MCP protocol framing on top of a pluggable transport, including +* features like request/response linking, notifications, and progress. +* +* `Protocol` is abstract; `Client` and `Server` are the concrete role-specific +* implementations most code should use. +*/ +var Protocol = class { + _transport; + _requestMessageId = 0; + _requestHandlers = /* @__PURE__ */ new Map(); + _requestHandlerAbortControllers = /* @__PURE__ */ new Map(); + _notificationHandlers = /* @__PURE__ */ new Map(); + _responseHandlers = /* @__PURE__ */ new Map(); + _progressHandlers = /* @__PURE__ */ new Map(); + _timeoutInfo = /* @__PURE__ */ new Map(); + _pendingDebouncedNotifications = /* @__PURE__ */ new Set(); + /** + * The protocol version negotiated for the current connection (`undefined` + * before negotiation completes), which determines the wire era this + * instance speaks. Set by the SDK's negotiation and initialize paths + * (`Client.connect`, `Server._oninitialize`). + */ + _negotiatedProtocolVersion; + static { + writeNegotiatedProtocolVersion = (instance, version) => { + instance._negotiatedProtocolVersion = version; + }; + } + _supportedProtocolVersions; + /** + * Callback for when the connection is closed for any reason. + * + * This is invoked when {@linkcode Protocol.close | close()} is called as well. + */ + onclose; + /** + * Callback for when an error occurs. + * + * Note that errors are not necessarily fatal; they are used for reporting any kind of exceptional condition out of band. + */ + onerror; + /** + * A handler to invoke for any request types that do not have their own handler installed. + */ + fallbackRequestHandler; + /** + * A handler to invoke for any notification types that do not have their own handler installed. + */ + fallbackNotificationHandler; + constructor(_options) { + this._options = _options; + this._supportedProtocolVersions = _options?.supportedProtocolVersions ?? auth_CUe6YdwF_SUPPORTED_PROTOCOL_VERSIONS; + this.setNotificationHandler("notifications/cancelled", (notification) => { + this._oncancel(notification); + }); + this.setNotificationHandler("notifications/progress", (notification) => { + this._onprogress(notification); + }); + this.setRequestHandler("ping", (_request) => ({})); + } + /** + * Drop consult for inbound messages whose transport did not classify them + * at the edge — long-lived channels such as stdio, where a role class may + * need to decline traffic the negotiated era has no answer for (the + * client-side inbound-request drop on modern-era connections: the + * 2026-07-28 era has no server→client request channel, and on stdio the + * client must never write JSON-RPC responses). + * + * Consulted ONLY when the transport supplied no + * {@linkcode MessageExtraInfo.classification}: edge-classified traffic + * never reaches the hook. Returning `'drop'` discards the message without + * writing any response (requests are surfaced via `onerror`). The base + * implementation returns `undefined`: unclassified traffic keeps today's + * dispatch path unchanged. Era selection never happens here — era is + * instance state, owned by the serving entry that constructed and + * connected the instance. + */ + _shouldDropInbound(_message) {} + /** + * The per-request `_meta` envelope this instance attaches to every outgoing + * request and notification, when one applies. The base implementation + * returns `undefined` (no envelope — the 2025-era posture, so legacy-era + * outbound traffic is byte-identical to a build without this seam). + * `Client` overrides it on a connection that negotiated a modern (2026-07-28+) + * era to return the reserved protocol-version / client-info / + * client-capabilities keys. User-supplied `_meta` keys take precedence over + * the auto-attached ones. + */ + _outboundMetaEnvelope() {} + /** + * Attach this instance's outbound `_meta` envelope (when one is configured) + * to a request or notification. A no-op when the seam returns `undefined` + * — the message returns by reference, so the legacy-era wire stays + * byte-identical. User-supplied `_meta` keys are spread last so they win + * over the auto-attached envelope keys. + */ + _envelopeOutbound(message) { + const envelope = this._outboundMetaEnvelope(); + if (envelope === void 0) return message; + const params = message.params ?? {}; + return { + ...message, + params: { + ...params, + _meta: { + ...envelope, + ...params._meta + } + } + }; + } + /** + * Extension point for non-`complete` decoded results in the response + * funnel: a result the wire codec discriminated into a kind other than + * `'complete'` or `'invalid'` is handed here for the role class to + * resolve. The base default surfaces it as a typed + * {@linkcode SdkErrorCode.UnsupportedResultType} error (no retry). + * + * Intended consumers (named so the seam stays accountable): + * - the `Client`'s multi-round-trip auto-fulfilment engine, which fulfils + * `'input_required'` results through the registered + * elicitation/sampling/roots handlers and retries via `flow.retry`; + * - a future client-side terminal-result handler for + * `subscriptions/listen`, when the spec defines one. + * + * `Server` instances never receive `input_required` responses on their + * outbound legs and leave the base behavior in place. + */ + _resolveNonCompleteResult(decoded, flow) { + return Promise.reject(new src_CX2iR2pK_SdkError(src_CX2iR2pK_SdkErrorCode.UnsupportedResultType, `Unsupported result type '${decoded.kind}' for ${flow.request.method}`, { + resultType: decoded.kind, + method: flow.request.method + })); + } + /** + * Protected accessor for a registered request handler. Used by role + * classes that dispatch synthesized requests through the same stored + * handler chain (e.g. the `Client` fulfilling an embedded multi-round-trip + * input request). + */ + _getRequestHandler(method) { + return this._requestHandlers.get(method); + } + async _oncancel(notification) { + if (!notification.params.requestId) return; + this._requestHandlerAbortControllers.get(notification.params.requestId)?.abort(notification.params.reason); + } + _setupTimeout(messageId, timeout, maxTotalTimeout, onTimeout, resetTimeoutOnProgress = false) { + this._timeoutInfo.set(messageId, { + timeoutId: setTimeout(onTimeout, timeout), + startTime: Date.now(), + timeout, + maxTotalTimeout, + resetTimeoutOnProgress, + onTimeout + }); + } + _resetTimeout(messageId) { + const info = this._timeoutInfo.get(messageId); + if (!info) return false; + const totalElapsed = Date.now() - info.startTime; + if (info.maxTotalTimeout && totalElapsed >= info.maxTotalTimeout) { + this._timeoutInfo.delete(messageId); + throw new src_CX2iR2pK_SdkError(src_CX2iR2pK_SdkErrorCode.RequestTimeout, "Maximum total timeout exceeded", { + maxTotalTimeout: info.maxTotalTimeout, + totalElapsed + }); + } + clearTimeout(info.timeoutId); + info.timeoutId = setTimeout(info.onTimeout, info.timeout); + return true; + } + _cleanupTimeout(messageId) { + const info = this._timeoutInfo.get(messageId); + if (info) { + clearTimeout(info.timeoutId); + this._timeoutInfo.delete(messageId); + } + } + /** + * Attaches to the given transport, starts it, and starts listening for messages. + * + * The caller assumes ownership of the {@linkcode Transport}, replacing any callbacks that have already been set, and expects that it is the only user of the {@linkcode Transport} instance going forward. + */ + async connect(transport) { + this._transport = transport; + const _onclose = this.transport?.onclose; + this._transport.onclose = () => { + try { + _onclose?.(); + } finally { + this._onclose(); + } + }; + const _onerror = this.transport?.onerror; + this._transport.onerror = (error) => { + _onerror?.(error); + this._onerror(error); + }; + const _onmessage = this._transport?.onmessage; + this._transport.onmessage = (message, extra) => { + _onmessage?.(message, extra); + if (src_CX2iR2pK_isJSONRPCResultResponse(message) || src_CX2iR2pK_isJSONRPCErrorResponse(message)) this._onresponse(message); + else if (src_CX2iR2pK_isJSONRPCRequest(message)) this._onrequest(message, extra); + else if (src_CX2iR2pK_isJSONRPCNotification(message)) this._onnotification(message, extra); + else this._onerror(/* @__PURE__ */ new Error(`Unknown message type: ${JSON.stringify(message)}`)); + }; + transport.setSupportedProtocolVersions?.(this._supportedProtocolVersions); + await this._transport.start(); + } + /** + * Transport-close hook. Subclass overrides MUST call `super._onclose()` + * after their own cleanup — base teardown (response-handler settlement, + * timeout clearing, in-flight request abort) does not run otherwise. + */ + _onclose() { + const responseHandlers = this._responseHandlers; + this._responseHandlers = /* @__PURE__ */ new Map(); + this._progressHandlers.clear(); + this._pendingDebouncedNotifications.clear(); + for (const info of this._timeoutInfo.values()) clearTimeout(info.timeoutId); + this._timeoutInfo.clear(); + const requestHandlerAbortControllers = this._requestHandlerAbortControllers; + this._requestHandlerAbortControllers = /* @__PURE__ */ new Map(); + const error = new src_CX2iR2pK_SdkError(src_CX2iR2pK_SdkErrorCode.ConnectionClosed, "Connection closed"); + this._transport = void 0; + try { + this.onclose?.(); + } finally { + for (const handler of responseHandlers.values()) handler(error); + for (const controller of requestHandlerAbortControllers.values()) controller.abort(error); + } + } + _onerror(error) { + this.onerror?.(error); + } + /** + * Inbound-notification dispatch. Subclass overrides MUST delegate + * unmatched traffic to `super._onnotification(rawNotification, extra)` — + * an override that consumes only what it owns and falls through to base + * dispatch for everything else. + */ + _onnotification(rawNotification, extra) { + const { message: notification } = liftWireOnlyMaterial(rawNotification, "notification"); + const codec = this._negotiatedWireCodec(); + if (extra?.classification === void 0 && this._shouldDropInbound(rawNotification) === "drop") return; + if (extra?.classification !== void 0) { + const classified = classifiedWireEra(extra.classification); + if (classified !== codec.era) { + this._onerror(/* @__PURE__ */ new Error(`Era mismatch on inbound notification '${notification.method}': classified as ${classified} but this instance serves ${codec.era}`)); + return; + } + } + if (isSpecNotificationMethod(notification.method) && !codec.hasNotificationMethod(notification.method)) return; + const handler = this._notificationHandlers.get(notification.method); + const fallback = this.fallbackNotificationHandler; + if (handler === void 0 && fallback === void 0) return; + Promise.resolve().then(() => handler === void 0 ? fallback(notification) : handler(notification, codec)).catch((error) => this._onerror(/* @__PURE__ */ new Error(`Uncaught error in notification handler: ${error}`))); + } + _onrequest(rawRequest, extra) { + const { message: request, lifted } = liftWireOnlyMaterial(rawRequest, "request"); + const codec = this._negotiatedWireCodec(); + if (extra?.classification === void 0 && this._shouldDropInbound(rawRequest) === "drop") { + this._onerror(/* @__PURE__ */ new Error(`Dropped inbound request '${rawRequest.method}': not servable on this connection's protocol era`)); + return; + } + const capturedTransport = this._transport; + const sendErrorResponse = (code, message, data) => { + const errorResponse = { + jsonrpc: "2.0", + id: request.id, + error: { + code, + message, + ...data !== void 0 && { data } + } + }; + capturedTransport?.send(errorResponse).catch((error) => this._onerror(/* @__PURE__ */ new Error(`Failed to send an error response: ${error}`))); + }; + if (extra?.classification !== void 0) { + const classified = classifiedWireEra(extra.classification); + if (classified !== codec.era) { + this._onerror(/* @__PURE__ */ new Error(`Era mismatch on inbound request '${request.method}': classified as ${classified} but this instance serves ${codec.era}`)); + const requested = extra.classification.revision ?? classified; + sendErrorResponse(src_CX2iR2pK_ProtocolErrorCode.UnsupportedProtocolVersion, `Unsupported protocol version: ${requested}`, { + supported: this._supportedProtocolVersions, + requested + }); + return; + } + } + if (isSpecRequestMethod(request.method) && !codec.hasRequestMethod(request.method)) { + sendErrorResponse(src_CX2iR2pK_ProtocolErrorCode.MethodNotFound, "Method not found"); + return; + } + const handler = this._requestHandlers.get(request.method) ?? this.fallbackRequestHandler; + if (handler === void 0) { + sendErrorResponse(src_CX2iR2pK_ProtocolErrorCode.MethodNotFound, "Method not found"); + return; + } + const envelopeError = codec.checkInboundEnvelope(lifted); + if (envelopeError !== void 0) { + sendErrorResponse(src_CX2iR2pK_ProtocolErrorCode.InvalidParams, envelopeError); + return; + } + const sendNotification = (notification, options) => this._notificationViaCodec(this._resolveOutboundCodec(notification.method), notification, { + ...options, + relatedRequestId: request.id + }); + const sendRequest = (r, resultSchema, options) => this._requestWithSchemaViaCodec(this._resolveOutboundCodec(r.method), r, resultSchema, { + ...options, + relatedRequestId: request.id + }); + const abortController = new AbortController(); + this._requestHandlerAbortControllers.set(request.id, abortController); + const partitionedInputResponses = lifted.inputResponses === void 0 ? void 0 : partitionInputResponses(lifted.inputResponses); + const baseCtx = { + sessionId: capturedTransport?.sessionId, + mcpReq: { + id: request.id, + method: request.method, + _meta: request.params?._meta, + ...lifted.envelope !== void 0 && { envelope: lifted.envelope }, + ...partitionedInputResponses !== void 0 && { inputResponses: partitionedInputResponses.accepted }, + ...partitionedInputResponses !== void 0 && partitionedInputResponses.droppedKeys.length > 0 && { droppedInputResponseKeys: partitionedInputResponses.droppedKeys }, + requestState: lifted.requestState === void 0 ? NO_REQUEST_STATE : requestStateAccessor(lifted.requestState), + signal: abortController.signal, + send: ((r, schemaOrOptions, maybeOptions) => { + const sendCodec = this._resolveOutboundCodec(r.method); + this._assertOutboundRequestInEra(sendCodec, r.method); + if (isStandardSchema(schemaOrOptions)) return sendRequest(r, schemaOrOptions, maybeOptions); + const validate = codecResultValidator(sendCodec, r.method); + if (validate === void 0) throw new TypeError(`'${r.method}' is not a spec method; pass a result schema as the second argument to ctx.mcpReq.send().`); + return sendRequest(r, validate, schemaOrOptions); + }), + notify: sendNotification + }, + http: extra?.authInfo ? { authInfo: extra.authInfo } : void 0 + }; + const ctx = this.buildContext(baseCtx, extra); + Promise.resolve().then(() => handler(request, ctx)).then(async (result) => { + if (abortController.signal.aborted) return; + let encoded; + try { + encoded = codec.encodeResult(request.method, result, this._outboundServerInfo()); + } catch (error) { + this._onerror(/* @__PURE__ */ new Error(`Failed to encode result for ${request.method}: ${error}`)); + sendErrorResponse(src_CX2iR2pK_ProtocolErrorCode.InternalError, "Internal error"); + return; + } + const response = { + result: encoded, + jsonrpc: "2.0", + id: request.id + }; + await capturedTransport?.send(response); + }, async (error) => { + if (abortController.signal.aborted) return; + const thrownCode = Number.isSafeInteger(error["code"]) ? error["code"] : src_CX2iR2pK_ProtocolErrorCode.InternalError; + const errorResponse = { + jsonrpc: "2.0", + id: request.id, + error: { + code: codec.encodeErrorCode(thrownCode), + message: error.message ?? "Internal error", + ...error["data"] !== void 0 && { data: error["data"] } + } + }; + await capturedTransport?.send(errorResponse); + }).catch((error) => this._onerror(/* @__PURE__ */ new Error(`Failed to send response: ${error}`))).finally(() => { + if (this._requestHandlerAbortControllers.get(request.id) === abortController) this._requestHandlerAbortControllers.delete(request.id); + }); + } + _onprogress(notification) { + const { progressToken, ...params } = notification.params; + const messageId = Number(progressToken); + const handler = this._progressHandlers.get(messageId); + if (!handler) { + this._onerror(/* @__PURE__ */ new Error(`Received a progress notification for an unknown token: ${JSON.stringify(notification)}`)); + return; + } + const responseHandler = this._responseHandlers.get(messageId); + const timeoutInfo = this._timeoutInfo.get(messageId); + if (timeoutInfo && responseHandler && timeoutInfo.resetTimeoutOnProgress) try { + this._resetTimeout(messageId); + } catch (error) { + this._responseHandlers.delete(messageId); + this._progressHandlers.delete(messageId); + this._cleanupTimeout(messageId); + responseHandler(error); + return; + } + handler(params); + } + /** + * Inbound-response dispatch. Subclass overrides MUST delegate unmatched + * traffic to `super._onresponse(response)` — an override that consumes + * only what it owns and falls through to base dispatch for everything + * else. + */ + _onresponse(response) { + const messageId = Number(response.id); + const handler = this._responseHandlers.get(messageId); + if (handler === void 0) { + this._onerror(/* @__PURE__ */ new Error(`Received a response for an unknown message ID: ${JSON.stringify(response)}`)); + return; + } + this._responseHandlers.delete(messageId); + this._cleanupTimeout(messageId); + this._progressHandlers.delete(messageId); + if (src_CX2iR2pK_isJSONRPCResultResponse(response)) handler(response); + else handler(src_CX2iR2pK_ProtocolError.fromError(response.error.code, response.error.message, response.error.data)); + } + get transport() { + return this._transport; + } + /** + * Closes the connection. + */ + async close() { + await this._transport?.close(); + } + request(request, schemaOrOptions, maybeOptions) { + const codec = this._resolveOutboundCodec(request.method); + this._assertOutboundRequestInEra(codec, request.method); + if (isStandardSchema(schemaOrOptions)) return this._requestWithSchemaViaCodec(codec, request, schemaOrOptions, maybeOptions); + const validate = codecResultValidator(codec, request.method); + if (validate === void 0) throw new TypeError(`'${request.method}' is not a spec method; pass a result schema as the second argument to request().`); + return this._requestWithSchemaViaCodec(codec, request, validate, schemaOrOptions); + } + /** + * The wire codec for this instance's negotiated era — the phase-2 truth: + * everything an established connection sends and receives resolves + * through it. Legacy until a version has been negotiated. + */ + _negotiatedWireCodec() { + return src_CX2iR2pK_codecForVersion(this._negotiatedProtocolVersion); + } + /** + * Protected accessor for the instance's negotiated wire codec, for role + * classes (Client/Server/McpServer) routing era-dependent behavior + * through the codec's function-only surface — `samplingResultVariant`, + * `outboundEnvelope`, `projectCallToolResult` — instead of branching on + * the protocol version themselves. + */ + _wireCodec() { + return this._negotiatedWireCodec(); + } + /** + * Outbound codec resolution: while the negotiated version is still unset + * (the negotiation window), lifecycle messages are bootstrap-pinned BY + * METHOD — they self-identify their era (`initialize` IS the legacy + * handshake, `server/discover` IS the modern probe). Once a version has + * been negotiated, the instance era is authoritative for everything — a + * negotiated session never re-routes a method onto the other era. + */ + _resolveOutboundCodec(method) { + if (this._negotiatedProtocolVersion === void 0) { + const pinned = bootstrapOutboundCodec(method); + if (pinned) return pinned; + } + return this._negotiatedWireCodec(); + } + /** + * Era gate for outbound requests — deletions are physical in BOTH + * directions: sending a spec method that the resolved era does not define + * dies locally with a typed error before anything reaches the transport. + * Methods outside the spec universe are consumer-owned extension methods + * and stay era-blind. + */ + _assertOutboundRequestInEra(codec, method) { + if (isSpecRequestMethod(method) && !codec.hasRequestMethod(method)) throw new src_CX2iR2pK_SdkError(src_CX2iR2pK_SdkErrorCode.MethodNotSupportedByProtocolVersion, `Method '${method}' is not supported by the negotiated protocol version (wire era ${codec.era})`, { + method, + era: codec.era + }); + } + /** + * Sends a request and waits for a response, using the provided schema for + * validation instead of the era registry's method-keyed entry. + * + * This is the internal implementation used by SDK methods whose result + * schema cannot be expressed as a method-keyed registry entry — the one + * surviving case is `server.createMessage`, whose result schema depends + * on the REQUEST params (tools vs no tools) — and by callers passing + * explicit compatibility schemas. Spec methods are still era-gated here: + * an explicit schema never smuggles a deleted method onto the wire. + */ + _requestWithSchema(request, resultSchema, options) { + const codec = this._resolveOutboundCodec(request.method); + this._assertOutboundRequestInEra(codec, request.method); + return this._requestWithSchemaViaCodec(codec, request, resultSchema, options); + } + /** + * The request funnel proper, keyed by the resolved era codec: the codec + * owns result decoding (raw-first `resultType` discrimination — V-1 — + * and the era's lift posture) before the schema validation step. + */ + _requestWithSchemaViaCodec(codec, request, resultSchema, options) { + const { relatedRequestId, resumptionToken, onresumptiontoken, headers } = options ?? {}; + const flowStartedAt = Date.now(); + let onAbort; + let cleanupMessageId; + return new Promise((resolve, reject) => { + const earlyReject = (error) => { + reject(error); + }; + if (!this._transport) { + earlyReject(/* @__PURE__ */ new Error("Not connected")); + return; + } + if (this._options?.enforceStrictCapabilities === true) try { + this.assertCapabilityForMethod(request.method); + } catch (error) { + earlyReject(error); + return; + } + if (options?.signal?.aborted) { + const reason = options.signal.reason; + throw reason instanceof src_CX2iR2pK_SdkError ? reason : new src_CX2iR2pK_SdkError(src_CX2iR2pK_SdkErrorCode.RequestTimeout, String(reason)); + } + const requestAbort = codec.era === src_CX2iR2pK_MODERN_WIRE_REVISION && this._transport.hasPerRequestStream === true ? new AbortController() : void 0; + const messageId = this._requestMessageId++; + cleanupMessageId = messageId; + const jsonrpcRequest = { + ...request, + jsonrpc: "2.0", + id: messageId + }; + if (options?.onprogress) { + this._progressHandlers.set(messageId, options.onprogress); + jsonrpcRequest.params = { + ...request.params, + _meta: { + ...request.params?._meta, + progressToken: messageId + } + }; + } + const outbound = this._envelopeOutbound(jsonrpcRequest); + let responseReceived = false; + const cancel = (reason) => { + if (responseReceived) return; + this._progressHandlers.delete(messageId); + if (requestAbort === void 0) this._transport?.send(this._envelopeOutbound({ + jsonrpc: "2.0", + method: "notifications/cancelled", + params: { + requestId: messageId, + reason: String(reason) + } + }), { + relatedRequestId, + resumptionToken, + onresumptiontoken + }).catch((error) => this._onerror(/* @__PURE__ */ new Error(`Failed to send cancellation: ${error}`))); + else requestAbort.abort(); + reject(reason instanceof src_CX2iR2pK_SdkError ? reason : new src_CX2iR2pK_SdkError(src_CX2iR2pK_SdkErrorCode.RequestTimeout, String(reason))); + }; + this._responseHandlers.set(messageId, (response) => { + if (options?.signal?.aborted) return; + responseReceived = true; + if (response instanceof Error) return reject(response); + let decoded; + try { + decoded = codec.decodeResult(request.method, response.result); + } catch (error) { + return reject(error instanceof Error ? error : new Error(String(error))); + } + if (decoded.kind === "invalid") return reject(decoded.error); + if (decoded.kind === "input_required") { + if (options?.allowInputRequired === true) return resolve(manualInputRequiredValue(decoded)); + const flow = { + codec, + request, + resultSchema, + options, + flowStartedAt, + retry: (params, legOptions) => this._requestWithSchemaViaCodec(codec, params === void 0 ? { method: request.method } : { + method: request.method, + params + }, resultSchema, legOptions) + }; + return resolve(this._resolveNonCompleteResult(decoded, flow)); + } + const result = decoded.result; + validateStandardSchema(resultSchema, result).then((parseResult) => { + if (parseResult.success) resolve(parseResult.data); + else reject(new src_CX2iR2pK_SdkError(src_CX2iR2pK_SdkErrorCode.InvalidResult, `Invalid result for ${request.method}: ${parseResult.error}`)); + }, reject); + }); + onAbort = () => cancel(options?.signal?.reason); + options?.signal?.addEventListener("abort", onAbort, { once: true }); + const timeout = options?.timeout ?? DEFAULT_REQUEST_TIMEOUT_MSEC; + const timeoutHandler = () => cancel(new src_CX2iR2pK_SdkError(src_CX2iR2pK_SdkErrorCode.RequestTimeout, "Request timed out", { timeout })); + this._setupTimeout(messageId, timeout, options?.maxTotalTimeout, timeoutHandler, options?.resetTimeoutOnProgress ?? false); + this._transport.send(outbound, { + relatedRequestId, + resumptionToken, + onresumptiontoken, + headers, + requestSignal: requestAbort?.signal + }).catch((error) => { + this._progressHandlers.delete(messageId); + reject(error); + }); + }).finally(() => { + if (onAbort) options?.signal?.removeEventListener("abort", onAbort); + if (cleanupMessageId !== void 0) { + this._responseHandlers.delete(cleanupMessageId); + this._cleanupTimeout(cleanupMessageId); + } + }); + } + /** + * Emits a notification, which is a one-way message that does not expect a response. + */ + async notification(notification, options) { + return this._notificationViaCodec(this._resolveOutboundCodec(notification.method), notification, options); + } + /** + * The notification funnel proper, keyed by the resolved era codec — + * direct sends and related notifications (`ctx.mcpReq.notify`) alike + * resolve through the instance's negotiated era at send time. + */ + async _notificationViaCodec(codec, notification, options) { + if (!this._transport) throw new src_CX2iR2pK_SdkError(src_CX2iR2pK_SdkErrorCode.NotConnected, "Not connected"); + if (isSpecNotificationMethod(notification.method) && !codec.hasNotificationMethod(notification.method)) throw new src_CX2iR2pK_SdkError(src_CX2iR2pK_SdkErrorCode.MethodNotSupportedByProtocolVersion, `Notification '${notification.method}' is not supported by the negotiated protocol version (wire era ${codec.era})`, { + method: notification.method, + era: codec.era + }); + this.assertNotificationCapability(notification.method); + const jsonrpcNotification = this._envelopeOutbound({ + jsonrpc: "2.0", + ...notification + }); + if ((this._options?.debouncedNotificationMethods ?? []).includes(notification.method) && !notification.params && !options?.relatedRequestId) { + if (this._pendingDebouncedNotifications.has(notification.method)) return; + this._pendingDebouncedNotifications.add(notification.method); + Promise.resolve().then(() => { + this._pendingDebouncedNotifications.delete(notification.method); + if (!this._transport) return; + this._transport?.send(jsonrpcNotification, options).catch((error) => this._onerror(error)); + }); + return; + } + await this._transport.send(jsonrpcNotification, options); + } + setRequestHandler(method, schemasOrHandler, maybeHandler) { + this.assertRequestHandlerCapability(method); + let stored; + if (typeof schemasOrHandler === "function") { + if (!isSpecRequestMethod(method)) throw new TypeError(`'${method}' is not a spec request method; pass schemas as the second argument to setRequestHandler().`); + stored = (request, ctx) => { + const dispatchCodec = this._negotiatedWireCodec(); + let outcome = dispatchCodec.validateRequest(method, request); + if (!outcome.ok && outcome.reason === "not-in-era") outcome = dispatchCodec.validateInputRequest(method, request); + if (!outcome.ok) { + if (outcome.reason === "not-in-era") throw new src_CX2iR2pK_ProtocolError(src_CX2iR2pK_ProtocolErrorCode.InternalError, `No wire schema for ${method} in the resolved era`); + throw new Error(outcome.message); + } + return Promise.resolve(schemasOrHandler(outcome.value, ctx)); + }; + } else if (maybeHandler) stored = async (request, ctx) => { + const parsed = await validateStandardSchema(schemasOrHandler.params, { ...request.params }); + if (!parsed.success) throw new src_CX2iR2pK_ProtocolError(src_CX2iR2pK_ProtocolErrorCode.InvalidParams, `Invalid params for ${method}: ${parsed.error}`); + return maybeHandler(parsed.data, ctx); + }; + else throw new TypeError("setRequestHandler: handler is required"); + this._requestHandlers.set(method, this._wrapHandler(method, stored)); + } + /** + * Hook for subclasses to wrap a registered request handler with role-specific + * validation or behavior (e.g. `Server` validates `tools/call` results, `Client` + * validates `elicitation/create` mode and result). Runs for both the 2-arg and + * 3-arg registration paths. The default implementation is identity. + * + * Subclasses overriding this hook avoid redeclaring `setRequestHandler`'s overload set. + */ + _wrapHandler(_method, handler) { + return handler; + } + /** + * Hook for subclasses to supply the implementation identity the 2026-era + * encode seam stamps into outbound result `_meta` under + * `io.modelcontextprotocol/serverInfo` (spec PR #3002: servers SHOULD + * identify themselves on every response). The default is `undefined` — no + * stamp. Only `Server` overrides this: the key identifies the software + * producing a response, and the 2025-era codec never stamps anything + * regardless (the never-stamp guarantee). + */ + _outboundServerInfo() {} + /** + * Removes the request handler for the given method. + */ + removeRequestHandler(method) { + this._requestHandlers.delete(method); + } + /** + * Asserts that a request handler has not already been set for the given method, in preparation for a new one being automatically installed. + */ + assertCanSetRequestHandler(method) { + if (this._requestHandlers.has(method)) throw new Error(`A request handler for ${method} already exists, which would be overridden`); + } + setNotificationHandler(method, schemasOrHandler, maybeHandler) { + if (typeof schemasOrHandler === "function") { + if (!isSpecNotificationMethod(method)) throw new TypeError(`'${method}' is not a spec notification method; pass schemas as the second argument to setNotificationHandler().`); + this._notificationHandlers.set(method, (notification, codec) => { + const outcome = codec.validateNotification(method, notification); + if (!outcome.ok) { + if (outcome.reason === "not-in-era") throw new src_CX2iR2pK_ProtocolError(src_CX2iR2pK_ProtocolErrorCode.InternalError, `No wire schema for ${method} in the resolved era`); + throw new Error(outcome.message); + } + return Promise.resolve(schemasOrHandler(outcome.value)); + }); + return; + } + if (!maybeHandler) throw new TypeError("setNotificationHandler: handler is required"); + this._notificationHandlers.set(method, async (notification) => { + const parsed = await validateStandardSchema(schemasOrHandler.params, { ...notification.params }); + if (!parsed.success) throw new src_CX2iR2pK_ProtocolError(src_CX2iR2pK_ProtocolErrorCode.InvalidParams, `Invalid params for notification ${method}: ${parsed.error}`); + await maybeHandler(parsed.data, notification); + }); + } + /** + * Removes the notification handler for the given method. + */ + removeNotificationHandler(method) { + this._notificationHandlers.delete(method); + } +}; +function isPlainObject$1(value) { + return value !== null && typeof value === "object" && !Array.isArray(value); +} +function mergeCapabilities(base, additional) { + const result = { ...base }; + for (const key in additional) { + const k = key; + const addValue = additional[k]; + if (addValue === void 0) continue; + const baseValue = result[k]; + result[k] = isPlainObject$1(baseValue) && isPlainObject$1(addValue) ? { + ...baseValue, + ...addValue + } : addValue; + } + return result; +} + +//#endregion +//#region ../core-internal/src/shared/inputRequiredEngine.ts +function src_CX2iR2pK_isPlainObject(value) { + return typeof value === "object" && value !== null && !Array.isArray(value); +} +/** +* Splits a retried request's `inputResponses` map into the BARE response +* entries the spec defines and everything else. The spec's embedded responses +* are the bare result objects (an `ElicitResult`, `CreateMessageResult`, or +* `ListRootsResult`); a wrapped `{method, result}` envelope (a shape some +* peers emit) is never accepted as a response — its key is recorded so the +* handler can re-issue the corresponding input request. +*/ +function partitionInputResponses(inputResponses) { + const accepted = {}; + const droppedKeys = []; + if (!src_CX2iR2pK_isPlainObject(inputResponses)) return { + accepted, + droppedKeys + }; + for (const [key, entry] of Object.entries(inputResponses)) { + if (!src_CX2iR2pK_isPlainObject(entry) || "method" in entry || "result" in entry) { + droppedKeys.push(key); + continue; + } + accepted[key] = entry; + } + return { + accepted, + droppedKeys + }; +} +/** +* Builds the manual-mode {@linkcode InputRequiredResult} value from the +* codec's decoded payload — what an `allowInputRequired: true` caller +* receives instead of the auto-fulfilled complete result. +*/ +function manualInputRequiredValue(decoded) { + return { + resultType: "input_required", + inputRequests: decoded.inputRequests, + ...decoded.requestState !== void 0 && { requestState: decoded.requestState } + }; +} + +//#endregion +//#region ../../node_modules/.pnpm/content-type@1.0.5/node_modules/content-type/index.js +/*! +* content-type +* Copyright(c) 2015 Douglas Christopher Wilson +* MIT Licensed +*/ +var require_content_type = /* @__PURE__ */ __commonJSMin(((exports) => { + /** + * RegExp to match *( ";" parameter ) in RFC 7231 sec 3.1.1.1 + * + * parameter = token "=" ( token / quoted-string ) + * token = 1*tchar + * tchar = "!" / "#" / "$" / "%" / "&" / "'" / "*" + * / "+" / "-" / "." / "^" / "_" / "`" / "|" / "~" + * / DIGIT / ALPHA + * ; any VCHAR, except delimiters + * quoted-string = DQUOTE *( qdtext / quoted-pair ) DQUOTE + * qdtext = HTAB / SP / %x21 / %x23-5B / %x5D-7E / obs-text + * obs-text = %x80-FF + * quoted-pair = "\" ( HTAB / SP / VCHAR / obs-text ) + */ + var PARAM_REGEXP = /; *([!#$%&'*+.^_`|~0-9A-Za-z-]+) *= *("(?:[\u000b\u0020\u0021\u0023-\u005b\u005d-\u007e\u0080-\u00ff]|\\[\u000b\u0020-\u00ff])*"|[!#$%&'*+.^_`|~0-9A-Za-z-]+) */g; + /** + * RegExp to match quoted-pair in RFC 7230 sec 3.2.6 + * + * quoted-pair = "\" ( HTAB / SP / VCHAR / obs-text ) + * obs-text = %x80-FF + */ + var QESC_REGEXP = /\\([\u000b\u0020-\u00ff])/g; + /** + * RegExp to match type in RFC 7231 sec 3.1.1.1 + * + * media-type = type "/" subtype + * type = token + * subtype = token + */ + var TYPE_REGEXP = /^[!#$%&'*+.^_`|~0-9A-Za-z-]+\/[!#$%&'*+.^_`|~0-9A-Za-z-]+$/; + exports.parse = parse; + /** + * Parse media type to object. + * + * @param {string|object} string + * @return {Object} + * @public + */ + function parse(string) { + if (!string) throw new TypeError("argument string is required"); + var header = typeof string === "object" ? getcontenttype(string) : string; + if (typeof header !== "string") throw new TypeError("argument string is required to be a string"); + var index = header.indexOf(";"); + var type = index !== -1 ? header.slice(0, index).trim() : header.trim(); + if (!TYPE_REGEXP.test(type)) throw new TypeError("invalid media type"); + var obj = new ContentType(type.toLowerCase()); + if (index !== -1) { + var key; + var match; + var value; + PARAM_REGEXP.lastIndex = index; + while (match = PARAM_REGEXP.exec(header)) { + if (match.index !== index) throw new TypeError("invalid parameter format"); + index += match[0].length; + key = match[1].toLowerCase(); + value = match[2]; + if (value.charCodeAt(0) === 34) { + value = value.slice(1, -1); + if (value.indexOf("\\") !== -1) value = value.replace(QESC_REGEXP, "$1"); + } + obj.parameters[key] = value; + } + if (index !== header.length) throw new TypeError("invalid parameter format"); + } + return obj; + } + /** + * Get content-type from req/res objects. + * + * @param {object} + * @return {Object} + * @private + */ + function getcontenttype(obj) { + var header; + if (typeof obj.getHeader === "function") header = obj.getHeader("content-type"); + else if (typeof obj.headers === "object") header = obj.headers && obj.headers["content-type"]; + if (typeof header !== "string") throw new TypeError("content-type header is missing from object"); + return header; + } + /** + * Class to represent a content type. + * @private + */ + function ContentType(type) { + this.parameters = Object.create(null); + this.type = type; + } +})); + +//#endregion +//#region ../core-internal/src/shared/mediaType.ts +var import_content_type = /* @__PURE__ */ __toESM(require_content_type(), 1); +/** +* Extracts the media type (the lowercased `type/subtype` pair, without +* parameters) from a raw `Content-Type` header value, or `undefined` when the +* header is missing or empty. +* +* Content-Type comparisons must use the parsed media type, never a substring +* search of the raw header: a value like `text/plain; a=application/json` +* contains the substring `application/json` but its media type is +* `text/plain`, and case variants or parameters make naive string comparison +* wrong in both directions. +* +* "Essence" is the WHATWG MIME Sniffing standard's term for the bare +* `type/subtype` pair (https://mimesniff.spec.whatwg.org/#mime-type-essence); +* the Fetch standard's request classification is defined against it +* (https://fetch.spec.whatwg.org/#cors-safelisted-request-header). +* +* Parsing is RFC 9110 (`content-type` package) first. When the parameter +* section is malformed (`application/json;`, `application/json; charset=`), +* browsers and most HTTP stacks still derive the media type from the segment +* before the first `;` — the fallback matches that widely-implemented +* behavior, so a header whose media type is unambiguous is not rejected for +* a sloppy parameter section. +*/ +function src_CX2iR2pK_mediaTypeEssence(header) { + if (!header) return; + try { + return import_content_type.parse(header).type; + } catch { + const essence = (header.split(";", 1)[0] ?? "").trim().toLowerCase(); + if (essence === "" || header.slice(essence.length).includes(",")) return; + return essence; + } +} +/** +* Whether a raw `Content-Type` header value denotes `application/json`. +* Parameters (for example `charset=utf-8`) are allowed and ignored; malformed +* parameter sections do not reject a header whose media type is unambiguously +* `application/json` (see `mediaTypeEssence` for the exact grammar). +*/ +function src_CX2iR2pK_isJsonContentType(header) { + if (header === "application/json") return true; + return src_CX2iR2pK_mediaTypeEssence(header) === "application/json"; +} + +//#endregion +//#region ../core-internal/src/shared/metadataUtils.ts +/** +* Utilities for working with {@linkcode BaseMetadata} objects. +*/ +/** +* Gets the display name for an object with {@linkcode BaseMetadata}. +* For tools, the precedence is: `title` → {@linkcode index.ToolAnnotations | annotations}.`title` → `name` +* For other objects: `title` → `name` +* This implements the spec requirement: "if no title is provided, name should be used for display purposes" +*/ +function getDisplayName(metadata) { + if (metadata.title !== void 0 && metadata.title !== "") return metadata.title; + if ("annotations" in metadata && metadata.annotations?.title) return metadata.annotations.title; + return metadata.name; +} + +//#endregion +//#region ../core-internal/src/shared/stdio.ts +const STDIO_DEFAULT_MAX_BUFFER_SIZE = 10 * 1024 * 1024; +/** +* Buffers a continuous stdio stream into discrete JSON-RPC messages. +*/ +var ReadBuffer = class { + _buffer; + _maxBufferSize; + constructor(options) { + this._maxBufferSize = options?.maxBufferSize ?? STDIO_DEFAULT_MAX_BUFFER_SIZE; + } + append(chunk) { + if ((this._buffer?.length ?? 0) + chunk.length > this._maxBufferSize) { + this.clear(); + throw new Error(`ReadBuffer exceeded maximum size of ${this._maxBufferSize} bytes`); + } + this._buffer = this._buffer ? Buffer.concat([this._buffer, chunk]) : chunk; + } + readMessage() { + while (this._buffer) { + const index = this._buffer.indexOf("\n"); + if (index === -1) return null; + const line = this._buffer.toString("utf8", 0, index).replace(/\r$/, ""); + this._buffer = this._buffer.subarray(index + 1); + try { + return deserializeMessage(line); + } catch (error) { + if (error instanceof SyntaxError) continue; + throw error; + } + } + return null; + } + clear() { + this._buffer = void 0; + } +}; +function deserializeMessage(line) { + return auth_CUe6YdwF_JSONRPCMessageSchema.parse(JSON.parse(line)); +} +function serializeMessage(message) { + return JSON.stringify(message) + "\n"; +} + +//#endregion +//#region ../core-internal/src/shared/toolNameValidation.ts +/** +* Tool name validation utilities according to SEP: Specify Format for Tool Names +* +* Tool names SHOULD be between 1 and 128 characters in length (inclusive). +* Tool names are case-sensitive. +* Allowed characters: uppercase and lowercase ASCII letters (`A-Z`, `a-z`), digits +* (`0-9`), underscore (`_`), dash (`-`), and dot (`.`). +* Tool names SHOULD NOT contain spaces, commas, or other special characters. +* +* @see {@link https://github.com/modelcontextprotocol/modelcontextprotocol/issues/986 | SEP-986: Specify Format for Tool Names} +*/ +/** +* Regular expression for valid tool names according to SEP-986 specification +*/ +const TOOL_NAME_REGEX = /^[A-Za-z0-9._-]{1,128}$/; +/** +* Validates a tool name according to the SEP specification +* @param name - The tool name to validate +* @returns An object containing validation result and any warnings +*/ +function validateToolName(name) { + const warnings = []; + if (name.length === 0) return { + isValid: false, + warnings: ["Tool name cannot be empty"] + }; + if (name.length > 128) return { + isValid: false, + warnings: [`Tool name exceeds maximum length of 128 characters (current: ${name.length})`] + }; + if (name.includes(" ")) warnings.push("Tool name contains spaces, which may cause parsing issues"); + if (name.includes(",")) warnings.push("Tool name contains commas, which may cause parsing issues"); + if (name.startsWith("-") || name.endsWith("-")) warnings.push("Tool name starts or ends with a dash, which may cause parsing issues in some contexts"); + if (name.startsWith(".") || name.endsWith(".")) warnings.push("Tool name starts or ends with a dot, which may cause parsing issues in some contexts"); + if (!TOOL_NAME_REGEX.test(name)) { + const invalidChars = [...name].filter((char) => !/[A-Za-z0-9._-]/.test(char)).filter((char, index, arr) => arr.indexOf(char) === index); + warnings.push(`Tool name contains invalid characters: ${invalidChars.map((c) => `"${c}"`).join(", ")}`, "Allowed characters are: A-Z, a-z, 0-9, underscore (_), dash (-), and dot (.)"); + return { + isValid: false, + warnings + }; + } + return { + isValid: true, + warnings + }; +} +/** +* Issues warnings for non-conforming tool names +* @param name - The tool name that triggered the warnings +* @param warnings - Array of warning messages +*/ +function issueToolNameWarning(name, warnings) { + if (warnings.length > 0) { + console.warn(`Tool name validation warning for "${name}":`); + for (const warning of warnings) console.warn(` - ${warning}`); + console.warn("Tool registration will proceed, but this may cause compatibility issues."); + console.warn("Consider updating the tool name to conform to the MCP tool naming standard."); + console.warn("See SEP: Specify Format for Tool Names (https://github.com/modelcontextprotocol/modelcontextprotocol/issues/986) for more details."); + } +} +/** +* Validates a tool name and issues warnings for non-conforming names +* @param name - The tool name to validate +* @returns `true` if the name is valid, `false` otherwise +*/ +function validateAndWarnToolName(name) { + const result = validateToolName(name); + issueToolNameWarning(name, result.warnings); + return result.isValid; +} + +//#endregion +//#region ../core-internal/src/shared/transport.ts +/** +* Normalizes `HeadersInit` to a plain `Record` for manipulation. +* Handles `Headers` objects, arrays of tuples, and plain objects. +*/ +function normalizeHeaders(headers) { + if (!headers) return {}; + if (headers instanceof Headers) return Object.fromEntries(headers.entries()); + if (Array.isArray(headers)) return Object.fromEntries(headers); + return { ...headers }; +} +/** +* Creates a fetch function that includes base `RequestInit` options. +* This ensures requests inherit settings like credentials, mode, headers, etc. from the base init. +* +* @param baseFetch - The base fetch function to wrap (defaults to global `fetch`) +* @param baseInit - The base `RequestInit` to merge with each request +* @returns A wrapped fetch function that merges base options with call-specific options +*/ +function createFetchWithInit(baseFetch = fetch, baseInit) { + if (!baseInit) return baseFetch; + return async (url, init) => { + return baseFetch(url, { + ...baseInit, + ...init, + headers: init?.headers ? { + ...normalizeHeaders(baseInit.headers), + ...normalizeHeaders(init.headers) + } : baseInit.headers + }); + }; +} + +//#endregion +//#region ../core-internal/src/shared/uriTemplate.ts +const MAX_TEMPLATE_LENGTH = 1e6; +const MAX_VARIABLE_LENGTH = 1e6; +const MAX_TEMPLATE_EXPRESSIONS = 1e4; +const MAX_REGEX_LENGTH = 1e6; +var src_CX2iR2pK_UriTemplate = class UriTemplate { + /** + * Returns true if the given string contains any URI template expressions. + * A template expression is a sequence of characters enclosed in curly braces, + * like `{foo}` or `{?bar}`. + */ + static isTemplate(str) { + return /\{[^}\s]+\}/.test(str); + } + static validateLength(str, max, context) { + if (str.length > max) throw new Error(`${context} exceeds maximum length of ${max} characters (got ${str.length})`); + } + template; + parts; + get variableNames() { + return this.parts.flatMap((part) => typeof part === "string" ? [] : part.names); + } + constructor(template) { + UriTemplate.validateLength(template, MAX_TEMPLATE_LENGTH, "Template"); + this.template = template; + this.parts = this.parse(template); + } + toString() { + return this.template; + } + parse(template) { + const parts = []; + let currentText = ""; + let i = 0; + let expressionCount = 0; + while (i < template.length) if (template[i] === "{") { + if (currentText) { + parts.push(currentText); + currentText = ""; + } + const end = template.indexOf("}", i); + if (end === -1) throw new Error("Unclosed template expression"); + expressionCount++; + if (expressionCount > MAX_TEMPLATE_EXPRESSIONS) throw new Error(`Template contains too many expressions (max ${MAX_TEMPLATE_EXPRESSIONS})`); + const expr = template.slice(i + 1, end); + const operator = this.getOperator(expr); + const exploded = expr.includes("*"); + const names = this.getNames(expr); + const name = names[0]; + for (const name$1 of names) UriTemplate.validateLength(name$1, MAX_VARIABLE_LENGTH, "Variable name"); + parts.push({ + name, + operator, + names, + exploded + }); + i = end + 1; + } else { + currentText += template[i]; + i++; + } + if (currentText) parts.push(currentText); + return parts; + } + getOperator(expr) { + return [ + "+", + "#", + ".", + "/", + "?", + "&" + ].find((op) => expr.startsWith(op)) || ""; + } + getNames(expr) { + const operator = this.getOperator(expr); + return expr.slice(operator.length).split(",").map((name) => name.replace("*", "").trim()).filter((name) => name.length > 0); + } + encodeValue(value, operator) { + UriTemplate.validateLength(value, MAX_VARIABLE_LENGTH, "Variable value"); + if (operator === "+" || operator === "#") return encodeURI(value); + return encodeURIComponent(value); + } + expandPart(part, variables) { + if (part.operator === "?" || part.operator === "&") { + const pairs = part.names.map((name) => { + const value$1 = variables[name]; + if (value$1 === void 0) return ""; + return `${name}=${Array.isArray(value$1) ? value$1.map((v) => this.encodeValue(v, part.operator)).join(",") : this.encodeValue(value$1.toString(), part.operator)}`; + }).filter((pair) => pair.length > 0); + if (pairs.length === 0) return ""; + return (part.operator === "?" ? "?" : "&") + pairs.join("&"); + } + if (part.names.length > 1) { + const values = part.names.map((name) => variables[name]).filter((v) => v !== void 0); + if (values.length === 0) return ""; + return values.map((v) => Array.isArray(v) ? v[0] : v).join(","); + } + const value = variables[part.name]; + if (value === void 0) return ""; + const encoded = (Array.isArray(value) ? value : [value]).map((v) => this.encodeValue(v, part.operator)); + switch (part.operator) { + case "": return encoded.join(","); + case "+": return encoded.join(","); + case "#": return "#" + encoded.join(","); + case ".": return "." + encoded.join("."); + case "/": return "/" + encoded.join("/"); + default: return encoded.join(","); + } + } + expand(variables) { + let result = ""; + let hasQueryParam = false; + for (const part of this.parts) { + if (typeof part === "string") { + result += part; + continue; + } + const expanded = this.expandPart(part, variables); + if (!expanded) continue; + result += (part.operator === "?" || part.operator === "&") && hasQueryParam ? expanded.replace("?", "&") : expanded; + if (part.operator === "?" || part.operator === "&") hasQueryParam = true; + } + return result; + } + escapeRegExp(str) { + return str.replaceAll(/[.*+?^${}()|[\]\\]/g, String.raw`\$&`); + } + partToRegExp(part) { + const patterns = []; + for (const name$1 of part.names) UriTemplate.validateLength(name$1, MAX_VARIABLE_LENGTH, "Variable name"); + if (part.operator === "?" || part.operator === "&") { + for (let i = 0; i < part.names.length; i++) { + const name$1 = part.names[i]; + const prefix = i === 0 ? "\\" + part.operator : "&"; + patterns.push({ + pattern: prefix + this.escapeRegExp(name$1) + "=([^&]+)", + name: name$1 + }); + } + return patterns; + } + let pattern; + const name = part.name; + switch (part.operator) { + case "": + pattern = part.exploded ? "([^/,]+(?:,[^/,]+)*)" : "([^/,]+)"; + break; + case "+": + case "#": + pattern = "(.+)"; + break; + case ".": + pattern = String.raw`\.([^/,]+)`; + break; + case "/": + pattern = "/" + (part.exploded ? "([^/,]+(?:,[^/,]+)*)" : "([^/,]+)"); + break; + default: pattern = "([^/]+)"; + } + patterns.push({ + pattern, + name + }); + return patterns; + } + match(uri) { + UriTemplate.validateLength(uri, MAX_TEMPLATE_LENGTH, "URI"); + let pattern = "^"; + const names = []; + for (const part of this.parts) if (typeof part === "string") pattern += this.escapeRegExp(part); + else { + const patterns = this.partToRegExp(part); + for (const { pattern: partPattern, name } of patterns) { + pattern += partPattern; + names.push({ + name, + exploded: part.exploded + }); + } + } + pattern += "$"; + UriTemplate.validateLength(pattern, MAX_REGEX_LENGTH, "Generated regex pattern"); + const regex = new RegExp(pattern); + const match = uri.match(regex); + if (!match) return null; + const result = {}; + for (const [i, name_] of names.entries()) { + const { name, exploded } = name_; + const value = match[i + 1]; + const cleanName = name.replace("*", ""); + result[cleanName] = exploded && value.includes(",") ? value.split(",") : value; + } + return result; + } +}; + +//#endregion +//#region ../core-internal/src/util/inMemory.ts +/** +* In-memory transport for creating clients and servers that talk to each other within the same process. +* +* Intended for testing and development. For production in-process connections, use +* `StreamableHTTPClientTransport` against a local server URL. +*/ +var src_CX2iR2pK_InMemoryTransport = class InMemoryTransport { + _otherTransport; + _messageQueue = []; + _closed = false; + onclose; + onerror; + onmessage; + sessionId; + /** + * Creates a pair of linked in-memory transports that can communicate with each other. One should be passed to a {@linkcode @modelcontextprotocol/client!client/client.Client | Client} and one to a {@linkcode @modelcontextprotocol/server!server/server.Server | Server}. + */ + static createLinkedPair() { + const clientTransport = new InMemoryTransport(); + const serverTransport = new InMemoryTransport(); + clientTransport._otherTransport = serverTransport; + serverTransport._otherTransport = clientTransport; + return [clientTransport, serverTransport]; + } + async start() { + while (this._messageQueue.length > 0) { + const queuedMessage = this._messageQueue.shift(); + this.onmessage?.(queuedMessage.message, queuedMessage.extra); + } + } + async close() { + if (this._closed) return; + this._closed = true; + const other = this._otherTransport; + this._otherTransport = void 0; + try { + await other?.close(); + } finally { + this.onclose?.(); + } + } + /** + * Sends a message with optional auth info. + * This is useful for testing authentication scenarios. + */ + async send(message, options) { + if (!this._otherTransport) throw new src_CX2iR2pK_SdkError(src_CX2iR2pK_SdkErrorCode.NotConnected, "Not connected"); + if (this._otherTransport.onmessage) this._otherTransport.onmessage(message, { authInfo: options?.authInfo }); + else this._otherTransport._messageQueue.push({ + message, + extra: { authInfo: options?.authInfo } + }); + } +}; + +//#endregion +//#region ../core-internal/src/util/zodCompat.ts +/** +* Zod-specific helpers for the v1-compat raw-shape shorthand on +* `registerTool`/`registerPrompt`. Kept separate from `standardSchema.ts` so +* that file stays library-agnostic per the Standard Schema spec. +*/ +function isZodV4Schema(v) { + return typeof v === "object" && v !== null && "_zod" in v; +} +function looksLikeZodV3(v) { + return typeof v === "object" && v !== null && !("_zod" in v) && "_def" in v && typeof v._def?.typeName === "string"; +} +/** +* Detects a "raw shape" — a plain object whose values are Zod field schemas, +* e.g. `{ name: z.string() }`. Powers the auto-wrap in +* {@linkcode normalizeRawShapeSchema}, which wraps with `z.object()`, so only +* Zod values are supported. +* +* @internal +*/ +function isZodRawShape(obj) { + if (typeof obj !== "object" || obj === null) return false; + if (isStandardSchema(obj)) return false; + const proto = Object.getPrototypeOf(obj); + if (proto !== Object.prototype && proto !== null) return false; + return Object.values(obj).every((v) => isZodV4Schema(v)); +} +/** +* Accepts either a {@linkcode StandardSchemaWithJSON} or a raw Zod shape +* `{ field: z.string() }` and returns a {@linkcode StandardSchemaWithJSON}. +* Raw shapes are wrapped with `z.object()` so the rest of the pipeline sees a +* uniform schema type; already-wrapped schemas pass through unchanged. +* +* @internal +*/ +function normalizeRawShapeSchema(schema) { + if (schema === void 0) return void 0; + if (isZodRawShape(schema)) return schemas_object(schema); + if (typeof schema === "object" && schema !== null && !isStandardSchema(schema) && Object.values(schema).some((v) => looksLikeZodV3(v))) throw new TypeError("Raw-shape inputSchema/outputSchema/argsSchema fields must be Zod v4 schemas. Got a Zod v3 field schema. Import from `zod/v4` (or upgrade your zod import), or wrap with `z.object({...})` yourself."); + if (!isStandardSchema(schema)) throw new TypeError("inputSchema/outputSchema/argsSchema must be a Standard Schema (e.g. z.object({...})) or a raw Zod shape ({ field: z.string() })."); + return schema; +} + +//#endregion +//#region ../core-internal/src/wire/preload.ts +/** +* Explicit warm-up entry for the lazy wire-schema layers. +* +* The per-revision wire schemas are built lazily: each era's schema set sits +* behind a memoized factory (`buildSchemas2025`/`buildSchemas2026`), and the +* registry/codec lookup maps above those factories are memoized the same way. +* That laziness is the right default on process-per-invocation runtimes (CLI +* tools, dev servers), where module evaluation IS startup latency and most +* short-lived processes never validate a message on both eras. +* +* On platforms that bill request CPU but not module evaluation — isolate-based +* edge/serverless runtimes such as Cloudflare Workers — the trade inverts: +* module-scope work runs during isolate warm-up outside any request, while +* lazy construction lands inside the first request's billed (and latency +* budgeted) CPU. `preloadSchemas()` lets deployments on such platforms move +* the one-time construction cost back to module scope by calling it at module +* scope themselves. The packages' own workerd shims already do this, so +* Workers deployments get eager construction automatically. +*/ +/** +* Eagerly builds every lazily-constructed wire-schema layer, so that no later +* validation pays schema-construction cost. +* +* Synchronous and idempotent: every layer is a memo, so the first call does +* all the work and subsequent calls return immediately. Reference identity is +* unaffected — this forces the same memos every lazy consumer pulls through. +* +* Call it at module scope on platforms that bill per-request CPU but not +* module evaluation (isolate-based edge/serverless runtimes), where deferring +* construction would move it into the first request of every fresh isolate: +* +* ```ts +* // from '@modelcontextprotocol/server' or '@modelcontextprotocol/client' — +* // each package bundles its own schema copy, so warm the one(s) you import. +* preloadSchemas(); // module scope — runs during isolate warm-up +* ``` +* +* On Node CLIs and other process-per-invocation runtimes, prefer the lazy +* default — there, module-scope construction is pure added boot latency. +*/ +function preloadSchemas() { + buildSchemas2025(); + buildSchemas2026(); + warmRegistryMaps2025(); + warmInputSchemaMaps2026(); + warmWireResultSchemas2026(); +} + +//#endregion +//#region ../core-internal/src/validators/fromJsonSchema.ts +/** +* Wrap a raw JSON Schema object as a {@linkcode StandardSchemaWithJSON} so it can be +* passed to `registerTool` / `registerPrompt`. Use this when you already have JSON +* Schema (e.g. from TypeBox, or hand-written) and want to register it without going +* through a Standard Schema library. +* +* The callback arguments will be typed `unknown` (raw JSON Schema has no TypeScript +* types attached). Cast at the call site, or use the generic `fromJsonSchema(...)`. +* +* @param schema - A JSON Schema object describing the expected shape +* @param validator - A validator provider. When importing `fromJsonSchema` from +* `@modelcontextprotocol/server` or `@modelcontextprotocol/client`, a runtime-appropriate +* default is provided automatically (AJV on Node.js, CfWorker on edge runtimes). +* +* @example +* ```ts source="./fromJsonSchema.examples.ts#fromJsonSchema_basicUsage" +* const inputSchema = fromJsonSchema<{ name: string }>( +* { type: 'object', properties: { name: { type: 'string' } }, required: ['name'] }, +* validator +* ); +* // Use with server.registerTool('greet', { inputSchema }, handler) +* ``` +*/ +function fromJsonSchema(schema, validator) { + const check = validator.getValidator(schema); + return { "~standard": { + version: 1, + vendor: "mcp", + jsonSchema: { + input: () => schema, + output: () => schema + }, + validate: (data) => { + const result = check(data); + return result.valid ? { value: result.data } : { issues: [{ message: result.errorMessage }] }; + } + } }; +} + +//#endregion + +//# sourceMappingURL=src-CX2iR2pK.mjs.map + + + +//#region ../../node_modules/.pnpm/ajv@8.18.0/node_modules/ajv/dist/compile/codegen/code.js +var require_code$1 = /* @__PURE__ */ __commonJSMin(((exports) => { + Object.defineProperty(exports, "__esModule", { value: true }); + exports.regexpCode = exports.getEsmExportName = exports.getProperty = exports.safeStringify = exports.stringify = exports.strConcat = exports.addCodeArg = exports.str = exports._ = exports.nil = exports._Code = exports.Name = exports.IDENTIFIER = exports._CodeOrName = void 0; + var _CodeOrName = class {}; + exports._CodeOrName = _CodeOrName; + exports.IDENTIFIER = /^[a-z$_][a-z$_0-9]*$/i; + var Name = class extends _CodeOrName { + constructor(s) { + super(); + if (!exports.IDENTIFIER.test(s)) throw new Error("CodeGen: name must be a valid identifier"); + this.str = s; + } + toString() { + return this.str; + } + emptyStr() { + return false; + } + get names() { + return { [this.str]: 1 }; + } + }; + exports.Name = Name; + var _Code = class extends _CodeOrName { + constructor(code) { + super(); + this._items = typeof code === "string" ? [code] : code; + } + toString() { + return this.str; + } + emptyStr() { + if (this._items.length > 1) return false; + const item = this._items[0]; + return item === "" || item === "\"\""; + } + get str() { + var _a; + return (_a = this._str) !== null && _a !== void 0 ? _a : this._str = this._items.reduce((s, c) => `${s}${c}`, ""); + } + get names() { + var _a; + return (_a = this._names) !== null && _a !== void 0 ? _a : this._names = this._items.reduce((names, c) => { + if (c instanceof Name) names[c.str] = (names[c.str] || 0) + 1; + return names; + }, {}); + } + }; + exports._Code = _Code; + exports.nil = new _Code(""); + function _(strs, ...args) { + const code = [strs[0]]; + let i = 0; + while (i < args.length) { + addCodeArg(code, args[i]); + code.push(strs[++i]); + } + return new _Code(code); + } + exports._ = _; + const plus = new _Code("+"); + function str(strs, ...args) { + const expr = [safeStringify(strs[0])]; + let i = 0; + while (i < args.length) { + expr.push(plus); + addCodeArg(expr, args[i]); + expr.push(plus, safeStringify(strs[++i])); + } + optimize(expr); + return new _Code(expr); + } + exports.str = str; + function addCodeArg(code, arg) { + if (arg instanceof _Code) code.push(...arg._items); + else if (arg instanceof Name) code.push(arg); + else code.push(interpolate(arg)); + } + exports.addCodeArg = addCodeArg; + function optimize(expr) { + let i = 1; + while (i < expr.length - 1) { + if (expr[i] === plus) { + const res = mergeExprItems(expr[i - 1], expr[i + 1]); + if (res !== void 0) { + expr.splice(i - 1, 3, res); + continue; + } + expr[i++] = "+"; + } + i++; + } + } + function mergeExprItems(a, b) { + if (b === "\"\"") return a; + if (a === "\"\"") return b; + if (typeof a == "string") { + if (b instanceof Name || a[a.length - 1] !== "\"") return; + if (typeof b != "string") return `${a.slice(0, -1)}${b}"`; + if (b[0] === "\"") return a.slice(0, -1) + b.slice(1); + return; + } + if (typeof b == "string" && b[0] === "\"" && !(a instanceof Name)) return `"${a}${b.slice(1)}`; + } + function strConcat(c1, c2) { + return c2.emptyStr() ? c1 : c1.emptyStr() ? c2 : str`${c1}${c2}`; + } + exports.strConcat = strConcat; + function interpolate(x) { + return typeof x == "number" || typeof x == "boolean" || x === null ? x : safeStringify(Array.isArray(x) ? x.join(",") : x); + } + function stringify(x) { + return new _Code(safeStringify(x)); + } + exports.stringify = stringify; + function safeStringify(x) { + return JSON.stringify(x).replace(/\u2028/g, "\\u2028").replace(/\u2029/g, "\\u2029"); + } + exports.safeStringify = safeStringify; + function getProperty(key) { + return typeof key == "string" && exports.IDENTIFIER.test(key) ? new _Code(`.${key}`) : _`[${key}]`; + } + exports.getProperty = getProperty; + function getEsmExportName(key) { + if (typeof key == "string" && exports.IDENTIFIER.test(key)) return new _Code(`${key}`); + throw new Error(`CodeGen: invalid export name: ${key}, use explicit $id name mapping`); + } + exports.getEsmExportName = getEsmExportName; + function regexpCode(rx) { + return new _Code(rx.toString()); + } + exports.regexpCode = regexpCode; +})); + +//#endregion +//#region ../../node_modules/.pnpm/ajv@8.18.0/node_modules/ajv/dist/compile/codegen/scope.js +var require_scope = /* @__PURE__ */ __commonJSMin(((exports) => { + Object.defineProperty(exports, "__esModule", { value: true }); + exports.ValueScope = exports.ValueScopeName = exports.Scope = exports.varKinds = exports.UsedValueState = void 0; + const code_1 = require_code$1(); + var ValueError = class extends Error { + constructor(name) { + super(`CodeGen: "code" for ${name} not defined`); + this.value = name.value; + } + }; + var UsedValueState; + (function(UsedValueState) { + UsedValueState[UsedValueState["Started"] = 0] = "Started"; + UsedValueState[UsedValueState["Completed"] = 1] = "Completed"; + })(UsedValueState || (exports.UsedValueState = UsedValueState = {})); + exports.varKinds = { + const: new code_1.Name("const"), + let: new code_1.Name("let"), + var: new code_1.Name("var") + }; + var Scope = class { + constructor({ prefixes, parent } = {}) { + this._names = {}; + this._prefixes = prefixes; + this._parent = parent; + } + toName(nameOrPrefix) { + return nameOrPrefix instanceof code_1.Name ? nameOrPrefix : this.name(nameOrPrefix); + } + name(prefix) { + return new code_1.Name(this._newName(prefix)); + } + _newName(prefix) { + const ng = this._names[prefix] || this._nameGroup(prefix); + return `${prefix}${ng.index++}`; + } + _nameGroup(prefix) { + var _a, _b; + if (((_b = (_a = this._parent) === null || _a === void 0 ? void 0 : _a._prefixes) === null || _b === void 0 ? void 0 : _b.has(prefix)) || this._prefixes && !this._prefixes.has(prefix)) throw new Error(`CodeGen: prefix "${prefix}" is not allowed in this scope`); + return this._names[prefix] = { + prefix, + index: 0 + }; + } + }; + exports.Scope = Scope; + var ValueScopeName = class extends code_1.Name { + constructor(prefix, nameStr) { + super(nameStr); + this.prefix = prefix; + } + setValue(value, { property, itemIndex }) { + this.value = value; + this.scopePath = (0, code_1._)`.${new code_1.Name(property)}[${itemIndex}]`; + } + }; + exports.ValueScopeName = ValueScopeName; + const line = (0, code_1._)`\n`; + var ValueScope = class extends Scope { + constructor(opts) { + super(opts); + this._values = {}; + this._scope = opts.scope; + this.opts = { + ...opts, + _n: opts.lines ? line : code_1.nil + }; + } + get() { + return this._scope; + } + name(prefix) { + return new ValueScopeName(prefix, this._newName(prefix)); + } + value(nameOrPrefix, value) { + var _a; + if (value.ref === void 0) throw new Error("CodeGen: ref must be passed in value"); + const name = this.toName(nameOrPrefix); + const { prefix } = name; + const valueKey = (_a = value.key) !== null && _a !== void 0 ? _a : value.ref; + let vs = this._values[prefix]; + if (vs) { + const _name = vs.get(valueKey); + if (_name) return _name; + } else vs = this._values[prefix] = /* @__PURE__ */ new Map(); + vs.set(valueKey, name); + const s = this._scope[prefix] || (this._scope[prefix] = []); + const itemIndex = s.length; + s[itemIndex] = value.ref; + name.setValue(value, { + property: prefix, + itemIndex + }); + return name; + } + getValue(prefix, keyOrRef) { + const vs = this._values[prefix]; + if (!vs) return; + return vs.get(keyOrRef); + } + scopeRefs(scopeName, values = this._values) { + return this._reduceValues(values, (name) => { + if (name.scopePath === void 0) throw new Error(`CodeGen: name "${name}" has no value`); + return (0, code_1._)`${scopeName}${name.scopePath}`; + }); + } + scopeCode(values = this._values, usedValues, getCode) { + return this._reduceValues(values, (name) => { + if (name.value === void 0) throw new Error(`CodeGen: name "${name}" has no value`); + return name.value.code; + }, usedValues, getCode); + } + _reduceValues(values, valueCode, usedValues = {}, getCode) { + let code = code_1.nil; + for (const prefix in values) { + const vs = values[prefix]; + if (!vs) continue; + const nameSet = usedValues[prefix] = usedValues[prefix] || /* @__PURE__ */ new Map(); + vs.forEach((name) => { + if (nameSet.has(name)) return; + nameSet.set(name, UsedValueState.Started); + let c = valueCode(name); + if (c) { + const def = this.opts.es5 ? exports.varKinds.var : exports.varKinds.const; + code = (0, code_1._)`${code}${def} ${name} = ${c};${this.opts._n}`; + } else if (c = getCode === null || getCode === void 0 ? void 0 : getCode(name)) code = (0, code_1._)`${code}${c}${this.opts._n}`; + else throw new ValueError(name); + nameSet.set(name, UsedValueState.Completed); + }); + } + return code; + } + }; + exports.ValueScope = ValueScope; +})); + +//#endregion +//#region ../../node_modules/.pnpm/ajv@8.18.0/node_modules/ajv/dist/compile/codegen/index.js +var require_codegen = /* @__PURE__ */ __commonJSMin(((exports) => { + Object.defineProperty(exports, "__esModule", { value: true }); + exports.or = exports.and = exports.not = exports.CodeGen = exports.operators = exports.varKinds = exports.ValueScopeName = exports.ValueScope = exports.Scope = exports.Name = exports.regexpCode = exports.stringify = exports.getProperty = exports.nil = exports.strConcat = exports.str = exports._ = void 0; + const code_1 = require_code$1(); + const scope_1 = require_scope(); + var code_2 = require_code$1(); + Object.defineProperty(exports, "_", { + enumerable: true, + get: function() { + return code_2._; + } + }); + Object.defineProperty(exports, "str", { + enumerable: true, + get: function() { + return code_2.str; + } + }); + Object.defineProperty(exports, "strConcat", { + enumerable: true, + get: function() { + return code_2.strConcat; + } + }); + Object.defineProperty(exports, "nil", { + enumerable: true, + get: function() { + return code_2.nil; + } + }); + Object.defineProperty(exports, "getProperty", { + enumerable: true, + get: function() { + return code_2.getProperty; + } + }); + Object.defineProperty(exports, "stringify", { + enumerable: true, + get: function() { + return code_2.stringify; + } + }); + Object.defineProperty(exports, "regexpCode", { + enumerable: true, + get: function() { + return code_2.regexpCode; + } + }); + Object.defineProperty(exports, "Name", { + enumerable: true, + get: function() { + return code_2.Name; + } + }); + var scope_2 = require_scope(); + Object.defineProperty(exports, "Scope", { + enumerable: true, + get: function() { + return scope_2.Scope; + } + }); + Object.defineProperty(exports, "ValueScope", { + enumerable: true, + get: function() { + return scope_2.ValueScope; + } + }); + Object.defineProperty(exports, "ValueScopeName", { + enumerable: true, + get: function() { + return scope_2.ValueScopeName; + } + }); + Object.defineProperty(exports, "varKinds", { + enumerable: true, + get: function() { + return scope_2.varKinds; + } + }); + exports.operators = { + GT: new code_1._Code(">"), + GTE: new code_1._Code(">="), + LT: new code_1._Code("<"), + LTE: new code_1._Code("<="), + EQ: new code_1._Code("==="), + NEQ: new code_1._Code("!=="), + NOT: new code_1._Code("!"), + OR: new code_1._Code("||"), + AND: new code_1._Code("&&"), + ADD: new code_1._Code("+") + }; + var Node = class { + optimizeNodes() { + return this; + } + optimizeNames(_names, _constants) { + return this; + } + }; + var Def = class extends Node { + constructor(varKind, name, rhs) { + super(); + this.varKind = varKind; + this.name = name; + this.rhs = rhs; + } + render({ es5, _n }) { + const varKind = es5 ? scope_1.varKinds.var : this.varKind; + const rhs = this.rhs === void 0 ? "" : ` = ${this.rhs}`; + return `${varKind} ${this.name}${rhs};` + _n; + } + optimizeNames(names, constants) { + if (!names[this.name.str]) return; + if (this.rhs) this.rhs = optimizeExpr(this.rhs, names, constants); + return this; + } + get names() { + return this.rhs instanceof code_1._CodeOrName ? this.rhs.names : {}; + } + }; + var Assign = class extends Node { + constructor(lhs, rhs, sideEffects) { + super(); + this.lhs = lhs; + this.rhs = rhs; + this.sideEffects = sideEffects; + } + render({ _n }) { + return `${this.lhs} = ${this.rhs};` + _n; + } + optimizeNames(names, constants) { + if (this.lhs instanceof code_1.Name && !names[this.lhs.str] && !this.sideEffects) return; + this.rhs = optimizeExpr(this.rhs, names, constants); + return this; + } + get names() { + return addExprNames(this.lhs instanceof code_1.Name ? {} : { ...this.lhs.names }, this.rhs); + } + }; + var AssignOp = class extends Assign { + constructor(lhs, op, rhs, sideEffects) { + super(lhs, rhs, sideEffects); + this.op = op; + } + render({ _n }) { + return `${this.lhs} ${this.op}= ${this.rhs};` + _n; + } + }; + var Label = class extends Node { + constructor(label) { + super(); + this.label = label; + this.names = {}; + } + render({ _n }) { + return `${this.label}:` + _n; + } + }; + var Break = class extends Node { + constructor(label) { + super(); + this.label = label; + this.names = {}; + } + render({ _n }) { + return `break${this.label ? ` ${this.label}` : ""};` + _n; + } + }; + var Throw = class extends Node { + constructor(error) { + super(); + this.error = error; + } + render({ _n }) { + return `throw ${this.error};` + _n; + } + get names() { + return this.error.names; + } + }; + var AnyCode = class extends Node { + constructor(code) { + super(); + this.code = code; + } + render({ _n }) { + return `${this.code};` + _n; + } + optimizeNodes() { + return `${this.code}` ? this : void 0; + } + optimizeNames(names, constants) { + this.code = optimizeExpr(this.code, names, constants); + return this; + } + get names() { + return this.code instanceof code_1._CodeOrName ? this.code.names : {}; + } + }; + var ParentNode = class extends Node { + constructor(nodes = []) { + super(); + this.nodes = nodes; + } + render(opts) { + return this.nodes.reduce((code, n) => code + n.render(opts), ""); + } + optimizeNodes() { + const { nodes } = this; + let i = nodes.length; + while (i--) { + const n = nodes[i].optimizeNodes(); + if (Array.isArray(n)) nodes.splice(i, 1, ...n); + else if (n) nodes[i] = n; + else nodes.splice(i, 1); + } + return nodes.length > 0 ? this : void 0; + } + optimizeNames(names, constants) { + const { nodes } = this; + let i = nodes.length; + while (i--) { + const n = nodes[i]; + if (n.optimizeNames(names, constants)) continue; + subtractNames(names, n.names); + nodes.splice(i, 1); + } + return nodes.length > 0 ? this : void 0; + } + get names() { + return this.nodes.reduce((names, n) => addNames(names, n.names), {}); + } + }; + var BlockNode = class extends ParentNode { + render(opts) { + return "{" + opts._n + super.render(opts) + "}" + opts._n; + } + }; + var Root = class extends ParentNode {}; + var Else = class extends BlockNode {}; + Else.kind = "else"; + var If = class If extends BlockNode { + constructor(condition, nodes) { + super(nodes); + this.condition = condition; + } + render(opts) { + let code = `if(${this.condition})` + super.render(opts); + if (this.else) code += "else " + this.else.render(opts); + return code; + } + optimizeNodes() { + super.optimizeNodes(); + const cond = this.condition; + if (cond === true) return this.nodes; + let e = this.else; + if (e) { + const ns = e.optimizeNodes(); + e = this.else = Array.isArray(ns) ? new Else(ns) : ns; + } + if (e) { + if (cond === false) return e instanceof If ? e : e.nodes; + if (this.nodes.length) return this; + return new If(not(cond), e instanceof If ? [e] : e.nodes); + } + if (cond === false || !this.nodes.length) return void 0; + return this; + } + optimizeNames(names, constants) { + var _a; + this.else = (_a = this.else) === null || _a === void 0 ? void 0 : _a.optimizeNames(names, constants); + if (!(super.optimizeNames(names, constants) || this.else)) return; + this.condition = optimizeExpr(this.condition, names, constants); + return this; + } + get names() { + const names = super.names; + addExprNames(names, this.condition); + if (this.else) addNames(names, this.else.names); + return names; + } + }; + If.kind = "if"; + var For = class extends BlockNode {}; + For.kind = "for"; + var ForLoop = class extends For { + constructor(iteration) { + super(); + this.iteration = iteration; + } + render(opts) { + return `for(${this.iteration})` + super.render(opts); + } + optimizeNames(names, constants) { + if (!super.optimizeNames(names, constants)) return; + this.iteration = optimizeExpr(this.iteration, names, constants); + return this; + } + get names() { + return addNames(super.names, this.iteration.names); + } + }; + var ForRange = class extends For { + constructor(varKind, name, from, to) { + super(); + this.varKind = varKind; + this.name = name; + this.from = from; + this.to = to; + } + render(opts) { + const varKind = opts.es5 ? scope_1.varKinds.var : this.varKind; + const { name, from, to } = this; + return `for(${varKind} ${name}=${from}; ${name}<${to}; ${name}++)` + super.render(opts); + } + get names() { + return addExprNames(addExprNames(super.names, this.from), this.to); + } + }; + var ForIter = class extends For { + constructor(loop, varKind, name, iterable) { + super(); + this.loop = loop; + this.varKind = varKind; + this.name = name; + this.iterable = iterable; + } + render(opts) { + return `for(${this.varKind} ${this.name} ${this.loop} ${this.iterable})` + super.render(opts); + } + optimizeNames(names, constants) { + if (!super.optimizeNames(names, constants)) return; + this.iterable = optimizeExpr(this.iterable, names, constants); + return this; + } + get names() { + return addNames(super.names, this.iterable.names); + } + }; + var Func = class extends BlockNode { + constructor(name, args, async) { + super(); + this.name = name; + this.args = args; + this.async = async; + } + render(opts) { + return `${this.async ? "async " : ""}function ${this.name}(${this.args})` + super.render(opts); + } + }; + Func.kind = "func"; + var Return = class extends ParentNode { + render(opts) { + return "return " + super.render(opts); + } + }; + Return.kind = "return"; + var Try = class extends BlockNode { + render(opts) { + let code = "try" + super.render(opts); + if (this.catch) code += this.catch.render(opts); + if (this.finally) code += this.finally.render(opts); + return code; + } + optimizeNodes() { + var _a, _b; + super.optimizeNodes(); + (_a = this.catch) === null || _a === void 0 || _a.optimizeNodes(); + (_b = this.finally) === null || _b === void 0 || _b.optimizeNodes(); + return this; + } + optimizeNames(names, constants) { + var _a, _b; + super.optimizeNames(names, constants); + (_a = this.catch) === null || _a === void 0 || _a.optimizeNames(names, constants); + (_b = this.finally) === null || _b === void 0 || _b.optimizeNames(names, constants); + return this; + } + get names() { + const names = super.names; + if (this.catch) addNames(names, this.catch.names); + if (this.finally) addNames(names, this.finally.names); + return names; + } + }; + var Catch = class extends BlockNode { + constructor(error) { + super(); + this.error = error; + } + render(opts) { + return `catch(${this.error})` + super.render(opts); + } + }; + Catch.kind = "catch"; + var Finally = class extends BlockNode { + render(opts) { + return "finally" + super.render(opts); + } + }; + Finally.kind = "finally"; + var CodeGen = class { + constructor(extScope, opts = {}) { + this._values = {}; + this._blockStarts = []; + this._constants = {}; + this.opts = { + ...opts, + _n: opts.lines ? "\n" : "" + }; + this._extScope = extScope; + this._scope = new scope_1.Scope({ parent: extScope }); + this._nodes = [new Root()]; + } + toString() { + return this._root.render(this.opts); + } + name(prefix) { + return this._scope.name(prefix); + } + scopeName(prefix) { + return this._extScope.name(prefix); + } + scopeValue(prefixOrName, value) { + const name = this._extScope.value(prefixOrName, value); + (this._values[name.prefix] || (this._values[name.prefix] = /* @__PURE__ */ new Set())).add(name); + return name; + } + getScopeValue(prefix, keyOrRef) { + return this._extScope.getValue(prefix, keyOrRef); + } + scopeRefs(scopeName) { + return this._extScope.scopeRefs(scopeName, this._values); + } + scopeCode() { + return this._extScope.scopeCode(this._values); + } + _def(varKind, nameOrPrefix, rhs, constant) { + const name = this._scope.toName(nameOrPrefix); + if (rhs !== void 0 && constant) this._constants[name.str] = rhs; + this._leafNode(new Def(varKind, name, rhs)); + return name; + } + const(nameOrPrefix, rhs, _constant) { + return this._def(scope_1.varKinds.const, nameOrPrefix, rhs, _constant); + } + let(nameOrPrefix, rhs, _constant) { + return this._def(scope_1.varKinds.let, nameOrPrefix, rhs, _constant); + } + var(nameOrPrefix, rhs, _constant) { + return this._def(scope_1.varKinds.var, nameOrPrefix, rhs, _constant); + } + assign(lhs, rhs, sideEffects) { + return this._leafNode(new Assign(lhs, rhs, sideEffects)); + } + add(lhs, rhs) { + return this._leafNode(new AssignOp(lhs, exports.operators.ADD, rhs)); + } + code(c) { + if (typeof c == "function") c(); + else if (c !== code_1.nil) this._leafNode(new AnyCode(c)); + return this; + } + object(...keyValues) { + const code = ["{"]; + for (const [key, value] of keyValues) { + if (code.length > 1) code.push(","); + code.push(key); + if (key !== value || this.opts.es5) { + code.push(":"); + (0, code_1.addCodeArg)(code, value); + } + } + code.push("}"); + return new code_1._Code(code); + } + if(condition, thenBody, elseBody) { + this._blockNode(new If(condition)); + if (thenBody && elseBody) this.code(thenBody).else().code(elseBody).endIf(); + else if (thenBody) this.code(thenBody).endIf(); + else if (elseBody) throw new Error("CodeGen: \"else\" body without \"then\" body"); + return this; + } + elseIf(condition) { + return this._elseNode(new If(condition)); + } + else() { + return this._elseNode(new Else()); + } + endIf() { + return this._endBlockNode(If, Else); + } + _for(node, forBody) { + this._blockNode(node); + if (forBody) this.code(forBody).endFor(); + return this; + } + for(iteration, forBody) { + return this._for(new ForLoop(iteration), forBody); + } + forRange(nameOrPrefix, from, to, forBody, varKind = this.opts.es5 ? scope_1.varKinds.var : scope_1.varKinds.let) { + const name = this._scope.toName(nameOrPrefix); + return this._for(new ForRange(varKind, name, from, to), () => forBody(name)); + } + forOf(nameOrPrefix, iterable, forBody, varKind = scope_1.varKinds.const) { + const name = this._scope.toName(nameOrPrefix); + if (this.opts.es5) { + const arr = iterable instanceof code_1.Name ? iterable : this.var("_arr", iterable); + return this.forRange("_i", 0, (0, code_1._)`${arr}.length`, (i) => { + this.var(name, (0, code_1._)`${arr}[${i}]`); + forBody(name); + }); + } + return this._for(new ForIter("of", varKind, name, iterable), () => forBody(name)); + } + forIn(nameOrPrefix, obj, forBody, varKind = this.opts.es5 ? scope_1.varKinds.var : scope_1.varKinds.const) { + if (this.opts.ownProperties) return this.forOf(nameOrPrefix, (0, code_1._)`Object.keys(${obj})`, forBody); + const name = this._scope.toName(nameOrPrefix); + return this._for(new ForIter("in", varKind, name, obj), () => forBody(name)); + } + endFor() { + return this._endBlockNode(For); + } + label(label) { + return this._leafNode(new Label(label)); + } + break(label) { + return this._leafNode(new Break(label)); + } + return(value) { + const node = new Return(); + this._blockNode(node); + this.code(value); + if (node.nodes.length !== 1) throw new Error("CodeGen: \"return\" should have one node"); + return this._endBlockNode(Return); + } + try(tryBody, catchCode, finallyCode) { + if (!catchCode && !finallyCode) throw new Error("CodeGen: \"try\" without \"catch\" and \"finally\""); + const node = new Try(); + this._blockNode(node); + this.code(tryBody); + if (catchCode) { + const error = this.name("e"); + this._currNode = node.catch = new Catch(error); + catchCode(error); + } + if (finallyCode) { + this._currNode = node.finally = new Finally(); + this.code(finallyCode); + } + return this._endBlockNode(Catch, Finally); + } + throw(error) { + return this._leafNode(new Throw(error)); + } + block(body, nodeCount) { + this._blockStarts.push(this._nodes.length); + if (body) this.code(body).endBlock(nodeCount); + return this; + } + endBlock(nodeCount) { + const len = this._blockStarts.pop(); + if (len === void 0) throw new Error("CodeGen: not in self-balancing block"); + const toClose = this._nodes.length - len; + if (toClose < 0 || nodeCount !== void 0 && toClose !== nodeCount) throw new Error(`CodeGen: wrong number of nodes: ${toClose} vs ${nodeCount} expected`); + this._nodes.length = len; + return this; + } + func(name, args = code_1.nil, async, funcBody) { + this._blockNode(new Func(name, args, async)); + if (funcBody) this.code(funcBody).endFunc(); + return this; + } + endFunc() { + return this._endBlockNode(Func); + } + optimize(n = 1) { + while (n-- > 0) { + this._root.optimizeNodes(); + this._root.optimizeNames(this._root.names, this._constants); + } + } + _leafNode(node) { + this._currNode.nodes.push(node); + return this; + } + _blockNode(node) { + this._currNode.nodes.push(node); + this._nodes.push(node); + } + _endBlockNode(N1, N2) { + const n = this._currNode; + if (n instanceof N1 || N2 && n instanceof N2) { + this._nodes.pop(); + return this; + } + throw new Error(`CodeGen: not in block "${N2 ? `${N1.kind}/${N2.kind}` : N1.kind}"`); + } + _elseNode(node) { + const n = this._currNode; + if (!(n instanceof If)) throw new Error("CodeGen: \"else\" without \"if\""); + this._currNode = n.else = node; + return this; + } + get _root() { + return this._nodes[0]; + } + get _currNode() { + const ns = this._nodes; + return ns[ns.length - 1]; + } + set _currNode(node) { + const ns = this._nodes; + ns[ns.length - 1] = node; + } + }; + exports.CodeGen = CodeGen; + function addNames(names, from) { + for (const n in from) names[n] = (names[n] || 0) + (from[n] || 0); + return names; + } + function addExprNames(names, from) { + return from instanceof code_1._CodeOrName ? addNames(names, from.names) : names; + } + function optimizeExpr(expr, names, constants) { + if (expr instanceof code_1.Name) return replaceName(expr); + if (!canOptimize(expr)) return expr; + return new code_1._Code(expr._items.reduce((items, c) => { + if (c instanceof code_1.Name) c = replaceName(c); + if (c instanceof code_1._Code) items.push(...c._items); + else items.push(c); + return items; + }, [])); + function replaceName(n) { + const c = constants[n.str]; + if (c === void 0 || names[n.str] !== 1) return n; + delete names[n.str]; + return c; + } + function canOptimize(e) { + return e instanceof code_1._Code && e._items.some((c) => c instanceof code_1.Name && names[c.str] === 1 && constants[c.str] !== void 0); + } + } + function subtractNames(names, from) { + for (const n in from) names[n] = (names[n] || 0) - (from[n] || 0); + } + function not(x) { + return typeof x == "boolean" || typeof x == "number" || x === null ? !x : (0, code_1._)`!${par(x)}`; + } + exports.not = not; + const andCode = mappend(exports.operators.AND); + function and(...args) { + return args.reduce(andCode); + } + exports.and = and; + const orCode = mappend(exports.operators.OR); + function or(...args) { + return args.reduce(orCode); + } + exports.or = or; + function mappend(op) { + return (x, y) => x === code_1.nil ? y : y === code_1.nil ? x : (0, code_1._)`${par(x)} ${op} ${par(y)}`; + } + function par(x) { + return x instanceof code_1.Name ? x : (0, code_1._)`(${x})`; + } +})); + +//#endregion +//#region ../../node_modules/.pnpm/ajv@8.18.0/node_modules/ajv/dist/compile/util.js +var require_util = /* @__PURE__ */ __commonJSMin(((exports) => { + Object.defineProperty(exports, "__esModule", { value: true }); + exports.checkStrictMode = exports.getErrorPath = exports.Type = exports.useFunc = exports.setEvaluated = exports.evaluatedPropsToName = exports.mergeEvaluated = exports.eachItem = exports.unescapeJsonPointer = exports.escapeJsonPointer = exports.escapeFragment = exports.unescapeFragment = exports.schemaRefOrVal = exports.schemaHasRulesButRef = exports.schemaHasRules = exports.checkUnknownRules = exports.alwaysValidSchema = exports.toHash = void 0; + const codegen_1 = require_codegen(); + const code_1 = require_code$1(); + function toHash(arr) { + const hash = {}; + for (const item of arr) hash[item] = true; + return hash; + } + exports.toHash = toHash; + function alwaysValidSchema(it, schema) { + if (typeof schema == "boolean") return schema; + if (Object.keys(schema).length === 0) return true; + checkUnknownRules(it, schema); + return !schemaHasRules(schema, it.self.RULES.all); + } + exports.alwaysValidSchema = alwaysValidSchema; + function checkUnknownRules(it, schema = it.schema) { + const { opts, self } = it; + if (!opts.strictSchema) return; + if (typeof schema === "boolean") return; + const rules = self.RULES.keywords; + for (const key in schema) if (!rules[key]) checkStrictMode(it, `unknown keyword: "${key}"`); + } + exports.checkUnknownRules = checkUnknownRules; + function schemaHasRules(schema, rules) { + if (typeof schema == "boolean") return !schema; + for (const key in schema) if (rules[key]) return true; + return false; + } + exports.schemaHasRules = schemaHasRules; + function schemaHasRulesButRef(schema, RULES) { + if (typeof schema == "boolean") return !schema; + for (const key in schema) if (key !== "$ref" && RULES.all[key]) return true; + return false; + } + exports.schemaHasRulesButRef = schemaHasRulesButRef; + function schemaRefOrVal({ topSchemaRef, schemaPath }, schema, keyword, $data) { + if (!$data) { + if (typeof schema == "number" || typeof schema == "boolean") return schema; + if (typeof schema == "string") return (0, codegen_1._)`${schema}`; + } + return (0, codegen_1._)`${topSchemaRef}${schemaPath}${(0, codegen_1.getProperty)(keyword)}`; + } + exports.schemaRefOrVal = schemaRefOrVal; + function unescapeFragment(str) { + return unescapeJsonPointer(decodeURIComponent(str)); + } + exports.unescapeFragment = unescapeFragment; + function escapeFragment(str) { + return encodeURIComponent(escapeJsonPointer(str)); + } + exports.escapeFragment = escapeFragment; + function escapeJsonPointer(str) { + if (typeof str == "number") return `${str}`; + return str.replace(/~/g, "~0").replace(/\//g, "~1"); + } + exports.escapeJsonPointer = escapeJsonPointer; + function unescapeJsonPointer(str) { + return str.replace(/~1/g, "/").replace(/~0/g, "~"); + } + exports.unescapeJsonPointer = unescapeJsonPointer; + function eachItem(xs, f) { + if (Array.isArray(xs)) for (const x of xs) f(x); + else f(xs); + } + exports.eachItem = eachItem; + function makeMergeEvaluated({ mergeNames, mergeToName, mergeValues, resultToName }) { + return (gen, from, to, toName) => { + const res = to === void 0 ? from : to instanceof codegen_1.Name ? (from instanceof codegen_1.Name ? mergeNames(gen, from, to) : mergeToName(gen, from, to), to) : from instanceof codegen_1.Name ? (mergeToName(gen, to, from), from) : mergeValues(from, to); + return toName === codegen_1.Name && !(res instanceof codegen_1.Name) ? resultToName(gen, res) : res; + }; + } + exports.mergeEvaluated = { + props: makeMergeEvaluated({ + mergeNames: (gen, from, to) => gen.if((0, codegen_1._)`${to} !== true && ${from} !== undefined`, () => { + gen.if((0, codegen_1._)`${from} === true`, () => gen.assign(to, true), () => gen.assign(to, (0, codegen_1._)`${to} || {}`).code((0, codegen_1._)`Object.assign(${to}, ${from})`)); + }), + mergeToName: (gen, from, to) => gen.if((0, codegen_1._)`${to} !== true`, () => { + if (from === true) gen.assign(to, true); + else { + gen.assign(to, (0, codegen_1._)`${to} || {}`); + setEvaluated(gen, to, from); + } + }), + mergeValues: (from, to) => from === true ? true : { + ...from, + ...to + }, + resultToName: evaluatedPropsToName + }), + items: makeMergeEvaluated({ + mergeNames: (gen, from, to) => gen.if((0, codegen_1._)`${to} !== true && ${from} !== undefined`, () => gen.assign(to, (0, codegen_1._)`${from} === true ? true : ${to} > ${from} ? ${to} : ${from}`)), + mergeToName: (gen, from, to) => gen.if((0, codegen_1._)`${to} !== true`, () => gen.assign(to, from === true ? true : (0, codegen_1._)`${to} > ${from} ? ${to} : ${from}`)), + mergeValues: (from, to) => from === true ? true : Math.max(from, to), + resultToName: (gen, items) => gen.var("items", items) + }) + }; + function evaluatedPropsToName(gen, ps) { + if (ps === true) return gen.var("props", true); + const props = gen.var("props", (0, codegen_1._)`{}`); + if (ps !== void 0) setEvaluated(gen, props, ps); + return props; + } + exports.evaluatedPropsToName = evaluatedPropsToName; + function setEvaluated(gen, props, ps) { + Object.keys(ps).forEach((p) => gen.assign((0, codegen_1._)`${props}${(0, codegen_1.getProperty)(p)}`, true)); + } + exports.setEvaluated = setEvaluated; + const snippets = {}; + function useFunc(gen, f) { + return gen.scopeValue("func", { + ref: f, + code: snippets[f.code] || (snippets[f.code] = new code_1._Code(f.code)) + }); + } + exports.useFunc = useFunc; + var Type; + (function(Type) { + Type[Type["Num"] = 0] = "Num"; + Type[Type["Str"] = 1] = "Str"; + })(Type || (exports.Type = Type = {})); + function getErrorPath(dataProp, dataPropType, jsPropertySyntax) { + if (dataProp instanceof codegen_1.Name) { + const isNumber = dataPropType === Type.Num; + return jsPropertySyntax ? isNumber ? (0, codegen_1._)`"[" + ${dataProp} + "]"` : (0, codegen_1._)`"['" + ${dataProp} + "']"` : isNumber ? (0, codegen_1._)`"/" + ${dataProp}` : (0, codegen_1._)`"/" + ${dataProp}.replace(/~/g, "~0").replace(/\\//g, "~1")`; + } + return jsPropertySyntax ? (0, codegen_1.getProperty)(dataProp).toString() : "/" + escapeJsonPointer(dataProp); + } + exports.getErrorPath = getErrorPath; + function checkStrictMode(it, msg, mode = it.opts.strictSchema) { + if (!mode) return; + msg = `strict mode: ${msg}`; + if (mode === true) throw new Error(msg); + it.self.logger.warn(msg); + } + exports.checkStrictMode = checkStrictMode; +})); + +//#endregion +//#region ../../node_modules/.pnpm/ajv@8.18.0/node_modules/ajv/dist/compile/names.js +var require_names = /* @__PURE__ */ __commonJSMin(((exports) => { + Object.defineProperty(exports, "__esModule", { value: true }); + const codegen_1 = require_codegen(); + const names = { + data: new codegen_1.Name("data"), + valCxt: new codegen_1.Name("valCxt"), + instancePath: new codegen_1.Name("instancePath"), + parentData: new codegen_1.Name("parentData"), + parentDataProperty: new codegen_1.Name("parentDataProperty"), + rootData: new codegen_1.Name("rootData"), + dynamicAnchors: new codegen_1.Name("dynamicAnchors"), + vErrors: new codegen_1.Name("vErrors"), + errors: new codegen_1.Name("errors"), + this: new codegen_1.Name("this"), + self: new codegen_1.Name("self"), + scope: new codegen_1.Name("scope"), + json: new codegen_1.Name("json"), + jsonPos: new codegen_1.Name("jsonPos"), + jsonLen: new codegen_1.Name("jsonLen"), + jsonPart: new codegen_1.Name("jsonPart") + }; + exports.default = names; +})); + +//#endregion +//#region ../../node_modules/.pnpm/ajv@8.18.0/node_modules/ajv/dist/compile/errors.js +var require_errors = /* @__PURE__ */ __commonJSMin(((exports) => { + Object.defineProperty(exports, "__esModule", { value: true }); + exports.extendErrors = exports.resetErrorsCount = exports.reportExtraError = exports.reportError = exports.keyword$DataError = exports.keywordError = void 0; + const codegen_1 = require_codegen(); + const util_1 = require_util(); + const names_1 = require_names(); + exports.keywordError = { message: ({ keyword }) => (0, codegen_1.str)`must pass "${keyword}" keyword validation` }; + exports.keyword$DataError = { message: ({ keyword, schemaType }) => schemaType ? (0, codegen_1.str)`"${keyword}" keyword must be ${schemaType} ($data)` : (0, codegen_1.str)`"${keyword}" keyword is invalid ($data)` }; + function reportError(cxt, error = exports.keywordError, errorPaths, overrideAllErrors) { + const { it } = cxt; + const { gen, compositeRule, allErrors } = it; + const errObj = errorObjectCode(cxt, error, errorPaths); + if (overrideAllErrors !== null && overrideAllErrors !== void 0 ? overrideAllErrors : compositeRule || allErrors) addError(gen, errObj); + else returnErrors(it, (0, codegen_1._)`[${errObj}]`); + } + exports.reportError = reportError; + function reportExtraError(cxt, error = exports.keywordError, errorPaths) { + const { it } = cxt; + const { gen, compositeRule, allErrors } = it; + addError(gen, errorObjectCode(cxt, error, errorPaths)); + if (!(compositeRule || allErrors)) returnErrors(it, names_1.default.vErrors); + } + exports.reportExtraError = reportExtraError; + function resetErrorsCount(gen, errsCount) { + gen.assign(names_1.default.errors, errsCount); + gen.if((0, codegen_1._)`${names_1.default.vErrors} !== null`, () => gen.if(errsCount, () => gen.assign((0, codegen_1._)`${names_1.default.vErrors}.length`, errsCount), () => gen.assign(names_1.default.vErrors, null))); + } + exports.resetErrorsCount = resetErrorsCount; + function extendErrors({ gen, keyword, schemaValue, data, errsCount, it }) { + /* istanbul ignore if */ + if (errsCount === void 0) throw new Error("ajv implementation error"); + const err = gen.name("err"); + gen.forRange("i", errsCount, names_1.default.errors, (i) => { + gen.const(err, (0, codegen_1._)`${names_1.default.vErrors}[${i}]`); + gen.if((0, codegen_1._)`${err}.instancePath === undefined`, () => gen.assign((0, codegen_1._)`${err}.instancePath`, (0, codegen_1.strConcat)(names_1.default.instancePath, it.errorPath))); + gen.assign((0, codegen_1._)`${err}.schemaPath`, (0, codegen_1.str)`${it.errSchemaPath}/${keyword}`); + if (it.opts.verbose) { + gen.assign((0, codegen_1._)`${err}.schema`, schemaValue); + gen.assign((0, codegen_1._)`${err}.data`, data); + } + }); + } + exports.extendErrors = extendErrors; + function addError(gen, errObj) { + const err = gen.const("err", errObj); + gen.if((0, codegen_1._)`${names_1.default.vErrors} === null`, () => gen.assign(names_1.default.vErrors, (0, codegen_1._)`[${err}]`), (0, codegen_1._)`${names_1.default.vErrors}.push(${err})`); + gen.code((0, codegen_1._)`${names_1.default.errors}++`); + } + function returnErrors(it, errs) { + const { gen, validateName, schemaEnv } = it; + if (schemaEnv.$async) gen.throw((0, codegen_1._)`new ${it.ValidationError}(${errs})`); + else { + gen.assign((0, codegen_1._)`${validateName}.errors`, errs); + gen.return(false); + } + } + const E = { + keyword: new codegen_1.Name("keyword"), + schemaPath: new codegen_1.Name("schemaPath"), + params: new codegen_1.Name("params"), + propertyName: new codegen_1.Name("propertyName"), + message: new codegen_1.Name("message"), + schema: new codegen_1.Name("schema"), + parentSchema: new codegen_1.Name("parentSchema") + }; + function errorObjectCode(cxt, error, errorPaths) { + const { createErrors } = cxt.it; + if (createErrors === false) return (0, codegen_1._)`{}`; + return errorObject(cxt, error, errorPaths); + } + function errorObject(cxt, error, errorPaths = {}) { + const { gen, it } = cxt; + const keyValues = [errorInstancePath(it, errorPaths), errorSchemaPath(cxt, errorPaths)]; + extraErrorProps(cxt, error, keyValues); + return gen.object(...keyValues); + } + function errorInstancePath({ errorPath }, { instancePath }) { + const instPath = instancePath ? (0, codegen_1.str)`${errorPath}${(0, util_1.getErrorPath)(instancePath, util_1.Type.Str)}` : errorPath; + return [names_1.default.instancePath, (0, codegen_1.strConcat)(names_1.default.instancePath, instPath)]; + } + function errorSchemaPath({ keyword, it: { errSchemaPath } }, { schemaPath, parentSchema }) { + let schPath = parentSchema ? errSchemaPath : (0, codegen_1.str)`${errSchemaPath}/${keyword}`; + if (schemaPath) schPath = (0, codegen_1.str)`${schPath}${(0, util_1.getErrorPath)(schemaPath, util_1.Type.Str)}`; + return [E.schemaPath, schPath]; + } + function extraErrorProps(cxt, { params, message }, keyValues) { + const { keyword, data, schemaValue, it } = cxt; + const { opts, propertyName, topSchemaRef, schemaPath } = it; + keyValues.push([E.keyword, keyword], [E.params, typeof params == "function" ? params(cxt) : params || (0, codegen_1._)`{}`]); + if (opts.messages) keyValues.push([E.message, typeof message == "function" ? message(cxt) : message]); + if (opts.verbose) keyValues.push([E.schema, schemaValue], [E.parentSchema, (0, codegen_1._)`${topSchemaRef}${schemaPath}`], [names_1.default.data, data]); + if (propertyName) keyValues.push([E.propertyName, propertyName]); + } +})); + +//#endregion +//#region ../../node_modules/.pnpm/ajv@8.18.0/node_modules/ajv/dist/compile/validate/boolSchema.js +var require_boolSchema = /* @__PURE__ */ __commonJSMin(((exports) => { + Object.defineProperty(exports, "__esModule", { value: true }); + exports.boolOrEmptySchema = exports.topBoolOrEmptySchema = void 0; + const errors_1 = require_errors(); + const codegen_1 = require_codegen(); + const names_1 = require_names(); + const boolError = { message: "boolean schema is false" }; + function topBoolOrEmptySchema(it) { + const { gen, schema, validateName } = it; + if (schema === false) falseSchemaError(it, false); + else if (typeof schema == "object" && schema.$async === true) gen.return(names_1.default.data); + else { + gen.assign((0, codegen_1._)`${validateName}.errors`, null); + gen.return(true); + } + } + exports.topBoolOrEmptySchema = topBoolOrEmptySchema; + function boolOrEmptySchema(it, valid) { + const { gen, schema } = it; + if (schema === false) { + gen.var(valid, false); + falseSchemaError(it); + } else gen.var(valid, true); + } + exports.boolOrEmptySchema = boolOrEmptySchema; + function falseSchemaError(it, overrideAllErrors) { + const { gen, data } = it; + const cxt = { + gen, + keyword: "false schema", + data, + schema: false, + schemaCode: false, + schemaValue: false, + params: {}, + it + }; + (0, errors_1.reportError)(cxt, boolError, void 0, overrideAllErrors); + } +})); + +//#endregion +//#region ../../node_modules/.pnpm/ajv@8.18.0/node_modules/ajv/dist/compile/rules.js +var require_rules = /* @__PURE__ */ __commonJSMin(((exports) => { + Object.defineProperty(exports, "__esModule", { value: true }); + exports.getRules = exports.isJSONType = void 0; + const jsonTypes = new Set([ + "string", + "number", + "integer", + "boolean", + "null", + "object", + "array" + ]); + function isJSONType(x) { + return typeof x == "string" && jsonTypes.has(x); + } + exports.isJSONType = isJSONType; + function getRules() { + const groups = { + number: { + type: "number", + rules: [] + }, + string: { + type: "string", + rules: [] + }, + array: { + type: "array", + rules: [] + }, + object: { + type: "object", + rules: [] + } + }; + return { + types: { + ...groups, + integer: true, + boolean: true, + null: true + }, + rules: [ + { rules: [] }, + groups.number, + groups.string, + groups.array, + groups.object + ], + post: { rules: [] }, + all: {}, + keywords: {} + }; + } + exports.getRules = getRules; +})); + +//#endregion +//#region ../../node_modules/.pnpm/ajv@8.18.0/node_modules/ajv/dist/compile/validate/applicability.js +var require_applicability = /* @__PURE__ */ __commonJSMin(((exports) => { + Object.defineProperty(exports, "__esModule", { value: true }); + exports.shouldUseRule = exports.shouldUseGroup = exports.schemaHasRulesForType = void 0; + function schemaHasRulesForType({ schema, self }, type) { + const group = self.RULES.types[type]; + return group && group !== true && shouldUseGroup(schema, group); + } + exports.schemaHasRulesForType = schemaHasRulesForType; + function shouldUseGroup(schema, group) { + return group.rules.some((rule) => shouldUseRule(schema, rule)); + } + exports.shouldUseGroup = shouldUseGroup; + function shouldUseRule(schema, rule) { + var _a; + return schema[rule.keyword] !== void 0 || ((_a = rule.definition.implements) === null || _a === void 0 ? void 0 : _a.some((kwd) => schema[kwd] !== void 0)); + } + exports.shouldUseRule = shouldUseRule; +})); + +//#endregion +//#region ../../node_modules/.pnpm/ajv@8.18.0/node_modules/ajv/dist/compile/validate/dataType.js +var require_dataType = /* @__PURE__ */ __commonJSMin(((exports) => { + Object.defineProperty(exports, "__esModule", { value: true }); + exports.reportTypeError = exports.checkDataTypes = exports.checkDataType = exports.coerceAndCheckDataType = exports.getJSONTypes = exports.getSchemaTypes = exports.DataType = void 0; + const rules_1 = require_rules(); + const applicability_1 = require_applicability(); + const errors_1 = require_errors(); + const codegen_1 = require_codegen(); + const util_1 = require_util(); + var DataType; + (function(DataType) { + DataType[DataType["Correct"] = 0] = "Correct"; + DataType[DataType["Wrong"] = 1] = "Wrong"; + })(DataType || (exports.DataType = DataType = {})); + function getSchemaTypes(schema) { + const types = getJSONTypes(schema.type); + if (types.includes("null")) { + if (schema.nullable === false) throw new Error("type: null contradicts nullable: false"); + } else { + if (!types.length && schema.nullable !== void 0) throw new Error("\"nullable\" cannot be used without \"type\""); + if (schema.nullable === true) types.push("null"); + } + return types; + } + exports.getSchemaTypes = getSchemaTypes; + function getJSONTypes(ts) { + const types = Array.isArray(ts) ? ts : ts ? [ts] : []; + if (types.every(rules_1.isJSONType)) return types; + throw new Error("type must be JSONType or JSONType[]: " + types.join(",")); + } + exports.getJSONTypes = getJSONTypes; + function coerceAndCheckDataType(it, types) { + const { gen, data, opts } = it; + const coerceTo = coerceToTypes(types, opts.coerceTypes); + const checkTypes = types.length > 0 && !(coerceTo.length === 0 && types.length === 1 && (0, applicability_1.schemaHasRulesForType)(it, types[0])); + if (checkTypes) { + const wrongType = checkDataTypes(types, data, opts.strictNumbers, DataType.Wrong); + gen.if(wrongType, () => { + if (coerceTo.length) coerceData(it, types, coerceTo); + else reportTypeError(it); + }); + } + return checkTypes; + } + exports.coerceAndCheckDataType = coerceAndCheckDataType; + const COERCIBLE = new Set([ + "string", + "number", + "integer", + "boolean", + "null" + ]); + function coerceToTypes(types, coerceTypes) { + return coerceTypes ? types.filter((t) => COERCIBLE.has(t) || coerceTypes === "array" && t === "array") : []; + } + function coerceData(it, types, coerceTo) { + const { gen, data, opts } = it; + const dataType = gen.let("dataType", (0, codegen_1._)`typeof ${data}`); + const coerced = gen.let("coerced", (0, codegen_1._)`undefined`); + if (opts.coerceTypes === "array") gen.if((0, codegen_1._)`${dataType} == 'object' && Array.isArray(${data}) && ${data}.length == 1`, () => gen.assign(data, (0, codegen_1._)`${data}[0]`).assign(dataType, (0, codegen_1._)`typeof ${data}`).if(checkDataTypes(types, data, opts.strictNumbers), () => gen.assign(coerced, data))); + gen.if((0, codegen_1._)`${coerced} !== undefined`); + for (const t of coerceTo) if (COERCIBLE.has(t) || t === "array" && opts.coerceTypes === "array") coerceSpecificType(t); + gen.else(); + reportTypeError(it); + gen.endIf(); + gen.if((0, codegen_1._)`${coerced} !== undefined`, () => { + gen.assign(data, coerced); + assignParentData(it, coerced); + }); + function coerceSpecificType(t) { + switch (t) { + case "string": + gen.elseIf((0, codegen_1._)`${dataType} == "number" || ${dataType} == "boolean"`).assign(coerced, (0, codegen_1._)`"" + ${data}`).elseIf((0, codegen_1._)`${data} === null`).assign(coerced, (0, codegen_1._)`""`); + return; + case "number": + gen.elseIf((0, codegen_1._)`${dataType} == "boolean" || ${data} === null + || (${dataType} == "string" && ${data} && ${data} == +${data})`).assign(coerced, (0, codegen_1._)`+${data}`); + return; + case "integer": + gen.elseIf((0, codegen_1._)`${dataType} === "boolean" || ${data} === null + || (${dataType} === "string" && ${data} && ${data} == +${data} && !(${data} % 1))`).assign(coerced, (0, codegen_1._)`+${data}`); + return; + case "boolean": + gen.elseIf((0, codegen_1._)`${data} === "false" || ${data} === 0 || ${data} === null`).assign(coerced, false).elseIf((0, codegen_1._)`${data} === "true" || ${data} === 1`).assign(coerced, true); + return; + case "null": + gen.elseIf((0, codegen_1._)`${data} === "" || ${data} === 0 || ${data} === false`); + gen.assign(coerced, null); + return; + case "array": gen.elseIf((0, codegen_1._)`${dataType} === "string" || ${dataType} === "number" + || ${dataType} === "boolean" || ${data} === null`).assign(coerced, (0, codegen_1._)`[${data}]`); + } + } + } + function assignParentData({ gen, parentData, parentDataProperty }, expr) { + gen.if((0, codegen_1._)`${parentData} !== undefined`, () => gen.assign((0, codegen_1._)`${parentData}[${parentDataProperty}]`, expr)); + } + function checkDataType(dataType, data, strictNums, correct = DataType.Correct) { + const EQ = correct === DataType.Correct ? codegen_1.operators.EQ : codegen_1.operators.NEQ; + let cond; + switch (dataType) { + case "null": return (0, codegen_1._)`${data} ${EQ} null`; + case "array": + cond = (0, codegen_1._)`Array.isArray(${data})`; + break; + case "object": + cond = (0, codegen_1._)`${data} && typeof ${data} == "object" && !Array.isArray(${data})`; + break; + case "integer": + cond = numCond((0, codegen_1._)`!(${data} % 1) && !isNaN(${data})`); + break; + case "number": + cond = numCond(); + break; + default: return (0, codegen_1._)`typeof ${data} ${EQ} ${dataType}`; + } + return correct === DataType.Correct ? cond : (0, codegen_1.not)(cond); + function numCond(_cond = codegen_1.nil) { + return (0, codegen_1.and)((0, codegen_1._)`typeof ${data} == "number"`, _cond, strictNums ? (0, codegen_1._)`isFinite(${data})` : codegen_1.nil); + } + } + exports.checkDataType = checkDataType; + function checkDataTypes(dataTypes, data, strictNums, correct) { + if (dataTypes.length === 1) return checkDataType(dataTypes[0], data, strictNums, correct); + let cond; + const types = (0, util_1.toHash)(dataTypes); + if (types.array && types.object) { + const notObj = (0, codegen_1._)`typeof ${data} != "object"`; + cond = types.null ? notObj : (0, codegen_1._)`!${data} || ${notObj}`; + delete types.null; + delete types.array; + delete types.object; + } else cond = codegen_1.nil; + if (types.number) delete types.integer; + for (const t in types) cond = (0, codegen_1.and)(cond, checkDataType(t, data, strictNums, correct)); + return cond; + } + exports.checkDataTypes = checkDataTypes; + const typeError = { + message: ({ schema }) => `must be ${schema}`, + params: ({ schema, schemaValue }) => typeof schema == "string" ? (0, codegen_1._)`{type: ${schema}}` : (0, codegen_1._)`{type: ${schemaValue}}` + }; + function reportTypeError(it) { + const cxt = getTypeErrorContext(it); + (0, errors_1.reportError)(cxt, typeError); + } + exports.reportTypeError = reportTypeError; + function getTypeErrorContext(it) { + const { gen, data, schema } = it; + const schemaCode = (0, util_1.schemaRefOrVal)(it, schema, "type"); + return { + gen, + keyword: "type", + data, + schema: schema.type, + schemaCode, + schemaValue: schemaCode, + parentSchema: schema, + params: {}, + it + }; + } +})); + +//#endregion +//#region ../../node_modules/.pnpm/ajv@8.18.0/node_modules/ajv/dist/compile/validate/defaults.js +var require_defaults = /* @__PURE__ */ __commonJSMin(((exports) => { + Object.defineProperty(exports, "__esModule", { value: true }); + exports.assignDefaults = void 0; + const codegen_1 = require_codegen(); + const util_1 = require_util(); + function assignDefaults(it, ty) { + const { properties, items } = it.schema; + if (ty === "object" && properties) for (const key in properties) assignDefault(it, key, properties[key].default); + else if (ty === "array" && Array.isArray(items)) items.forEach((sch, i) => assignDefault(it, i, sch.default)); + } + exports.assignDefaults = assignDefaults; + function assignDefault(it, prop, defaultValue) { + const { gen, compositeRule, data, opts } = it; + if (defaultValue === void 0) return; + const childData = (0, codegen_1._)`${data}${(0, codegen_1.getProperty)(prop)}`; + if (compositeRule) { + (0, util_1.checkStrictMode)(it, `default is ignored for: ${childData}`); + return; + } + let condition = (0, codegen_1._)`${childData} === undefined`; + if (opts.useDefaults === "empty") condition = (0, codegen_1._)`${condition} || ${childData} === null || ${childData} === ""`; + gen.if(condition, (0, codegen_1._)`${childData} = ${(0, codegen_1.stringify)(defaultValue)}`); + } +})); + +//#endregion +//#region ../../node_modules/.pnpm/ajv@8.18.0/node_modules/ajv/dist/vocabularies/code.js +var require_code = /* @__PURE__ */ __commonJSMin(((exports) => { + Object.defineProperty(exports, "__esModule", { value: true }); + exports.validateUnion = exports.validateArray = exports.usePattern = exports.callValidateCode = exports.schemaProperties = exports.allSchemaProperties = exports.noPropertyInData = exports.propertyInData = exports.isOwnProperty = exports.hasPropFunc = exports.reportMissingProp = exports.checkMissingProp = exports.checkReportMissingProp = void 0; + const codegen_1 = require_codegen(); + const util_1 = require_util(); + const names_1 = require_names(); + const util_2 = require_util(); + function checkReportMissingProp(cxt, prop) { + const { gen, data, it } = cxt; + gen.if(noPropertyInData(gen, data, prop, it.opts.ownProperties), () => { + cxt.setParams({ missingProperty: (0, codegen_1._)`${prop}` }, true); + cxt.error(); + }); + } + exports.checkReportMissingProp = checkReportMissingProp; + function checkMissingProp({ gen, data, it: { opts } }, properties, missing) { + return (0, codegen_1.or)(...properties.map((prop) => (0, codegen_1.and)(noPropertyInData(gen, data, prop, opts.ownProperties), (0, codegen_1._)`${missing} = ${prop}`))); + } + exports.checkMissingProp = checkMissingProp; + function reportMissingProp(cxt, missing) { + cxt.setParams({ missingProperty: missing }, true); + cxt.error(); + } + exports.reportMissingProp = reportMissingProp; + function hasPropFunc(gen) { + return gen.scopeValue("func", { + ref: Object.prototype.hasOwnProperty, + code: (0, codegen_1._)`Object.prototype.hasOwnProperty` + }); + } + exports.hasPropFunc = hasPropFunc; + function isOwnProperty(gen, data, property) { + return (0, codegen_1._)`${hasPropFunc(gen)}.call(${data}, ${property})`; + } + exports.isOwnProperty = isOwnProperty; + function propertyInData(gen, data, property, ownProperties) { + const cond = (0, codegen_1._)`${data}${(0, codegen_1.getProperty)(property)} !== undefined`; + return ownProperties ? (0, codegen_1._)`${cond} && ${isOwnProperty(gen, data, property)}` : cond; + } + exports.propertyInData = propertyInData; + function noPropertyInData(gen, data, property, ownProperties) { + const cond = (0, codegen_1._)`${data}${(0, codegen_1.getProperty)(property)} === undefined`; + return ownProperties ? (0, codegen_1.or)(cond, (0, codegen_1.not)(isOwnProperty(gen, data, property))) : cond; + } + exports.noPropertyInData = noPropertyInData; + function allSchemaProperties(schemaMap) { + return schemaMap ? Object.keys(schemaMap).filter((p) => p !== "__proto__") : []; + } + exports.allSchemaProperties = allSchemaProperties; + function schemaProperties(it, schemaMap) { + return allSchemaProperties(schemaMap).filter((p) => !(0, util_1.alwaysValidSchema)(it, schemaMap[p])); + } + exports.schemaProperties = schemaProperties; + function callValidateCode({ schemaCode, data, it: { gen, topSchemaRef, schemaPath, errorPath }, it }, func, context, passSchema) { + const dataAndSchema = passSchema ? (0, codegen_1._)`${schemaCode}, ${data}, ${topSchemaRef}${schemaPath}` : data; + const valCxt = [ + [names_1.default.instancePath, (0, codegen_1.strConcat)(names_1.default.instancePath, errorPath)], + [names_1.default.parentData, it.parentData], + [names_1.default.parentDataProperty, it.parentDataProperty], + [names_1.default.rootData, names_1.default.rootData] + ]; + if (it.opts.dynamicRef) valCxt.push([names_1.default.dynamicAnchors, names_1.default.dynamicAnchors]); + const args = (0, codegen_1._)`${dataAndSchema}, ${gen.object(...valCxt)}`; + return context !== codegen_1.nil ? (0, codegen_1._)`${func}.call(${context}, ${args})` : (0, codegen_1._)`${func}(${args})`; + } + exports.callValidateCode = callValidateCode; + const newRegExp = (0, codegen_1._)`new RegExp`; + function usePattern({ gen, it: { opts } }, pattern) { + const u = opts.unicodeRegExp ? "u" : ""; + const { regExp } = opts.code; + const rx = regExp(pattern, u); + return gen.scopeValue("pattern", { + key: rx.toString(), + ref: rx, + code: (0, codegen_1._)`${regExp.code === "new RegExp" ? newRegExp : (0, util_2.useFunc)(gen, regExp)}(${pattern}, ${u})` + }); + } + exports.usePattern = usePattern; + function validateArray(cxt) { + const { gen, data, keyword, it } = cxt; + const valid = gen.name("valid"); + if (it.allErrors) { + const validArr = gen.let("valid", true); + validateItems(() => gen.assign(validArr, false)); + return validArr; + } + gen.var(valid, true); + validateItems(() => gen.break()); + return valid; + function validateItems(notValid) { + const len = gen.const("len", (0, codegen_1._)`${data}.length`); + gen.forRange("i", 0, len, (i) => { + cxt.subschema({ + keyword, + dataProp: i, + dataPropType: util_1.Type.Num + }, valid); + gen.if((0, codegen_1.not)(valid), notValid); + }); + } + } + exports.validateArray = validateArray; + function validateUnion(cxt) { + const { gen, schema, keyword, it } = cxt; + /* istanbul ignore if */ + if (!Array.isArray(schema)) throw new Error("ajv implementation error"); + if (schema.some((sch) => (0, util_1.alwaysValidSchema)(it, sch)) && !it.opts.unevaluated) return; + const valid = gen.let("valid", false); + const schValid = gen.name("_valid"); + gen.block(() => schema.forEach((_sch, i) => { + const schCxt = cxt.subschema({ + keyword, + schemaProp: i, + compositeRule: true + }, schValid); + gen.assign(valid, (0, codegen_1._)`${valid} || ${schValid}`); + if (!cxt.mergeValidEvaluated(schCxt, schValid)) gen.if((0, codegen_1.not)(valid)); + })); + cxt.result(valid, () => cxt.reset(), () => cxt.error(true)); + } + exports.validateUnion = validateUnion; +})); + +//#endregion +//#region ../../node_modules/.pnpm/ajv@8.18.0/node_modules/ajv/dist/compile/validate/keyword.js +var require_keyword = /* @__PURE__ */ __commonJSMin(((exports) => { + Object.defineProperty(exports, "__esModule", { value: true }); + exports.validateKeywordUsage = exports.validSchemaType = exports.funcKeywordCode = exports.macroKeywordCode = void 0; + const codegen_1 = require_codegen(); + const names_1 = require_names(); + const code_1 = require_code(); + const errors_1 = require_errors(); + function macroKeywordCode(cxt, def) { + const { gen, keyword, schema, parentSchema, it } = cxt; + const macroSchema = def.macro.call(it.self, schema, parentSchema, it); + const schemaRef = useKeyword(gen, keyword, macroSchema); + if (it.opts.validateSchema !== false) it.self.validateSchema(macroSchema, true); + const valid = gen.name("valid"); + cxt.subschema({ + schema: macroSchema, + schemaPath: codegen_1.nil, + errSchemaPath: `${it.errSchemaPath}/${keyword}`, + topSchemaRef: schemaRef, + compositeRule: true + }, valid); + cxt.pass(valid, () => cxt.error(true)); + } + exports.macroKeywordCode = macroKeywordCode; + function funcKeywordCode(cxt, def) { + var _a; + const { gen, keyword, schema, parentSchema, $data, it } = cxt; + checkAsyncKeyword(it, def); + const validateRef = useKeyword(gen, keyword, !$data && def.compile ? def.compile.call(it.self, schema, parentSchema, it) : def.validate); + const valid = gen.let("valid"); + cxt.block$data(valid, validateKeyword); + cxt.ok((_a = def.valid) !== null && _a !== void 0 ? _a : valid); + function validateKeyword() { + if (def.errors === false) { + assignValid(); + if (def.modifying) modifyData(cxt); + reportErrs(() => cxt.error()); + } else { + const ruleErrs = def.async ? validateAsync() : validateSync(); + if (def.modifying) modifyData(cxt); + reportErrs(() => addErrs(cxt, ruleErrs)); + } + } + function validateAsync() { + const ruleErrs = gen.let("ruleErrs", null); + gen.try(() => assignValid((0, codegen_1._)`await `), (e) => gen.assign(valid, false).if((0, codegen_1._)`${e} instanceof ${it.ValidationError}`, () => gen.assign(ruleErrs, (0, codegen_1._)`${e}.errors`), () => gen.throw(e))); + return ruleErrs; + } + function validateSync() { + const validateErrs = (0, codegen_1._)`${validateRef}.errors`; + gen.assign(validateErrs, null); + assignValid(codegen_1.nil); + return validateErrs; + } + function assignValid(_await = def.async ? (0, codegen_1._)`await ` : codegen_1.nil) { + const passCxt = it.opts.passContext ? names_1.default.this : names_1.default.self; + const passSchema = !("compile" in def && !$data || def.schema === false); + gen.assign(valid, (0, codegen_1._)`${_await}${(0, code_1.callValidateCode)(cxt, validateRef, passCxt, passSchema)}`, def.modifying); + } + function reportErrs(errors) { + var _a$1; + gen.if((0, codegen_1.not)((_a$1 = def.valid) !== null && _a$1 !== void 0 ? _a$1 : valid), errors); + } + } + exports.funcKeywordCode = funcKeywordCode; + function modifyData(cxt) { + const { gen, data, it } = cxt; + gen.if(it.parentData, () => gen.assign(data, (0, codegen_1._)`${it.parentData}[${it.parentDataProperty}]`)); + } + function addErrs(cxt, errs) { + const { gen } = cxt; + gen.if((0, codegen_1._)`Array.isArray(${errs})`, () => { + gen.assign(names_1.default.vErrors, (0, codegen_1._)`${names_1.default.vErrors} === null ? ${errs} : ${names_1.default.vErrors}.concat(${errs})`).assign(names_1.default.errors, (0, codegen_1._)`${names_1.default.vErrors}.length`); + (0, errors_1.extendErrors)(cxt); + }, () => cxt.error()); + } + function checkAsyncKeyword({ schemaEnv }, def) { + if (def.async && !schemaEnv.$async) throw new Error("async keyword in sync schema"); + } + function useKeyword(gen, keyword, result) { + if (result === void 0) throw new Error(`keyword "${keyword}" failed to compile`); + return gen.scopeValue("keyword", typeof result == "function" ? { ref: result } : { + ref: result, + code: (0, codegen_1.stringify)(result) + }); + } + function validSchemaType(schema, schemaType, allowUndefined = false) { + return !schemaType.length || schemaType.some((st) => st === "array" ? Array.isArray(schema) : st === "object" ? schema && typeof schema == "object" && !Array.isArray(schema) : typeof schema == st || allowUndefined && typeof schema == "undefined"); + } + exports.validSchemaType = validSchemaType; + function validateKeywordUsage({ schema, opts, self, errSchemaPath }, def, keyword) { + /* istanbul ignore if */ + if (Array.isArray(def.keyword) ? !def.keyword.includes(keyword) : def.keyword !== keyword) throw new Error("ajv implementation error"); + const deps = def.dependencies; + if (deps === null || deps === void 0 ? void 0 : deps.some((kwd) => !Object.prototype.hasOwnProperty.call(schema, kwd))) throw new Error(`parent schema must have dependencies of ${keyword}: ${deps.join(",")}`); + if (def.validateSchema) { + if (!def.validateSchema(schema[keyword])) { + const msg = `keyword "${keyword}" value is invalid at path "${errSchemaPath}": ` + self.errorsText(def.validateSchema.errors); + if (opts.validateSchema === "log") self.logger.error(msg); + else throw new Error(msg); + } + } + } + exports.validateKeywordUsage = validateKeywordUsage; +})); + +//#endregion +//#region ../../node_modules/.pnpm/ajv@8.18.0/node_modules/ajv/dist/compile/validate/subschema.js +var require_subschema = /* @__PURE__ */ __commonJSMin(((exports) => { + Object.defineProperty(exports, "__esModule", { value: true }); + exports.extendSubschemaMode = exports.extendSubschemaData = exports.getSubschema = void 0; + const codegen_1 = require_codegen(); + const util_1 = require_util(); + function getSubschema(it, { keyword, schemaProp, schema, schemaPath, errSchemaPath, topSchemaRef }) { + if (keyword !== void 0 && schema !== void 0) throw new Error("both \"keyword\" and \"schema\" passed, only one allowed"); + if (keyword !== void 0) { + const sch = it.schema[keyword]; + return schemaProp === void 0 ? { + schema: sch, + schemaPath: (0, codegen_1._)`${it.schemaPath}${(0, codegen_1.getProperty)(keyword)}`, + errSchemaPath: `${it.errSchemaPath}/${keyword}` + } : { + schema: sch[schemaProp], + schemaPath: (0, codegen_1._)`${it.schemaPath}${(0, codegen_1.getProperty)(keyword)}${(0, codegen_1.getProperty)(schemaProp)}`, + errSchemaPath: `${it.errSchemaPath}/${keyword}/${(0, util_1.escapeFragment)(schemaProp)}` + }; + } + if (schema !== void 0) { + if (schemaPath === void 0 || errSchemaPath === void 0 || topSchemaRef === void 0) throw new Error("\"schemaPath\", \"errSchemaPath\" and \"topSchemaRef\" are required with \"schema\""); + return { + schema, + schemaPath, + topSchemaRef, + errSchemaPath + }; + } + throw new Error("either \"keyword\" or \"schema\" must be passed"); + } + exports.getSubschema = getSubschema; + function extendSubschemaData(subschema, it, { dataProp, dataPropType: dpType, data, dataTypes, propertyName }) { + if (data !== void 0 && dataProp !== void 0) throw new Error("both \"data\" and \"dataProp\" passed, only one allowed"); + const { gen } = it; + if (dataProp !== void 0) { + const { errorPath, dataPathArr, opts } = it; + dataContextProps(gen.let("data", (0, codegen_1._)`${it.data}${(0, codegen_1.getProperty)(dataProp)}`, true)); + subschema.errorPath = (0, codegen_1.str)`${errorPath}${(0, util_1.getErrorPath)(dataProp, dpType, opts.jsPropertySyntax)}`; + subschema.parentDataProperty = (0, codegen_1._)`${dataProp}`; + subschema.dataPathArr = [...dataPathArr, subschema.parentDataProperty]; + } + if (data !== void 0) { + dataContextProps(data instanceof codegen_1.Name ? data : gen.let("data", data, true)); + if (propertyName !== void 0) subschema.propertyName = propertyName; + } + if (dataTypes) subschema.dataTypes = dataTypes; + function dataContextProps(_nextData) { + subschema.data = _nextData; + subschema.dataLevel = it.dataLevel + 1; + subschema.dataTypes = []; + it.definedProperties = /* @__PURE__ */ new Set(); + subschema.parentData = it.data; + subschema.dataNames = [...it.dataNames, _nextData]; + } + } + exports.extendSubschemaData = extendSubschemaData; + function extendSubschemaMode(subschema, { jtdDiscriminator, jtdMetadata, compositeRule, createErrors, allErrors }) { + if (compositeRule !== void 0) subschema.compositeRule = compositeRule; + if (createErrors !== void 0) subschema.createErrors = createErrors; + if (allErrors !== void 0) subschema.allErrors = allErrors; + subschema.jtdDiscriminator = jtdDiscriminator; + subschema.jtdMetadata = jtdMetadata; + } + exports.extendSubschemaMode = extendSubschemaMode; +})); + +//#endregion +//#region ../../node_modules/.pnpm/fast-deep-equal@3.1.3/node_modules/fast-deep-equal/index.js +var require_fast_deep_equal = /* @__PURE__ */ __commonJSMin(((exports, module) => { + module.exports = function equal(a, b) { + if (a === b) return true; + if (a && b && typeof a == "object" && typeof b == "object") { + if (a.constructor !== b.constructor) return false; + var length, i, keys; + if (Array.isArray(a)) { + length = a.length; + if (length != b.length) return false; + for (i = length; i-- !== 0;) if (!equal(a[i], b[i])) return false; + return true; + } + if (a.constructor === RegExp) return a.source === b.source && a.flags === b.flags; + if (a.valueOf !== Object.prototype.valueOf) return a.valueOf() === b.valueOf(); + if (a.toString !== Object.prototype.toString) return a.toString() === b.toString(); + keys = Object.keys(a); + length = keys.length; + if (length !== Object.keys(b).length) return false; + for (i = length; i-- !== 0;) if (!Object.prototype.hasOwnProperty.call(b, keys[i])) return false; + for (i = length; i-- !== 0;) { + var key = keys[i]; + if (!equal(a[key], b[key])) return false; + } + return true; + } + return a !== a && b !== b; + }; +})); + +//#endregion +//#region ../../node_modules/.pnpm/json-schema-traverse@1.0.0/node_modules/json-schema-traverse/index.js +var require_json_schema_traverse = /* @__PURE__ */ __commonJSMin(((exports, module) => { + var traverse = module.exports = function(schema, opts, cb) { + if (typeof opts == "function") { + cb = opts; + opts = {}; + } + cb = opts.cb || cb; + var pre = typeof cb == "function" ? cb : cb.pre || function() {}; + var post = cb.post || function() {}; + _traverse(opts, pre, post, schema, "", schema); + }; + traverse.keywords = { + additionalItems: true, + items: true, + contains: true, + additionalProperties: true, + propertyNames: true, + not: true, + if: true, + then: true, + else: true + }; + traverse.arrayKeywords = { + items: true, + allOf: true, + anyOf: true, + oneOf: true + }; + traverse.propsKeywords = { + $defs: true, + definitions: true, + properties: true, + patternProperties: true, + dependencies: true + }; + traverse.skipKeywords = { + default: true, + enum: true, + const: true, + required: true, + maximum: true, + minimum: true, + exclusiveMaximum: true, + exclusiveMinimum: true, + multipleOf: true, + maxLength: true, + minLength: true, + pattern: true, + format: true, + maxItems: true, + minItems: true, + uniqueItems: true, + maxProperties: true, + minProperties: true + }; + function _traverse(opts, pre, post, schema, jsonPtr, rootSchema, parentJsonPtr, parentKeyword, parentSchema, keyIndex) { + if (schema && typeof schema == "object" && !Array.isArray(schema)) { + pre(schema, jsonPtr, rootSchema, parentJsonPtr, parentKeyword, parentSchema, keyIndex); + for (var key in schema) { + var sch = schema[key]; + if (Array.isArray(sch)) { + if (key in traverse.arrayKeywords) for (var i = 0; i < sch.length; i++) _traverse(opts, pre, post, sch[i], jsonPtr + "/" + key + "/" + i, rootSchema, jsonPtr, key, schema, i); + } else if (key in traverse.propsKeywords) { + if (sch && typeof sch == "object") for (var prop in sch) _traverse(opts, pre, post, sch[prop], jsonPtr + "/" + key + "/" + escapeJsonPtr(prop), rootSchema, jsonPtr, key, schema, prop); + } else if (key in traverse.keywords || opts.allKeys && !(key in traverse.skipKeywords)) _traverse(opts, pre, post, sch, jsonPtr + "/" + key, rootSchema, jsonPtr, key, schema); + } + post(schema, jsonPtr, rootSchema, parentJsonPtr, parentKeyword, parentSchema, keyIndex); + } + } + function escapeJsonPtr(str) { + return str.replace(/~/g, "~0").replace(/\//g, "~1"); + } +})); + +//#endregion +//#region ../../node_modules/.pnpm/ajv@8.18.0/node_modules/ajv/dist/compile/resolve.js +var require_resolve = /* @__PURE__ */ __commonJSMin(((exports) => { + Object.defineProperty(exports, "__esModule", { value: true }); + exports.getSchemaRefs = exports.resolveUrl = exports.normalizeId = exports._getFullPath = exports.getFullPath = exports.inlineRef = void 0; + const util_1 = require_util(); + const equal = require_fast_deep_equal(); + const traverse = require_json_schema_traverse(); + const SIMPLE_INLINED = new Set([ + "type", + "format", + "pattern", + "maxLength", + "minLength", + "maxProperties", + "minProperties", + "maxItems", + "minItems", + "maximum", + "minimum", + "uniqueItems", + "multipleOf", + "required", + "enum", + "const" + ]); + function inlineRef(schema, limit = true) { + if (typeof schema == "boolean") return true; + if (limit === true) return !hasRef(schema); + if (!limit) return false; + return countKeys(schema) <= limit; + } + exports.inlineRef = inlineRef; + const REF_KEYWORDS = new Set([ + "$ref", + "$recursiveRef", + "$recursiveAnchor", + "$dynamicRef", + "$dynamicAnchor" + ]); + function hasRef(schema) { + for (const key in schema) { + if (REF_KEYWORDS.has(key)) return true; + const sch = schema[key]; + if (Array.isArray(sch) && sch.some(hasRef)) return true; + if (typeof sch == "object" && hasRef(sch)) return true; + } + return false; + } + function countKeys(schema) { + let count = 0; + for (const key in schema) { + if (key === "$ref") return Infinity; + count++; + if (SIMPLE_INLINED.has(key)) continue; + if (typeof schema[key] == "object") (0, util_1.eachItem)(schema[key], (sch) => count += countKeys(sch)); + if (count === Infinity) return Infinity; + } + return count; + } + function getFullPath(resolver, id = "", normalize) { + if (normalize !== false) id = normalizeId(id); + return _getFullPath(resolver, resolver.parse(id)); + } + exports.getFullPath = getFullPath; + function _getFullPath(resolver, p) { + return resolver.serialize(p).split("#")[0] + "#"; + } + exports._getFullPath = _getFullPath; + const TRAILING_SLASH_HASH = /#\/?$/; + function normalizeId(id) { + return id ? id.replace(TRAILING_SLASH_HASH, "") : ""; + } + exports.normalizeId = normalizeId; + function resolveUrl(resolver, baseId, id) { + id = normalizeId(id); + return resolver.resolve(baseId, id); + } + exports.resolveUrl = resolveUrl; + const ANCHOR = /^[a-z_][-a-z0-9._]*$/i; + function getSchemaRefs(schema, baseId) { + if (typeof schema == "boolean") return {}; + const { schemaId, uriResolver } = this.opts; + const schId = normalizeId(schema[schemaId] || baseId); + const baseIds = { "": schId }; + const pathPrefix = getFullPath(uriResolver, schId, false); + const localRefs = {}; + const schemaRefs = /* @__PURE__ */ new Set(); + traverse(schema, { allKeys: true }, (sch, jsonPtr, _, parentJsonPtr) => { + if (parentJsonPtr === void 0) return; + const fullPath = pathPrefix + jsonPtr; + let innerBaseId = baseIds[parentJsonPtr]; + if (typeof sch[schemaId] == "string") innerBaseId = addRef.call(this, sch[schemaId]); + addAnchor.call(this, sch.$anchor); + addAnchor.call(this, sch.$dynamicAnchor); + baseIds[jsonPtr] = innerBaseId; + function addRef(ref) { + const _resolve = this.opts.uriResolver.resolve; + ref = normalizeId(innerBaseId ? _resolve(innerBaseId, ref) : ref); + if (schemaRefs.has(ref)) throw ambiguos(ref); + schemaRefs.add(ref); + let schOrRef = this.refs[ref]; + if (typeof schOrRef == "string") schOrRef = this.refs[schOrRef]; + if (typeof schOrRef == "object") checkAmbiguosRef(sch, schOrRef.schema, ref); + else if (ref !== normalizeId(fullPath)) if (ref[0] === "#") { + checkAmbiguosRef(sch, localRefs[ref], ref); + localRefs[ref] = sch; + } else this.refs[ref] = fullPath; + return ref; + } + function addAnchor(anchor) { + if (typeof anchor == "string") { + if (!ANCHOR.test(anchor)) throw new Error(`invalid anchor "${anchor}"`); + addRef.call(this, `#${anchor}`); + } + } + }); + return localRefs; + function checkAmbiguosRef(sch1, sch2, ref) { + if (sch2 !== void 0 && !equal(sch1, sch2)) throw ambiguos(ref); + } + function ambiguos(ref) { + return /* @__PURE__ */ new Error(`reference "${ref}" resolves to more than one schema`); + } + } + exports.getSchemaRefs = getSchemaRefs; +})); + +//#endregion +//#region ../../node_modules/.pnpm/ajv@8.18.0/node_modules/ajv/dist/compile/validate/index.js +var require_validate = /* @__PURE__ */ __commonJSMin(((exports) => { + Object.defineProperty(exports, "__esModule", { value: true }); + exports.getData = exports.KeywordCxt = exports.validateFunctionCode = void 0; + const boolSchema_1 = require_boolSchema(); + const dataType_1 = require_dataType(); + const applicability_1 = require_applicability(); + const dataType_2 = require_dataType(); + const defaults_1 = require_defaults(); + const keyword_1 = require_keyword(); + const subschema_1 = require_subschema(); + const codegen_1 = require_codegen(); + const names_1 = require_names(); + const resolve_1 = require_resolve(); + const util_1 = require_util(); + const errors_1 = require_errors(); + function validateFunctionCode(it) { + if (isSchemaObj(it)) { + checkKeywords(it); + if (schemaCxtHasRules(it)) { + topSchemaObjCode(it); + return; + } + } + validateFunction(it, () => (0, boolSchema_1.topBoolOrEmptySchema)(it)); + } + exports.validateFunctionCode = validateFunctionCode; + function validateFunction({ gen, validateName, schema, schemaEnv, opts }, body) { + if (opts.code.es5) gen.func(validateName, (0, codegen_1._)`${names_1.default.data}, ${names_1.default.valCxt}`, schemaEnv.$async, () => { + gen.code((0, codegen_1._)`"use strict"; ${funcSourceUrl(schema, opts)}`); + destructureValCxtES5(gen, opts); + gen.code(body); + }); + else gen.func(validateName, (0, codegen_1._)`${names_1.default.data}, ${destructureValCxt(opts)}`, schemaEnv.$async, () => gen.code(funcSourceUrl(schema, opts)).code(body)); + } + function destructureValCxt(opts) { + return (0, codegen_1._)`{${names_1.default.instancePath}="", ${names_1.default.parentData}, ${names_1.default.parentDataProperty}, ${names_1.default.rootData}=${names_1.default.data}${opts.dynamicRef ? (0, codegen_1._)`, ${names_1.default.dynamicAnchors}={}` : codegen_1.nil}}={}`; + } + function destructureValCxtES5(gen, opts) { + gen.if(names_1.default.valCxt, () => { + gen.var(names_1.default.instancePath, (0, codegen_1._)`${names_1.default.valCxt}.${names_1.default.instancePath}`); + gen.var(names_1.default.parentData, (0, codegen_1._)`${names_1.default.valCxt}.${names_1.default.parentData}`); + gen.var(names_1.default.parentDataProperty, (0, codegen_1._)`${names_1.default.valCxt}.${names_1.default.parentDataProperty}`); + gen.var(names_1.default.rootData, (0, codegen_1._)`${names_1.default.valCxt}.${names_1.default.rootData}`); + if (opts.dynamicRef) gen.var(names_1.default.dynamicAnchors, (0, codegen_1._)`${names_1.default.valCxt}.${names_1.default.dynamicAnchors}`); + }, () => { + gen.var(names_1.default.instancePath, (0, codegen_1._)`""`); + gen.var(names_1.default.parentData, (0, codegen_1._)`undefined`); + gen.var(names_1.default.parentDataProperty, (0, codegen_1._)`undefined`); + gen.var(names_1.default.rootData, names_1.default.data); + if (opts.dynamicRef) gen.var(names_1.default.dynamicAnchors, (0, codegen_1._)`{}`); + }); + } + function topSchemaObjCode(it) { + const { schema, opts, gen } = it; + validateFunction(it, () => { + if (opts.$comment && schema.$comment) commentKeyword(it); + checkNoDefault(it); + gen.let(names_1.default.vErrors, null); + gen.let(names_1.default.errors, 0); + if (opts.unevaluated) resetEvaluated(it); + typeAndKeywords(it); + returnResults(it); + }); + } + function resetEvaluated(it) { + const { gen, validateName } = it; + it.evaluated = gen.const("evaluated", (0, codegen_1._)`${validateName}.evaluated`); + gen.if((0, codegen_1._)`${it.evaluated}.dynamicProps`, () => gen.assign((0, codegen_1._)`${it.evaluated}.props`, (0, codegen_1._)`undefined`)); + gen.if((0, codegen_1._)`${it.evaluated}.dynamicItems`, () => gen.assign((0, codegen_1._)`${it.evaluated}.items`, (0, codegen_1._)`undefined`)); + } + function funcSourceUrl(schema, opts) { + const schId = typeof schema == "object" && schema[opts.schemaId]; + return schId && (opts.code.source || opts.code.process) ? (0, codegen_1._)`/*# sourceURL=${schId} */` : codegen_1.nil; + } + function subschemaCode(it, valid) { + if (isSchemaObj(it)) { + checkKeywords(it); + if (schemaCxtHasRules(it)) { + subSchemaObjCode(it, valid); + return; + } + } + (0, boolSchema_1.boolOrEmptySchema)(it, valid); + } + function schemaCxtHasRules({ schema, self }) { + if (typeof schema == "boolean") return !schema; + for (const key in schema) if (self.RULES.all[key]) return true; + return false; + } + function isSchemaObj(it) { + return typeof it.schema != "boolean"; + } + function subSchemaObjCode(it, valid) { + const { schema, gen, opts } = it; + if (opts.$comment && schema.$comment) commentKeyword(it); + updateContext(it); + checkAsyncSchema(it); + const errsCount = gen.const("_errs", names_1.default.errors); + typeAndKeywords(it, errsCount); + gen.var(valid, (0, codegen_1._)`${errsCount} === ${names_1.default.errors}`); + } + function checkKeywords(it) { + (0, util_1.checkUnknownRules)(it); + checkRefsAndKeywords(it); + } + function typeAndKeywords(it, errsCount) { + if (it.opts.jtd) return schemaKeywords(it, [], false, errsCount); + const types = (0, dataType_1.getSchemaTypes)(it.schema); + schemaKeywords(it, types, !(0, dataType_1.coerceAndCheckDataType)(it, types), errsCount); + } + function checkRefsAndKeywords(it) { + const { schema, errSchemaPath, opts, self } = it; + if (schema.$ref && opts.ignoreKeywordsWithRef && (0, util_1.schemaHasRulesButRef)(schema, self.RULES)) self.logger.warn(`$ref: keywords ignored in schema at path "${errSchemaPath}"`); + } + function checkNoDefault(it) { + const { schema, opts } = it; + if (schema.default !== void 0 && opts.useDefaults && opts.strictSchema) (0, util_1.checkStrictMode)(it, "default is ignored in the schema root"); + } + function updateContext(it) { + const schId = it.schema[it.opts.schemaId]; + if (schId) it.baseId = (0, resolve_1.resolveUrl)(it.opts.uriResolver, it.baseId, schId); + } + function checkAsyncSchema(it) { + if (it.schema.$async && !it.schemaEnv.$async) throw new Error("async schema in sync schema"); + } + function commentKeyword({ gen, schemaEnv, schema, errSchemaPath, opts }) { + const msg = schema.$comment; + if (opts.$comment === true) gen.code((0, codegen_1._)`${names_1.default.self}.logger.log(${msg})`); + else if (typeof opts.$comment == "function") { + const schemaPath = (0, codegen_1.str)`${errSchemaPath}/$comment`; + const rootName = gen.scopeValue("root", { ref: schemaEnv.root }); + gen.code((0, codegen_1._)`${names_1.default.self}.opts.$comment(${msg}, ${schemaPath}, ${rootName}.schema)`); + } + } + function returnResults(it) { + const { gen, schemaEnv, validateName, ValidationError, opts } = it; + if (schemaEnv.$async) gen.if((0, codegen_1._)`${names_1.default.errors} === 0`, () => gen.return(names_1.default.data), () => gen.throw((0, codegen_1._)`new ${ValidationError}(${names_1.default.vErrors})`)); + else { + gen.assign((0, codegen_1._)`${validateName}.errors`, names_1.default.vErrors); + if (opts.unevaluated) assignEvaluated(it); + gen.return((0, codegen_1._)`${names_1.default.errors} === 0`); + } + } + function assignEvaluated({ gen, evaluated, props, items }) { + if (props instanceof codegen_1.Name) gen.assign((0, codegen_1._)`${evaluated}.props`, props); + if (items instanceof codegen_1.Name) gen.assign((0, codegen_1._)`${evaluated}.items`, items); + } + function schemaKeywords(it, types, typeErrors, errsCount) { + const { gen, schema, data, allErrors, opts, self } = it; + const { RULES } = self; + if (schema.$ref && (opts.ignoreKeywordsWithRef || !(0, util_1.schemaHasRulesButRef)(schema, RULES))) { + gen.block(() => keywordCode(it, "$ref", RULES.all.$ref.definition)); + return; + } + if (!opts.jtd) checkStrictTypes(it, types); + gen.block(() => { + for (const group of RULES.rules) groupKeywords(group); + groupKeywords(RULES.post); + }); + function groupKeywords(group) { + if (!(0, applicability_1.shouldUseGroup)(schema, group)) return; + if (group.type) { + gen.if((0, dataType_2.checkDataType)(group.type, data, opts.strictNumbers)); + iterateKeywords(it, group); + if (types.length === 1 && types[0] === group.type && typeErrors) { + gen.else(); + (0, dataType_2.reportTypeError)(it); + } + gen.endIf(); + } else iterateKeywords(it, group); + if (!allErrors) gen.if((0, codegen_1._)`${names_1.default.errors} === ${errsCount || 0}`); + } + } + function iterateKeywords(it, group) { + const { gen, schema, opts: { useDefaults } } = it; + if (useDefaults) (0, defaults_1.assignDefaults)(it, group.type); + gen.block(() => { + for (const rule of group.rules) if ((0, applicability_1.shouldUseRule)(schema, rule)) keywordCode(it, rule.keyword, rule.definition, group.type); + }); + } + function checkStrictTypes(it, types) { + if (it.schemaEnv.meta || !it.opts.strictTypes) return; + checkContextTypes(it, types); + if (!it.opts.allowUnionTypes) checkMultipleTypes(it, types); + checkKeywordTypes(it, it.dataTypes); + } + function checkContextTypes(it, types) { + if (!types.length) return; + if (!it.dataTypes.length) { + it.dataTypes = types; + return; + } + types.forEach((t) => { + if (!includesType(it.dataTypes, t)) strictTypesError(it, `type "${t}" not allowed by context "${it.dataTypes.join(",")}"`); + }); + narrowSchemaTypes(it, types); + } + function checkMultipleTypes(it, ts) { + if (ts.length > 1 && !(ts.length === 2 && ts.includes("null"))) strictTypesError(it, "use allowUnionTypes to allow union type keyword"); + } + function checkKeywordTypes(it, ts) { + const rules = it.self.RULES.all; + for (const keyword in rules) { + const rule = rules[keyword]; + if (typeof rule == "object" && (0, applicability_1.shouldUseRule)(it.schema, rule)) { + const { type } = rule.definition; + if (type.length && !type.some((t) => hasApplicableType(ts, t))) strictTypesError(it, `missing type "${type.join(",")}" for keyword "${keyword}"`); + } + } + } + function hasApplicableType(schTs, kwdT) { + return schTs.includes(kwdT) || kwdT === "number" && schTs.includes("integer"); + } + function includesType(ts, t) { + return ts.includes(t) || t === "integer" && ts.includes("number"); + } + function narrowSchemaTypes(it, withTypes) { + const ts = []; + for (const t of it.dataTypes) if (includesType(withTypes, t)) ts.push(t); + else if (withTypes.includes("integer") && t === "number") ts.push("integer"); + it.dataTypes = ts; + } + function strictTypesError(it, msg) { + const schemaPath = it.schemaEnv.baseId + it.errSchemaPath; + msg += ` at "${schemaPath}" (strictTypes)`; + (0, util_1.checkStrictMode)(it, msg, it.opts.strictTypes); + } + var KeywordCxt = class { + constructor(it, def, keyword) { + (0, keyword_1.validateKeywordUsage)(it, def, keyword); + this.gen = it.gen; + this.allErrors = it.allErrors; + this.keyword = keyword; + this.data = it.data; + this.schema = it.schema[keyword]; + this.$data = def.$data && it.opts.$data && this.schema && this.schema.$data; + this.schemaValue = (0, util_1.schemaRefOrVal)(it, this.schema, keyword, this.$data); + this.schemaType = def.schemaType; + this.parentSchema = it.schema; + this.params = {}; + this.it = it; + this.def = def; + if (this.$data) this.schemaCode = it.gen.const("vSchema", getData(this.$data, it)); + else { + this.schemaCode = this.schemaValue; + if (!(0, keyword_1.validSchemaType)(this.schema, def.schemaType, def.allowUndefined)) throw new Error(`${keyword} value must be ${JSON.stringify(def.schemaType)}`); + } + if ("code" in def ? def.trackErrors : def.errors !== false) this.errsCount = it.gen.const("_errs", names_1.default.errors); + } + result(condition, successAction, failAction) { + this.failResult((0, codegen_1.not)(condition), successAction, failAction); + } + failResult(condition, successAction, failAction) { + this.gen.if(condition); + if (failAction) failAction(); + else this.error(); + if (successAction) { + this.gen.else(); + successAction(); + if (this.allErrors) this.gen.endIf(); + } else if (this.allErrors) this.gen.endIf(); + else this.gen.else(); + } + pass(condition, failAction) { + this.failResult((0, codegen_1.not)(condition), void 0, failAction); + } + fail(condition) { + if (condition === void 0) { + this.error(); + if (!this.allErrors) this.gen.if(false); + return; + } + this.gen.if(condition); + this.error(); + if (this.allErrors) this.gen.endIf(); + else this.gen.else(); + } + fail$data(condition) { + if (!this.$data) return this.fail(condition); + const { schemaCode } = this; + this.fail((0, codegen_1._)`${schemaCode} !== undefined && (${(0, codegen_1.or)(this.invalid$data(), condition)})`); + } + error(append, errorParams, errorPaths) { + if (errorParams) { + this.setParams(errorParams); + this._error(append, errorPaths); + this.setParams({}); + return; + } + this._error(append, errorPaths); + } + _error(append, errorPaths) { + (append ? errors_1.reportExtraError : errors_1.reportError)(this, this.def.error, errorPaths); + } + $dataError() { + (0, errors_1.reportError)(this, this.def.$dataError || errors_1.keyword$DataError); + } + reset() { + if (this.errsCount === void 0) throw new Error("add \"trackErrors\" to keyword definition"); + (0, errors_1.resetErrorsCount)(this.gen, this.errsCount); + } + ok(cond) { + if (!this.allErrors) this.gen.if(cond); + } + setParams(obj, assign) { + if (assign) Object.assign(this.params, obj); + else this.params = obj; + } + block$data(valid, codeBlock, $dataValid = codegen_1.nil) { + this.gen.block(() => { + this.check$data(valid, $dataValid); + codeBlock(); + }); + } + check$data(valid = codegen_1.nil, $dataValid = codegen_1.nil) { + if (!this.$data) return; + const { gen, schemaCode, schemaType, def } = this; + gen.if((0, codegen_1.or)((0, codegen_1._)`${schemaCode} === undefined`, $dataValid)); + if (valid !== codegen_1.nil) gen.assign(valid, true); + if (schemaType.length || def.validateSchema) { + gen.elseIf(this.invalid$data()); + this.$dataError(); + if (valid !== codegen_1.nil) gen.assign(valid, false); + } + gen.else(); + } + invalid$data() { + const { gen, schemaCode, schemaType, def, it } = this; + return (0, codegen_1.or)(wrong$DataType(), invalid$DataSchema()); + function wrong$DataType() { + if (schemaType.length) { + /* istanbul ignore if */ + if (!(schemaCode instanceof codegen_1.Name)) throw new Error("ajv implementation error"); + const st = Array.isArray(schemaType) ? schemaType : [schemaType]; + return (0, codegen_1._)`${(0, dataType_2.checkDataTypes)(st, schemaCode, it.opts.strictNumbers, dataType_2.DataType.Wrong)}`; + } + return codegen_1.nil; + } + function invalid$DataSchema() { + if (def.validateSchema) { + const validateSchemaRef = gen.scopeValue("validate$data", { ref: def.validateSchema }); + return (0, codegen_1._)`!${validateSchemaRef}(${schemaCode})`; + } + return codegen_1.nil; + } + } + subschema(appl, valid) { + const subschema = (0, subschema_1.getSubschema)(this.it, appl); + (0, subschema_1.extendSubschemaData)(subschema, this.it, appl); + (0, subschema_1.extendSubschemaMode)(subschema, appl); + const nextContext = { + ...this.it, + ...subschema, + items: void 0, + props: void 0 + }; + subschemaCode(nextContext, valid); + return nextContext; + } + mergeEvaluated(schemaCxt, toName) { + const { it, gen } = this; + if (!it.opts.unevaluated) return; + if (it.props !== true && schemaCxt.props !== void 0) it.props = util_1.mergeEvaluated.props(gen, schemaCxt.props, it.props, toName); + if (it.items !== true && schemaCxt.items !== void 0) it.items = util_1.mergeEvaluated.items(gen, schemaCxt.items, it.items, toName); + } + mergeValidEvaluated(schemaCxt, valid) { + const { it, gen } = this; + if (it.opts.unevaluated && (it.props !== true || it.items !== true)) { + gen.if(valid, () => this.mergeEvaluated(schemaCxt, codegen_1.Name)); + return true; + } + } + }; + exports.KeywordCxt = KeywordCxt; + function keywordCode(it, keyword, def, ruleType) { + const cxt = new KeywordCxt(it, def, keyword); + if ("code" in def) def.code(cxt, ruleType); + else if (cxt.$data && def.validate) (0, keyword_1.funcKeywordCode)(cxt, def); + else if ("macro" in def) (0, keyword_1.macroKeywordCode)(cxt, def); + else if (def.compile || def.validate) (0, keyword_1.funcKeywordCode)(cxt, def); + } + const JSON_POINTER = /^\/(?:[^~]|~0|~1)*$/; + const RELATIVE_JSON_POINTER = /^([0-9]+)(#|\/(?:[^~]|~0|~1)*)?$/; + function getData($data, { dataLevel, dataNames, dataPathArr }) { + let jsonPointer; + let data; + if ($data === "") return names_1.default.rootData; + if ($data[0] === "/") { + if (!JSON_POINTER.test($data)) throw new Error(`Invalid JSON-pointer: ${$data}`); + jsonPointer = $data; + data = names_1.default.rootData; + } else { + const matches = RELATIVE_JSON_POINTER.exec($data); + if (!matches) throw new Error(`Invalid JSON-pointer: ${$data}`); + const up = +matches[1]; + jsonPointer = matches[2]; + if (jsonPointer === "#") { + if (up >= dataLevel) throw new Error(errorMsg("property/index", up)); + return dataPathArr[dataLevel - up]; + } + if (up > dataLevel) throw new Error(errorMsg("data", up)); + data = dataNames[dataLevel - up]; + if (!jsonPointer) return data; + } + let expr = data; + const segments = jsonPointer.split("/"); + for (const segment of segments) if (segment) { + data = (0, codegen_1._)`${data}${(0, codegen_1.getProperty)((0, util_1.unescapeJsonPointer)(segment))}`; + expr = (0, codegen_1._)`${expr} && ${data}`; + } + return expr; + function errorMsg(pointerType, up) { + return `Cannot access ${pointerType} ${up} levels up, current level is ${dataLevel}`; + } + } + exports.getData = getData; +})); + +//#endregion +//#region ../../node_modules/.pnpm/ajv@8.18.0/node_modules/ajv/dist/runtime/validation_error.js +var require_validation_error = /* @__PURE__ */ __commonJSMin(((exports) => { + Object.defineProperty(exports, "__esModule", { value: true }); + var ValidationError = class extends Error { + constructor(errors) { + super("validation failed"); + this.errors = errors; + this.ajv = this.validation = true; + } + }; + exports.default = ValidationError; +})); + +//#endregion +//#region ../../node_modules/.pnpm/ajv@8.18.0/node_modules/ajv/dist/compile/ref_error.js +var require_ref_error = /* @__PURE__ */ __commonJSMin(((exports) => { + Object.defineProperty(exports, "__esModule", { value: true }); + const resolve_1 = require_resolve(); + var MissingRefError = class extends Error { + constructor(resolver, baseId, ref, msg) { + super(msg || `can't resolve reference ${ref} from id ${baseId}`); + this.missingRef = (0, resolve_1.resolveUrl)(resolver, baseId, ref); + this.missingSchema = (0, resolve_1.normalizeId)((0, resolve_1.getFullPath)(resolver, this.missingRef)); + } + }; + exports.default = MissingRefError; +})); + +//#endregion +//#region ../../node_modules/.pnpm/ajv@8.18.0/node_modules/ajv/dist/compile/index.js +var require_compile = /* @__PURE__ */ __commonJSMin(((exports) => { + Object.defineProperty(exports, "__esModule", { value: true }); + exports.resolveSchema = exports.getCompilingSchema = exports.resolveRef = exports.compileSchema = exports.SchemaEnv = void 0; + const codegen_1 = require_codegen(); + const validation_error_1 = require_validation_error(); + const names_1 = require_names(); + const resolve_1 = require_resolve(); + const util_1 = require_util(); + const validate_1 = require_validate(); + var SchemaEnv = class { + constructor(env) { + var _a; + this.refs = {}; + this.dynamicAnchors = {}; + let schema; + if (typeof env.schema == "object") schema = env.schema; + this.schema = env.schema; + this.schemaId = env.schemaId; + this.root = env.root || this; + this.baseId = (_a = env.baseId) !== null && _a !== void 0 ? _a : (0, resolve_1.normalizeId)(schema === null || schema === void 0 ? void 0 : schema[env.schemaId || "$id"]); + this.schemaPath = env.schemaPath; + this.localRefs = env.localRefs; + this.meta = env.meta; + this.$async = schema === null || schema === void 0 ? void 0 : schema.$async; + this.refs = {}; + } + }; + exports.SchemaEnv = SchemaEnv; + function compileSchema(sch) { + const _sch = getCompilingSchema.call(this, sch); + if (_sch) return _sch; + const rootId = (0, resolve_1.getFullPath)(this.opts.uriResolver, sch.root.baseId); + const { es5, lines } = this.opts.code; + const { ownProperties } = this.opts; + const gen = new codegen_1.CodeGen(this.scope, { + es5, + lines, + ownProperties + }); + let _ValidationError; + if (sch.$async) _ValidationError = gen.scopeValue("Error", { + ref: validation_error_1.default, + code: (0, codegen_1._)`require("ajv/dist/runtime/validation_error").default` + }); + const validateName = gen.scopeName("validate"); + sch.validateName = validateName; + const schemaCxt = { + gen, + allErrors: this.opts.allErrors, + data: names_1.default.data, + parentData: names_1.default.parentData, + parentDataProperty: names_1.default.parentDataProperty, + dataNames: [names_1.default.data], + dataPathArr: [codegen_1.nil], + dataLevel: 0, + dataTypes: [], + definedProperties: /* @__PURE__ */ new Set(), + topSchemaRef: gen.scopeValue("schema", this.opts.code.source === true ? { + ref: sch.schema, + code: (0, codegen_1.stringify)(sch.schema) + } : { ref: sch.schema }), + validateName, + ValidationError: _ValidationError, + schema: sch.schema, + schemaEnv: sch, + rootId, + baseId: sch.baseId || rootId, + schemaPath: codegen_1.nil, + errSchemaPath: sch.schemaPath || (this.opts.jtd ? "" : "#"), + errorPath: (0, codegen_1._)`""`, + opts: this.opts, + self: this + }; + let sourceCode; + try { + this._compilations.add(sch); + (0, validate_1.validateFunctionCode)(schemaCxt); + gen.optimize(this.opts.code.optimize); + const validateCode = gen.toString(); + sourceCode = `${gen.scopeRefs(names_1.default.scope)}return ${validateCode}`; + if (this.opts.code.process) sourceCode = this.opts.code.process(sourceCode, sch); + const validate = new Function(`${names_1.default.self}`, `${names_1.default.scope}`, sourceCode)(this, this.scope.get()); + this.scope.value(validateName, { ref: validate }); + validate.errors = null; + validate.schema = sch.schema; + validate.schemaEnv = sch; + if (sch.$async) validate.$async = true; + if (this.opts.code.source === true) validate.source = { + validateName, + validateCode, + scopeValues: gen._values + }; + if (this.opts.unevaluated) { + const { props, items } = schemaCxt; + validate.evaluated = { + props: props instanceof codegen_1.Name ? void 0 : props, + items: items instanceof codegen_1.Name ? void 0 : items, + dynamicProps: props instanceof codegen_1.Name, + dynamicItems: items instanceof codegen_1.Name + }; + if (validate.source) validate.source.evaluated = (0, codegen_1.stringify)(validate.evaluated); + } + sch.validate = validate; + return sch; + } catch (e) { + delete sch.validate; + delete sch.validateName; + if (sourceCode) this.logger.error("Error compiling schema, function code:", sourceCode); + throw e; + } finally { + this._compilations.delete(sch); + } + } + exports.compileSchema = compileSchema; + function resolveRef(root, baseId, ref) { + var _a; + ref = (0, resolve_1.resolveUrl)(this.opts.uriResolver, baseId, ref); + const schOrFunc = root.refs[ref]; + if (schOrFunc) return schOrFunc; + let _sch = resolve.call(this, root, ref); + if (_sch === void 0) { + const schema = (_a = root.localRefs) === null || _a === void 0 ? void 0 : _a[ref]; + const { schemaId } = this.opts; + if (schema) _sch = new SchemaEnv({ + schema, + schemaId, + root, + baseId + }); + } + if (_sch === void 0) return; + return root.refs[ref] = inlineOrCompile.call(this, _sch); + } + exports.resolveRef = resolveRef; + function inlineOrCompile(sch) { + if ((0, resolve_1.inlineRef)(sch.schema, this.opts.inlineRefs)) return sch.schema; + return sch.validate ? sch : compileSchema.call(this, sch); + } + function getCompilingSchema(schEnv) { + for (const sch of this._compilations) if (sameSchemaEnv(sch, schEnv)) return sch; + } + exports.getCompilingSchema = getCompilingSchema; + function sameSchemaEnv(s1, s2) { + return s1.schema === s2.schema && s1.root === s2.root && s1.baseId === s2.baseId; + } + function resolve(root, ref) { + let sch; + while (typeof (sch = this.refs[ref]) == "string") ref = sch; + return sch || this.schemas[ref] || resolveSchema.call(this, root, ref); + } + function resolveSchema(root, ref) { + const p = this.opts.uriResolver.parse(ref); + const refPath = (0, resolve_1._getFullPath)(this.opts.uriResolver, p); + let baseId = (0, resolve_1.getFullPath)(this.opts.uriResolver, root.baseId, void 0); + if (Object.keys(root.schema).length > 0 && refPath === baseId) return getJsonPointer.call(this, p, root); + const id = (0, resolve_1.normalizeId)(refPath); + const schOrRef = this.refs[id] || this.schemas[id]; + if (typeof schOrRef == "string") { + const sch = resolveSchema.call(this, root, schOrRef); + if (typeof (sch === null || sch === void 0 ? void 0 : sch.schema) !== "object") return; + return getJsonPointer.call(this, p, sch); + } + if (typeof (schOrRef === null || schOrRef === void 0 ? void 0 : schOrRef.schema) !== "object") return; + if (!schOrRef.validate) compileSchema.call(this, schOrRef); + if (id === (0, resolve_1.normalizeId)(ref)) { + const { schema } = schOrRef; + const { schemaId } = this.opts; + const schId = schema[schemaId]; + if (schId) baseId = (0, resolve_1.resolveUrl)(this.opts.uriResolver, baseId, schId); + return new SchemaEnv({ + schema, + schemaId, + root, + baseId + }); + } + return getJsonPointer.call(this, p, schOrRef); + } + exports.resolveSchema = resolveSchema; + const PREVENT_SCOPE_CHANGE = new Set([ + "properties", + "patternProperties", + "enum", + "dependencies", + "definitions" + ]); + function getJsonPointer(parsedRef, { baseId, schema, root }) { + var _a; + if (((_a = parsedRef.fragment) === null || _a === void 0 ? void 0 : _a[0]) !== "/") return; + for (const part of parsedRef.fragment.slice(1).split("/")) { + if (typeof schema === "boolean") return; + const partSchema = schema[(0, util_1.unescapeFragment)(part)]; + if (partSchema === void 0) return; + schema = partSchema; + const schId = typeof schema === "object" && schema[this.opts.schemaId]; + if (!PREVENT_SCOPE_CHANGE.has(part) && schId) baseId = (0, resolve_1.resolveUrl)(this.opts.uriResolver, baseId, schId); + } + let env; + if (typeof schema != "boolean" && schema.$ref && !(0, util_1.schemaHasRulesButRef)(schema, this.RULES)) { + const $ref = (0, resolve_1.resolveUrl)(this.opts.uriResolver, baseId, schema.$ref); + env = resolveSchema.call(this, root, $ref); + } + const { schemaId } = this.opts; + env = env || new SchemaEnv({ + schema, + schemaId, + root, + baseId + }); + if (env.schema !== env.root.schema) return env; + } +})); + +//#endregion +//#region ../../node_modules/.pnpm/ajv@8.18.0/node_modules/ajv/dist/refs/data.json +var require_data = /* @__PURE__ */ __commonJSMin(((exports, module) => { + module.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": false + }; +})); + +//#endregion +//#region ../../node_modules/.pnpm/fast-uri@3.1.0/node_modules/fast-uri/lib/utils.js +var require_utils = /* @__PURE__ */ __commonJSMin(((exports, module) => { + /** @type {(value: string) => boolean} */ + const isUUID = RegExp.prototype.test.bind(/^[\da-f]{8}-[\da-f]{4}-[\da-f]{4}-[\da-f]{4}-[\da-f]{12}$/iu); + /** @type {(value: string) => boolean} */ + const isIPv4 = 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); + /** + * @param {Array} input + * @returns {string} + */ + function stringArrayToHexStripped(input) { + let acc = ""; + let code = 0; + let i = 0; + for (i = 0; i < input.length; i++) { + code = input[i].charCodeAt(0); + if (code === 48) continue; + if (!(code >= 48 && code <= 57 || code >= 65 && code <= 70 || code >= 97 && code <= 102)) return ""; + acc += input[i]; + break; + } + for (i += 1; i < input.length; i++) { + code = input[i].charCodeAt(0); + if (!(code >= 48 && code <= 57 || code >= 65 && code <= 70 || code >= 97 && code <= 102)) return ""; + acc += input[i]; + } + return acc; + } + /** + * @typedef {Object} GetIPV6Result + * @property {boolean} error - Indicates if there was an error parsing the IPv6 address. + * @property {string} address - The parsed IPv6 address. + * @property {string} [zone] - The zone identifier, if present. + */ + /** + * @param {string} value + * @returns {boolean} + */ + const nonSimpleDomain = RegExp.prototype.test.bind(/[^!"$&'()*+,\-.;=_`a-z{}~]/u); + /** + * @param {Array} buffer + * @returns {boolean} + */ + function consumeIsZone(buffer) { + buffer.length = 0; + return true; + } + /** + * @param {Array} buffer + * @param {Array} address + * @param {GetIPV6Result} output + * @returns {boolean} + */ + function consumeHextets(buffer, address, output) { + if (buffer.length) { + const hex = stringArrayToHexStripped(buffer); + if (hex !== "") address.push(hex); + else { + output.error = true; + return false; + } + buffer.length = 0; + } + return true; + } + /** + * @param {string} input + * @returns {GetIPV6Result} + */ + function getIPV6(input) { + let tokenCount = 0; + const output = { + error: false, + address: "", + zone: "" + }; + /** @type {Array} */ + const address = []; + /** @type {Array} */ + const buffer = []; + let endipv6Encountered = false; + let endIpv6 = false; + let consume = consumeHextets; + for (let i = 0; i < input.length; i++) { + const cursor = input[i]; + if (cursor === "[" || cursor === "]") continue; + if (cursor === ":") { + if (endipv6Encountered === true) endIpv6 = true; + if (!consume(buffer, address, output)) break; + if (++tokenCount > 7) { + output.error = true; + break; + } + if (i > 0 && input[i - 1] === ":") endipv6Encountered = true; + address.push(":"); + continue; + } else if (cursor === "%") { + if (!consume(buffer, address, output)) break; + consume = consumeIsZone; + } else { + buffer.push(cursor); + continue; + } + } + if (buffer.length) if (consume === consumeIsZone) output.zone = buffer.join(""); + else if (endIpv6) address.push(buffer.join("")); + else address.push(stringArrayToHexStripped(buffer)); + output.address = address.join(""); + return output; + } + /** + * @typedef {Object} NormalizeIPv6Result + * @property {string} host - The normalized host. + * @property {string} [escapedHost] - The escaped host. + * @property {boolean} isIPV6 - Indicates if the host is an IPv6 address. + */ + /** + * @param {string} host + * @returns {NormalizeIPv6Result} + */ + function normalizeIPv6(host) { + if (findToken(host, ":") < 2) return { + host, + isIPV6: false + }; + const ipv6 = getIPV6(host); + if (!ipv6.error) { + let newHost = ipv6.address; + let escapedHost = ipv6.address; + if (ipv6.zone) { + newHost += "%" + ipv6.zone; + escapedHost += "%25" + ipv6.zone; + } + return { + host: newHost, + isIPV6: true, + escapedHost + }; + } else return { + host, + isIPV6: false + }; + } + /** + * @param {string} str + * @param {string} token + * @returns {number} + */ + function findToken(str, token) { + let ind = 0; + for (let i = 0; i < str.length; i++) if (str[i] === token) ind++; + return ind; + } + /** + * @param {string} path + * @returns {string} + * + * @see https://datatracker.ietf.org/doc/html/rfc3986#section-5.2.4 + */ + function removeDotSegments(path) { + let input = path; + const output = []; + let nextSlash = -1; + let len = 0; + while (len = input.length) { + if (len === 1) if (input === ".") break; + else if (input === "/") { + output.push("/"); + break; + } else { + output.push(input); + break; + } + else if (len === 2) { + if (input[0] === ".") { + if (input[1] === ".") break; + else if (input[1] === "/") { + input = input.slice(2); + continue; + } + } else if (input[0] === "/") { + if (input[1] === "." || input[1] === "/") { + output.push("/"); + break; + } + } + } else if (len === 3) { + if (input === "/..") { + if (output.length !== 0) output.pop(); + output.push("/"); + break; + } + } + if (input[0] === ".") { + if (input[1] === ".") { + if (input[2] === "/") { + input = input.slice(3); + continue; + } + } else if (input[1] === "/") { + input = input.slice(2); + continue; + } + } else if (input[0] === "/") { + if (input[1] === ".") { + if (input[2] === "/") { + input = input.slice(2); + continue; + } else if (input[2] === ".") { + if (input[3] === "/") { + input = input.slice(3); + if (output.length !== 0) output.pop(); + continue; + } + } + } + } + if ((nextSlash = input.indexOf("/", 1)) === -1) { + output.push(input); + break; + } else { + output.push(input.slice(0, nextSlash)); + input = input.slice(nextSlash); + } + } + return output.join(""); + } + /** + * @param {import('../types/index').URIComponent} component + * @param {boolean} esc + * @returns {import('../types/index').URIComponent} + */ + function normalizeComponentEncoding(component, esc) { + const func = esc !== true ? escape : unescape; + if (component.scheme !== void 0) component.scheme = func(component.scheme); + if (component.userinfo !== void 0) component.userinfo = func(component.userinfo); + if (component.host !== void 0) component.host = func(component.host); + if (component.path !== void 0) component.path = func(component.path); + if (component.query !== void 0) component.query = func(component.query); + if (component.fragment !== void 0) component.fragment = func(component.fragment); + return component; + } + /** + * @param {import('../types/index').URIComponent} component + * @returns {string|undefined} + */ + function recomposeAuthority(component) { + const uriTokens = []; + if (component.userinfo !== void 0) { + uriTokens.push(component.userinfo); + uriTokens.push("@"); + } + if (component.host !== void 0) { + let host = unescape(component.host); + if (!isIPv4(host)) { + const ipV6res = normalizeIPv6(host); + if (ipV6res.isIPV6 === true) host = `[${ipV6res.escapedHost}]`; + else host = component.host; + } + uriTokens.push(host); + } + if (typeof component.port === "number" || typeof component.port === "string") { + uriTokens.push(":"); + uriTokens.push(String(component.port)); + } + return uriTokens.length ? uriTokens.join("") : void 0; + } + module.exports = { + nonSimpleDomain, + recomposeAuthority, + normalizeComponentEncoding, + removeDotSegments, + isIPv4, + isUUID, + normalizeIPv6, + stringArrayToHexStripped + }; +})); + +//#endregion +//#region ../../node_modules/.pnpm/fast-uri@3.1.0/node_modules/fast-uri/lib/schemes.js +var require_schemes = /* @__PURE__ */ __commonJSMin(((exports, module) => { + const { isUUID } = require_utils(); + const URN_REG = /([\da-z][\d\-a-z]{0,31}):((?:[\w!$'()*+,\-.:;=@]|%[\da-f]{2})+)/iu; + const supportedSchemeNames = [ + "http", + "https", + "ws", + "wss", + "urn", + "urn:uuid" + ]; + /** @typedef {supportedSchemeNames[number]} SchemeName */ + /** + * @param {string} name + * @returns {name is SchemeName} + */ + function isValidSchemeName(name) { + return supportedSchemeNames.indexOf(name) !== -1; + } + /** + * @callback SchemeFn + * @param {import('../types/index').URIComponent} component + * @param {import('../types/index').Options} options + * @returns {import('../types/index').URIComponent} + */ + /** + * @typedef {Object} SchemeHandler + * @property {SchemeName} scheme - The scheme name. + * @property {boolean} [domainHost] - Indicates if the scheme supports domain hosts. + * @property {SchemeFn} parse - Function to parse the URI component for this scheme. + * @property {SchemeFn} serialize - Function to serialize the URI component for this scheme. + * @property {boolean} [skipNormalize] - Indicates if normalization should be skipped for this scheme. + * @property {boolean} [absolutePath] - Indicates if the scheme uses absolute paths. + * @property {boolean} [unicodeSupport] - Indicates if the scheme supports Unicode. + */ + /** + * @param {import('../types/index').URIComponent} wsComponent + * @returns {boolean} + */ + function wsIsSecure(wsComponent) { + if (wsComponent.secure === true) return true; + else if (wsComponent.secure === false) return false; + else if (wsComponent.scheme) return wsComponent.scheme.length === 3 && (wsComponent.scheme[0] === "w" || wsComponent.scheme[0] === "W") && (wsComponent.scheme[1] === "s" || wsComponent.scheme[1] === "S") && (wsComponent.scheme[2] === "s" || wsComponent.scheme[2] === "S"); + else return false; + } + /** @type {SchemeFn} */ + function httpParse(component) { + if (!component.host) component.error = component.error || "HTTP URIs must have a host."; + return component; + } + /** @type {SchemeFn} */ + function httpSerialize(component) { + const secure = String(component.scheme).toLowerCase() === "https"; + if (component.port === (secure ? 443 : 80) || component.port === "") component.port = void 0; + if (!component.path) component.path = "/"; + return component; + } + /** @type {SchemeFn} */ + function wsParse(wsComponent) { + wsComponent.secure = wsIsSecure(wsComponent); + wsComponent.resourceName = (wsComponent.path || "/") + (wsComponent.query ? "?" + wsComponent.query : ""); + wsComponent.path = void 0; + wsComponent.query = void 0; + return wsComponent; + } + /** @type {SchemeFn} */ + function wsSerialize(wsComponent) { + if (wsComponent.port === (wsIsSecure(wsComponent) ? 443 : 80) || wsComponent.port === "") wsComponent.port = void 0; + if (typeof wsComponent.secure === "boolean") { + wsComponent.scheme = wsComponent.secure ? "wss" : "ws"; + wsComponent.secure = void 0; + } + if (wsComponent.resourceName) { + const [path, query] = wsComponent.resourceName.split("?"); + wsComponent.path = path && path !== "/" ? path : void 0; + wsComponent.query = query; + wsComponent.resourceName = void 0; + } + wsComponent.fragment = void 0; + return wsComponent; + } + /** @type {SchemeFn} */ + function urnParse(urnComponent, options) { + if (!urnComponent.path) { + urnComponent.error = "URN can not be parsed"; + return urnComponent; + } + const matches = urnComponent.path.match(URN_REG); + if (matches) { + const scheme = options.scheme || urnComponent.scheme || "urn"; + urnComponent.nid = matches[1].toLowerCase(); + urnComponent.nss = matches[2]; + const schemeHandler = getSchemeHandler(`${scheme}:${options.nid || urnComponent.nid}`); + urnComponent.path = void 0; + if (schemeHandler) urnComponent = schemeHandler.parse(urnComponent, options); + } else urnComponent.error = urnComponent.error || "URN can not be parsed."; + return urnComponent; + } + /** @type {SchemeFn} */ + function urnSerialize(urnComponent, options) { + if (urnComponent.nid === void 0) throw new Error("URN without nid cannot be serialized"); + const scheme = options.scheme || urnComponent.scheme || "urn"; + const nid = urnComponent.nid.toLowerCase(); + const schemeHandler = getSchemeHandler(`${scheme}:${options.nid || nid}`); + if (schemeHandler) urnComponent = schemeHandler.serialize(urnComponent, options); + const uriComponent = urnComponent; + const nss = urnComponent.nss; + uriComponent.path = `${nid || options.nid}:${nss}`; + options.skipEscape = true; + return uriComponent; + } + /** @type {SchemeFn} */ + function urnuuidParse(urnComponent, options) { + const uuidComponent = urnComponent; + uuidComponent.uuid = uuidComponent.nss; + uuidComponent.nss = void 0; + if (!options.tolerant && (!uuidComponent.uuid || !isUUID(uuidComponent.uuid))) uuidComponent.error = uuidComponent.error || "UUID is not valid."; + return uuidComponent; + } + /** @type {SchemeFn} */ + function urnuuidSerialize(uuidComponent) { + const urnComponent = uuidComponent; + urnComponent.nss = (uuidComponent.uuid || "").toLowerCase(); + return urnComponent; + } + const http = { + scheme: "http", + domainHost: true, + parse: httpParse, + serialize: httpSerialize + }; + const https = { + scheme: "https", + domainHost: http.domainHost, + parse: httpParse, + serialize: httpSerialize + }; + const ws = { + scheme: "ws", + domainHost: true, + parse: wsParse, + serialize: wsSerialize + }; + const wss = { + scheme: "wss", + domainHost: ws.domainHost, + parse: ws.parse, + serialize: ws.serialize + }; + const urn = { + scheme: "urn", + parse: urnParse, + serialize: urnSerialize, + skipNormalize: true + }; + const urnuuid = { + scheme: "urn:uuid", + parse: urnuuidParse, + serialize: urnuuidSerialize, + skipNormalize: true + }; + const SCHEMES = { + http, + https, + ws, + wss, + urn, + "urn:uuid": urnuuid + }; + Object.setPrototypeOf(SCHEMES, null); + /** + * @param {string|undefined} scheme + * @returns {SchemeHandler|undefined} + */ + function getSchemeHandler(scheme) { + return scheme && (SCHEMES[scheme] || SCHEMES[scheme.toLowerCase()]) || void 0; + } + module.exports = { + wsIsSecure, + SCHEMES, + isValidSchemeName, + getSchemeHandler + }; +})); + +//#endregion +//#region ../../node_modules/.pnpm/fast-uri@3.1.0/node_modules/fast-uri/index.js +var require_fast_uri = /* @__PURE__ */ __commonJSMin(((exports, module) => { + const { normalizeIPv6, removeDotSegments, recomposeAuthority, normalizeComponentEncoding, isIPv4, nonSimpleDomain } = require_utils(); + const { SCHEMES, getSchemeHandler } = require_schemes(); + /** + * @template {import('./types/index').URIComponent|string} T + * @param {T} uri + * @param {import('./types/index').Options} [options] + * @returns {T} + */ + function normalize(uri, options) { + if (typeof uri === "string") uri = serialize(parse(uri, options), options); + else if (typeof uri === "object") uri = parse(serialize(uri, options), options); + return uri; + } + /** + * @param {string} baseURI + * @param {string} relativeURI + * @param {import('./types/index').Options} [options] + * @returns {string} + */ + function resolve(baseURI, relativeURI, options) { + const schemelessOptions = options ? Object.assign({ scheme: "null" }, options) : { scheme: "null" }; + const resolved = resolveComponent(parse(baseURI, schemelessOptions), parse(relativeURI, schemelessOptions), schemelessOptions, true); + schemelessOptions.skipEscape = true; + return serialize(resolved, schemelessOptions); + } + /** + * @param {import ('./types/index').URIComponent} base + * @param {import ('./types/index').URIComponent} relative + * @param {import('./types/index').Options} [options] + * @param {boolean} [skipNormalization=false] + * @returns {import ('./types/index').URIComponent} + */ + function resolveComponent(base, relative, options, skipNormalization) { + /** @type {import('./types/index').URIComponent} */ + const target = {}; + if (!skipNormalization) { + base = parse(serialize(base, options), options); + relative = parse(serialize(relative, options), options); + } + options = options || {}; + if (!options.tolerant && relative.scheme) { + target.scheme = relative.scheme; + target.userinfo = relative.userinfo; + target.host = relative.host; + target.port = relative.port; + target.path = removeDotSegments(relative.path || ""); + target.query = relative.query; + } else { + if (relative.userinfo !== void 0 || relative.host !== void 0 || relative.port !== void 0) { + target.userinfo = relative.userinfo; + target.host = relative.host; + target.port = relative.port; + target.path = removeDotSegments(relative.path || ""); + target.query = relative.query; + } else { + if (!relative.path) { + target.path = base.path; + if (relative.query !== void 0) target.query = relative.query; + else target.query = base.query; + } else { + if (relative.path[0] === "/") target.path = removeDotSegments(relative.path); + else { + if ((base.userinfo !== void 0 || base.host !== void 0 || base.port !== void 0) && !base.path) target.path = "/" + relative.path; + else if (!base.path) target.path = relative.path; + else target.path = base.path.slice(0, base.path.lastIndexOf("/") + 1) + relative.path; + target.path = removeDotSegments(target.path); + } + target.query = relative.query; + } + target.userinfo = base.userinfo; + target.host = base.host; + target.port = base.port; + } + target.scheme = base.scheme; + } + target.fragment = relative.fragment; + return target; + } + /** + * @param {import ('./types/index').URIComponent|string} uriA + * @param {import ('./types/index').URIComponent|string} uriB + * @param {import ('./types/index').Options} options + * @returns {boolean} + */ + function equal(uriA, uriB, options) { + if (typeof uriA === "string") { + uriA = unescape(uriA); + uriA = serialize(normalizeComponentEncoding(parse(uriA, options), true), { + ...options, + skipEscape: true + }); + } else if (typeof uriA === "object") uriA = serialize(normalizeComponentEncoding(uriA, true), { + ...options, + skipEscape: true + }); + if (typeof uriB === "string") { + uriB = unescape(uriB); + uriB = serialize(normalizeComponentEncoding(parse(uriB, options), true), { + ...options, + skipEscape: true + }); + } else if (typeof uriB === "object") uriB = serialize(normalizeComponentEncoding(uriB, true), { + ...options, + skipEscape: true + }); + return uriA.toLowerCase() === uriB.toLowerCase(); + } + /** + * @param {Readonly} cmpts + * @param {import('./types/index').Options} [opts] + * @returns {string} + */ + function serialize(cmpts, opts) { + const component = { + host: cmpts.host, + scheme: cmpts.scheme, + userinfo: cmpts.userinfo, + port: cmpts.port, + path: cmpts.path, + query: cmpts.query, + nid: cmpts.nid, + nss: cmpts.nss, + uuid: cmpts.uuid, + fragment: cmpts.fragment, + reference: cmpts.reference, + resourceName: cmpts.resourceName, + secure: cmpts.secure, + error: "" + }; + const options = Object.assign({}, opts); + const uriTokens = []; + const schemeHandler = getSchemeHandler(options.scheme || component.scheme); + if (schemeHandler && schemeHandler.serialize) schemeHandler.serialize(component, options); + if (component.path !== void 0) if (!options.skipEscape) { + component.path = escape(component.path); + if (component.scheme !== void 0) component.path = component.path.split("%3A").join(":"); + } else component.path = unescape(component.path); + if (options.reference !== "suffix" && component.scheme) uriTokens.push(component.scheme, ":"); + const authority = recomposeAuthority(component); + if (authority !== void 0) { + if (options.reference !== "suffix") uriTokens.push("//"); + uriTokens.push(authority); + if (component.path && component.path[0] !== "/") uriTokens.push("/"); + } + if (component.path !== void 0) { + let s = component.path; + if (!options.absolutePath && (!schemeHandler || !schemeHandler.absolutePath)) s = removeDotSegments(s); + if (authority === void 0 && s[0] === "/" && s[1] === "/") s = "/%2F" + s.slice(2); + uriTokens.push(s); + } + if (component.query !== void 0) uriTokens.push("?", component.query); + if (component.fragment !== void 0) uriTokens.push("#", component.fragment); + return uriTokens.join(""); + } + const URI_PARSE = /^(?:([^#/:?]+):)?(?:\/\/((?:([^#/?@]*)@)?(\[[^#/?\]]+\]|[^#/:?]*)(?::(\d*))?))?([^#?]*)(?:\?([^#]*))?(?:#((?:.|[\n\r])*))?/u; + /** + * @param {string} uri + * @param {import('./types/index').Options} [opts] + * @returns + */ + function parse(uri, opts) { + const options = Object.assign({}, opts); + /** @type {import('./types/index').URIComponent} */ + const parsed = { + scheme: void 0, + userinfo: void 0, + host: "", + port: void 0, + path: "", + query: void 0, + fragment: void 0 + }; + let isIP = false; + if (options.reference === "suffix") if (options.scheme) uri = options.scheme + ":" + uri; + else uri = "//" + uri; + const matches = uri.match(URI_PARSE); + if (matches) { + parsed.scheme = matches[1]; + parsed.userinfo = matches[3]; + parsed.host = matches[4]; + parsed.port = parseInt(matches[5], 10); + parsed.path = matches[6] || ""; + parsed.query = matches[7]; + parsed.fragment = matches[8]; + if (isNaN(parsed.port)) parsed.port = matches[5]; + if (parsed.host) if (isIPv4(parsed.host) === false) { + const ipv6result = normalizeIPv6(parsed.host); + parsed.host = ipv6result.host.toLowerCase(); + isIP = ipv6result.isIPV6; + } else isIP = true; + if (parsed.scheme === void 0 && parsed.userinfo === void 0 && parsed.host === void 0 && parsed.port === void 0 && parsed.query === void 0 && !parsed.path) parsed.reference = "same-document"; + else if (parsed.scheme === void 0) parsed.reference = "relative"; + else if (parsed.fragment === void 0) parsed.reference = "absolute"; + else parsed.reference = "uri"; + if (options.reference && options.reference !== "suffix" && options.reference !== parsed.reference) parsed.error = parsed.error || "URI is not a " + options.reference + " reference."; + const schemeHandler = getSchemeHandler(options.scheme || parsed.scheme); + if (!options.unicodeSupport && (!schemeHandler || !schemeHandler.unicodeSupport)) { + if (parsed.host && (options.domainHost || schemeHandler && schemeHandler.domainHost) && isIP === false && nonSimpleDomain(parsed.host)) try { + parsed.host = URL.domainToASCII(parsed.host.toLowerCase()); + } catch (e) { + parsed.error = parsed.error || "Host's domain name can not be converted to ASCII: " + e; + } + } + if (!schemeHandler || schemeHandler && !schemeHandler.skipNormalize) { + if (uri.indexOf("%") !== -1) { + if (parsed.scheme !== void 0) parsed.scheme = unescape(parsed.scheme); + if (parsed.host !== void 0) parsed.host = unescape(parsed.host); + } + if (parsed.path) parsed.path = escape(unescape(parsed.path)); + if (parsed.fragment) parsed.fragment = encodeURI(decodeURIComponent(parsed.fragment)); + } + if (schemeHandler && schemeHandler.parse) schemeHandler.parse(parsed, options); + } else parsed.error = parsed.error || "URI can not be parsed."; + return parsed; + } + const fastUri = { + SCHEMES, + normalize, + resolve, + resolveComponent, + equal, + serialize, + parse + }; + module.exports = fastUri; + module.exports.default = fastUri; + module.exports.fastUri = fastUri; +})); + +//#endregion +//#region ../../node_modules/.pnpm/ajv@8.18.0/node_modules/ajv/dist/runtime/uri.js +var require_uri = /* @__PURE__ */ __commonJSMin(((exports) => { + Object.defineProperty(exports, "__esModule", { value: true }); + const uri = require_fast_uri(); + uri.code = "require(\"ajv/dist/runtime/uri\").default"; + exports.default = uri; +})); + +//#endregion +//#region ../../node_modules/.pnpm/ajv@8.18.0/node_modules/ajv/dist/core.js +var require_core$3 = /* @__PURE__ */ __commonJSMin(((exports) => { + Object.defineProperty(exports, "__esModule", { value: true }); + exports.CodeGen = exports.Name = exports.nil = exports.stringify = exports.str = exports._ = exports.KeywordCxt = void 0; + var validate_1 = require_validate(); + Object.defineProperty(exports, "KeywordCxt", { + enumerable: true, + get: function() { + return validate_1.KeywordCxt; + } + }); + var codegen_1 = require_codegen(); + Object.defineProperty(exports, "_", { + enumerable: true, + get: function() { + return codegen_1._; + } + }); + Object.defineProperty(exports, "str", { + enumerable: true, + get: function() { + return codegen_1.str; + } + }); + Object.defineProperty(exports, "stringify", { + enumerable: true, + get: function() { + return codegen_1.stringify; + } + }); + Object.defineProperty(exports, "nil", { + enumerable: true, + get: function() { + return codegen_1.nil; + } + }); + Object.defineProperty(exports, "Name", { + enumerable: true, + get: function() { + return codegen_1.Name; + } + }); + Object.defineProperty(exports, "CodeGen", { + enumerable: true, + get: function() { + return codegen_1.CodeGen; + } + }); + const validation_error_1 = require_validation_error(); + const ref_error_1 = require_ref_error(); + const rules_1 = require_rules(); + const compile_1 = require_compile(); + const codegen_2 = require_codegen(); + const resolve_1 = require_resolve(); + const dataType_1 = require_dataType(); + const util_1 = require_util(); + const $dataRefSchema = require_data(); + const uri_1 = require_uri(); + const defaultRegExp = (str, flags) => new RegExp(str, flags); + defaultRegExp.code = "new RegExp"; + const META_IGNORE_OPTIONS = [ + "removeAdditional", + "useDefaults", + "coerceTypes" + ]; + const EXT_SCOPE_NAMES = new Set([ + "validate", + "serialize", + "parse", + "wrapper", + "root", + "schema", + "keyword", + "pattern", + "formats", + "validate$data", + "func", + "obj", + "Error" + ]); + const removedOptions = { + 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." + }; + const deprecatedOptions = { + ignoreKeywordsWithRef: "", + jsPropertySyntax: "", + unicode: "\"minLength\"/\"maxLength\" account for unicode characters by default." + }; + const MAX_EXPRESSION = 200; + function requiredOptions(o) { + var _a, _b, _c, _d, _e, _f, _g, _h, _j, _k, _l, _m, _o, _p, _q, _r, _s, _t, _u, _v, _w, _x, _y, _z, _0; + const s = o.strict; + const _optz = (_a = o.code) === null || _a === void 0 ? void 0 : _a.optimize; + const optimize = _optz === true || _optz === void 0 ? 1 : _optz || 0; + const regExp = (_c = (_b = o.code) === null || _b === void 0 ? void 0 : _b.regExp) !== null && _c !== void 0 ? _c : defaultRegExp; + const uriResolver = (_d = o.uriResolver) !== null && _d !== void 0 ? _d : uri_1.default; + return { + strictSchema: (_f = (_e = o.strictSchema) !== null && _e !== void 0 ? _e : s) !== null && _f !== void 0 ? _f : true, + strictNumbers: (_h = (_g = o.strictNumbers) !== null && _g !== void 0 ? _g : s) !== null && _h !== void 0 ? _h : true, + strictTypes: (_k = (_j = o.strictTypes) !== null && _j !== void 0 ? _j : s) !== null && _k !== void 0 ? _k : "log", + strictTuples: (_m = (_l = o.strictTuples) !== null && _l !== void 0 ? _l : s) !== null && _m !== void 0 ? _m : "log", + strictRequired: (_p = (_o = o.strictRequired) !== null && _o !== void 0 ? _o : s) !== null && _p !== void 0 ? _p : false, + code: o.code ? { + ...o.code, + optimize, + regExp + } : { + optimize, + regExp + }, + loopRequired: (_q = o.loopRequired) !== null && _q !== void 0 ? _q : MAX_EXPRESSION, + loopEnum: (_r = o.loopEnum) !== null && _r !== void 0 ? _r : MAX_EXPRESSION, + meta: (_s = o.meta) !== null && _s !== void 0 ? _s : true, + messages: (_t = o.messages) !== null && _t !== void 0 ? _t : true, + inlineRefs: (_u = o.inlineRefs) !== null && _u !== void 0 ? _u : true, + schemaId: (_v = o.schemaId) !== null && _v !== void 0 ? _v : "$id", + addUsedSchema: (_w = o.addUsedSchema) !== null && _w !== void 0 ? _w : true, + validateSchema: (_x = o.validateSchema) !== null && _x !== void 0 ? _x : true, + validateFormats: (_y = o.validateFormats) !== null && _y !== void 0 ? _y : true, + unicodeRegExp: (_z = o.unicodeRegExp) !== null && _z !== void 0 ? _z : true, + int32range: (_0 = o.int32range) !== null && _0 !== void 0 ? _0 : true, + uriResolver + }; + } + var Ajv = class { + constructor(opts = {}) { + this.schemas = {}; + this.refs = {}; + this.formats = {}; + this._compilations = /* @__PURE__ */ new Set(); + this._loading = {}; + this._cache = /* @__PURE__ */ new Map(); + opts = this.opts = { + ...opts, + ...requiredOptions(opts) + }; + const { es5, lines } = this.opts.code; + this.scope = new codegen_2.ValueScope({ + scope: {}, + prefixes: EXT_SCOPE_NAMES, + es5, + lines + }); + this.logger = getLogger(opts.logger); + const formatOpt = opts.validateFormats; + opts.validateFormats = false; + this.RULES = (0, rules_1.getRules)(); + checkOptions.call(this, removedOptions, opts, "NOT SUPPORTED"); + checkOptions.call(this, deprecatedOptions, opts, "DEPRECATED", "warn"); + this._metaOpts = getMetaSchemaOptions.call(this); + if (opts.formats) addInitialFormats.call(this); + this._addVocabularies(); + this._addDefaultMetaSchema(); + if (opts.keywords) addInitialKeywords.call(this, opts.keywords); + if (typeof opts.meta == "object") this.addMetaSchema(opts.meta); + addInitialSchemas.call(this); + opts.validateFormats = formatOpt; + } + _addVocabularies() { + this.addKeyword("$async"); + } + _addDefaultMetaSchema() { + const { $data, meta, schemaId } = this.opts; + let _dataRefSchema = $dataRefSchema; + if (schemaId === "id") { + _dataRefSchema = { ...$dataRefSchema }; + _dataRefSchema.id = _dataRefSchema.$id; + delete _dataRefSchema.$id; + } + if (meta && $data) this.addMetaSchema(_dataRefSchema, _dataRefSchema[schemaId], false); + } + defaultMeta() { + const { meta, schemaId } = this.opts; + return this.opts.defaultMeta = typeof meta == "object" ? meta[schemaId] || meta : void 0; + } + validate(schemaKeyRef, data) { + let v; + if (typeof schemaKeyRef == "string") { + v = this.getSchema(schemaKeyRef); + if (!v) throw new Error(`no schema with key or ref "${schemaKeyRef}"`); + } else v = this.compile(schemaKeyRef); + const valid = v(data); + if (!("$async" in v)) this.errors = v.errors; + return valid; + } + compile(schema, _meta) { + const sch = this._addSchema(schema, _meta); + return sch.validate || this._compileSchemaEnv(sch); + } + compileAsync(schema, meta) { + if (typeof this.opts.loadSchema != "function") throw new Error("options.loadSchema should be a function"); + const { loadSchema } = this.opts; + return runCompileAsync.call(this, schema, meta); + async function runCompileAsync(_schema, _meta) { + await loadMetaSchema.call(this, _schema.$schema); + const sch = this._addSchema(_schema, _meta); + return sch.validate || _compileAsync.call(this, sch); + } + async function loadMetaSchema($ref) { + if ($ref && !this.getSchema($ref)) await runCompileAsync.call(this, { $ref }, true); + } + async function _compileAsync(sch) { + try { + return this._compileSchemaEnv(sch); + } catch (e) { + if (!(e instanceof ref_error_1.default)) throw e; + checkLoaded.call(this, e); + await loadMissingSchema.call(this, e.missingSchema); + return _compileAsync.call(this, sch); + } + } + function checkLoaded({ missingSchema: ref, missingRef }) { + if (this.refs[ref]) throw new Error(`AnySchema ${ref} is loaded but ${missingRef} cannot be resolved`); + } + async function loadMissingSchema(ref) { + const _schema = await _loadSchema.call(this, ref); + if (!this.refs[ref]) await loadMetaSchema.call(this, _schema.$schema); + if (!this.refs[ref]) this.addSchema(_schema, ref, meta); + } + async function _loadSchema(ref) { + const p = this._loading[ref]; + if (p) return p; + try { + return await (this._loading[ref] = loadSchema(ref)); + } finally { + delete this._loading[ref]; + } + } + } + addSchema(schema, key, _meta, _validateSchema = this.opts.validateSchema) { + if (Array.isArray(schema)) { + for (const sch of schema) this.addSchema(sch, void 0, _meta, _validateSchema); + return this; + } + let id; + if (typeof schema === "object") { + const { schemaId } = this.opts; + id = schema[schemaId]; + if (id !== void 0 && typeof id != "string") throw new Error(`schema ${schemaId} must be string`); + } + key = (0, resolve_1.normalizeId)(key || id); + this._checkUnique(key); + this.schemas[key] = this._addSchema(schema, _meta, key, _validateSchema, true); + return this; + } + addMetaSchema(schema, key, _validateSchema = this.opts.validateSchema) { + this.addSchema(schema, key, true, _validateSchema); + return this; + } + validateSchema(schema, throwOrLogError) { + if (typeof schema == "boolean") return true; + let $schema; + $schema = schema.$schema; + if ($schema !== void 0 && typeof $schema != "string") throw new Error("$schema must be a string"); + $schema = $schema || this.opts.defaultMeta || this.defaultMeta(); + if (!$schema) { + this.logger.warn("meta-schema not available"); + this.errors = null; + return true; + } + const valid = this.validate($schema, schema); + if (!valid && throwOrLogError) { + const message = "schema is invalid: " + this.errorsText(); + if (this.opts.validateSchema === "log") this.logger.error(message); + else throw new Error(message); + } + return valid; + } + getSchema(keyRef) { + let sch; + while (typeof (sch = getSchEnv.call(this, keyRef)) == "string") keyRef = sch; + if (sch === void 0) { + const { schemaId } = this.opts; + const root = new compile_1.SchemaEnv({ + schema: {}, + schemaId + }); + sch = compile_1.resolveSchema.call(this, root, keyRef); + if (!sch) return; + this.refs[keyRef] = sch; + } + return sch.validate || this._compileSchemaEnv(sch); + } + removeSchema(schemaKeyRef) { + if (schemaKeyRef instanceof RegExp) { + this._removeAllSchemas(this.schemas, schemaKeyRef); + this._removeAllSchemas(this.refs, schemaKeyRef); + return this; + } + switch (typeof schemaKeyRef) { + case "undefined": + this._removeAllSchemas(this.schemas); + this._removeAllSchemas(this.refs); + this._cache.clear(); + return this; + case "string": { + const sch = getSchEnv.call(this, schemaKeyRef); + if (typeof sch == "object") this._cache.delete(sch.schema); + delete this.schemas[schemaKeyRef]; + delete this.refs[schemaKeyRef]; + return this; + } + case "object": { + const cacheKey = schemaKeyRef; + this._cache.delete(cacheKey); + let id = schemaKeyRef[this.opts.schemaId]; + if (id) { + id = (0, resolve_1.normalizeId)(id); + delete this.schemas[id]; + delete this.refs[id]; + } + return this; + } + default: throw new Error("ajv.removeSchema: invalid parameter"); + } + } + addVocabulary(definitions) { + for (const def of definitions) this.addKeyword(def); + return this; + } + addKeyword(kwdOrDef, def) { + let keyword; + if (typeof kwdOrDef == "string") { + keyword = kwdOrDef; + if (typeof def == "object") { + this.logger.warn("these parameters are deprecated, see docs for addKeyword"); + def.keyword = keyword; + } + } else if (typeof kwdOrDef == "object" && def === void 0) { + def = kwdOrDef; + keyword = def.keyword; + if (Array.isArray(keyword) && !keyword.length) throw new Error("addKeywords: keyword must be string or non-empty array"); + } else throw new Error("invalid addKeywords parameters"); + checkKeyword.call(this, keyword, def); + if (!def) { + (0, util_1.eachItem)(keyword, (kwd) => addRule.call(this, kwd)); + return this; + } + keywordMetaschema.call(this, def); + const definition = { + ...def, + type: (0, dataType_1.getJSONTypes)(def.type), + schemaType: (0, dataType_1.getJSONTypes)(def.schemaType) + }; + (0, util_1.eachItem)(keyword, definition.type.length === 0 ? (k) => addRule.call(this, k, definition) : (k) => definition.type.forEach((t) => addRule.call(this, k, definition, t))); + return this; + } + getKeyword(keyword) { + const rule = this.RULES.all[keyword]; + return typeof rule == "object" ? rule.definition : !!rule; + } + removeKeyword(keyword) { + const { RULES } = this; + delete RULES.keywords[keyword]; + delete RULES.all[keyword]; + for (const group of RULES.rules) { + const i = group.rules.findIndex((rule) => rule.keyword === keyword); + if (i >= 0) group.rules.splice(i, 1); + } + return this; + } + addFormat(name, format) { + if (typeof format == "string") format = new RegExp(format); + this.formats[name] = format; + return this; + } + errorsText(errors = this.errors, { separator = ", ", dataVar = "data" } = {}) { + if (!errors || errors.length === 0) return "No errors"; + return errors.map((e) => `${dataVar}${e.instancePath} ${e.message}`).reduce((text, msg) => text + separator + msg); + } + $dataMetaSchema(metaSchema, keywordsJsonPointers) { + const rules = this.RULES.all; + metaSchema = JSON.parse(JSON.stringify(metaSchema)); + for (const jsonPointer of keywordsJsonPointers) { + const segments = jsonPointer.split("/").slice(1); + let keywords = metaSchema; + for (const seg of segments) keywords = keywords[seg]; + for (const key in rules) { + const rule = rules[key]; + if (typeof rule != "object") continue; + const { $data } = rule.definition; + const schema = keywords[key]; + if ($data && schema) keywords[key] = schemaOrData(schema); + } + } + return metaSchema; + } + _removeAllSchemas(schemas, regex) { + for (const keyRef in schemas) { + const sch = schemas[keyRef]; + if (!regex || regex.test(keyRef)) { + if (typeof sch == "string") delete schemas[keyRef]; + else if (sch && !sch.meta) { + this._cache.delete(sch.schema); + delete schemas[keyRef]; + } + } + } + } + _addSchema(schema, meta, baseId, validateSchema = this.opts.validateSchema, addSchema = this.opts.addUsedSchema) { + let id; + const { schemaId } = this.opts; + if (typeof schema == "object") id = schema[schemaId]; + else if (this.opts.jtd) throw new Error("schema must be object"); + else if (typeof schema != "boolean") throw new Error("schema must be object or boolean"); + let sch = this._cache.get(schema); + if (sch !== void 0) return sch; + baseId = (0, resolve_1.normalizeId)(id || baseId); + const localRefs = resolve_1.getSchemaRefs.call(this, schema, baseId); + sch = new compile_1.SchemaEnv({ + schema, + schemaId, + meta, + baseId, + localRefs + }); + this._cache.set(sch.schema, sch); + if (addSchema && !baseId.startsWith("#")) { + if (baseId) this._checkUnique(baseId); + this.refs[baseId] = sch; + } + if (validateSchema) this.validateSchema(schema, true); + return sch; + } + _checkUnique(id) { + if (this.schemas[id] || this.refs[id]) throw new Error(`schema with key or id "${id}" already exists`); + } + _compileSchemaEnv(sch) { + if (sch.meta) this._compileMetaSchema(sch); + else compile_1.compileSchema.call(this, sch); + /* istanbul ignore if */ + if (!sch.validate) throw new Error("ajv implementation error"); + return sch.validate; + } + _compileMetaSchema(sch) { + const currentOpts = this.opts; + this.opts = this._metaOpts; + try { + compile_1.compileSchema.call(this, sch); + } finally { + this.opts = currentOpts; + } + } + }; + Ajv.ValidationError = validation_error_1.default; + Ajv.MissingRefError = ref_error_1.default; + exports.default = Ajv; + function checkOptions(checkOpts, options, msg, log = "error") { + for (const key in checkOpts) { + const opt = key; + if (opt in options) this.logger[log](`${msg}: option ${key}. ${checkOpts[opt]}`); + } + } + function getSchEnv(keyRef) { + keyRef = (0, resolve_1.normalizeId)(keyRef); + return this.schemas[keyRef] || this.refs[keyRef]; + } + function addInitialSchemas() { + const optsSchemas = this.opts.schemas; + if (!optsSchemas) return; + if (Array.isArray(optsSchemas)) this.addSchema(optsSchemas); + else for (const key in optsSchemas) this.addSchema(optsSchemas[key], key); + } + function addInitialFormats() { + for (const name in this.opts.formats) { + const format = this.opts.formats[name]; + if (format) this.addFormat(name, format); + } + } + function addInitialKeywords(defs) { + if (Array.isArray(defs)) { + this.addVocabulary(defs); + return; + } + this.logger.warn("keywords option as map is deprecated, pass array"); + for (const keyword in defs) { + const def = defs[keyword]; + if (!def.keyword) def.keyword = keyword; + this.addKeyword(def); + } + } + function getMetaSchemaOptions() { + const metaOpts = { ...this.opts }; + for (const opt of META_IGNORE_OPTIONS) delete metaOpts[opt]; + return metaOpts; + } + const noLogs = { + log() {}, + warn() {}, + error() {} + }; + function getLogger(logger) { + if (logger === false) return noLogs; + if (logger === void 0) return console; + if (logger.log && logger.warn && logger.error) return logger; + throw new Error("logger must implement log, warn and error methods"); + } + const KEYWORD_NAME = /^[a-z_$][a-z0-9_$:-]*$/i; + function checkKeyword(keyword, def) { + const { RULES } = this; + (0, util_1.eachItem)(keyword, (kwd) => { + if (RULES.keywords[kwd]) throw new Error(`Keyword ${kwd} is already defined`); + if (!KEYWORD_NAME.test(kwd)) throw new Error(`Keyword ${kwd} has invalid name`); + }); + if (!def) return; + if (def.$data && !("code" in def || "validate" in def)) throw new Error("$data keyword must have \"code\" or \"validate\" function"); + } + function addRule(keyword, definition, dataType) { + var _a; + const post = definition === null || definition === void 0 ? void 0 : definition.post; + if (dataType && post) throw new Error("keyword with \"post\" flag cannot have \"type\""); + const { RULES } = this; + let ruleGroup = post ? RULES.post : RULES.rules.find(({ type: t }) => t === dataType); + if (!ruleGroup) { + ruleGroup = { + type: dataType, + rules: [] + }; + RULES.rules.push(ruleGroup); + } + RULES.keywords[keyword] = true; + if (!definition) return; + const rule = { + keyword, + definition: { + ...definition, + type: (0, dataType_1.getJSONTypes)(definition.type), + schemaType: (0, dataType_1.getJSONTypes)(definition.schemaType) + } + }; + if (definition.before) addBeforeRule.call(this, ruleGroup, rule, definition.before); + else ruleGroup.rules.push(rule); + RULES.all[keyword] = rule; + (_a = definition.implements) === null || _a === void 0 || _a.forEach((kwd) => this.addKeyword(kwd)); + } + function addBeforeRule(ruleGroup, rule, before) { + const i = ruleGroup.rules.findIndex((_rule) => _rule.keyword === before); + if (i >= 0) ruleGroup.rules.splice(i, 0, rule); + else { + ruleGroup.rules.push(rule); + this.logger.warn(`rule ${before} is not defined`); + } + } + function keywordMetaschema(def) { + let { metaSchema } = def; + if (metaSchema === void 0) return; + if (def.$data && this.opts.$data) metaSchema = schemaOrData(metaSchema); + def.validateSchema = this.compile(metaSchema, true); + } + const $dataRef = { $ref: "https://raw.githubusercontent.com/ajv-validator/ajv/master/lib/refs/data.json#" }; + function schemaOrData(schema) { + return { anyOf: [schema, $dataRef] }; + } +})); + +//#endregion +//#region ../../node_modules/.pnpm/ajv@8.18.0/node_modules/ajv/dist/vocabularies/core/id.js +var require_id = /* @__PURE__ */ __commonJSMin(((exports) => { + Object.defineProperty(exports, "__esModule", { value: true }); + const def = { + keyword: "id", + code() { + throw new Error("NOT SUPPORTED: keyword \"id\", use \"$id\" for schema ID"); + } + }; + exports.default = def; +})); + +//#endregion +//#region ../../node_modules/.pnpm/ajv@8.18.0/node_modules/ajv/dist/vocabularies/core/ref.js +var require_ref = /* @__PURE__ */ __commonJSMin(((exports) => { + Object.defineProperty(exports, "__esModule", { value: true }); + exports.callRef = exports.getValidate = void 0; + const ref_error_1 = require_ref_error(); + const code_1 = require_code(); + const codegen_1 = require_codegen(); + const names_1 = require_names(); + const compile_1 = require_compile(); + const util_1 = require_util(); + const def = { + keyword: "$ref", + schemaType: "string", + code(cxt) { + const { gen, schema: $ref, it } = cxt; + const { baseId, schemaEnv: env, validateName, opts, self } = it; + const { root } = env; + if (($ref === "#" || $ref === "#/") && baseId === root.baseId) return callRootRef(); + const schOrEnv = compile_1.resolveRef.call(self, root, baseId, $ref); + if (schOrEnv === void 0) throw new ref_error_1.default(it.opts.uriResolver, baseId, $ref); + if (schOrEnv instanceof compile_1.SchemaEnv) return callValidate(schOrEnv); + return inlineRefSchema(schOrEnv); + function callRootRef() { + if (env === root) return callRef(cxt, validateName, env, env.$async); + const rootName = gen.scopeValue("root", { ref: root }); + return callRef(cxt, (0, codegen_1._)`${rootName}.validate`, root, root.$async); + } + function callValidate(sch) { + callRef(cxt, getValidate(cxt, sch), sch, sch.$async); + } + function inlineRefSchema(sch) { + const schName = gen.scopeValue("schema", opts.code.source === true ? { + ref: sch, + code: (0, codegen_1.stringify)(sch) + } : { ref: sch }); + const valid = gen.name("valid"); + const schCxt = cxt.subschema({ + schema: sch, + dataTypes: [], + schemaPath: codegen_1.nil, + topSchemaRef: schName, + errSchemaPath: $ref + }, valid); + cxt.mergeEvaluated(schCxt); + cxt.ok(valid); + } + } + }; + function getValidate(cxt, sch) { + const { gen } = cxt; + return sch.validate ? gen.scopeValue("validate", { ref: sch.validate }) : (0, codegen_1._)`${gen.scopeValue("wrapper", { ref: sch })}.validate`; + } + exports.getValidate = getValidate; + function callRef(cxt, v, sch, $async) { + const { gen, it } = cxt; + const { allErrors, schemaEnv: env, opts } = it; + const passCxt = opts.passContext ? names_1.default.this : codegen_1.nil; + if ($async) callAsyncRef(); + else callSyncRef(); + function callAsyncRef() { + if (!env.$async) throw new Error("async schema referenced by sync schema"); + const valid = gen.let("valid"); + gen.try(() => { + gen.code((0, codegen_1._)`await ${(0, code_1.callValidateCode)(cxt, v, passCxt)}`); + addEvaluatedFrom(v); + if (!allErrors) gen.assign(valid, true); + }, (e) => { + gen.if((0, codegen_1._)`!(${e} instanceof ${it.ValidationError})`, () => gen.throw(e)); + addErrorsFrom(e); + if (!allErrors) gen.assign(valid, false); + }); + cxt.ok(valid); + } + function callSyncRef() { + cxt.result((0, code_1.callValidateCode)(cxt, v, passCxt), () => addEvaluatedFrom(v), () => addErrorsFrom(v)); + } + function addErrorsFrom(source) { + const errs = (0, codegen_1._)`${source}.errors`; + gen.assign(names_1.default.vErrors, (0, codegen_1._)`${names_1.default.vErrors} === null ? ${errs} : ${names_1.default.vErrors}.concat(${errs})`); + gen.assign(names_1.default.errors, (0, codegen_1._)`${names_1.default.vErrors}.length`); + } + function addEvaluatedFrom(source) { + var _a; + if (!it.opts.unevaluated) return; + const schEvaluated = (_a = sch === null || sch === void 0 ? void 0 : sch.validate) === null || _a === void 0 ? void 0 : _a.evaluated; + if (it.props !== true) if (schEvaluated && !schEvaluated.dynamicProps) { + if (schEvaluated.props !== void 0) it.props = util_1.mergeEvaluated.props(gen, schEvaluated.props, it.props); + } else { + const props = gen.var("props", (0, codegen_1._)`${source}.evaluated.props`); + it.props = util_1.mergeEvaluated.props(gen, props, it.props, codegen_1.Name); + } + if (it.items !== true) if (schEvaluated && !schEvaluated.dynamicItems) { + if (schEvaluated.items !== void 0) it.items = util_1.mergeEvaluated.items(gen, schEvaluated.items, it.items); + } else { + const items = gen.var("items", (0, codegen_1._)`${source}.evaluated.items`); + it.items = util_1.mergeEvaluated.items(gen, items, it.items, codegen_1.Name); + } + } + } + exports.callRef = callRef; + exports.default = def; +})); + +//#endregion +//#region ../../node_modules/.pnpm/ajv@8.18.0/node_modules/ajv/dist/vocabularies/core/index.js +var require_core$2 = /* @__PURE__ */ __commonJSMin(((exports) => { + Object.defineProperty(exports, "__esModule", { value: true }); + const id_1 = require_id(); + const ref_1 = require_ref(); + const core = [ + "$schema", + "$id", + "$defs", + "$vocabulary", + { keyword: "$comment" }, + "definitions", + id_1.default, + ref_1.default + ]; + exports.default = core; +})); + +//#endregion +//#region ../../node_modules/.pnpm/ajv@8.18.0/node_modules/ajv/dist/vocabularies/validation/limitNumber.js +var require_limitNumber = /* @__PURE__ */ __commonJSMin(((exports) => { + Object.defineProperty(exports, "__esModule", { value: true }); + const codegen_1 = require_codegen(); + const ops = codegen_1.operators; + const KWDs = { + maximum: { + okStr: "<=", + ok: ops.LTE, + fail: ops.GT + }, + minimum: { + okStr: ">=", + ok: ops.GTE, + fail: ops.LT + }, + exclusiveMaximum: { + okStr: "<", + ok: ops.LT, + fail: ops.GTE + }, + exclusiveMinimum: { + okStr: ">", + ok: ops.GT, + fail: ops.LTE + } + }; + const def = { + keyword: Object.keys(KWDs), + type: "number", + schemaType: "number", + $data: true, + error: { + message: ({ keyword, schemaCode }) => (0, codegen_1.str)`must be ${KWDs[keyword].okStr} ${schemaCode}`, + params: ({ keyword, schemaCode }) => (0, codegen_1._)`{comparison: ${KWDs[keyword].okStr}, limit: ${schemaCode}}` + }, + code(cxt) { + const { keyword, data, schemaCode } = cxt; + cxt.fail$data((0, codegen_1._)`${data} ${KWDs[keyword].fail} ${schemaCode} || isNaN(${data})`); + } + }; + exports.default = def; +})); + +//#endregion +//#region ../../node_modules/.pnpm/ajv@8.18.0/node_modules/ajv/dist/vocabularies/validation/multipleOf.js +var require_multipleOf = /* @__PURE__ */ __commonJSMin(((exports) => { + Object.defineProperty(exports, "__esModule", { value: true }); + const codegen_1 = require_codegen(); + const def = { + keyword: "multipleOf", + type: "number", + schemaType: "number", + $data: true, + error: { + message: ({ schemaCode }) => (0, codegen_1.str)`must be multiple of ${schemaCode}`, + params: ({ schemaCode }) => (0, codegen_1._)`{multipleOf: ${schemaCode}}` + }, + code(cxt) { + const { gen, data, schemaCode, it } = cxt; + const prec = it.opts.multipleOfPrecision; + const res = gen.let("res"); + const invalid = prec ? (0, codegen_1._)`Math.abs(Math.round(${res}) - ${res}) > 1e-${prec}` : (0, codegen_1._)`${res} !== parseInt(${res})`; + cxt.fail$data((0, codegen_1._)`(${schemaCode} === 0 || (${res} = ${data}/${schemaCode}, ${invalid}))`); + } + }; + exports.default = def; +})); + +//#endregion +//#region ../../node_modules/.pnpm/ajv@8.18.0/node_modules/ajv/dist/runtime/ucs2length.js +var require_ucs2length = /* @__PURE__ */ __commonJSMin(((exports) => { + Object.defineProperty(exports, "__esModule", { value: true }); + function ucs2length(str) { + const len = str.length; + let length = 0; + let pos = 0; + let value; + while (pos < len) { + length++; + value = str.charCodeAt(pos++); + if (value >= 55296 && value <= 56319 && pos < len) { + value = str.charCodeAt(pos); + if ((value & 64512) === 56320) pos++; + } + } + return length; + } + exports.default = ucs2length; + ucs2length.code = "require(\"ajv/dist/runtime/ucs2length\").default"; +})); + +//#endregion +//#region ../../node_modules/.pnpm/ajv@8.18.0/node_modules/ajv/dist/vocabularies/validation/limitLength.js +var require_limitLength = /* @__PURE__ */ __commonJSMin(((exports) => { + Object.defineProperty(exports, "__esModule", { value: true }); + const codegen_1 = require_codegen(); + const util_1 = require_util(); + const ucs2length_1 = require_ucs2length(); + const def = { + keyword: ["maxLength", "minLength"], + type: "string", + schemaType: "number", + $data: true, + error: { + message({ keyword, schemaCode }) { + const comp = keyword === "maxLength" ? "more" : "fewer"; + return (0, codegen_1.str)`must NOT have ${comp} than ${schemaCode} characters`; + }, + params: ({ schemaCode }) => (0, codegen_1._)`{limit: ${schemaCode}}` + }, + code(cxt) { + const { keyword, data, schemaCode, it } = cxt; + const op = keyword === "maxLength" ? codegen_1.operators.GT : codegen_1.operators.LT; + const len = it.opts.unicode === false ? (0, codegen_1._)`${data}.length` : (0, codegen_1._)`${(0, util_1.useFunc)(cxt.gen, ucs2length_1.default)}(${data})`; + cxt.fail$data((0, codegen_1._)`${len} ${op} ${schemaCode}`); + } + }; + exports.default = def; +})); + +//#endregion +//#region ../../node_modules/.pnpm/ajv@8.18.0/node_modules/ajv/dist/vocabularies/validation/pattern.js +var require_pattern = /* @__PURE__ */ __commonJSMin(((exports) => { + Object.defineProperty(exports, "__esModule", { value: true }); + const code_1 = require_code(); + const util_1 = require_util(); + const codegen_1 = require_codegen(); + const def = { + keyword: "pattern", + type: "string", + schemaType: "string", + $data: true, + error: { + message: ({ schemaCode }) => (0, codegen_1.str)`must match pattern "${schemaCode}"`, + params: ({ schemaCode }) => (0, codegen_1._)`{pattern: ${schemaCode}}` + }, + code(cxt) { + const { gen, data, $data, schema, schemaCode, it } = cxt; + const u = it.opts.unicodeRegExp ? "u" : ""; + if ($data) { + const { regExp } = it.opts.code; + const regExpCode = regExp.code === "new RegExp" ? (0, codegen_1._)`new RegExp` : (0, util_1.useFunc)(gen, regExp); + const valid = gen.let("valid"); + gen.try(() => gen.assign(valid, (0, codegen_1._)`${regExpCode}(${schemaCode}, ${u}).test(${data})`), () => gen.assign(valid, false)); + cxt.fail$data((0, codegen_1._)`!${valid}`); + } else { + const regExp = (0, code_1.usePattern)(cxt, schema); + cxt.fail$data((0, codegen_1._)`!${regExp}.test(${data})`); + } + } + }; + exports.default = def; +})); + +//#endregion +//#region ../../node_modules/.pnpm/ajv@8.18.0/node_modules/ajv/dist/vocabularies/validation/limitProperties.js +var require_limitProperties = /* @__PURE__ */ __commonJSMin(((exports) => { + Object.defineProperty(exports, "__esModule", { value: true }); + const codegen_1 = require_codegen(); + const def = { + keyword: ["maxProperties", "minProperties"], + type: "object", + schemaType: "number", + $data: true, + error: { + message({ keyword, schemaCode }) { + const comp = keyword === "maxProperties" ? "more" : "fewer"; + return (0, codegen_1.str)`must NOT have ${comp} than ${schemaCode} properties`; + }, + params: ({ schemaCode }) => (0, codegen_1._)`{limit: ${schemaCode}}` + }, + code(cxt) { + const { keyword, data, schemaCode } = cxt; + const op = keyword === "maxProperties" ? codegen_1.operators.GT : codegen_1.operators.LT; + cxt.fail$data((0, codegen_1._)`Object.keys(${data}).length ${op} ${schemaCode}`); + } + }; + exports.default = def; +})); + +//#endregion +//#region ../../node_modules/.pnpm/ajv@8.18.0/node_modules/ajv/dist/vocabularies/validation/required.js +var require_required = /* @__PURE__ */ __commonJSMin(((exports) => { + Object.defineProperty(exports, "__esModule", { value: true }); + const code_1 = require_code(); + const codegen_1 = require_codegen(); + const util_1 = require_util(); + const def = { + keyword: "required", + type: "object", + schemaType: "array", + $data: true, + error: { + message: ({ params: { missingProperty } }) => (0, codegen_1.str)`must have required property '${missingProperty}'`, + params: ({ params: { missingProperty } }) => (0, codegen_1._)`{missingProperty: ${missingProperty}}` + }, + code(cxt) { + const { gen, schema, schemaCode, data, $data, it } = cxt; + const { opts } = it; + if (!$data && schema.length === 0) return; + const useLoop = schema.length >= opts.loopRequired; + if (it.allErrors) allErrorsMode(); + else exitOnErrorMode(); + if (opts.strictRequired) { + const props = cxt.parentSchema.properties; + const { definedProperties } = cxt.it; + for (const requiredKey of schema) if ((props === null || props === void 0 ? void 0 : props[requiredKey]) === void 0 && !definedProperties.has(requiredKey)) { + const msg = `required property "${requiredKey}" is not defined at "${it.schemaEnv.baseId + it.errSchemaPath}" (strictRequired)`; + (0, util_1.checkStrictMode)(it, msg, it.opts.strictRequired); + } + } + function allErrorsMode() { + if (useLoop || $data) cxt.block$data(codegen_1.nil, loopAllRequired); + else for (const prop of schema) (0, code_1.checkReportMissingProp)(cxt, prop); + } + function exitOnErrorMode() { + const missing = gen.let("missing"); + if (useLoop || $data) { + const valid = gen.let("valid", true); + cxt.block$data(valid, () => loopUntilMissing(missing, valid)); + cxt.ok(valid); + } else { + gen.if((0, code_1.checkMissingProp)(cxt, schema, missing)); + (0, code_1.reportMissingProp)(cxt, missing); + gen.else(); + } + } + function loopAllRequired() { + gen.forOf("prop", schemaCode, (prop) => { + cxt.setParams({ missingProperty: prop }); + gen.if((0, code_1.noPropertyInData)(gen, data, prop, opts.ownProperties), () => cxt.error()); + }); + } + function loopUntilMissing(missing, valid) { + cxt.setParams({ missingProperty: missing }); + gen.forOf(missing, schemaCode, () => { + gen.assign(valid, (0, code_1.propertyInData)(gen, data, missing, opts.ownProperties)); + gen.if((0, codegen_1.not)(valid), () => { + cxt.error(); + gen.break(); + }); + }, codegen_1.nil); + } + } + }; + exports.default = def; +})); + +//#endregion +//#region ../../node_modules/.pnpm/ajv@8.18.0/node_modules/ajv/dist/vocabularies/validation/limitItems.js +var require_limitItems = /* @__PURE__ */ __commonJSMin(((exports) => { + Object.defineProperty(exports, "__esModule", { value: true }); + const codegen_1 = require_codegen(); + const def = { + keyword: ["maxItems", "minItems"], + type: "array", + schemaType: "number", + $data: true, + error: { + message({ keyword, schemaCode }) { + const comp = keyword === "maxItems" ? "more" : "fewer"; + return (0, codegen_1.str)`must NOT have ${comp} than ${schemaCode} items`; + }, + params: ({ schemaCode }) => (0, codegen_1._)`{limit: ${schemaCode}}` + }, + code(cxt) { + const { keyword, data, schemaCode } = cxt; + const op = keyword === "maxItems" ? codegen_1.operators.GT : codegen_1.operators.LT; + cxt.fail$data((0, codegen_1._)`${data}.length ${op} ${schemaCode}`); + } + }; + exports.default = def; +})); + +//#endregion +//#region ../../node_modules/.pnpm/ajv@8.18.0/node_modules/ajv/dist/runtime/equal.js +var require_equal = /* @__PURE__ */ __commonJSMin(((exports) => { + Object.defineProperty(exports, "__esModule", { value: true }); + const equal = require_fast_deep_equal(); + equal.code = "require(\"ajv/dist/runtime/equal\").default"; + exports.default = equal; +})); + +//#endregion +//#region ../../node_modules/.pnpm/ajv@8.18.0/node_modules/ajv/dist/vocabularies/validation/uniqueItems.js +var require_uniqueItems = /* @__PURE__ */ __commonJSMin(((exports) => { + Object.defineProperty(exports, "__esModule", { value: true }); + const dataType_1 = require_dataType(); + const codegen_1 = require_codegen(); + const util_1 = require_util(); + const equal_1 = require_equal(); + const def = { + keyword: "uniqueItems", + type: "array", + schemaType: "boolean", + $data: true, + error: { + message: ({ params: { i, j } }) => (0, codegen_1.str)`must NOT have duplicate items (items ## ${j} and ${i} are identical)`, + params: ({ params: { i, j } }) => (0, codegen_1._)`{i: ${i}, j: ${j}}` + }, + code(cxt) { + const { gen, data, $data, schema, parentSchema, schemaCode, it } = cxt; + if (!$data && !schema) return; + const valid = gen.let("valid"); + const itemTypes = parentSchema.items ? (0, dataType_1.getSchemaTypes)(parentSchema.items) : []; + cxt.block$data(valid, validateUniqueItems, (0, codegen_1._)`${schemaCode} === false`); + cxt.ok(valid); + function validateUniqueItems() { + const i = gen.let("i", (0, codegen_1._)`${data}.length`); + const j = gen.let("j"); + cxt.setParams({ + i, + j + }); + gen.assign(valid, true); + gen.if((0, codegen_1._)`${i} > 1`, () => (canOptimize() ? loopN : loopN2)(i, j)); + } + function canOptimize() { + return itemTypes.length > 0 && !itemTypes.some((t) => t === "object" || t === "array"); + } + function loopN(i, j) { + const item = gen.name("item"); + const wrongType = (0, dataType_1.checkDataTypes)(itemTypes, item, it.opts.strictNumbers, dataType_1.DataType.Wrong); + const indices = gen.const("indices", (0, codegen_1._)`{}`); + gen.for((0, codegen_1._)`;${i}--;`, () => { + gen.let(item, (0, codegen_1._)`${data}[${i}]`); + gen.if(wrongType, (0, codegen_1._)`continue`); + if (itemTypes.length > 1) gen.if((0, codegen_1._)`typeof ${item} == "string"`, (0, codegen_1._)`${item} += "_"`); + gen.if((0, codegen_1._)`typeof ${indices}[${item}] == "number"`, () => { + gen.assign(j, (0, codegen_1._)`${indices}[${item}]`); + cxt.error(); + gen.assign(valid, false).break(); + }).code((0, codegen_1._)`${indices}[${item}] = ${i}`); + }); + } + function loopN2(i, j) { + const eql = (0, util_1.useFunc)(gen, equal_1.default); + const outer = gen.name("outer"); + gen.label(outer).for((0, codegen_1._)`;${i}--;`, () => gen.for((0, codegen_1._)`${j} = ${i}; ${j}--;`, () => gen.if((0, codegen_1._)`${eql}(${data}[${i}], ${data}[${j}])`, () => { + cxt.error(); + gen.assign(valid, false).break(outer); + }))); + } + } + }; + exports.default = def; +})); + +//#endregion +//#region ../../node_modules/.pnpm/ajv@8.18.0/node_modules/ajv/dist/vocabularies/validation/const.js +var require_const = /* @__PURE__ */ __commonJSMin(((exports) => { + Object.defineProperty(exports, "__esModule", { value: true }); + const codegen_1 = require_codegen(); + const util_1 = require_util(); + const equal_1 = require_equal(); + const def = { + keyword: "const", + $data: true, + error: { + message: "must be equal to constant", + params: ({ schemaCode }) => (0, codegen_1._)`{allowedValue: ${schemaCode}}` + }, + code(cxt) { + const { gen, data, $data, schemaCode, schema } = cxt; + if ($data || schema && typeof schema == "object") cxt.fail$data((0, codegen_1._)`!${(0, util_1.useFunc)(gen, equal_1.default)}(${data}, ${schemaCode})`); + else cxt.fail((0, codegen_1._)`${schema} !== ${data}`); + } + }; + exports.default = def; +})); + +//#endregion +//#region ../../node_modules/.pnpm/ajv@8.18.0/node_modules/ajv/dist/vocabularies/validation/enum.js +var require_enum = /* @__PURE__ */ __commonJSMin(((exports) => { + Object.defineProperty(exports, "__esModule", { value: true }); + const codegen_1 = require_codegen(); + const util_1 = require_util(); + const equal_1 = require_equal(); + const def = { + keyword: "enum", + schemaType: "array", + $data: true, + error: { + message: "must be equal to one of the allowed values", + params: ({ schemaCode }) => (0, codegen_1._)`{allowedValues: ${schemaCode}}` + }, + code(cxt) { + const { gen, data, $data, schema, schemaCode, it } = cxt; + if (!$data && schema.length === 0) throw new Error("enum must have non-empty array"); + const useLoop = schema.length >= it.opts.loopEnum; + let eql; + const getEql = () => eql !== null && eql !== void 0 ? eql : eql = (0, util_1.useFunc)(gen, equal_1.default); + let valid; + if (useLoop || $data) { + valid = gen.let("valid"); + cxt.block$data(valid, loopEnum); + } else { + /* istanbul ignore if */ + if (!Array.isArray(schema)) throw new Error("ajv implementation error"); + const vSchema = gen.const("vSchema", schemaCode); + valid = (0, codegen_1.or)(...schema.map((_x, i) => equalCode(vSchema, i))); + } + cxt.pass(valid); + function loopEnum() { + gen.assign(valid, false); + gen.forOf("v", schemaCode, (v) => gen.if((0, codegen_1._)`${getEql()}(${data}, ${v})`, () => gen.assign(valid, true).break())); + } + function equalCode(vSchema, i) { + const sch = schema[i]; + return typeof sch === "object" && sch !== null ? (0, codegen_1._)`${getEql()}(${data}, ${vSchema}[${i}])` : (0, codegen_1._)`${data} === ${sch}`; + } + } + }; + exports.default = def; +})); + +//#endregion +//#region ../../node_modules/.pnpm/ajv@8.18.0/node_modules/ajv/dist/vocabularies/validation/index.js +var require_validation$2 = /* @__PURE__ */ __commonJSMin(((exports) => { + Object.defineProperty(exports, "__esModule", { value: true }); + const limitNumber_1 = require_limitNumber(); + const multipleOf_1 = require_multipleOf(); + const limitLength_1 = require_limitLength(); + const pattern_1 = require_pattern(); + const limitProperties_1 = require_limitProperties(); + const required_1 = require_required(); + const limitItems_1 = require_limitItems(); + const uniqueItems_1 = require_uniqueItems(); + const const_1 = require_const(); + const enum_1 = require_enum(); + const validation = [ + limitNumber_1.default, + multipleOf_1.default, + limitLength_1.default, + pattern_1.default, + limitProperties_1.default, + required_1.default, + limitItems_1.default, + uniqueItems_1.default, + { + keyword: "type", + schemaType: ["string", "array"] + }, + { + keyword: "nullable", + schemaType: "boolean" + }, + const_1.default, + enum_1.default + ]; + exports.default = validation; +})); + +//#endregion +//#region ../../node_modules/.pnpm/ajv@8.18.0/node_modules/ajv/dist/vocabularies/applicator/additionalItems.js +var require_additionalItems = /* @__PURE__ */ __commonJSMin(((exports) => { + Object.defineProperty(exports, "__esModule", { value: true }); + exports.validateAdditionalItems = void 0; + const codegen_1 = require_codegen(); + const util_1 = require_util(); + const def = { + keyword: "additionalItems", + type: "array", + schemaType: ["boolean", "object"], + before: "uniqueItems", + error: { + message: ({ params: { len } }) => (0, codegen_1.str)`must NOT have more than ${len} items`, + params: ({ params: { len } }) => (0, codegen_1._)`{limit: ${len}}` + }, + code(cxt) { + const { parentSchema, it } = cxt; + const { items } = parentSchema; + if (!Array.isArray(items)) { + (0, util_1.checkStrictMode)(it, "\"additionalItems\" is ignored when \"items\" is not an array of schemas"); + return; + } + validateAdditionalItems(cxt, items); + } + }; + function validateAdditionalItems(cxt, items) { + const { gen, schema, data, keyword, it } = cxt; + it.items = true; + const len = gen.const("len", (0, codegen_1._)`${data}.length`); + if (schema === false) { + cxt.setParams({ len: items.length }); + cxt.pass((0, codegen_1._)`${len} <= ${items.length}`); + } else if (typeof schema == "object" && !(0, util_1.alwaysValidSchema)(it, schema)) { + const valid = gen.var("valid", (0, codegen_1._)`${len} <= ${items.length}`); + gen.if((0, codegen_1.not)(valid), () => validateItems(valid)); + cxt.ok(valid); + } + function validateItems(valid) { + gen.forRange("i", items.length, len, (i) => { + cxt.subschema({ + keyword, + dataProp: i, + dataPropType: util_1.Type.Num + }, valid); + if (!it.allErrors) gen.if((0, codegen_1.not)(valid), () => gen.break()); + }); + } + } + exports.validateAdditionalItems = validateAdditionalItems; + exports.default = def; +})); + +//#endregion +//#region ../../node_modules/.pnpm/ajv@8.18.0/node_modules/ajv/dist/vocabularies/applicator/items.js +var require_items = /* @__PURE__ */ __commonJSMin(((exports) => { + Object.defineProperty(exports, "__esModule", { value: true }); + exports.validateTuple = void 0; + const codegen_1 = require_codegen(); + const util_1 = require_util(); + const code_1 = require_code(); + const def = { + keyword: "items", + type: "array", + schemaType: [ + "object", + "array", + "boolean" + ], + before: "uniqueItems", + code(cxt) { + const { schema, it } = cxt; + if (Array.isArray(schema)) return validateTuple(cxt, "additionalItems", schema); + it.items = true; + if ((0, util_1.alwaysValidSchema)(it, schema)) return; + cxt.ok((0, code_1.validateArray)(cxt)); + } + }; + function validateTuple(cxt, extraItems, schArr = cxt.schema) { + const { gen, parentSchema, data, keyword, it } = cxt; + checkStrictTuple(parentSchema); + if (it.opts.unevaluated && schArr.length && it.items !== true) it.items = util_1.mergeEvaluated.items(gen, schArr.length, it.items); + const valid = gen.name("valid"); + const len = gen.const("len", (0, codegen_1._)`${data}.length`); + schArr.forEach((sch, i) => { + if ((0, util_1.alwaysValidSchema)(it, sch)) return; + gen.if((0, codegen_1._)`${len} > ${i}`, () => cxt.subschema({ + keyword, + schemaProp: i, + dataProp: i + }, valid)); + cxt.ok(valid); + }); + function checkStrictTuple(sch) { + const { opts, errSchemaPath } = it; + const l = schArr.length; + const fullTuple = l === sch.minItems && (l === sch.maxItems || sch[extraItems] === false); + if (opts.strictTuples && !fullTuple) { + const msg = `"${keyword}" is ${l}-tuple, but minItems or maxItems/${extraItems} are not specified or different at path "${errSchemaPath}"`; + (0, util_1.checkStrictMode)(it, msg, opts.strictTuples); + } + } + } + exports.validateTuple = validateTuple; + exports.default = def; +})); + +//#endregion +//#region ../../node_modules/.pnpm/ajv@8.18.0/node_modules/ajv/dist/vocabularies/applicator/prefixItems.js +var require_prefixItems = /* @__PURE__ */ __commonJSMin(((exports) => { + Object.defineProperty(exports, "__esModule", { value: true }); + const items_1 = require_items(); + const def = { + keyword: "prefixItems", + type: "array", + schemaType: ["array"], + before: "uniqueItems", + code: (cxt) => (0, items_1.validateTuple)(cxt, "items") + }; + exports.default = def; +})); + +//#endregion +//#region ../../node_modules/.pnpm/ajv@8.18.0/node_modules/ajv/dist/vocabularies/applicator/items2020.js +var require_items2020 = /* @__PURE__ */ __commonJSMin(((exports) => { + Object.defineProperty(exports, "__esModule", { value: true }); + const codegen_1 = require_codegen(); + const util_1 = require_util(); + const code_1 = require_code(); + const additionalItems_1 = require_additionalItems(); + const def = { + keyword: "items", + type: "array", + schemaType: ["object", "boolean"], + before: "uniqueItems", + error: { + message: ({ params: { len } }) => (0, codegen_1.str)`must NOT have more than ${len} items`, + params: ({ params: { len } }) => (0, codegen_1._)`{limit: ${len}}` + }, + code(cxt) { + const { schema, parentSchema, it } = cxt; + const { prefixItems } = parentSchema; + it.items = true; + if ((0, util_1.alwaysValidSchema)(it, schema)) return; + if (prefixItems) (0, additionalItems_1.validateAdditionalItems)(cxt, prefixItems); + else cxt.ok((0, code_1.validateArray)(cxt)); + } + }; + exports.default = def; +})); + +//#endregion +//#region ../../node_modules/.pnpm/ajv@8.18.0/node_modules/ajv/dist/vocabularies/applicator/contains.js +var require_contains = /* @__PURE__ */ __commonJSMin(((exports) => { + Object.defineProperty(exports, "__esModule", { value: true }); + const codegen_1 = require_codegen(); + const util_1 = require_util(); + const def = { + keyword: "contains", + type: "array", + schemaType: ["object", "boolean"], + before: "uniqueItems", + trackErrors: true, + error: { + message: ({ params: { min, max } }) => max === void 0 ? (0, codegen_1.str)`must contain at least ${min} valid item(s)` : (0, codegen_1.str)`must contain at least ${min} and no more than ${max} valid item(s)`, + params: ({ params: { min, max } }) => max === void 0 ? (0, codegen_1._)`{minContains: ${min}}` : (0, codegen_1._)`{minContains: ${min}, maxContains: ${max}}` + }, + code(cxt) { + const { gen, schema, parentSchema, data, it } = cxt; + let min; + let max; + const { minContains, maxContains } = parentSchema; + if (it.opts.next) { + min = minContains === void 0 ? 1 : minContains; + max = maxContains; + } else min = 1; + const len = gen.const("len", (0, codegen_1._)`${data}.length`); + cxt.setParams({ + min, + max + }); + if (max === void 0 && min === 0) { + (0, util_1.checkStrictMode)(it, `"minContains" == 0 without "maxContains": "contains" keyword ignored`); + return; + } + if (max !== void 0 && min > max) { + (0, util_1.checkStrictMode)(it, `"minContains" > "maxContains" is always invalid`); + cxt.fail(); + return; + } + if ((0, util_1.alwaysValidSchema)(it, schema)) { + let cond = (0, codegen_1._)`${len} >= ${min}`; + if (max !== void 0) cond = (0, codegen_1._)`${cond} && ${len} <= ${max}`; + cxt.pass(cond); + return; + } + it.items = true; + const valid = gen.name("valid"); + if (max === void 0 && min === 1) validateItems(valid, () => gen.if(valid, () => gen.break())); + else if (min === 0) { + gen.let(valid, true); + if (max !== void 0) gen.if((0, codegen_1._)`${data}.length > 0`, validateItemsWithCount); + } else { + gen.let(valid, false); + validateItemsWithCount(); + } + cxt.result(valid, () => cxt.reset()); + function validateItemsWithCount() { + const schValid = gen.name("_valid"); + const count = gen.let("count", 0); + validateItems(schValid, () => gen.if(schValid, () => checkLimits(count))); + } + function validateItems(_valid, block) { + gen.forRange("i", 0, len, (i) => { + cxt.subschema({ + keyword: "contains", + dataProp: i, + dataPropType: util_1.Type.Num, + compositeRule: true + }, _valid); + block(); + }); + } + function checkLimits(count) { + gen.code((0, codegen_1._)`${count}++`); + if (max === void 0) gen.if((0, codegen_1._)`${count} >= ${min}`, () => gen.assign(valid, true).break()); + else { + gen.if((0, codegen_1._)`${count} > ${max}`, () => gen.assign(valid, false).break()); + if (min === 1) gen.assign(valid, true); + else gen.if((0, codegen_1._)`${count} >= ${min}`, () => gen.assign(valid, true)); + } + } + } + }; + exports.default = def; +})); + +//#endregion +//#region ../../node_modules/.pnpm/ajv@8.18.0/node_modules/ajv/dist/vocabularies/applicator/dependencies.js +var require_dependencies = /* @__PURE__ */ __commonJSMin(((exports) => { + Object.defineProperty(exports, "__esModule", { value: true }); + exports.validateSchemaDeps = exports.validatePropertyDeps = exports.error = void 0; + const codegen_1 = require_codegen(); + const util_1 = require_util(); + const code_1 = require_code(); + exports.error = { + message: ({ params: { property, depsCount, deps } }) => { + const property_ies = depsCount === 1 ? "property" : "properties"; + return (0, codegen_1.str)`must have ${property_ies} ${deps} when property ${property} is present`; + }, + params: ({ params: { property, depsCount, deps, missingProperty } }) => (0, codegen_1._)`{property: ${property}, + missingProperty: ${missingProperty}, + depsCount: ${depsCount}, + deps: ${deps}}` + }; + const def = { + keyword: "dependencies", + type: "object", + schemaType: "object", + error: exports.error, + code(cxt) { + const [propDeps, schDeps] = splitDependencies(cxt); + validatePropertyDeps(cxt, propDeps); + validateSchemaDeps(cxt, schDeps); + } + }; + function splitDependencies({ schema }) { + const propertyDeps = {}; + const schemaDeps = {}; + for (const key in schema) { + if (key === "__proto__") continue; + const deps = Array.isArray(schema[key]) ? propertyDeps : schemaDeps; + deps[key] = schema[key]; + } + return [propertyDeps, schemaDeps]; + } + function validatePropertyDeps(cxt, propertyDeps = cxt.schema) { + const { gen, data, it } = cxt; + if (Object.keys(propertyDeps).length === 0) return; + const missing = gen.let("missing"); + for (const prop in propertyDeps) { + const deps = propertyDeps[prop]; + if (deps.length === 0) continue; + const hasProperty = (0, code_1.propertyInData)(gen, data, prop, it.opts.ownProperties); + cxt.setParams({ + property: prop, + depsCount: deps.length, + deps: deps.join(", ") + }); + if (it.allErrors) gen.if(hasProperty, () => { + for (const depProp of deps) (0, code_1.checkReportMissingProp)(cxt, depProp); + }); + else { + gen.if((0, codegen_1._)`${hasProperty} && (${(0, code_1.checkMissingProp)(cxt, deps, missing)})`); + (0, code_1.reportMissingProp)(cxt, missing); + gen.else(); + } + } + } + exports.validatePropertyDeps = validatePropertyDeps; + function validateSchemaDeps(cxt, schemaDeps = cxt.schema) { + const { gen, data, keyword, it } = cxt; + const valid = gen.name("valid"); + for (const prop in schemaDeps) { + if ((0, util_1.alwaysValidSchema)(it, schemaDeps[prop])) continue; + gen.if((0, code_1.propertyInData)(gen, data, prop, it.opts.ownProperties), () => { + const schCxt = cxt.subschema({ + keyword, + schemaProp: prop + }, valid); + cxt.mergeValidEvaluated(schCxt, valid); + }, () => gen.var(valid, true)); + cxt.ok(valid); + } + } + exports.validateSchemaDeps = validateSchemaDeps; + exports.default = def; +})); + +//#endregion +//#region ../../node_modules/.pnpm/ajv@8.18.0/node_modules/ajv/dist/vocabularies/applicator/propertyNames.js +var require_propertyNames = /* @__PURE__ */ __commonJSMin(((exports) => { + Object.defineProperty(exports, "__esModule", { value: true }); + const codegen_1 = require_codegen(); + const util_1 = require_util(); + const def = { + keyword: "propertyNames", + type: "object", + schemaType: ["object", "boolean"], + error: { + message: "property name must be valid", + params: ({ params }) => (0, codegen_1._)`{propertyName: ${params.propertyName}}` + }, + code(cxt) { + const { gen, schema, data, it } = cxt; + if ((0, util_1.alwaysValidSchema)(it, schema)) return; + const valid = gen.name("valid"); + gen.forIn("key", data, (key) => { + cxt.setParams({ propertyName: key }); + cxt.subschema({ + keyword: "propertyNames", + data: key, + dataTypes: ["string"], + propertyName: key, + compositeRule: true + }, valid); + gen.if((0, codegen_1.not)(valid), () => { + cxt.error(true); + if (!it.allErrors) gen.break(); + }); + }); + cxt.ok(valid); + } + }; + exports.default = def; +})); + +//#endregion +//#region ../../node_modules/.pnpm/ajv@8.18.0/node_modules/ajv/dist/vocabularies/applicator/additionalProperties.js +var require_additionalProperties = /* @__PURE__ */ __commonJSMin(((exports) => { + Object.defineProperty(exports, "__esModule", { value: true }); + const code_1 = require_code(); + const codegen_1 = require_codegen(); + const names_1 = require_names(); + const util_1 = require_util(); + const def = { + keyword: "additionalProperties", + type: ["object"], + schemaType: ["boolean", "object"], + allowUndefined: true, + trackErrors: true, + error: { + message: "must NOT have additional properties", + params: ({ params }) => (0, codegen_1._)`{additionalProperty: ${params.additionalProperty}}` + }, + code(cxt) { + const { gen, schema, parentSchema, data, errsCount, it } = cxt; + /* istanbul ignore if */ + if (!errsCount) throw new Error("ajv implementation error"); + const { allErrors, opts } = it; + it.props = true; + if (opts.removeAdditional !== "all" && (0, util_1.alwaysValidSchema)(it, schema)) return; + const props = (0, code_1.allSchemaProperties)(parentSchema.properties); + const patProps = (0, code_1.allSchemaProperties)(parentSchema.patternProperties); + checkAdditionalProperties(); + cxt.ok((0, codegen_1._)`${errsCount} === ${names_1.default.errors}`); + function checkAdditionalProperties() { + gen.forIn("key", data, (key) => { + if (!props.length && !patProps.length) additionalPropertyCode(key); + else gen.if(isAdditional(key), () => additionalPropertyCode(key)); + }); + } + function isAdditional(key) { + let definedProp; + if (props.length > 8) { + const propsSchema = (0, util_1.schemaRefOrVal)(it, parentSchema.properties, "properties"); + definedProp = (0, code_1.isOwnProperty)(gen, propsSchema, key); + } else if (props.length) definedProp = (0, codegen_1.or)(...props.map((p) => (0, codegen_1._)`${key} === ${p}`)); + else definedProp = codegen_1.nil; + if (patProps.length) definedProp = (0, codegen_1.or)(definedProp, ...patProps.map((p) => (0, codegen_1._)`${(0, code_1.usePattern)(cxt, p)}.test(${key})`)); + return (0, codegen_1.not)(definedProp); + } + function deleteAdditional(key) { + gen.code((0, codegen_1._)`delete ${data}[${key}]`); + } + function additionalPropertyCode(key) { + if (opts.removeAdditional === "all" || opts.removeAdditional && schema === false) { + deleteAdditional(key); + return; + } + if (schema === false) { + cxt.setParams({ additionalProperty: key }); + cxt.error(); + if (!allErrors) gen.break(); + return; + } + if (typeof schema == "object" && !(0, util_1.alwaysValidSchema)(it, schema)) { + const valid = gen.name("valid"); + if (opts.removeAdditional === "failing") { + applyAdditionalSchema(key, valid, false); + gen.if((0, codegen_1.not)(valid), () => { + cxt.reset(); + deleteAdditional(key); + }); + } else { + applyAdditionalSchema(key, valid); + if (!allErrors) gen.if((0, codegen_1.not)(valid), () => gen.break()); + } + } + } + function applyAdditionalSchema(key, valid, errors) { + const subschema = { + keyword: "additionalProperties", + dataProp: key, + dataPropType: util_1.Type.Str + }; + if (errors === false) Object.assign(subschema, { + compositeRule: true, + createErrors: false, + allErrors: false + }); + cxt.subschema(subschema, valid); + } + } + }; + exports.default = def; +})); + +//#endregion +//#region ../../node_modules/.pnpm/ajv@8.18.0/node_modules/ajv/dist/vocabularies/applicator/properties.js +var require_properties = /* @__PURE__ */ __commonJSMin(((exports) => { + Object.defineProperty(exports, "__esModule", { value: true }); + const validate_1 = require_validate(); + const code_1 = require_code(); + const util_1 = require_util(); + const additionalProperties_1 = require_additionalProperties(); + const def = { + keyword: "properties", + type: "object", + schemaType: "object", + code(cxt) { + const { gen, schema, parentSchema, data, it } = cxt; + if (it.opts.removeAdditional === "all" && parentSchema.additionalProperties === void 0) additionalProperties_1.default.code(new validate_1.KeywordCxt(it, additionalProperties_1.default, "additionalProperties")); + const allProps = (0, code_1.allSchemaProperties)(schema); + for (const prop of allProps) it.definedProperties.add(prop); + if (it.opts.unevaluated && allProps.length && it.props !== true) it.props = util_1.mergeEvaluated.props(gen, (0, util_1.toHash)(allProps), it.props); + const properties = allProps.filter((p) => !(0, util_1.alwaysValidSchema)(it, schema[p])); + if (properties.length === 0) return; + const valid = gen.name("valid"); + for (const prop of properties) { + if (hasDefault(prop)) applyPropertySchema(prop); + else { + gen.if((0, code_1.propertyInData)(gen, data, prop, it.opts.ownProperties)); + applyPropertySchema(prop); + if (!it.allErrors) gen.else().var(valid, true); + gen.endIf(); + } + cxt.it.definedProperties.add(prop); + cxt.ok(valid); + } + function hasDefault(prop) { + return it.opts.useDefaults && !it.compositeRule && schema[prop].default !== void 0; + } + function applyPropertySchema(prop) { + cxt.subschema({ + keyword: "properties", + schemaProp: prop, + dataProp: prop + }, valid); + } + } + }; + exports.default = def; +})); + +//#endregion +//#region ../../node_modules/.pnpm/ajv@8.18.0/node_modules/ajv/dist/vocabularies/applicator/patternProperties.js +var require_patternProperties = /* @__PURE__ */ __commonJSMin(((exports) => { + Object.defineProperty(exports, "__esModule", { value: true }); + const code_1 = require_code(); + const codegen_1 = require_codegen(); + const util_1 = require_util(); + const util_2 = require_util(); + const def = { + keyword: "patternProperties", + type: "object", + schemaType: "object", + code(cxt) { + const { gen, schema, data, parentSchema, it } = cxt; + const { opts } = it; + const patterns = (0, code_1.allSchemaProperties)(schema); + const alwaysValidPatterns = patterns.filter((p) => (0, util_1.alwaysValidSchema)(it, schema[p])); + if (patterns.length === 0 || alwaysValidPatterns.length === patterns.length && (!it.opts.unevaluated || it.props === true)) return; + const checkProperties = opts.strictSchema && !opts.allowMatchingProperties && parentSchema.properties; + const valid = gen.name("valid"); + if (it.props !== true && !(it.props instanceof codegen_1.Name)) it.props = (0, util_2.evaluatedPropsToName)(gen, it.props); + const { props } = it; + validatePatternProperties(); + function validatePatternProperties() { + for (const pat of patterns) { + if (checkProperties) checkMatchingProperties(pat); + if (it.allErrors) validateProperties(pat); + else { + gen.var(valid, true); + validateProperties(pat); + gen.if(valid); + } + } + } + function checkMatchingProperties(pat) { + for (const prop in checkProperties) if (new RegExp(pat).test(prop)) (0, util_1.checkStrictMode)(it, `property ${prop} matches pattern ${pat} (use allowMatchingProperties)`); + } + function validateProperties(pat) { + gen.forIn("key", data, (key) => { + gen.if((0, codegen_1._)`${(0, code_1.usePattern)(cxt, pat)}.test(${key})`, () => { + const alwaysValid = alwaysValidPatterns.includes(pat); + if (!alwaysValid) cxt.subschema({ + keyword: "patternProperties", + schemaProp: pat, + dataProp: key, + dataPropType: util_2.Type.Str + }, valid); + if (it.opts.unevaluated && props !== true) gen.assign((0, codegen_1._)`${props}[${key}]`, true); + else if (!alwaysValid && !it.allErrors) gen.if((0, codegen_1.not)(valid), () => gen.break()); + }); + }); + } + } + }; + exports.default = def; +})); + +//#endregion +//#region ../../node_modules/.pnpm/ajv@8.18.0/node_modules/ajv/dist/vocabularies/applicator/not.js +var require_not = /* @__PURE__ */ __commonJSMin(((exports) => { + Object.defineProperty(exports, "__esModule", { value: true }); + const util_1 = require_util(); + const def = { + keyword: "not", + schemaType: ["object", "boolean"], + trackErrors: true, + code(cxt) { + const { gen, schema, it } = cxt; + if ((0, util_1.alwaysValidSchema)(it, schema)) { + cxt.fail(); + return; + } + const valid = gen.name("valid"); + cxt.subschema({ + keyword: "not", + compositeRule: true, + createErrors: false, + allErrors: false + }, valid); + cxt.failResult(valid, () => cxt.reset(), () => cxt.error()); + }, + error: { message: "must NOT be valid" } + }; + exports.default = def; +})); + +//#endregion +//#region ../../node_modules/.pnpm/ajv@8.18.0/node_modules/ajv/dist/vocabularies/applicator/anyOf.js +var require_anyOf = /* @__PURE__ */ __commonJSMin(((exports) => { + Object.defineProperty(exports, "__esModule", { value: true }); + const def = { + keyword: "anyOf", + schemaType: "array", + trackErrors: true, + code: require_code().validateUnion, + error: { message: "must match a schema in anyOf" } + }; + exports.default = def; +})); + +//#endregion +//#region ../../node_modules/.pnpm/ajv@8.18.0/node_modules/ajv/dist/vocabularies/applicator/oneOf.js +var require_oneOf = /* @__PURE__ */ __commonJSMin(((exports) => { + Object.defineProperty(exports, "__esModule", { value: true }); + const codegen_1 = require_codegen(); + const util_1 = require_util(); + const def = { + keyword: "oneOf", + schemaType: "array", + trackErrors: true, + error: { + message: "must match exactly one schema in oneOf", + params: ({ params }) => (0, codegen_1._)`{passingSchemas: ${params.passing}}` + }, + code(cxt) { + const { gen, schema, parentSchema, it } = cxt; + /* istanbul ignore if */ + if (!Array.isArray(schema)) throw new Error("ajv implementation error"); + if (it.opts.discriminator && parentSchema.discriminator) return; + const schArr = schema; + const valid = gen.let("valid", false); + const passing = gen.let("passing", null); + const schValid = gen.name("_valid"); + cxt.setParams({ passing }); + gen.block(validateOneOf); + cxt.result(valid, () => cxt.reset(), () => cxt.error(true)); + function validateOneOf() { + schArr.forEach((sch, i) => { + let schCxt; + if ((0, util_1.alwaysValidSchema)(it, sch)) gen.var(schValid, true); + else schCxt = cxt.subschema({ + keyword: "oneOf", + schemaProp: i, + compositeRule: true + }, schValid); + if (i > 0) gen.if((0, codegen_1._)`${schValid} && ${valid}`).assign(valid, false).assign(passing, (0, codegen_1._)`[${passing}, ${i}]`).else(); + gen.if(schValid, () => { + gen.assign(valid, true); + gen.assign(passing, i); + if (schCxt) cxt.mergeEvaluated(schCxt, codegen_1.Name); + }); + }); + } + } + }; + exports.default = def; +})); + +//#endregion +//#region ../../node_modules/.pnpm/ajv@8.18.0/node_modules/ajv/dist/vocabularies/applicator/allOf.js +var require_allOf = /* @__PURE__ */ __commonJSMin(((exports) => { + Object.defineProperty(exports, "__esModule", { value: true }); + const util_1 = require_util(); + const def = { + keyword: "allOf", + schemaType: "array", + code(cxt) { + const { gen, schema, it } = cxt; + /* istanbul ignore if */ + if (!Array.isArray(schema)) throw new Error("ajv implementation error"); + const valid = gen.name("valid"); + schema.forEach((sch, i) => { + if ((0, util_1.alwaysValidSchema)(it, sch)) return; + const schCxt = cxt.subschema({ + keyword: "allOf", + schemaProp: i + }, valid); + cxt.ok(valid); + cxt.mergeEvaluated(schCxt); + }); + } + }; + exports.default = def; +})); + +//#endregion +//#region ../../node_modules/.pnpm/ajv@8.18.0/node_modules/ajv/dist/vocabularies/applicator/if.js +var require_if = /* @__PURE__ */ __commonJSMin(((exports) => { + Object.defineProperty(exports, "__esModule", { value: true }); + const codegen_1 = require_codegen(); + const util_1 = require_util(); + const def = { + keyword: "if", + schemaType: ["object", "boolean"], + trackErrors: true, + error: { + message: ({ params }) => (0, codegen_1.str)`must match "${params.ifClause}" schema`, + params: ({ params }) => (0, codegen_1._)`{failingKeyword: ${params.ifClause}}` + }, + code(cxt) { + const { gen, parentSchema, it } = cxt; + if (parentSchema.then === void 0 && parentSchema.else === void 0) (0, util_1.checkStrictMode)(it, "\"if\" without \"then\" and \"else\" is ignored"); + const hasThen = hasSchema(it, "then"); + const hasElse = hasSchema(it, "else"); + if (!hasThen && !hasElse) return; + const valid = gen.let("valid", true); + const schValid = gen.name("_valid"); + validateIf(); + cxt.reset(); + if (hasThen && hasElse) { + const ifClause = gen.let("ifClause"); + cxt.setParams({ ifClause }); + gen.if(schValid, validateClause("then", ifClause), validateClause("else", ifClause)); + } else if (hasThen) gen.if(schValid, validateClause("then")); + else gen.if((0, codegen_1.not)(schValid), validateClause("else")); + cxt.pass(valid, () => cxt.error(true)); + function validateIf() { + const schCxt = cxt.subschema({ + keyword: "if", + compositeRule: true, + createErrors: false, + allErrors: false + }, schValid); + cxt.mergeEvaluated(schCxt); + } + function validateClause(keyword, ifClause) { + return () => { + const schCxt = cxt.subschema({ keyword }, schValid); + gen.assign(valid, schValid); + cxt.mergeValidEvaluated(schCxt, valid); + if (ifClause) gen.assign(ifClause, (0, codegen_1._)`${keyword}`); + else cxt.setParams({ ifClause: keyword }); + }; + } + } + }; + function hasSchema(it, keyword) { + const schema = it.schema[keyword]; + return schema !== void 0 && !(0, util_1.alwaysValidSchema)(it, schema); + } + exports.default = def; +})); + +//#endregion +//#region ../../node_modules/.pnpm/ajv@8.18.0/node_modules/ajv/dist/vocabularies/applicator/thenElse.js +var require_thenElse = /* @__PURE__ */ __commonJSMin(((exports) => { + Object.defineProperty(exports, "__esModule", { value: true }); + const util_1 = require_util(); + const def = { + keyword: ["then", "else"], + schemaType: ["object", "boolean"], + code({ keyword, parentSchema, it }) { + if (parentSchema.if === void 0) (0, util_1.checkStrictMode)(it, `"${keyword}" without "if" is ignored`); + } + }; + exports.default = def; +})); + +//#endregion +//#region ../../node_modules/.pnpm/ajv@8.18.0/node_modules/ajv/dist/vocabularies/applicator/index.js +var require_applicator$2 = /* @__PURE__ */ __commonJSMin(((exports) => { + Object.defineProperty(exports, "__esModule", { value: true }); + const additionalItems_1 = require_additionalItems(); + const prefixItems_1 = require_prefixItems(); + const items_1 = require_items(); + const items2020_1 = require_items2020(); + const contains_1 = require_contains(); + const dependencies_1 = require_dependencies(); + const propertyNames_1 = require_propertyNames(); + const additionalProperties_1 = require_additionalProperties(); + const properties_1 = require_properties(); + const patternProperties_1 = require_patternProperties(); + const not_1 = require_not(); + const anyOf_1 = require_anyOf(); + const oneOf_1 = require_oneOf(); + const allOf_1 = require_allOf(); + const if_1 = require_if(); + const thenElse_1 = require_thenElse(); + function getApplicator(draft2020 = false) { + const applicator = [ + not_1.default, + anyOf_1.default, + oneOf_1.default, + allOf_1.default, + if_1.default, + thenElse_1.default, + propertyNames_1.default, + additionalProperties_1.default, + dependencies_1.default, + properties_1.default, + patternProperties_1.default + ]; + if (draft2020) applicator.push(prefixItems_1.default, items2020_1.default); + else applicator.push(additionalItems_1.default, items_1.default); + applicator.push(contains_1.default); + return applicator; + } + exports.default = getApplicator; +})); + +//#endregion +//#region ../../node_modules/.pnpm/ajv@8.18.0/node_modules/ajv/dist/vocabularies/format/format.js +var require_format$2 = /* @__PURE__ */ __commonJSMin(((exports) => { + Object.defineProperty(exports, "__esModule", { value: true }); + const codegen_1 = require_codegen(); + const def = { + keyword: "format", + type: ["number", "string"], + schemaType: "string", + $data: true, + error: { + message: ({ schemaCode }) => (0, codegen_1.str)`must match format "${schemaCode}"`, + params: ({ schemaCode }) => (0, codegen_1._)`{format: ${schemaCode}}` + }, + code(cxt, ruleType) { + const { gen, data, $data, schema, schemaCode, it } = cxt; + const { opts, errSchemaPath, schemaEnv, self } = it; + if (!opts.validateFormats) return; + if ($data) validate$DataFormat(); + else validateFormat(); + function validate$DataFormat() { + const fmts = gen.scopeValue("formats", { + ref: self.formats, + code: opts.code.formats + }); + const fDef = gen.const("fDef", (0, codegen_1._)`${fmts}[${schemaCode}]`); + const fType = gen.let("fType"); + const format = gen.let("format"); + gen.if((0, codegen_1._)`typeof ${fDef} == "object" && !(${fDef} instanceof RegExp)`, () => gen.assign(fType, (0, codegen_1._)`${fDef}.type || "string"`).assign(format, (0, codegen_1._)`${fDef}.validate`), () => gen.assign(fType, (0, codegen_1._)`"string"`).assign(format, fDef)); + cxt.fail$data((0, codegen_1.or)(unknownFmt(), invalidFmt())); + function unknownFmt() { + if (opts.strictSchema === false) return codegen_1.nil; + return (0, codegen_1._)`${schemaCode} && !${format}`; + } + function invalidFmt() { + const callFormat = schemaEnv.$async ? (0, codegen_1._)`(${fDef}.async ? await ${format}(${data}) : ${format}(${data}))` : (0, codegen_1._)`${format}(${data})`; + const validData = (0, codegen_1._)`(typeof ${format} == "function" ? ${callFormat} : ${format}.test(${data}))`; + return (0, codegen_1._)`${format} && ${format} !== true && ${fType} === ${ruleType} && !${validData}`; + } + } + function validateFormat() { + const formatDef = self.formats[schema]; + if (!formatDef) { + unknownFormat(); + return; + } + if (formatDef === true) return; + const [fmtType, format, fmtRef] = getFormat(formatDef); + if (fmtType === ruleType) cxt.pass(validCondition()); + function unknownFormat() { + if (opts.strictSchema === false) { + self.logger.warn(unknownMsg()); + return; + } + throw new Error(unknownMsg()); + function unknownMsg() { + return `unknown format "${schema}" ignored in schema at path "${errSchemaPath}"`; + } + } + function getFormat(fmtDef) { + const code = fmtDef instanceof RegExp ? (0, codegen_1.regexpCode)(fmtDef) : opts.code.formats ? (0, codegen_1._)`${opts.code.formats}${(0, codegen_1.getProperty)(schema)}` : void 0; + const fmt = gen.scopeValue("formats", { + key: schema, + ref: fmtDef, + code + }); + if (typeof fmtDef == "object" && !(fmtDef instanceof RegExp)) return [ + fmtDef.type || "string", + fmtDef.validate, + (0, codegen_1._)`${fmt}.validate` + ]; + return [ + "string", + fmtDef, + fmt + ]; + } + function validCondition() { + if (typeof formatDef == "object" && !(formatDef instanceof RegExp) && formatDef.async) { + if (!schemaEnv.$async) throw new Error("async format in sync schema"); + return (0, codegen_1._)`await ${fmtRef}(${data})`; + } + return typeof format == "function" ? (0, codegen_1._)`${fmtRef}(${data})` : (0, codegen_1._)`${fmtRef}.test(${data})`; + } + } + } + }; + exports.default = def; +})); + +//#endregion +//#region ../../node_modules/.pnpm/ajv@8.18.0/node_modules/ajv/dist/vocabularies/format/index.js +var require_format$1 = /* @__PURE__ */ __commonJSMin(((exports) => { + Object.defineProperty(exports, "__esModule", { value: true }); + const format = [require_format$2().default]; + exports.default = format; +})); + +//#endregion +//#region ../../node_modules/.pnpm/ajv@8.18.0/node_modules/ajv/dist/vocabularies/metadata.js +var require_metadata = /* @__PURE__ */ __commonJSMin(((exports) => { + Object.defineProperty(exports, "__esModule", { value: true }); + exports.contentVocabulary = exports.metadataVocabulary = void 0; + exports.metadataVocabulary = [ + "title", + "description", + "default", + "deprecated", + "readOnly", + "writeOnly", + "examples" + ]; + exports.contentVocabulary = [ + "contentMediaType", + "contentEncoding", + "contentSchema" + ]; +})); + +//#endregion +//#region ../../node_modules/.pnpm/ajv@8.18.0/node_modules/ajv/dist/vocabularies/draft7.js +var require_draft7 = /* @__PURE__ */ __commonJSMin(((exports) => { + Object.defineProperty(exports, "__esModule", { value: true }); + const core_1 = require_core$2(); + const validation_1 = require_validation$2(); + const applicator_1 = require_applicator$2(); + const format_1 = require_format$1(); + const metadata_1 = require_metadata(); + const draft7Vocabularies = [ + core_1.default, + validation_1.default, + (0, applicator_1.default)(), + format_1.default, + metadata_1.metadataVocabulary, + metadata_1.contentVocabulary + ]; + exports.default = draft7Vocabularies; +})); + +//#endregion +//#region ../../node_modules/.pnpm/ajv@8.18.0/node_modules/ajv/dist/vocabularies/discriminator/types.js +var require_types = /* @__PURE__ */ __commonJSMin(((exports) => { + Object.defineProperty(exports, "__esModule", { value: true }); + exports.DiscrError = void 0; + var DiscrError; + (function(DiscrError) { + DiscrError["Tag"] = "tag"; + DiscrError["Mapping"] = "mapping"; + })(DiscrError || (exports.DiscrError = DiscrError = {})); +})); + +//#endregion +//#region ../../node_modules/.pnpm/ajv@8.18.0/node_modules/ajv/dist/vocabularies/discriminator/index.js +var require_discriminator = /* @__PURE__ */ __commonJSMin(((exports) => { + Object.defineProperty(exports, "__esModule", { value: true }); + const codegen_1 = require_codegen(); + const types_1 = require_types(); + const compile_1 = require_compile(); + const ref_error_1 = require_ref_error(); + const util_1 = require_util(); + const def = { + keyword: "discriminator", + type: "object", + schemaType: "object", + error: { + message: ({ params: { discrError, tagName } }) => discrError === types_1.DiscrError.Tag ? `tag "${tagName}" must be string` : `value of tag "${tagName}" must be in oneOf`, + params: ({ params: { discrError, tag, tagName } }) => (0, codegen_1._)`{error: ${discrError}, tag: ${tagName}, tagValue: ${tag}}` + }, + code(cxt) { + const { gen, data, schema, parentSchema, it } = cxt; + const { oneOf } = parentSchema; + if (!it.opts.discriminator) throw new Error("discriminator: requires discriminator option"); + const tagName = schema.propertyName; + if (typeof tagName != "string") throw new Error("discriminator: requires propertyName"); + if (schema.mapping) throw new Error("discriminator: mapping is not supported"); + if (!oneOf) throw new Error("discriminator: requires oneOf keyword"); + const valid = gen.let("valid", false); + const tag = gen.const("tag", (0, codegen_1._)`${data}${(0, codegen_1.getProperty)(tagName)}`); + gen.if((0, codegen_1._)`typeof ${tag} == "string"`, () => validateMapping(), () => cxt.error(false, { + discrError: types_1.DiscrError.Tag, + tag, + tagName + })); + cxt.ok(valid); + function validateMapping() { + const mapping = getMapping(); + gen.if(false); + for (const tagValue in mapping) { + gen.elseIf((0, codegen_1._)`${tag} === ${tagValue}`); + gen.assign(valid, applyTagSchema(mapping[tagValue])); + } + gen.else(); + cxt.error(false, { + discrError: types_1.DiscrError.Mapping, + tag, + tagName + }); + gen.endIf(); + } + function applyTagSchema(schemaProp) { + const _valid = gen.name("valid"); + const schCxt = cxt.subschema({ + keyword: "oneOf", + schemaProp + }, _valid); + cxt.mergeEvaluated(schCxt, codegen_1.Name); + return _valid; + } + function getMapping() { + var _a; + const oneOfMapping = {}; + const topRequired = hasRequired(parentSchema); + let tagRequired = true; + for (let i = 0; i < oneOf.length; i++) { + let sch = oneOf[i]; + if ((sch === null || sch === void 0 ? void 0 : sch.$ref) && !(0, util_1.schemaHasRulesButRef)(sch, it.self.RULES)) { + const ref = sch.$ref; + sch = compile_1.resolveRef.call(it.self, it.schemaEnv.root, it.baseId, ref); + if (sch instanceof compile_1.SchemaEnv) sch = sch.schema; + if (sch === void 0) throw new ref_error_1.default(it.opts.uriResolver, it.baseId, ref); + } + const propSch = (_a = sch === null || sch === void 0 ? void 0 : sch.properties) === null || _a === void 0 ? void 0 : _a[tagName]; + if (typeof propSch != "object") throw new Error(`discriminator: oneOf subschemas (or referenced schemas) must have "properties/${tagName}"`); + tagRequired = tagRequired && (topRequired || hasRequired(sch)); + addMappings(propSch, i); + } + if (!tagRequired) throw new Error(`discriminator: "${tagName}" must be required`); + return oneOfMapping; + function hasRequired({ required }) { + return Array.isArray(required) && required.includes(tagName); + } + function addMappings(sch, i) { + if (sch.const) addMapping(sch.const, i); + else if (sch.enum) for (const tagValue of sch.enum) addMapping(tagValue, i); + else throw new Error(`discriminator: "properties/${tagName}" must have "const" or "enum"`); + } + function addMapping(tagValue, i) { + if (typeof tagValue != "string" || tagValue in oneOfMapping) throw new Error(`discriminator: "${tagName}" values must be unique strings`); + oneOfMapping[tagValue] = i; + } + } + } + }; + exports.default = def; +})); + +//#endregion +//#region ../../node_modules/.pnpm/ajv@8.18.0/node_modules/ajv/dist/refs/json-schema-draft-07.json +var require_json_schema_draft_07 = /* @__PURE__ */ __commonJSMin(((exports, module) => { + module.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": true, + "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": true, + "readOnly": { + "type": "boolean", + "default": false + }, + "examples": { + "type": "array", + "items": true + }, + "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": true + }, + "maxItems": { "$ref": "#/definitions/nonNegativeInteger" }, + "minItems": { "$ref": "#/definitions/nonNegativeIntegerDefault0" }, + "uniqueItems": { + "type": "boolean", + "default": false + }, + "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": true, + "enum": { + "type": "array", + "items": true, + "minItems": 1, + "uniqueItems": true + }, + "type": { "anyOf": [{ "$ref": "#/definitions/simpleTypes" }, { + "type": "array", + "items": { "$ref": "#/definitions/simpleTypes" }, + "minItems": 1, + "uniqueItems": true + }] }, + "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": true + }; +})); + +//#endregion +//#region ../../node_modules/.pnpm/ajv@8.18.0/node_modules/ajv/dist/ajv.js +var require_ajv = /* @__PURE__ */ __commonJSMin(((exports, module) => { + Object.defineProperty(exports, "__esModule", { value: true }); + exports.MissingRefError = exports.ValidationError = exports.CodeGen = exports.Name = exports.nil = exports.stringify = exports.str = exports._ = exports.KeywordCxt = exports.Ajv = void 0; + const core_1 = require_core$3(); + const draft7_1 = require_draft7(); + const discriminator_1 = require_discriminator(); + const draft7MetaSchema = require_json_schema_draft_07(); + const META_SUPPORT_DATA = ["/properties"]; + const META_SCHEMA_ID = "http://json-schema.org/draft-07/schema"; + var Ajv = class extends core_1.default { + _addVocabularies() { + super._addVocabularies(); + draft7_1.default.forEach((v) => this.addVocabulary(v)); + if (this.opts.discriminator) this.addKeyword(discriminator_1.default); + } + _addDefaultMetaSchema() { + super._addDefaultMetaSchema(); + if (!this.opts.meta) return; + const metaSchema = this.opts.$data ? this.$dataMetaSchema(draft7MetaSchema, META_SUPPORT_DATA) : draft7MetaSchema; + this.addMetaSchema(metaSchema, META_SCHEMA_ID, false); + this.refs["http://json-schema.org/schema"] = META_SCHEMA_ID; + } + defaultMeta() { + return this.opts.defaultMeta = super.defaultMeta() || (this.getSchema(META_SCHEMA_ID) ? META_SCHEMA_ID : void 0); + } + }; + exports.Ajv = Ajv; + module.exports = exports = Ajv; + module.exports.Ajv = Ajv; + Object.defineProperty(exports, "__esModule", { value: true }); + exports.default = Ajv; + var validate_1 = require_validate(); + Object.defineProperty(exports, "KeywordCxt", { + enumerable: true, + get: function() { + return validate_1.KeywordCxt; + } + }); + var codegen_1 = require_codegen(); + Object.defineProperty(exports, "_", { + enumerable: true, + get: function() { + return codegen_1._; + } + }); + Object.defineProperty(exports, "str", { + enumerable: true, + get: function() { + return codegen_1.str; + } + }); + Object.defineProperty(exports, "stringify", { + enumerable: true, + get: function() { + return codegen_1.stringify; + } + }); + Object.defineProperty(exports, "nil", { + enumerable: true, + get: function() { + return codegen_1.nil; + } + }); + Object.defineProperty(exports, "Name", { + enumerable: true, + get: function() { + return codegen_1.Name; + } + }); + Object.defineProperty(exports, "CodeGen", { + enumerable: true, + get: function() { + return codegen_1.CodeGen; + } + }); + var validation_error_1 = require_validation_error(); + Object.defineProperty(exports, "ValidationError", { + enumerable: true, + get: function() { + return validation_error_1.default; + } + }); + var ref_error_1 = require_ref_error(); + Object.defineProperty(exports, "MissingRefError", { + enumerable: true, + get: function() { + return ref_error_1.default; + } + }); +})); + +//#endregion +//#region ../../node_modules/.pnpm/ajv@8.18.0/node_modules/ajv/dist/vocabularies/dynamic/dynamicAnchor.js +var require_dynamicAnchor = /* @__PURE__ */ __commonJSMin(((exports) => { + Object.defineProperty(exports, "__esModule", { value: true }); + exports.dynamicAnchor = void 0; + const codegen_1 = require_codegen(); + const names_1 = require_names(); + const compile_1 = require_compile(); + const ref_1 = require_ref(); + const def = { + keyword: "$dynamicAnchor", + schemaType: "string", + code: (cxt) => dynamicAnchor(cxt, cxt.schema) + }; + function dynamicAnchor(cxt, anchor) { + const { gen, it } = cxt; + it.schemaEnv.root.dynamicAnchors[anchor] = true; + const v = (0, codegen_1._)`${names_1.default.dynamicAnchors}${(0, codegen_1.getProperty)(anchor)}`; + const validate = it.errSchemaPath === "#" ? it.validateName : _getValidate(cxt); + gen.if((0, codegen_1._)`!${v}`, () => gen.assign(v, validate)); + } + exports.dynamicAnchor = dynamicAnchor; + function _getValidate(cxt) { + const { schemaEnv, schema, self } = cxt.it; + const { root, baseId, localRefs, meta } = schemaEnv.root; + const { schemaId } = self.opts; + const sch = new compile_1.SchemaEnv({ + schema, + schemaId, + root, + baseId, + localRefs, + meta + }); + compile_1.compileSchema.call(self, sch); + return (0, ref_1.getValidate)(cxt, sch); + } + exports.default = def; +})); + +//#endregion +//#region ../../node_modules/.pnpm/ajv@8.18.0/node_modules/ajv/dist/vocabularies/dynamic/dynamicRef.js +var require_dynamicRef = /* @__PURE__ */ __commonJSMin(((exports) => { + Object.defineProperty(exports, "__esModule", { value: true }); + exports.dynamicRef = void 0; + const codegen_1 = require_codegen(); + const names_1 = require_names(); + const ref_1 = require_ref(); + const def = { + keyword: "$dynamicRef", + schemaType: "string", + code: (cxt) => dynamicRef(cxt, cxt.schema) + }; + function dynamicRef(cxt, ref) { + const { gen, keyword, it } = cxt; + if (ref[0] !== "#") throw new Error(`"${keyword}" only supports hash fragment reference`); + const anchor = ref.slice(1); + if (it.allErrors) _dynamicRef(); + else { + const valid = gen.let("valid", false); + _dynamicRef(valid); + cxt.ok(valid); + } + function _dynamicRef(valid) { + if (it.schemaEnv.root.dynamicAnchors[anchor]) { + const v = gen.let("_v", (0, codegen_1._)`${names_1.default.dynamicAnchors}${(0, codegen_1.getProperty)(anchor)}`); + gen.if(v, _callRef(v, valid), _callRef(it.validateName, valid)); + } else _callRef(it.validateName, valid)(); + } + function _callRef(validate, valid) { + return valid ? () => gen.block(() => { + (0, ref_1.callRef)(cxt, validate); + gen.let(valid, true); + }) : () => (0, ref_1.callRef)(cxt, validate); + } + } + exports.dynamicRef = dynamicRef; + exports.default = def; +})); + +//#endregion +//#region ../../node_modules/.pnpm/ajv@8.18.0/node_modules/ajv/dist/vocabularies/dynamic/recursiveAnchor.js +var require_recursiveAnchor = /* @__PURE__ */ __commonJSMin(((exports) => { + Object.defineProperty(exports, "__esModule", { value: true }); + const dynamicAnchor_1 = require_dynamicAnchor(); + const util_1 = require_util(); + const def = { + keyword: "$recursiveAnchor", + schemaType: "boolean", + code(cxt) { + if (cxt.schema) (0, dynamicAnchor_1.dynamicAnchor)(cxt, ""); + else (0, util_1.checkStrictMode)(cxt.it, "$recursiveAnchor: false is ignored"); + } + }; + exports.default = def; +})); + +//#endregion +//#region ../../node_modules/.pnpm/ajv@8.18.0/node_modules/ajv/dist/vocabularies/dynamic/recursiveRef.js +var require_recursiveRef = /* @__PURE__ */ __commonJSMin(((exports) => { + Object.defineProperty(exports, "__esModule", { value: true }); + const dynamicRef_1 = require_dynamicRef(); + const def = { + keyword: "$recursiveRef", + schemaType: "string", + code: (cxt) => (0, dynamicRef_1.dynamicRef)(cxt, cxt.schema) + }; + exports.default = def; +})); + +//#endregion +//#region ../../node_modules/.pnpm/ajv@8.18.0/node_modules/ajv/dist/vocabularies/dynamic/index.js +var require_dynamic = /* @__PURE__ */ __commonJSMin(((exports) => { + Object.defineProperty(exports, "__esModule", { value: true }); + const dynamicAnchor_1 = require_dynamicAnchor(); + const dynamicRef_1 = require_dynamicRef(); + const recursiveAnchor_1 = require_recursiveAnchor(); + const recursiveRef_1 = require_recursiveRef(); + const dynamic = [ + dynamicAnchor_1.default, + dynamicRef_1.default, + recursiveAnchor_1.default, + recursiveRef_1.default + ]; + exports.default = dynamic; +})); + +//#endregion +//#region ../../node_modules/.pnpm/ajv@8.18.0/node_modules/ajv/dist/vocabularies/validation/dependentRequired.js +var require_dependentRequired = /* @__PURE__ */ __commonJSMin(((exports) => { + Object.defineProperty(exports, "__esModule", { value: true }); + const dependencies_1 = require_dependencies(); + const def = { + keyword: "dependentRequired", + type: "object", + schemaType: "object", + error: dependencies_1.error, + code: (cxt) => (0, dependencies_1.validatePropertyDeps)(cxt) + }; + exports.default = def; +})); + +//#endregion +//#region ../../node_modules/.pnpm/ajv@8.18.0/node_modules/ajv/dist/vocabularies/applicator/dependentSchemas.js +var require_dependentSchemas = /* @__PURE__ */ __commonJSMin(((exports) => { + Object.defineProperty(exports, "__esModule", { value: true }); + const dependencies_1 = require_dependencies(); + const def = { + keyword: "dependentSchemas", + type: "object", + schemaType: "object", + code: (cxt) => (0, dependencies_1.validateSchemaDeps)(cxt) + }; + exports.default = def; +})); + +//#endregion +//#region ../../node_modules/.pnpm/ajv@8.18.0/node_modules/ajv/dist/vocabularies/validation/limitContains.js +var require_limitContains = /* @__PURE__ */ __commonJSMin(((exports) => { + Object.defineProperty(exports, "__esModule", { value: true }); + const util_1 = require_util(); + const def = { + keyword: ["maxContains", "minContains"], + type: "array", + schemaType: "number", + code({ keyword, parentSchema, it }) { + if (parentSchema.contains === void 0) (0, util_1.checkStrictMode)(it, `"${keyword}" without "contains" is ignored`); + } + }; + exports.default = def; +})); + +//#endregion +//#region ../../node_modules/.pnpm/ajv@8.18.0/node_modules/ajv/dist/vocabularies/next.js +var require_next = /* @__PURE__ */ __commonJSMin(((exports) => { + Object.defineProperty(exports, "__esModule", { value: true }); + const dependentRequired_1 = require_dependentRequired(); + const dependentSchemas_1 = require_dependentSchemas(); + const limitContains_1 = require_limitContains(); + const next = [ + dependentRequired_1.default, + dependentSchemas_1.default, + limitContains_1.default + ]; + exports.default = next; +})); + +//#endregion +//#region ../../node_modules/.pnpm/ajv@8.18.0/node_modules/ajv/dist/vocabularies/unevaluated/unevaluatedProperties.js +var require_unevaluatedProperties = /* @__PURE__ */ __commonJSMin(((exports) => { + Object.defineProperty(exports, "__esModule", { value: true }); + const codegen_1 = require_codegen(); + const util_1 = require_util(); + const names_1 = require_names(); + const def = { + keyword: "unevaluatedProperties", + type: "object", + schemaType: ["boolean", "object"], + trackErrors: true, + error: { + message: "must NOT have unevaluated properties", + params: ({ params }) => (0, codegen_1._)`{unevaluatedProperty: ${params.unevaluatedProperty}}` + }, + code(cxt) { + const { gen, schema, data, errsCount, it } = cxt; + /* istanbul ignore if */ + if (!errsCount) throw new Error("ajv implementation error"); + const { allErrors, props } = it; + if (props instanceof codegen_1.Name) gen.if((0, codegen_1._)`${props} !== true`, () => gen.forIn("key", data, (key) => gen.if(unevaluatedDynamic(props, key), () => unevaluatedPropCode(key)))); + else if (props !== true) gen.forIn("key", data, (key) => props === void 0 ? unevaluatedPropCode(key) : gen.if(unevaluatedStatic(props, key), () => unevaluatedPropCode(key))); + it.props = true; + cxt.ok((0, codegen_1._)`${errsCount} === ${names_1.default.errors}`); + function unevaluatedPropCode(key) { + if (schema === false) { + cxt.setParams({ unevaluatedProperty: key }); + cxt.error(); + if (!allErrors) gen.break(); + return; + } + if (!(0, util_1.alwaysValidSchema)(it, schema)) { + const valid = gen.name("valid"); + cxt.subschema({ + keyword: "unevaluatedProperties", + dataProp: key, + dataPropType: util_1.Type.Str + }, valid); + if (!allErrors) gen.if((0, codegen_1.not)(valid), () => gen.break()); + } + } + function unevaluatedDynamic(evaluatedProps, key) { + return (0, codegen_1._)`!${evaluatedProps} || !${evaluatedProps}[${key}]`; + } + function unevaluatedStatic(evaluatedProps, key) { + const ps = []; + for (const p in evaluatedProps) if (evaluatedProps[p] === true) ps.push((0, codegen_1._)`${key} !== ${p}`); + return (0, codegen_1.and)(...ps); + } + } + }; + exports.default = def; +})); + +//#endregion +//#region ../../node_modules/.pnpm/ajv@8.18.0/node_modules/ajv/dist/vocabularies/unevaluated/unevaluatedItems.js +var require_unevaluatedItems = /* @__PURE__ */ __commonJSMin(((exports) => { + Object.defineProperty(exports, "__esModule", { value: true }); + const codegen_1 = require_codegen(); + const util_1 = require_util(); + const def = { + keyword: "unevaluatedItems", + type: "array", + schemaType: ["boolean", "object"], + error: { + message: ({ params: { len } }) => (0, codegen_1.str)`must NOT have more than ${len} items`, + params: ({ params: { len } }) => (0, codegen_1._)`{limit: ${len}}` + }, + code(cxt) { + const { gen, schema, data, it } = cxt; + const items = it.items || 0; + if (items === true) return; + const len = gen.const("len", (0, codegen_1._)`${data}.length`); + if (schema === false) { + cxt.setParams({ len: items }); + cxt.fail((0, codegen_1._)`${len} > ${items}`); + } else if (typeof schema == "object" && !(0, util_1.alwaysValidSchema)(it, schema)) { + const valid = gen.var("valid", (0, codegen_1._)`${len} <= ${items}`); + gen.if((0, codegen_1.not)(valid), () => validateItems(valid, items)); + cxt.ok(valid); + } + it.items = true; + function validateItems(valid, from) { + gen.forRange("i", from, len, (i) => { + cxt.subschema({ + keyword: "unevaluatedItems", + dataProp: i, + dataPropType: util_1.Type.Num + }, valid); + if (!it.allErrors) gen.if((0, codegen_1.not)(valid), () => gen.break()); + }); + } + } + }; + exports.default = def; +})); + +//#endregion +//#region ../../node_modules/.pnpm/ajv@8.18.0/node_modules/ajv/dist/vocabularies/unevaluated/index.js +var require_unevaluated$1 = /* @__PURE__ */ __commonJSMin(((exports) => { + Object.defineProperty(exports, "__esModule", { value: true }); + const unevaluatedProperties_1 = require_unevaluatedProperties(); + const unevaluatedItems_1 = require_unevaluatedItems(); + const unevaluated = [unevaluatedProperties_1.default, unevaluatedItems_1.default]; + exports.default = unevaluated; +})); + +//#endregion +//#region ../../node_modules/.pnpm/ajv@8.18.0/node_modules/ajv/dist/refs/json-schema-2019-09/schema.json +var require_schema$1 = /* @__PURE__ */ __commonJSMin(((exports, module) => { + module.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": true, + "https://json-schema.org/draft/2019-09/vocab/applicator": true, + "https://json-schema.org/draft/2019-09/vocab/validation": true, + "https://json-schema.org/draft/2019-09/vocab/meta-data": true, + "https://json-schema.org/draft/2019-09/vocab/format": false, + "https://json-schema.org/draft/2019-09/vocab/content": true + }, + "$recursiveAnchor": true, + "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" }] } + } + } + }; +})); + +//#endregion +//#region ../../node_modules/.pnpm/ajv@8.18.0/node_modules/ajv/dist/refs/json-schema-2019-09/meta/applicator.json +var require_applicator$1 = /* @__PURE__ */ __commonJSMin(((exports, module) => { + module.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": true }, + "$recursiveAnchor": true, + "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": "#" } + } } + }; +})); + +//#endregion +//#region ../../node_modules/.pnpm/ajv@8.18.0/node_modules/ajv/dist/refs/json-schema-2019-09/meta/content.json +var require_content$1 = /* @__PURE__ */ __commonJSMin(((exports, module) => { + module.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": true }, + "$recursiveAnchor": true, + "title": "Content vocabulary meta-schema", + "type": ["object", "boolean"], + "properties": { + "contentMediaType": { "type": "string" }, + "contentEncoding": { "type": "string" }, + "contentSchema": { "$recursiveRef": "#" } + } + }; +})); + +//#endregion +//#region ../../node_modules/.pnpm/ajv@8.18.0/node_modules/ajv/dist/refs/json-schema-2019-09/meta/core.json +var require_core$1 = /* @__PURE__ */ __commonJSMin(((exports, module) => { + module.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": true }, + "$recursiveAnchor": true, + "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": false + }, + "$vocabulary": { + "type": "object", + "propertyNames": { + "type": "string", + "format": "uri" + }, + "additionalProperties": { "type": "boolean" } + }, + "$comment": { "type": "string" }, + "$defs": { + "type": "object", + "additionalProperties": { "$recursiveRef": "#" }, + "default": {} + } + } + }; +})); + +//#endregion +//#region ../../node_modules/.pnpm/ajv@8.18.0/node_modules/ajv/dist/refs/json-schema-2019-09/meta/format.json +var require_format = /* @__PURE__ */ __commonJSMin(((exports, module) => { + module.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": true }, + "$recursiveAnchor": true, + "title": "Format vocabulary meta-schema", + "type": ["object", "boolean"], + "properties": { "format": { "type": "string" } } + }; +})); + +//#endregion +//#region ../../node_modules/.pnpm/ajv@8.18.0/node_modules/ajv/dist/refs/json-schema-2019-09/meta/meta-data.json +var require_meta_data$1 = /* @__PURE__ */ __commonJSMin(((exports, module) => { + module.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": true }, + "$recursiveAnchor": true, + "title": "Meta-data vocabulary meta-schema", + "type": ["object", "boolean"], + "properties": { + "title": { "type": "string" }, + "description": { "type": "string" }, + "default": true, + "deprecated": { + "type": "boolean", + "default": false + }, + "readOnly": { + "type": "boolean", + "default": false + }, + "writeOnly": { + "type": "boolean", + "default": false + }, + "examples": { + "type": "array", + "items": true + } + } + }; +})); + +//#endregion +//#region ../../node_modules/.pnpm/ajv@8.18.0/node_modules/ajv/dist/refs/json-schema-2019-09/meta/validation.json +var require_validation$1 = /* @__PURE__ */ __commonJSMin(((exports, module) => { + module.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": true }, + "$recursiveAnchor": true, + "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": false + }, + "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": true, + "enum": { + "type": "array", + "items": true + }, + "type": { "anyOf": [{ "$ref": "#/$defs/simpleTypes" }, { + "type": "array", + "items": { "$ref": "#/$defs/simpleTypes" }, + "minItems": 1, + "uniqueItems": true + }] } + }, + "$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": true, + "default": [] + } + } + }; +})); + +//#endregion +//#region ../../node_modules/.pnpm/ajv@8.18.0/node_modules/ajv/dist/refs/json-schema-2019-09/index.js +var require_json_schema_2019_09 = /* @__PURE__ */ __commonJSMin(((exports) => { + Object.defineProperty(exports, "__esModule", { value: true }); + const metaSchema = require_schema$1(); + const applicator = require_applicator$1(); + const content = require_content$1(); + const core = require_core$1(); + const format = require_format(); + const metadata = require_meta_data$1(); + const validation = require_validation$1(); + const META_SUPPORT_DATA = ["/properties"]; + function addMetaSchema2019($data) { + [ + metaSchema, + applicator, + content, + core, + with$data(this, format), + metadata, + with$data(this, validation) + ].forEach((sch) => this.addMetaSchema(sch, void 0, false)); + return this; + function with$data(ajv, sch) { + return $data ? ajv.$dataMetaSchema(sch, META_SUPPORT_DATA) : sch; + } + } + exports.default = addMetaSchema2019; +})); + +//#endregion +//#region ../../node_modules/.pnpm/ajv@8.18.0/node_modules/ajv/dist/2019.js +var require__2019 = /* @__PURE__ */ __commonJSMin(((exports, module) => { + Object.defineProperty(exports, "__esModule", { value: true }); + exports.MissingRefError = exports.ValidationError = exports.CodeGen = exports.Name = exports.nil = exports.stringify = exports.str = exports._ = exports.KeywordCxt = exports.Ajv2019 = void 0; + const core_1 = require_core$3(); + const draft7_1 = require_draft7(); + const dynamic_1 = require_dynamic(); + const next_1 = require_next(); + const unevaluated_1 = require_unevaluated$1(); + const discriminator_1 = require_discriminator(); + const json_schema_2019_09_1 = require_json_schema_2019_09(); + const META_SCHEMA_ID = "https://json-schema.org/draft/2019-09/schema"; + var Ajv2019 = class extends core_1.default { + constructor(opts = {}) { + super({ + ...opts, + dynamicRef: true, + next: true, + unevaluated: true + }); + } + _addVocabularies() { + super._addVocabularies(); + this.addVocabulary(dynamic_1.default); + draft7_1.default.forEach((v) => this.addVocabulary(v)); + this.addVocabulary(next_1.default); + this.addVocabulary(unevaluated_1.default); + if (this.opts.discriminator) this.addKeyword(discriminator_1.default); + } + _addDefaultMetaSchema() { + super._addDefaultMetaSchema(); + const { $data, meta } = this.opts; + if (!meta) return; + json_schema_2019_09_1.default.call(this, $data); + this.refs["http://json-schema.org/schema"] = META_SCHEMA_ID; + } + defaultMeta() { + return this.opts.defaultMeta = super.defaultMeta() || (this.getSchema(META_SCHEMA_ID) ? META_SCHEMA_ID : void 0); + } + }; + exports.Ajv2019 = Ajv2019; + module.exports = exports = Ajv2019; + module.exports.Ajv2019 = Ajv2019; + Object.defineProperty(exports, "__esModule", { value: true }); + exports.default = Ajv2019; + var validate_1 = require_validate(); + Object.defineProperty(exports, "KeywordCxt", { + enumerable: true, + get: function() { + return validate_1.KeywordCxt; + } + }); + var codegen_1 = require_codegen(); + Object.defineProperty(exports, "_", { + enumerable: true, + get: function() { + return codegen_1._; + } + }); + Object.defineProperty(exports, "str", { + enumerable: true, + get: function() { + return codegen_1.str; + } + }); + Object.defineProperty(exports, "stringify", { + enumerable: true, + get: function() { + return codegen_1.stringify; + } + }); + Object.defineProperty(exports, "nil", { + enumerable: true, + get: function() { + return codegen_1.nil; + } + }); + Object.defineProperty(exports, "Name", { + enumerable: true, + get: function() { + return codegen_1.Name; + } + }); + Object.defineProperty(exports, "CodeGen", { + enumerable: true, + get: function() { + return codegen_1.CodeGen; + } + }); + var validation_error_1 = require_validation_error(); + Object.defineProperty(exports, "ValidationError", { + enumerable: true, + get: function() { + return validation_error_1.default; + } + }); + var ref_error_1 = require_ref_error(); + Object.defineProperty(exports, "MissingRefError", { + enumerable: true, + get: function() { + return ref_error_1.default; + } + }); +})); + +//#endregion +//#region ../../node_modules/.pnpm/ajv@8.18.0/node_modules/ajv/dist/vocabularies/draft2020.js +var require_draft2020 = /* @__PURE__ */ __commonJSMin(((exports) => { + Object.defineProperty(exports, "__esModule", { value: true }); + const core_1 = require_core$2(); + const validation_1 = require_validation$2(); + const applicator_1 = require_applicator$2(); + const dynamic_1 = require_dynamic(); + const next_1 = require_next(); + const unevaluated_1 = require_unevaluated$1(); + const format_1 = require_format$1(); + const metadata_1 = require_metadata(); + const draft2020Vocabularies = [ + dynamic_1.default, + core_1.default, + validation_1.default, + (0, applicator_1.default)(true), + format_1.default, + metadata_1.metadataVocabulary, + metadata_1.contentVocabulary, + next_1.default, + unevaluated_1.default + ]; + exports.default = draft2020Vocabularies; +})); + +//#endregion +//#region ../../node_modules/.pnpm/ajv@8.18.0/node_modules/ajv/dist/refs/json-schema-2020-12/schema.json +var require_schema = /* @__PURE__ */ __commonJSMin(((exports, module) => { + module.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": true, + "https://json-schema.org/draft/2020-12/vocab/applicator": true, + "https://json-schema.org/draft/2020-12/vocab/unevaluated": true, + "https://json-schema.org/draft/2020-12/vocab/validation": true, + "https://json-schema.org/draft/2020-12/vocab/meta-data": true, + "https://json-schema.org/draft/2020-12/vocab/format-annotation": true, + "https://json-schema.org/draft/2020-12/vocab/content": true + }, + "$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": true, + "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": true, + "default": {} + }, + "$recursiveAnchor": { + "$comment": "\"$recursiveAnchor\" has been replaced by \"$dynamicAnchor\".", + "$ref": "meta/core#/$defs/anchorString", + "deprecated": true + }, + "$recursiveRef": { + "$comment": "\"$recursiveRef\" has been replaced by \"$dynamicRef\".", + "$ref": "meta/core#/$defs/uriReferenceString", + "deprecated": true + } + } + }; +})); + +//#endregion +//#region ../../node_modules/.pnpm/ajv@8.18.0/node_modules/ajv/dist/refs/json-schema-2020-12/meta/applicator.json +var require_applicator = /* @__PURE__ */ __commonJSMin(((exports, module) => { + module.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": true }, + "$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" } + } } + }; +})); + +//#endregion +//#region ../../node_modules/.pnpm/ajv@8.18.0/node_modules/ajv/dist/refs/json-schema-2020-12/meta/unevaluated.json +var require_unevaluated = /* @__PURE__ */ __commonJSMin(((exports, module) => { + module.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": true }, + "$dynamicAnchor": "meta", + "title": "Unevaluated applicator vocabulary meta-schema", + "type": ["object", "boolean"], + "properties": { + "unevaluatedItems": { "$dynamicRef": "#meta" }, + "unevaluatedProperties": { "$dynamicRef": "#meta" } + } + }; +})); + +//#endregion +//#region ../../node_modules/.pnpm/ajv@8.18.0/node_modules/ajv/dist/refs/json-schema-2020-12/meta/content.json +var require_content = /* @__PURE__ */ __commonJSMin(((exports, module) => { + module.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": true }, + "$dynamicAnchor": "meta", + "title": "Content vocabulary meta-schema", + "type": ["object", "boolean"], + "properties": { + "contentEncoding": { "type": "string" }, + "contentMediaType": { "type": "string" }, + "contentSchema": { "$dynamicRef": "#meta" } + } + }; +})); + +//#endregion +//#region ../../node_modules/.pnpm/ajv@8.18.0/node_modules/ajv/dist/refs/json-schema-2020-12/meta/core.json +var require_core = /* @__PURE__ */ __commonJSMin(((exports, module) => { + module.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": true }, + "$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" + } + } + }; +})); + +//#endregion +//#region ../../node_modules/.pnpm/ajv@8.18.0/node_modules/ajv/dist/refs/json-schema-2020-12/meta/format-annotation.json +var require_format_annotation = /* @__PURE__ */ __commonJSMin(((exports, module) => { + module.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": true }, + "$dynamicAnchor": "meta", + "title": "Format vocabulary meta-schema for annotation results", + "type": ["object", "boolean"], + "properties": { "format": { "type": "string" } } + }; +})); + +//#endregion +//#region ../../node_modules/.pnpm/ajv@8.18.0/node_modules/ajv/dist/refs/json-schema-2020-12/meta/meta-data.json +var require_meta_data = /* @__PURE__ */ __commonJSMin(((exports, module) => { + module.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": true }, + "$dynamicAnchor": "meta", + "title": "Meta-data vocabulary meta-schema", + "type": ["object", "boolean"], + "properties": { + "title": { "type": "string" }, + "description": { "type": "string" }, + "default": true, + "deprecated": { + "type": "boolean", + "default": false + }, + "readOnly": { + "type": "boolean", + "default": false + }, + "writeOnly": { + "type": "boolean", + "default": false + }, + "examples": { + "type": "array", + "items": true + } + } + }; +})); + +//#endregion +//#region ../../node_modules/.pnpm/ajv@8.18.0/node_modules/ajv/dist/refs/json-schema-2020-12/meta/validation.json +var require_validation = /* @__PURE__ */ __commonJSMin(((exports, module) => { + module.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": true }, + "$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": true + }] }, + "const": true, + "enum": { + "type": "array", + "items": true + }, + "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": false + }, + "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": true, + "default": [] + } + } + }; +})); + +//#endregion +//#region ../../node_modules/.pnpm/ajv@8.18.0/node_modules/ajv/dist/refs/json-schema-2020-12/index.js +var require_json_schema_2020_12 = /* @__PURE__ */ __commonJSMin(((exports) => { + Object.defineProperty(exports, "__esModule", { value: true }); + const metaSchema = require_schema(); + const applicator = require_applicator(); + const unevaluated = require_unevaluated(); + const content = require_content(); + const core = require_core(); + const format = require_format_annotation(); + const metadata = require_meta_data(); + const validation = require_validation(); + const META_SUPPORT_DATA = ["/properties"]; + function addMetaSchema2020($data) { + [ + metaSchema, + applicator, + unevaluated, + content, + core, + with$data(this, format), + metadata, + with$data(this, validation) + ].forEach((sch) => this.addMetaSchema(sch, void 0, false)); + return this; + function with$data(ajv, sch) { + return $data ? ajv.$dataMetaSchema(sch, META_SUPPORT_DATA) : sch; + } + } + exports.default = addMetaSchema2020; +})); + +//#endregion +//#region ../../node_modules/.pnpm/ajv@8.18.0/node_modules/ajv/dist/2020.js +var require__2020 = /* @__PURE__ */ __commonJSMin(((exports, module) => { + Object.defineProperty(exports, "__esModule", { value: true }); + exports.MissingRefError = exports.ValidationError = exports.CodeGen = exports.Name = exports.nil = exports.stringify = exports.str = exports._ = exports.KeywordCxt = exports.Ajv2020 = void 0; + const core_1 = require_core$3(); + const draft2020_1 = require_draft2020(); + const discriminator_1 = require_discriminator(); + const json_schema_2020_12_1 = require_json_schema_2020_12(); + const META_SCHEMA_ID = "https://json-schema.org/draft/2020-12/schema"; + var Ajv2020 = class extends core_1.default { + constructor(opts = {}) { + super({ + ...opts, + dynamicRef: true, + next: true, + unevaluated: true + }); + } + _addVocabularies() { + super._addVocabularies(); + draft2020_1.default.forEach((v) => this.addVocabulary(v)); + if (this.opts.discriminator) this.addKeyword(discriminator_1.default); + } + _addDefaultMetaSchema() { + super._addDefaultMetaSchema(); + const { $data, meta } = this.opts; + if (!meta) return; + json_schema_2020_12_1.default.call(this, $data); + this.refs["http://json-schema.org/schema"] = META_SCHEMA_ID; + } + defaultMeta() { + return this.opts.defaultMeta = super.defaultMeta() || (this.getSchema(META_SCHEMA_ID) ? META_SCHEMA_ID : void 0); + } + }; + exports.Ajv2020 = Ajv2020; + module.exports = exports = Ajv2020; + module.exports.Ajv2020 = Ajv2020; + Object.defineProperty(exports, "__esModule", { value: true }); + exports.default = Ajv2020; + var validate_1 = require_validate(); + Object.defineProperty(exports, "KeywordCxt", { + enumerable: true, + get: function() { + return validate_1.KeywordCxt; + } + }); + var codegen_1 = require_codegen(); + Object.defineProperty(exports, "_", { + enumerable: true, + get: function() { + return codegen_1._; + } + }); + Object.defineProperty(exports, "str", { + enumerable: true, + get: function() { + return codegen_1.str; + } + }); + Object.defineProperty(exports, "stringify", { + enumerable: true, + get: function() { + return codegen_1.stringify; + } + }); + Object.defineProperty(exports, "nil", { + enumerable: true, + get: function() { + return codegen_1.nil; + } + }); + Object.defineProperty(exports, "Name", { + enumerable: true, + get: function() { + return codegen_1.Name; + } + }); + Object.defineProperty(exports, "CodeGen", { + enumerable: true, + get: function() { + return codegen_1.CodeGen; + } + }); + var validation_error_1 = require_validation_error(); + Object.defineProperty(exports, "ValidationError", { + enumerable: true, + get: function() { + return validation_error_1.default; + } + }); + var ref_error_1 = require_ref_error(); + Object.defineProperty(exports, "MissingRefError", { + enumerable: true, + get: function() { + return ref_error_1.default; + } + }); +})); + +//#endregion +//#region ../../node_modules/.pnpm/ajv-formats@3.0.1_ajv@8.18.0/node_modules/ajv-formats/dist/formats.js +var require_formats = /* @__PURE__ */ __commonJSMin(((exports) => { + Object.defineProperty(exports, "__esModule", { value: true }); + exports.formatNames = exports.fastFormats = exports.fullFormats = void 0; + function fmtDef(validate, compare) { + return { + validate, + compare + }; + } + exports.fullFormats = { + date: fmtDef(date, compareDate), + time: fmtDef(getTime(true), compareTime), + "date-time": fmtDef(getDateTime(true), compareDateTime), + "iso-time": fmtDef(getTime(), compareIsoTime), + "iso-date-time": fmtDef(getDateTime(), compareIsoDateTime), + duration: /^P(?!$)((\d+Y)?(\d+M)?(\d+D)?(T(?=\d)(\d+H)?(\d+M)?(\d+S)?)?|(\d+W)?)$/, + uri, + "uri-reference": /^(?:[a-z][a-z0-9+\-.]*:)?(?:\/?\/(?:(?:[a-z0-9\-._~!$&'()*+,;=:]|%[0-9a-f]{2})*@)?(?:\[(?:(?:(?:(?:[0-9a-f]{1,4}:){6}|::(?:[0-9a-f]{1,4}:){5}|(?:[0-9a-f]{1,4})?::(?:[0-9a-f]{1,4}:){4}|(?:(?:[0-9a-f]{1,4}:){0,1}[0-9a-f]{1,4})?::(?:[0-9a-f]{1,4}:){3}|(?:(?:[0-9a-f]{1,4}:){0,2}[0-9a-f]{1,4})?::(?:[0-9a-f]{1,4}:){2}|(?:(?:[0-9a-f]{1,4}:){0,3}[0-9a-f]{1,4})?::[0-9a-f]{1,4}:|(?:(?:[0-9a-f]{1,4}:){0,4}[0-9a-f]{1,4})?::)(?:[0-9a-f]{1,4}:[0-9a-f]{1,4}|(?:(?:25[0-5]|2[0-4]\d|[01]?\d\d?)\.){3}(?:25[0-5]|2[0-4]\d|[01]?\d\d?))|(?:(?:[0-9a-f]{1,4}:){0,5}[0-9a-f]{1,4})?::[0-9a-f]{1,4}|(?:(?:[0-9a-f]{1,4}:){0,6}[0-9a-f]{1,4})?::)|[Vv][0-9a-f]+\.[a-z0-9\-._~!$&'()*+,;=:]+)\]|(?:(?:25[0-5]|2[0-4]\d|[01]?\d\d?)\.){3}(?:25[0-5]|2[0-4]\d|[01]?\d\d?)|(?:[a-z0-9\-._~!$&'"()*+,;=]|%[0-9a-f]{2})*)(?::\d*)?(?:\/(?:[a-z0-9\-._~!$&'"()*+,;=:@]|%[0-9a-f]{2})*)*|\/(?:(?:[a-z0-9\-._~!$&'"()*+,;=:@]|%[0-9a-f]{2})+(?:\/(?:[a-z0-9\-._~!$&'"()*+,;=:@]|%[0-9a-f]{2})*)*)?|(?:[a-z0-9\-._~!$&'"()*+,;=:@]|%[0-9a-f]{2})+(?:\/(?:[a-z0-9\-._~!$&'"()*+,;=:@]|%[0-9a-f]{2})*)*)?(?:\?(?:[a-z0-9\-._~!$&'"()*+,;=:@/?]|%[0-9a-f]{2})*)?(?:#(?:[a-z0-9\-._~!$&'"()*+,;=:@/?]|%[0-9a-f]{2})*)?$/i, + "uri-template": /^(?:(?:[^\x00-\x20"'<>%\\^`{|}]|%[0-9a-f]{2})|\{[+#./;?&=,!@|]?(?:[a-z0-9_]|%[0-9a-f]{2})+(?::[1-9][0-9]{0,3}|\*)?(?:,(?:[a-z0-9_]|%[0-9a-f]{2})+(?::[1-9][0-9]{0,3}|\*)?)*\})*$/i, + url: /^(?:https?|ftp):\/\/(?:\S+(?::\S*)?@)?(?:(?!(?:10|127)(?:\.\d{1,3}){3})(?!(?:169\.254|192\.168)(?:\.\d{1,3}){2})(?!172\.(?:1[6-9]|2\d|3[0-1])(?:\.\d{1,3}){2})(?:[1-9]\d?|1\d\d|2[01]\d|22[0-3])(?:\.(?:1?\d{1,2}|2[0-4]\d|25[0-5])){2}(?:\.(?:[1-9]\d?|1\d\d|2[0-4]\d|25[0-4]))|(?:(?:[a-z0-9\u{00a1}-\u{ffff}]+-)*[a-z0-9\u{00a1}-\u{ffff}]+)(?:\.(?:[a-z0-9\u{00a1}-\u{ffff}]+-)*[a-z0-9\u{00a1}-\u{ffff}]+)*(?:\.(?:[a-z\u{00a1}-\u{ffff}]{2,})))(?::\d{2,5})?(?:\/[^\s]*)?$/iu, + email: /^[a-z0-9!#$%&'*+/=?^_`{|}~-]+(?:\.[a-z0-9!#$%&'*+/=?^_`{|}~-]+)*@(?:[a-z0-9](?:[a-z0-9-]*[a-z0-9])?\.)+[a-z0-9](?:[a-z0-9-]*[a-z0-9])?$/i, + hostname: /^(?=.{1,253}\.?$)[a-z0-9](?:[a-z0-9-]{0,61}[a-z0-9])?(?:\.[a-z0-9](?:[-0-9a-z]{0,61}[0-9a-z])?)*\.?$/i, + ipv4: /^(?:(?:25[0-5]|2[0-4]\d|1\d\d|[1-9]?\d)\.){3}(?:25[0-5]|2[0-4]\d|1\d\d|[1-9]?\d)$/, + ipv6: /^((([0-9a-f]{1,4}:){7}([0-9a-f]{1,4}|:))|(([0-9a-f]{1,4}:){6}(:[0-9a-f]{1,4}|((25[0-5]|2[0-4]\d|1\d\d|[1-9]?\d)(\.(25[0-5]|2[0-4]\d|1\d\d|[1-9]?\d)){3})|:))|(([0-9a-f]{1,4}:){5}(((:[0-9a-f]{1,4}){1,2})|:((25[0-5]|2[0-4]\d|1\d\d|[1-9]?\d)(\.(25[0-5]|2[0-4]\d|1\d\d|[1-9]?\d)){3})|:))|(([0-9a-f]{1,4}:){4}(((:[0-9a-f]{1,4}){1,3})|((:[0-9a-f]{1,4})?:((25[0-5]|2[0-4]\d|1\d\d|[1-9]?\d)(\.(25[0-5]|2[0-4]\d|1\d\d|[1-9]?\d)){3}))|:))|(([0-9a-f]{1,4}:){3}(((:[0-9a-f]{1,4}){1,4})|((:[0-9a-f]{1,4}){0,2}:((25[0-5]|2[0-4]\d|1\d\d|[1-9]?\d)(\.(25[0-5]|2[0-4]\d|1\d\d|[1-9]?\d)){3}))|:))|(([0-9a-f]{1,4}:){2}(((:[0-9a-f]{1,4}){1,5})|((:[0-9a-f]{1,4}){0,3}:((25[0-5]|2[0-4]\d|1\d\d|[1-9]?\d)(\.(25[0-5]|2[0-4]\d|1\d\d|[1-9]?\d)){3}))|:))|(([0-9a-f]{1,4}:){1}(((:[0-9a-f]{1,4}){1,6})|((:[0-9a-f]{1,4}){0,4}:((25[0-5]|2[0-4]\d|1\d\d|[1-9]?\d)(\.(25[0-5]|2[0-4]\d|1\d\d|[1-9]?\d)){3}))|:))|(:(((:[0-9a-f]{1,4}){1,7})|((:[0-9a-f]{1,4}){0,5}:((25[0-5]|2[0-4]\d|1\d\d|[1-9]?\d)(\.(25[0-5]|2[0-4]\d|1\d\d|[1-9]?\d)){3}))|:)))$/i, + regex, + 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, + int32: { + type: "number", + validate: validateInt32 + }, + int64: { + type: "number", + validate: validateInt64 + }, + float: { + type: "number", + validate: validateNumber + }, + double: { + type: "number", + validate: validateNumber + }, + password: true, + binary: true + }; + exports.fastFormats = { + ...exports.fullFormats, + date: fmtDef(/^\d\d\d\d-[0-1]\d-[0-3]\d$/, compareDate), + time: fmtDef(/^(?:[0-2]\d:[0-5]\d:[0-5]\d|23:59:60)(?:\.\d+)?(?:z|[+-]\d\d(?::?\d\d)?)$/i, compareTime), + "date-time": fmtDef(/^\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, compareDateTime), + "iso-time": fmtDef(/^(?:[0-2]\d:[0-5]\d:[0-5]\d|23:59:60)(?:\.\d+)?(?:z|[+-]\d\d(?::?\d\d)?)?$/i, compareIsoTime), + "iso-date-time": fmtDef(/^\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, compareIsoDateTime), + uri: /^(?:[a-z][a-z0-9+\-.]*:)(?:\/?\/)?[^\s]*$/i, + "uri-reference": /^(?:(?:[a-z][a-z0-9+\-.]*:)?\/?\/)?(?:[^\\\s#][^\s#]*)?(?:#[^\\\s]*)?$/i, + email: /^[a-z0-9.!#$%&'*+/=?^_`{|}~-]+@[a-z0-9](?:[a-z0-9-]{0,61}[a-z0-9])?(?:\.[a-z0-9](?:[a-z0-9-]{0,61}[a-z0-9])?)*$/i + }; + exports.formatNames = Object.keys(exports.fullFormats); + function isLeapYear(year) { + return year % 4 === 0 && (year % 100 !== 0 || year % 400 === 0); + } + const DATE = /^(\d\d\d\d)-(\d\d)-(\d\d)$/; + const DAYS = [ + 0, + 31, + 28, + 31, + 30, + 31, + 30, + 31, + 31, + 30, + 31, + 30, + 31 + ]; + function date(str) { + const matches = DATE.exec(str); + if (!matches) return false; + const year = +matches[1]; + const month = +matches[2]; + const day = +matches[3]; + return month >= 1 && month <= 12 && day >= 1 && day <= (month === 2 && isLeapYear(year) ? 29 : DAYS[month]); + } + function compareDate(d1, d2) { + if (!(d1 && d2)) return void 0; + if (d1 > d2) return 1; + if (d1 < d2) return -1; + return 0; + } + const TIME = /^(\d\d):(\d\d):(\d\d(?:\.\d+)?)(z|([+-])(\d\d)(?::?(\d\d))?)?$/i; + function getTime(strictTimeZone) { + return function time(str) { + const matches = TIME.exec(str); + if (!matches) return false; + const hr = +matches[1]; + const min = +matches[2]; + const sec = +matches[3]; + const tz = matches[4]; + const tzSign = matches[5] === "-" ? -1 : 1; + const tzH = +(matches[6] || 0); + const tzM = +(matches[7] || 0); + if (tzH > 23 || tzM > 59 || strictTimeZone && !tz) return false; + if (hr <= 23 && min <= 59 && sec < 60) return true; + const utcMin = min - tzM * tzSign; + const utcHr = hr - tzH * tzSign - (utcMin < 0 ? 1 : 0); + return (utcHr === 23 || utcHr === -1) && (utcMin === 59 || utcMin === -1) && sec < 61; + }; + } + function compareTime(s1, s2) { + if (!(s1 && s2)) return void 0; + const t1 = (/* @__PURE__ */ new Date("2020-01-01T" + s1)).valueOf(); + const t2 = (/* @__PURE__ */ new Date("2020-01-01T" + s2)).valueOf(); + if (!(t1 && t2)) return void 0; + return t1 - t2; + } + function compareIsoTime(t1, t2) { + if (!(t1 && t2)) return void 0; + const a1 = TIME.exec(t1); + const a2 = TIME.exec(t2); + if (!(a1 && a2)) return void 0; + t1 = a1[1] + a1[2] + a1[3]; + t2 = a2[1] + a2[2] + a2[3]; + if (t1 > t2) return 1; + if (t1 < t2) return -1; + return 0; + } + const DATE_TIME_SEPARATOR = /t|\s/i; + function getDateTime(strictTimeZone) { + const time = getTime(strictTimeZone); + return function date_time(str) { + const dateTime = str.split(DATE_TIME_SEPARATOR); + return dateTime.length === 2 && date(dateTime[0]) && time(dateTime[1]); + }; + } + function compareDateTime(dt1, dt2) { + if (!(dt1 && dt2)) return void 0; + const d1 = new Date(dt1).valueOf(); + const d2 = new Date(dt2).valueOf(); + if (!(d1 && d2)) return void 0; + return d1 - d2; + } + function compareIsoDateTime(dt1, dt2) { + if (!(dt1 && dt2)) return void 0; + const [d1, t1] = dt1.split(DATE_TIME_SEPARATOR); + const [d2, t2] = dt2.split(DATE_TIME_SEPARATOR); + const res = compareDate(d1, d2); + if (res === void 0) return void 0; + return res || compareTime(t1, t2); + } + const NOT_URI_FRAGMENT = /\/|:/; + const URI = /^(?:[a-z][a-z0-9+\-.]*:)(?:\/?\/(?:(?:[a-z0-9\-._~!$&'()*+,;=:]|%[0-9a-f]{2})*@)?(?:\[(?:(?:(?:(?:[0-9a-f]{1,4}:){6}|::(?:[0-9a-f]{1,4}:){5}|(?:[0-9a-f]{1,4})?::(?:[0-9a-f]{1,4}:){4}|(?:(?:[0-9a-f]{1,4}:){0,1}[0-9a-f]{1,4})?::(?:[0-9a-f]{1,4}:){3}|(?:(?:[0-9a-f]{1,4}:){0,2}[0-9a-f]{1,4})?::(?:[0-9a-f]{1,4}:){2}|(?:(?:[0-9a-f]{1,4}:){0,3}[0-9a-f]{1,4})?::[0-9a-f]{1,4}:|(?:(?:[0-9a-f]{1,4}:){0,4}[0-9a-f]{1,4})?::)(?:[0-9a-f]{1,4}:[0-9a-f]{1,4}|(?:(?:25[0-5]|2[0-4]\d|[01]?\d\d?)\.){3}(?:25[0-5]|2[0-4]\d|[01]?\d\d?))|(?:(?:[0-9a-f]{1,4}:){0,5}[0-9a-f]{1,4})?::[0-9a-f]{1,4}|(?:(?:[0-9a-f]{1,4}:){0,6}[0-9a-f]{1,4})?::)|[Vv][0-9a-f]+\.[a-z0-9\-._~!$&'()*+,;=:]+)\]|(?:(?:25[0-5]|2[0-4]\d|[01]?\d\d?)\.){3}(?:25[0-5]|2[0-4]\d|[01]?\d\d?)|(?:[a-z0-9\-._~!$&'()*+,;=]|%[0-9a-f]{2})*)(?::\d*)?(?:\/(?:[a-z0-9\-._~!$&'()*+,;=:@]|%[0-9a-f]{2})*)*|\/(?:(?:[a-z0-9\-._~!$&'()*+,;=:@]|%[0-9a-f]{2})+(?:\/(?:[a-z0-9\-._~!$&'()*+,;=:@]|%[0-9a-f]{2})*)*)?|(?:[a-z0-9\-._~!$&'()*+,;=:@]|%[0-9a-f]{2})+(?:\/(?:[a-z0-9\-._~!$&'()*+,;=:@]|%[0-9a-f]{2})*)*)(?:\?(?:[a-z0-9\-._~!$&'()*+,;=:@/?]|%[0-9a-f]{2})*)?(?:#(?:[a-z0-9\-._~!$&'()*+,;=:@/?]|%[0-9a-f]{2})*)?$/i; + function uri(str) { + return NOT_URI_FRAGMENT.test(str) && URI.test(str); + } + const BYTE = /^(?:[A-Za-z0-9+/]{4})*(?:[A-Za-z0-9+/]{2}==|[A-Za-z0-9+/]{3}=)?$/gm; + function byte(str) { + BYTE.lastIndex = 0; + return BYTE.test(str); + } + const MIN_INT32 = -(2 ** 31); + const MAX_INT32 = 2 ** 31 - 1; + function validateInt32(value) { + return Number.isInteger(value) && value <= MAX_INT32 && value >= MIN_INT32; + } + function validateInt64(value) { + return Number.isInteger(value); + } + function validateNumber() { + return true; + } + const Z_ANCHOR = /[^\\]\\Z/; + function regex(str) { + if (Z_ANCHOR.test(str)) return false; + try { + new RegExp(str); + return true; + } catch (e) { + return false; + } + } +})); + +//#endregion +//#region ../../node_modules/.pnpm/ajv-formats@3.0.1_ajv@8.18.0/node_modules/ajv-formats/dist/limit.js +var require_limit = /* @__PURE__ */ __commonJSMin(((exports) => { + Object.defineProperty(exports, "__esModule", { value: true }); + exports.formatLimitDefinition = void 0; + const ajv_1 = require_ajv(); + const codegen_1 = require_codegen(); + const ops = codegen_1.operators; + const KWDs = { + formatMaximum: { + okStr: "<=", + ok: ops.LTE, + fail: ops.GT + }, + formatMinimum: { + okStr: ">=", + ok: ops.GTE, + fail: ops.LT + }, + formatExclusiveMaximum: { + okStr: "<", + ok: ops.LT, + fail: ops.GTE + }, + formatExclusiveMinimum: { + okStr: ">", + ok: ops.GT, + fail: ops.LTE + } + }; + const error = { + message: ({ keyword, schemaCode }) => (0, codegen_1.str)`should be ${KWDs[keyword].okStr} ${schemaCode}`, + params: ({ keyword, schemaCode }) => (0, codegen_1._)`{comparison: ${KWDs[keyword].okStr}, limit: ${schemaCode}}` + }; + exports.formatLimitDefinition = { + keyword: Object.keys(KWDs), + type: "string", + schemaType: "string", + $data: true, + error, + code(cxt) { + const { gen, data, schemaCode, keyword, it } = cxt; + const { opts, self } = it; + if (!opts.validateFormats) return; + const fCxt = new ajv_1.KeywordCxt(it, self.RULES.all.format.definition, "format"); + if (fCxt.$data) validate$DataFormat(); + else validateFormat(); + function validate$DataFormat() { + const fmts = gen.scopeValue("formats", { + ref: self.formats, + code: opts.code.formats + }); + const fmt = gen.const("fmt", (0, codegen_1._)`${fmts}[${fCxt.schemaCode}]`); + cxt.fail$data((0, codegen_1.or)((0, codegen_1._)`typeof ${fmt} != "object"`, (0, codegen_1._)`${fmt} instanceof RegExp`, (0, codegen_1._)`typeof ${fmt}.compare != "function"`, compareCode(fmt))); + } + function validateFormat() { + const format = fCxt.schema; + const fmtDef = self.formats[format]; + if (!fmtDef || fmtDef === true) return; + if (typeof fmtDef != "object" || fmtDef instanceof RegExp || typeof fmtDef.compare != "function") throw new Error(`"${keyword}": format "${format}" does not define "compare" function`); + const fmt = gen.scopeValue("formats", { + key: format, + ref: fmtDef, + code: opts.code.formats ? (0, codegen_1._)`${opts.code.formats}${(0, codegen_1.getProperty)(format)}` : void 0 + }); + cxt.fail$data(compareCode(fmt)); + } + function compareCode(fmt) { + return (0, codegen_1._)`${fmt}.compare(${data}, ${schemaCode}) ${KWDs[keyword].fail} 0`; + } + }, + dependencies: ["format"] + }; + const formatLimitPlugin = (ajv) => { + ajv.addKeyword(exports.formatLimitDefinition); + return ajv; + }; + exports.default = formatLimitPlugin; +})); + +//#endregion +//#region ../../node_modules/.pnpm/ajv-formats@3.0.1_ajv@8.18.0/node_modules/ajv-formats/dist/index.js +var require_dist = /* @__PURE__ */ __commonJSMin(((exports, module) => { + Object.defineProperty(exports, "__esModule", { value: true }); + const formats_1 = require_formats(); + const limit_1 = require_limit(); + const codegen_1 = require_codegen(); + const fullName = new codegen_1.Name("fullFormats"); + const fastName = new codegen_1.Name("fastFormats"); + const formatsPlugin = (ajv, opts = { keywords: true }) => { + if (Array.isArray(opts)) { + addFormats(ajv, opts, formats_1.fullFormats, fullName); + return ajv; + } + const [formats, exportName] = opts.mode === "fast" ? [formats_1.fastFormats, fastName] : [formats_1.fullFormats, fullName]; + addFormats(ajv, opts.formats || formats_1.formatNames, formats, exportName); + if (opts.keywords) (0, limit_1.default)(ajv); + return ajv; + }; + formatsPlugin.get = (name, mode = "full") => { + const f = (mode === "fast" ? formats_1.fastFormats : formats_1.fullFormats)[name]; + if (!f) throw new Error(`Unknown format "${name}"`); + return f; + }; + function addFormats(ajv, list, fs, exportName) { + var _a; + var _b; + (_a = (_b = ajv.opts.code).formats) !== null && _a !== void 0 || (_b.formats = (0, codegen_1._)`require("ajv-formats/dist/formats").${exportName}`); + for (const f of list) ajv.addFormat(f, fs[f]); + } + module.exports = exports = formatsPlugin; + Object.defineProperty(exports, "__esModule", { value: true }); + exports.default = formatsPlugin; +})); + +//#endregion +//#region ../core-internal/src/validators/ajvProvider.ts +var import_ajv = require_ajv(); +var import__2019 = require__2019(); +var import__2020 = require__2020(); +var import_dist = /* @__PURE__ */ __toESM(require_dist(), 1); +/** `ajv-formats` default export, normalised through the CJS/ESM interop wrapper. */ +const ajvProvider_CEoC_sr_addFormats = import_dist.default; +function createDefaultAjvInstance(engineClass) { + const ajv = new engineClass({ + strict: false, + validateFormats: true, + validateSchema: false, + allErrors: true + }); + ajvProvider_CEoC_sr_addFormats(ajv); + return ajv; +} +/** +* AJV-backed JSON Schema validator. See `@modelcontextprotocol/{client,server}/validators/ajv` +* for the customisation entry point (re-exports `Ajv` and `addFormats` from the bundled copy). +* +* Default dispatches on the schema's declared dialect: no `$schema` or 2020-12 → `Ajv2020` +* (SEP-1613); 2019-09 → `Ajv2019`; draft-07 or draft-06 → the classic draft-07 `Ajv` class +* (draft-07's changes over draft-06 are additive, so one engine covers both). Known draft-07 deviation: classic Ajv +* evaluates keywords adjacent to `$ref` (stricter than draft-07's ignore-siblings rule, matching +* v1's default engine), while the cfworker provider ignores them per spec. +* Schemas declaring any other `$schema` are +* rejected with a plain `Error`; pass a pre-configured Ajv instance to validate +* other dialects. The SDK bundles ajv internally but does not re-export `Ajv2020` (its type +* graph tips downstream declaration bundling — see #2339). To construct a custom 2020-12 +* instance, add `ajv` to your own dependencies (matching the SDK's pinned version) and +* `import { Ajv2020 } from 'ajv/dist/2020.js'` — `new Ajv(...)` is the draft-07 class and would +* silently downgrade dialect. +* +* @example Use with default configuration +* ```ts source="./ajvProvider.examples.ts#AjvJsonSchemaValidator_default" +* const validator = new AjvJsonSchemaValidator(); +* ``` +* +* @example Use with a custom AJV instance +* ```ts source="./ajvProvider.examples.ts#AjvJsonSchemaValidator_customInstance" +* // import { Ajv2020 } from 'ajv/dist/2020.js'; +* const ajv = new Ajv2020({ strict: false, validateSchema: false, allErrors: true }); +* const validator = new AjvJsonSchemaValidator(ajv); +* ``` +* +* @example Register ajv-formats +* ```ts source="./ajvProvider.examples.ts#AjvJsonSchemaValidator_withFormats" +* // import { Ajv2020 } from 'ajv/dist/2020.js'; +* const ajv = new Ajv2020({ strict: false, validateSchema: false, allErrors: true }); +* addFormats(ajv); +* const validator = new AjvJsonSchemaValidator(ajv); +* ``` +*/ +var AjvJsonSchemaValidator = class { + _ajv; + /** Lazy classic (draft-07) engine, built on the first draft-07/draft-06-declared schema. */ + _ajvDraft7; + /** Lazy 2019-09 engine, built on the first 2019-09-declared schema. */ + _ajv2019; + /** True iff the constructor received a caller-supplied engine; the `$schema` dispatch is skipped. */ + _userAjv; + /** + * @param ajv - Optional pre-configured AJV-compatible instance. When supplied, this instance is + * used for **every** schema regardless of its declared `$schema` (the caller owns dialect + * choice). When omitted, the provider constructs per-dialect engines (`Ajv2020`, `Ajv2019`, + * and the classic draft-07 `Ajv` for draft-07/06-declared schemas) with + * `strict: false`, `validateFormats: true`, `validateSchema: false`, `allErrors: true`, and + * `ajv-formats` registered — **lazily, on the first {@linkcode getValidator} call needing each**, so + * constructing the provider (e.g. as the default validator of a `Client`/`Server` that never + * validates a JSON Schema) does not pay the ajv + ajv-formats instantiation cost. The parameter + * is typed structurally so consumers who don't pass an instance need not have `ajv` installed. + */ + constructor(ajv) { + this._userAjv = ajv !== void 0; + this._ajv = ajv; + } + /** The underlying 2020-12 engine — the default instance is created on first use. */ + get ajv() { + return this._ajv ??= createDefaultAjvInstance(import__2020.Ajv2020); + } + /** + * Pick the engine for a schema's declared dialect. A caller-supplied engine is used for + * every schema — do not second-guess by `$schema` (bring-your-own-validator means + * bring-your-own-dialect). Otherwise: no `$schema` or 2020-12 → `Ajv2020`; 2019-09 → + * `Ajv2019`; draft-07 or draft-06 → classic `Ajv`; anything else → `Error`. + */ + _engineFor(schema) { + if (this._userAjv) return this.ajv; + const dialect = declaredDialect(schema, "pass a pre-configured Ajv instance to AjvJsonSchemaValidator(ajv) to validate other dialects."); + if (dialect === "2020-12") return this.ajv; + if (dialect === "2019-09") return this._ajv2019 ??= createDefaultAjvInstance(import__2019.Ajv2019); + return this._ajvDraft7 ??= createDefaultAjvInstance(import_ajv.Ajv); + } + getValidator(schema) { + const engine = this._engineFor(schema); + const ajvValidator = "$id" in schema && typeof schema.$id === "string" ? engine.getSchema(schema.$id) ?? engine.compile(schema) : engine.compile(schema); + return (input) => { + return ajvValidator(input) ? { + valid: true, + data: input, + errorMessage: void 0 + } : { + valid: false, + data: void 0, + errorMessage: engine.errorsText(ajvValidator.errors) + }; + }; + } +}; +/** +* Draft-07 AJV class, re-exported for consumers who need to opt back to the pre-SEP-1613 default. +* The full v1-equivalent construction is: +* +* ```ts +* const ajv = new Ajv({ strict: false, validateFormats: true, validateSchema: false, allErrors: true }); +* addFormats(ajv); +* new AjvJsonSchemaValidator(ajv); +* ``` +* +* (omitting `validateSchema: false` makes a 2020-12-stamped `$schema` fail with an opaque +* "no schema with key or ref …" engine error; omitting `addFormats` silently drops `format` +* validation that the v1 default had). +* +* The SDK bundles ajv internally but does not re-export `Ajv2020` (its type graph tips downstream +* declaration bundling — see #2339). To construct a custom 2020-12 instance, add `ajv` to your own +* dependencies (matching the SDK's pinned version) and `import { Ajv2020 } from 'ajv/dist/2020.js'`. +*/ +const ajvProvider_CEoC_sr_Ajv = import_ajv.Ajv; + +//#endregion + +//# sourceMappingURL=ajvProvider-CEoC__sr.mjs.map + + + + + + + + +//#region src/server/completable.ts +const COMPLETABLE_SYMBOL = Symbol.for("mcp.completable"); +/** +* Wraps a schema to provide autocompletion capabilities. Useful for, e.g., prompt arguments in MCP. +* +* @example +* ```ts source="./completable.examples.ts#completable_basicUsage" +* server.registerPrompt( +* 'review-code', +* { +* title: 'Code Review', +* argsSchema: z.object({ +* language: completable(z.string().describe('Programming language'), value => +* ['typescript', 'javascript', 'python', 'rust', 'go'].filter(lang => lang.startsWith(value)) +* ) +* }) +* }, +* ({ language }) => ({ +* messages: [ +* { +* role: 'user' as const, +* content: { +* type: 'text' as const, +* text: `Review this ${language} code.` +* } +* } +* ] +* }) +* ); +* ``` +* +* @see {@linkcode server/mcp.McpServer.registerPrompt | McpServer.registerPrompt} for using completable schemas in prompt argument definitions +*/ +function completable(schema, complete) { + Object.defineProperty(schema, COMPLETABLE_SYMBOL, { + value: { complete }, + enumerable: false, + writable: false, + configurable: false + }); + return schema; +} +/** +* Checks if a schema is completable (has completion metadata). +*/ +function isCompletable(schema) { + return !!schema && typeof schema === "object" && COMPLETABLE_SYMBOL in schema; +} +/** +* Gets the completer callback from a completable schema, if it exists. +*/ +function getCompleter(schema) { + return schema[COMPLETABLE_SYMBOL]?.complete; +} + +//#endregion +//#region src/server/sseKeepAlive.ts +/** Default interval between SSE keep-alive comment frames. */ +const mcp_DXXb3Vv3_DEFAULT_SSE_KEEP_ALIVE_MS = 15e3; +const MAX_TIMER_DELAY_MS = (/* unused pure expression or super */ null && (2 ** 31 - 1)); +/** Arms an unref'd timer, or disables keep-alive for invalid delays. */ +function mcp_DXXb3Vv3_armSseKeepAlive(intervalMs, onTick) { + if (!Number.isFinite(intervalMs) || intervalMs < 1) return; + const timer = setInterval(onTick, Math.min(intervalMs, MAX_TIMER_DELAY_MS)); + timer.unref?.(); + return timer; +} + +//#endregion +//#region src/server/serverEventBus.ts +/** +* A `ServerEventBus` backed by an in-process listener set. +* +* `publish()` delivers synchronously to the live listener set (a listener +* unsubscribing itself mid-dispatch is safe; the entry's listen-router +* listeners never unsubscribe peers). A throwing listener does not stop +* delivery to the others. +*/ +var mcp_DXXb3Vv3_InMemoryServerEventBus = class { + _listeners = /* @__PURE__ */ new Set(); + /** + * @param onerror - Optional callback for errors thrown by listeners + * during dispatch. + */ + constructor(onerror) { + this.onerror = onerror; + } + publish(event) { + for (const listener of this._listeners) try { + listener(event); + } catch (error) { + this.onerror?.(error instanceof Error ? error : new Error(String(error))); + } + } + subscribe(listener) { + this._listeners.add(listener); + let live = true; + return () => { + if (!live) return; + live = false; + this._listeners.delete(listener); + }; + } + /** The number of currently registered listeners (test/introspection only — the routers track capacity via their own open-subscription set). */ + get listenerCount() { + return this._listeners.size; + } +}; +/** Build a {@linkcode ServerNotifier} over a bus. */ +function mcp_DXXb3Vv3_createServerNotifier(bus) { + return { + toolsChanged: () => bus.publish({ kind: "tools_list_changed" }), + promptsChanged: () => bus.publish({ kind: "prompts_list_changed" }), + resourcesChanged: () => bus.publish({ kind: "resources_list_changed" }), + resourceUpdated: (uri) => bus.publish({ + kind: "resource_updated", + uri + }) + }; +} +/** +* Whether a `subscriptions/listen` filter accepts a given change event. +* +* Pure: no I/O, no mutation. The filter governs ONLY the four +* subscription-gated change types — non-gated notifications never reach the +* bus and are not modeled here. +* +* `resource_updated` matches only when `resourceSubscriptions` is present and +* contains the event's URI exactly (per the spec: "for these resource URIs"). +*/ +function listenFilterAccepts(filter, event) { + switch (event.kind) { + case "tools_list_changed": return filter.toolsListChanged === true; + case "prompts_list_changed": return filter.promptsListChanged === true; + case "resources_list_changed": return filter.resourcesListChanged === true; + case "resource_updated": return filter.resourceSubscriptions !== void 0 && filter.resourceSubscriptions.includes(event.uri); + } +} +/** +* The honored subset of a requested filter: keeps only the fields the client +* explicitly opted in to (drops `false` and absent fields), narrowed against +* the server's declared capabilities when supplied. The serving entry sends +* this back in `notifications/subscriptions/acknowledged` so the ack reflects +* what the server can actually deliver. +* +* - `toolsListChanged` is honored only when `capabilities.tools.listChanged` +* is advertised; likewise `promptsListChanged` / `resourcesListChanged`. +* - `resourceSubscriptions` is honored only when +* `capabilities.resources.subscribe` is advertised. +* +* `capabilities` is optional on this pure helper for test convenience only — +* both wired routers REQUIRE capabilities at the call site (the HTTP router's +* `serve()` takes a required parameter; `StdioListenRouter.serve()` throws +* before `setServerCapabilities()` was called), so the fail-open +* `undefined → honor everything` branch is never reachable on a wired entry. +*/ +function honoredSubset(requested, capabilities) { + const honored = {}; + const allow = (bit) => capabilities === void 0 || bit === true; + if (requested.toolsListChanged === true && allow(capabilities?.tools?.listChanged)) honored.toolsListChanged = true; + if (requested.promptsListChanged === true && allow(capabilities?.prompts?.listChanged)) honored.promptsListChanged = true; + if (requested.resourcesListChanged === true && allow(capabilities?.resources?.listChanged)) honored.resourcesListChanged = true; + if (requested.resourceSubscriptions !== void 0 && requested.resourceSubscriptions.length > 0 && allow(capabilities?.resources?.subscribe)) honored.resourceSubscriptions = [...requested.resourceSubscriptions]; + return honored; +} +/** Map a {@linkcode ServerEvent} onto its wire notification `{method, params}`. */ +function serverEventToNotification(event) { + switch (event.kind) { + case "tools_list_changed": return { method: "notifications/tools/list_changed" }; + case "prompts_list_changed": return { method: "notifications/prompts/list_changed" }; + case "resources_list_changed": return { method: "notifications/resources/list_changed" }; + case "resource_updated": return { + method: "notifications/resources/updated", + params: { uri: event.uri } + }; + } +} + +//#endregion +//#region src/server/listenRouter.ts +/** Default capacity guard: refuse a new subscription when this many are already open. */ +const mcp_DXXb3Vv3_DEFAULT_MAX_SUBSCRIPTIONS = 1024; +function jsonRpcError(id, code, message) { + return Response.json({ + jsonrpc: "2.0", + error: { + code, + message + }, + id + }, { status: 200 }); +} +/** Stamp the subscription id onto a notification's `_meta`. Non-mutating. */ +function stampSubscriptionId(notification, subscriptionId) { + return { + method: notification.method, + params: { + ...notification.params, + _meta: { + ...notification.params?._meta, + [SUBSCRIPTION_ID_META_KEY]: subscriptionId + } + } + }; +} +/** +* Read the requested filter off a `subscriptions/listen` request body. +* Returns the validated filter, or `undefined` when `params.notifications` +* is absent or fails the schema (the caller answers `-32602` — the spec +* marks `notifications` REQUIRED on the listen request). +*/ +function parseListenFilter(message) { + const outcome = codecForVersion(MODERN_WIRE_REVISION).validateRequest("subscriptions/listen", message); + return outcome.ok ? outcome.value.params?.notifications : void 0; +} +function mcp_DXXb3Vv3_createListenRouter(options) { + const { bus, onerror } = options; + const maxSubscriptions = options.maxSubscriptions ?? mcp_DXXb3Vv3_DEFAULT_MAX_SUBSCRIPTIONS; + const keepAliveMs = options.keepAliveMs ?? mcp_DXXb3Vv3_DEFAULT_SSE_KEEP_ALIVE_MS; + const open = /* @__PURE__ */ new Set(); + function serve(message, signal, capabilities, serverInfo) { + if (open.size >= maxSubscriptions) { + onerror?.(/* @__PURE__ */ new Error(`subscriptions/listen refused: subscription limit reached (${maxSubscriptions})`)); + return jsonRpcError(message.id, -32603, "Subscription limit reached"); + } + const filter = parseListenFilter(message); + if (filter === void 0) return jsonRpcError(message.id, -32602, "Invalid params: 'notifications' is required and must be a valid SubscriptionFilter"); + const honored = honoredSubset(filter, capabilities); + const subscriptionId = message.id; + const encoder = new TextEncoder(); + let controller; + let closed = false; + let unsubscribe; + let keepAliveTimer; + let abortCleanup; + const writeFrame = (frame) => { + if (closed) return; + try { + controller.enqueue(encoder.encode(frame)); + } catch (error) { + onerror?.(error instanceof Error ? error : new Error(String(error))); + } + }; + const writeNotification = (method, params) => { + writeFrame(`event: message\ndata: ${JSON.stringify({ + jsonrpc: "2.0", + method, + params + })}\n\n`); + }; + const teardown = (graceful) => { + if (closed) return; + if (graceful) writeFrame(`event: message\ndata: ${JSON.stringify({ + jsonrpc: "2.0", + id: subscriptionId, + result: { + resultType: "complete", + _meta: { + [SUBSCRIPTION_ID_META_KEY]: subscriptionId, + [SERVER_INFO_META_KEY]: serverInfo + } + } + })}\n\n`); + closed = true; + try { + unsubscribe?.(); + } catch (error) { + onerror?.(error instanceof Error ? error : new Error(String(error))); + } + if (keepAliveTimer !== void 0) clearInterval(keepAliveTimer); + abortCleanup?.(); + open.delete(teardown); + try { + controller.close(); + } catch {} + }; + const readable = new ReadableStream({ + start(streamController) { + controller = streamController; + const ack = stampSubscriptionId({ + method: "notifications/subscriptions/acknowledged", + params: { notifications: honored } + }, subscriptionId); + writeNotification(ack.method, ack.params); + unsubscribe = bus.subscribe((event) => { + if (closed || !listenFilterAccepts(honored, event)) return; + const note = stampSubscriptionId(serverEventToNotification(event), subscriptionId); + writeNotification(note.method, note.params); + }); + keepAliveTimer = mcp_DXXb3Vv3_armSseKeepAlive(keepAliveMs, () => writeFrame(": keepalive\n\n")); + open.add(teardown); + }, + cancel() { + teardown(false); + } + }); + if (signal !== void 0) if (signal.aborted) teardown(false); + else { + const onAbort = () => teardown(false); + signal.addEventListener("abort", onAbort, { once: true }); + abortCleanup = () => signal.removeEventListener("abort", onAbort); + } + return new Response(readable, { + status: 200, + headers: { + "Content-Type": "text/event-stream", + "Cache-Control": "no-cache, no-transform", + Connection: "keep-alive", + "X-Accel-Buffering": "no" + } + }); + } + return { + serve, + closeAll() { + for (const teardown of open) teardown(true); + }, + get openCount() { + return open.size; + } + }; +} +const CHANGE_NOTIFICATION_METHODS = new Set([ + "notifications/tools/list_changed", + "notifications/prompts/list_changed", + "notifications/resources/list_changed", + "notifications/resources/updated" +]); +/** +* Per-connection listen state for the stdio entry. One instance is held by +* `serveStdio` for the connection lifetime; it routes inbound +* `subscriptions/listen` / `notifications/cancelled` and rewrites outbound +* change notifications onto the active subscriptions. No bus — the long-lived +* pinned instance's existing `send*ListChanged()` calls feed straight into +* `routeOutbound()`. +*/ +var mcp_DXXb3Vv3_StdioListenRouter = class { + /** Active subscriptions, keyed by the listen request's JSON-RPC id verbatim. */ + _subs = /* @__PURE__ */ new Map(); + /** + * The serving instance's declared capabilities. Filled in by the entry + * once the modern instance is constructed (the router is created before + * the instance exists), so the acknowledged filter is narrowed against + * what the server can actually deliver. + */ + _serverCapabilities; + /** + * The serving instance's identity, stamped onto the graceful-close + * results' `_meta` (the spec's `SubscriptionsListenResultMeta` extends + * `ResultMetaObject`). Handed over together with the capabilities. + */ + _serverInfo; + constructor(_maxSubscriptions = mcp_DXXb3Vv3_DEFAULT_MAX_SUBSCRIPTIONS, serverCapabilities, serverInfo) { + this._maxSubscriptions = _maxSubscriptions; + this._serverCapabilities = serverCapabilities; + this._serverInfo = serverInfo; + } + /** + * Record the serving instance's declared capabilities and identity once + * it has been constructed. Called by `serveStdio`'s connect path; + * subsequent `serve()` calls narrow the honored filter against the + * capabilities, and `teardownAll()` stamps the identity. + */ + setServerCapabilities(capabilities, serverInfo) { + this._serverCapabilities = capabilities; + if (serverInfo !== void 0) this._serverInfo = serverInfo; + } + /** Whether `id` is an active listen subscription on this connection. */ + has(id) { + return this._subs.has(id); + } + /** + * Serve one inbound `subscriptions/listen` request: registers the + * subscription and returns the stamped acknowledged notification (or, on + * capacity / params rejection, the in-band JSON-RPC error response). + * + * @throws when called before {@linkcode setServerCapabilities} (or the + * constructor) has supplied the serving instance's capabilities. Honoring a + * filter without knowing the server's advertised capabilities would fail + * open (deliver unadvertised types); the entry guarantees capabilities are + * set before any listen request is routed here. + */ + serve(message) { + if (this._serverCapabilities === void 0) throw new Error("StdioListenRouter.serve() called before setServerCapabilities(); refusing to honor a filter without capabilities"); + if (this._subs.size >= this._maxSubscriptions) return { + jsonrpc: "2.0", + id: message.id, + error: { + code: -32603, + message: "Subscription limit reached" + } + }; + const filter = parseListenFilter(message); + if (filter === void 0) return { + jsonrpc: "2.0", + id: message.id, + error: { + code: -32602, + message: "Invalid params: 'notifications' is required and must be a valid SubscriptionFilter" + } + }; + const honored = honoredSubset(filter, this._serverCapabilities); + this._subs.set(message.id, honored); + return stampSubscriptionId({ + method: "notifications/subscriptions/acknowledged", + params: { notifications: honored } + }, message.id); + } + /** + * Tear down one subscription (inbound `notifications/cancelled`). Returns + * `true` when a subscription was removed. After this call NOTHING further + * is delivered for that subscription id (the post-cancel hardening). + */ + cancel(id) { + return this._subs.delete(id); + } + /** + * Route an outbound notification through the active subscriptions. + * + * - For a subscription-gated change notification, returns one stamped copy + * per subscription that opted in to it (an empty array means it is + * dropped — the modern era never delivers an un-requested change type). + * - For any other outbound message, returns `'passthrough'` (the entry + * forwards it as-is). + */ + routeOutbound(message) { + if (!CHANGE_NOTIFICATION_METHODS.has(message.method)) return "passthrough"; + const uriParam = message.params?.["uri"]; + const uri = typeof uriParam === "string" ? uriParam : void 0; + const event = notificationToServerEvent(message.method, uri); + const out = []; + for (const [subscriptionId, filter] of this._subs) if (listenFilterAccepts(filter, event)) out.push(stampSubscriptionId({ + method: message.method, + params: message.params ?? {} + }, subscriptionId)); + return out; + } + /** + * Server-side graceful teardown of every active subscription: returns the + * empty `subscriptions/listen` JSON-RPC result for each subscription id — + * the spec's graceful-close signal, `_meta` carrying the subscription id + * and the serving instance's identity — for the entry to emit before + * closing the wire. Clears the set so nothing further is delivered. + */ + teardownAll() { + const out = []; + for (const id of this._subs.keys()) out.push({ + jsonrpc: "2.0", + id, + result: { + resultType: "complete", + _meta: { + [SUBSCRIPTION_ID_META_KEY]: id, + ...this._serverInfo !== void 0 && { [SERVER_INFO_META_KEY]: this._serverInfo } + } + } + }); + this._subs.clear(); + return out; + } +}; +function notificationToServerEvent(method, uri) { + switch (method) { + case "notifications/tools/list_changed": return { kind: "tools_list_changed" }; + case "notifications/prompts/list_changed": return { kind: "prompts_list_changed" }; + case "notifications/resources/list_changed": return { kind: "resources_list_changed" }; + default: return { + kind: "resource_updated", + uri: uri ?? "" + }; + } +} + +//#endregion +//#region src/server/legacyInputRequiredShim.ts +/** +* Default handler re-entries per originating request — tighter than the +* client driver's 10 because the shim holds a live wire request open. +*/ +const DEFAULT_LEGACY_SHIM_MAX_ROUNDS = 8; +/** Default per-leg timeout: legs are human-paced, so the 60s protocol default is wrong. */ +const DEFAULT_LEGACY_SHIM_ROUND_TIMEOUT_MS = 6e5; +/** Resolves and validates `ServerOptions.inputRequired`, failing loudly at construction time. */ +function resolveLegacyShimOptions(options) { + if (options?.maxRounds !== void 0 && (!Number.isInteger(options.maxRounds) || options.maxRounds < 1)) throw new RangeError(`inputRequired.maxRounds must be a positive integer (got ${options.maxRounds})`); + if (options?.roundTimeoutMs !== void 0 && (!Number.isFinite(options.roundTimeoutMs) || options.roundTimeoutMs <= 0)) throw new RangeError(`inputRequired.roundTimeoutMs must be a positive number (got ${options.roundTimeoutMs})`); + return { + maxRounds: options?.maxRounds ?? DEFAULT_LEGACY_SHIM_MAX_ROUNDS, + roundTimeoutMs: options?.roundTimeoutMs ?? DEFAULT_LEGACY_SHIM_ROUND_TIMEOUT_MS, + legacyShim: options?.legacyShim ?? true + }; +} +/** +* Validates one `inputRequests` entry: malformed or unknown kinds are server +* bugs and fail loudly on both eras. Shared by the modern seam's capability +* check and the shim's gate. +*/ +function coerceEmbeddedInputRequest(method, key, entry) { + if (entry === null || typeof entry !== "object" || typeof entry.method !== "string") throw new src_CX2iR2pK_ProtocolError(src_CX2iR2pK_ProtocolErrorCode.InternalError, `Handler for ${method} returned an invalid input request '${key}': each inputRequests entry must be an embedded elicitation/create, sampling/createMessage, or roots/list request`); + const embedded = entry; + const required = requiredClientCapabilitiesForInputRequest(embedded); + if (required === void 0) throw new src_CX2iR2pK_ProtocolError(src_CX2iR2pK_ProtocolErrorCode.InternalError, `Handler for ${method} returned an input request '${key}' of kind '${embedded.method}', which is not an embedded request the 2026-07-28 revision defines`); + return { + embedded, + required + }; +} +/** +* The 2025-11-25 URL-mode wire shape requires an `elicitationId`; the 2026 +* in-band shape has none, so URL legs mint one (CSPRNG-backed, with a +* getRandomValues fallback for runtimes without `randomUUID`). +*/ +function syntheticElicitationId() { + const webCrypto = globalThis.crypto; + if (webCrypto?.randomUUID !== void 0) return webCrypto.randomUUID(); + const bytes = new Uint8Array(16); + webCrypto.getRandomValues(bytes); + bytes[6] = bytes[6] & 15 | 64; + bytes[8] = bytes[8] & 63 | 128; + const hex = [...bytes].map((byte) => byte.toString(16).padStart(2, "0")).join(""); + return `${hex.slice(0, 8)}-${hex.slice(8, 12)}-${hex.slice(12, 16)}-${hex.slice(16, 20)}-${hex.slice(20)}`; +} +/** Per-family surfacing: tools/call → isError result (the 2025 idiom); prompts/resources → JSON-RPC error. */ +function legacyShimFailure(method, message) { + if (method === "tools/call") return { + content: [{ + type: "text", + text: message + }], + isError: true + }; + throw new src_CX2iR2pK_ProtocolError(src_CX2iR2pK_ProtocolErrorCode.InternalError, message); +} +/** The fulfilment loop — see the module doc for the contract. */ +var LegacyInputRequiredShim = class { + constructor(_host) { + this._host = _host; + } + async fulfill(method, handler, request, ctx, firstResult) { + const { maxRounds, roundTimeoutMs } = this._host; + const outerSignal = ctx.mcpReq.signal; + let current = firstResult; + let round = 0; + while (true) { + round += 1; + if (round > maxRounds) return legacyShimFailure(method, inputRequiredRoundsExceededMessage(method, maxRounds)); + const inputRequests = current.inputRequests; + const hasInputRequests = inputRequests != null && Object.keys(inputRequests).length > 0; + const requestState = typeof current.requestState === "string" ? current.requestState : void 0; + if (!hasInputRequests && requestState === void 0) throw new src_CX2iR2pK_ProtocolError(src_CX2iR2pK_ProtocolErrorCode.InternalError, `Handler for ${method} returned an input-required result with neither inputRequests nor requestState (every InputRequiredResult must include at least one of the two)`); + let responses; + if (hasInputRequests) { + const declared = this._host.resolvedClientCapabilities(ctx); + const coerced = []; + for (const [key, entry] of Object.entries(inputRequests)) { + const { embedded, required } = coerceEmbeddedInputRequest(method, key, entry); + if (embedded.method !== "roots/list" && embedded.params === void 0) throw new src_CX2iR2pK_ProtocolError(src_CX2iR2pK_ProtocolErrorCode.InternalError, `Handler for ${method} returned an input request '${key}' of kind '${embedded.method}' without params`); + if (src_CX2iR2pK_missingClientCapabilities(required, declared) !== void 0) return legacyShimFailure(method, `Cannot request input '${key}' (${embedded.method}): the client on this 2025-era connection did not declare the required capability${declared === void 0 ? " (no client capabilities are available on this connection — per-request legacy serving cannot receive server-to-client requests)" : ""}`); + coerced.push([key, embedded]); + } + const roundAbort = linkedRoundAbort(outerSignal); + try { + const legOptions = { + relatedRequestId: ctx.mcpReq.id, + timeout: roundTimeoutMs, + resetTimeoutOnProgress: true, + onprogress: () => {}, + signal: roundAbort.signal + }; + const fulfilled = await Promise.all(coerced.map(async ([key, embedded]) => { + try { + return [key, await this._dispatchLeg(embedded, legOptions)]; + } catch (error) { + roundAbort.abort(error); + throw error; + } + })); + responses = Object.fromEntries(fulfilled); + } catch (error) { + if (outerSignal.aborted) throw error; + return legacyShimFailure(method, `Fulfilling input required by '${method}' failed: ${error instanceof Error ? error.message : String(error)}`); + } finally { + roundAbort.dispose(); + } + } else await sleep((/* inlined export .C */250), outerSignal); + let ctxNext = { + ...ctx, + mcpReq: { + ...ctx.mcpReq, + inputResponses: responses, + droppedInputResponseKeys: void 0, + requestState: requestStateAccessor(requestState) + } + }; + if (requestState !== void 0) { + const decoded = await this._host.verifyRequestState(requestState, ctxNext, method); + if (decoded !== void 0) ctxNext = withRequestStateValue(ctxNext, decoded); + } + const next = await handler(request, ctxNext); + if (!isInputRequiredResult(next)) return next; + current = next; + } + } + /** Routes one embedded request through the host's existing 2025-era senders (gate already ran). */ + async _dispatchLeg(embedded, options) { + switch (embedded.method) { + case "elicitation/create": { + let params = embedded.params; + if (params.mode === "url" && params.elicitationId === void 0) params = { + ...params, + elicitationId: syntheticElicitationId() + }; + return await this._host.sendElicitation(params, options); + } + case "sampling/createMessage": return await this._host.sendSampling(embedded.params, options); + case "roots/list": return await this._host.listRoots(embedded.params, options); + } + } +}; + +//#endregion +//#region src/server/server.ts +/** +* The request methods whose 2026-07-28 result vocabulary includes +* `input_required` (the multi round-trip methods). Returning an +* input-required result from any other handler is a server bug. +*/ +const INPUT_REQUIRED_CAPABLE_METHODS = new Set([ + "tools/call", + "prompts/get", + "resources/read" +]); +let writeClientIdentity; +let installDiscoverHandler; +let readServerIdentity; +/** +* Package-internal: backfills the connection-scoped client-identity fields of a +* per-request server instance from the request's validated `_meta` envelope, so the +* (deprecated) {@linkcode Server.getClientCapabilities} / {@linkcode Server.getClientVersion} +* accessors keep answering on instances that never see an `initialize` handshake. +* Not public API. +*/ +function mcp_DXXb3Vv3_seedClientIdentityFromEnvelope(server, identity) { + writeClientIdentity(server, identity); +} +/** +* Package-internal: installs the modern-only `server/discover` handler on an instance +* the HTTP entry has marked as serving the 2026-07-28 era, and makes sure the modern +* revisions the entry serves appear in the instance's supported-versions list (so the +* discover advertisement and version-mismatch errors name them). Idempotent. +* Hand-constructed instances are unaffected: nothing else calls this, so they keep +* answering `-32601` unless their own supported-versions list opts into a modern +* revision. Not public API. +*/ +function mcp_DXXb3Vv3_installModernOnlyHandlers(server, servedModernVersions) { + installDiscoverHandler(server, servedModernVersions); +} +/** +* Package-internal: the instance's implementation identity, for the serving +* entries to stamp onto entry-built results (the `subscriptions/listen` +* graceful-close result — built outside the encode seam, but the spec's +* `SubscriptionsListenResultMeta` extends `ResultMetaObject`, so it carries +* the serverInfo SHOULD like every other result). Not public API. +*/ +function mcp_DXXb3Vv3_serverIdentityOf(server) { + return readServerIdentity(server); +} +/** +* An MCP server on top of a pluggable transport. +* +* This server will automatically respond to the initialization flow as initiated from the client. +* +* @deprecated Use {@linkcode server/mcp.McpServer | McpServer} instead for the high-level API. Only use `Server` for advanced use cases. +*/ +var Server = class extends Protocol { + _clientCapabilities; + _clientVersion; + static { + writeClientIdentity = (server, identity) => { + if (identity.clientCapabilities !== void 0) server._clientCapabilities = identity.clientCapabilities; + if (identity.clientInfo !== void 0) server._clientVersion = identity.clientInfo; + }; + installDiscoverHandler = (server, servedModernVersions) => { + const missing = servedModernVersions.filter((version) => !server._supportedProtocolVersions.includes(version)); + if (missing.length > 0) server._supportedProtocolVersions = [...server._supportedProtocolVersions, ...missing]; + server.setRequestHandler("server/discover", () => server._ondiscover()); + }; + readServerIdentity = (server) => server._serverInfo; + } + _capabilities; + _instructions; + _jsonSchemaValidator; + _cacheHints; + _requestStateVerify; + _inputRequiredServing; + _legacyShim; + /** Lazily-built legacy shim; the loop lives in legacyInputRequiredShim.ts behind a narrow host contract. */ + _legacyInputRequiredShim() { + return this._legacyShim ??= new LegacyInputRequiredShim({ + maxRounds: this._inputRequiredServing.maxRounds, + roundTimeoutMs: this._inputRequiredServing.roundTimeoutMs, + resolvedClientCapabilities: (ctx) => this._inputRequestCapabilityView(ctx), + verifyRequestState: (state, ctx, method) => this._verifyRequestState(state, ctx, method), + sendElicitation: (params, options) => this._sendElicitationLeg(params, options, { validateAcceptedContent: false }), + sendSampling: (params, options) => this.createMessage(params, options), + listRoots: (params, options) => this.listRoots(params, options) + }); + } + /** + * Callback for when initialization has fully completed (i.e., the client has sent an `notifications/initialized` notification). + */ + oninitialized; + /** + * Initializes this server with the given name and version information. + */ + constructor(_serverInfo, options) { + super(options); + this._serverInfo = _serverInfo; + this._capabilities = options?.capabilities ? { ...options.capabilities } : {}; + this._instructions = options?.instructions; + this._jsonSchemaValidator = options?.jsonSchemaValidator ?? new AjvJsonSchemaValidator(); + this._requestStateVerify = options?.requestState?.verify; + this._inputRequiredServing = resolveLegacyShimOptions(options?.inputRequired); + if (options?.cacheHints !== void 0) { + for (const [operation, hint] of Object.entries(options.cacheHints)) if (hint !== void 0) assertValidCacheHint(hint, `cacheHints['${operation}']`); + this._cacheHints = options.cacheHints; + } + this.setRequestHandler("initialize", (request) => this._oninitialize(request)); + this.setNotificationHandler("notifications/initialized", () => this.oninitialized?.()); + if (modernProtocolVersions(this._supportedProtocolVersions).length > 0) this.setRequestHandler("server/discover", () => this._ondiscover()); + if (this._capabilities.logging) this._registerLoggingHandler(); + } + /** + * Registers the built-in `logging/setLevel` request handler. + * + * @deprecated Deprecated as of protocol version 2026-07-28 (SEP-2577). + * Remains functional during the deprecation window (at least twelve months). + * Migrate to stderr logging (STDIO servers) or OpenTelemetry. + */ + _registerLoggingHandler() { + this.setRequestHandler("logging/setLevel", async (request, ctx) => { + const transportSessionId = ctx.sessionId || ctx.http?.req?.headers.get("mcp-session-id") || void 0; + const { level } = request.params; + const parseResult = parseSchema(LoggingLevelSchema, level); + if (parseResult.success) this._loggingLevels.set(transportSessionId, parseResult.data); + return {}; + }); + } + buildContext(ctx, transportInfo) { + const hasHttpInfo = ctx.http || transportInfo?.request || transportInfo?.closeSSEStream || transportInfo?.closeStandaloneSSEStream; + return { + ...ctx, + mcpReq: { + ...ctx.mcpReq, + log: (level, data, logger) => { + if (!this._capabilities.logging) return Promise.resolve(); + let threshold; + if (this._servedModernEra()) { + threshold = ctx.mcpReq.envelope?.[LOG_LEVEL_META_KEY]; + if (threshold === void 0) return Promise.resolve(); + } else threshold = this._loggingLevels.get(ctx.sessionId) ?? this._loggingLevels.get(void 0); + if (threshold !== void 0 && this.LOG_LEVEL_SEVERITY.get(level) < this.LOG_LEVEL_SEVERITY.get(threshold)) return Promise.resolve(); + return ctx.mcpReq.notify({ + method: "notifications/message", + params: { + level, + data, + logger + } + }); + }, + elicitInput: (params, options) => this.elicitInput(params, options), + requestSampling: (params, options) => this.createMessage(params, options) + }, + http: hasHttpInfo ? { + ...ctx.http, + req: transportInfo?.request, + closeSSE: transportInfo?.closeSSEStream, + closeStandaloneSSE: transportInfo?.closeStandaloneSSEStream + } : void 0 + }; + } + _loggingLevels = /* @__PURE__ */ new Map(); + LOG_LEVEL_SEVERITY = new Map(LoggingLevelSchema.options.map((level, index) => [level, index])); + isMessageIgnored = (level, sessionId) => { + const currentLevel = this._loggingLevels.get(sessionId); + return currentLevel ? this.LOG_LEVEL_SEVERITY.get(level) < this.LOG_LEVEL_SEVERITY.get(currentLevel) : false; + }; + /** + * Registers new capabilities. This can only be called before connecting to a transport. + * + * The new capabilities will be merged with any existing capabilities previously given (e.g., at initialization). + */ + registerCapabilities(capabilities) { + if (this.transport) throw new src_CX2iR2pK_SdkError(src_CX2iR2pK_SdkErrorCode.AlreadyConnected, "Cannot register capabilities after connecting to transport"); + const hadLogging = !!this._capabilities.logging; + this._capabilities = mergeCapabilities(this._capabilities, capabilities); + if (!hadLogging && this._capabilities.logging) this._registerLoggingHandler(); + } + /** + * Enforces server-side validation for `tools/call` results regardless of how the + * handler was registered, attaches the configured per-operation cache hint + * (when one exists) so the 2026-07-28 encode seam can fill `ttlMs`/`cacheScope` + * for results that do not provide their own, and owns the multi-round-trip + * seam: on the methods whose 2026-07-28 result vocabulary includes + * `input_required` (`tools/call`, `prompts/get`, `resources/read`) an + * input-required return skips result-schema validation and is checked + * against the served era, the at-least-one rule, and the request's own + * declared client capabilities; on every other method an input-required + * return is a server bug and fails loudly. The hint rides a symbol-keyed + * property that is never serialized, so 2025-era responses are unaffected. + */ + _wrapHandler(method, handler) { + if (method !== "tools/call") { + const cacheHint = this._cacheHints?.[method]; + const isInputRequiredCapable = INPUT_REQUIRED_CAPABLE_METHODS.has(method); + if (cacheHint === void 0 && !isInputRequiredCapable) return async (request, ctx) => { + const result = await handler(request, ctx); + if (isInputRequiredResult(result)) throw new src_CX2iR2pK_ProtocolError(src_CX2iR2pK_ProtocolErrorCode.InternalError, `Handler for ${method} returned an input-required result, but only tools/call, prompts/get and resources/read support input_required (protocol revision 2026-07-28)`); + return result; + }; + return async (request, ctx) => { + const result = isInputRequiredCapable ? await this._invokeInputRequiredCapableHandler(method, handler, request, ctx) : await handler(request, ctx); + if (isInputRequiredResult(result)) { + if (!isInputRequiredCapable) throw new src_CX2iR2pK_ProtocolError(src_CX2iR2pK_ProtocolErrorCode.InternalError, `Handler for ${method} returned an input-required result, but only tools/call, prompts/get and resources/read support input_required (protocol revision 2026-07-28)`); + return result; + } + return cacheHint === void 0 ? result : attachCacheHintFallback(result, cacheHint); + }; + } + return async (request, ctx) => { + const codec = src_CX2iR2pK_codecForVersion(this._negotiatedProtocolVersion); + const validatedRequest = codec.validateRequest("tools/call", request); + if (!validatedRequest.ok) throw new src_CX2iR2pK_ProtocolError(validatedRequest.reason === "not-in-era" ? src_CX2iR2pK_ProtocolErrorCode.InternalError : src_CX2iR2pK_ProtocolErrorCode.InvalidParams, validatedRequest.reason === "not-in-era" ? "No wire schema for tools/call in the resolved era" : `Invalid tools/call request: ${validatedRequest.message}`); + const result = await this._invokeInputRequiredCapableHandler("tools/call", handler, request, ctx); + if (isInputRequiredResult(result)) return result; + const normalizedResult = normalizeContentlessToolResult(result); + const validationResult = codec.validateResult("tools/call", normalizedResult); + if (!validationResult.ok) throw new src_CX2iR2pK_ProtocolError(validationResult.reason === "not-in-era" ? src_CX2iR2pK_ProtocolErrorCode.InternalError : src_CX2iR2pK_ProtocolErrorCode.InvalidParams, validationResult.reason === "not-in-era" ? "No wire schema for tools/call in the resolved era" : `Invalid tools/call result: ${validationResult.message}`); + return validationResult.value; + }; + } + /** + * Whether this instance is bound to a 2026-07-28-or-later protocol + * revision. Era is instance state — a serving entry (`createMcpHandler`, + * `serveStdio`) marks the instance modern at construction; a 2025-era + * `initialize` handshake binds it legacy. The multi-round-trip seam reads + * this directly: there is no per-request era consult. + */ + _servedModernEra() { + return this._negotiatedProtocolVersion !== void 0 && isModernProtocolVersion(this._negotiatedProtocolVersion); + } + /** + * Invokes a handler for one of the multi-round-trip methods and applies + * the input-required seam: + * + * - a `UrlElicitationRequiredError` (or any 2025-style server→client + * request idiom) escaping the handler on a request served on the + * 2026-07-28 era fails LOUDLY with a clear steer to + * `inputRequired.elicitUrl(...)` — the `-32042` error never reaches the + * 2026-07-28 wire and the throw is not silently converted. Requests + * served on the 2025 era keep today's `-32042` behavior byte-exact (the + * error is rethrown unchanged). + * - an input-required RETURN toward a 2026-07-28 request must satisfy + * the at-least-one rule, and every embedded request must be covered by + * the capabilities declared on the request's envelope (violations + * answer the typed `-32021` error). Toward a 2025-era request the + * return is fulfilled by the default-on legacy shim, whose own gate + * consults the initialize-declared capabilities and surfaces + * violations per family; `inputRequired.legacyShim: false` restores + * the pre-shim loud failure. + */ + async _invokeInputRequiredCapableHandler(method, handler, request, ctx) { + const servedModern = this._servedModernEra(); + const rawRequestState = ctx.mcpReq.requestState(); + if (rawRequestState !== void 0 && typeof rawRequestState !== "string") throw new src_CX2iR2pK_ProtocolError(src_CX2iR2pK_ProtocolErrorCode.InvalidParams, "Invalid or expired requestState", { reason: "invalid_request_state" }); + let ctxForHandler = ctx; + if (typeof rawRequestState === "string") { + const decoded = await this._verifyRequestState(rawRequestState, ctx, method); + if (decoded !== void 0) ctxForHandler = withRequestStateValue(ctx, decoded); + } + let result; + try { + result = await handler(request, ctxForHandler); + } catch (error) { + if (error instanceof src_CX2iR2pK_ProtocolError && error.code === src_CX2iR2pK_ProtocolErrorCode.UrlElicitationRequired) { + if (!servedModern) throw error; + throw new src_CX2iR2pK_ProtocolError(src_CX2iR2pK_ProtocolErrorCode.InternalError, `URL elicitation cannot be signalled by throwing UrlElicitationRequiredError on protocol revision ${this._negotiatedProtocolVersion}: return inputRequired({ inputRequests: { …: inputRequired.elicitUrl(...) } }) from the handler instead. The urlElicitationRequired error (-32042) of earlier revisions is not available on this revision.`); + } + throw error; + } + if (!isInputRequiredResult(result)) return result; + if (!servedModern) { + if (!this._inputRequiredServing.legacyShim) throw new src_CX2iR2pK_ProtocolError(src_CX2iR2pK_ProtocolErrorCode.InternalError, `Handler for ${method} returned an input-required result, but this request is served on protocol revision ${this._negotiatedProtocolVersion ?? LATEST_PROTOCOL_VERSION}, which has no input_required vocabulary`); + return await this._legacyInputRequiredShim().fulfill(method, handler, request, ctxForHandler, result); + } + const inputRequests = result.inputRequests; + const hasInputRequests = inputRequests != null && Object.keys(inputRequests).length > 0; + const hasRequestState = typeof result.requestState === "string"; + if (!hasInputRequests && !hasRequestState) throw new src_CX2iR2pK_ProtocolError(src_CX2iR2pK_ProtocolErrorCode.InternalError, `Handler for ${method} returned an input-required result with neither inputRequests nor requestState (every InputRequiredResult must include at least one of the two)`); + if (hasInputRequests) { + const declared = this._inputRequestCapabilityView(ctx); + for (const [key, entry] of Object.entries(inputRequests)) { + const { embedded, required } = coerceEmbeddedInputRequest(method, key, entry); + const missing = src_CX2iR2pK_missingClientCapabilities(required, declared); + if (missing !== void 0) throw new src_CX2iR2pK_MissingRequiredClientCapabilityError({ requiredCapabilities: missing }, `Cannot request input '${key}' (${embedded.method}): the request's client capabilities do not declare the required capability`); + } + } + return result; + } + /** + * Runs the configured `requestState.verify` hook and returns its + * resolved value (`undefined` when unconfigured or the hook returns + * nothing). Deny-on-error: any hook failure answers the frozen `-32602`; + * the reason goes to `onerror` only. + */ + async _verifyRequestState(state, ctx, method) { + if (this._requestStateVerify === void 0) return; + try { + return await this._requestStateVerify(state, ctx); + } catch (error) { + this.onerror?.(/* @__PURE__ */ new Error(`requestState verification rejected ${method}: ${error instanceof Error ? error.message : String(error)}`)); + throw new src_CX2iR2pK_ProtocolError(src_CX2iR2pK_ProtocolErrorCode.InvalidParams, "Invalid or expired requestState", { reason: "invalid_request_state" }); + } + } + /** + * The per-request resolved client-capabilities view: the request's own + * `_meta` envelope on the 2026 era; the `initialize`-declared state on a + * 2025-era connection. Per-request instances that never saw an + * initialize (stateless legacy) hold nothing, so gates refuse there. + */ + _inputRequestCapabilityView(ctx) { + return this._servedModernEra() ? ctx.mcpReq.envelope?.[auth_CUe6YdwF_CLIENT_CAPABILITIES_META_KEY] : this._clientCapabilities; + } + /** + * Guard for the push-style server→client request APIs ({@linkcode createMessage}, + * {@linkcode elicitInput}, {@linkcode listRoots}, {@linkcode ping}) on a + * modern-era instance: the 2026-07-28 revision has no server→client request + * channel, so the call fails before any wire traffic with a typed error + * whose message steers to `inputRequired(...)`. The base era gate would + * also reject it; this guard runs first to carry the steer. + */ + _assertPushApiInServedEra(method) { + if (this._servedModernEra()) throw new src_CX2iR2pK_SdkError(src_CX2iR2pK_SdkErrorCode.MethodNotSupportedByProtocolVersion, `Server-to-client requests are not available on protocol revision ${this._negotiatedProtocolVersion}: '${method}' cannot be sent while serving a request on that revision. Return inputRequired({ ... }) from the handler instead — the client fulfils the embedded requests and retries the original request (multi round-trip requests).`, { + method, + era: "2026-07-28" + }); + } + assertCapabilityForMethod(method) { + switch (method) { + case "sampling/createMessage": + if (!this._clientCapabilities?.sampling) throw new src_CX2iR2pK_SdkError(src_CX2iR2pK_SdkErrorCode.CapabilityNotSupported, `Client does not support sampling (required for ${method})`); + break; + case "elicitation/create": + if (!this._clientCapabilities?.elicitation) throw new src_CX2iR2pK_SdkError(src_CX2iR2pK_SdkErrorCode.CapabilityNotSupported, `Client does not support elicitation (required for ${method})`); + break; + case "roots/list": + if (!this._clientCapabilities?.roots) throw new src_CX2iR2pK_SdkError(src_CX2iR2pK_SdkErrorCode.CapabilityNotSupported, `Client does not support listing roots (required for ${method})`); + break; + case "ping": break; + } + } + assertNotificationCapability(method) { + switch (method) { + case "notifications/message": + if (!this._capabilities.logging) throw new src_CX2iR2pK_SdkError(src_CX2iR2pK_SdkErrorCode.CapabilityNotSupported, `Server does not support logging (required for ${method})`); + break; + case "notifications/resources/updated": + case "notifications/resources/list_changed": + if (!this._capabilities.resources) throw new src_CX2iR2pK_SdkError(src_CX2iR2pK_SdkErrorCode.CapabilityNotSupported, `Server does not support notifying about resources (required for ${method})`); + break; + case "notifications/tools/list_changed": + if (!this._capabilities.tools) throw new src_CX2iR2pK_SdkError(src_CX2iR2pK_SdkErrorCode.CapabilityNotSupported, `Server does not support notifying of tool list changes (required for ${method})`); + break; + case "notifications/prompts/list_changed": + if (!this._capabilities.prompts) throw new src_CX2iR2pK_SdkError(src_CX2iR2pK_SdkErrorCode.CapabilityNotSupported, `Server does not support notifying of prompt list changes (required for ${method})`); + break; + case "notifications/elicitation/complete": + if (!this._clientCapabilities?.elicitation?.url) throw new src_CX2iR2pK_SdkError(src_CX2iR2pK_SdkErrorCode.CapabilityNotSupported, `Client does not support URL elicitation (required for ${method})`); + break; + case "notifications/cancelled": break; + case "notifications/progress": break; + } + } + assertRequestHandlerCapability(method) { + switch (method) { + case "completion/complete": + if (!this._capabilities.completions) throw new src_CX2iR2pK_SdkError(src_CX2iR2pK_SdkErrorCode.CapabilityNotSupported, `Server does not support completions (required for ${method})`); + break; + case "logging/setLevel": + if (!this._capabilities.logging) throw new src_CX2iR2pK_SdkError(src_CX2iR2pK_SdkErrorCode.CapabilityNotSupported, `Server does not support logging (required for ${method})`); + break; + case "prompts/get": + case "prompts/list": + if (!this._capabilities.prompts) throw new src_CX2iR2pK_SdkError(src_CX2iR2pK_SdkErrorCode.CapabilityNotSupported, `Server does not support prompts (required for ${method})`); + break; + case "resources/list": + case "resources/templates/list": + case "resources/read": + if (!this._capabilities.resources) throw new src_CX2iR2pK_SdkError(src_CX2iR2pK_SdkErrorCode.CapabilityNotSupported, `Server does not support resources (required for ${method})`); + break; + case "tools/call": + case "tools/list": + if (!this._capabilities.tools) throw new src_CX2iR2pK_SdkError(src_CX2iR2pK_SdkErrorCode.CapabilityNotSupported, `Server does not support tools (required for ${method})`); + break; + case "ping": + case "initialize": break; + } + } + async _oninitialize(request) { + const requestedVersion = request.params.protocolVersion; + this._clientCapabilities = request.params.capabilities; + this._clientVersion = request.params.clientInfo; + const legacyVersions = legacyProtocolVersions(this._supportedProtocolVersions); + const protocolVersion = legacyVersions.includes(requestedVersion) ? requestedVersion : legacyVersions[0] ?? LATEST_PROTOCOL_VERSION; + this._negotiatedProtocolVersion = protocolVersion; + this.transport?.setProtocolVersion?.(protocolVersion); + return { + protocolVersion, + capabilities: this.getCapabilities(), + serverInfo: this._serverInfo, + ...this._instructions && { instructions: this._instructions } + }; + } + /** + * Answers `server/discover` (protocol revision 2026-07-28). `supportedVersions` + * lists only modern revisions (2025-era versions are negotiated via `initialize`); + * the capabilities are advertised as-is, listChanged/subscribe bits included + * (see {@linkcode discoverAdvertisedCapabilities}). + */ + _ondiscover() { + return { + supportedVersions: modernProtocolVersions(this._supportedProtocolVersions), + capabilities: discoverAdvertisedCapabilities(this.getCapabilities()), + ...this._instructions && { instructions: this._instructions } + }; + } + /** + * The identity the 2026-era encode seam stamps into every outbound + * result's `_meta` under `io.modelcontextprotocol/serverInfo` (spec PR + * #3002: servers SHOULD identify themselves on every response). + */ + _outboundServerInfo() { + return this._serverInfo; + } + /** + * After initialization has completed, this will be populated with the client's reported capabilities. + * + * @deprecated Read client identity from the per-request handler context instead: on + * 2026-07-28 (per-request envelope) requests `ctx.mcpReq.envelope` carries the client's + * declared capabilities, while on 2025-era connections this accessor keeps returning the + * `initialize`-scoped value. The accessor remains functional — instances serving the + * 2026-07-28 era are backfilled per request from the validated envelope. + */ + getClientCapabilities() { + return this._clientCapabilities; + } + /** + * After initialization has completed, this will be populated with information about the client's name and version. + * + * @deprecated Read client identity from the per-request handler context instead: on + * 2026-07-28 (per-request envelope) requests `ctx.mcpReq.envelope` carries the client's + * name and version, while on 2025-era connections this accessor keeps returning the + * `initialize`-scoped value. The accessor remains functional — instances serving the + * 2026-07-28 era are backfilled per request from the validated envelope. + */ + getClientVersion() { + return this._clientVersion; + } + /** + * After initialization has completed, this will be populated with the protocol version negotiated + * with the client (the version the server responded with during the initialize handshake), or + * `undefined` before initialization. + * + * @deprecated Read the protocol revision from the per-request handler context instead: on + * 2026-07-28 (per-request envelope) requests `ctx.mcpReq.envelope` names the revision the + * request was sent for, while on 2025-era connections this accessor keeps returning the + * `initialize`-negotiated version. The accessor remains functional — instances serving the + * 2026-07-28 era report that revision. + */ + getNegotiatedProtocolVersion() { + return this._negotiatedProtocolVersion; + } + /** + * Project a `tools/call` result through this instance's negotiated wire + * codec — the era-agnostic SEP-2106 §4.3 TextContent auto-append, plus on + * the 2025 era the `{result:…}` wrap when `structuredContent` is a + * non-object value or the advertised `outputSchema` had a non-object root. + * Identity for object-shaped `structuredContent` on the 2026 era. + * + * `McpServer`'s built-in `tools/call` handler routes through this method. + * Low-level `setRequestHandler('tools/call', …)` authors call it + * themselves so the projection lives in one place (the codec) and the + * server-side handler stays era-blind. + * + * This is the only codec function exposed on `Server` — the full + * `WireCodec` is intentionally not part of the public surface. + */ + projectCallToolResult(result, advertisedOutputSchema) { + return this._wireCodec().projectCallToolResult(result, advertisedOutputSchema); + } + /** + * Returns the current server capabilities. + */ + getCapabilities() { + return this._capabilities; + } + /** + * Sends a `ping` request to the connected client. + * + * @deprecated The 2026-07-28 protocol removed ping; it throws on a 2026-07-28-era instance. + * If your factory serves both eras, this only works on the legacy path. + */ + async ping() { + this._assertPushApiInServedEra("ping"); + return this.request({ method: "ping" }); + } + async createMessage(params, options) { + this._assertPushApiInServedEra("sampling/createMessage"); + if ((params.tools || params.toolChoice) && !this._clientCapabilities?.sampling?.tools) throw new src_CX2iR2pK_SdkError(src_CX2iR2pK_SdkErrorCode.CapabilityNotSupported, "Client does not support sampling tools capability."); + if (params.messages.length > 0) { + const lastMessage = params.messages.at(-1); + const lastContent = Array.isArray(lastMessage.content) ? lastMessage.content : [lastMessage.content]; + const hasToolResults = lastContent.some((c) => c.type === "tool_result"); + const previousMessage = params.messages.length > 1 ? params.messages.at(-2) : void 0; + const previousContent = previousMessage ? Array.isArray(previousMessage.content) ? previousMessage.content : [previousMessage.content] : []; + const hasPreviousToolUse = previousContent.some((c) => c.type === "tool_use"); + if (hasToolResults) { + if (lastContent.some((c) => c.type !== "tool_result")) throw new src_CX2iR2pK_ProtocolError(src_CX2iR2pK_ProtocolErrorCode.InvalidParams, "The last message must contain only tool_result content if any is present"); + if (!hasPreviousToolUse) throw new src_CX2iR2pK_ProtocolError(src_CX2iR2pK_ProtocolErrorCode.InvalidParams, "tool_result blocks are not matching any tool_use from the previous message"); + } + if (hasPreviousToolUse) { + const toolUseIds = new Set(previousContent.filter((c) => c.type === "tool_use").map((c) => c.id)); + const toolResultIds = new Set(lastContent.filter((c) => c.type === "tool_result").map((c) => c.toolUseId)); + if (toolUseIds.size !== toolResultIds.size || ![...toolUseIds].every((id) => toolResultIds.has(id))) throw new src_CX2iR2pK_ProtocolError(src_CX2iR2pK_ProtocolErrorCode.InvalidParams, "ids of tool_result blocks and tool_use blocks from previous message do not match"); + } + } + const hasTools = Boolean(params.tools || params.toolChoice); + const wide = await this.request({ + method: "sampling/createMessage", + params + }, options); + const outcome = this._wireCodec().samplingResultVariant(hasTools, wide); + if (!outcome.ok) throw new src_CX2iR2pK_SdkError(src_CX2iR2pK_SdkErrorCode.InvalidResult, `Invalid sampling/createMessage result: ${outcome.reason === "invalid" ? outcome.message : outcome.reason}`); + return outcome.value; + } + /** + * Creates an elicitation request for the given parameters. + * For backwards compatibility, `mode` may be omitted for form requests and will default to `"form"`. + * @param params The parameters for the elicitation request. + * @param options Optional request options. + * @returns The result of the elicitation request. + * + * @deprecated Throws on a 2026-07-28-era request — use {@link index.inputRequired | inputRequired} (multi-round-trip) + * instead. The 2025 push-style server-to-client request model is replaced by input_required + * results in the 2026-07-28 protocol. If your factory serves both eras, this only works on the + * legacy path. + */ + async elicitInput(params, options) { + this._assertPushApiInServedEra("elicitation/create"); + switch (params.mode ?? "form") { + case "url": + if (!this._clientCapabilities?.elicitation?.url) throw new src_CX2iR2pK_SdkError(src_CX2iR2pK_SdkErrorCode.CapabilityNotSupported, "Client does not support url elicitation."); + break; + case "form": + if (!this._clientCapabilities?.elicitation?.form) throw new src_CX2iR2pK_SdkError(src_CX2iR2pK_SdkErrorCode.CapabilityNotSupported, "Client does not support form elicitation."); + break; + } + return this._sendElicitationLeg(params, options); + } + /** + * The capability-check-free core of {@linkcode elicitInput}. The shim + * uses it because its gate differs from the public checks: a bare + * `elicitation: {}` counts as form support (the pre-mode rule), and + * accepted content passes through unvalidated for parity with the + * modern client driver (handlers validate via the schema-aware + * `acceptedContent` overload and can re-ask). + */ + async _sendElicitationLeg(params, options, behavior) { + const mode = params.mode ?? "form"; + const validateAcceptedContent = behavior?.validateAcceptedContent ?? true; + switch (mode) { + case "url": { + const urlParams = params; + return this.request({ + method: "elicitation/create", + params: urlParams + }, options); + } + case "form": { + const formParams = params.mode === "form" ? params : { + ...params, + mode: "form" + }; + const result = await this.request({ + method: "elicitation/create", + params: formParams + }, options); + if (validateAcceptedContent && result.action === "accept" && result.content && formParams.requestedSchema) try { + const validationResult = this._jsonSchemaValidator.getValidator(formParams.requestedSchema)(result.content); + if (!validationResult.valid) throw new src_CX2iR2pK_ProtocolError(src_CX2iR2pK_ProtocolErrorCode.InvalidParams, `Elicitation response content does not match requested schema: ${validationResult.errorMessage}`); + } catch (error) { + if (error instanceof src_CX2iR2pK_ProtocolError) throw error; + throw new src_CX2iR2pK_ProtocolError(src_CX2iR2pK_ProtocolErrorCode.InternalError, `Error validating elicitation response: ${error instanceof Error ? error.message : String(error)}`); + } + return result; + } + } + } + /** + * Creates a reusable callback that, when invoked, will send a `notifications/elicitation/complete` + * notification for the specified elicitation ID. + * + * The notification (and the `elicitationId` it references) exists only on protocol revision + * 2025-11-25 — the 2026-07-28 revision removed both. On a connection negotiated at 2026-07-28 the + * returned callback rejects with a typed local error before anything reaches the transport + * (the method is not part of that revision's wire registry). + * + * @param elicitationId The ID of the elicitation to mark as complete. + * @param options Optional notification options. Useful when the completion notification should be related to a prior request. + * @returns A function that emits the completion notification when awaited. + */ + createElicitationCompletionNotifier(elicitationId, options) { + if (!this._clientCapabilities?.elicitation?.url) throw new src_CX2iR2pK_SdkError(src_CX2iR2pK_SdkErrorCode.CapabilityNotSupported, "Client does not support URL elicitation (required for notifications/elicitation/complete)"); + return () => this.notification({ + method: "notifications/elicitation/complete", + params: { elicitationId } + }, options); + } + /** + * Requests the list of roots from the client. + * + * @deprecated Deprecated as of protocol version 2026-07-28 (SEP-2577). + * Throws on a 2026-07-28-era request — use {@link index.inputRequired | inputRequired} (multi-round-trip) instead, + * or migrate to passing paths via tool parameters, resource URIs, or configuration. The 2025 + * push-style server-to-client request model is replaced by input_required results in the + * 2026-07-28 protocol. If your factory serves both eras, this only works on the legacy path. + */ + async listRoots(params, options) { + this._assertPushApiInServedEra("roots/list"); + return this.request({ + method: "roots/list", + params + }, options); + } + /** + * Sends a logging message to the client, if connected. + * Note: You only need to send the parameters object, not the entire JSON-RPC message. + * @see {@linkcode LoggingMessageNotification} + * @param params + * @param sessionId Optional for stateless transports and backward compatibility. + * + * @deprecated Deprecated as of protocol version 2026-07-28 (SEP-2577). + * Remains functional during the deprecation window (at least twelve months). + * Migrate to stderr logging (STDIO servers) or OpenTelemetry. + */ + async sendLoggingMessage(params, sessionId) { + if (this._capabilities.logging && !this.isMessageIgnored(params.level, sessionId)) return this.notification({ + method: "notifications/message", + params + }); + } + async sendResourceUpdated(params) { + return this.notification({ + method: "notifications/resources/updated", + params + }); + } + 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" }); + } +}; +/** +* The capability set a server advertises on `server/discover`. Pure — never +* mutates the input; the legacy `initialize` advertisement is untouched. +* +* The serving entries serve `subscriptions/listen` themselves, so the +* `listChanged` and `resources.subscribe` capability bits are advertised +* as-is: a modern-era client uses them to decide which notification types to +* request on its listen filter. +*/ +function discoverAdvertisedCapabilities(capabilities) { + return { ...capabilities }; +} + +//#endregion +//#region src/server/mcp.ts +/** +* High-level MCP server that provides a simpler API for working with resources, tools, and prompts. +* For advanced usage (like sending notifications or setting custom request handlers), use the underlying +* {@linkcode Server} instance available via the {@linkcode McpServer.server | server} property. +* +* @example +* ```ts source="./mcp.examples.ts#McpServer_basicUsage" +* const server = new McpServer({ +* name: 'my-server', +* version: '1.0.0' +* }); +* ``` +*/ +var mcp_DXXb3Vv3_McpServer = class { + /** + * The underlying {@linkcode Server} instance, useful for advanced operations like sending notifications. + */ + server; + _registeredResources = {}; + _registeredResourceTemplates = {}; + _registeredTools = {}; + _registeredPrompts = {}; + /** + * Per-tool JSON-converted `inputSchema`, memoized so the SEP-2243 + * registration-time scan and the pre-dispatch validation step share one + * conversion instead of paying it twice per request under the + * per-request-factory `createMcpHandler` model. + */ + _toolInputSchemaJson = {}; + /** + * The JSON-serialized `inputSchema` of a registered tool, or `undefined` + * when no such tool is registered. Used by the HTTP entry's pre-dispatch + * SEP-2243 `Mcp-Param-*` validation step (which needs the same JSON Schema + * `tools/list` would emit, before dispatch reaches the handler). + * + * @internal + */ + toolInputSchemaJson(name) { + const tool = this._registeredTools[name]; + if (tool === void 0 || !tool.enabled) return void 0; + if (Object.hasOwn(this._toolInputSchemaJson, name)) return this._toolInputSchemaJson[name]; + if (tool.inputSchema === void 0) return EMPTY_OBJECT_JSON_SCHEMA; + try { + const json = standardSchemaToJsonSchema(tool.inputSchema, "input"); + this._toolInputSchemaJson[name] = json; + return json; + } catch { + return; + } + } + constructor(serverInfo, options) { + this.server = new Server(serverInfo, options); + if (options?.capabilities?.tools) this.setToolRequestHandlers(); + if (options?.capabilities?.resources) this.setResourceRequestHandlers(); + if (options?.capabilities?.prompts) this.setPromptRequestHandlers(); + } + /** + * Attaches to the given transport, starts it, and starts listening for messages. + * + * The `server` object assumes ownership of the {@linkcode Transport}, replacing any callbacks that have already been set, and expects that it is the only user of the {@linkcode Transport} instance going forward. + * + * @example + * ```ts source="./mcp.examples.ts#McpServer_connect_stdio" + * const server = new McpServer({ name: 'my-server', version: '1.0.0' }); + * const transport = new StdioServerTransport(); + * await server.connect(transport); + * ``` + */ + async connect(transport) { + return await this.server.connect(transport); + } + /** + * Closes the connection. + */ + async close() { + await this.server.close(); + } + _toolHandlersInitialized = false; + setToolRequestHandlers() { + if (this._toolHandlersInitialized) return; + this.server.assertCanSetRequestHandler("tools/list"); + this.server.assertCanSetRequestHandler("tools/call"); + this.server.registerCapabilities({ tools: { listChanged: this.server.getCapabilities().tools?.listChanged ?? true } }); + this.server.setRequestHandler("tools/list", () => ({ tools: Object.entries(this._registeredTools).filter(([, tool]) => tool.enabled).map(([name, tool]) => { + const toolDefinition = { + name, + title: tool.title, + description: tool.description, + inputSchema: tool.inputSchema ? standardSchemaToJsonSchema(tool.inputSchema, "input") : EMPTY_OBJECT_JSON_SCHEMA, + annotations: tool.annotations, + icons: tool.icons, + execution: tool.execution, + _meta: tool._meta + }; + if (tool.outputSchema) toolDefinition.outputSchema = standardSchemaToJsonSchema(tool.outputSchema, "output"); + return toolDefinition; + }) })); + this.server.setRequestHandler("tools/call", async (request, ctx) => { + const tool = this._registeredTools[request.params.name]; + if (!tool) throw new src_CX2iR2pK_ProtocolError(src_CX2iR2pK_ProtocolErrorCode.InvalidParams, `Tool ${request.params.name} not found`); + if (!tool.enabled) throw new src_CX2iR2pK_ProtocolError(src_CX2iR2pK_ProtocolErrorCode.InvalidParams, `Tool ${request.params.name} disabled`); + try { + const args = await this.validateToolInput(tool, request.params.arguments, request.params.name); + const result = await this.executeToolHandler(tool, args, ctx); + await this.validateToolOutput(tool, result, request.params.name); + if (isInputRequiredResult(result)) return result; + return this.server.projectCallToolResult(result, tool.outputSchemaJson); + } catch (error) { + if (error instanceof src_CX2iR2pK_ProtocolError && error.code === src_CX2iR2pK_ProtocolErrorCode.UrlElicitationRequired) throw error; + return this.createToolError(error instanceof Error ? error.message : String(error)); + } + }); + this._toolHandlersInitialized = true; + } + /** + * Creates a tool error result. + * + * @param errorMessage - The error message. + * @returns The tool error result. + */ + createToolError(errorMessage) { + return { + content: [{ + type: "text", + text: errorMessage + }], + isError: true + }; + } + /** + * Validates tool input arguments against the tool's input schema. + */ + async validateToolInput(tool, args, toolName) { + if (!tool.inputSchema) return; + const parseResult = await validateStandardSchema(tool.inputSchema, args ?? {}); + if (!parseResult.success) throw new src_CX2iR2pK_ProtocolError(src_CX2iR2pK_ProtocolErrorCode.InvalidParams, `Input validation error: Invalid arguments for tool ${toolName}: ${parseResult.error}`); + return parseResult.data; + } + /** + * Validates tool output against the tool's output schema. + */ + async validateToolOutput(tool, result, toolName) { + if (!tool.outputSchema) return; + if (isInputRequiredResult(result)) return; + if (result.isError) return; + if (result.structuredContent === void 0) throw new src_CX2iR2pK_ProtocolError(src_CX2iR2pK_ProtocolErrorCode.InvalidParams, `Output validation error: Tool ${toolName} has an output schema but no structured content was provided`); + const parseResult = await validateStandardSchema(tool.outputSchema, result.structuredContent); + if (!parseResult.success) throw new src_CX2iR2pK_ProtocolError(src_CX2iR2pK_ProtocolErrorCode.InvalidParams, `Output validation error: Invalid structured content for tool ${toolName}: ${parseResult.error}`); + } + /** + * Executes a tool handler. + */ + async executeToolHandler(tool, args, ctx) { + return tool.executor(args, ctx); + } + _completionHandlerInitialized = false; + setCompletionRequestHandler() { + if (this._completionHandlerInitialized) return; + this.server.assertCanSetRequestHandler("completion/complete"); + this.server.registerCapabilities({ completions: {} }); + this.server.setRequestHandler("completion/complete", async (request) => { + switch (request.params.ref.type) { + case "ref/prompt": + assertCompleteRequestPrompt(request); + return this.handlePromptCompletion(request, request.params.ref); + case "ref/resource": + assertCompleteRequestResourceTemplate(request); + return this.handleResourceCompletion(request, request.params.ref); + default: throw new src_CX2iR2pK_ProtocolError(src_CX2iR2pK_ProtocolErrorCode.InvalidParams, `Invalid completion reference: ${request.params.ref}`); + } + }); + this._completionHandlerInitialized = true; + } + async handlePromptCompletion(request, ref) { + const prompt = this._registeredPrompts[ref.name]; + if (!prompt) throw new src_CX2iR2pK_ProtocolError(src_CX2iR2pK_ProtocolErrorCode.InvalidParams, `Prompt ${ref.name} not found`); + if (!prompt.enabled) throw new src_CX2iR2pK_ProtocolError(src_CX2iR2pK_ProtocolErrorCode.InvalidParams, `Prompt ${ref.name} disabled`); + if (!prompt.argsSchema) return EMPTY_COMPLETION_RESULT; + const field = unwrapOptionalSchema(getSchemaShape(prompt.argsSchema)?.[request.params.argument.name]); + if (!isCompletable(field)) return EMPTY_COMPLETION_RESULT; + const completer = getCompleter(field); + if (!completer) return EMPTY_COMPLETION_RESULT; + return createCompletionResult(await completer(request.params.argument.value, request.params.context)); + } + async handleResourceCompletion(request, ref) { + const template = Object.values(this._registeredResourceTemplates).find((t) => t.resourceTemplate.uriTemplate.toString() === ref.uri); + if (!template) { + if (this._registeredResources[ref.uri]) return EMPTY_COMPLETION_RESULT; + throw new src_CX2iR2pK_ProtocolError(src_CX2iR2pK_ProtocolErrorCode.InvalidParams, `Resource template ${request.params.ref.uri} not found`); + } + const completer = template.resourceTemplate.completeCallback(request.params.argument.name); + if (!completer) return EMPTY_COMPLETION_RESULT; + return createCompletionResult(await completer(request.params.argument.value, request.params.context)); + } + _resourceHandlersInitialized = false; + setResourceRequestHandlers() { + if (this._resourceHandlersInitialized) return; + this.server.assertCanSetRequestHandler("resources/list"); + this.server.assertCanSetRequestHandler("resources/templates/list"); + this.server.assertCanSetRequestHandler("resources/read"); + this.server.registerCapabilities({ resources: { listChanged: this.server.getCapabilities().resources?.listChanged ?? true } }); + this.server.setRequestHandler("resources/list", async (_request, ctx) => { + const resources = Object.entries(this._registeredResources).filter(([_, resource]) => resource.enabled).map(([uri, resource]) => ({ + uri, + name: resource.name, + ...resource.metadata + })); + const templateResources = []; + for (const template of Object.values(this._registeredResourceTemplates)) { + if (!template.resourceTemplate.listCallback) continue; + const result = await template.resourceTemplate.listCallback(ctx); + for (const resource of result.resources) templateResources.push({ + ...template.metadata, + ...resource + }); + } + return { resources: [...resources, ...templateResources] }; + }); + this.server.setRequestHandler("resources/templates/list", async () => { + return { resourceTemplates: Object.entries(this._registeredResourceTemplates).map(([name, template]) => ({ + name, + uriTemplate: template.resourceTemplate.uriTemplate.toString(), + ...template.metadata + })) }; + }); + this.server.setRequestHandler("resources/read", async (request, ctx) => { + let uri; + try { + uri = new URL(request.params.uri); + } catch { + throw new src_CX2iR2pK_ProtocolError(src_CX2iR2pK_ProtocolErrorCode.InvalidParams, `Resource URI ${request.params.uri} is invalid`, { + uri: request.params.uri, + reason: "invalid_uri" + }); + } + const resource = this._registeredResources[uri.toString()]; + if (resource) { + if (!resource.enabled) throw new src_CX2iR2pK_ProtocolError(src_CX2iR2pK_ProtocolErrorCode.InvalidParams, `Resource ${uri} disabled`); + return attachCacheHintFallback(await resource.readCallback(uri, ctx), resource.cacheHint); + } + for (const template of Object.values(this._registeredResourceTemplates)) { + const variables = template.resourceTemplate.uriTemplate.match(uri.toString()); + if (variables) return attachCacheHintFallback(await template.readCallback(uri, variables, ctx), template.cacheHint); + } + throw new ResourceNotFoundError(request.params.uri); + }); + this._resourceHandlersInitialized = true; + } + _promptHandlersInitialized = false; + setPromptRequestHandlers() { + if (this._promptHandlersInitialized) return; + this.server.assertCanSetRequestHandler("prompts/list"); + this.server.assertCanSetRequestHandler("prompts/get"); + this.server.registerCapabilities({ prompts: { listChanged: this.server.getCapabilities().prompts?.listChanged ?? true } }); + this.server.setRequestHandler("prompts/list", () => ({ prompts: Object.entries(this._registeredPrompts).filter(([, prompt]) => prompt.enabled).map(([name, prompt]) => { + return { + name, + title: prompt.title, + description: prompt.description, + arguments: prompt.argsSchema ? promptArgumentsFromStandardSchema(prompt.argsSchema) : void 0, + icons: prompt.icons, + _meta: prompt._meta + }; + }) })); + this.server.setRequestHandler("prompts/get", async (request, ctx) => { + const prompt = this._registeredPrompts[request.params.name]; + if (!prompt) throw new src_CX2iR2pK_ProtocolError(src_CX2iR2pK_ProtocolErrorCode.InvalidParams, `Prompt ${request.params.name} not found`); + if (!prompt.enabled) throw new src_CX2iR2pK_ProtocolError(src_CX2iR2pK_ProtocolErrorCode.InvalidParams, `Prompt ${request.params.name} disabled`); + return prompt.handler(request.params.arguments, ctx); + }); + this._promptHandlersInitialized = true; + } + registerResource(name, uriOrTemplate, config, readCallback) { + const cacheHint = config.cacheHint; + let metadata = config; + if (cacheHint !== void 0) { + assertValidCacheHint(cacheHint, `resource ${name}`); + const rest = { ...config }; + delete rest.cacheHint; + metadata = rest; + } + if (typeof uriOrTemplate === "string") { + if (this._registeredResources[uriOrTemplate]) throw new Error(`Resource ${uriOrTemplate} is already registered`); + const registeredResource = this._createRegisteredResource(name, config.title, uriOrTemplate, metadata, readCallback); + if (cacheHint !== void 0) registeredResource.cacheHint = cacheHint; + this.setResourceRequestHandlers(); + this.sendResourceListChanged(); + return registeredResource; + } else { + if (this._registeredResourceTemplates[name]) throw new Error(`Resource template ${name} is already registered`); + const registeredResourceTemplate = this._createRegisteredResourceTemplate(name, config.title, uriOrTemplate, metadata, readCallback); + if (cacheHint !== void 0) registeredResourceTemplate.cacheHint = cacheHint; + this.setResourceRequestHandlers(); + this.sendResourceListChanged(); + return registeredResourceTemplate; + } + } + _createRegisteredResource(name, title, uri, metadata, readCallback) { + const registeredResource = { + name, + title, + metadata, + readCallback, + enabled: true, + disable: () => registeredResource.update({ enabled: false }), + enable: () => registeredResource.update({ enabled: true }), + remove: () => registeredResource.update({ uri: null }), + update: (updates) => { + if (updates.uri !== void 0 && updates.uri !== uri) { + delete this._registeredResources[uri]; + if (updates.uri) this._registeredResources[updates.uri] = registeredResource; + } + if (updates.name !== void 0) registeredResource.name = updates.name; + if (updates.title !== void 0) registeredResource.title = updates.title; + if (updates.metadata !== void 0) registeredResource.metadata = updates.metadata; + if (updates.callback !== void 0) registeredResource.readCallback = updates.callback; + if (updates.enabled !== void 0) registeredResource.enabled = updates.enabled; + this.sendResourceListChanged(); + } + }; + this._registeredResources[uri] = registeredResource; + return registeredResource; + } + _createRegisteredResourceTemplate(name, title, template, metadata, readCallback) { + const registeredResourceTemplate = { + resourceTemplate: template, + title, + metadata, + readCallback, + enabled: true, + disable: () => registeredResourceTemplate.update({ enabled: false }), + enable: () => registeredResourceTemplate.update({ enabled: true }), + remove: () => registeredResourceTemplate.update({ name: null }), + update: (updates) => { + if (updates.name !== void 0 && updates.name !== name) { + delete this._registeredResourceTemplates[name]; + if (updates.name) this._registeredResourceTemplates[updates.name] = registeredResourceTemplate; + } + if (updates.title !== void 0) registeredResourceTemplate.title = updates.title; + if (updates.template !== void 0) registeredResourceTemplate.resourceTemplate = updates.template; + if (updates.metadata !== void 0) registeredResourceTemplate.metadata = updates.metadata; + if (updates.callback !== void 0) registeredResourceTemplate.readCallback = updates.callback; + if (updates.enabled !== void 0) registeredResourceTemplate.enabled = updates.enabled; + this.sendResourceListChanged(); + } + }; + this._registeredResourceTemplates[name] = registeredResourceTemplate; + const variableNames = template.uriTemplate.variableNames; + if (Array.isArray(variableNames) && variableNames.some((v) => !!template.completeCallback(v))) this.setCompletionRequestHandler(); + return registeredResourceTemplate; + } + _createRegisteredPrompt(name, title, description, argsSchema, callback, icons, _meta) { + let currentArgsSchema = argsSchema; + let currentCallback = callback; + const registeredPrompt = { + title, + description, + argsSchema, + icons, + _meta, + handler: createPromptHandler(name, argsSchema, callback), + enabled: true, + disable: () => registeredPrompt.update({ enabled: false }), + enable: () => registeredPrompt.update({ enabled: true }), + remove: () => registeredPrompt.update({ name: null }), + update: (updates) => { + if (updates.name !== void 0 && updates.name !== name) { + delete this._registeredPrompts[name]; + if (updates.name) this._registeredPrompts[updates.name] = registeredPrompt; + } + if (updates.title !== void 0) registeredPrompt.title = updates.title; + if (updates.description !== void 0) registeredPrompt.description = updates.description; + if (updates.icons !== void 0) registeredPrompt.icons = updates.icons; + if (updates._meta !== void 0) registeredPrompt._meta = updates._meta; + let needsHandlerRegen = false; + if (updates.argsSchema !== void 0) { + registeredPrompt.argsSchema = updates.argsSchema; + currentArgsSchema = updates.argsSchema; + needsHandlerRegen = true; + } + if (updates.callback !== void 0) { + currentCallback = updates.callback; + needsHandlerRegen = true; + } + if (needsHandlerRegen) registeredPrompt.handler = createPromptHandler(name, currentArgsSchema, currentCallback); + if (updates.enabled !== void 0) registeredPrompt.enabled = updates.enabled; + this.sendPromptListChanged(); + } + }; + this._registeredPrompts[name] = registeredPrompt; + if (argsSchema) { + const shape = getSchemaShape(argsSchema); + if (shape) { + if (Object.values(shape).some((field) => { + return isCompletable(unwrapOptionalSchema(field)); + })) this.setCompletionRequestHandler(); + } + } + return registeredPrompt; + } + _createRegisteredTool(name, title, description, inputSchema, outputSchema, annotations, icons, execution, _meta, handler) { + validateAndWarnToolName(name); + if (inputSchema !== void 0) try { + const json = standardSchemaToJsonSchema(inputSchema, "input"); + this._toolInputSchemaJson[name] = json; + const scan = src_CX2iR2pK_scanXMcpHeaderDeclarations(json); + if (!scan.valid) console.warn(`[mcp-sdk] tool '${name}' carries an invalid x-mcp-header declaration and will be excluded by conforming Streamable HTTP clients: ${scan.reason}`); + } catch {} + let currentHandler = handler; + const registeredTool = { + title, + description, + inputSchema, + outputSchema, + outputSchemaJson: convertOutputSchemaJson(outputSchema), + annotations, + icons, + execution, + _meta, + handler, + executor: createToolExecutor(inputSchema, handler), + enabled: true, + disable: () => registeredTool.update({ enabled: false }), + enable: () => registeredTool.update({ enabled: true }), + remove: () => registeredTool.update({ name: null }), + update: (updates) => { + if (updates.name !== void 0 && updates.name !== name) { + if (typeof updates.name === "string") validateAndWarnToolName(updates.name); + delete this._registeredTools[name]; + delete this._toolInputSchemaJson[name]; + if (updates.name) { + delete this._toolInputSchemaJson[updates.name]; + this._registeredTools[updates.name] = registeredTool; + name = updates.name; + } + } + if (updates.title !== void 0) registeredTool.title = updates.title; + if (updates.description !== void 0) registeredTool.description = updates.description; + let needsExecutorRegen = false; + if (updates.paramsSchema !== void 0) { + registeredTool.inputSchema = updates.paramsSchema; + delete this._toolInputSchemaJson[name]; + needsExecutorRegen = true; + } + if (updates.callback !== void 0) { + registeredTool.handler = updates.callback; + currentHandler = updates.callback; + needsExecutorRegen = true; + } + if (needsExecutorRegen) registeredTool.executor = createToolExecutor(registeredTool.inputSchema, currentHandler); + if (updates.outputSchema !== void 0) { + registeredTool.outputSchema = updates.outputSchema; + registeredTool.outputSchemaJson = convertOutputSchemaJson(updates.outputSchema); + } + if (updates.annotations !== void 0) registeredTool.annotations = updates.annotations; + if (updates.icons !== void 0) registeredTool.icons = updates.icons; + if (updates._meta !== void 0) registeredTool._meta = updates._meta; + if (updates.enabled !== void 0) registeredTool.enabled = updates.enabled; + this.sendToolListChanged(); + } + }; + this._registeredTools[name] = registeredTool; + this.setToolRequestHandlers(); + this.sendToolListChanged(); + return registeredTool; + } + registerTool(name, config, cb) { + if (this._registeredTools[name]) throw new Error(`Tool ${name} is already registered`); + const { title, description, inputSchema, outputSchema, annotations, icons, _meta } = config; + return this._createRegisteredTool(name, title, description, normalizeRawShapeSchema(inputSchema), normalizeRawShapeSchema(outputSchema), annotations, icons, void 0, _meta, cb); + } + registerPrompt(name, config, cb) { + if (this._registeredPrompts[name]) throw new Error(`Prompt ${name} is already registered`); + const { title, description, argsSchema, icons, _meta } = config; + const registeredPrompt = this._createRegisteredPrompt(name, title, description, normalizeRawShapeSchema(argsSchema), cb, icons, _meta); + this.setPromptRequestHandlers(); + this.sendPromptListChanged(); + return registeredPrompt; + } + /** + * Checks if the server is connected to a transport. + * @returns `true` if the server is connected + */ + isConnected() { + return this.server.transport !== void 0; + } + /** + * Sends a logging message to the client, if connected. + * Note: You only need to send the parameters object, not the entire JSON-RPC message. + * @see {@linkcode LoggingMessageNotification} + * @param params + * @param sessionId Optional for stateless transports and backward compatibility. + * + * @example + * ```ts source="./mcp.examples.ts#McpServer_sendLoggingMessage_basic" + * await server.sendLoggingMessage({ + * level: 'info', + * data: 'Processing complete' + * }); + * ``` + * + * @deprecated Deprecated as of protocol version 2026-07-28 (SEP-2577). + * Remains functional during the deprecation window (at least twelve months). + * Migrate to stderr logging (STDIO servers) or OpenTelemetry. + */ + async sendLoggingMessage(params, sessionId) { + return this.server.sendLoggingMessage(params, sessionId); + } + /** + * Sends a resource list changed event to the client, if connected. + */ + sendResourceListChanged() { + if (this.isConnected()) this.server.sendResourceListChanged(); + } + /** + * Sends a tool list changed event to the client, if connected. + */ + sendToolListChanged() { + if (this.isConnected()) this.server.sendToolListChanged(); + } + /** + * Sends a prompt list changed event to the client, if connected. + */ + sendPromptListChanged() { + if (this.isConnected()) this.server.sendPromptListChanged(); + } +}; +/** +* A resource template combines a URI pattern with optional functionality to enumerate +* all resources matching that pattern. +*/ +var ResourceTemplate = class { + _uriTemplate; + constructor(uriTemplate, _callbacks) { + this._callbacks = _callbacks; + this._uriTemplate = typeof uriTemplate === "string" ? new UriTemplate(uriTemplate) : uriTemplate; + } + /** + * Gets the URI template pattern. + */ + get uriTemplate() { + return this._uriTemplate; + } + /** + * Gets the list callback, if one was provided. + */ + get listCallback() { + return this._callbacks.list; + } + /** + * Gets the callback for completing a specific URI template variable, if one was provided. + */ + completeCallback(variable) { + return this._callbacks.complete?.[variable]; + } +}; +/** +* Creates an executor that invokes the handler with the appropriate arguments. +* When `inputSchema` is defined, the handler is called with `(args, ctx)`. +* When `inputSchema` is undefined, the handler is called with just `(ctx)`. +*/ +function createToolExecutor(inputSchema, handler) { + if (inputSchema) { + const callback$1 = handler; + return async (args, ctx) => callback$1(args, ctx); + } + const callback = handler; + return async (_args, ctx) => callback(ctx); +} +const EMPTY_OBJECT_JSON_SCHEMA = { + type: "object", + properties: {} +}; +/** +* Convert a registered `outputSchema` to JSON Schema, memoised on {@link RegisteredTool.outputSchemaJson} +* so `tools/call` passes the SAME advertised schema to the wire codec's `projectCallToolResult` that +* `tools/list` emits (and that the 2025 codec's `encodeResult('tools/list', …)` may wrap). A conversion +* failure yields `undefined` so the failure surfaces where it always has (`tools/list`). +*/ +function convertOutputSchemaJson(outputSchema) { + if (outputSchema === void 0) return void 0; + try { + return standardSchemaToJsonSchema(outputSchema, "output"); + } catch { + return; + } +} +/** +* Creates a type-safe prompt handler that captures the schema and callback in a closure. +* This eliminates the need for type assertions at the call site. +*/ +function createPromptHandler(name, argsSchema, callback) { + if (argsSchema) { + const typedCallback = callback; + return async (args, ctx) => { + const parseResult = await validateStandardSchema(argsSchema, args); + if (!parseResult.success) throw new src_CX2iR2pK_ProtocolError(src_CX2iR2pK_ProtocolErrorCode.InvalidParams, `Invalid arguments for prompt ${name}: ${parseResult.error}`); + return typedCallback(parseResult.data, ctx); + }; + } else { + const typedCallback = callback; + return async (_args, ctx) => { + return typedCallback(ctx); + }; + } +} +function createCompletionResult(suggestions) { + return { completion: { + values: suggestions.map(String).slice(0, 100), + total: suggestions.length, + hasMore: suggestions.length > 100 + } }; +} +const EMPTY_COMPLETION_RESULT = { completion: { + values: [], + hasMore: false +} }; +/** @internal Gets the shape of a Zod object schema */ +function getSchemaShape(schema) { + const candidate = schema; + if (candidate.shape && typeof candidate.shape === "object") return candidate.shape; +} +/** @internal Checks if a Zod schema is optional */ +function isOptionalSchema(schema) { + return schema?.type === "optional"; +} +/** @internal Unwraps an optional Zod schema */ +function unwrapOptionalSchema(schema) { + if (!isOptionalSchema(schema)) return schema; + return schema.def?.innerType ?? schema; +} + +//#endregion + +//# sourceMappingURL=mcp-DXXb3Vv3.mjs.map + + + + +//#region src/server/perRequestTransport.ts +/** +* The per-request micro-transport: a real, connected `Transport` whose whole +* lifetime is one HTTP exchange. See the module documentation for the +* response shapes it produces. +*/ +var PerRequestHTTPServerTransport = class { + onclose; + onerror; + onmessage; + _classification; + _responseMode; + _started = false; + _used = false; + _closed = false; + _terminalDelivered = false; + /** + * `true` only while the inbound message is being delivered synchronously + * to the connected protocol layer. The pre-handler gates (the era + * registry gate, the edge→instance handoff check, the missing-handler + * rejection) answer inside this window; request handlers always run + * after it (the protocol layer defers them to a microtask). An error + * sent inside the window is therefore ladder-originated, and an error + * sent after it is handler-produced. + */ + _dispatchWindowOpen = false; + _requestId; + _deferredResponse; + _sse; + _abortCleanup; + _keepAliveMs; + constructor(options) { + this._classification = options.classification; + this._responseMode = options.responseMode ?? "auto"; + this._keepAliveMs = options.keepAliveMs ?? DEFAULT_SSE_KEEP_ALIVE_MS; + } + async start() { + if (this._started) throw new Error("PerRequestHTTPServerTransport is already started"); + this._started = true; + } + /** + * Serves the single exchange: delivers the classified message to the + * connected server instance and resolves with the HTTP response. + * + * Throws when called a second time (the transport is strictly + * single-use), or before a server has been connected to the transport. + * The returned promise rejects with a connection-closed error when the + * transport is closed before a response was produced (for example because + * the client disconnected). + */ + async handleMessage(message, extra) { + if (this._used) throw new Error("PerRequestHTTPServerTransport serves exactly one exchange; construct a new transport per request"); + if (!this._started || this.onmessage === void 0) throw new Error("PerRequestHTTPServerTransport is not connected: connect a server to this transport before handling a message"); + if (this._closed) throw new Error("PerRequestHTTPServerTransport is closed"); + this._used = true; + const signal = extra?.request?.signal; + if (signal?.aborted) { + await this.close(); + throw new SdkError(SdkErrorCode.ConnectionClosed, "The request was aborted before it could be handled"); + } + const messageExtra = { + classification: this._classification, + ...extra?.request !== void 0 && { request: extra.request }, + ...extra?.authInfo !== void 0 && { authInfo: extra.authInfo } + }; + if (isJSONRPCRequest(message)) { + this._requestId = message.id; + let resolve; + let reject; + const promise = new Promise((promiseResolve, promiseReject) => { + resolve = promiseResolve; + reject = promiseReject; + }); + this._deferredResponse = { + promise, + resolve, + reject, + settled: false + }; + if (signal !== void 0) { + const onAbort = () => void this.close(); + signal.addEventListener("abort", onAbort, { once: true }); + this._abortCleanup = () => signal.removeEventListener("abort", onAbort); + } + this._dispatchWindowOpen = true; + try { + this.onmessage(message, messageExtra); + } finally { + this._dispatchWindowOpen = false; + } + if (this._responseMode === "sse" && !this._closed && !this._deferredResponse.settled) this.upgradeToSse(); + return promise; + } + this.onmessage(message, messageExtra); + return new Response(null, { status: 202 }); + } + async send(message, options) { + if (this._closed) return; + const isResponse = isJSONRPCResultResponse(message) || isJSONRPCErrorResponse(message); + const relatedId = isResponse ? message.id : options?.relatedRequestId; + if (this._requestId === void 0 || relatedId === void 0 || relatedId !== this._requestId) { + if (isResponse) this.onerror?.(/* @__PURE__ */ new Error(`Received a response for an unknown request id: ${String(message.id)}`)); + return; + } + if (isResponse) { + if (this._terminalDelivered) return; + this._terminalDelivered = true; + const errorCode = isJSONRPCErrorResponse(message) ? message.error.code : void 0; + const ladderStatus = errorCode !== void 0 && (this._dispatchWindowOpen || errorCode === ProtocolErrorCode.MissingRequiredClientCapability) ? LADDER_ERROR_HTTP_STATUS[errorCode] : void 0; + if (ladderStatus !== void 0 && this._sse === void 0) { + this.settleResponse(Response.json(message, { + status: ladderStatus, + headers: { "Content-Type": "application/json" } + })); + queueMicrotask(() => void this.close()); + return; + } + if (this._sse !== void 0 || this._responseMode === "sse") { + if (this._sse === void 0) this.upgradeToSse(); + this.writeMessageFrame(message); + this.finalizeStream(); + return; + } + this.settleResponse(Response.json(message, { + status: 200, + headers: { "Content-Type": "application/json" } + })); + queueMicrotask(() => void this.close()); + return; + } + if (this._responseMode === "json") return; + if (this._sse === void 0) this.upgradeToSse(); + this.writeMessageFrame(message); + } + /** + * Writes an SSE comment frame (a keep-alive heartbeat). Dropped when the + * exchange is not currently streaming. + */ + writeCommentFrame(comment) { + if (this._closed || this._sse === void 0 || this._sse.closed) return; + const frame = comment.split("\n").map((line) => `: ${line}`).join("\n"); + this.writeFrame(`${frame}\n\n`); + } + async close() { + if (this._closed) return; + this._closed = true; + this._abortCleanup?.(); + this._abortCleanup = void 0; + if (this._sse?.keepAliveTimer !== void 0) clearInterval(this._sse.keepAliveTimer); + if (this._sse !== void 0 && !this._sse.closed) { + this._sse.closed = true; + try { + this._sse.controller.close(); + } catch {} + } + if (this._deferredResponse !== void 0 && !this._deferredResponse.settled) { + this._deferredResponse.settled = true; + this._deferredResponse.reject(new SdkError(SdkErrorCode.ConnectionClosed, "Connection closed before a response was produced")); + } + this.onclose?.(); + } + settleResponse(response) { + if (this._deferredResponse === void 0 || this._deferredResponse.settled) return; + this._deferredResponse.settled = true; + this._deferredResponse.resolve(response); + } + upgradeToSse() { + let controller; + const readable = new ReadableStream({ + start: (streamController) => { + controller = streamController; + }, + cancel: () => { + this.close(); + } + }); + this._sse = { + controller, + encoder: new TextEncoder(), + closed: false + }; + this._sse.keepAliveTimer = armSseKeepAlive(this._keepAliveMs, () => this.writeCommentFrame("keepalive")); + this.settleResponse(new Response(readable, { + status: 200, + headers: { + "Content-Type": "text/event-stream", + "Cache-Control": "no-cache, no-transform", + Connection: "keep-alive", + "X-Accel-Buffering": "no" + } + })); + } + finalizeStream() { + if (this._sse?.keepAliveTimer !== void 0) clearInterval(this._sse.keepAliveTimer); + if (this._sse !== void 0 && !this._sse.closed) { + this._sse.closed = true; + try { + this._sse.controller.close(); + } catch {} + } + queueMicrotask(() => void this.close()); + } + writeMessageFrame(message) { + this.writeFrame(`event: message\ndata: ${JSON.stringify(message)}\n\n`); + } + writeFrame(frame) { + if (this._sse === void 0 || this._sse.closed) return; + try { + this._sse.controller.enqueue(this._sse.encoder.encode(frame)); + } catch (error) { + this.onerror?.(/* @__PURE__ */ new Error(`Failed to write to the response stream: ${error}`)); + } + } +}; + +//#endregion +//#region src/server/invoke.ts +/** +* Serves one classified inbound message on the given server instance and +* returns the HTTP response for the exchange. +* +* The instance is connected to a fresh single-exchange transport, the message +* is injected through the normal transport message path, and whatever the +* dispatch layer produces (the handler result, a protocol-level rejection, or +* streamed related messages followed by the result) is captured as the +* returned `Response`. For request exchanges, teardown rides the transport's +* close chain once the terminal response has been delivered; notification +* exchanges resolve with the 202 response immediately and do NOT run the +* close chain — the transport stays connected until the caller closes it or +* drops the per-request instance, which is the caller's choice either way. +*/ +async function invoke(server, message, ctx) { + const transport = new PerRequestHTTPServerTransport({ + classification: ctx.classification, + ...ctx.responseMode !== void 0 && { responseMode: ctx.responseMode }, + ...ctx.keepAliveMs !== void 0 && { keepAliveMs: ctx.keepAliveMs } + }); + await server.connect(transport); + return transport.handleMessage(message, { + ...ctx.request !== void 0 && { request: ctx.request }, + ...ctx.authInfo !== void 0 && { authInfo: ctx.authInfo } + }); +} + +//#endregion +//#region src/server/streamableHttp.ts +/** +* Server transport for Web Standards Streamable HTTP: this implements the MCP Streamable HTTP transport specification +* using Web Standard APIs (`Request`, `Response`, `ReadableStream`). +* +* This transport works on any runtime that supports Web Standards: Node.js 18+, Cloudflare Workers, Deno, Bun, etc. +* +* In stateful mode: +* - Session ID is generated and included in response headers +* - Session ID is always included in initialization responses +* - Requests with invalid session IDs are rejected with `404 Not Found` +* - Non-initialization requests without a session ID are rejected with `400 Bad Request` +* - State is maintained in-memory (connections, message history) +* +* In stateless mode: +* - No Session ID is included in any responses +* - No session validation is performed +* +* @example Stateful setup +* ```ts source="./streamableHttp.examples.ts#WebStandardStreamableHTTPServerTransport_stateful" +* const server = new McpServer({ name: 'my-server', version: '1.0.0' }); +* +* const transport = new WebStandardStreamableHTTPServerTransport({ +* sessionIdGenerator: () => crypto.randomUUID() +* }); +* +* await server.connect(transport); +* ``` +* +* @example Stateless setup +* ```ts source="./streamableHttp.examples.ts#WebStandardStreamableHTTPServerTransport_stateless" +* const transport = new WebStandardStreamableHTTPServerTransport({ +* sessionIdGenerator: undefined +* }); +* ``` +* +* @example Hono.js +* ```ts source="./streamableHttp.examples.ts#WebStandardStreamableHTTPServerTransport_hono" +* app.all('/mcp', async c => { +* return transport.handleRequest(c.req.raw); +* }); +* ``` +* +* @example Cloudflare Workers +* ```ts source="./streamableHttp.examples.ts#WebStandardStreamableHTTPServerTransport_workers" +* const worker = { +* async fetch(request: Request): Promise { +* return transport.handleRequest(request); +* } +* }; +* ``` +*/ +var WebStandardStreamableHTTPServerTransport = class { + sessionIdGenerator; + _started = false; + _closed = false; + _streamMapping = /* @__PURE__ */ new Map(); + _requestToStreamMapping = /* @__PURE__ */ new Map(); + _requestResponseMap = /* @__PURE__ */ new Map(); + _initialized = false; + _enableJsonResponse = false; + _standaloneSseStreamId = "_GET_stream"; + _eventStore; + _onsessioninitialized; + _onsessionclosed; + _allowedHosts; + _allowedOrigins; + _enableDnsRebindingProtection; + _retryInterval; + _supportedProtocolVersions; + _keepAliveMs; + sessionId; + onclose; + onerror; + onmessage; + constructor(options = {}) { + this.sessionIdGenerator = options.sessionIdGenerator; + this._enableJsonResponse = options.enableJsonResponse ?? false; + this._eventStore = options.eventStore; + this._onsessioninitialized = options.onsessioninitialized; + this._onsessionclosed = options.onsessionclosed; + this._allowedHosts = options.allowedHosts; + this._allowedOrigins = options.allowedOrigins; + this._enableDnsRebindingProtection = options.enableDnsRebindingProtection ?? false; + this._retryInterval = options.retryInterval; + this._supportedProtocolVersions = options.supportedProtocolVersions ?? SUPPORTED_PROTOCOL_VERSIONS; + this._keepAliveMs = options.keepAliveMs ?? DEFAULT_SSE_KEEP_ALIVE_MS; + } + startKeepAlive(controller, encoder) { + if (this._closed) return void 0; + const timer = armSseKeepAlive(this._keepAliveMs, () => { + try { + controller.enqueue(encoder.encode(": keepalive\n\n")); + } catch { + if (timer !== void 0) clearInterval(timer); + } + }); + return timer; + } + /** + * Starts the transport. This is required by the {@linkcode Transport} interface but is a no-op + * for the Streamable HTTP transport as connections are managed per-request. + */ + async start() { + if (this._started) throw new Error("Transport already started"); + this._started = true; + } + /** + * Sets the supported protocol versions for header validation. + * Called by the server during {@linkcode server/server.Server.connect | connect()} to pass its supported versions. + */ + setSupportedProtocolVersions(versions) { + this._supportedProtocolVersions = versions; + } + /** + * Helper to create a JSON error response + */ + createJsonErrorResponse(status, code, message, options) { + const error = { + code, + message + }; + if (options?.data !== void 0) error.data = options.data; + return Response.json({ + jsonrpc: "2.0", + error, + id: null + }, { + status, + headers: { + "Content-Type": "application/json", + ...options?.headers + } + }); + } + /** + * Validates request headers for DNS rebinding protection. + * @returns Error response if validation fails, `undefined` if validation passes. + */ + validateRequestHeaders(req) { + if (!this._enableDnsRebindingProtection) return; + if (this._allowedHosts && this._allowedHosts.length > 0) { + const hostHeader = req.headers.get("host"); + if (!hostHeader || !this._allowedHosts.includes(hostHeader)) { + const error = `Invalid Host header: ${hostHeader}`; + this.onerror?.(new Error(error)); + return this.createJsonErrorResponse(403, -32e3, error); + } + } + if (this._allowedOrigins && this._allowedOrigins.length > 0) { + const originHeader = req.headers.get("origin"); + if (originHeader && !this._allowedOrigins.includes(originHeader)) { + const error = `Invalid Origin header: ${originHeader}`; + this.onerror?.(new Error(error)); + return this.createJsonErrorResponse(403, -32e3, error); + } + } + } + /** + * Handles an incoming HTTP request, whether `GET`, `POST`, or `DELETE` + * Returns a `Response` object (Web Standard) + */ + async handleRequest(req, options) { + if (this._closed) return this.createJsonErrorResponse(404, -32001, "Session not found"); + const validationError = this.validateRequestHeaders(req); + if (validationError) return validationError; + switch (req.method) { + case "POST": return this.handlePostRequest(req, options); + case "GET": return this.handleGetRequest(req); + case "DELETE": return this.handleDeleteRequest(req); + default: return this.handleUnsupportedRequest(); + } + } + /** + * Returns true if the client's protocol version supports empty SSE data in + * priming events (the fix shipped with protocol version `2025-11-25`). + * + * The version is checked for membership in this transport instance's + * supported protocol versions rather than with an open-ended + * `>= '2025-11-25'` comparison: the value may come from an `initialize` + * request body, which (unlike the `MCP-Protocol-Version` header) is not + * validated against `supportedProtocolVersions` before reaching this + * check. An unknown future version string must not silently enable + * behavior reserved for versions this transport actually supports. + */ + supportsEmptySSEData(protocolVersion) { + return this._supportedProtocolVersions.includes(protocolVersion) && protocolVersion >= "2025-11-25"; + } + /** + * Writes a priming event to establish resumption capability. + * Only sends if `eventStore` is configured (opt-in for resumability) and + * the client's protocol version supports empty SSE data (a supported + * version that is >= `2025-11-25`). + */ + async writePrimingEvent(controller, encoder, streamId, protocolVersion) { + if (!this._eventStore) return; + if (!this.supportsEmptySSEData(protocolVersion)) return; + const primingEventId = await this._eventStore.storeEvent(streamId, {}); + let primingEvent = `id: ${primingEventId}\ndata: \n\n`; + if (this._retryInterval !== void 0) primingEvent = `id: ${primingEventId}\nretry: ${this._retryInterval}\ndata: \n\n`; + controller.enqueue(encoder.encode(primingEvent)); + } + /** + * Handles `GET` requests for SSE stream + */ + async handleGetRequest(req) { + if (!req.headers.get("accept")?.includes("text/event-stream")) { + this.onerror?.(/* @__PURE__ */ new Error("Not Acceptable: Client must accept text/event-stream")); + return this.createJsonErrorResponse(406, -32e3, "Not Acceptable: Client must accept text/event-stream"); + } + const sessionError = this.validateSession(req); + if (sessionError) return sessionError; + const protocolError = this.validateProtocolVersion(req); + if (protocolError) return protocolError; + if (this._eventStore) { + const lastEventId = req.headers.get("last-event-id"); + if (lastEventId) return this.replayEvents(lastEventId); + } + if (this._streamMapping.get(this._standaloneSseStreamId) !== void 0) { + this.onerror?.(/* @__PURE__ */ new Error("Conflict: Only one SSE stream is allowed per session")); + return this.createJsonErrorResponse(409, -32e3, "Conflict: Only one SSE stream is allowed per session"); + } + const encoder = new TextEncoder(); + let streamController; + let keepAliveTimer; + const readable = new ReadableStream({ + start: (controller) => { + streamController = controller; + }, + cancel: () => { + if (keepAliveTimer !== void 0) clearInterval(keepAliveTimer); + if (this._streamMapping.get(this._standaloneSseStreamId)?.controller === streamController) this._streamMapping.delete(this._standaloneSseStreamId); + } + }); + const headers = { + "Content-Type": "text/event-stream", + "Cache-Control": "no-cache, no-transform", + Connection: "keep-alive", + "X-Accel-Buffering": "no" + }; + if (this.sessionId !== void 0) headers["mcp-session-id"] = this.sessionId; + this._streamMapping.set(this._standaloneSseStreamId, { + controller: streamController, + encoder, + cleanup: () => { + if (keepAliveTimer !== void 0) clearInterval(keepAliveTimer); + this._streamMapping.delete(this._standaloneSseStreamId); + try { + streamController.close(); + } catch {} + } + }); + keepAliveTimer = this.startKeepAlive(streamController, encoder); + return new Response(readable, { headers }); + } + /** + * Replays events that would have been sent after the specified event ID + * Only used when resumability is enabled + */ + async replayEvents(lastEventId) { + if (!this._eventStore) { + this.onerror?.(/* @__PURE__ */ new Error("Event store not configured")); + return this.createJsonErrorResponse(400, -32e3, "Event store not configured"); + } + try { + let streamId; + if (this._eventStore.getStreamIdForEventId) { + streamId = await this._eventStore.getStreamIdForEventId(lastEventId); + if (!streamId) { + this.onerror?.(/* @__PURE__ */ new Error("Invalid event ID format")); + return this.createJsonErrorResponse(400, -32e3, "Invalid event ID format"); + } + if (this._streamMapping.get(streamId) !== void 0) { + this.onerror?.(/* @__PURE__ */ new Error("Conflict: Stream already has an active connection")); + return this.createJsonErrorResponse(409, -32e3, "Conflict: Stream already has an active connection"); + } + } + const headers = { + "Content-Type": "text/event-stream", + "Cache-Control": "no-cache, no-transform", + Connection: "keep-alive", + "X-Accel-Buffering": "no" + }; + if (this.sessionId !== void 0) headers["mcp-session-id"] = this.sessionId; + const encoder = new TextEncoder(); + let streamController; + let keepAliveTimer; + let cancelled = false; + let replayedStreamId; + const readable = new ReadableStream({ + start: (controller) => { + streamController = controller; + }, + cancel: () => { + cancelled = true; + if (keepAliveTimer !== void 0) clearInterval(keepAliveTimer); + if (replayedStreamId !== void 0 && this._streamMapping.get(replayedStreamId)?.controller === streamController) this._streamMapping.delete(replayedStreamId); + } + }); + const replayedEventIds = /* @__PURE__ */ new Set(); + replayedStreamId = await this._eventStore.replayEventsAfter(lastEventId, { send: async (eventId, message) => { + replayedEventIds.add(eventId); + if (!this.writeSSEEvent(streamController, encoder, message, eventId)) try { + streamController.close(); + } catch {} + } }); + if (this._closed || cancelled) { + try { + streamController.close(); + } catch {} + return this.createJsonErrorResponse(404, -32001, "Session not found"); + } + this._streamMapping.get(replayedStreamId)?.cleanup(); + this._streamMapping.set(replayedStreamId, { + controller: streamController, + encoder, + replayedEventIds, + cleanup: () => { + if (keepAliveTimer !== void 0) clearInterval(keepAliveTimer); + this._streamMapping.delete(replayedStreamId); + try { + streamController.close(); + } catch {} + } + }); + if (replayedStreamId !== this._standaloneSseStreamId) { + if (![...this._requestToStreamMapping.values()].includes(replayedStreamId)) { + this._streamMapping.delete(replayedStreamId); + try { + streamController.close(); + } catch {} + } + } + if (this._streamMapping.get(replayedStreamId)?.controller === streamController) keepAliveTimer = this.startKeepAlive(streamController, encoder); + return new Response(readable, { headers }); + } catch (error) { + this.onerror?.(error); + return this.createJsonErrorResponse(500, -32e3, "Error replaying events"); + } + } + /** + * Writes an event to an SSE stream via controller with proper formatting + */ + writeSSEEvent(controller, encoder, message, eventId) { + try { + let eventData = `event: message\n`; + if (eventId) eventData += `id: ${eventId}\n`; + eventData += `data: ${JSON.stringify(message)}\n\n`; + controller.enqueue(encoder.encode(eventData)); + return true; + } catch (error) { + this.onerror?.(error); + return false; + } + } + /** + * Handles unsupported requests (`PUT`, `PATCH`, etc.) + */ + handleUnsupportedRequest() { + this.onerror?.(/* @__PURE__ */ new Error("Method not allowed.")); + return Response.json({ + jsonrpc: "2.0", + error: { + code: -32e3, + message: "Method not allowed." + }, + id: null + }, { + status: 405, + headers: { + Allow: "GET, POST, DELETE", + "Content-Type": "application/json" + } + }); + } + /** + * Handles `POST` requests containing JSON-RPC messages + */ + async handlePostRequest(req, options) { + try { + const acceptHeader = req.headers.get("accept"); + if (!acceptHeader?.includes("application/json") || !acceptHeader.includes("text/event-stream")) { + this.onerror?.(/* @__PURE__ */ new Error("Not Acceptable: Client must accept both application/json and text/event-stream")); + return this.createJsonErrorResponse(406, -32e3, "Not Acceptable: Client must accept both application/json and text/event-stream"); + } + if (!isJsonContentType(req.headers.get("content-type"))) { + this.onerror?.(/* @__PURE__ */ new Error("Unsupported Media Type: Content-Type must be application/json")); + return this.createJsonErrorResponse(415, -32e3, "Unsupported Media Type: Content-Type must be application/json"); + } + const request = req; + let rawMessage; + if (options?.parsedBody === void 0) try { + rawMessage = await req.json(); + } catch (error) { + this.onerror?.(error); + return this.createJsonErrorResponse(400, -32700, "Parse error: Invalid JSON"); + } + else rawMessage = options.parsedBody; + let messages; + try { + messages = Array.isArray(rawMessage) ? rawMessage.map((msg) => JSONRPCMessageSchema.parse(msg)) : [JSONRPCMessageSchema.parse(rawMessage)]; + } catch (error) { + this.onerror?.(error); + return this.createJsonErrorResponse(400, -32700, "Parse error: Invalid JSON-RPC message"); + } + if (this._closed) return this.createJsonErrorResponse(404, -32001, "Session not found"); + const isInitializationRequest = messages.some((element) => isInitializeRequest(element)); + if (isInitializationRequest) { + if (this._initialized && this.sessionId !== void 0) { + this.onerror?.(/* @__PURE__ */ new Error("Invalid Request: Server already initialized")); + return this.createJsonErrorResponse(400, -32600, "Invalid Request: Server already initialized"); + } + if (messages.length > 1) { + this.onerror?.(/* @__PURE__ */ new Error("Invalid Request: Only one initialization request is allowed")); + return this.createJsonErrorResponse(400, -32600, "Invalid Request: Only one initialization request is allowed"); + } + this.sessionId = this.sessionIdGenerator?.(); + this._initialized = true; + if (this.sessionId && this._onsessioninitialized) await Promise.resolve(this._onsessioninitialized(this.sessionId)); + } + if (!isInitializationRequest) { + const sessionError = this.validateSession(req); + if (sessionError) return sessionError; + const protocolError = this.validateProtocolVersion(req); + if (protocolError) return protocolError; + } + if (this._closed) return this.createJsonErrorResponse(404, -32001, "Session not found"); + if (!messages.some((element) => isJSONRPCRequest(element))) { + for (const message of messages) this.onmessage?.(message, { + authInfo: options?.authInfo, + request + }); + return new Response(null, { status: 202 }); + } + const streamId = crypto.randomUUID(); + const initRequest = messages.find((m) => isInitializeRequest(m)); + const clientProtocolVersion = initRequest ? initRequest.params.protocolVersion : req.headers.get("mcp-protocol-version") ?? DEFAULT_NEGOTIATED_PROTOCOL_VERSION; + if (this._enableJsonResponse) return new Promise((resolve) => { + this._streamMapping.set(streamId, { + resolveJson: resolve, + cleanup: () => { + this._streamMapping.delete(streamId); + } + }); + for (const message of messages) if (isJSONRPCRequest(message)) this._requestToStreamMapping.set(message.id, streamId); + for (const message of messages) this.onmessage?.(message, { + authInfo: options?.authInfo, + request + }); + }); + const encoder = new TextEncoder(); + let streamController; + let keepAliveTimer; + const readable = new ReadableStream({ + start: (controller) => { + streamController = controller; + }, + cancel: () => { + if (keepAliveTimer !== void 0) clearInterval(keepAliveTimer); + if (this._streamMapping.get(streamId)?.controller === streamController) this._streamMapping.delete(streamId); + } + }); + const headers = { + "Content-Type": "text/event-stream", + "Cache-Control": "no-cache, no-transform", + Connection: "keep-alive", + "X-Accel-Buffering": "no" + }; + if (this.sessionId !== void 0) headers["mcp-session-id"] = this.sessionId; + for (const message of messages) if (isJSONRPCRequest(message)) { + this._streamMapping.set(streamId, { + controller: streamController, + encoder, + cleanup: () => { + if (keepAliveTimer !== void 0) clearInterval(keepAliveTimer); + this._streamMapping.delete(streamId); + try { + streamController.close(); + } catch {} + } + }); + this._requestToStreamMapping.set(message.id, streamId); + } + await this.writePrimingEvent(streamController, encoder, streamId, clientProtocolVersion); + for (const message of messages) { + let closeSSEStream; + let closeStandaloneSSEStream; + if (isJSONRPCRequest(message) && this._eventStore && this.supportsEmptySSEData(clientProtocolVersion)) { + closeSSEStream = () => { + this.closeSSEStream(message.id); + }; + closeStandaloneSSEStream = () => { + this.closeStandaloneSSEStream(); + }; + } + this.onmessage?.(message, { + authInfo: options?.authInfo, + request, + closeSSEStream, + closeStandaloneSSEStream + }); + } + if (this._streamMapping.get(streamId)?.controller === streamController) keepAliveTimer = this.startKeepAlive(streamController, encoder); + return new Response(readable, { + status: 200, + headers + }); + } catch (error) { + this.onerror?.(error); + return this.createJsonErrorResponse(400, -32700, "Parse error", { data: String(error) }); + } + } + /** + * Handles `DELETE` requests to terminate sessions + */ + async handleDeleteRequest(req) { + const sessionError = this.validateSession(req); + if (sessionError) return sessionError; + const protocolError = this.validateProtocolVersion(req); + if (protocolError) return protocolError; + try { + await Promise.resolve(this._onsessionclosed?.(this.sessionId)); + return new Response(null, { status: 200 }); + } finally { + await this.close(); + } + } + /** + * Validates session ID for non-initialization requests. + * Returns `Response` error if invalid, `undefined` otherwise + */ + validateSession(req) { + if (this.sessionIdGenerator === void 0) return; + if (!this._initialized) { + this.onerror?.(/* @__PURE__ */ new Error("Bad Request: Server not initialized")); + return this.createJsonErrorResponse(400, -32e3, "Bad Request: Server not initialized"); + } + const sessionId = req.headers.get("mcp-session-id"); + if (!sessionId) { + this.onerror?.(/* @__PURE__ */ new Error("Bad Request: Mcp-Session-Id header is required")); + return this.createJsonErrorResponse(400, -32e3, "Bad Request: Mcp-Session-Id header is required"); + } + if (sessionId !== this.sessionId) { + this.onerror?.(/* @__PURE__ */ new Error("Session not found")); + return this.createJsonErrorResponse(404, -32001, "Session not found"); + } + } + /** + * Validates the `MCP-Protocol-Version` header on incoming requests. + * + * For initialization: Version negotiation handles unknown versions gracefully + * (server responds with its supported version). + * + * For subsequent requests with `MCP-Protocol-Version` header: + * - Accept if in supported list + * - 400 if unsupported + * + * For HTTP requests without the `MCP-Protocol-Version` header: + * - Accept and default to the version negotiated at initialization + */ + validateProtocolVersion(req) { + const protocolVersion = req.headers.get("mcp-protocol-version"); + if (protocolVersion !== null && !this._supportedProtocolVersions.includes(protocolVersion)) { + const error = `Bad Request: Unsupported protocol version: ${protocolVersion} (supported versions: ${this._supportedProtocolVersions.join(", ")})`; + this.onerror?.(new Error(error)); + return this.createJsonErrorResponse(400, -32e3, error); + } + } + async close() { + if (this._closed) return; + this._closed = true; + for (const { cleanup } of this._streamMapping.values()) cleanup(); + this._streamMapping.clear(); + this._requestResponseMap.clear(); + this.onclose?.(); + } + /** + * Close an SSE stream for a specific request, triggering client reconnection. + * Use this to implement polling behavior during long-running operations - + * client will reconnect after the retry interval specified in the priming event. + */ + closeSSEStream(requestId) { + const streamId = this._requestToStreamMapping.get(requestId); + if (!streamId) return; + const stream = this._streamMapping.get(streamId); + if (stream) stream.cleanup(); + } + /** + * Close the standalone `GET` SSE stream, triggering client reconnection. + * Use this to implement polling behavior for server-initiated notifications. + */ + closeStandaloneSSEStream() { + const stream = this._streamMapping.get(this._standaloneSseStreamId); + if (stream) stream.cleanup(); + } + async send(message, options) { + let requestId = options?.relatedRequestId; + if (isJSONRPCResultResponse(message) || isJSONRPCErrorResponse(message)) requestId = message.id; + if (requestId === void 0) { + if (isJSONRPCResultResponse(message) || isJSONRPCErrorResponse(message)) throw new Error("Cannot send a response on a standalone SSE stream unless resuming a previous client request"); + let eventId; + if (this._eventStore) eventId = await this._eventStore.storeEvent(this._standaloneSseStreamId, message); + const standaloneSse = this._streamMapping.get(this._standaloneSseStreamId); + if (standaloneSse === void 0) return; + if (standaloneSse.controller && standaloneSse.encoder && (eventId === void 0 || !standaloneSse.replayedEventIds?.has(eventId))) this.writeSSEEvent(standaloneSse.controller, standaloneSse.encoder, message, eventId); + return; + } + const streamId = this._requestToStreamMapping.get(requestId); + if (!streamId) throw new Error(`No connection established for request ID: ${String(requestId)}`); + let stream = this._streamMapping.get(streamId); + if (!this._enableJsonResponse) { + let eventId; + if (this._eventStore) { + eventId = await this._eventStore.storeEvent(streamId, message); + stream = this._streamMapping.get(streamId); + } + if (stream?.controller && stream?.encoder && (eventId === void 0 || !stream.replayedEventIds?.has(eventId))) this.writeSSEEvent(stream.controller, stream.encoder, message, eventId); + } + if (isJSONRPCResultResponse(message) || isJSONRPCErrorResponse(message)) { + this._requestResponseMap.set(requestId, message); + const relatedIds = [...this._requestToStreamMapping.entries()].filter(([_, sid]) => sid === streamId).map(([id]) => id); + if (relatedIds.every((id) => this._requestResponseMap.has(id))) { + if (!stream) { + if (this._enableJsonResponse) throw new Error(`No connection established for request ID: ${String(requestId)}`); + if (!this._eventStore) { + this.onerror?.(/* @__PURE__ */ new Error(`Response for request ID ${String(requestId)} is undeliverable: per-request stream is disconnected and no eventStore is configured`)); + for (const id of relatedIds) { + this._requestResponseMap.delete(id); + this._requestToStreamMapping.delete(id); + } + return; + } + for (const id of relatedIds) { + this._requestResponseMap.delete(id); + this._requestToStreamMapping.delete(id); + } + return; + } + if (this._enableJsonResponse && stream.resolveJson) { + const headers = { "Content-Type": "application/json" }; + if (this.sessionId !== void 0) headers["mcp-session-id"] = this.sessionId; + const responses = relatedIds.map((id) => this._requestResponseMap.get(id)); + if (responses.length === 1) stream.resolveJson(Response.json(responses[0], { + status: 200, + headers + })); + else stream.resolveJson(Response.json(responses, { + status: 200, + headers + })); + stream.cleanup(); + } else stream.cleanup(); + for (const id of relatedIds) { + this._requestResponseMap.delete(id); + this._requestToStreamMapping.delete(id); + } + } + } + } +}; + +//#endregion +//#region src/server/createMcpHandler.ts +/** +* The JSON-RPC id to echo on an entry-built error response: the body's `id` +* when the body is a single JSON-RPC request whose id is a string or number, +* `null` otherwise. Error responses must carry the id of the request they +* correspond to whenever it could be read; `null` is reserved for the cases +* where no single request id is determinable — unparseable bodies, body-less +* methods, notifications, posted responses and batch arrays. +*/ +function echoableRequestId(body) { + if (body === null || typeof body !== "object" || Array.isArray(body)) return null; + const { method, id } = body; + if (typeof method !== "string") return null; + return typeof id === "string" || typeof id === "number" ? id : null; +} +function jsonRpcErrorResponse(httpStatus, code, message, data, id = null) { + return Response.json({ + jsonrpc: "2.0", + error: { + code, + message, + ...data !== void 0 && { data } + }, + id + }, { status: httpStatus }); +} +function rejectionResponse(rejection, id = null) { + return jsonRpcErrorResponse(rejection.httpStatus, rejection.code, rejection.message, rejection.data, id); +} +function toError(value) { + return value instanceof Error ? value : new Error(String(value)); +} +function internalServerErrorResponse(id = null) { + return jsonRpcErrorResponse(500, -32603, "Internal server error", void 0, id); +} +/** +* The entry's default legacy serving (`legacy: 'stateless'`): per-request +* stateless serving of 2025-era traffic using the same factory as the modern +* path. Exported as a standalone building block for hand-wired compositions +* (for example mounting legacy stateless serving on its own route next to a +* strict modern endpoint). +* +* Each POST is served by a fresh instance from the factory connected to a +* fresh streamable HTTP transport constructed with only +* `sessionIdGenerator: undefined` — the established stateless idiom, unchanged. +* Because serving is per-request and stateless, GET and DELETE (2025 session +* operations) are answered with `405` / `Method not allowed.`, exactly like the +* canonical stateless example. +* +* The optional `onerror` callback receives factory and serving failures on +* this leg (reporting only — the response stays the 500 internal-error body). +* The entry passes its own `onerror` here when expanding the default, so +* legacy-leg failures are never silently swallowed. +*/ +function createLegacyStatelessFallback(factory, onerror, keepAliveMs) { + return async (request, options) => { + if (request.method.toUpperCase() !== "POST") return jsonRpcErrorResponse(405, -32e3, "Method not allowed."); + try { + const product = await factory({ + era: "legacy", + ...options?.authInfo !== void 0 && { authInfo: options.authInfo }, + requestInfo: request + }); + const transport = new WebStandardStreamableHTTPServerTransport({ + sessionIdGenerator: void 0, + ...keepAliveMs !== void 0 && { keepAliveMs } + }); + await product.connect(transport); + const teardown = () => { + transport.close().catch(() => {}); + product.close().catch(() => {}); + }; + request.signal?.addEventListener("abort", teardown, { once: true }); + const response = await transport.handleRequest(request, { + ...options?.authInfo !== void 0 && { authInfo: options.authInfo }, + ...options?.parsedBody !== void 0 && { parsedBody: options.parsedBody } + }); + if (response.body === null || mediaTypeEssence(response.headers.get("content-type")) !== "text/event-stream") { + teardown(); + return response; + } + const reader = response.body.getReader(); + let toreDown = false; + const completeExchange = () => { + if (!toreDown) { + toreDown = true; + teardown(); + } + }; + const monitoredBody = new ReadableStream({ + pull: async (controller) => { + try { + const { done, value } = await reader.read(); + if (done) { + completeExchange(); + controller.close(); + return; + } + if (value !== void 0) controller.enqueue(value); + } catch (error) { + completeExchange(); + controller.error(error); + } + }, + cancel: (reason) => { + completeExchange(); + return reader.cancel(reason).catch(() => {}); + } + }); + return new Response(monitoredBody, { + status: response.status, + statusText: response.statusText, + headers: response.headers + }); + } catch (error) { + try { + onerror?.(toError(error)); + } catch {} + return internalServerErrorResponse(echoableRequestId(options?.parsedBody)); + } + }; +} +function legacyStatelessFallback(factory, onerror) { + return createLegacyStatelessFallback(factory, onerror); +} +/** +* The entry's classification step: read the request body exactly once (unless +* a pre-parsed body is supplied) and classify the request with +* {@linkcode classifyInboundRequest}. This is the single code path behind both +* {@linkcode createMcpHandler}'s routing and the exported +* {@linkcode isLegacyRequest} predicate, so the two can never disagree. +* +* Pass `needsForward: false` when the caller never reads `forwardRequest` — +* the body-preserving clone is then skipped and `forwardRequest` is the +* (consumed) input request. +*/ +async function classifyEntryRequest(request, providedParsedBody, needsForward = true) { + const httpMethod = request.method.toUpperCase(); + let body; + let parsedBody = providedParsedBody; + let forwardRequest = request; + let unparseable = false; + if (httpMethod === "POST") { + if (parsedBody === void 0) { + if (needsForward) forwardRequest = request.clone(); + let bodyText; + try { + bodyText = await request.text(); + } catch { + return { step: "unreadable-body" }; + } + try { + body = bodyText.length === 0 ? void 0 : JSON.parse(bodyText); + } catch { + unparseable = true; + } + if (!unparseable && body !== void 0) parsedBody = body; + } else body = parsedBody; + if (unparseable || body === void 0) return { + step: "no-json-body", + forwardRequest + }; + } + return { + step: "classified", + outcome: classifyInboundRequest({ + httpMethod, + protocolVersionHeader: request.headers.get("mcp-protocol-version") ?? void 0, + mcpMethodHeader: request.headers.get("mcp-method") ?? void 0, + mcpNameHeader: request.headers.get("mcp-name") ?? void 0, + ...body !== void 0 && { body } + }), + body, + parsedBody, + forwardRequest + }; +} +/** +* Whether {@linkcode createMcpHandler} would route this request to its legacy +* (2025-era) serving rather than the modern (2026-07-28) path. +* +* Call it with just the request: `await isLegacyRequest(request)`. For a +* `POST` the body is read from an internal clone, so the request you pass +* stays fully readable for whichever handler you route it to — no second +* argument is needed. (In a Node `(req, res)` handler, build that `Request` +* with `toWebRequest(req)` from `@modelcontextprotocol/node`; behind a body +* parser, which has already drained the Node stream, build it as +* `toWebRequest(req, req.body)` so the bytes come from the parsed body — +* either way the predicate still takes just the request.) The optional +* `parsedBody` is a perf escape hatch for a body you already hold parsed: +* pass it and the predicate classifies from the value directly, reading and +* cloning nothing. It is needed, not just faster, when the request's own +* body was already read — the internal clone is then impossible (cloning a +* used body throws a `TypeError`), so such a single-argument call rejects +* instead of guessing. +* +* This is the entry's own classification step exported as a predicate — it +* runs exactly the code `createMcpHandler` runs to make the routing decision, +* not a re-implementation — so a hand-wired composition that branches on it +* can never disagree with the entry. It is classification only: hand-wired +* compositions must validate Content-Type themselves (415 for POSTs whose +* media type is not `application/json`, via {@linkcode isJsonContentType}) +* before dispatching either leg — routing the legacy leg into the SDK +* transports gets their built-in check, but a custom modern leg has none. Use it to keep an existing legacy +* deployment (for example a sessionful streamable HTTP wiring) serving 2025 +* traffic next to a strict modern endpoint, now that the entry has no +* handler-valued `legacy` option: +* +* ```ts +* import { createMcpHandler, isLegacyRequest } from '@modelcontextprotocol/server'; +* +* const modern = createMcpHandler(factory, { legacy: 'reject' }); +* +* export default { +* async fetch(request: Request): Promise { +* if (await isLegacyRequest(request)) { +* // e.g. an existing sessionful WebStandardStreamableHTTPServerTransport wiring +* return myExistingLegacyHandler(request); +* } +* return modern.fetch(request); +* } +* }; +* ``` +* +* Semantics (identical to the entry's routing): +* +* - Returns `true` only for requests with no per-request `_meta` envelope +* claim: claim-less POSTs (including the `initialize` handshake and 2025-era +* notification POSTs without a modern protocol-version header), body-less +* GET/DELETE session operations, all-legacy JSON-RPC batch arrays, posted +* JSON-RPC responses, and POSTs whose body is empty or not valid JSON. +* - Returns `false` for everything the modern path answers, including its +* validation-ladder rejections: a request carrying the envelope claim (even +* one naming a revision the endpoint does not serve — the modern path +* answers it with the unsupported-protocol-version error), a malformed +* envelope behind a present claim (answered `-32602`), a request whose +* `MCP-Protocol-Version` header names a modern revision but that lacks the +* envelope (`-32602`), and header/body mismatches (`-32020`). Consumers +* routing on the predicate must send `false` traffic to the modern handler, +* never to a legacy handler — the modern path owns those error answers. +* - `server/discover` probes sent by negotiating clients always carry the +* envelope claim, so they are never legacy; a hand-built claim-less POST to +* a method named `server/discover` has no claim and classifies legacy, +* exactly as the entry itself routes it. +*/ +async function isLegacyRequest(request, parsedBody) { + const classified = await classifyEntryRequest(parsedBody === void 0 && request.method.toUpperCase() === "POST" ? request.clone() : request, parsedBody, false); + return classified.step === "no-json-body" || classified.step === "classified" && classified.outcome.kind === "legacy"; +} +/** +* Creates an HTTP handler that serves the 2026-07-28 protocol revision from a +* per-request server factory and, by default, falls back to old-school +* stateless serving for 2025-era traffic. Pass `legacy: 'reject'` for a +* modern-only strict endpoint. +* +* Mounting: `handler.fetch` is the web-standard face (Cloudflare Workers, +* Deno, Bun, Hono's `c.req.raw`); for Express/Fastify/plain `node:http`, wrap +* the handler once with `toNodeHandler(handler)` from +* `@modelcontextprotocol/node`. When mounting bare on a fetch-native runtime, +* put Origin/Host validation in front of the handler — the entry itself is +* deliberately validation-free: +* +* ```ts +* import { hostHeaderValidationResponse, originValidationResponse, localhostAllowedHostnames, localhostAllowedOrigins } from '@modelcontextprotocol/server'; +* +* export default { +* async fetch(request: Request): Promise { +* const rejected = +* hostHeaderValidationResponse(request, localhostAllowedHostnames()) ?? +* originValidationResponse(request, localhostAllowedOrigins()); +* return rejected ?? handler.fetch(request); +* } +* }; +* ``` +* +* Use ONE factory for both legs: the same tools/resources/prompts definition +* backs the modern path and the stateless legacy fallback, so the two eras can +* never drift apart. To keep an existing legacy deployment (for example a +* sessionful streamable HTTP wiring) serving 2025 traffic instead of the +* stateless fallback, route in user land with {@linkcode isLegacyRequest} in +* front of a strict handler — see that predicate's documentation for the +* pattern. Power users composing transport-neutral routing can also use the +* exported building blocks directly: {@linkcode classifyInboundRequest} for +* the era decision and `PerRequestHTTPServerTransport` for single-exchange +* serving — such compositions must reject POSTs whose Content-Type media type +* is not `application/json` (415) before parsing the body, using +* {@linkcode isJsonContentType}; neither building block performs this +* validation itself. +* +* The entry performs no token verification: `authInfo` given to `fetch` is +* passed through to handlers and the factory as-is and is never derived from +* request headers. +*/ +function createMcpHandler(factory, options = {}) { + const { legacy, onerror, responseMode } = options; + if (typeof legacy === "function") throw new TypeError("The 'legacy' option only accepts 'stateless' or 'reject', not a handler function. To serve 2025-era traffic with your own handler, route in user land with the exported isLegacyRequest(request) predicate in front of a strict (legacy: 'reject') handler."); + /** Modern per-request instances with an exchange still in flight (close() tears these down). */ + const inflight = /* @__PURE__ */ new Set(); + let closed = false; + const reportError = (error) => { + try { + onerror?.(error); + } catch {} + }; + const bus = options.bus ?? new InMemoryServerEventBus(reportError); + const notify = createServerNotifier(bus); + const listenRouter = createListenRouter({ + bus, + maxSubscriptions: options.maxSubscriptions ?? DEFAULT_MAX_SUBSCRIPTIONS, + keepAliveMs: options.keepAliveMs ?? DEFAULT_SSE_KEEP_ALIVE_MS, + onerror: reportError + }); + if (responseMode === "json") console.warn("responseMode: 'json' drops mid-call notifications. subscriptions/listen streams are always served over SSE regardless; other notifications emitted before a result are dropped."); + const legacyHandler = legacy === "reject" ? void 0 : createLegacyStatelessFallback(factory, reportError, options.keepAliveMs); + async function serveModern(route, request, authInfo) { + const claimedRevision = route.classification.revision; + if (claimedRevision === void 0 || !SUPPORTED_MODERN_PROTOCOL_VERSIONS.includes(claimedRevision)) { + const error = new UnsupportedProtocolVersionError({ + supported: [...SUPPORTED_MODERN_PROTOCOL_VERSIONS], + requested: claimedRevision ?? "unknown" + }); + reportError(error); + return jsonRpcErrorResponse(400, error.code, error.message, error.data, echoableRequestId(route.message)); + } + const stdHeaderRejection = validateStandardRequestHeaders({ + httpMethod: request.method, + mcpMethodHeader: request.headers.get("mcp-method") ?? void 0, + mcpNameHeader: request.headers.get("mcp-name") ?? void 0 + }, route); + if (stdHeaderRejection !== void 0) { + reportError(/* @__PURE__ */ new Error(`Rejected inbound request (${stdHeaderRejection.cell}): ${stdHeaderRejection.message}`)); + return rejectionResponse(stdHeaderRejection, echoableRequestId(route.message)); + } + const meta = route.messageKind === "request" ? requestMetaOf(route.message.params) : void 0; + const declaredClientCapabilities = meta?.[CLIENT_CAPABILITIES_META_KEY]; + if (route.messageKind === "request") { + const required = requiredClientCapabilitiesForRequest(route.message.method); + if (required !== void 0) { + const missing = missingClientCapabilities(required, declaredClientCapabilities); + if (missing !== void 0) { + const error = new MissingRequiredClientCapabilityError({ requiredCapabilities: missing }); + reportError(error); + return jsonRpcErrorResponse(httpStatusForErrorCode(error.code, "ladder"), error.code, error.message, error.data, route.message.id); + } + } + } + const product = await factory({ + era: "modern", + ...authInfo !== void 0 && { authInfo }, + requestInfo: request + }); + const server = product instanceof McpServer ? product.server : product; + if (route.messageKind === "request" && route.message.method === "subscriptions/listen") { + const capabilities = server.getCapabilities(); + const serverInfo = serverIdentityOf(server); + product.close().catch(reportError); + return listenRouter.serve(route.message, request.signal, capabilities, serverInfo); + } + if (route.messageKind === "request" && route.message.method === "tools/call" && product instanceof McpServer) { + const callParams = route.message.params; + const toolName = typeof callParams?.name === "string" ? callParams.name : void 0; + const inputSchema = toolName === void 0 ? void 0 : product.toolInputSchemaJson(toolName); + if (inputSchema !== void 0) { + const scan = scanXMcpHeaderDeclarations(inputSchema); + if (scan.valid && scan.declarations.length > 0) { + const rejection = validateMcpParamHeaders(scan.declarations, callParams?.arguments, request.headers); + if (rejection !== void 0) { + product.close().catch(reportError); + reportError(/* @__PURE__ */ new Error(`Rejected inbound request (${rejection.cell}): ${rejection.message}`)); + return rejectionResponse(rejection, route.message.id); + } + } + } + } + setNegotiatedProtocolVersion(server, claimedRevision); + installModernOnlyHandlers(server, SUPPORTED_MODERN_PROTOCOL_VERSIONS); + if (meta !== void 0) seedClientIdentityFromEnvelope(server, { + clientInfo: meta[CLIENT_INFO_META_KEY], + clientCapabilities: declaredClientCapabilities + }); + const previousOnClose = server.onclose; + inflight.add(server); + server.onclose = () => { + inflight.delete(server); + previousOnClose?.(); + }; + try { + const response = await invoke(product, route.message, { + classification: route.classification, + request, + ...authInfo !== void 0 && { authInfo }, + ...responseMode !== void 0 && { responseMode }, + ...options.keepAliveMs !== void 0 && { keepAliveMs: options.keepAliveMs } + }); + if (route.messageKind === "notification") queueMicrotask(() => void server.close().catch(() => {})); + return response; + } catch (error) { + if (error instanceof SdkError && error.code === SdkErrorCode.ConnectionClosed) return new Response(null, { status: 499 }); + await server.close().catch(() => {}); + inflight.delete(server); + reportError(toError(error)); + return internalServerErrorResponse(echoableRequestId(route.message)); + } + } + async function serveLegacyRoute(route, forwardRequest, authInfo, parsedBody) { + if (legacyHandler !== void 0) return legacyHandler(forwardRequest, { + ...authInfo !== void 0 && { authInfo }, + ...parsedBody !== void 0 && { parsedBody } + }); + const strict = modernOnlyStrictRejection(route, SUPPORTED_MODERN_PROTOCOL_VERSIONS); + if (strict === void 0) return new Response(null, { status: 202 }); + reportError(/* @__PURE__ */ new Error(`Rejected 2025-era request on a modern-only endpoint (${strict.cell}): ${strict.message}`)); + return rejectionResponse(strict, echoableRequestId(parsedBody)); + } + async function handle(request, requestOptions) { + const authInfo = requestOptions?.authInfo; + if (request.method.toUpperCase() === "POST" && !isJsonContentType(request.headers.get("content-type"))) { + reportError(/* @__PURE__ */ new Error("Unsupported Media Type: Content-Type must be application/json")); + return jsonRpcErrorResponse(415, -32e3, "Unsupported Media Type: Content-Type must be application/json"); + } + const classified = await classifyEntryRequest(request, requestOptions?.parsedBody); + if (classified.step === "unreadable-body") return jsonRpcErrorResponse(400, -32700, "Parse error: the request body could not be read"); + if (classified.step === "no-json-body") { + if (legacyHandler !== void 0) return legacyHandler(classified.forwardRequest, { ...authInfo !== void 0 && { authInfo } }); + return jsonRpcErrorResponse(400, -32700, "Parse error: the request body is not valid JSON"); + } + const { outcome, body, parsedBody, forwardRequest } = classified; + try { + switch (outcome.kind) { + case "reject": + reportError(/* @__PURE__ */ new Error(`Rejected inbound request (${outcome.cell}): ${outcome.message}`)); + return rejectionResponse(outcome, echoableRequestId(body)); + case "modern": return await serveModern(outcome, request, authInfo); + case "legacy": return await serveLegacyRoute(outcome, forwardRequest, authInfo, parsedBody); + } + } catch (error) { + reportError(toError(error)); + return internalServerErrorResponse(echoableRequestId(body)); + } + } + const fetchFace = async (request, requestOptions) => { + if (closed) throw new Error("This MCP handler has been closed"); + try { + return await handle(request, requestOptions); + } catch (error) { + reportError(toError(error)); + return internalServerErrorResponse(echoableRequestId(requestOptions?.parsedBody)); + } + }; + return { + fetch: fetchFace, + notify, + bus, + close: async () => { + closed = true; + listenRouter.closeAll(); + const closing = [...inflight].map((server) => server.close().catch(() => {})); + inflight.clear(); + await Promise.all(closing); + } + }; +} + +//#endregion +//#region src/server/middleware/bearerAuth.ts +function headerQuotedValue(value) { + return value.replaceAll(/[\\"]/g, String.raw`\$&`).replaceAll(/[^\u0020-\u007E]/g, " "); +} +function buildWwwAuthenticateHeader(errorCode, description, requiredScopes, resourceMetadataUrl) { + let header = `Bearer error="${headerQuotedValue(errorCode)}", error_description="${headerQuotedValue(description)}"`; + if (requiredScopes.length > 0) header += `, scope="${requiredScopes.join(" ")}"`; + if (resourceMetadataUrl) header += `, resource_metadata="${resourceMetadataUrl}"`; + return header; +} +/** +* Validate a raw `Authorization` header value as a Bearer token and return +* the verified {@link AuthInfo}. +* +* The runtime-neutral core of Bearer authentication: it parses the header, +* runs the verifier, enforces `requiredScopes`, and rejects tokens without an +* expiration or past it. On any failure it throws an {@link OAuthError} — +* pass that to {@link bearerAuthChallengeResponse} for the matching HTTP +* answer, or use {@link requireBearerAuth} to get both steps as one call. +* +* Framework adapters build on this: `requireBearerAuth` from +* `@modelcontextprotocol/express` feeds it `req.headers.authorization`. +*/ +async function verifyBearerToken(authorizationHeader, options) { + const { verifier, requiredScopes = [] } = options; + if (!authorizationHeader) throw new OAuthError(OAuthErrorCode.InvalidToken, "Missing Authorization header"); + const [type, token] = authorizationHeader.split(" "); + if (type?.toLowerCase() !== "bearer" || !token) throw new OAuthError(OAuthErrorCode.InvalidToken, "Invalid Authorization header format, expected 'Bearer TOKEN'"); + const authInfo = await verifier.verifyAccessToken(token); + if (requiredScopes.length > 0) { + if (!requiredScopes.every((scope) => authInfo.scopes.includes(scope))) throw new OAuthError(OAuthErrorCode.InsufficientScope, "Insufficient scope"); + } + if (typeof authInfo.expiresAt !== "number" || Number.isNaN(authInfo.expiresAt)) throw new OAuthError(OAuthErrorCode.InvalidToken, "Token has no expiration time"); + else if (authInfo.expiresAt < Date.now() / 1e3) throw new OAuthError(OAuthErrorCode.InvalidToken, "Token has expired"); + return authInfo; +} +/** +* Build the HTTP answer for a Bearer authentication failure. +* +* Maps an {@link OAuthError} to its status — `401` for `invalid_token` and +* `403` for `insufficient_scope` (both carrying the `WWW-Authenticate: Bearer …` +* challenge, with `resource_metadata` when configured so clients can discover +* the Authorization Server), `500` for `server_error`, `400` for anything +* else. A non-`OAuthError` value answers `500 server_error`. The body is the +* OAuth error JSON. +*/ +function bearerAuthChallengeResponse(error, options) { + const { requiredScopes = [], resourceMetadataUrl } = options ?? {}; + if (!(error instanceof OAuthError)) { + const serverError = new OAuthError(OAuthErrorCode.ServerError, "Internal Server Error"); + return Response.json(serverError.toResponseObject(), { status: 500 }); + } + switch (error.code) { + case OAuthErrorCode.InvalidToken: { + const challenge = buildWwwAuthenticateHeader(error.code, error.message, requiredScopes, resourceMetadataUrl); + return Response.json(error.toResponseObject(), { + status: 401, + headers: { "WWW-Authenticate": challenge } + }); + } + case OAuthErrorCode.InsufficientScope: { + const challenge = buildWwwAuthenticateHeader(error.code, error.message, requiredScopes, resourceMetadataUrl); + return Response.json(error.toResponseObject(), { + status: 403, + headers: { "WWW-Authenticate": challenge } + }); + } + case OAuthErrorCode.ServerError: return Response.json(error.toResponseObject(), { status: 500 }); + default: return Response.json(error.toResponseObject(), { status: 400 }); + } +} +/** +* Require a valid Bearer token on web-standard requests. +* +* The framework-free counterpart of `requireBearerAuth` from +* `@modelcontextprotocol/express`, for hosts whose HTTP surface is a +* `fetch(request)` handler — Cloudflare Workers, Deno, Bun, Hono. The +* returned gate resolves to the verified {@link AuthInfo}, or to the +* ready-to-return challenge `Response` when the request must be refused. +* +* @example +* ```ts source="./bearerAuth.examples.ts#requireBearerAuth_fetchGate" +* const gate = requireBearerAuth({ verifier, requiredScopes: ['mcp'] }); +* +* async function fetchHandler(request: Request): Promise { +* const auth: AuthInfo | Response = await gate(request); +* if (auth instanceof Response) return auth; +* return handler.fetch(request, { authInfo: auth }); +* } +* ``` +*/ +function requireBearerAuth(options) { + const { verifier, requiredScopes = [], resourceMetadataUrl } = options; + const resolved = { + verifier, + requiredScopes, + resourceMetadataUrl + }; + return async (request) => { + const [authorizationHeader] = (request.headers.get("authorization") ?? "").split(","); + try { + return await verifyBearerToken(authorizationHeader || void 0, resolved); + } catch (error) { + return bearerAuthChallengeResponse(error, resolved); + } + }; +} + +//#endregion +//#region src/server/middleware/hostHeaderValidation.ts +/** +* Parse and validate a `Host` header against an allowlist of hostnames (port-agnostic). +* +* - Input host header may include a port (e.g. `localhost:3000`) or IPv6 brackets (e.g. `[::1]:3000`). +* - Allowlist items should be hostnames only (no ports). For IPv6, include brackets (e.g. `[::1]`). +*/ +function validateHostHeader(hostHeader, allowedHostnames) { + if (!hostHeader) return { + ok: false, + errorCode: "missing_host", + message: "Missing Host header" + }; + let hostname; + try { + hostname = new URL(`http://${hostHeader}`).hostname; + } catch { + return { + ok: false, + errorCode: "invalid_host_header", + message: `Invalid Host header: ${hostHeader}`, + hostHeader + }; + } + if (!allowedHostnames.includes(hostname)) return { + ok: false, + errorCode: "invalid_host", + message: `Invalid Host: ${hostname}`, + hostHeader, + hostname + }; + return { + ok: true, + hostname + }; +} +/** +* Convenience allowlist for `localhost` DNS rebinding protection. +*/ +function localhostAllowedHostnames() { + return [ + "localhost", + "127.0.0.1", + "[::1]" + ]; +} +/** +* Web-standard `Request` helper for DNS rebinding protection. +* @example +* ```ts source="./hostHeaderValidation.examples.ts#hostHeaderValidationResponse_basicUsage" +* const result = validateHostHeader(req.headers.get('host'), ['localhost']); +* ``` +*/ +function hostHeaderValidationResponse(req, allowedHostnames) { + const result = validateHostHeader(req.headers.get("host"), allowedHostnames); + if (result.ok) return void 0; + return Response.json({ + jsonrpc: "2.0", + error: { + code: -32e3, + message: result.message + }, + id: null + }, { + status: 403, + headers: { "Content-Type": "application/json" } + }); +} + +//#endregion +//#region src/server/middleware/oauthMetadata.ts +function checkIssuerUrl(issuer, allowInsecure) { + if (issuer.protocol !== "https:" && issuer.hostname !== "localhost" && issuer.hostname !== "127.0.0.1" && !allowInsecure) throw new Error("Issuer URL must be HTTPS"); + if (issuer.hash) throw new Error(`Issuer URL must not have a fragment: ${issuer}`); + if (issuer.search) throw new Error(`Issuer URL must not have a query string: ${issuer}`); +} +/** +* Derive the RFC 9728 Protected Resource Metadata document from +* {@link AuthMetadataOptions}, validating the Authorization Server issuer URL +* (HTTPS required outside localhost) in the process. +* +* `oauthMetadataResponse` and the Express `mcpAuthMetadataRouter` both build +* on this; use it directly when serving the document through your own +* routing — or call it once at startup to fail fast on a misconfigured +* issuer before any request arrives. +*/ +function buildOAuthProtectedResourceMetadata(options) { + checkIssuerUrl(new URL(options.oauthMetadata.issuer), options.dangerouslyAllowInsecureIssuerUrl); + return { + resource: options.resourceServerUrl.href, + authorization_servers: [options.oauthMetadata.issuer], + scopes_supported: options.scopesSupported, + resource_name: options.resourceName, + resource_documentation: options.serviceDocumentationUrl?.href + }; +} +/** +* Builds the RFC 9728 Protected Resource Metadata URL for a given MCP server +* URL by inserting `/.well-known/oauth-protected-resource` ahead of the path. +* +* @example +* ```ts +* getOAuthProtectedResourceMetadataUrl(new URL('https://api.example.com/mcp')) +* // → 'https://api.example.com/.well-known/oauth-protected-resource/mcp' +* ``` +*/ +function getOAuthProtectedResourceMetadataUrl(serverUrl) { + return new URL(protectedResourceMetadataPath(serverUrl), serverUrl).href; +} +/** The RFC 9728 path-aware well-known path for a resource URL. */ +function protectedResourceMetadataPath(resourceServerUrl) { + const rsPath = stripTrailingSlash(resourceServerUrl.pathname); + return `/.well-known/oauth-protected-resource${rsPath === "/" ? "" : rsPath}`; +} +function stripTrailingSlash(path) { + return path.length > 1 && path.endsWith("/") ? path.slice(0, -1) : path; +} +const ALLOWED_METHODS = "GET, HEAD, OPTIONS"; +function metadataDocumentResponse(request, metadata) { + if (request.method === "OPTIONS") { + const requestedHeaders = request.headers.get("access-control-request-headers"); + return new Response(null, { + status: 204, + headers: { + "Access-Control-Allow-Origin": "*", + "Access-Control-Allow-Methods": ALLOWED_METHODS, + ...requestedHeaders === null ? {} : { + "Access-Control-Allow-Headers": requestedHeaders, + Vary: "Access-Control-Request-Headers" + } + } + }); + } + if (request.method !== "GET" && request.method !== "HEAD") { + const error = new OAuthError(OAuthErrorCode.MethodNotAllowed, `The method ${request.method} is not allowed for this endpoint`); + return Response.json(error.toResponseObject(), { + status: 405, + headers: { + Allow: ALLOWED_METHODS, + "Access-Control-Allow-Origin": "*" + } + }); + } + const response = Response.json(metadata, { headers: { "Access-Control-Allow-Origin": "*" } }); + return request.method === "HEAD" ? new Response(null, { + status: response.status, + headers: response.headers + }) : response; +} +/** +* Serve the two OAuth discovery documents an MCP server acting as a Resource +* Server exposes, from a web-standard `fetch(request)` handler: +* +* - `/.well-known/oauth-protected-resource[/]` — RFC 9728 Protected +* Resource Metadata, derived from the supplied options (path-aware: the +* resource URL's path is reflected in the route). +* - `/.well-known/oauth-authorization-server` — RFC 8414 Authorization +* Server Metadata, passed through verbatim. +* +* Returns the matched document `Response` (JSON with permissive CORS, `405` +* with an `Allow` header for non-GET methods, `204` for CORS preflight), or +* `undefined` when the request path is neither well-known route — fall +* through to your own routing. The framework-free counterpart of +* `mcpAuthMetadataRouter` from `@modelcontextprotocol/express`; pair it with +* `requireBearerAuth` and `getOAuthProtectedResourceMetadataUrl` so +* unauthenticated clients can discover the AS from the `401` challenge. +* +* @example +* ```ts source="./oauthMetadata.examples.ts#oauthMetadataResponse_fetchHandler" +* async function fetchHandler(request: Request): Promise { +* return oauthMetadataResponse(request, options) ?? serveMcp(request); +* } +* ``` +*/ +function oauthMetadataResponse(request, options) { + const requestPath = stripTrailingSlash(new URL(request.url).pathname); + if (requestPath === protectedResourceMetadataPath(options.resourceServerUrl)) return metadataDocumentResponse(request, buildOAuthProtectedResourceMetadata(options)); + if (requestPath === "/.well-known/oauth-authorization-server") { + buildOAuthProtectedResourceMetadata(options); + return metadataDocumentResponse(request, options.oauthMetadata); + } +} + +//#endregion +//#region src/server/middleware/originValidation.ts +/** +* Validate an `Origin` header against an allowlist of hostnames (port-agnostic). +* +* - A missing/empty `Origin` header passes: non-browser clients do not send one, +* and only browser-originated requests carry the header this check defends against. +* - Allowlist items are hostnames only (no scheme, no port), the same convention as +* `validateHostHeader`. For IPv6, include brackets (e.g. `[::1]`). +* - Any present value that cannot be parsed as an origin URL — including the literal +* `null` origin browsers send for opaque contexts — is rejected (deny on failure). +*/ +function validateOriginHeader(originHeader, allowedOriginHostnames) { + if (originHeader === null || originHeader === void 0 || originHeader === "") return { ok: true }; + let hostname; + try { + hostname = new URL(originHeader).hostname; + } catch { + return { + ok: false, + errorCode: "invalid_origin_header", + message: `Invalid Origin header: ${originHeader}`, + originHeader + }; + } + if (hostname === "") return { + ok: false, + errorCode: "invalid_origin_header", + message: `Invalid Origin header: ${originHeader}`, + originHeader + }; + if (!allowedOriginHostnames.includes(hostname)) return { + ok: false, + errorCode: "invalid_origin", + message: `Invalid Origin: ${hostname}`, + originHeader, + hostname + }; + return { + ok: true, + origin: originHeader, + hostname + }; +} +/** +* Convenience allowlist of localhost-class origin hostnames, mirroring +* `localhostAllowedHostnames`. +*/ +function localhostAllowedOrigins() { + return [ + "localhost", + "127.0.0.1", + "[::1]" + ]; +} +/** +* Web-standard `Request` helper for Origin validation: returns a `403` JSON-RPC +* error response when the request's `Origin` header is not allowed, and +* `undefined` when the request may proceed. +* +* ```ts +* const rejected = originValidationResponse(request, localhostAllowedOrigins()); +* if (rejected) return rejected; +* ``` +*/ +function originValidationResponse(req, allowedOriginHostnames) { + const result = validateOriginHeader(req.headers.get("origin"), allowedOriginHostnames); + if (result.ok) return void 0; + return Response.json({ + jsonrpc: "2.0", + error: { + code: -32e3, + message: result.message + }, + id: null + }, { + status: 403, + headers: { "Content-Type": "application/json" } + }); +} + +//#endregion +//#region src/server/requestStateCodec.ts +const PREFIX = "v1."; +function bytesToBase64Url(bytes) { + let bin = ""; + for (const b of bytes) bin += String.fromCodePoint(b); + return btoa(bin).replaceAll("+", "-").replaceAll("/", "_").replace(/=+$/, ""); +} +function constantTimeTagEqual(a, b) { + if (a.length !== b.length) return false; + let r = 0; + for (let i = 0; i < a.length; i++) r |= a.codePointAt(i) ^ b.codePointAt(i); + return r === 0; +} +function base64UrlToBytes(s) { + const b64 = s.replaceAll("-", "+").replaceAll("_", "/"); + const bin = atob(b64); + const bytes = new Uint8Array(bin.length); + for (let i = 0; i < bin.length; i++) bytes[i] = bin.codePointAt(i); + return bytes; +} +/** +* Create an opt-in HMAC-SHA256 codec for the multi-round-trip `requestState` +* (protocol revision 2026-07-28). +* +* `requestState` round-trips through the client and is attacker-controlled +* input on re-entry. The SDK applies no protection of its own; this helper is +* the convenience implementation of the spec's integrity MUST so authors don't +* hand-roll HMAC. Wire shape: +* +* "v1." b64url({"p":,"exp":,"b":?}) "." b64url(mac) +* +* where `bindTag` is `b64url(HMAC(key, "mcp.requestState.bind:" + bind(ctx))[:16])` +* — the binding value is never embedded raw. +* +* The codec is **signed, not encrypted**: the body is integrity-protected but +* the client can base64url-decode it and read the payload (`p`) in clear. Do +* not put secrets in the payload; use an AEAD construction if confidentiality +* is required. The handler reads its payload back via the typed +* `ctx.mcpReq.requestState()` accessor — the seam has already run `verify` +* (integrity proven, payload decoded) by the time the handler is entered. +* +* Verification is fail-closed and constant-time (WebCrypto `subtle.verify` for +* the body MAC; a fixed-length XOR-accumulator compare for the bind tag). +* See `examples/mrtr/server.ts` for a worked end-to-end example. +* +* Design comparison (mcp.d `secureRequestState`, the peer SDK's reference +* implementation): mcp.d additionally offers an AES-256-GCM encrypted mode and +* derives independent cipher / bind-HMAC sub-keys from the operator secret via +* HKDF-SHA256, with an auto-generated per-process ephemeral key when none is +* supplied. This codec deliberately ships only the signed mode and a single +* keyed HMAC (domain-separated by input prefix) — HKDF sub-key derivation and +* an encrypted mode are intentionally out of scope for the initial release. +*/ +function createRequestStateCodec(options) { + const subtle = globalThis.crypto?.subtle; + if (subtle === void 0) throw new TypeError("createRequestStateCodec requires the Web Crypto API (globalThis.crypto.subtle); see https://ts.sdk.modelcontextprotocol.io/v2/troubleshooting for the Node.js polyfill instructions"); + const keyBytes = typeof options.key === "string" ? new TextEncoder().encode(options.key) : Uint8Array.from(options.key); + if (keyBytes.byteLength < 32) throw new RangeError(`createRequestStateCodec: key must be at least 32 bytes (got ${keyBytes.byteLength})`); + const ttlSeconds = options.ttlSeconds ?? 600; + if (!Number.isFinite(ttlSeconds)) throw new RangeError("createRequestStateCodec: ttlSeconds must be a finite number"); + const bind = options.bind; + let cryptoKey; + const importedKey = () => cryptoKey ??= subtle.importKey("raw", keyBytes, { + name: "HMAC", + hash: "SHA-256" + }, false, ["sign", "verify"]); + const utf8 = new TextEncoder(); + const BIND_LABEL = "mcp.requestState.bind:"; + const bindTag = async (value) => { + return bytesToBase64Url(new Uint8Array(await subtle.sign("HMAC", await importedKey(), utf8.encode(BIND_LABEL + value))).slice(0, 16)); + }; + return { + async mint(payload, ctx) { + const envelope = { + p: payload, + exp: Math.floor(Date.now() / 1e3) + ttlSeconds + }; + if (bind !== void 0) { + if (ctx === void 0) throw new TypeError("createRequestStateCodec: mint() requires ctx when a bind callback is configured"); + envelope.b = await bindTag(bind(ctx)); + } + const body = bytesToBase64Url(utf8.encode(JSON.stringify(envelope))); + return `${PREFIX}${body}.${bytesToBase64Url(new Uint8Array(await subtle.sign("HMAC", await importedKey(), utf8.encode(PREFIX + body))))}`; + }, + async verify(state, ctx) { + const dot = state.lastIndexOf("."); + if (!state.startsWith(PREFIX) || dot <= 3) throw new Error("malformed"); + const body = state.slice(3, dot); + let macBytes; + try { + macBytes = base64UrlToBytes(state.slice(dot + 1)); + } catch { + throw new Error("malformed"); + } + if (!await subtle.verify("HMAC", await importedKey(), macBytes, utf8.encode(PREFIX + body))) throw new Error("mac"); + let envelope; + try { + envelope = JSON.parse(new TextDecoder("utf-8", { fatal: true }).decode(base64UrlToBytes(body))); + } catch { + throw new Error("malformed"); + } + if (typeof envelope.exp !== "number" || envelope.exp < Math.floor(Date.now() / 1e3)) throw new Error("expired"); + if (bind !== void 0) { + const expected = await bindTag(bind(ctx)); + if (envelope.b === void 0 || !constantTimeTagEqual(envelope.b, expected)) throw new Error("bind"); + } else if (envelope.b !== void 0) throw new Error("bind"); + return envelope.p; + } + }; +} + +//#endregion +//#region src/fromJsonSchema.ts +let _defaultValidator; +function dist_fromJsonSchema(schema, validator) { + return fromJsonSchema$1(schema, validator ?? (_defaultValidator ??= new DefaultJsonSchemaValidator())); +} + +//#endregion + +//# sourceMappingURL=index.mjs.map +const mcpApps = Object.freeze([]); + +/* export default */ const mcp_status_073c1634_0 = (mcpApps); + +// Generated by agent-bundle. Do not edit. +const meta_name = "mcp-app-example"; +const packageName = "@agent-bundle-example/mcp-app"; +const packageVersion = undefined; +const meta_version = "1.0.0"; +const meta_meta = Object.freeze({ + name: meta_name, + packageName: packageName, + packageVersion: packageVersion, + version: meta_version +}); +/* export default */ const _agent_bundle_virtual_meta = ((/* unused pure expression or super */ null && (meta_meta))); + +const healthyCompilerStatus = Object.freeze({ + checks: Object.freeze([ + Object.freeze({ + label: 'Availability', + status: 'passing' + }), + Object.freeze({ + label: 'Build queue', + status: 'passing' + }) + ]), + service: 'compiler', + status: 'healthy', + summary: 'Compiler service is ready for release.' +}); +const isRecord = (value)=>value !== null && typeof value === 'object' && !Array.isArray(value); +const isHealthyCompilerFixture = (value)=>{ + if (!isRecord(value) || value.service !== healthyCompilerStatus.service || value.status !== healthyCompilerStatus.status || value.summary !== healthyCompilerStatus.summary || !Array.isArray(value.checks) || value.checks.length !== healthyCompilerStatus.checks.length) { + return false; + } + return healthyCompilerStatus.checks.every((expected, index)=>{ + const received = value.checks[index]; + return isRecord(received) && received.label === expected.label && received.status === expected.status; + }); +}; + + + + + + +const app = mcp_status_073c1634_0["0"]; +if (app === undefined) throw new Error('Expected the status MCP App.'); +const serviceCatalog = Object.freeze({ + compiler: healthyCompilerStatus, + 'payments-api': Object.freeze({ + checks: Object.freeze([ + Object.freeze({ + label: 'Availability', + status: 'passing' + }), + Object.freeze({ + label: 'P95 latency', + status: 'failing' + }) + ]), + service: 'payments-api', + status: 'degraded', + summary: 'Payment latency is above the release threshold.' + }) +}); +const createStatusServer = ()=>{ + // The compiler stamps this project's identity into `agent-bundle/meta`, so + // the wire identity cannot drift from the config or package.json. + const server = new mcp_DXXb3Vv3_McpServer({ + name: meta_name, + version: (/* inlined export .version */"1.0.0") + }); + server.registerResource(app.name, app.resourceUri, { + _meta: { + ui: { + resourceUri: app.resourceUri + } + }, + mimeType: app.mimeType + }, async (uri)=>({ + contents: [ + { + mimeType: app.mimeType, + text: app.html, + uri: uri.href + } + ] + })); + server.registerTool('show-status', { + _meta: { + ui: { + resourceUri: app.resourceUri + } + }, + description: 'Show the health of one example service.', + inputSchema: schemas_object({ + service: schemas_enum([ + 'compiler', + 'payments-api' + ]) + }) + }, async ({ service })=>{ + const result = serviceCatalog[service]; + return { + _meta: { + ui: { + resourceUri: app.resourceUri + } + }, + content: [ + { + text: result.summary, + type: 'text' + } + ], + structuredContent: result + }; + }); + return server; +}; +/** + * Default-exported server factory: `agent-bundle build` detects it and wraps + * this entry in the framework stdio lifecycle shell (console-to-stderr guard, + * SIGINT/SIGTERM handling, stdin-EOF exit, bounded shutdown, heartbeat). + */ /* export default */ const mcp_status = (createStatusServer); + + + + + +//#region src/server/stdio.ts +/** +* Server transport for stdio: this communicates with an MCP client by reading from the current process' `stdin` and writing to `stdout`. +* +* This transport is only available in Node.js environments. +* +* @example +* ```ts source="./stdio.examples.ts#StdioServerTransport_basicUsage" +* const server = new McpServer({ name: 'my-server', version: '1.0.0' }); +* const transport = new StdioServerTransport(); +* await server.connect(transport); +* ``` +*/ +var stdio_StdioServerTransport = class { + _readBuffer; + _started = false; + _closed = false; + constructor(_stdin = node_process.stdin, _stdout = node_process.stdout, options) { + this._stdin = _stdin; + this._stdout = _stdout; + this._readBuffer = new ReadBuffer({ maxBufferSize: options?.maxBufferSize }); + } + onclose; + onerror; + onmessage; + _ondata = (chunk) => { + try { + this._readBuffer.append(chunk); + this.processReadBuffer(); + } catch (error) { + this.onerror?.(error); + this.close().catch(() => {}); + } + }; + _onerror = (error) => { + this.onerror?.(error); + }; + _onstdouterror = (error) => { + this.onerror?.(error); + this.close().catch(() => {}); + }; + /** + * Starts listening for messages on `stdin`. + */ + async start() { + if (this._started) throw new Error("StdioServerTransport already started! If using Server class, note that connect() calls start() automatically."); + this._started = true; + this._stdin.on("data", this._ondata); + this._stdin.on("error", this._onerror); + this._stdout.on("error", this._onstdouterror); + } + processReadBuffer() { + while (true) try { + const message = this._readBuffer.readMessage(); + if (message === null) break; + this.onmessage?.(message); + } catch (error) { + this.onerror?.(error); + } + } + async close() { + if (this._closed) return; + this._closed = true; + this._stdin.off("data", this._ondata); + this._stdin.off("error", this._onerror); + this._stdout.off("error", this._onstdouterror); + if (this._stdin.listenerCount("data") === 0) this._stdin.pause(); + this._readBuffer.clear(); + this.onclose?.(); + } + send(message) { + if (this._closed) return Promise.reject(/* @__PURE__ */ new Error("StdioServerTransport is closed")); + return new Promise((resolve, reject) => { + const json = serializeMessage(message); + let settled = false; + const onError = (error) => { + if (settled) return; + settled = true; + this._stdout.off("error", onError); + this._stdout.off("drain", onDrain); + reject(error); + }; + const onDrain = () => { + if (settled) return; + settled = true; + this._stdout.off("error", onError); + this._stdout.off("drain", onDrain); + resolve(); + }; + this._stdout.once("error", onError); + if (this._stdout.write(json)) { + if (settled) return; + settled = true; + this._stdout.off("error", onError); + resolve(); + } else if (!settled) this._stdout.once("drain", onDrain); + }); + } +}; + +//#endregion +//#region src/server/serveStdio.ts +/** +* How long the probe-discard path waits for the probe instance to answer the +* requests it was delivered before closing it. The wait normally settles as +* soon as the DiscoverResult is handed to the wire (or immediately, when a +* delivered cancellation already settled the probe); the bound is a backstop +* so no edge can ever hold the connection's inbound pump indefinitely behind +* the discard. +*/ +const DISCARD_ANSWER_TIMEOUT_MS = 3e3; +/** +* The transport a pinned instance is connected to: a thin channel that writes +* through to the entry-owned wire transport and receives the messages the +* entry forwards. The wire transport itself is never handed to an instance — +* that is what lets the entry discard an optimistic probe instance (close the +* channel) without tearing down the connection. +*/ +var StdioConnectionChannel = class { + onclose; + onerror; + onmessage; + _closed = false; + /** Request ids the entry delivered to the instance that the instance has not yet answered. */ + _pendingRequests = /* @__PURE__ */ new Set(); + _drainWaiters = []; + constructor(_wire, _onInstanceClose, _outboundIntercept) { + this._wire = _wire; + this._onInstanceClose = _onInstanceClose; + this._outboundIntercept = _outboundIntercept; + } + async start() {} + async send(message, options) { + if (isJSONRPCResultResponse(message) || isJSONRPCErrorResponse(message)) { + const { id } = message; + if (id !== void 0) this._settle(id); + } + if (this._closed) return; + if (this._outboundIntercept?.(message) === "handled") return; + return this._wire.send(message, options); + } + setProtocolVersion = (version) => { + this._wire.setProtocolVersion?.(version); + }; + /** Forwards one inbound message to the connected instance. */ + deliver(message, extra) { + if (this._closed) return; + if (isJSONRPCRequest(message)) this._pendingRequests.add(message.id); + else if (isJSONRPCNotification(message) && message.method === "notifications/cancelled") { + const cancelledId = message.params?.requestId; + if (cancelledId !== void 0) this._settle(cancelledId); + } + this.onmessage?.(message, extra); + } + /** + * Resolves once every request delivered to the instance has been answered + * through {@linkcode send}, settled by a delivered cancellation, or the + * channel has been closed and nothing further can be answered. The wait is + * bounded by `timeoutMs` as a backstop so no edge can hold the caller + * indefinitely; resolves `false` only when the bound elapsed with requests + * still unanswered. Used by the probe-discard path so a probe request the + * entry accepted is never silently dropped. + */ + async whenRequestsAnswered(timeoutMs) { + if (this._closed || this._pendingRequests.size === 0) return true; + return await new Promise((resolve) => { + const waiter = () => { + clearTimeout(timer); + resolve(true); + }; + const timer = setTimeout(() => { + this._drainWaiters = this._drainWaiters.filter((pending) => pending !== waiter); + resolve(false); + }, timeoutMs); + this._drainWaiters.push(waiter); + }); + } + async close() { + if (this._closed) return; + this._closed = true; + this._pendingRequests.clear(); + this._releaseDrainWaiters(); + try { + this._onInstanceClose(); + } finally { + this.onclose?.(); + } + } + _settle(id) { + this._pendingRequests.delete(id); + if (this._pendingRequests.size === 0) this._releaseDrainWaiters(); + } + _releaseDrainWaiters() { + const waiters = this._drainWaiters; + this._drainWaiters = []; + for (const waiter of waiters) waiter(); + } +}; +/** +* Classifies one message of the opening exchange with the same body-primary +* rules the HTTP entry applies per request: `initialize` is the legacy +* handshake unless it carries a valid modern envelope claim; a present claim +* is validated (never silently ignored); a claim-less message is 2025-era +* traffic. There is no header layer on stdio, so the body is the only signal. +*/ +function classifyOpeningMessage(message) { + const params = message.params; + if (message.method === "initialize" && !carriesValidModernEnvelopeClaim(params)) { + const requestedVersion = params !== null && typeof params === "object" && typeof params.protocolVersion === "string" ? params.protocolVersion : void 0; + return { + kind: "legacy", + reason: "initialize", + ...requestedVersion !== void 0 && { requestedVersion } + }; + } + if (!hasEnvelopeClaim(params)) return { + kind: "legacy", + reason: "no-claim" + }; + const meta = requestMetaOf(params); + const firstIssue = (meta === void 0 ? [] : validateEnvelopeMeta(meta))[0]; + if (firstIssue !== void 0) return { + kind: "invalid-envelope", + issue: firstIssue + }; + const claimedVersion = envelopeClaimVersion(params); + if (claimedVersion === void 0 || !SUPPORTED_MODERN_PROTOCOL_VERSIONS.includes(claimedVersion)) return { + kind: "unsupported-revision", + requested: claimedVersion ?? "unknown" + }; + return { + kind: "modern", + revision: claimedVersion, + classification: { + era: "modern", + revision: claimedVersion + } + }; +} +/** +* Serves MCP over stdio from a server factory, owning the era decision for +* the connection: the opening exchange selects the era, ONE instance from the +* factory is pinned for the connection lifetime, and everything after passes +* straight through to it. See the module documentation for the opening rules. +* +* ```ts +* import { serveStdio } from '@modelcontextprotocol/server/stdio'; +* +* serveStdio(() => { +* const server = new McpServer({ name: 'my-server', version: '1.0.0' }, { capabilities: { tools: {} } }); +* // register tools/resources/prompts once — the same factory serves both eras +* return server; +* }); +* ``` +*/ +function serveStdio(factory, options = {}) { + const legacyMode = options.legacy ?? "serve"; + const wire = options.transport ?? new stdio_StdioServerTransport(); + let state = { phase: "opening" }; + /** Channel currently being discarded (its close must not tear the connection down). */ + let discarding; + let closing = false; + /** + * Whether the connection has been torn down (`handle.close()` or the wire + * closing). The opening arms re-check this after every await: a close can + * race factory construction, and the continuation must neither resurrect + * the connection state nor keep a late-resolved instance around. + */ + const isTornDown = () => closing || state.phase === "closed"; + const reportError = (error) => { + try { + options.onerror?.(error); + } catch {} + }; + const writeErrorResponse = (id, code, message, data) => wire.send({ + jsonrpc: "2.0", + id, + error: { + code, + message, + ...data !== void 0 && { data } + } + }).catch((error) => reportError(stdio_toError(error))); + /** + * Entry-handled `subscriptions/listen` for this connection: holds the + * active subscriptions, serves inbound listen / cancelled-of-listen + * before the pinned instance is consulted, and rewrites the instance's + * outbound change notifications onto the active subscriptions. Only + * consulted on a modern-pinned connection — on a legacy connection + * change notifications pass straight through (the 2025 unsolicited + * delivery model is unchanged). + */ + const listenRouter = new StdioListenRouter(options.maxSubscriptions ?? DEFAULT_MAX_SUBSCRIPTIONS); + /** Outbound intercept installed on a modern instance's channel. */ + const modernOutboundIntercept = (message) => { + if (!isJSONRPCNotification(message)) return void 0; + const routed = listenRouter.routeOutbound(message); + if (routed === "passthrough") return void 0; + for (const stamped of routed) wire.send({ + jsonrpc: "2.0", + ...stamped + }).catch((error) => reportError(stdio_toError(error))); + return "handled"; + }; + /** + * Entry-handled inbound listen routing for a modern-pinned connection. + * Returns `true` when the message was served at the entry and must NOT + * be delivered to the pinned instance. + */ + const tryServeListen = async (message) => { + if (isJSONRPCRequest(message) && message.method === "subscriptions/listen") { + const meta = requestMetaOf(message.params); + const issue = hasEnvelopeClaim(message.params) ? (meta === void 0 ? [] : validateEnvelopeMeta(meta))[0] : { + key: "_meta", + problem: "the per-request envelope is required on protocol revision 2026-07-28" + }; + const claimedVersion = envelopeClaimVersion(message.params); + let reply; + if (issue !== void 0) reply = { + jsonrpc: "2.0", + id: message.id, + error: { + code: -32602, + message: `Invalid _meta envelope: ${issue.key}: ${issue.problem}` + } + }; + else if (claimedVersion === void 0 || !SUPPORTED_MODERN_PROTOCOL_VERSIONS.includes(claimedVersion)) { + const error = new UnsupportedProtocolVersionError({ + supported: [...SUPPORTED_MODERN_PROTOCOL_VERSIONS], + requested: claimedVersion ?? "unknown" + }); + reply = { + jsonrpc: "2.0", + id: message.id, + error: { + code: error.code, + message: error.message, + data: error.data + } + }; + } else reply = listenRouter.serve(message); + await wire.send("error" in reply ? reply : { + jsonrpc: "2.0", + method: reply.method, + params: reply.params + }).catch((error) => reportError(stdio_toError(error))); + return true; + } + if (isJSONRPCNotification(message) && message.method === "notifications/cancelled") { + const cancelledId = message.params?.requestId; + if (cancelledId !== void 0 && listenRouter.cancel(cancelledId)) return true; + } + return false; + }; + /** Answers a 2025-era request the entry will not serve (the modern-only rejection cells). */ + const answerLegacyRejection = (request, reason, requestedVersion) => { + const rejection = modernOnlyStrictRejection({ + kind: "legacy", + reason, + ...requestedVersion !== void 0 && { requestedVersion } + }, SUPPORTED_MODERN_PROTOCOL_VERSIONS); + if (rejection === void 0) return Promise.resolve(); + reportError(/* @__PURE__ */ new Error(`Rejected 2025-era request on a modern-only stdio connection (${rejection.cell}): ${rejection.message}`)); + return writeErrorResponse(request.id, rejection.code, rejection.message, rejection.data); + }; + const onInstanceClosed = (channel) => { + if (closing || channel === discarding) return; + closeAll(); + }; + const connectInstance = async (era, revision) => { + const product = await factory({ era }); + const server = product instanceof McpServer ? product.server : product; + if (era === "modern") { + setNegotiatedProtocolVersion(server, revision); + installModernOnlyHandlers(server, SUPPORTED_MODERN_PROTOCOL_VERSIONS); + listenRouter.setServerCapabilities(server.getCapabilities(), serverIdentityOf(server)); + } + const channel = new StdioConnectionChannel(wire, () => onInstanceClosed(channel), era === "modern" ? modernOutboundIntercept : void 0); + await product.connect(channel); + return { + product, + channel + }; + }; + /** Closes an instance whose factory resolved only after the connection was torn down. */ + const disposeLateInstance = (instance) => instance.product.close().catch((error) => reportError(stdio_toError(error))); + const discardProbeInstance = async (instance) => { + discarding = instance.channel; + try { + if (!await instance.channel.whenRequestsAnswered(DISCARD_ANSWER_TIMEOUT_MS)) reportError(/* @__PURE__ */ new Error(`Discarded the probe instance with requests still unanswered after ${DISCARD_ANSWER_TIMEOUT_MS}ms; continuing with the fallback`)); + await instance.product.close(); + } catch (error) { + reportError(stdio_toError(error)); + } finally { + discarding = void 0; + } + }; + const processMessage = async (message) => { + if (state.phase === "closed") return; + if (state.phase === "pinned") { + if (state.era === "modern" && isJSONRPCRequest(message) && message.method === "initialize" && !carriesValidModernEnvelopeClaim(message.params)) { + await answerLegacyRejection(message, "initialize", message.params !== null && typeof message.params === "object" && typeof message.params.protocolVersion === "string" ? message.params.protocolVersion : void 0); + return; + } + if (state.era === "modern" && await tryServeListen(message)) return; + state.instance.channel.deliver(message); + return; + } + if (!isJSONRPCRequest(message) && !isJSONRPCNotification(message)) { + reportError(/* @__PURE__ */ new Error("Discarded a JSON-RPC response received before the connection negotiated an era")); + return; + } + const opening = classifyOpeningMessage(message); + switch (opening.kind) { + case "invalid-envelope": { + const detail = `Invalid _meta envelope for protocol revision 2026-07-28: ${opening.issue.key}: ${opening.issue.problem}`; + if (isJSONRPCRequest(message)) await writeErrorResponse(message.id, ProtocolErrorCode.InvalidParams, detail, { envelope: opening.issue }); + else reportError(/* @__PURE__ */ new Error(`Discarded a notification with a malformed envelope: ${detail}`)); + return; + } + case "unsupported-revision": + if (isJSONRPCRequest(message)) { + const error = new UnsupportedProtocolVersionError({ + supported: [...SUPPORTED_MODERN_PROTOCOL_VERSIONS], + requested: opening.requested + }); + reportError(error); + await writeErrorResponse(message.id, error.code, error.message, error.data); + } else reportError(/* @__PURE__ */ new Error(`Discarded a notification claiming unsupported protocol revision ${opening.requested}`)); + return; + case "modern": + if (isJSONRPCRequest(message) && message.method === "server/discover") { + if (state.phase === "probe") { + state.instance.channel.deliver(message, { classification: opening.classification }); + return; + } + const instance = await connectInstance("modern", opening.revision); + if (isTornDown()) { + await disposeLateInstance(instance); + return; + } + state = { + phase: "probe", + instance + }; + instance.channel.deliver(message, { classification: opening.classification }); + return; + } + if (state.phase === "probe") { + if (isJSONRPCNotification(message)) { + state.instance.channel.deliver(message, { classification: opening.classification }); + return; + } + state = { + phase: "pinned", + era: "modern", + instance: state.instance + }; + } else { + const instance = await connectInstance("modern", opening.revision); + if (isTornDown()) { + await disposeLateInstance(instance); + return; + } + state = { + phase: "pinned", + era: "modern", + instance + }; + } + if (await tryServeListen(message)) return; + state.instance.channel.deliver(message, { classification: opening.classification }); + return; + case "legacy": { + if (legacyMode === "reject") { + if (isJSONRPCRequest(message)) await answerLegacyRejection(message, opening.reason, opening.requestedVersion); + return; + } + if (state.phase === "probe") { + await discardProbeInstance(state.instance); + if (isTornDown()) return; + state = { phase: "opening" }; + } + const instance = await connectInstance("legacy"); + if (isTornDown()) { + await disposeLateInstance(instance); + return; + } + state = { + phase: "pinned", + era: "legacy", + instance + }; + state.instance.channel.deliver(message); + return; + } + } + }; + const queue = []; + let pumping = false; + const pump = async () => { + if (pumping) return; + pumping = true; + try { + while (queue.length > 0) { + const message = queue.shift(); + try { + await processMessage(message); + } catch (error) { + if (isJSONRPCRequest(message)) await writeErrorResponse(message.id, ProtocolErrorCode.InternalError, "Internal server error"); + reportError(stdio_toError(error)); + } + } + } finally { + pumping = false; + } + }; + const closeAll = async () => { + if (closing || state.phase === "closed") return; + closing = true; + const current = state; + state = { phase: "closed" }; + for (const result of listenRouter.teardownAll()) await wire.send(result).catch((error) => reportError(stdio_toError(error))); + if (current.phase === "probe" || current.phase === "pinned") await current.instance.product.close().catch((error) => reportError(stdio_toError(error))); + await wire.close().catch((error) => reportError(stdio_toError(error))); + }; + wire.onmessage = (message) => { + queue.push(message); + pump(); + }; + wire.onerror = (error) => { + reportError(error); + if (state.phase === "probe" || state.phase === "pinned") state.instance.channel.onerror?.(error); + }; + wire.onclose = () => { + if (closing || state.phase === "closed") return; + closing = true; + const current = state; + state = { phase: "closed" }; + if (current.phase === "probe" || current.phase === "pinned") current.instance.product.close().catch((error) => reportError(stdio_toError(error))); + }; + const started = wire.start().catch((error) => { + reportError(stdio_toError(error)); + throw error; + }); + started.catch(() => {}); + return { close: async () => { + await started.catch(() => {}); + await closeAll(); + } }; +} +function stdio_toError(value) { + return value instanceof Error ? value : new Error(String(value)); +} + +//#endregion + +//# sourceMappingURL=stdio.mjs.map +const defaultHeartbeatIntervalMs = 300000; +const defaultActivityThrottleMs = 60000; +const defaultShutdownTimeoutMs = 5000; +const defaultHeartbeatName = 'agent-bundle'; +const redirectConsoleToStderr = ()=>{ + const originalStdoutWrite = process.stdout.write.bind(process.stdout); + const stderrConsole = new console.Console({ + stderr: process.stderr, + stdout: process.stderr + }); + const methods = [ + 'debug', + 'dir', + 'error', + 'info', + 'log', + 'trace', + 'warn' + ]; + for (const method of methods)console[method] = stderrConsole[method].bind(stderrConsole); + process.stdout.write = (chunk, encoding, callback)=>process.stderr.write(chunk, encoding, callback); + return Object.freeze({ + restoreProtocolStdout: ()=>{ + process.stdout.write = originalStdoutWrite; + } + }); +}; +const createHeartbeat = ({ activityThrottleMs = defaultActivityThrottleMs, intervalMs = defaultHeartbeatIntervalMs, name = defaultHeartbeatName, writeLine })=>{ + const startedAt = Date.now(); + let lastActivityAt = startedAt; + let lastActivityLogAt = 0; + const log = (reason)=>{ + const uptimeSeconds = Math.round((Date.now() - startedAt) / 1000); + const idleSeconds = Math.round((Date.now() - lastActivityAt) / 1000); + writeLine(`[${name}] stdio heartbeat (${reason}) pid=${process.pid} uptime=${uptimeSeconds}s idle=${idleSeconds}s`); + }; + const timer = setInterval(()=>log('interval'), intervalMs); + timer.unref?.(); + return Object.freeze({ + log, + noteActivity: ()=>{ + lastActivityAt = Date.now(); + if (lastActivityAt - lastActivityLogAt >= activityThrottleMs) { + lastActivityLogAt = lastActivityAt; + log('activity'); + } + }, + stop: ()=>clearInterval(timer) + }); +}; +const runStdioServer = async ({ activityThrottleMs, exit = (code)=>process.exit(code), heartbeat: heartbeatEnabled = true, heartbeatIntervalMs, server, serverName, shutdownTimeoutMs = defaultShutdownTimeoutMs, signals = process, stdin = process.stdin, transport, writeLine = (line)=>void process.stderr.write(`${line}\n`) })=>{ + const heartbeat = createHeartbeat({ + ...void 0 === activityThrottleMs ? {} : { + activityThrottleMs + }, + ...void 0 === heartbeatIntervalMs ? {} : { + intervalMs: heartbeatIntervalMs + }, + ...void 0 === serverName ? {} : { + name: serverName + }, + writeLine: heartbeatEnabled ? writeLine : ()=>void 0 + }); + const keepalive = setInterval(()=>void 0, 60000); + keepalive.unref?.(); + let shuttingDown = false; + const shutdown = async (exitCode = 0)=>{ + if (shuttingDown) return; + shuttingDown = true; + signals.off('SIGINT', handleSigint); + signals.off('SIGTERM', handleSigterm); + stdin.off?.('end', handleStdinEnd); + clearInterval(keepalive); + heartbeat.stop(); + await Promise.race([ + Promise.allSettled([ + Promise.resolve().then(()=>transport.close()), + Promise.resolve().then(()=>server.close()) + ]), + new Promise((resolve)=>setTimeout(resolve, shutdownTimeoutMs)) + ]); + exit(exitCode); + }; + const handleSigint = ()=>{ + shutdown(130); + }; + const handleSigterm = ()=>{ + shutdown(143); + }; + const handleStdinEnd = ()=>{ + shutdown(0); + }; + signals.on('SIGINT', handleSigint); + signals.on('SIGTERM', handleSigterm); + stdin.once?.('end', handleStdinEnd); + transport.onclose = ()=>{ + shutdown(0); + }; + await server.connect(transport); + const originalOnMessage = transport.onmessage; + transport.onmessage = (message, extra)=>{ + heartbeat.noteActivity(); + originalOnMessage?.(message, extra); + }; + return Object.freeze({ + heartbeat, + shutdown + }); +}; +const runGeneratedStdioMcpEntry = async (options)=>{ + const guard = redirectConsoleToStderr(); + const entry = await options.loadEntry(); + const factory = entry.default; + if ('function' != typeof factory) throw new TypeError(`Generated stdio entry for MCP server ${JSON.stringify(options.serverName)} must default-export a server factory.`); + const server = await factory(); + const { StdioServerTransport } = await Promise.resolve(stdio_namespaceObject); + guard.restoreProtocolStdout(); + const transport = new StdioServerTransport(); + return runStdioServer({ + ...options.lifecycle, + server, + serverName: options.serverName, + transport: transport + }); +}; + + + +await runGeneratedStdioMcpEntry({ + loadEntry: ()=>Promise.resolve(status_namespaceObject), + serverName: "status" +}); + +export {}; diff --git a/examples/mcp-app/artifact/claude/scripts/check-service-fixture.mjs b/examples/mcp-app/artifact/claude/scripts/check-service-fixture.mjs new file mode 100644 index 000000000..a059060bb --- /dev/null +++ b/examples/mcp-app/artifact/claude/scripts/check-service-fixture.mjs @@ -0,0 +1,60 @@ +import { readFile } from "node:fs/promises"; + + + + +const healthyCompilerStatus = Object.freeze({ + checks: Object.freeze([ + Object.freeze({ + label: 'Availability', + status: 'passing' + }), + Object.freeze({ + label: 'Build queue', + status: 'passing' + }) + ]), + service: 'compiler', + status: 'healthy', + summary: 'Compiler service is ready for release.' +}); +const isRecord = (value)=>value !== null && typeof value === 'object' && !Array.isArray(value); +const isHealthyCompilerFixture = (value)=>{ + if (!isRecord(value) || value.service !== healthyCompilerStatus.service || value.status !== healthyCompilerStatus.status || value.summary !== healthyCompilerStatus.summary || !Array.isArray(value.checks) || value.checks.length !== healthyCompilerStatus.checks.length) { + return false; + } + return healthyCompilerStatus.checks.every((expected, index)=>{ + const received = value.checks[index]; + return isRecord(received) && received.label === expected.label && received.status === expected.status; + }); +}; + + + +const fixturePath = new URL('../assets/evals/fixtures/status/result.json', import.meta.url); +/** + * `agent-bundle build` detects the `main` export and generates the process + * envelope (argv, awaiting, numeric-return exit-code adoption) around it. + */ const main = async ()=>{ + try { + const fixture = JSON.parse(await readFile(fixturePath, 'utf8')); + if (!isHealthyCompilerFixture(fixture)) { + throw new Error('compiler fixture must contain the exact healthy compiler status'); + } + process.stdout.write('Compiler fixture is healthy.\n'); + return 0; + } catch (error) { + process.stderr.write(`Unable to verify service fixture: ${error instanceof Error ? error.message : String(error)}\n`); + return 1; + } +}; + + +const check_service_fixture_entry_main = main; +if (typeof check_service_fixture_entry_main !== 'function') { + throw new TypeError('Executable entry must export a main function: ' + "/fast/projects/agent-bundle-worktrees/host-test/examples/mcp-app/src/scripts/check-service-fixture.ts"); +} +const code = await check_service_fixture_entry_main(process.argv.slice(2)); +if (typeof code === 'number') process.exitCode = code; + +export {}; diff --git a/examples/mcp-app/artifact/claude/skills/service-readiness/SKILL.md b/examples/mcp-app/artifact/claude/skills/service-readiness/SKILL.md new file mode 100644 index 000000000..8f91a79d7 --- /dev/null +++ b/examples/mcp-app/artifact/claude/skills/service-readiness/SKILL.md @@ -0,0 +1,33 @@ +--- +name: service-readiness +description: Reviews service health evidence and records an auditable readiness decision. +--- +# Service readiness + +## When to use + +Use this Skill when a release, incident decision, or service handoff needs a +clear health verdict backed by named checks and current evidence. + +## Required resources + +- Apply [the service status policy](references/status-policy.md) before + classifying a healthy, degraded, or blocked result. +- Deliver the decision with [the readiness report](assets/readiness-report.md). + +## Workflow + +1. Identify the service and collect its current summary and every labelled + check. Record the command, time, result, and evidence source. +2. Classify any failing check with the status policy. A degraded service is not + release-ready until its failing check has an approved mitigation. +3. State the readiness verdict only after confirming availability and the + service-specific release threshold. +4. Complete the report with the status, checks, evidence, owner, and next + action. Do not omit a failing check from the final decision. + +## Final report requirements + +State `ready`, `degraded`, `blocked`, or `needs evidence`; reproduce the +service summary; list each labelled check and its status; identify the owner +and due date for every non-passing check; and name the next required action. diff --git a/examples/mcp-app/artifact/claude/skills/service-readiness/assets/readiness-report.md b/examples/mcp-app/artifact/claude/skills/service-readiness/assets/readiness-report.md new file mode 100644 index 000000000..3da5d52ea --- /dev/null +++ b/examples/mcp-app/artifact/claude/skills/service-readiness/assets/readiness-report.md @@ -0,0 +1,22 @@ +# Service readiness report + +## Verdict + +State `ready`, `degraded`, `blocked`, or `needs evidence` and name the service. + +## Evidence + +Record the collection time, command or artifact, service summary, and source. + +## Checks + +List every labelled check with its observed status and release threshold. + +## Findings and mitigation + +For each non-passing check, record the impact, owner, mitigation, due date, +and the evidence required to clear it. + +## Next action + +Name the decision owner and the next verification or release action. diff --git a/examples/mcp-app/artifact/claude/skills/service-readiness/references/status-policy.md b/examples/mcp-app/artifact/claude/skills/service-readiness/references/status-policy.md new file mode 100644 index 000000000..7e5766172 --- /dev/null +++ b/examples/mcp-app/artifact/claude/skills/service-readiness/references/status-policy.md @@ -0,0 +1,22 @@ +# Service status policy + +## Evidence standard + +Readiness evidence must identify the service, collection time, check label, +observed status, and source command or artifact. Missing or stale evidence is +not a passing check. + +## Status classification + +- **Healthy**: every required release check is passing. +- **Degraded**: availability remains sufficient, but a release threshold such + as P95 latency is failing. Record an owner and mitigation before release. +- **Blocked**: availability or a critical safety check is failing. Do not + release until new passing evidence is collected. +- **Needs evidence**: the service or any required check cannot be verified. + +## Release decision + +Issue `ready` only for a healthy service with current evidence. A degraded +service needs an explicit mitigation decision; a blocked service cannot pass; +and missing evidence requires a new check rather than an assumption. diff --git a/examples/mcp-app/artifact/codex/.agents/plugins/marketplace.json b/examples/mcp-app/artifact/codex/.agents/plugins/marketplace.json new file mode 100644 index 000000000..37ef3be4a --- /dev/null +++ b/examples/mcp-app/artifact/codex/.agents/plugins/marketplace.json @@ -0,0 +1 @@ +{"interface":{"displayName":"mcp-app-example"},"name":"mcp-app-example-marketplace","plugins":[{"category":"Productivity","name":"mcp-app-example","policy":{"authentication":"ON_INSTALL","installation":"AVAILABLE"},"source":{"path":"./","source":"local"}}]} diff --git a/examples/mcp-app/artifact/codex/.codex-plugin/plugin.json b/examples/mcp-app/artifact/codex/.codex-plugin/plugin.json new file mode 100644 index 000000000..a86a5db3f --- /dev/null +++ b/examples/mcp-app/artifact/codex/.codex-plugin/plugin.json @@ -0,0 +1 @@ +{"author":{"name":"mcp-app-example"},"description":"A unified service-readiness assistant with MCP, Skills, Hooks, scripts, and evaluation.","hooks":"./hooks/hooks.json","interface":{"capabilities":["mcp","hooks","skills"],"category":"Productivity","defaultPrompt":["Help me use mcp-app-example."],"developerName":"mcp-app-example","displayName":"mcp-app-example","longDescription":"A unified service-readiness assistant with MCP, Skills, Hooks, scripts, and evaluation.","shortDescription":"A unified service-readiness assistant with MCP, Skills, Hooks, scripts, and evaluation."},"mcpServers":"./.mcp.json","name":"mcp-app-example","skills":"./skills/","version":"1.0.0"} diff --git a/examples/mcp-app/artifact/codex/.mcp.json b/examples/mcp-app/artifact/codex/.mcp.json new file mode 100644 index 000000000..8a84f9c2f --- /dev/null +++ b/examples/mcp-app/artifact/codex/.mcp.json @@ -0,0 +1 @@ +{"mcpServers":{"status":{"args":["./mcp/mcp-status-073c1634.mjs"],"command":"node","cwd":"./","env":{"AGENT_BUNDLE_PLUGIN_ROOT":"./"},"type":"stdio"}}} diff --git a/examples/mcp-app/artifact/codex/INSTALL.md b/examples/mcp-app/artifact/codex/INSTALL.md new file mode 100644 index 000000000..f93c7ff0b --- /dev/null +++ b/examples/mcp-app/artifact/codex/INSTALL.md @@ -0,0 +1,16 @@ +# Install mcp-app-example + +A unified service-readiness assistant with MCP, Skills, Hooks, scripts, and evaluation. + +Version: `1.0.0` + +Run these commands from this bundle directory. + +## Codex + +Codex installs this bundle from its local marketplace snapshot: + +```sh +codex plugin marketplace add ./ +codex plugin add mcp-app-example@mcp-app-example-marketplace +``` diff --git a/examples/mcp-app/artifact/codex/assets/evals/fixtures/status/result.json b/examples/mcp-app/artifact/codex/assets/evals/fixtures/status/result.json new file mode 100644 index 000000000..a765aa4b5 --- /dev/null +++ b/examples/mcp-app/artifact/codex/assets/evals/fixtures/status/result.json @@ -0,0 +1,9 @@ +{ + "service": "compiler", + "status": "healthy", + "summary": "Compiler service is ready for release.", + "checks": [ + { "label": "Availability", "status": "passing" }, + { "label": "Build queue", "status": "passing" } + ] +} diff --git a/examples/mcp-app/artifact/codex/hooks/hooks.json b/examples/mcp-app/artifact/codex/hooks/hooks.json new file mode 100644 index 000000000..eb4f61756 --- /dev/null +++ b/examples/mcp-app/artifact/codex/hooks/hooks.json @@ -0,0 +1 @@ +{"hooks":{"SessionStart":[{"hooks":[{"command":"node \"${PLUGIN_ROOT}/hooks/session-start-session-start-7ab7e8a5.mjs\"","type":"command"}]}]}} diff --git a/examples/mcp-app/artifact/codex/hooks/session-start-session-start-7ab7e8a5.mjs b/examples/mcp-app/artifact/codex/hooks/session-start-session-start-7ab7e8a5.mjs new file mode 100644 index 000000000..e38d8499c --- /dev/null +++ b/examples/mcp-app/artifact/codex/hooks/session-start-session-start-7ab7e8a5.mjs @@ -0,0 +1,258 @@ +// The require scope +var __webpack_require__ = {}; + +// webpack/runtime/define_property_getters +(() => { +__webpack_require__.d = (exports, getters, values) => { + var define = (defs, kind) => { + for(var key in defs) { + if(__webpack_require__.o(defs, key) && !__webpack_require__.o(exports, key)) { + Object.defineProperty(exports, key, { enumerable: true, [kind]: defs[key] }); + } + } + }; + define(getters, "get"); + define(values, "value"); +}; +})(); +// webpack/runtime/has_own_property +(() => { +__webpack_require__.o = (obj, prop) => (Object.prototype.hasOwnProperty.call(obj, prop)) +})(); +// webpack/runtime/make_namespace_object +(() => { +// define __esModule on exports +__webpack_require__.r = (exports) => { + if(typeof Symbol !== 'undefined' && Symbol.toStringTag) { + Object.defineProperty(exports, Symbol.toStringTag, { value: 'Module' }); + } + Object.defineProperty(exports, '__esModule', { value: true }); +}; +})(); + +// NAMESPACE OBJECT: ./src/hooks/session-start.ts +var session_start_namespaceObject = {}; +__webpack_require__.r(session_start_namespaceObject); +__webpack_require__.d(session_start_namespaceObject, { + "default": () => (session_start) }); + + +/* export default */ const session_start = ((event)=>({ + additionalContext: [ + `Service readiness session ${event.sessionId ?? 'is active'} from ${event.source ?? 'an unknown source'}.`, + `Use the service-readiness Skill, then run check-service-fixture from ${event.cwd ?? process.cwd()} before release review.`, + 'Use show-status for compiler or payments-api when live service evidence is needed.' + ].join(' '), + outcome: 'continue' + })); + + +const target = "codex"; +const canonicalEvent = "sessionStart"; +const nativeEvent = "SessionStart"; +const isRecord = (value)=>typeof value === "object" && value !== null && !Array.isArray(value); +const defined = (value)=>Object.fromEntries(Object.entries(value).filter(([, item])=>item !== undefined)); +const decodeCodexNative = (nativeInput)=>({ + agentId: nativeInput.agent_id, + agentTranscriptPath: nativeInput.agent_transcript_path, + agentType: nativeInput.agent_type, + cwd: nativeInput.cwd, + effort: nativeInput.effort, + hookEventName: nativeInput.hook_event_name, + lastAssistantMessage: nativeInput.last_assistant_message, + model: nativeInput.model, + permissionMode: nativeInput.permission_mode, + promptId: nativeInput.prompt_id, + sessionId: nativeInput.session_id, + source: nativeInput.source, + stopHookActive: nativeInput.stop_hook_active, + toolInput: nativeInput.tool_input, + toolName: nativeInput.tool_name, + toolResponse: nativeInput.tool_response, + toolUseId: nativeInput.tool_use_id, + transcriptPath: nativeInput.transcript_path, + turnId: nativeInput.turn_id + }); +const encodeCodexNative = (canonicalInput)=>defined({ + hook_event_name: nativeEvent, + agent_id: canonicalInput.agentId, + agent_transcript_path: canonicalInput.agentTranscriptPath, + agent_type: canonicalInput.agentType, + cwd: canonicalInput.cwd, + effort: canonicalInput.effort, + last_assistant_message: canonicalInput.lastAssistantMessage, + model: canonicalInput.model, + permission_mode: canonicalInput.permissionMode, + prompt_id: canonicalInput.promptId, + session_id: canonicalInput.sessionId, + source: canonicalInput.source, + stop_hook_active: canonicalInput.stopHookActive, + tool_input: canonicalInput.toolInput, + tool_name: canonicalInput.toolName, + tool_response: canonicalInput.toolResponse, + tool_use_id: canonicalInput.toolUseId, + transcript_path: canonicalInput.transcriptPath, + turn_id: canonicalInput.turnId + }); +const decodeNative = decodeCodexNative; +const encodeNative = encodeCodexNative; +const fail = (message)=>{ + throw new Error(`Agent Bundle hook error: ${message}`); +}; +const validateResult = (result)=>{ + if (result === undefined) return undefined; + if (!isRecord(result)) fail("handler must return void or a result object"); + const allowed = new Set([ + "outcome", + "reason", + "updatedInput", + "additionalContext" + ]); + for (const key of Object.keys(result))if (!allowed.has(key)) fail(`handler result has unsupported field ${key}`); + if (result.outcome !== undefined && ![ + "continue", + "deny", + "stop" + ].includes(result.outcome)) fail("handler result outcome is invalid"); + if (result.reason !== undefined && typeof result.reason !== "string") fail("handler result reason must be a string"); + if (result.additionalContext !== undefined && typeof result.additionalContext !== "string") fail("handler result additionalContext must be a string"); + if (result.updatedInput !== undefined && !isRecord(result.updatedInput)) fail("handler result updatedInput must be an object"); + const supportsDeniedReason = canonicalEvent === "beforeTool" || canonicalEvent === "stop" || canonicalEvent === "agentStop"; + if (result.reason !== undefined && !(result.outcome === "deny" && supportsDeniedReason)) fail("reason is only valid for a denied beforeTool, stop, or agentStop hook"); + if (result.outcome === "deny" && supportsDeniedReason && (typeof result.reason !== "string" || result.reason.trim().length === 0)) fail(`denied ${canonicalEvent} hook requires a nonempty reason`); + if ((canonicalEvent === "sessionStart" || canonicalEvent === "afterTool" || canonicalEvent === "agentStart") && (result.outcome === "deny" || result.outcome === "stop" || result.updatedInput !== undefined)) fail(`${canonicalEvent} cannot deny, stop, or replace input`); + if (canonicalEvent === "beforeTool" && (result.outcome === "stop" || result.outcome === "deny" && result.updatedInput !== undefined)) fail("beforeTool cannot stop or replace input while denying"); + if (canonicalEvent === "stop" && (result.outcome === "stop" || result.updatedInput !== undefined || result.additionalContext !== undefined)) fail("stop only accepts continue or deny with a reason"); + if (canonicalEvent === "agentStop" && (result.outcome === "stop" || result.updatedInput !== undefined)) fail("agentStop cannot stop the parent flow or replace input"); + if (canonicalEvent === "agentStop" && target === "codex" && result.additionalContext !== undefined) fail("Codex SubagentStop does not support additionalContext"); + return result; +}; +const encodeOutput = (result)=>{ + if (result === undefined) return undefined; + if (canonicalEvent === "stop" || canonicalEvent === "agentStop") { + if (result.outcome === "deny") return defined({ + decision: "block", + reason: result.reason + }); + if (canonicalEvent === "agentStop" && target === "claude" && 0) {} + return undefined; + } + const output = defined({ + additionalContext: result.additionalContext, + hookEventName: nativeEvent, + permissionDecision: canonicalEvent === "beforeTool" ? result.outcome === "deny" ? "deny" : "allow" : undefined, + permissionDecisionReason: canonicalEvent === "beforeTool" && result.outcome === "deny" ? result.reason : undefined, + updatedInput: canonicalEvent === "beforeTool" && result.outcome !== "deny" ? result.updatedInput : undefined + }); + return Object.keys(output).length === 1 && output.hookEventName !== undefined ? undefined : { + hookSpecificOutput: output + }; +}; +const decodeOutput = (nativeOutput)=>{ + if (nativeOutput === undefined) return undefined; + if (canonicalEvent === "stop" || canonicalEvent === "agentStop") { + if (nativeOutput.decision === "block") return defined({ + outcome: "deny", + reason: nativeOutput.reason + }); + if (canonicalEvent === "agentStop" && target === "claude" && 0) {} + return undefined; + } + const output = nativeOutput.hookSpecificOutput; + if (!isRecord(output)) fail("native hook output is malformed"); + return defined({ + additionalContext: output.additionalContext, + outcome: output.permissionDecision === "deny" ? "deny" : "continue", + reason: output.permissionDecisionReason, + updatedInput: output.updatedInput + }); +}; +const requireString = (input, field)=>{ + if (typeof input[field] !== "string") fail(`native ${field} must be a string`); +}; +const requireNullableString = (input, field)=>{ + if (input[field] !== null && typeof input[field] !== "string") fail(`native ${field} must be a string or null`); +}; +const validateNativeInput = (input)=>{ + requireString(input, "session_id"); + if (true) requireNullableString(input, "transcript_path"); + else {} + requireString(input, "cwd"); + if (input.hook_event_name !== nativeEvent) fail(`native hook_event_name must equal ${nativeEvent}`); + if (input.prompt_id !== undefined) requireString(input, "prompt_id"); + if (input.permission_mode !== undefined) requireString(input, "permission_mode"); + if (input.model !== undefined) requireString(input, "model"); + if (canonicalEvent === "sessionStart") { + requireString(input, "source"); + return; + } + if (canonicalEvent === "beforeTool" || canonicalEvent === "afterTool") { + requireString(input, "tool_name"); + if (true) { + if (input.tool_input === undefined) fail(`native ${nativeEvent} tool_input is required`); + } else {} + requireString(input, "tool_use_id"); + if (canonicalEvent === "afterTool") { + if (input.tool_response === undefined) fail("native PostToolUse tool_response is required"); + } + return; + } + if (canonicalEvent === "agentStart" || canonicalEvent === "agentStop") { + requireString(input, "agent_id"); + requireString(input, "agent_type"); + if (true) { + requireString(input, "turn_id"); + requireString(input, "model"); + requireString(input, "permission_mode"); + if (![ + "default", + "acceptEdits", + "plan", + "dontAsk", + "bypassPermissions" + ].includes(input.permission_mode)) fail("native permission_mode is invalid"); + } + if (canonicalEvent === "agentStart") return; + if (typeof input.stop_hook_active !== "boolean") fail("native SubagentStop stop_hook_active must be a boolean"); + requireNullableString(input, "agent_transcript_path"); + requireNullableString(input, "last_assistant_message"); + return; + } + if (typeof input.stop_hook_active !== "boolean") fail("native Stop stop_hook_active must be a boolean"); + if (true) requireNullableString(input, "last_assistant_message"); + else {} +}; +const run = async ()=>{ + const handler = Reflect.get(session_start_namespaceObject, "default"); + if (typeof handler !== "function") fail("default export must be a function"); + let raw = ""; + for await (const chunk of process.stdin)raw += chunk; + if (raw.trim().length === 0) fail("stdin must contain exactly one JSON value"); + let input; + try { + input = JSON.parse(raw); + } catch { + fail("stdin must contain exactly one JSON value"); + } + if (!isRecord(input)) fail("stdin JSON value must be an object"); + const simulation = process.env.AGENT_BUNDLE_HOOK_SIMULATION === "1"; + const nativeInput = simulation ? encodeNative(input) : input; + validateNativeInput(nativeInput); + const event = decodeNative(nativeInput); + const result = validateResult(await handler(event, { + nativeEvent: nativeEvent, + nativeInput, + target: target + })); + const nativeOutput = encodeOutput(result); + const output = simulation ? decodeOutput(nativeOutput) : nativeOutput; + if (output !== undefined) process.stdout.write(JSON.stringify(output)); +}; +if (import.meta.main) { + await run().catch((error)=>{ + process.stderr.write(`${error instanceof Error ? error.message : String(error)}\n`); + process.exitCode = 1; + }); +} + +export {}; diff --git a/examples/mcp-app/artifact/codex/mcp/mcp-status-073c1634.mjs b/examples/mcp-app/artifact/codex/mcp/mcp-status-073c1634.mjs new file mode 100644 index 000000000..29189bf45 --- /dev/null +++ b/examples/mcp-app/artifact/codex/mcp/mcp-status-073c1634.mjs @@ -0,0 +1,30761 @@ +import node_process from "node:process"; + +// The require scope +var __webpack_require__ = {}; + +// webpack/runtime/define_property_getters +(() => { +__webpack_require__.d = (exports, getters, values) => { + var define = (defs, kind) => { + for(var key in defs) { + if(__webpack_require__.o(defs, key) && !__webpack_require__.o(exports, key)) { + Object.defineProperty(exports, key, { enumerable: true, [kind]: defs[key] }); + } + } + }; + define(getters, "get"); + define(values, "value"); +}; +})(); +// webpack/runtime/has_own_property +(() => { +__webpack_require__.o = (obj, prop) => (Object.prototype.hasOwnProperty.call(obj, prop)) +})(); +// webpack/runtime/make_namespace_object +(() => { +// define __esModule on exports +__webpack_require__.r = (exports) => { + if(typeof Symbol !== 'undefined' && Symbol.toStringTag) { + Object.defineProperty(exports, Symbol.toStringTag, { value: 'Module' }); + } + Object.defineProperty(exports, '__esModule', { value: true }); +}; +})(); + +// NAMESPACE OBJECT: ./src/mcp/status.ts +var status_namespaceObject = {}; +__webpack_require__.r(status_namespaceObject); +__webpack_require__.d(status_namespaceObject, { + createStatusServer: () => (createStatusServer), + "default": () => (mcp_status) }); + + +// NAMESPACE OBJECT: ../../node_modules/.pnpm/@modelcontextprotocol+server@2.0.0/node_modules/@modelcontextprotocol/server/dist/stdio.mjs +var stdio_namespaceObject = {}; +__webpack_require__.r(stdio_namespaceObject); +__webpack_require__.d(stdio_namespaceObject, { + StdioServerTransport: () => (stdio_StdioServerTransport) }); + + +//#region rolldown:runtime +var __create = Object.create; +var __defProp = Object.defineProperty; +var __getOwnPropDesc = Object.getOwnPropertyDescriptor; +var __getOwnPropNames = Object.getOwnPropertyNames; +var __getProtoOf = Object.getPrototypeOf; +var __hasOwnProp = Object.prototype.hasOwnProperty; +var __commonJSMin = (cb, mod) => () => (mod || cb((mod = { exports: {} }).exports, mod), mod.exports); +var __exportAll = (all, symbols) => { + let target = {}; + for (var name in all) { + __defProp(target, name, { + get: all[name], + enumerable: true + }); + } + if (symbols) { + __defProp(target, Symbol.toStringTag, { value: "Module" }); + } + return target; +}; +var __copyProps = (to, from, except, desc) => { + if (from && typeof from === "object" || typeof from === "function") { + for (var keys = __getOwnPropNames(from), i = 0, n = keys.length, key; i < n; i++) { + key = keys[i]; + if (!__hasOwnProp.call(to, key) && key !== except) { + __defProp(to, key, { + get: ((k) => from[k]).bind(null, key), + enumerable: !(desc = __getOwnPropDesc(from, key)) || desc.enumerable + }); + } + } + } + return to; +}; +var __toESM = (mod, isNodeMode, target) => (target = mod != null ? __create(__getProtoOf(mod)) : {}, __copyProps(isNodeMode || !mod || !mod.__esModule ? __defProp(target, "default", { + value: mod, + enumerable: true +}) : target, mod)); + +//#endregion + +//#region ../core-internal/src/validators/dialects.ts +/** +* Canonical `$schema` URIs per supported dialect (http + https variants, trailing-`#` stripped). +*/ +const DRAFT_2020_12_URIS = new Set(["https://json-schema.org/draft/2020-12/schema", "http://json-schema.org/draft/2020-12/schema"]); +const DRAFT_2019_09_URIS = new Set(["https://json-schema.org/draft/2019-09/schema", "http://json-schema.org/draft/2019-09/schema"]); +const DRAFT_07_URIS = new Set(["https://json-schema.org/draft-07/schema", "http://json-schema.org/draft-07/schema"]); +const DRAFT_06_URIS = new Set(["https://json-schema.org/draft-06/schema", "http://json-schema.org/draft-06/schema"]); +/** +* Whether a `$schema` value declares the 2019-09 dialect — the only supported dialect with +* `$recursiveRef`/`$recursiveAnchor`. Non-throwing (unlike {@linkcode declaredDialect}) so +* wire-layer callers can consult it for documents whose dialect may be unsupported. +*/ +function declares2019Dialect($schema) { + return typeof $schema === "string" && DRAFT_2019_09_URIS.has($schema.replace(/#$/, "")); +} +/** +* Classify a schema's declared `$schema` dialect. No `$schema` (or a non-string one) means +* 2020-12. Any other dialect throws a plain `Error` with a clear message rather than letting the +* engine crash on an opaque internal error or silently mis-validate; `remedy` names the calling +* provider's escape hatch in that message. +*/ +function declaredDialect(schema, remedy) { + if (!("$schema" in schema) || typeof schema.$schema !== "string") return "2020-12"; + const declared = schema.$schema.replace(/#$/, ""); + if (DRAFT_2020_12_URIS.has(declared)) return "2020-12"; + if (DRAFT_2019_09_URIS.has(declared)) return "2019-09"; + if (DRAFT_07_URIS.has(declared) || DRAFT_06_URIS.has(declared)) return "draft-7"; + throw new Error(`JSON Schema declares an unsupported dialect ("$schema": "${schema.$schema.slice(0, 200)}"). The default validator supports JSON Schema 2020-12, 2019-09, draft-07, and draft-06; ${remedy}`); +} + +//#endregion + +//# sourceMappingURL=dialects-DoSzNhcb.mjs.map + +// functions +function assertEqual(val) { + return val; +} +function assertNotEqual(val) { + return val; +} +function toZod() { + return (schema) => schema; +} +function assertIs(_arg) { } +function assertNever(_x) { + throw new Error("Unexpected value in exhaustive check"); +} +function assert(_) { } +function getEnumValues(entries) { + const numericValues = Object.values(entries).filter((v) => typeof v === "number"); + const values = Object.entries(entries) + .filter(([k, _]) => numericValues.indexOf(+k) === -1) + .map(([_, v]) => v); + return values; +} +function joinValues(array, separator = "|") { + return array.map((val) => stringifyPrimitive(val)).join(separator); +} +function jsonStringifyReplacer(_, value) { + if (typeof value === "bigint") + return value.toString(); + return value; +} +function util_cached(getter) { + const set = false; + return { + get value() { + if (!set) { + const value = getter(); + Object.defineProperty(this, "value", { value }); + return value; + } + throw new Error("cached value already set"); + }, + }; +} +function nullish(input) { + return input === null || input === undefined; +} +function cleanRegex(source) { + const start = source.startsWith("^") ? 1 : 0; + const end = source.endsWith("$") ? source.length - 1 : source.length; + return source.slice(start, end); +} +function floatSafeRemainder(val, step) { + const ratio = val / step; + const roundedRatio = Math.round(ratio); + // `val` and `step` each round to a double before the division rounds again, so a true decimal multiple's quotient can sit up to 1.5 of these scaled epsilons from the integer. A 1x tolerance therefore rejected 2.03 as a multiple of 0.07; 4x covers the worst case with margin. + const tolerance = 4 * Number.EPSILON * Math.max(Math.abs(ratio), 1); + if (Math.abs(ratio - roundedRatio) < tolerance) + return 0; + return ratio - roundedRatio; +} +const EVALUATING = /* @__PURE__*/ Symbol("evaluating"); +function defineLazy(object, key, getter) { + let value = undefined; + Object.defineProperty(object, key, { + get() { + if (value === EVALUATING) { + // Circular reference detected, return undefined to break the cycle + return undefined; + } + if (value === undefined) { + value = EVALUATING; + value = getter(); + } + return value; + }, + set(v) { + Object.defineProperty(object, key, { + value: v, + // configurable: true, + }); + // object[key] = v; + }, + configurable: true, + }); +} +function objectClone(obj) { + return Object.create(Object.getPrototypeOf(obj), Object.getOwnPropertyDescriptors(obj)); +} +function assignProp(target, prop, value) { + Object.defineProperty(target, prop, { + value, + writable: true, + enumerable: true, + configurable: true, + }); +} +function mergeDefs(...defs) { + const mergedDescriptors = {}; + for (const def of defs) { + const descriptors = Object.getOwnPropertyDescriptors(def); + Object.assign(mergedDescriptors, descriptors); + } + return Object.defineProperties({}, mergedDescriptors); +} +function cloneDef(schema) { + return mergeDefs(schema._zod.def); +} +function getElementAtPath(obj, path) { + if (!path) + return obj; + return path.reduce((acc, key) => acc?.[key], obj); +} +function promiseAllObject(promisesObj) { + const keys = Object.keys(promisesObj); + const promises = keys.map((key) => promisesObj[key]); + return Promise.all(promises).then((results) => { + const resolvedObj = {}; + for (let i = 0; i < keys.length; i++) { + resolvedObj[keys[i]] = results[i]; + } + return resolvedObj; + }); +} +function randomString(length = 10) { + const chars = "abcdefghijklmnopqrstuvwxyz"; + let str = ""; + for (let i = 0; i < length; i++) { + str += chars[Math.floor(Math.random() * chars.length)]; + } + return str; +} +function util_esc(str) { + return JSON.stringify(str); +} +function slugify(input) { + return input + .toLowerCase() + .trim() + .replace(/[^\w\s-]/g, "") + .replace(/[\s_-]+/g, "-") + .replace(/^-+|-+$/g, ""); +} +const captureStackTrace = ("captureStackTrace" in Error ? Error.captureStackTrace : (..._args) => { }); +function util_isObject(data) { + return typeof data === "object" && data !== null && !Array.isArray(data); +} +const util_allowsEval = /* @__PURE__*/ util_cached(() => { + // Skip the probe under `jitless`: strict CSPs report the caught `new Function` as a `securitypolicyviolation` even though the throw is swallowed. + if (globalConfig.jitless) { + return false; + } + // @ts-ignore + if (typeof navigator !== "undefined" && navigator?.userAgent?.includes("Cloudflare")) { + return false; + } + try { + const F = Function; + new F(""); + return true; + } + catch (_) { + return false; + } +}); +function isPlainObject(o) { + if (util_isObject(o) === false) + return false; + // modified constructor + const ctor = o.constructor; + if (ctor === undefined) + return true; + if (typeof ctor !== "function") + return true; + // modified prototype + const prot = ctor.prototype; + if (util_isObject(prot) === false) + return false; + // ctor doesn't have static `isPrototypeOf` + if (Object.prototype.hasOwnProperty.call(prot, "isPrototypeOf") === false) { + return false; + } + return true; +} +function shallowClone(o) { + if (isPlainObject(o)) + return { ...o }; + if (Array.isArray(o)) + return [...o]; + if (o instanceof Map) + return new Map(o); + if (o instanceof Set) + return new Set(o); + return o; +} +function numKeys(data) { + let keyCount = 0; + for (const key in data) { + if (Object.prototype.hasOwnProperty.call(data, key)) { + keyCount++; + } + } + return keyCount; +} +const getParsedType = (data) => { + const t = typeof data; + switch (t) { + case "undefined": + return "undefined"; + case "string": + return "string"; + case "number": + return Number.isNaN(data) ? "nan" : "number"; + case "boolean": + return "boolean"; + case "function": + return "function"; + case "bigint": + return "bigint"; + case "symbol": + return "symbol"; + case "object": + if (Array.isArray(data)) { + return "array"; + } + if (data === null) { + return "null"; + } + if (data.then && typeof data.then === "function" && data.catch && typeof data.catch === "function") { + return "promise"; + } + if (typeof Map !== "undefined" && data instanceof Map) { + return "map"; + } + if (typeof Set !== "undefined" && data instanceof Set) { + return "set"; + } + if (typeof Date !== "undefined" && data instanceof Date) { + return "date"; + } + // @ts-ignore + if (typeof File !== "undefined" && data instanceof File) { + return "file"; + } + return "object"; + default: + throw new Error(`Unknown data type: ${t}`); + } +}; +const propertyKeyTypes = /* @__PURE__*/ new Set(["string", "number", "symbol"]); +const primitiveTypes = /* @__PURE__*/ (/* unused pure expression or super */ null && (new Set([ + "string", + "number", + "bigint", + "boolean", + "symbol", + "undefined", +]))); +function escapeRegex(str) { + return str.replace(/[.*+?^${}()|[\]\\]/g, "\\$&"); +} +// zod-specific utils +function clone(inst, def, params) { + const cl = new inst._zod.constr(def ?? inst._zod.def); + if (!def || params?.parent) + cl._zod.parent = inst; + return cl; +} +function normalizeParams(_params) { + const params = _params; + if (!params) + return {}; + if (typeof params === "string") + return { error: () => params }; + if (params?.message !== undefined) { + if (params?.error !== undefined) + throw new Error("Cannot specify both `message` and `error` params"); + params.error = params.message; + } + delete params.message; + if (typeof params.error === "string") + return { ...params, error: () => params.error }; + return params; +} +function createTransparentProxy(getter) { + let target; + return new Proxy({}, { + get(_, prop, receiver) { + target ?? (target = getter()); + return Reflect.get(target, prop, receiver); + }, + set(_, prop, value, receiver) { + target ?? (target = getter()); + return Reflect.set(target, prop, value, receiver); + }, + has(_, prop) { + target ?? (target = getter()); + return Reflect.has(target, prop); + }, + deleteProperty(_, prop) { + target ?? (target = getter()); + return Reflect.deleteProperty(target, prop); + }, + ownKeys(_) { + target ?? (target = getter()); + return Reflect.ownKeys(target); + }, + getOwnPropertyDescriptor(_, prop) { + target ?? (target = getter()); + return Reflect.getOwnPropertyDescriptor(target, prop); + }, + defineProperty(_, prop, descriptor) { + target ?? (target = getter()); + return Reflect.defineProperty(target, prop, descriptor); + }, + }); +} +function stringifyPrimitive(value) { + if (typeof value === "bigint") + return value.toString() + "n"; + if (typeof value === "string") + return `"${value}"`; + return `${value}`; +} +function optionalKeys(shape) { + return Object.keys(shape).filter((k) => { + return shape[k]._zod.optin !== undefined && shape[k]._zod.optout === "optional"; + }); +} +// Wrapped in a `@__PURE__` IIFE: esbuild never tree-shakes a top-level initializer that contains a member access on `Number`, so the bare object literal survived into every bundle. +const NUMBER_FORMAT_RANGES = /*@__PURE__*/ (() => ({ + safeint: [Number.MIN_SAFE_INTEGER, Number.MAX_SAFE_INTEGER], + int32: [-2147483648, 2147483647], + uint32: [0, 4294967295], + float32: [-3.4028234663852886e38, 3.4028234663852886e38], + float64: [-Number.MAX_VALUE, Number.MAX_VALUE], +}))(); +const BIGINT_FORMAT_RANGES = { + int64: [/* @__PURE__*/ BigInt("-9223372036854775808"), /* @__PURE__*/ BigInt("9223372036854775807")], + uint64: [/* @__PURE__*/ BigInt(0), /* @__PURE__*/ BigInt("18446744073709551615")], +}; +function pick(schema, mask) { + const currDef = schema._zod.def; + const checks = currDef.checks; + const hasChecks = checks && checks.length > 0; + if (hasChecks) { + throw new Error(".pick() cannot be used on object schemas containing refinements"); + } + const def = mergeDefs(schema._zod.def, { + get shape() { + const newShape = {}; + // `for...in` skips symbols, so a symbol in the mask would select nothing + for (const key of Reflect.ownKeys(mask)) { + if (!Object.prototype.hasOwnProperty.call(currDef.shape, key)) { + throw new Error(`Unrecognized key: "${String(key)}"`); + } + if (!mask[key]) + continue; + assignProp(newShape, key, currDef.shape[key]); + } + assignProp(this, "shape", newShape); // self-caching + return newShape; + }, + checks: [], + }); + return clone(schema, def); +} +function omit(schema, mask) { + const currDef = schema._zod.def; + const checks = currDef.checks; + const hasChecks = checks && checks.length > 0; + if (hasChecks) { + throw new Error(".omit() cannot be used on object schemas containing refinements"); + } + const def = mergeDefs(schema._zod.def, { + get shape() { + const newShape = { ...schema._zod.def.shape }; + for (const key of Reflect.ownKeys(mask)) { + if (!Object.prototype.hasOwnProperty.call(currDef.shape, key)) { + throw new Error(`Unrecognized key: "${String(key)}"`); + } + if (!mask[key]) + continue; + delete newShape[key]; + } + assignProp(this, "shape", newShape); // self-caching + return newShape; + }, + checks: [], + }); + return clone(schema, def); +} +function extend(schema, shape) { + if (!isPlainObject(shape)) { + throw new Error("Invalid input to extend: expected a plain object"); + } + const checks = schema._zod.def.checks; + const hasChecks = checks && checks.length > 0; + if (hasChecks) { + // Only throw if new shape overlaps with existing shape. Use getOwnPropertyDescriptor to check key existence without accessing values + const existingShape = schema._zod.def.shape; + for (const key of Reflect.ownKeys(shape)) { + if (Object.getOwnPropertyDescriptor(existingShape, key) !== undefined) { + throw new Error("Cannot overwrite keys on object schemas containing refinements. Use `.safeExtend()` instead."); + } + } + } + const def = mergeDefs(schema._zod.def, { + get shape() { + const _shape = { ...schema._zod.def.shape, ...shape }; + assignProp(this, "shape", _shape); // self-caching + return _shape; + }, + }); + return clone(schema, def); +} +function safeExtend(schema, shape) { + if (!isPlainObject(shape)) { + throw new Error("Invalid input to safeExtend: expected a plain object"); + } + const def = mergeDefs(schema._zod.def, { + get shape() { + const _shape = { ...schema._zod.def.shape, ...shape }; + assignProp(this, "shape", _shape); // self-caching + return _shape; + }, + }); + return clone(schema, def); +} +function merge(a, b) { + if (!b?._zod?.def) { + throw new Error("Invalid input to merge: expected an object schema. To merge a plain shape, use `.extend()`."); + } + if (a._zod.def.checks?.length) { + throw new Error(".merge() cannot be used on object schemas containing refinements. Use .safeExtend() instead."); + } + const def = mergeDefs(a._zod.def, { + get shape() { + const _shape = { ...a._zod.def.shape, ...b._zod.def.shape }; + assignProp(this, "shape", _shape); // self-caching + return _shape; + }, + get catchall() { + return b._zod.def.catchall; + }, + checks: b._zod.def.checks ?? [], + }); + return clone(a, def); +} +function partial(Class, schema, mask, name = "partial") { + const currDef = schema._zod.def; + const checks = currDef.checks; + const hasChecks = checks && checks.length > 0; + if (hasChecks) { + throw new Error(`.${name}() cannot be used on object schemas containing refinements`); + } + const def = mergeDefs(schema._zod.def, { + get shape() { + const oldShape = schema._zod.def.shape; + const shape = { ...oldShape }; + if (mask) { + for (const key of Reflect.ownKeys(mask)) { + if (!Object.prototype.hasOwnProperty.call(oldShape, key)) { + throw new Error(`Unrecognized key: "${String(key)}"`); + } + if (!mask[key]) + continue; + // if (oldShape[key]!._zod.optin === "optional") continue; + shape[key] = Class + ? new Class({ + type: "optional", + innerType: oldShape[key], + }) + : oldShape[key]; + } + } + else { + // the spread copies symbol keys; `for...in` would not reach them + for (const key of Reflect.ownKeys(oldShape)) { + // if (oldShape[key]!._zod.optin === "optional") continue; + shape[key] = Class + ? new Class({ + type: "optional", + innerType: oldShape[key], + }) + : oldShape[key]; + } + } + assignProp(this, "shape", shape); // self-caching + return shape; + }, + checks: [], + }); + return clone(schema, def); +} +function util_required(Class, schema, mask) { + const def = mergeDefs(schema._zod.def, { + get shape() { + const oldShape = schema._zod.def.shape; + const shape = { ...oldShape }; + if (mask) { + for (const key of Reflect.ownKeys(mask)) { + if (!Object.prototype.hasOwnProperty.call(shape, key)) { + throw new Error(`Unrecognized key: "${String(key)}"`); + } + if (!mask[key]) + continue; + // overwrite with non-optional + shape[key] = new Class({ + type: "nonoptional", + innerType: oldShape[key], + }); + } + } + else { + for (const key of Reflect.ownKeys(oldShape)) { + // overwrite with non-optional + shape[key] = new Class({ + type: "nonoptional", + innerType: oldShape[key], + }); + } + } + assignProp(this, "shape", shape); // self-caching + return shape; + }, + }); + return clone(schema, def); +} +// invalid_type | too_big | too_small | invalid_format | not_multiple_of | unrecognized_keys | invalid_union | invalid_key | invalid_element | invalid_value | custom +function aborted(x, startIndex = 0) { + if (x.aborted === true) + return true; + for (let i = startIndex; i < x.issues.length; i++) { + if (x.issues[i]?.continue !== true) { + return true; + } + } + return false; +} +// Checks for explicit abort (continue === false), as opposed to implicit abort (continue === undefined). Used to respect `abort: true` in .refine() even for checks that have a `when` function. +function explicitlyAborted(x, startIndex = 0) { + if (x.aborted === true) + return true; + for (let i = startIndex; i < x.issues.length; i++) { + if (x.issues[i]?.continue === false) { + return true; + } + } + return false; +} +function prefixIssues(path, issues) { + return issues.map((iss) => { + var _a; + (_a = iss).path ?? (_a.path = []); + iss.path.unshift(path); + return iss; + }); +} +function unwrapMessage(message) { + return typeof message === "string" ? message : message?.message; +} +/* A check holds no link back to the schema it is attached to — the same check instance is shared by every clone of that schema — so the owner is stamped onto the issues a check just raised, at the only point where both are in scope. Runs on the failure path only; `start` is the issue count from before the check ran. */ +function attachSchema(issues, start, inst) { + var _a; + for (let i = start; i < issues.length; i++) { + (_a = issues[i]).schema ?? (_a.schema = inst); + } +} +function finalizeIssue(iss, ctx, config) { + var _a; + // A schema that raised an issue itself owns it outright, and outranks any stamp an enclosing check left in `attachSchema`. String formats and z.custom() are schema and check at once, so when they act as a check they defer to that stamp instead. + const traits = iss.inst?._zod?.traits; + if (traits?.has("$ZodType")) { + if (traits.has("$ZodCheck")) + (_a = iss).schema ?? (_a.schema = iss.inst); + else + iss.schema = iss.inst; + } + // Decreasing specificity, first map to return a message wins. `inst` is whatever raised the issue, so a check's own map outranks the owning schema's. + const schemaError = iss.schema !== iss.inst ? iss.schema?._zod.def?.error : undefined; + const message = iss.message + ? iss.message + : (unwrapMessage(iss.inst?._zod.def?.error?.(iss)) ?? + unwrapMessage(schemaError?.(iss)) ?? + unwrapMessage(ctx?.error?.(iss)) ?? + unwrapMessage(config.customError?.(iss)) ?? + unwrapMessage(config.localeError?.(iss)) ?? + "Invalid input"); + const { inst: _inst, schema: _schema, continue: _continue, input: _input, ...rest } = iss; + rest.path ?? (rest.path = []); + rest.message = message; + if (ctx?.reportInput) { + rest.input = _input; + } + return rest; +} +function getSizableOrigin(input) { + if (input instanceof Set) + return "set"; + if (input instanceof Map) + return "map"; + // @ts-ignore + if (input instanceof File) + return "file"; + return "unknown"; +} +const highSurrogate = /[\uD800-\uDBFF]/; +// Code points in `str`: a surrogate pair counts once, a lone surrogate as itself. Hand-rolled because the string iterator allocates and runs ~250x slower on this path; the regex probe exits ~50x quicker for a string with no astral characters. +function codePointLength(str) { + const units = str.length; + if (!highSurrogate.test(str)) + return units; + let count = units; + for (let i = 0; i < units - 1; i++) { + if ((str.charCodeAt(i) & 0xfc00) === 0xd800 && (str.charCodeAt(i + 1) & 0xfc00) === 0xdc00) { + count--; + i++; + } + } + return count; +} +function getLengthableOrigin(input) { + if (Array.isArray(input)) + return "array"; + if (typeof input === "string") + return "string"; + return "unknown"; +} +function parsedType(data) { + const t = typeof data; + switch (t) { + case "number": { + return Number.isNaN(data) ? "nan" : "number"; + } + case "object": { + if (data === null) { + return "null"; + } + if (Array.isArray(data)) { + return "array"; + } + const obj = data; + if (obj && Object.getPrototypeOf(obj) !== Object.prototype && "constructor" in obj && obj.constructor) { + return obj.constructor.name; + } + } + } + return t; +} +function util_issue(...args) { + const [iss, input, inst] = args; + if (typeof iss === "string") { + return { + message: iss, + code: "custom", + input, + inst, + }; + } + return { ...iss }; +} +function cleanEnum(obj) { + return Object.entries(obj) + .filter(([k, _]) => { + // return true if NaN, meaning it's not a number, thus a string key + return Number.isNaN(Number.parseInt(k, 10)); + }) + .map((el) => el[1]); +} +// Codec utility functions +function base64ToUint8Array(base64) { + const binaryString = atob(base64); + const bytes = new Uint8Array(binaryString.length); + for (let i = 0; i < binaryString.length; i++) { + bytes[i] = binaryString.charCodeAt(i); + } + return bytes; +} +function uint8ArrayToBase64(bytes) { + let binaryString = ""; + for (let i = 0; i < bytes.length; i++) { + binaryString += String.fromCharCode(bytes[i]); + } + return btoa(binaryString); +} +function base64urlToUint8Array(base64url) { + const base64 = base64url.replace(/-/g, "+").replace(/_/g, "/"); + const padding = "=".repeat((4 - (base64.length % 4)) % 4); + return base64ToUint8Array(base64 + padding); +} +function uint8ArrayToBase64url(bytes) { + return uint8ArrayToBase64(bytes).replace(/\+/g, "-").replace(/\//g, "_").replace(/=/g, ""); +} +function hexToUint8Array(hex) { + const cleanHex = hex.replace(/^0x/, ""); + if (cleanHex.length % 2 !== 0) { + throw new Error("Invalid hex string length"); + } + const bytes = new Uint8Array(cleanHex.length / 2); + for (let i = 0; i < cleanHex.length; i += 2) { + bytes[i / 2] = Number.parseInt(cleanHex.slice(i, i + 2), 16); + } + return bytes; +} +function uint8ArrayToHex(bytes) { + return Array.from(bytes) + .map((b) => b.toString(16).padStart(2, "0")) + .join(""); +} +// instanceof +class util_Class { + constructor(..._args) { } +} +////////// PROTOTYPE INSTALLERS ////////// +// +// Members live on the prototype and materialize per instance on first read, which keeps own-property count under the step where V8 stops using inline slots. Changing anything here means re-measuring runtime, memory and bundle size together — see "The three axes" in AGENTS.md. +/** + * Installs a trait's members on its prototype. Each value builds that member for the instance on first read; the built value shadows the accessor as an own property, so a detached `const { parse } = schema` keeps working. + * + * Call this from a `proto` initializer, which runs once per prototype — never per instance. + */ +function util_members(proto, table) { + for (const key in table) { + const desc = Object.getOwnPropertyDescriptor(table, key); + // a getter installs as written, so it stays live: `description` reads through to the registry on every access. not enumerable: an object literal's is, and a prototype member never was + if (desc.get) + Object.defineProperty(proto, key, { ...desc, enumerable: false }); + // a method materializes bound on first read, which is what keeps a detached member working: `const opt = schema.optional; opt()` + else + defineBound(proto, key, desc.value); + } +} +/** Shadows a prototype member with an own value, so a getter that builds from the instance runs once. */ +function util_own(inst, key, value, enumerable = true) { + Object.defineProperty(inst, key, { configurable: true, writable: true, enumerable, value }); + return value; +} +/** Like {@link own}, for a member that was never an own data property and has to stay out of `Object.keys`. */ +function hide(inst, key, value) { + return util_own(inst, key, value, false); +} +function defineBound(proto, key, fn) { + Object.defineProperty(proto, key, { + configurable: true, + get() { + // vitest's spyOn calls a prototype getter bare to find the function it wraps, so a nullish receiver answers the raw method + return this == null ? fn : util_own(this, key, fn.bind(this)); + }, + set(value) { + util_own(this, key, value); + }, + }); +} +/** Returns the prototype to install on, or `undefined` if this group is already installed on it. */ +function claim(inst, sentinel) { + const proto = Object.getPrototypeOf(inst); + // Runs on every construction, so `in` rather than the costlier `hasOwnProperty.call`. Sentinels are keys the group itself defines. + return sentinel in proto ? undefined : proto; +} +// The internals whose init chain is installing. A second call for the same one is a derived constructor overriding its base, so it must not construct another schema in between or the override is dropped. +let installing; +// Set while a getter is running, so a value that resolved through a recursion break is not memoized. One shared descriptor shadows the key for the duration, which costs no per-key allocation. +let broke = false; +const breaker = { + configurable: true, + get() { + broke = true; + return undefined; + }, +}; +/** + * Installs a lazily-derived internal on the `_zod` prototype of `inst`'s + * constructor, computed from the internals object itself and cached there on + * first read. One accessor per constructor rather than one per instance. + */ +function defineLazyInternal(inst, key, compute) { + const proto = Object.getPrototypeOf(inst._zod); + if (key in proto && installing !== inst._zod) { + // A repeat construction: everything is installed already. Cleared here so the reference is not held past the first construction of every type. + installing = undefined; + return; + } + installing = inst._zod; + Object.defineProperty(proto, key, { + configurable: true, + get() { + // Shadowed before computing so a re-entrant read from a recursive schema resolves to undefined instead of running the getter again. + Object.defineProperty(this, key, breaker); + const outer = broke; + broke = false; + try { + const value = compute(this); + // A result that resolved through a recursion break is recomputed once the graph is complete; everything else memoizes, undefined included. + if (broke) + delete this[key]; + else + Object.defineProperty(this, key, { configurable: true, writable: true, value }); + broke = broke || outer; + return value; + } + catch (err) { + // A compute that threw memoizes nothing, so a later read runs it again and fails the same way. The shadow goes with it, since leaving it installed would answer undefined for every later read. + delete this[key]; + broke = broke || outer; + throw err; + } + }, + set(value) { + Object.defineProperty(this, key, { configurable: true, writable: true, value }); + }, + }); +} +/** + * Installs `key` on `inst`'s prototype, computed by `make` on first read and cached there as an own + * data property. One accessor per constructor rather than one per instance, because an own accessor + * puts every instance after the first into v8 dictionary mode. The key doubles as the sentinel. + */ +function installLazyProp(inst, key, make, enumerable) { + const proto = claim(inst, key); + if (!proto) + return; + Object.defineProperty(proto, key, { + configurable: true, + get() { + // Shadowed before computing, so a re-entrant read from a self-referential shape resolves to undefined instead of running the getter again. A data property rather than an accessor: an own accessor is the dictionary-mode transition this exists to avoid. + const desc = { configurable: true, writable: true, enumerable, value: undefined }; + Object.defineProperty(this, key, desc); + // a compute that throws leaves the shadow behind, so later reads answer undefined instead of re-throwing; `defineLazy` did the same, and `defineLazyInternal`'s delete-on-catch would cost bytes in every bundle for a case only a throwing user getter reaches + desc.value = make(this); + Object.defineProperty(this, key, desc); + return desc.value; + }, + set(value) { + Object.defineProperty(this, key, { configurable: true, writable: true, enumerable, value }); + }, + }); +} +/** Marks the thunk `_catch` synthesises for a constant catch value. `Function.length` cannot tell that thunk from a user callback — rest and defaulted parameters both report arity 0 — and a user callback reads `ctx.error`, whose issues only finalize correctly against the caller's per-parse error map. Provenance can say what arity cannot. A plain string key rather than `Symbol.for`, whose call at module scope no bundler can prove pure — the same shape that anchored `urlCanParse` into every build. */ +const CONSTANT_CATCH = "~constantCatch"; +/** Wraps a constant catch value in a thunk tagged with {@link CONSTANT_CATCH}. */ +function constantCatch(value) { + const fn = () => value; + fn[CONSTANT_CATCH] = true; + return fn; +} + +var core_a; + +/** A special constant with type `never` */ +const NEVER = /*@__PURE__*/ Object.freeze({ + status: "aborted", +}); +/* Shared descriptor for installing `_zod`; defineProperty reads it + * synchronously, so reusing one object avoids a per-instance allocation. */ +const _zodDesc = { value: undefined, enumerable: false }; +// null where suppressing the capture would be unrecoverable: `parse()` puts the frames back with `captureStackTrace`, so without it the throw would lose its stack. also latched to null once `stackTraceLimit` proves unassignable, which a realm can do at any point by hardening Error +let _E = "captureStackTrace" in Error ? Error : null; +// v8 captures a stack trace inside the Error constructor, which dominates a failed parse; costs only the frames, and parse() restores those. the constructor must RUN: Object.create is cheaper and passes instanceof, but Error.isError and util.types.isNativeError check an internal slot +function newError(Definition) { + const E = _E; + if (E) { + const saved = E.stackTraceLimit; + if (typeof saved === "number") { + try { + E.stackTraceLimit = 0; + } + catch { + _E = null; + return new Definition(); + } + try { + return new Definition(); + } + finally { + E.stackTraceLimit = saved; + } + } + } + return new Definition(); +} +function $constructor(name, initializer, +/** This trait's members, installed once on every prototype that composes it. They cannot be declared in the initializer above: that runs per instance, and the prototype is shared. */ +proto, params) { + // Prototype for this constructor's `_zod` internals. Lazily-derived fields (`values`, `pattern`, `optin`, …) install here once rather than as an accessor on every instance. + const zodProto = {}; + // Assigning the fields in the constructor body is what gives instances in-object slots; building the object literally and reparenting it costs a second allocation and a generic property copy. + function Internals(def) { + this.def = def; + this.constr = _; + this.traits = new Set(); + } + Internals.prototype = zodProto; + const protoMembers = proto; + // One trait's members land on every prototype whose chain composes it, so the answer is per prototype rather than per trait. + const initialized = protoMembers && new WeakSet(); + function init(inst, def) { + if (!inst._zod) { + _zodDesc.value = new Internals(def); + try { + Object.defineProperty(inst, "_zod", _zodDesc); + } + finally { + // Cleared even on throw, so the shared descriptor never leaks one instance's internals into the next. + _zodDesc.value = undefined; + } + } + if (inst._zod.traits.has(name)) { + return; + } + inst._zod.traits.add(name); + initializer(inst, def); + if (initialized) { + // `super(def)` from a user subclass gives `this` a prototype the subclass owns, and installing there would overwrite whatever the subclass declared. `constr` built the instance, so its prototype is the one below the subclass's that should carry the members. A receiver whose chain never reaches that prototype installs on its own, which for a plain object handed straight to `init` means `Object.prototype` — unchanged from before. + const own = Object.getPrototypeOf(inst); + const ctorProto = inst._zod.constr.prototype; + let up = own; + while (up && up !== ctorProto) + up = Object.getPrototypeOf(up); + const target = up ?? own; + if (!initialized.has(target)) { + initialized.add(target); + util_members(target, protoMembers); + } + } + // support prototype modifications; for-in avoids the array allocation of Object.keys on the (usually empty) prototype + const proto = _.prototype; + for (const k in proto) { + if (!Object.prototype.hasOwnProperty.call(proto, k)) + continue; + if (!(k in inst)) { + inst[k] = proto[k].bind(inst); + } + } + } + // doesn't work if Parent has a constructor with arguments + const Parent = params?.Parent ?? Object; + class Definition extends Parent { + } + Object.defineProperty(Definition, "name", { value: name }); + function _(def) { + const inst = params?.Parent ? newError(Definition) : this; + init(inst, def); + const deferred = inst._zod.deferred; + if (deferred) { + for (const fn of deferred) { + fn(); + } + // Released: initializers run once, and the list would otherwise be retained for the schema's lifetime. + inst._zod.deferred = undefined; + } + // Global post-processor hook. Internal: installed by `import "zod/compile"` to enable AOT compilation for every constructed schema. Runs last, once the instance is fully built, because it hands the instance to compile(). The post-processor is expected to be reentrancy-guarded by its own implementation. + const pp = globalThis.__zod_globalConfig?.postProcessor; + if (pp) + pp(inst); + return inst; + } + Object.defineProperty(_, "init", { value: init }); + Object.defineProperty(_, Symbol.hasInstance, { + value: (inst) => { + if (params?.Parent && inst instanceof params.Parent) + return true; + return inst?._zod?.traits?.has(name); + }, + }); + Object.defineProperty(_, "name", { value: name }); + return _; +} +////////////////////////////// UTILITIES /////////////////////////////////////// +const $brand = /*@__PURE__*/ (/* unused pure expression or super */ null && (Symbol("zod_brand"))); +class $ZodAsyncError extends Error { + constructor() { + super(`Encountered Promise during synchronous parse. Use .parseAsync() instead.`); + } +} +class $ZodEncodeError extends Error { + constructor(name) { + super(`Encountered unidirectional transform during encode: ${name}`); + this.name = "ZodEncodeError"; + } +} +(core_a = globalThis).__zod_globalConfig ?? (core_a.__zod_globalConfig = {}); +const globalConfig = globalThis.__zod_globalConfig; +function core_config(newConfig) { + if (newConfig) + Object.assign(globalConfig, newConfig); + return globalConfig; +} + +class $ZodCyclicError extends Error { + constructor() { + super(`Cannot parse a reference cycle that closes through a transform`); + this.name = "ZodCyclicError"; + } +} +/** Keyed off the context object every schema in one parse call already shares. */ +const STATE = "~memo"; +const NO_ISSUES = []; +// Receivers prefix paths in place, so the cache and every hand-out need their own copies. +function cloneIssues(issues) { + return issues.map((iss) => (iss.path ? { ...iss, path: iss.path.slice() } : { ...iss })); +} +const recursive = /*@__PURE__*/ new WeakMap(); +/** Whether this schema's subtree contains a cycle, so one parse can re-enter it. */ +function isRecursive(inst, stack) { + const cached = recursive.get(inst); + if (cached !== undefined) + return cached; + // Relative to the walk in progress, so not cached. + if (stack.has(inst)) + return true; + stack.add(inst); + let result = false; + const check = (child) => { + if (!result && child?._zod && isRecursive(child, stack)) + result = true; + }; + const def = inst._zod.def; + const kind = def.type; + switch (kind) { + case "object": { + // `Reflect.ownKeys` rather than `Object.keys`, so a cycle through a declared symbol key is still seen + for (const key of Reflect.ownKeys(def.shape)) + check(def.shape[key]); + check(def.catchall); + break; + } + case "array": + check(def.element); + break; + case "tuple": + for (const el of def.items) + check(el); + check(def.rest); + break; + case "record": + case "map": + check(def.keyType); + check(def.valueType); + break; + case "set": + check(def.valueType); + break; + case "union": + for (const el of def.options) + check(el); + break; + case "intersection": + check(def.left); + check(def.right); + break; + case "optional": + case "nullable": + case "default": + case "prefault": + case "catch": + case "readonly": + case "nonoptional": + case "promise": + case "success": + check(def.innerType); + break; + case "pipe": + check(def.in); + check(def.out); + break; + case "function": + check(def.input); + check(def.output); + break; + // reading `_zod.innerType` resolves the getter once and caches it + case "lazy": + check(inst._zod.innerType); + break; + // a leaf by choice: `parts` are regex fragments, not data positions + case "template_literal": + // leaves + case "string": + case "number": + case "int": + case "boolean": + case "bigint": + case "symbol": + case "undefined": + case "null": + case "void": + case "never": + case "any": + case "unknown": + case "date": + case "nan": + case "enum": + case "literal": + case "file": + case "transform": + case "custom": + break; + default: { + // a new built-in kind becomes a compile error here + kind; + // a user-defined kind can still hold children, and only its author knows where, so fall back to scanning the def — skipping accessors, since reading one can run user code + for (const key in def) { + const desc = Object.getOwnPropertyDescriptor(def, key); + if (!desc || desc.get) + continue; + const value = desc.value; + if (!value || typeof value !== "object") + continue; + if (value._zod) + check(value); + else if (Array.isArray(value)) + for (const el of value) + check(el); + } + } + } + stack.delete(inst); + recursive.set(inst, result); + return result; +} +/** + * Whether one parse can re-enter this schema, i.e. its subtree contains a cycle. + * Exported for `z.compile`, which refuses to compile such a schema: cycle + * breaking is driven from here off state keyed on the parse context, and a + * generated fast path has no context to key on. + */ +function isRecursiveSchema(inst) { + return isRecursive(inst, new Set()); +} +function bucketFor(state, inst) { + let bucket = state.buckets.get(inst); + if (!bucket) { + bucket = new Map(); + state.buckets.set(inst, bucket); + } + return bucket; +} +// Set immediately before delegating to core and cleared immediately after, so `alloc` registers only for a visit this module is driving. +let handoff; +// Allocated but unfinished entries. `alloc` and the matching pop both happen in the synchronous part of a parse, so they nest even when children are async, and one stack serves every schema. +const memoizer_open = []; +const memoizer_memo = { + alloc(_inst, payload, empty) { + const bucket = handoff; + if (!bucket) + return empty; + handoff = undefined; + const entry = { value: empty, issues: null }; + bucket.set(payload.value, entry); + memoizer_open.push(entry); + return empty; + }, + guard(inst) { + var _a; + (_a = inst._zod).deferred ?? (_a.deferred = []); + inst._zod.deferred.push(() => { + const base = inst._zod.parse; + const wrapped = (payload, ctx) => { + // The value is a placeholder a back-edge is still waiting on, so the cycle closes through this transform. Its output can't exist in time to bind. + if (ctx.direction !== "backward" && isBackEdge(ctx, payload.value)) + throw new $ZodCyclicError(); + return base(payload, ctx); + }; + inst._zod.parse = wrapped; + if (inst._zod.run === base) + inst._zod.run = wrapped; + }); + }, + attach(inst) { + var _a; + let isRecursiveInst; + // `bucket` memoized for one parse; a recursive schema is re-entered many times and its bucket never changes + let lastCtx; + let lastBucket; + // Wraps `parse` in a deferred so it sees the container's final parse. Core's own deferred copies `parse` into `run` when there are no checks, and it ran first, so `run` is patched to match; with checks, `run` reads `parse` dynamically. + (_a = inst._zod).deferred ?? (_a.deferred = []); + inst._zod.deferred.push(() => { + const base = inst._zod.parse; + const wrapped = (payload, ctx) => { + if (isRecursiveInst === undefined) { + isRecursiveInst = isRecursive(inst, new Set()); + if (!isRecursiveInst) { + // Nothing here can ever fire, so take it back out. + inst._zod.parse = base; + if (inst._zod.run === wrapped) + inst._zod.run = base; + return base(payload, ctx); + } + } + const input = payload.value; + if (input === null || typeof input !== "object") + return base(payload, ctx); + let state = ctx[STATE]; + if (!state) { + state = { buckets: new Map(), backEdges: undefined }; + ctx[STATE] = state; + } + let bucket; + if (lastCtx === ctx) { + bucket = lastBucket; + } + else { + bucket = bucketFor(state, inst); + lastCtx = ctx; + lastBucket = bucket; + } + const hit = bucket.get(input); + if (hit) { + payload.value = hit.value; + if (hit.issues) { + if (hit.issues.length) + payload.issues.push(...cloneIssues(hit.issues)); + } + else { + // Still being parsed: its own checks cover it, so skip them here. + payload.memo = true; + state.backEdges ?? (state.backEdges = new Set()); + state.backEdges.add(hit.value); + } + return payload; + } + handoff = bucket; + const depth = memoizer_open.length; + const result = base(payload, ctx); + handoff = undefined; + // A container that rejected its input outright allocated nothing. + const entry = memoizer_open.length > depth ? memoizer_open.pop() : undefined; + // Both paths written out so the sync one allocates no closure. It runs once per node, and capturing here cost more than everything else combined. + if (result instanceof Promise) { + return result.then((r) => { + if (entry) + entry.issues = r.issues.length ? cloneIssues(r.issues) : NO_ISSUES; + return r; + }); + } + if (entry) + entry.issues = result.issues.length ? cloneIssues(result.issues) : NO_ISSUES; + return result; + }; + inst._zod.parse = wrapped; + if (inst._zod.run === base) + inst._zod.run = wrapped; + }); + }, +}; +/** The memoizer that gives containers cycle support. `zod` installs it by default; `zod/mini` opts in with `config({ memoizer: memoizer() })`. */ +function memoizer() { + return memoizer_memo; +} +/** Whether this value is a node a back-edge resolved to before it finished. */ +function isBackEdge(ctx, value) { + const backEdges = ctx[STATE]?.backEdges; + return backEdges !== undefined && value !== null && typeof value === "object" && backEdges.has(value); +} + + +/** + * @deprecated CUID v1 is deprecated by its authors due to information leakage + * (timestamps embedded in the id). Use {@link cuid2} instead. + * See https://github.com/paralleldrive/cuid. + */ +const cuid = /^[cC][0-9a-z]{6,}$/; +const cuid2 = /^[0-9a-z]+$/; +const ulid = /^[0-7][0-9A-HJKMNP-TV-Za-hjkmnp-tv-z]{25}$/; +const xid = /^[0-9a-vA-V]{20}$/; +const ksuid = /^[A-Za-z0-9]{27}$/; +const nanoid = /^[a-zA-Z0-9_-]{21}$/; +function nanoidOfLength(length) { + return new RegExp(`^[a-zA-Z0-9_-]{${length}}$`); +} +/** ISO 8601-1 duration regex. Does not support the 8601-2 extensions like negative durations or fractional/negative components. */ +const duration = /^P(?:(\d+W)|(?!.*W)(?=\d|T\d)(\d+Y)?(\d+M)?(\d+D)?(T(?=\d)(\d+H)?(\d+M)?(\d+([.,]\d+)?S)?)?)$/; +/** Implements ISO 8601-2 extensions like explicit +- prefixes, mixing weeks with other units, and fractional/negative components. */ +const extendedDuration = /^[-+]?P(?!$)(?:(?:[-+]?\d+Y)|(?:[-+]?\d+[.,]\d+Y$))?(?:(?:[-+]?\d+M)|(?:[-+]?\d+[.,]\d+M$))?(?:(?:[-+]?\d+W)|(?:[-+]?\d+[.,]\d+W$))?(?:(?:[-+]?\d+D)|(?:[-+]?\d+[.,]\d+D$))?(?:T(?=[\d+-])(?:(?:[-+]?\d+H)|(?:[-+]?\d+[.,]\d+H$))?(?:(?:[-+]?\d+M)|(?:[-+]?\d+[.,]\d+M$))?(?:[-+]?\d+(?:[.,]\d+)?S)?)??$/; +/** A regex for any UUID-like identifier: 8-4-4-4-12 hex pattern */ +const guid = /^([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})$/; +/** Returns a regex for validating an RFC 9562/4122 UUID. + * + * @param version Optionally specify a version 1-8. If no version is specified, all versions are supported. */ +const uuid = (version) => { + if (!version) + return /^([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)$/; + return new RegExp(`^([0-9a-fA-F]{8}-[0-9a-fA-F]{4}-${version}[0-9a-fA-F]{3}-[89abAB][0-9a-fA-F]{3}-[0-9a-fA-F]{12})$`); +}; +const uuid4 = /*@__PURE__*/ (/* unused pure expression or super */ null && (uuid(4))); +const uuid6 = /*@__PURE__*/ (/* unused pure expression or super */ null && (uuid(6))); +const uuid7 = /*@__PURE__*/ (/* unused pure expression or super */ null && (uuid(7))); +/** Practical email validation */ +const email = /^(?!\.)(?!.*\.\.)([A-Za-z0-9_'+\-\.]*)[A-Za-z0-9_+-]@([A-Za-z0-9][A-Za-z0-9\-]*\.)+[A-Za-z]{2,}$/; +/** Equivalent to the HTML5 input[type=email] validation implemented by browsers. Source: https://developer.mozilla.org/en-US/docs/Web/HTML/Element/input/email */ +const html5Email = /^[a-zA-Z0-9.!#$%&'*+/=?^_`{|}~-]+@[a-zA-Z0-9](?:[a-zA-Z0-9-]{0,61}[a-zA-Z0-9])?(?:\.[a-zA-Z0-9](?:[a-zA-Z0-9-]{0,61}[a-zA-Z0-9])?)*$/; +/** The classic emailregex.com regex for RFC 5322-compliant emails */ +const rfc5322Email = /^(([^<>()\[\]\\.,;:\s@"]+(\.[^<>()\[\]\\.,;:\s@"]+)*)|(".+"))@((\[[0-9]{1,3}\.[0-9]{1,3}\.[0-9]{1,3}\.[0-9]{1,3}])|(([a-zA-Z\-0-9]+\.)+[a-zA-Z]{2,}))$/; +/** A loose regex that allows Unicode characters, enforces length limits, and that's about it. */ +const unicodeEmail = /^[^\s@"]{1,64}@[^\s@]{1,255}$/u; +const idnEmail = (/* unused pure expression or super */ null && (unicodeEmail)); +const browserEmail = /^[a-zA-Z0-9.!#$%&'*+/=?^_`{|}~-]+@[a-zA-Z0-9](?:[a-zA-Z0-9-]{0,61}[a-zA-Z0-9])?(?:\.[a-zA-Z0-9](?:[a-zA-Z0-9-]{0,61}[a-zA-Z0-9])?)*$/; +// from https://thekevinscott.com/emojis-in-javascript/#writing-a-regular-expression +// Single character class, not an alternation: the two properties overlap (U+1F9B0-U+1F9B3), so `(A|B)+` backtracks exponentially on a failed match. +const _emoji = `^[\\p{Extended_Pictographic}\\p{Emoji_Component}]+$`; +function emoji() { + return new RegExp(_emoji, "u"); +} +const ipv4 = /^(?:(?: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])$/; +const regexes_ipv6 = /^(([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}|:))$/; +const mac = (delimiter) => { + const escapedDelim = util.escapeRegex(delimiter ?? ":"); + return new RegExp(`^(?:[0-9A-F]{2}${escapedDelim}){5}[0-9A-F]{2}$|^(?:[0-9a-f]{2}${escapedDelim}){5}[0-9a-f]{2}$`); +}; +const cidrv4 = /^((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])$/; +const cidrv6 = /^(([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}|:))\/(12[0-8]|1[01][0-9]|[1-9]?[0-9])$/; +// https://stackoverflow.com/questions/7860392/determine-if-string-is-in-base64-using-javascript +const regexes_base64 = /^$|^(?:[0-9a-zA-Z+/]{4})*(?:(?:[0-9a-zA-Z+/]{2}==)|(?:[0-9a-zA-Z+/]{3}=))?$/; +const regexes_base64url = /^[A-Za-z0-9_-]*$/; +// based on https://stackoverflow.com/questions/106179/regular-expression-to-match-dns-hostname-or-ip-address +// export const hostname: RegExp = /^([a-zA-Z0-9-]+\.)*[a-zA-Z0-9-]+$/; +const regexes_hostname = /^(?=.{1,253}\.?$)[a-zA-Z0-9](?:[a-zA-Z0-9-]{0,61}[a-zA-Z0-9])?(?:\.[a-zA-Z0-9](?:[-0-9a-zA-Z]{0,61}[0-9a-zA-Z])?)*\.?$/; +const domain = /^(?=.{1,253}$)([a-zA-Z0-9](?:[a-zA-Z0-9-]{0,61}[a-zA-Z0-9])?\.)+[a-zA-Z]{2,63}$/; +const httpProtocol = /^https?$/; +// https://blog.stevenlevithan.com/archives/validate-phone-number#r4-3 (regex sans spaces) E.164: leading digit must be 1-9; total digits (excluding '+') between 7-15 +const e164 = /^\+[1-9]\d{6,14}$/; +// Credit card shape: 12–19 digits, optionally separated by single spaces or single hyphens. ISO/IEC 7812 caps the PAN at 19 digits; 12 is the shortest issued length (Maestro). +const creditCard = /^\d(?:[ -]?\d){11,18}$/; +const dateSource = `(?:(?:\\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])))`; +/** Anchors a pattern source. The interpolation lives here rather than at the call site because + * esbuild will not drop a `@__PURE__` call whose own argument interpolates a variable, but it + * will drop `anchor(dateSource)`. Keeping it inline pinned `date` into every bundle. */ +function regexes_anchor(source) { + return new RegExp(`^${source}$`); +} +const regexes_date = /*@__PURE__*/ regexes_anchor(dateSource); +function timeSource(args) { + const hhmm = `(?:[01]\\d|2[0-3]):[0-5]\\d`; + const regex = typeof args.precision === "number" + ? args.precision === -1 + ? `${hhmm}` + : args.precision === 0 + ? `${hhmm}:[0-5]\\d` + : `${hhmm}:[0-5]\\d\\.\\d{${args.precision}}` + : args.seconds + ? `${hhmm}:[0-5]\\d(?:\\.\\d+)?` + : `${hhmm}(?::[0-5]\\d(?:\\.\\d+)?)?`; + return regex; +} +function regexes_time(args) { + return new RegExp(`^${timeSource(args)}$`); +} +// Adapted from https://stackoverflow.com/a/3143231 +function datetime(args) { + const opts = ["Z"]; + // if (args.offset) opts.push(`([+-]\\d{2}:\\d{2})`); + if (args.offset) + opts.push(`([+-](?:[01]\\d|2[0-3]):[0-5]\\d)`); + // RFC 3339 mandates seconds wherever the time carries a `Z` or an offset, so only the unqualified form `local` adds may omit them + const qualified = `${timeSource({ precision: args.precision, seconds: true })}(?:${opts.join("|")})`; + const timeRegex = args.local ? `${qualified}|${timeSource({ precision: args.precision })}` : qualified; + return new RegExp(`^${dateSource}T(?:${timeRegex})$`); +} +const regexes_string = (params) => { + const regex = params ? `[\\s\\S]{${params?.minimum ?? 0},${params?.maximum ?? ""}}` : `[\\s\\S]*`; + return new RegExp(`^${regex}$`); +}; +const bigint = /^-?\d+n?$/; +const integer = /^-?\d+$/; +const number = /^-?\d+(?:\.\d+)?$/; +const regexes_boolean = /^(?:true|false)$/i; +const _null = /^null$/i; + +const _undefined = /^undefined$/i; + +// regex for string with no uppercase letters +const lowercase = /^[^A-Z]*$/; +// regex for string with no lowercase letters +const uppercase = /^[^a-z]*$/; +// regex for hexadecimal strings (any length) +const regexes_hex = /^[0-9a-fA-F]*$/; +// Hash regexes for different algorithms and encodings +// Helper function to create base64 regex with exact length and padding +function fixedBase64(bodyLength, padding) { + return new RegExp(`^[A-Za-z0-9+/]{${bodyLength}}${padding}$`); +} +// Helper function to create base64url regex with exact length (no padding) +function fixedBase64url(length) { + return new RegExp(`^[A-Za-z0-9_-]{${length}}$`); +} +// MD5 (16 bytes): base64 = 24 chars total (22 + "==") +const md5_hex = /^[0-9a-fA-F]{32}$/; +const md5_base64 = /*@__PURE__*/ (/* unused pure expression or super */ null && (fixedBase64(22, "=="))); +const md5_base64url = /*@__PURE__*/ (/* unused pure expression or super */ null && (fixedBase64url(22))); +// SHA1 (20 bytes): base64 = 28 chars total (27 + "=") +const sha1_hex = /^[0-9a-fA-F]{40}$/; +const sha1_base64 = /*@__PURE__*/ (/* unused pure expression or super */ null && (fixedBase64(27, "="))); +const sha1_base64url = /*@__PURE__*/ (/* unused pure expression or super */ null && (fixedBase64url(27))); +// SHA256 (32 bytes): base64 = 44 chars total (43 + "=") +const sha256_hex = /^[0-9a-fA-F]{64}$/; +const sha256_base64 = /*@__PURE__*/ (/* unused pure expression or super */ null && (fixedBase64(43, "="))); +const sha256_base64url = /*@__PURE__*/ (/* unused pure expression or super */ null && (fixedBase64url(43))); +// SHA384 (48 bytes): base64 = 64 chars total (no padding) +const sha384_hex = /^[0-9a-fA-F]{96}$/; +const sha384_base64 = /*@__PURE__*/ (/* unused pure expression or super */ null && (fixedBase64(64, ""))); +const sha384_base64url = /*@__PURE__*/ (/* unused pure expression or super */ null && (fixedBase64url(64))); +// SHA512 (64 bytes): base64 = 88 chars total (86 + "==") +const sha512_hex = /^[0-9a-fA-F]{128}$/; +const sha512_base64 = /*@__PURE__*/ (/* unused pure expression or super */ null && (fixedBase64(86, "=="))); +const sha512_base64url = /*@__PURE__*/ (/* unused pure expression or super */ null && (fixedBase64url(86))); + +// import { $ZodType } from "./schemas.js"; + + + +const $ZodCheck = /*@__PURE__*/ $constructor("$ZodCheck", (inst, def) => { + var _a; + inst._zod ?? (inst._zod = {}); + inst._zod.def = def; + (_a = inst._zod).onattach ?? (_a.onattach = []); +}); +/** Default `when` for size-based checks: run only on non-nullish values with a `size`. */ +const _whenHasSize = (payload) => { + const val = payload.value; + return !util.nullish(val) && val.size !== undefined; +}; +/** Default `when` for length-based checks: run only on non-nullish values with a `length`. */ +const _whenHasLength = (payload) => { + const val = payload.value; + return !nullish(val) && val.length !== undefined; +}; +const numericOriginMap = { + number: "number", + bigint: "bigint", + object: "date", +}; +const $ZodCheckLessThan = /*@__PURE__*/ $constructor("$ZodCheckLessThan", (inst, def) => { + $ZodCheck.init(inst, def); + const origin = numericOriginMap[typeof def.value]; + inst._zod.onattach.push((inst) => { + const bag = inst._zod.bag; + const curr = (def.inclusive ? bag.maximum : bag.exclusiveMaximum) ?? Number.POSITIVE_INFINITY; + if (def.value < curr) { + if (def.inclusive) + bag.maximum = def.value; + else + bag.exclusiveMaximum = def.value; + } + }); + inst._zod.check = (payload) => { + if (def.inclusive ? payload.value <= def.value : payload.value < def.value) { + return; + } + payload.issues.push({ + origin: numericOriginMap[typeof payload.value] ?? origin, + code: "too_big", + maximum: typeof def.value === "object" ? def.value.getTime() : def.value, + input: payload.value, + inclusive: def.inclusive, + inst, + continue: !def.abort, + }); + }; +}); +const $ZodCheckGreaterThan = /*@__PURE__*/ $constructor("$ZodCheckGreaterThan", (inst, def) => { + $ZodCheck.init(inst, def); + const origin = numericOriginMap[typeof def.value]; + inst._zod.onattach.push((inst) => { + const bag = inst._zod.bag; + const curr = (def.inclusive ? bag.minimum : bag.exclusiveMinimum) ?? Number.NEGATIVE_INFINITY; + if (def.value > curr) { + if (def.inclusive) + bag.minimum = def.value; + else + bag.exclusiveMinimum = def.value; + } + }); + inst._zod.check = (payload) => { + if (def.inclusive ? payload.value >= def.value : payload.value > def.value) { + return; + } + payload.issues.push({ + origin: numericOriginMap[typeof payload.value] ?? origin, + code: "too_small", + minimum: typeof def.value === "object" ? def.value.getTime() : def.value, + input: payload.value, + inclusive: def.inclusive, + inst, + continue: !def.abort, + }); + }; +}); +const $ZodCheckMultipleOf = +/*@__PURE__*/ $constructor("$ZodCheckMultipleOf", (inst, def) => { + $ZodCheck.init(inst, def); + inst._zod.onattach.push((inst) => { + var _a; + (_a = inst._zod.bag).multipleOf ?? (_a.multipleOf = def.value); + }); + inst._zod.check = (payload) => { + if (typeof payload.value !== typeof def.value) + throw new Error("Cannot mix number and bigint in multiple_of check."); + const isMultiple = typeof payload.value === "bigint" + ? // `value % 0n` throws, and nothing is a multiple of zero — the number branch already fails this way via NaN + def.value !== BigInt(0) && payload.value % def.value === BigInt(0) + : floatSafeRemainder(payload.value, def.value) === 0; + if (isMultiple) + return; + payload.issues.push({ + origin: typeof payload.value, + code: "not_multiple_of", + divisor: def.value, + input: payload.value, + inst, + continue: !def.abort, + }); + }; +}); +const $ZodCheckNumberFormat = /*@__PURE__*/ $constructor("$ZodCheckNumberFormat", (inst, def) => { + $ZodCheck.init(inst, def); // no format checks + def.format = def.format || "float64"; + const isInt = def.format?.includes("int"); + const origin = isInt ? "int" : "number"; + const [minimum, maximum] = NUMBER_FORMAT_RANGES[def.format]; + inst._zod.onattach.push((inst) => { + const bag = inst._zod.bag; + bag.format = def.format; + bag.minimum = minimum; + bag.maximum = maximum; + if (isInt) + bag.pattern = integer; + }); + inst._zod.check = (payload) => { + const input = payload.value; + if (isInt) { + if (!Number.isInteger(input)) { + // invalid_format issue + // payload.issues.push({ + // expected: def.format, + // format: def.format, + // code: "invalid_format", + // input, + // inst, + // }); + // invalid_type issue + payload.issues.push({ + expected: origin, + format: def.format, + code: "invalid_type", + continue: false, + input, + inst, + }); + return; + // not_multiple_of issue + // payload.issues.push({ + // code: "not_multiple_of", + // origin: "number", + // input, + // inst, + // divisor: 1, + // }); + } + if (!Number.isSafeInteger(input)) { + if (input > 0) { + // too_big + payload.issues.push({ + input, + code: "too_big", + maximum: Number.MAX_SAFE_INTEGER, + note: "Integers must be within the safe integer range.", + inst, + origin, + inclusive: true, + continue: !def.abort, + }); + } + else { + // too_small + payload.issues.push({ + input, + code: "too_small", + minimum: Number.MIN_SAFE_INTEGER, + note: "Integers must be within the safe integer range.", + inst, + origin, + inclusive: true, + continue: !def.abort, + }); + } + return; + } + } + if (input < minimum) { + payload.issues.push({ + origin: "number", + input, + code: "too_small", + minimum, + inclusive: true, + inst, + continue: !def.abort, + }); + } + if (input > maximum) { + payload.issues.push({ + origin: "number", + input, + code: "too_big", + maximum, + inclusive: true, + inst, + continue: !def.abort, + }); + } + }; +}); +const $ZodCheckBigIntFormat = /*@__PURE__*/ (/* unused pure expression or super */ null && (core.$constructor("$ZodCheckBigIntFormat", (inst, def) => { + $ZodCheck.init(inst, def); // no format checks + const [minimum, maximum] = util.BIGINT_FORMAT_RANGES[def.format]; + inst._zod.onattach.push((inst) => { + const bag = inst._zod.bag; + bag.format = def.format; + bag.minimum = minimum; + bag.maximum = maximum; + }); + inst._zod.check = (payload) => { + const input = payload.value; + if (input < minimum) { + payload.issues.push({ + origin: "bigint", + input, + code: "too_small", + minimum: minimum, + inclusive: true, + inst, + continue: !def.abort, + }); + } + if (input > maximum) { + payload.issues.push({ + origin: "bigint", + input, + code: "too_big", + maximum, + inclusive: true, + inst, + continue: !def.abort, + }); + } + }; +}))); +const $ZodCheckMaxSize = /*@__PURE__*/ (/* unused pure expression or super */ null && (core.$constructor("$ZodCheckMaxSize", (inst, def) => { + var _a; + $ZodCheck.init(inst, def); + (_a = inst._zod.def).when ?? (_a.when = _whenHasSize); + inst._zod.onattach.push((inst) => { + const curr = (inst._zod.bag.maximum ?? Number.POSITIVE_INFINITY); + if (def.maximum < curr) + inst._zod.bag.maximum = def.maximum; + }); + inst._zod.check = (payload) => { + const input = payload.value; + const size = input.size; + if (size <= def.maximum) + return; + payload.issues.push({ + origin: util.getSizableOrigin(input), + code: "too_big", + maximum: def.maximum, + inclusive: true, + input, + inst, + continue: !def.abort, + }); + }; +}))); +const $ZodCheckMinSize = /*@__PURE__*/ (/* unused pure expression or super */ null && (core.$constructor("$ZodCheckMinSize", (inst, def) => { + var _a; + $ZodCheck.init(inst, def); + (_a = inst._zod.def).when ?? (_a.when = _whenHasSize); + inst._zod.onattach.push((inst) => { + const curr = (inst._zod.bag.minimum ?? Number.NEGATIVE_INFINITY); + if (def.minimum > curr) + inst._zod.bag.minimum = def.minimum; + }); + inst._zod.check = (payload) => { + const input = payload.value; + const size = input.size; + if (size >= def.minimum) + return; + payload.issues.push({ + origin: util.getSizableOrigin(input), + code: "too_small", + minimum: def.minimum, + inclusive: true, + input, + inst, + continue: !def.abort, + }); + }; +}))); +const $ZodCheckSizeEquals = /*@__PURE__*/ (/* unused pure expression or super */ null && (core.$constructor("$ZodCheckSizeEquals", (inst, def) => { + var _a; + $ZodCheck.init(inst, def); + (_a = inst._zod.def).when ?? (_a.when = _whenHasSize); + inst._zod.onattach.push((inst) => { + const bag = inst._zod.bag; + bag.minimum = def.size; + bag.maximum = def.size; + bag.size = def.size; + }); + inst._zod.check = (payload) => { + const input = payload.value; + const size = input.size; + if (size === def.size) + return; + const tooBig = size > def.size; + payload.issues.push({ + origin: util.getSizableOrigin(input), + ...(tooBig ? { code: "too_big", maximum: def.size } : { code: "too_small", minimum: def.size }), + inclusive: true, + exact: true, + input: payload.value, + inst, + continue: !def.abort, + }); + }; +}))); +const $ZodCheckMaxLength = /*@__PURE__*/ $constructor("$ZodCheckMaxLength", (inst, def) => { + var _a; + $ZodCheck.init(inst, def); + (_a = inst._zod.def).when ?? (_a.when = _whenHasLength); + inst._zod.onattach.push((inst) => { + const curr = (inst._zod.bag.maximum ?? Number.POSITIVE_INFINITY); + if (def.maximum < curr) + inst._zod.bag.maximum = def.maximum; + }); + inst._zod.check = (payload) => { + const input = payload.value; + const units = input.length; + // Strings are measured in Unicode code points, not UTF-16 units. A code point is at most two units, so a string that already fits in units fits in code points; only an overflow has to be counted. + const length = typeof input === "string" && units > def.maximum ? codePointLength(input) : units; + if (length <= def.maximum) + return; + const origin = getLengthableOrigin(input); + payload.issues.push({ + origin, + code: "too_big", + maximum: def.maximum, + inclusive: true, + input, + inst, + continue: !def.abort, + }); + }; +}); +const $ZodCheckMinLength = /*@__PURE__*/ $constructor("$ZodCheckMinLength", (inst, def) => { + var _a; + $ZodCheck.init(inst, def); + (_a = inst._zod.def).when ?? (_a.when = _whenHasLength); + inst._zod.onattach.push((inst) => { + const curr = (inst._zod.bag.minimum ?? Number.NEGATIVE_INFINITY); + if (def.minimum > curr) + inst._zod.bag.minimum = def.minimum; + }); + inst._zod.check = (payload) => { + const input = payload.value; + const units = input.length; + // A code point is one or two UTF-16 units, so fewer units than the floor can never reach it and twice the floor always clears it. Only in between is the exact count in doubt. + const length = typeof input === "string" && units >= def.minimum && units < def.minimum * 2 + ? codePointLength(input) + : units; + if (length >= def.minimum) + return; + const origin = getLengthableOrigin(input); + payload.issues.push({ + origin, + code: "too_small", + minimum: def.minimum, + inclusive: true, + input, + inst, + continue: !def.abort, + }); + }; +}); +const $ZodCheckLengthEquals = /*@__PURE__*/ $constructor("$ZodCheckLengthEquals", (inst, def) => { + var _a; + $ZodCheck.init(inst, def); + (_a = inst._zod.def).when ?? (_a.when = _whenHasLength); + inst._zod.onattach.push((inst) => { + const bag = inst._zod.bag; + bag.minimum = def.length; + bag.maximum = def.length; + bag.length = def.length; + }); + inst._zod.check = (payload) => { + const input = payload.value; + const units = input.length; + // A code point is one or two UTF-16 units, so outside `[length, length * 2]` units the target is missed either way — and missed in the same direction in both measures. + const length = typeof input === "string" && units >= def.length && units <= def.length * 2 + ? codePointLength(input) + : units; + if (length === def.length) + return; + const origin = getLengthableOrigin(input); + const tooBig = length > def.length; + payload.issues.push({ + origin, + ...(tooBig ? { code: "too_big", maximum: def.length } : { code: "too_small", minimum: def.length }), + inclusive: true, + exact: true, + input: payload.value, + inst, + continue: !def.abort, + }); + }; +}); +const $ZodCheckStringFormat = /*@__PURE__*/ $constructor("$ZodCheckStringFormat", (inst, def) => { + var _a, _b; + $ZodCheck.init(inst, def); + inst._zod.onattach.push((inst) => { + const bag = inst._zod.bag; + bag.format = def.format; + if (def.pattern) { + bag.patterns ?? (bag.patterns = new Set()); + bag.patterns.add(def.pattern); + } + }); + if (def.pattern) + (_a = inst._zod).check ?? (_a.check = (payload) => { + def.pattern.lastIndex = 0; + if (def.pattern.test(payload.value)) + return; + payload.issues.push({ + origin: "string", + code: "invalid_format", + format: def.format, + input: payload.value, + ...(def.pattern ? { pattern: def.pattern.toString() } : {}), + inst, + continue: !def.abort, + }); + }); + else + (_b = inst._zod).check ?? (_b.check = () => { }); +}); +const $ZodCheckRegex = /*@__PURE__*/ $constructor("$ZodCheckRegex", (inst, def) => { + $ZodCheckStringFormat.init(inst, def); + inst._zod.check = (payload) => { + def.pattern.lastIndex = 0; + if (def.pattern.test(payload.value)) + return; + payload.issues.push({ + origin: "string", + code: "invalid_format", + format: "regex", + input: payload.value, + pattern: def.pattern.toString(), + inst, + continue: !def.abort, + }); + }; +}); +const $ZodCheckLowerCase = /*@__PURE__*/ $constructor("$ZodCheckLowerCase", (inst, def) => { + def.pattern ?? (def.pattern = lowercase); + $ZodCheckStringFormat.init(inst, def); +}); +const $ZodCheckUpperCase = /*@__PURE__*/ $constructor("$ZodCheckUpperCase", (inst, def) => { + def.pattern ?? (def.pattern = uppercase); + $ZodCheckStringFormat.init(inst, def); +}); +const $ZodCheckIncludes = /*@__PURE__*/ $constructor("$ZodCheckIncludes", (inst, def) => { + $ZodCheck.init(inst, def); + const escapedRegex = escapeRegex(def.includes); + // `String.prototype.includes(sub, position)` matches `sub` at `position` + // OR LATER, so the pattern must allow at least `position` leading chars + // (`{N,}`), not exactly `position` chars (`{N}`). + const pattern = new RegExp(typeof def.position === "number" ? `^.{${def.position},}${escapedRegex}` : escapedRegex); + def.pattern = pattern; + inst._zod.onattach.push((inst) => { + const bag = inst._zod.bag; + bag.patterns ?? (bag.patterns = new Set()); + bag.patterns.add(pattern); + }); + inst._zod.check = (payload) => { + if (payload.value.includes(def.includes, def.position)) + return; + payload.issues.push({ + origin: "string", + code: "invalid_format", + format: "includes", + includes: def.includes, + input: payload.value, + inst, + continue: !def.abort, + }); + }; +}); +const $ZodCheckStartsWith = /*@__PURE__*/ $constructor("$ZodCheckStartsWith", (inst, def) => { + $ZodCheck.init(inst, def); + const pattern = new RegExp(`^${escapeRegex(def.prefix)}.*`); + def.pattern ?? (def.pattern = pattern); + inst._zod.onattach.push((inst) => { + const bag = inst._zod.bag; + bag.patterns ?? (bag.patterns = new Set()); + bag.patterns.add(pattern); + }); + inst._zod.check = (payload) => { + if (payload.value.startsWith(def.prefix)) + return; + payload.issues.push({ + origin: "string", + code: "invalid_format", + format: "starts_with", + prefix: def.prefix, + input: payload.value, + inst, + continue: !def.abort, + }); + }; +}); +const $ZodCheckEndsWith = /*@__PURE__*/ $constructor("$ZodCheckEndsWith", (inst, def) => { + $ZodCheck.init(inst, def); + const pattern = new RegExp(`.*${escapeRegex(def.suffix)}$`); + def.pattern ?? (def.pattern = pattern); + inst._zod.onattach.push((inst) => { + const bag = inst._zod.bag; + bag.patterns ?? (bag.patterns = new Set()); + bag.patterns.add(pattern); + }); + inst._zod.check = (payload) => { + if (payload.value.endsWith(def.suffix)) + return; + payload.issues.push({ + origin: "string", + code: "invalid_format", + format: "ends_with", + suffix: def.suffix, + input: payload.value, + inst, + continue: !def.abort, + }); + }; +}); +/////////////////////////////////// +///// $ZodCheckProperty ///// +/////////////////////////////////// +function handleCheckPropertyResult(result, payload, property) { + if (result.issues.length) { + payload.issues.push(...util.prefixIssues(property, result.issues)); + } +} +const $ZodCheckProperty = /*@__PURE__*/ (/* unused pure expression or super */ null && (core.$constructor("$ZodCheckProperty", (inst, def) => { + $ZodCheck.init(inst, def); + inst._zod.check = (payload) => { + const result = def.schema._zod.run({ + value: payload.value[def.property], + issues: [], + }, {}); + if (result instanceof Promise) { + return result.then((result) => handleCheckPropertyResult(result, payload, def.property)); + } + handleCheckPropertyResult(result, payload, def.property); + return; + }; +}))); +const $ZodCheckMimeType = /*@__PURE__*/ (/* unused pure expression or super */ null && (core.$constructor("$ZodCheckMimeType", (inst, def) => { + $ZodCheck.init(inst, def); + const mimeSet = new Set(def.mime); + inst._zod.onattach.push((inst) => { + inst._zod.bag.mime = def.mime; + }); + inst._zod.check = (payload) => { + if (mimeSet.has(payload.value.type)) + return; + payload.issues.push({ + code: "invalid_value", + values: def.mime, + input: payload.value.type, + inst, + continue: !def.abort, + }); + }; +}))); +const $ZodCheckOverwrite = /*@__PURE__*/ $constructor("$ZodCheckOverwrite", (inst, def) => { + $ZodCheck.init(inst, def); + inst._zod.check = (payload) => { + payload.value = def.tx(payload.value); + }; +}); + +class Doc { + constructor(args = [], closed = {}) { + this.content = []; + this.indent = 0; + this.args = args; + this.closed = closed; + } + indented(fn) { + this.indent += 1; + fn(this); + this.indent -= 1; + } + write(arg) { + if (typeof arg === "function") { + arg(this, { execution: "sync" }); + arg(this, { execution: "async" }); + return; + } + const content = arg; + const lines = content.split("\n").filter((x) => x); + const minIndent = Math.min(...lines.map((x) => x.length - x.trimStart().length)); + const dedented = lines.map((x) => x.slice(minIndent)).map((x) => " ".repeat(this.indent * 2) + x); + for (const line of dedented) { + this.content.push(line); + } + } + compile() { + const F = Function; + const content = this?.content ?? [``]; + const factory = new F(...Object.keys(this.closed), `return function (${this.args.join(", ")}) {\n${content.join("\n")}\n};`); + return factory(...Object.values(this.closed)); + } +} + + + +/* Computing the message eagerly is expensive (pretty-printed JSON of all + * issues), so defer it until first read. The accessor functions and + * descriptors are shared across instances to keep error construction + * cheap; the computed message is cached on the internals object. The + * setter preserves plain assignment semantics for consumers that + * overwrite `message`. */ +function _getMessage() { + const internals = this._zod; + internals.message ?? (internals.message = JSON.stringify(internals.def, jsonStringifyReplacer, 2)); + return internals.message; +} +function _setMessage(value) { + this._zod.message = value; +} +const _messageDesc = { + get: _getMessage, + set: _setMessage, + enumerable: true, + configurable: true, +}; +const errors_zodDesc = { value: undefined, enumerable: false }; +const _issuesDesc = { value: undefined, enumerable: false }; +/* Prototypes that already carry the lazy `toString`. Seeded with the + * intrinsics so that `init` on a foreign object — it accepts any object — + * can never install an accessor onto a prototype we do not own. */ +const _installedToString = /* @__PURE__ */ new WeakSet([Object.prototype, Error.prototype]); +const errors_initializer = (inst, def) => { + inst.name = "$ZodError"; + errors_zodDesc.value = inst._zod; + Object.defineProperty(inst, "_zod", errors_zodDesc); + _issuesDesc.value = def; + Object.defineProperty(inst, "issues", _issuesDesc); + // Clear the shared slots; a retained `value` pins the last error's issues. + errors_zodDesc.value = undefined; + _issuesDesc.value = undefined; + Object.defineProperty(inst, "message", _messageDesc); + /* `toString` lives as a non-enumerable lazy getter on the shared + * prototype; on first access it caches a per-instance closure so + * detached usage still works. */ + const proto = Object.getPrototypeOf(inst); + if (!_installedToString.has(proto)) { + _installedToString.add(proto); + Object.defineProperty(proto, "toString", { + configurable: true, + enumerable: false, + get() { + const value = () => this.message; + Object.defineProperty(this, "toString", { value, configurable: true, writable: true }); + return value; + }, + set(value) { + Object.defineProperty(this, "toString", { value, configurable: true, writable: true }); + }, + }); + } +}; +const $ZodError = $constructor("$ZodError", errors_initializer); +const $ZodRealError = $constructor("$ZodError", errors_initializer, undefined, { + Parent: Error, +}); +/** Get-or-create `obj[key]` as an own data property. A path segment naming an inherited member + * ("toString", "constructor") would otherwise read through to the prototype, and assigning + * "__proto__" would hit the setter instead of creating a key. */ +function errors_node(obj, key, make) { + if (!Object.prototype.hasOwnProperty.call(obj, key)) { + if (key === "__proto__") { + Object.defineProperty(obj, key, { value: make(), writable: true, enumerable: true, configurable: true }); + } + else { + obj[key] = make(); + } + } + return obj[key]; +} +function flattenError(error, mapper = (issue) => issue.message) { + const fieldErrors = {}; + const formErrors = []; + for (const sub of error.issues) { + if (sub.path.length > 0) { + errors_node(fieldErrors, sub.path[0], () => []).push(mapper(sub)); + } + else { + formErrors.push(mapper(sub)); + } + } + return { formErrors, fieldErrors }; +} +function formatError(error, mapper = (issue) => issue.message) { + const fieldErrors = { _errors: [] }; + const processError = (error, path = []) => { + for (const issue of error.issues) { + if (issue.code === "invalid_union" && issue.errors.length) { + issue.errors.map((issues) => processError({ issues }, [...path, ...issue.path])); + } + else if (issue.code === "invalid_key") { + processError({ issues: issue.issues }, [...path, ...issue.path]); + } + else if (issue.code === "invalid_element") { + processError({ issues: issue.issues }, [...path, ...issue.path]); + } + else { + const fullpath = [...path, ...issue.path]; + if (fullpath.length === 0) { + fieldErrors._errors.push(mapper(issue)); + } + else { + let curr = fieldErrors; + let i = 0; + while (i < fullpath.length) { + const el = fullpath[i]; + const terminal = i === fullpath.length - 1; + // `_errors` is reserved by this legacy format, so merge a matching path segment into the current node instead of treating its array as a child. + if (el === "_errors") { + if (terminal) + curr._errors.push(mapper(issue)); + i++; + continue; + } + // A path element may collide with an inherited property name such as + // "__proto__" or "constructor". Truthiness checks read the prototype + // (so no node is created, then ._errors.push throws), and bracket + // assignment of "__proto__" hits the setter instead of creating an + // own key. Guard the read with hasOwnProperty and create the node + // with defineProperty so any path element becomes a real own key. + if (!Object.prototype.hasOwnProperty.call(curr, el)) { + Object.defineProperty(curr, el, { + value: { _errors: [] }, + enumerable: true, + writable: true, + configurable: true, + }); + } + const node = curr[el]; + if (terminal) { + node._errors.push(mapper(issue)); + } + curr = node; + i++; + } + } + } + } + }; + processError(error); + return fieldErrors; +} +function treeifyError(error, mapper = (issue) => issue.message) { + const result = { errors: [] }; + const processError = (error, path = []) => { + var _a; + for (const issue of error.issues) { + if (issue.code === "invalid_union" && issue.errors.length) { + // regular union error + issue.errors.map((issues) => processError({ issues }, [...path, ...issue.path])); + } + else if (issue.code === "invalid_key") { + processError({ issues: issue.issues }, [...path, ...issue.path]); + } + else if (issue.code === "invalid_element") { + processError({ issues: issue.issues }, [...path, ...issue.path]); + } + else { + const fullpath = [...path, ...issue.path]; + if (fullpath.length === 0) { + result.errors.push(mapper(issue)); + continue; + } + let curr = result; + let i = 0; + while (i < fullpath.length) { + const el = fullpath[i]; + const terminal = i === fullpath.length - 1; + if (typeof el === "string") { + curr.properties ?? (curr.properties = {}); + // el may collide with an inherited property name ("__proto__", + // "constructor", ...); ??= reads the prototype so the node is never + // created and curr.errors.push throws. Guard with hasOwnProperty and + // create the node with defineProperty so "__proto__" becomes a real + // own key rather than invoking the prototype setter. + if (!Object.prototype.hasOwnProperty.call(curr.properties, el)) { + Object.defineProperty(curr.properties, el, { + value: { errors: [] }, + enumerable: true, + writable: true, + configurable: true, + }); + } + curr = curr.properties[el]; + } + else { + curr.items ?? (curr.items = []); + (_a = curr.items)[el] ?? (_a[el] = { errors: [] }); + curr = curr.items[el]; + } + if (terminal) { + curr.errors.push(mapper(issue)); + } + i++; + } + } + } + }; + processError(error); + return result; +} +/** Format a ZodError as a human-readable string in the following form. + * + * From + * + * ```ts + * ZodError { + * issues: [ + * { + * expected: 'string', + * code: 'invalid_type', + * path: [ 'username' ], + * message: 'Invalid input: expected string' + * }, + * { + * expected: 'number', + * code: 'invalid_type', + * path: [ 'favoriteNumbers', 1 ], + * message: 'Invalid input: expected number' + * } + * ]; + * } + * ``` + * + * to + * + * ``` + * username + * ✖ Expected number, received string at "username + * favoriteNumbers[0] + * ✖ Invalid input: expected number + * ``` + */ +function toDotPath(_path) { + const segs = []; + const path = _path.map((seg) => (typeof seg === "object" ? seg.key : seg)); + for (const seg of path) { + if (typeof seg === "number") + segs.push(`[${seg}]`); + else if (typeof seg === "symbol") + segs.push(`[${JSON.stringify(String(seg))}]`); + else if (/[^\w$]/.test(seg)) + segs.push(`[${JSON.stringify(seg)}]`); + else { + if (segs.length) + segs.push("."); + segs.push(seg); + } + } + return segs.join(""); +} +function prettifyError(error) { + const lines = []; + // sort by path length + const issues = [...error.issues].sort((a, b) => (a.path ?? []).length - (b.path ?? []).length); + // Process each issue + for (const issue of issues) { + lines.push(`✖ ${issue.message}`); + if (issue.path?.length) + lines.push(` → at ${toDotPath(issue.path)}`); + } + // Convert Map to formatted string + return lines.join("\n"); +} + + + + +// Always both keys, so the `_params` read site in `_parse` sees one object shape rather than two. +function finalizeParams(callee, params) { + return { callee: params?.callee ?? callee, Err: params?.Err }; +} +const parse_parse = (_Err) => { + const fn = (schema, value, _ctx, _params) => { + const ctx = _ctx ? { ..._ctx, async: false } : { async: false }; + const result = schema._zod.run({ value, issues: [] }, ctx); + if (result instanceof Promise) { + throw new $ZodAsyncError(); + } + if (result.issues.length) { + const e = new (_params?.Err ?? _Err)(result.issues.map((iss) => finalizeIssue(iss, ctx, core_config()))); + captureStackTrace(e, _params?.callee ?? fn); + throw e; + } + return result.value; + }; + return fn; +}; +const core_parse_parse = /* @__PURE__*/ parse_parse($ZodRealError); +const parse_parseAsync = (_Err) => { + const fn = async (schema, value, _ctx, params) => { + const ctx = _ctx ? { ..._ctx, async: true } : { async: true }; + let result = schema._zod.run({ value, issues: [] }, ctx); + if (result instanceof Promise) + result = await result; + if (result.issues.length) { + const e = new (params?.Err ?? _Err)(result.issues.map((iss) => finalizeIssue(iss, ctx, core_config()))); + captureStackTrace(e, params?.callee ?? fn); + throw e; + } + return result.value; + }; + return fn; +}; +const core_parse_parseAsync = /* @__PURE__*/ parse_parseAsync($ZodRealError); +const _safeParse = (_Err) => (schema, value, _ctx) => { + const ctx = _ctx ? { ..._ctx, async: false } : { async: false }; + const result = schema._zod.run({ value, issues: [] }, ctx); + if (result instanceof Promise) { + throw new $ZodAsyncError(); + } + return result.issues.length + ? { + success: false, + error: new (_Err ?? $ZodError)(result.issues.map((iss) => finalizeIssue(iss, ctx, core_config()))), + } + : { success: true, data: result.value }; +}; +const safeParse = /* @__PURE__*/ _safeParse($ZodRealError); +const _safeParseAsync = (_Err) => async (schema, value, _ctx) => { + const ctx = _ctx ? { ..._ctx, async: true } : { async: true }; + let result = schema._zod.run({ value, issues: [] }, ctx); + if (result instanceof Promise) + result = await result; + return result.issues.length + ? { + success: false, + error: new _Err(result.issues.map((iss) => finalizeIssue(iss, ctx, core_config()))), + } + : { success: true, data: result.value }; +}; +const safeParseAsync = /* @__PURE__*/ _safeParseAsync($ZodRealError); +// registry mirrors of the compiler's sentinels, so this module never imports the compiler +const COMPILE_INVALID = /* @__PURE__ */ (/* unused pure expression or super */ null && (Symbol.for("zod.compile.invalid"))); +const COMPILE_FALLBACK = /* @__PURE__ */ (/* unused pure expression or super */ null && (Symbol.for("zod.compile.fallback"))); +// Deliberately tiny, because v8 will not inline a body carrying the fallback's object literals and throw. Everything that is not the compiled happy path lives in validateFallback, and that split is worth ~35% on a compiled schema. +const parse_validate = ((schema, value, _ctx) => { + const validator = schema._zod.bag.validator; + if (validator !== undefined && validator(value) !== COMPILE_INVALID) + return true; + return validateFallback(schema, value, _ctx); +}); +function validateFallback(schema, value, _ctx) { + const ctx = _ctx ? { ..._ctx, async: false } : { async: false }; + const fallbackRun = schema._zod.bag.fallbackRun; + let result; + if (fallbackRun) { + // skip nested fast paths on the fallback, so user callbacks keep the at-most-twice bound + ctx[COMPILE_FALLBACK] = true; + result = fallbackRun({ value, issues: [] }, ctx); + } + else { + result = schema._zod.run({ value, issues: [] }, ctx); + } + if (result instanceof Promise) { + throw new core.$ZodAsyncError(); + } + return result.issues.length === 0; +} +// no fast path: the compiler keeps async parses on the runtime, because a promise-returning callback that is not declared async compiles to a throw +const parse_validateAsync = async (schema, value, _ctx) => { + const ctx = _ctx ? { ..._ctx, async: true } : { async: true }; + let result = schema._zod.run({ value, issues: [] }, ctx); + if (result instanceof Promise) + result = await result; + return result.issues.length === 0; +}; +const parse_encode = (_Err) => { + const parse = parse_parse(_Err); + const fn = (schema, value, _ctx, _params) => { + const ctx = _ctx ? { ..._ctx, direction: "backward" } : { direction: "backward" }; + return parse(schema, value, ctx, finalizeParams(fn, _params)); + }; + return fn; +}; +const encode = /* @__PURE__*/ parse_encode($ZodRealError); +const parse_decode = (_Err) => { + const parse = parse_parse(_Err); + const fn = (schema, value, _ctx, _params) => { + return parse(schema, value, _ctx, finalizeParams(fn, _params)); + }; + return fn; +}; +const decode = /* @__PURE__*/ parse_decode($ZodRealError); +const parse_encodeAsync = (_Err) => { + const parseAsync = parse_parseAsync(_Err); + const fn = async (schema, value, _ctx, _params) => { + const ctx = _ctx ? { ..._ctx, direction: "backward" } : { direction: "backward" }; + return (await parseAsync(schema, value, ctx, finalizeParams(fn, _params))); + }; + return fn; +}; +const encodeAsync = /* @__PURE__*/ parse_encodeAsync($ZodRealError); +const parse_decodeAsync = (_Err) => { + const parseAsync = parse_parseAsync(_Err); + const fn = async (schema, value, _ctx, _params) => { + return await parseAsync(schema, value, _ctx, finalizeParams(fn, _params)); + }; + return fn; +}; +const decodeAsync = /* @__PURE__*/ parse_decodeAsync($ZodRealError); +const _safeEncode = (_Err) => (schema, value, _ctx) => { + const ctx = _ctx ? { ..._ctx, direction: "backward" } : { direction: "backward" }; + return _safeParse(_Err)(schema, value, ctx); +}; +const safeEncode = /* @__PURE__*/ _safeEncode($ZodRealError); +const _safeDecode = (_Err) => (schema, value, _ctx) => { + return _safeParse(_Err)(schema, value, _ctx); +}; +const safeDecode = /* @__PURE__*/ _safeDecode($ZodRealError); +const _safeEncodeAsync = (_Err) => async (schema, value, _ctx) => { + const ctx = _ctx ? { ..._ctx, direction: "backward" } : { direction: "backward" }; + return _safeParseAsync(_Err)(schema, value, ctx); +}; +const safeEncodeAsync = /* @__PURE__*/ _safeEncodeAsync($ZodRealError); +const _safeDecodeAsync = (_Err) => async (schema, value, _ctx) => { + return _safeParseAsync(_Err)(schema, value, _ctx); +}; +const safeDecodeAsync = /* @__PURE__*/ _safeDecodeAsync($ZodRealError); + +const versions_version = { + major: 4, + minor: 5, + patch: 4, +}; + + + + + + + + +const $ZodType = /*@__PURE__*/ $constructor("$ZodType", (inst, def) => { + var _a; + inst ?? (inst = {}); + inst._zod.def = def; // set _def property + inst._zod.bag = inst._zod.bag || {}; // initialize _bag object + inst._zod.version = versions_version; + const defChecks = inst._zod.def.checks; + // if inst is itself a checks.$ZodCheck, run it as a check + const checks = inst._zod.traits.has("$ZodCheck") + ? [inst, ...(defChecks ?? [])] + : defChecks?.length + ? [...defChecks] + : []; + for (const ch of checks) { + for (const fn of ch._zod.onattach) { + fn(inst); + } + } + if (checks.length === 0) { + // deferred initializer inst._zod.parse is not yet defined + (_a = inst._zod).deferred ?? (_a.deferred = []); + inst._zod.deferred?.push(() => { + inst._zod.run = inst._zod.parse; + }); + } + else { + const runChecks = (payload, checks, ctx) => { + if (payload.memo) + return payload; + let isAborted = aborted(payload); + let asyncResult; + for (const ch of checks) { + if (ch._zod.def.when) { + if (explicitlyAborted(payload)) + continue; + const shouldRun = ch._zod.def.when(payload); + if (!shouldRun) + continue; + } + else if (isAborted) { + continue; + } + const currLen = payload.issues.length; + const _ = ch._zod.check(payload); + if (_ instanceof Promise && ctx?.async === false) { + throw new $ZodAsyncError(); + } + if (asyncResult || _ instanceof Promise) { + asyncResult = (asyncResult ?? Promise.resolve()).then(async () => { + await _; + const nextLen = payload.issues.length; + if (nextLen === currLen) + return; + attachSchema(payload.issues, currLen, inst); + if (!isAborted) + isAborted = aborted(payload, currLen); + }); + } + else { + const nextLen = payload.issues.length; + if (nextLen === currLen) + continue; + attachSchema(payload.issues, currLen, inst); + if (!isAborted) + isAborted = aborted(payload, currLen); + } + } + if (asyncResult) { + return asyncResult.then(() => { + return payload; + }); + } + return payload; + }; + const handleCanaryResult = (canary, payload, ctx) => { + // abort if the canary is aborted + if (aborted(canary)) { + canary.aborted = true; + return canary; + } + // run checks first, then + const checkResult = runChecks(payload, checks, ctx); + if (checkResult instanceof Promise) { + if (ctx.async === false) + throw new $ZodAsyncError(); + return checkResult.then((checkResult) => inst._zod.parse(checkResult, ctx)); + } + return inst._zod.parse(checkResult, ctx); + }; + inst._zod.run = (payload, ctx) => { + if (ctx.skipChecks) { + return inst._zod.parse(payload, ctx); + } + if (ctx.direction === "backward") { + // run canary initial pass (no checks) + const canary = inst._zod.parse({ value: payload.value, issues: [] }, { ...ctx, skipChecks: true }); + if (canary instanceof Promise) { + return canary.then((canary) => { + return handleCanaryResult(canary, payload, ctx); + }); + } + return handleCanaryResult(canary, payload, ctx); + } + // forward + const result = inst._zod.parse(payload, ctx); + if (result instanceof Promise) { + if (ctx.async === false) + throw new $ZodAsyncError(); + return result.then((result) => runChecks(result, checks, ctx)); + } + return runChecks(result, checks, ctx); + }; + } +}, { + // Wrappers extend this by installing a richer factory over it; reading it eagerly would defeat the laziness. + get "~standard"() { + return hide(this, "~standard", standardProps(this)); + }, + set "~standard"(value) { + util_own(this, "~standard", value); + }, +}); +/** The Standard Schema surface for `inst`. Shared so wrappers can extend it without forcing it. */ +const toStandardResult = (r) => r.success ? { value: r.data } : { issues: r.error?.issues }; +function standardProps(inst) { + return { + validate: (value) => { + try { + return toStandardResult(safeParse(inst, value)); + } + catch (_) { + return safeParseAsync(inst, value).then(toStandardResult); + } + }, + vendor: "zod", + version: 1, + }; +} + +const $ZodString = /*@__PURE__*/ $constructor("$ZodString", (inst, def) => { + $ZodType.init(inst, def); + inst._zod.pattern = [...(inst?._zod.bag?.patterns ?? [])].pop() ?? regexes_string(inst._zod.bag); + inst._zod.parse = (payload, _) => { + if (def.coerce) + try { + payload.value = String(payload.value); + } + catch (_) { } + if (typeof payload.value === "string") + return payload; + payload.issues.push({ + expected: "string", + code: "invalid_type", + input: payload.value, + inst, + }); + return payload; + }; +}); +const $ZodStringFormat = /*@__PURE__*/ $constructor("$ZodStringFormat", (inst, def) => { + // check initialization must come first + $ZodCheckStringFormat.init(inst, def); + $ZodString.init(inst, def); +}); +const $ZodGUID = /*@__PURE__*/ $constructor("$ZodGUID", (inst, def) => { + def.pattern ?? (def.pattern = guid); + $ZodStringFormat.init(inst, def); +}); +const $ZodUUID = /*@__PURE__*/ $constructor("$ZodUUID", (inst, def) => { + if (def.version) { + const versionMap = { + v1: 1, + v2: 2, + v3: 3, + v4: 4, + v5: 5, + v6: 6, + v7: 7, + v8: 8, + }; + const v = versionMap[def.version]; + if (v === undefined) + throw new Error(`Invalid UUID version: "${def.version}"`); + def.pattern ?? (def.pattern = uuid(v)); + } + else + def.pattern ?? (def.pattern = uuid()); + $ZodStringFormat.init(inst, def); +}); +const $ZodEmail = /*@__PURE__*/ $constructor("$ZodEmail", (inst, def) => { + def.pattern ?? (def.pattern = email); + $ZodStringFormat.init(inst, def); +}); +/** The `://` guard rejected the input before the URL constructor saw it. */ +const URL_BAD_FORMAT = 1; +/** The URL constructor rejected the input. */ +const URL_UNPARSEABLE = 2; +/** Parses a URL for `$ZodURL`, applying the one guard the URL constructor cannot express. Returns the parsed URL, or a code naming the stage that rejected it — the runtime needs that distinction to pick an issue note, and compiled code only needs to know it is not a URL. */ +function parseURLObject(trimmed, def) { + // When normalize is off, require :// for http/https URLs. This prevents strings like "http:example.com" or "https:/path" from being silently accepted + if (!def.normalize && def.protocol?.source === httpProtocol.source && !/^https?:\/\//i.test(trimmed)) { + return URL_BAD_FORMAT; + } + try { + // @ts-ignore + return new URL(trimmed); + } + catch { + return URL_UNPARSEABLE; + } +} +const asciiTabOrNewline = /[\t\n\r]/g; +/** The URL parser deletes every ASCII tab, LF and CR from its input before it parses, so `new URL("https://exa\nmple.com")` reports on `example.com`. Applying the same deletion to the returned value closes the half of that divergence which can move the host; the parser's other rewrite, stripping C0 controls at the edges, cannot. */ +function stripTabAndNewline(value) { + return value.replace(asciiTabOrNewline, ""); +} +function urlHostnameOk(url, hostname) { + hostname.lastIndex = 0; + return hostname.test(url.hostname); +} +function urlProtocolOk(url, protocol) { + protocol.lastIndex = 0; + return protocol.test(url.protocol.endsWith(":") ? url.protocol.slice(0, -1) : url.protocol); +} +const $ZodURL = /*@__PURE__*/ $constructor("$ZodURL", (inst, def) => { + $ZodStringFormat.init(inst, def); + inst._zod.check = (payload) => { + try { + // Trim whitespace from input + const trimmed = payload.value.trim(); + const url = parseURLObject(trimmed, def); + if (url === URL_BAD_FORMAT) { + payload.issues.push({ + code: "invalid_format", + format: "url", + note: "Invalid URL format", + input: payload.value, + inst, + continue: !def.abort, + }); + return; + } + if (url === URL_UNPARSEABLE) { + payload.issues.push({ + code: "invalid_format", + format: "url", + input: payload.value, + inst, + continue: !def.abort, + }); + return; + } + if (def.hostname && !urlHostnameOk(url, def.hostname)) { + payload.issues.push({ + code: "invalid_format", + format: "url", + note: "Invalid hostname", + pattern: def.hostname.source, + input: payload.value, + inst, + continue: !def.abort, + }); + } + if (def.protocol && !urlProtocolOk(url, def.protocol)) { + payload.issues.push({ + code: "invalid_format", + format: "url", + note: "Invalid protocol", + pattern: def.protocol.source, + input: payload.value, + inst, + continue: !def.abort, + }); + } + // Set the output value based on normalize flag + payload.value = def.normalize ? url.href : stripTabAndNewline(trimmed); + return; + } + catch (_) { + payload.issues.push({ + code: "invalid_format", + format: "url", + input: payload.value, + inst, + continue: !def.abort, + }); + } + }; +}); +const $ZodEmoji = /*@__PURE__*/ $constructor("$ZodEmoji", (inst, def) => { + def.pattern ?? (def.pattern = emoji()); + $ZodStringFormat.init(inst, def); +}); +const $ZodNanoID = /*@__PURE__*/ $constructor("$ZodNanoID", (inst, def) => { + if (def.length !== undefined && (!Number.isInteger(def.length) || def.length < 1)) + throw new Error(`Invalid nanoid length: ${def.length}`); + def.pattern ?? (def.pattern = def.length === undefined ? nanoid : nanoidOfLength(def.length)); + $ZodStringFormat.init(inst, def); +}); +/** + * @deprecated CUID v1 is deprecated by its authors due to information leakage + * (timestamps embedded in the id). Use {@link $ZodCUID2} instead. + * See https://github.com/paralleldrive/cuid. + */ +const $ZodCUID = /*@__PURE__*/ $constructor("$ZodCUID", (inst, def) => { + def.pattern ?? (def.pattern = cuid); + $ZodStringFormat.init(inst, def); +}); +const $ZodCUID2 = /*@__PURE__*/ $constructor("$ZodCUID2", (inst, def) => { + def.pattern ?? (def.pattern = cuid2); + $ZodStringFormat.init(inst, def); +}); +const $ZodULID = /*@__PURE__*/ $constructor("$ZodULID", (inst, def) => { + def.pattern ?? (def.pattern = ulid); + $ZodStringFormat.init(inst, def); +}); +const $ZodXID = /*@__PURE__*/ $constructor("$ZodXID", (inst, def) => { + def.pattern ?? (def.pattern = xid); + $ZodStringFormat.init(inst, def); +}); +const $ZodKSUID = /*@__PURE__*/ $constructor("$ZodKSUID", (inst, def) => { + def.pattern ?? (def.pattern = ksuid); + $ZodStringFormat.init(inst, def); +}); +const $ZodISODateTime = /*@__PURE__*/ $constructor("$ZodISODateTime", (inst, def) => { + def.pattern ?? (def.pattern = datetime(def)); + $ZodStringFormat.init(inst, def); + // these two drop the offset or seconds `date-time` requires — on the bag not the def, since `z.string().check(...)` lands the format on a different schema + if (def.local || def.precision === -1) { + inst._zod.bag.laxFormat = true; + inst._zod.onattach.push((s) => { + s._zod.bag.laxFormat = true; + }); + } +}); +const $ZodISODate = /*@__PURE__*/ $constructor("$ZodISODate", (inst, def) => { + def.pattern ?? (def.pattern = regexes_date); + $ZodStringFormat.init(inst, def); +}); +const $ZodISOTime = /*@__PURE__*/ $constructor("$ZodISOTime", (inst, def) => { + def.pattern ?? (def.pattern = regexes_time(def)); + $ZodStringFormat.init(inst, def); +}); +const $ZodISODuration = /*@__PURE__*/ $constructor("$ZodISODuration", (inst, def) => { + def.pattern ?? (def.pattern = duration); + $ZodStringFormat.init(inst, def); +}); +const $ZodIPv4 = /*@__PURE__*/ $constructor("$ZodIPv4", (inst, def) => { + def.pattern ?? (def.pattern = ipv4); + $ZodStringFormat.init(inst, def); + inst._zod.bag.format = `ipv4`; +}); +/** An IPv6 address is written with hex digits, colons and dots, and nothing else. The guard is what makes the check below an IPv6 check: `new URL("http://[...]")` parses an authority, not an address, so `@` and `\` re-delimit it and `"::@1\\"` validates against the host `0.0.0.1`. The URL parser also deletes ASCII tab, LF and CR rather than failing, which is how `"::1\n"` validated as `::1`. */ +const ipv6Alphabet = /^[0-9a-fA-F:.]+$/; +function isValidIPv6(value) { + if (!ipv6Alphabet.test(value)) + return false; + try { + // @ts-ignore + new URL(`http://[${value}]`); + return true; + } + catch { + return false; + } +} +const $ZodIPv6 = /*@__PURE__*/ $constructor("$ZodIPv6", (inst, def) => { + def.pattern ?? (def.pattern = regexes_ipv6); + $ZodStringFormat.init(inst, def); + inst._zod.bag.format = `ipv6`; + inst._zod.check = (payload) => { + if (!isValidIPv6(payload.value)) { + payload.issues.push({ + code: "invalid_format", + format: "ipv6", + input: payload.value, + inst, + continue: !def.abort, + }); + } + }; +}); +const $ZodMAC = /*@__PURE__*/ (/* unused pure expression or super */ null && (core.$constructor("$ZodMAC", (inst, def) => { + def.pattern ?? (def.pattern = regexes.mac(def.delimiter)); + $ZodStringFormat.init(inst, def); + inst._zod.bag.format = `mac`; +}))); +const $ZodCIDRv4 = /*@__PURE__*/ $constructor("$ZodCIDRv4", (inst, def) => { + def.pattern ?? (def.pattern = cidrv4); + $ZodStringFormat.init(inst, def); +}); +function isValidCIDRv6(value) { + const parts = value.split("/"); + if (parts.length !== 2) + return false; + const [address, prefix] = parts; + if (!prefix) + return false; + const prefixNum = Number(prefix); + if (`${prefixNum}` !== prefix) + return false; + if (prefixNum < 0 || prefixNum > 128) + return false; + return isValidIPv6(address); +} +const $ZodCIDRv6 = /*@__PURE__*/ $constructor("$ZodCIDRv6", (inst, def) => { + def.pattern ?? (def.pattern = cidrv6); // not used for validation + $ZodStringFormat.init(inst, def); + inst._zod.check = (payload) => { + if (!isValidCIDRv6(payload.value)) { + payload.issues.push({ + code: "invalid_format", + format: "cidrv6", + input: payload.value, + inst, + continue: !def.abort, + }); + } + }; +}); +////////////////////////////// ZodBase64 ////////////////////////////// +function isValidBase64(data) { + if (data === "") + return true; + // atob ignores whitespace, so reject it up front. + if (/\s/.test(data)) + return false; + if (data.length % 4 !== 0) + return false; + try { + // @ts-ignore + atob(data); + return true; + } + catch { + return false; + } +} +const $ZodBase64 = /*@__PURE__*/ $constructor("$ZodBase64", (inst, def) => { + def.pattern ?? (def.pattern = regexes_base64); + $ZodStringFormat.init(inst, def); + inst._zod.bag.contentEncoding = "base64"; + inst._zod.check = (payload) => { + if (isValidBase64(payload.value)) + return; + payload.issues.push({ + code: "invalid_format", + format: "base64", + input: payload.value, + inst, + continue: !def.abort, + }); + }; +}); +////////////////////////////// ZodBase64 ////////////////////////////// +function isValidBase64URL(data) { + if (!regexes_base64url.test(data)) + return false; + const base64 = data.replace(/[-_]/g, (c) => (c === "-" ? "+" : "/")); + const padded = base64.padEnd(Math.ceil(base64.length / 4) * 4, "="); + return isValidBase64(padded); +} +const $ZodBase64URL = /*@__PURE__*/ $constructor("$ZodBase64URL", (inst, def) => { + def.pattern ?? (def.pattern = regexes_base64url); + $ZodStringFormat.init(inst, def); + inst._zod.bag.contentEncoding = "base64url"; + inst._zod.check = (payload) => { + if (isValidBase64URL(payload.value)) + return; + payload.issues.push({ + code: "invalid_format", + format: "base64url", + input: payload.value, + inst, + continue: !def.abort, + }); + }; +}); +const $ZodE164 = /*@__PURE__*/ $constructor("$ZodE164", (inst, def) => { + def.pattern ?? (def.pattern = e164); + $ZodStringFormat.init(inst, def); +}); +////////////////////////////// ZodCreditCard ////////////////////////////// +const CC_SANITIZE = /[- ]/g; +/** Luhn checksum on a digit-only string. Adapted from valibot (MIT). */ +function isLuhnAlgo(digits) { + let length = digits.length; + let bit = 1; + let sum = 0; + while (length) { + const value = +digits[--length]; + bit ^= 1; + sum += bit ? [0, 2, 4, 6, 8, 1, 3, 5, 7, 9][value] : value; + } + return sum % 10 === 0; +} +function isValidCreditCard(input) { + if (!regexes.creditCard.test(input)) + return false; + return isLuhnAlgo(input.replace(CC_SANITIZE, "")); +} +const $ZodCreditCard = /*@__PURE__*/ (/* unused pure expression or super */ null && (core.$constructor("$ZodCreditCard", (inst, def) => { + // Shape only — the Luhn check below is not expressible as a pattern, so consumers of `pattern` (JSON Schema, template literals) get the length and separator rules alone. + def.pattern ?? (def.pattern = regexes.creditCard); + $ZodStringFormat.init(inst, def); + inst._zod.check = (payload) => { + if (isValidCreditCard(payload.value)) + return; + payload.issues.push({ + code: "invalid_format", + format: "credit_card", + input: payload.value, + inst, + continue: !def.abort, + }); + }; +}))); +////////////////////////////// ZodJWT ////////////////////////////// +function isValidJWT(token, algorithm = null) { + try { + const tokensParts = token.split("."); + if (tokensParts.length !== 3) + return false; + const [header] = tokensParts; + if (!header) + return false; + // @ts-ignore + const parsedHeader = JSON.parse(atob(header)); + if ("typ" in parsedHeader && parsedHeader?.typ !== "JWT") + return false; + if (!parsedHeader.alg) + return false; + if (algorithm && (!("alg" in parsedHeader) || parsedHeader.alg !== algorithm)) + return false; + return true; + } + catch { + return false; + } +} +const $ZodJWT = /*@__PURE__*/ $constructor("$ZodJWT", (inst, def) => { + $ZodStringFormat.init(inst, def); + inst._zod.check = (payload) => { + if (isValidJWT(payload.value, def.alg)) + return; + payload.issues.push({ + code: "invalid_format", + format: "jwt", + input: payload.value, + inst, + continue: !def.abort, + }); + }; +}); +const $ZodCustomStringFormat = /*@__PURE__*/ (/* unused pure expression or super */ null && (core.$constructor("$ZodCustomStringFormat", (inst, def) => { + $ZodStringFormat.init(inst, def); + inst._zod.check = (payload) => { + if (def.fn(payload.value)) + return; + payload.issues.push({ + code: "invalid_format", + format: def.format, + input: payload.value, + inst, + continue: !def.abort, + }); + }; +}))); +const $ZodNumber = /*@__PURE__*/ $constructor("$ZodNumber", (inst, def) => { + $ZodType.init(inst, def); + inst._zod.pattern = inst._zod.bag.pattern ?? number; + inst._zod.parse = (payload, _ctx) => { + if (def.coerce) + try { + payload.value = Number(payload.value); + } + catch (_) { } + const input = payload.value; + if (typeof input === "number" && !Number.isNaN(input) && Number.isFinite(input)) { + return payload; + } + const received = typeof input === "number" + ? Number.isNaN(input) + ? "NaN" + : !Number.isFinite(input) + ? String(input) + : undefined + : undefined; + payload.issues.push({ + expected: "number", + code: "invalid_type", + input, + inst, + ...(received ? { received } : {}), + }); + return payload; + }; +}); +const $ZodNumberFormat = /*@__PURE__*/ $constructor("$ZodNumberFormat", (inst, def) => { + $ZodCheckNumberFormat.init(inst, def); + $ZodNumber.init(inst, def); // no format checks +}); +const $ZodBoolean = /*@__PURE__*/ $constructor("$ZodBoolean", (inst, def) => { + $ZodType.init(inst, def); + inst._zod.pattern = regexes_boolean; + inst._zod.parse = (payload, _ctx) => { + if (def.coerce) + try { + payload.value = Boolean(payload.value); + } + catch (_) { } + const input = payload.value; + if (typeof input === "boolean") + return payload; + payload.issues.push({ + expected: "boolean", + code: "invalid_type", + input, + inst, + }); + return payload; + }; +}); +const $ZodBigInt = /*@__PURE__*/ (/* unused pure expression or super */ null && (core.$constructor("$ZodBigInt", (inst, def) => { + $ZodType.init(inst, def); + inst._zod.pattern = regexes.bigint; + inst._zod.parse = (payload, _ctx) => { + if (def.coerce) + try { + payload.value = BigInt(payload.value); + } + catch (_) { } + if (typeof payload.value === "bigint") + return payload; + payload.issues.push({ + expected: "bigint", + code: "invalid_type", + input: payload.value, + inst, + }); + return payload; + }; +}))); +const $ZodBigIntFormat = /*@__PURE__*/ (/* unused pure expression or super */ null && (core.$constructor("$ZodBigIntFormat", (inst, def) => { + checks.$ZodCheckBigIntFormat.init(inst, def); + $ZodBigInt.init(inst, def); // no format checks +}))); +const $ZodSymbol = /*@__PURE__*/ (/* unused pure expression or super */ null && (core.$constructor("$ZodSymbol", (inst, def) => { + $ZodType.init(inst, def); + inst._zod.parse = (payload, _ctx) => { + const input = payload.value; + if (typeof input === "symbol") + return payload; + payload.issues.push({ + expected: "symbol", + code: "invalid_type", + input, + inst, + }); + return payload; + }; +}))); +const $ZodUndefined = /*@__PURE__*/ (/* unused pure expression or super */ null && (core.$constructor("$ZodUndefined", (inst, def) => { + $ZodType.init(inst, def); + inst._zod.pattern = regexes.undefined; + inst._zod.values = new Set([undefined]); + inst._zod.parse = (payload, _ctx) => { + const input = payload.value; + if (typeof input === "undefined") + return payload; + payload.issues.push({ + expected: "undefined", + code: "invalid_type", + input, + inst, + }); + return payload; + }; +}))); +const $ZodNull = /*@__PURE__*/ $constructor("$ZodNull", (inst, def) => { + $ZodType.init(inst, def); + inst._zod.pattern = _null; + inst._zod.values = new Set([null]); + inst._zod.parse = (payload, _ctx) => { + const input = payload.value; + if (input === null) + return payload; + payload.issues.push({ + expected: "null", + code: "invalid_type", + input, + inst, + }); + return payload; + }; +}); +const $ZodAny = /*@__PURE__*/ $constructor("$ZodAny", (inst, def) => { + $ZodType.init(inst, def); + inst._zod.parse = (payload) => payload; +}); +const $ZodUnknown = /*@__PURE__*/ $constructor("$ZodUnknown", (inst, def) => { + $ZodType.init(inst, def); + inst._zod.parse = (payload) => payload; +}); +const $ZodNever = /*@__PURE__*/ $constructor("$ZodNever", (inst, def) => { + $ZodType.init(inst, def); + inst._zod.parse = (payload, _ctx) => { + payload.issues.push({ + expected: "never", + code: "invalid_type", + input: payload.value, + inst, + }); + return payload; + }; +}); +const $ZodVoid = /*@__PURE__*/ (/* unused pure expression or super */ null && (core.$constructor("$ZodVoid", (inst, def) => { + $ZodType.init(inst, def); + inst._zod.parse = (payload, _ctx) => { + const input = payload.value; + if (typeof input === "undefined") + return payload; + payload.issues.push({ + expected: "void", + code: "invalid_type", + input, + inst, + }); + return payload; + }; +}))); +const $ZodDate = /*@__PURE__*/ (/* unused pure expression or super */ null && (core.$constructor("$ZodDate", (inst, def) => { + $ZodType.init(inst, def); + inst._zod.parse = (payload, _ctx) => { + if (def.coerce) { + try { + payload.value = new Date(payload.value); + } + catch (_err) { } + } + const input = payload.value; + const isDate = input instanceof Date; + const isValidDate = isDate && !Number.isNaN(input.getTime()); + if (isValidDate) + return payload; + payload.issues.push({ + expected: "date", + code: "invalid_type", + input, + ...(isDate ? { received: "Invalid Date" } : {}), + inst, + }); + return payload; + }; +}))); +function handleArrayResult(result, final, index) { + if (result.issues.length) { + final.issues.push(...prefixIssues(index, result.issues)); + } + final.value[index] = result.value; +} +const $ZodArray = /*@__PURE__*/ $constructor("$ZodArray", (inst, def) => { + $ZodType.init(inst, def); + const memo = globalConfig.memoizer; + memo?.attach(inst); + inst._zod.parse = (payload, ctx) => { + const input = payload.value; + if (!Array.isArray(input)) { + payload.issues.push({ + expected: "array", + code: "invalid_type", + input, + inst, + }); + return payload; + } + payload.value = memo ? memo.alloc(inst, payload, Array(input.length), ctx) : Array(input.length); + const proms = []; + for (let i = 0; i < input.length; i++) { + const item = input[i]; + const result = def.element._zod.run({ + value: item, + issues: [], + }, ctx); + if (result instanceof Promise) { + proms.push(result.then((result) => handleArrayResult(result, payload, i))); + } + else { + handleArrayResult(result, payload, i); + } + } + if (proms.length) { + return Promise.all(proms).then(() => payload); + } + return payload; //handleArrayResultsAsync(parseResults, final); + }; +}); +function handlePropertyResult(result, final, key, input, optin, optout) { + const isPresent = key in input; + const isOptionalOut = optout === "optional"; + // The middle rung means "absence permitted, nothing supplied in its place", so an absent key contributes nothing — whatever the schema made of `undefined` is invented, not substituted. Only `optional` reaches this with a value: `defaulted` substitutes, and a schema that isn't optional-out has to keep the key. + if (!isPresent && isOptionalOut && optin === "optional") { + return; + } + if (result.issues.length) { + // For optional-in/out schemas, ignore errors on absent keys. + if (optin !== undefined && isOptionalOut && !isPresent) { + return; + } + final.issues.push(...prefixIssues(key, result.issues)); + } + if (!isPresent && optin === undefined) { + if (!result.issues.length) { + final.issues.push({ + code: "invalid_type", + expected: "nonoptional", + input: undefined, + path: [key], + }); + } + return; + } + if (result.value === undefined) { + if (isPresent) { + final.value[key] = undefined; + } + } + else { + final.value[key] = result.value; + } +} +// one shared instance; a fresh [] per schema cost 56 bytes retained +const NO_SYMBOL_KEYS = []; +function normalizeDef(def) { + const keys = Object.keys(def.shape); + const ownSymbols = Object.getOwnPropertySymbols(def.shape); + const symbolKeys = ownSymbols.length ? ownSymbols : NO_SYMBOL_KEYS; + // aliases `keys` when there are no symbols, so a string-only shape keeps one array + const allKeys = symbolKeys.length ? [...keys, ...symbolKeys] : keys; + for (const k of allKeys) { + if (!def.shape?.[k]?._zod?.traits?.has("$ZodType")) { + throw new Error(`Invalid element at key "${String(k)}": expected a Zod schema`); + } + } + const okeys = optionalKeys(def.shape); + return { + ...def, + allKeys, + symbolKeys, + // string-only: handleCatchall matches it against `for...in`, which never yields a symbol + keySet: new Set(keys), + numKeys: keys.length, + optionalKeys: new Set(okeys), + }; +} +function handleCatchall(proms, input, payload, ctx, def, inst) { + const unrecognized = []; + const keySet = def.keySet; + const _catchall = def.catchall._zod; + const t = _catchall.def.type; + const optin = _catchall.optin; + const optout = _catchall.optout; + for (const key in input) { + // Must precede the __proto__ branch: a declared key is not unrecognized, even though the shape loop deliberately strips __proto__ from the parsed output. + if (keySet.has(key)) + continue; + // Don't copy an undeclared __proto__ into the result; assignment to a plain {} would replace the result prototype. But in strict mode it is still an unknown key, so report it before skipping. + if (key === "__proto__") { + if (t === "never") + unrecognized.push(key); + continue; + } + if (t === "never") { + unrecognized.push(key); + continue; + } + const r = _catchall.run({ value: input[key], issues: [] }, ctx); + if (r instanceof Promise) { + proms.push(r.then((r) => handlePropertyResult(r, payload, key, input, optin, optout))); + } + else { + handlePropertyResult(r, payload, key, input, optin, optout); + } + } + if (unrecognized.length) { + payload.issues.push({ + code: "unrecognized_keys", + keys: unrecognized, + input, + inst, + // Describes the shape of the input, not the validity of the parsed value, so it never aborts. The parse still fails; the schema's own checks just get to run first, and an enclosing intersection can reconcile the key against a sibling operand. + continue: true, + }); + } + if (!proms.length) + return payload; + return Promise.all(proms).then(() => { + return payload; + }); +} +// Whichever object a def's `shape` currently answers from: the one the caller passed until the first read, the frozen copy after it. Keyed by def, so a def rebuilt by a builder is simply absent rather than inheriting the source's. Read its keys with `Object.keys`, which does not invoke them — that is what lets a discriminated union check its discriminator without resolving an option whose getters reference the union being constructed. +const propShapes = new WeakMap(); +const $ZodObject = /*@__PURE__*/ $constructor("$ZodObject", (inst, def) => { + // requires cast because technically $ZodObject doesn't extend + $ZodType.init(inst, def); + // const sh = def.shape; + const desc = Object.getOwnPropertyDescriptor(def, "shape"); + if (!desc?.get) { + const sh = def.shape; + propShapes.set(def, sh); + Object.defineProperty(def, "shape", { + get: () => { + const newSh = { ...sh }; + Object.defineProperty(def, "shape", { + value: newSh, + }); + propShapes.set(def, newSh); + return newSh; + }, + }); + } + const _normalized = util_cached(() => normalizeDef(def)); + defineLazyInternal(inst, "propValues", (zod) => { + const shape = zod.def.shape; + const propValues = {}; + for (const key in shape) { + const field = shape[key]._zod; + if (field.values) { + if (!Object.prototype.hasOwnProperty.call(propValues, key)) { + assignProp(propValues, key, new Set()); + } + for (const v of field.values) + propValues[key].add(v); + // An omittable slot reads back as undefined at a discriminator lookup, so it has to claim undefined: two options that can both omit the key are not discriminable on it. + if (field.optin !== undefined) + propValues[key].add(undefined); + } + } + return propValues; + }); + const isObject = util_isObject; + const catchall = def.catchall; + let value; + const memo = globalConfig.memoizer; + memo?.attach(inst); + inst._zod.parse = (payload, ctx) => { + value ?? (value = _normalized.value); + const input = payload.value; + if (!isObject(input)) { + payload.issues.push({ + expected: "object", + code: "invalid_type", + input, + inst, + }); + return payload; + } + payload.value = memo ? memo.alloc(inst, payload, {}, ctx) : {}; + const proms = []; + const shape = value.shape; + for (const key of value.allKeys) { + if (key === "__proto__") + continue; + const el = shape[key]; + const optin = el._zod.optin; + const optout = el._zod.optout; + const r = el._zod.run({ value: input[key], issues: [] }, ctx); + if (r instanceof Promise) { + proms.push(r.then((r) => handlePropertyResult(r, payload, key, input, optin, optout))); + } + else { + handlePropertyResult(r, payload, key, input, optin, optout); + } + } + if (!catchall) { + return proms.length ? Promise.all(proms).then(() => payload) : payload; + } + return handleCatchall(proms, input, payload, ctx, _normalized.value, inst); + }; +}); +const $ZodObjectJIT = /*@__PURE__*/ $constructor("$ZodObjectJIT", (inst, def) => { + // requires cast because technically $ZodObject doesn't extend + $ZodObject.init(inst, def); + const superParse = inst._zod.parse; + const _normalized = util_cached(() => normalizeDef(def)); + const memo = globalConfig.memoizer; + const generateFastpass = (shape) => { + const normalized = _normalized.value; + const syms = normalized.symbolKeys; + // a symbol has no source literal, so it is read as `syms[i]` off the closed-over scope + const doc = new Doc(["payload", "ctx"], { shape, inst, memo, syms }); + const parseStr = (k) => `shape[${k}]._zod.run({ value: input[${k}], issues: [] }, ctx)`; + // Prefixes in place, like util.prefixIssues does for every interpreted path. + const prefixStr = (id, k) => ` + for (let i = 0; i < ${id}.issues.length; i++) { + const iss = ${id}.issues[i]; + iss.path = iss.path ? [${k}, ...iss.path] : [${k}]; + payload.issues.push(iss); + }`; + doc.write(`const input = payload.value;`); + const ids = Object.create(null); + let counter = 0; + for (const key of normalized.allKeys) { + ids[key] = `key_${counter++}`; + } + // A: preserve key order { + doc.write(memo ? `const newResult = memo.alloc(inst, payload, {}, ctx);` : `const newResult = {};`); + for (const key of normalized.allKeys) { + if (key === "__proto__") + continue; + const id = ids[key]; + const k = typeof key === "symbol" ? `syms[${syms.indexOf(key)}]` : util_esc(key); + const isPresent = `${k} in input`; + const schema = shape[key]; + const optin = schema?._zod?.optin; + const isOptionalIn = optin !== undefined; + const isOptionalOut = schema?._zod?.optout === "optional"; + doc.write(`const ${id} = ${parseStr(k)};`); + if (isOptionalIn && isOptionalOut) { + // For optional-in/out schemas, ignore errors on absent keys — and, like the interpreted path, drop the value produced alongside them. The middle rung goes further: it permits absence without supplying anything in its place, so an absent key contributes nothing at all. + const assign = optin === "optional" ? `${id}_present` : `${id}.value !== undefined || ${id}_present`; + doc.write(` + const ${id}_present = ${isPresent}; + if (!${id}.issues.length || ${id}_present) { + if (${id}.issues.length) {${prefixStr(id, k)} + } + + if (${assign}) { + newResult[${k}] = ${id}.value; + } + } + + `); + } + else if (!isOptionalIn) { + doc.write(` + const ${id}_present = ${isPresent}; + if (${id}.issues.length) {${prefixStr(id, k)} + } + if (!${id}_present && !${id}.issues.length) { + payload.issues.push({ + code: "invalid_type", + expected: "nonoptional", + input: undefined, + path: [${k}] + }); + } + + if (${id}_present) { + newResult[${k}] = ${id}.value; + } + + `); + } + else { + doc.write(` + if (${id}.issues.length) {${prefixStr(id, k)} + } + + if (${id}.value === undefined) { + if (${isPresent}) { + newResult[${k}] = undefined; + } + } else { + newResult[${k}] = ${id}.value; + } + + `); + } + } + doc.write(`payload.value = newResult;`); + doc.write(`return payload;`); + // closing `shape` in is what pays: turbofan specializes the parser against that one shape object, so every `shape[k]._zod.run` folds to a known callee. as a parameter it stays a generic load and measures 13% slower even with the forwarding frame gone + return doc.compile(); + }; + let fastpass; + const isObject = util_isObject; + const jit = !globalConfig.jitless; + const allowsEval = util_allowsEval; + const fastEnabled = jit && allowsEval.value; // && !def.catchall; + const catchall = def.catchall; + let value; + inst._zod.parse = (payload, ctx) => { + value ?? (value = _normalized.value); + const input = payload.value; + if (!isObject(input)) { + payload.issues.push({ + expected: "object", + code: "invalid_type", + input, + inst, + }); + return payload; + } + if (jit && fastEnabled && ctx?.async === false && ctx.jitless !== true) { + // always synchronous + if (!fastpass) + fastpass = generateFastpass(def.shape); + payload = fastpass(payload, ctx); + if (!catchall) + return payload; + return handleCatchall([], input, payload, ctx, value, inst); + } + return superParse(payload, ctx); + }; +}); +function handleUnionResults(results, final, inst, ctx) { + for (const result of results) { + if (result.issues.length === 0) { + final.value = result.value; + return final; + } + } + const nonaborted = results.filter((r) => !aborted(r)); + if (nonaborted.length === 1) { + final.value = nonaborted[0].value; + return nonaborted[0]; + } + final.issues.push({ + code: "invalid_union", + input: final.value, + inst, + errors: results.map((result) => result.issues.map((iss) => finalizeIssue(iss, ctx, core_config()))), + }); + return final; +} +const $ZodUnion = /*@__PURE__*/ $constructor("$ZodUnion", (inst, def) => { + $ZodType.init(inst, def); + defineLazyInternal(inst, "optin", (zod) => zod.def.options.some((o) => o._zod.optin === "defaulted") + ? "defaulted" + : zod.def.options.some((o) => o._zod.optin !== undefined) + ? "optional" + : undefined); + defineLazyInternal(inst, "optout", (zod) => zod.def.options.some((o) => o._zod.optout === "optional") ? "optional" : undefined); + defineLazyInternal(inst, "values", (zod) => { + if (zod.def.options.every((o) => o._zod.values)) { + return new Set(zod.def.options.flatMap((option) => Array.from(option._zod.values))); + } + return undefined; + }); + defineLazyInternal(inst, "pattern", (zod) => { + if (zod.def.options.every((o) => o._zod.pattern)) { + const patterns = zod.def.options.map((o) => o._zod.pattern); + return new RegExp(`^(${patterns.map((p) => cleanRegex(p.source)).join("|")})$`); + } + return undefined; + }); + const first = def.options.length === 1 ? def.options[0]._zod.run : null; + inst._zod.parse = (payload, ctx) => { + if (first) { + return first(payload, ctx); + } + let async = false; + const results = []; + for (const option of def.options) { + const result = option._zod.run({ + value: payload.value, + issues: [], + }, ctx); + if (result instanceof Promise) { + results.push(result); + async = true; + } + else { + if (result.issues.length === 0) + return result; + results.push(result); + } + } + if (!async) + return handleUnionResults(results, payload, inst, ctx); + return Promise.all(results).then((results) => { + return handleUnionResults(results, payload, inst, ctx); + }); + }; +}); +function handleExclusiveUnionResults(results, final, inst, ctx) { + const matches = []; + for (let i = 0; i < results.length; i++) { + if (results[i].issues.length === 0) + matches.push(i); + } + if (matches.length === 1) { + final.value = results[matches[0]].value; + return final; + } + if (matches.length === 0) { + // No matches - same as regular union + final.issues.push({ + code: "invalid_union", + input: final.value, + inst, + errors: results.map((result) => result.issues.map((iss) => util.finalizeIssue(iss, ctx, core.config()))), + }); + } + else { + // Multiple matches - exclusive union failure + final.issues.push({ + code: "invalid_union", + input: final.value, + inst, + errors: [], + inclusive: false, + matches, + }); + } + return final; +} +const $ZodXor = /*@__PURE__*/ (/* unused pure expression or super */ null && (core.$constructor("$ZodXor", (inst, def) => { + $ZodUnion.init(inst, def); + def.inclusive = false; + const first = def.options.length === 1 ? def.options[0]._zod.run : null; + inst._zod.parse = (payload, ctx) => { + if (first) { + return first(payload, ctx); + } + let async = false; + const results = []; + for (const option of def.options) { + const result = option._zod.run({ + value: payload.value, + issues: [], + }, ctx); + if (result instanceof Promise) { + results.push(result); + async = true; + } + else { + results.push(result); + } + } + if (!async) + return handleExclusiveUnionResults(results, payload, inst, ctx); + return Promise.all(results).then((results) => { + return handleExclusiveUnionResults(results, payload, inst, ctx); + }); + }; +}))); +/** Returns the option of `union` whose discriminator claims `value`. */ +function getDiscriminatedOption(union, value) { + const internals = union._zod; + let map = internals.bag.optionsMap; + if (!map) { + map = new Map(); + const { options, discriminator } = internals.def; + for (const option of options) { + // First declaration wins, matching the order the parse path resolves a duplicate in. + for (const v of option._zod.propValues?.[discriminator] ?? []) + if (!map.has(v)) + map.set(v, option); + } + internals.bag.optionsMap = map; + } + return map.get(value); +} +const $ZodDiscriminatedUnion = +/*@__PURE__*/ +$constructor("$ZodDiscriminatedUnion", (inst, def) => { + def.inclusive = false; + $ZodUnion.init(inst, def); + const _super = inst._zod.parse; + defineLazyInternal(inst, "propValues", (zod) => { + const propValues = {}; + for (const option of zod.def.options) { + const pv = option._zod.propValues; + if (!pv || Object.keys(pv).length === 0) + throw new Error(`Invalid discriminated union option at index "${zod.def.options.indexOf(option)}"`); + for (const [k, v] of Object.entries(pv)) { + if (!Object.prototype.hasOwnProperty.call(propValues, k)) { + assignProp(propValues, k, new Set()); + } + for (const val of v) { + propValues[k].add(val); + } + } + } + return propValues; + }); + // Checked now rather than in the lookup map below, so an option that lacks the discriminator fails at the `discriminatedUnion` call instead of on the first object parsed. Options whose shape cannot be enumerated without resolving it — pipes, lazies, and objects rebuilt by a builder such as `.extend()` — are left to the map. + def.options.forEach((option, i) => { + const propShape = propShapes.get(option._zod.def); + if (propShape && !Object.prototype.hasOwnProperty.call(propShape, def.discriminator)) { + throw new Error(`Invalid discriminated union option at index "${i}"`); + } + }); + const disc = util_cached(() => { + const opts = def.options; + const map = new Map(); + for (const o of opts) { + const values = o._zod.propValues?.[def.discriminator]; + if (!values || values.size === 0) + throw new Error(`Invalid discriminated union option at index "${def.options.indexOf(o)}"`); + for (const v of values) { + if (map.has(v)) { + throw new Error(`Duplicate discriminator value "${String(v)}"`); + } + map.set(v, o); + } + } + return map; + }); + inst._zod.parse = (payload, ctx) => { + const input = payload.value; + if (!util_isObject(input)) { + payload.issues.push({ + code: "invalid_type", + expected: "object", + input, + inst, + }); + return payload; + } + const opt = disc.value.get(input?.[def.discriminator]); + if (opt) { + return opt._zod.run(payload, ctx); + } + // Fall back to union matching when the fast discriminator path fails: + // - explicitly enabled via unionFallback, or + // - during backward direction (encode), since codec-based discriminators have different values in forward vs backward directions + if (def.unionFallback || ctx.direction === "backward") { + return _super(payload, ctx); + } + // no matching discriminator + payload.issues.push({ + code: "invalid_union", + errors: [], + note: "No matching discriminator", + discriminator: def.discriminator, + options: Array.from(disc.value.keys()), + input, + path: [def.discriminator], + inst, + }); + return payload; + }; +}); +const $ZodIntersection = /*@__PURE__*/ $constructor("$ZodIntersection", (inst, def) => { + $ZodType.init(inst, def); + inst._zod.parse = (payload, ctx) => { + const input = payload.value; + const left = def.left._zod.run({ value: input, issues: [] }, ctx); + const right = def.right._zod.run({ value: input, issues: [] }, ctx); + const async = left instanceof Promise || right instanceof Promise; + if (async) { + return Promise.all([left, right]).then(([left, right]) => { + return handleIntersectionResults(payload, left, right); + }); + } + return handleIntersectionResults(payload, left, right); + }; +}); +function schemas_mergeValues(a, b) { + // const aType = parse.t(a); + // const bType = parse.t(b); + if (a === b) { + return { valid: true, data: a }; + } + if (a instanceof Date && b instanceof Date && +a === +b) { + return { valid: true, data: a }; + } + if (isPlainObject(a) && isPlainObject(b)) { + const bKeys = Object.keys(b); + const sharedKeys = Object.keys(a).filter((key) => bKeys.indexOf(key) !== -1); + const newObj = { ...a, ...b }; + if (Object.prototype.hasOwnProperty.call(newObj, "__proto__")) + delete newObj.__proto__; + for (const key of sharedKeys) { + if (key === "__proto__") + continue; + const sharedValue = schemas_mergeValues(a[key], b[key]); + if (!sharedValue.valid) { + return { + valid: false, + mergeErrorPath: [key, ...sharedValue.mergeErrorPath], + }; + } + newObj[key] = sharedValue.data; + } + return { valid: true, data: newObj }; + } + if (Array.isArray(a) && Array.isArray(b)) { + if (a.length !== b.length) { + return { valid: false, mergeErrorPath: [] }; + } + const newArray = []; + for (let index = 0; index < a.length; index++) { + const itemA = a[index]; + const itemB = b[index]; + const sharedValue = schemas_mergeValues(itemA, itemB); + if (!sharedValue.valid) { + return { + valid: false, + mergeErrorPath: [index, ...sharedValue.mergeErrorPath], + }; + } + newArray.push(sharedValue.data); + } + return { valid: true, data: newArray }; + } + return { valid: false, mergeErrorPath: [] }; +} +function handleIntersectionResults(result, left, right) { + // Track which side(s) reject each key. A key rejection is reported only when BOTH sides reject it, so a key owned by one branch survives the other's key schema. strictObject reports these as unrecognized_keys; a record with an open key schema reports one invalid_key per key. + const unrecKeys = new Map(); + let unrecIssue; + const keyIssues = new Map(); + const collect = (iss, side) => { + let keys; + if (iss.code === "unrecognized_keys" && !iss.path?.length) { + unrecIssue ?? (unrecIssue = iss); + keys = iss.keys; + } + else if (iss.code === "invalid_key" && iss.origin === "record" && iss.path?.length === 1) { + const k = String(iss.path[0]); + if (!keyIssues.has(k)) + keyIssues.set(k, iss); + keys = [k]; + } + else { + return false; + } + for (const k of keys) { + if (!unrecKeys.has(k)) + unrecKeys.set(k, {}); + unrecKeys.get(k)[side] = true; + } + return true; + }; + for (const iss of left.issues) { + if (!collect(iss, "l")) + result.issues.push(iss); + } + for (const iss of right.issues) { + if (!collect(iss, "r")) + result.issues.push(iss); + } + // Report only keys rejected by BOTH sides + const bothKeys = [...unrecKeys].filter(([, f]) => f.l && f.r).map(([k]) => k); + if (bothKeys.length) { + const aggregated = unrecIssue ? bothKeys.filter((k) => unrecIssue.keys.includes(k)) : []; + if (aggregated.length) + result.issues.push({ ...unrecIssue, keys: aggregated }); + for (const k of bothKeys) { + if (!aggregated.includes(k) && keyIssues.has(k)) + result.issues.push(keyIssues.get(k)); + } + } + const merged = schemas_mergeValues(left.value, right.value); + if (!merged.valid) { + if (aborted(result)) + return result; + throw new Error(`Unmergable intersection. Error path: ` + `${JSON.stringify(merged.mergeErrorPath)}`); + } + result.value = merged.data; + return result; +} +const $ZodTuple = /*@__PURE__*/ (/* unused pure expression or super */ null && (core.$constructor("$ZodTuple", (inst, def) => { + $ZodType.init(inst, def); + const items = def.items; + const memo = core.globalConfig.memoizer; + memo?.attach(inst); + inst._zod.parse = (payload, ctx) => { + const input = payload.value; + if (!Array.isArray(input)) { + payload.issues.push({ + input, + inst, + expected: "tuple", + code: "invalid_type", + }); + return payload; + } + payload.value = memo ? memo.alloc(inst, payload, [], ctx) : []; + const proms = []; + const optinStart = getTupleOptStart(items, "optin"); + const optoutStart = getTupleOptStart(items, "optout"); + if (!def.rest) { + if (input.length < optinStart) { + payload.issues.push({ + code: "too_small", + minimum: optinStart, + inclusive: true, + input, + inst, + origin: "array", + }); + return payload; + } + if (input.length > items.length) { + payload.issues.push({ + code: "too_big", + maximum: items.length, + inclusive: true, + input, + inst, + origin: "array", + }); + } + } + // Run every item in parallel, collecting results into an indexed array. The post-processing in `handleTupleResults` walks them in order so it can decide whether an absent optional-output error can truncate the tail or must be reported to preserve required output. + const itemResults = new Array(items.length); + for (let i = 0; i < items.length; i++) { + const r = items[i]._zod.run({ value: input[i], issues: [] }, ctx); + if (r instanceof Promise) { + proms.push(r.then((rr) => { + itemResults[i] = rr; + })); + } + else { + itemResults[i] = r; + } + } + if (def.rest) { + let i = items.length - 1; + const rest = input.slice(items.length); + for (const el of rest) { + i++; + const result = def.rest._zod.run({ value: el, issues: [] }, ctx); + if (result instanceof Promise) { + proms.push(result.then((r) => handleTupleResult(r, payload, i))); + } + else { + handleTupleResult(result, payload, i); + } + } + } + if (proms.length) { + return Promise.all(proms).then(() => handleTupleResults(itemResults, payload, items, input, optoutStart)); + } + return handleTupleResults(itemResults, payload, items, input, optoutStart); + }; +}))); +function getTupleOptStart(items, key) { + for (let i = items.length - 1; i >= 0; i--) { + // optin is a three-rung ladder so any rung above `undefined` permits an absent slot; optout stays two-valued. + const omittable = key === "optin" ? items[i]._zod.optin !== undefined : items[i]._zod.optout === "optional"; + if (!omittable) + return i + 1; + } + return 0; +} +function handleTupleResult(result, final, index) { + if (result.issues.length) { + final.issues.push(...util.prefixIssues(index, result.issues)); + } + final.value[index] = result.value; +} +function handleTupleResults(itemResults, final, items, input, optoutStart) { + // Walk results in order. Mirror $ZodObject's swallow-on-absent-optional rule, but only after `optoutStart`: the first index where the output tuple tail can be absent. + for (let i = 0; i < items.length; i++) { + const r = itemResults[i]; + const isPresent = i < input.length; + // The array analog of `handlePropertyResult`'s absent-key early return: the middle rung permits absence without supplying anything in its place, so the tail truncates here instead of materializing whatever the item made of `undefined`. + if (!isPresent && i >= optoutStart && items[i]._zod.optin === "optional") { + final.value.length = i; + break; + } + if (r.issues.length) { + if (!isPresent && i >= optoutStart) { + final.value.length = i; + break; + } + final.issues.push(...util.prefixIssues(i, r.issues)); + } + final.value[i] = r.value; + } + // Drop trailing slots that produced `undefined` for absent input + // (the array analog of an absent optional key on an object). The + // `i >= input.length` floor is critical: an explicit `undefined` + // *inside* the input must be preserved even when the schema is + // optional-out (e.g. `z.string().or(z.undefined())` accepting an + // explicit undefined value). + for (let i = final.value.length - 1; i >= input.length; i--) { + if (items[i]._zod.optout === "optional" && final.value[i] === undefined) { + final.value.length = i; + } + else { + break; + } + } + return final; +} +const $ZodRecord = /*@__PURE__*/ $constructor("$ZodRecord", (inst, def) => { + $ZodType.init(inst, def); + const memo = globalConfig.memoizer; + memo?.attach(inst); + inst._zod.parse = (payload, ctx) => { + const input = payload.value; + if (!isPlainObject(input)) { + payload.issues.push({ + expected: "record", + code: "invalid_type", + input, + inst, + }); + return payload; + } + const proms = []; + const values = def.keyType._zod.values; + if (values && !def.partial) { + payload.value = memo ? memo.alloc(inst, payload, {}, ctx) : {}; + const recordKeys = new Set(); + for (const key of values) { + if (typeof key === "string" || typeof key === "number" || typeof key === "symbol") { + recordKeys.add(typeof key === "number" ? key.toString() : key); + // A declared __proto__ is stripped but is not an unrecognized key. + if (key === "__proto__") + continue; + const keyResult = def.keyType._zod.run({ value: key, issues: [] }, ctx); + if (keyResult instanceof Promise) { + throw new Error("Async schemas not supported in object keys currently"); + } + if (keyResult.issues.length) { + payload.issues.push({ + code: "invalid_key", + origin: "record", + issues: keyResult.issues.map((iss) => finalizeIssue(iss, ctx, core_config())), + input: key, + path: [key], + inst, + }); + continue; + } + const outKey = keyResult.value; + if (outKey === "__proto__") + continue; + const result = def.valueType._zod.run({ value: input[key], issues: [] }, ctx); + if (result instanceof Promise) { + proms.push(result.then((result) => { + if (result.issues.length) { + payload.issues.push(...prefixIssues(key, result.issues)); + } + payload.value[outKey] = result.value; + })); + } + else { + if (result.issues.length) { + payload.issues.push(...prefixIssues(key, result.issues)); + } + payload.value[outKey] = result.value; + } + } + } + let unrecognized; + for (const key in input) { + if (!recordKeys.has(key)) { + if (def.mode === "loose") { + // skip __proto__ so it can't replace the result prototype via the assignment setter on the plain {} we build into + if (key === "__proto__") + continue; + payload.value[key] = input[key]; + } + else { + unrecognized = unrecognized ?? []; + unrecognized.push(key); + } + } + } + if (unrecognized && unrecognized.length > 0) { + payload.issues.push({ + code: "unrecognized_keys", + input, + inst, + keys: unrecognized, + continue: true, + }); + } + } + else { + payload.value = memo ? memo.alloc(inst, payload, {}, ctx) : {}; + // An enumerable key schema declares which keys the record owns, so a key outside the set is unrecognized. A non-enumerable one (regex, refine) is a constraint every key must satisfy, so a failing key is invalid. Only the former is reconcilable against the other side of an intersection. + let unrecognized; + // Reflect.ownKeys for Symbol-key support; filter non-enumerable to match z.object() + for (const key of Reflect.ownKeys(input)) { + if (key === "__proto__") + continue; + if (!Object.prototype.propertyIsEnumerable.call(input, key)) + continue; + let keyResult = def.keyType._zod.run({ value: key, issues: [] }, ctx); + if (keyResult instanceof Promise) { + throw new Error("Async schemas not supported in object keys currently"); + } + // Numeric string fallback: if key is a numeric string and failed, retry with Number(key). This handles z.number(), z.literal([1, 2, 3]), and unions containing numeric literals + const checkNumericKey = typeof key === "string" && number.test(key) && keyResult.issues.length; + if (checkNumericKey) { + const retryResult = def.keyType._zod.run({ value: Number(key), issues: [] }, ctx); + if (retryResult instanceof Promise) { + throw new Error("Async schemas not supported in object keys currently"); + } + if (retryResult.issues.length === 0) { + keyResult = retryResult; + } + } + if (keyResult.issues.length) { + if (def.mode === "loose") { + // Pass through unchanged + payload.value[key] = input[key]; + } + else if (values) { + unrecognized = unrecognized ?? []; + unrecognized.push(key); + } + else { + // Default "strict" behavior: error on invalid key + payload.issues.push({ + code: "invalid_key", + origin: "record", + issues: keyResult.issues.map((iss) => finalizeIssue(iss, ctx, core_config())), + input: key, + path: [key], + inst, + }); + } + continue; + } + // the guard above tests the raw input key, but the key schema can normalize an ordinary key into __proto__; re-check the key we actually write under + const outKey = keyResult.value; + if (outKey === "__proto__") + continue; + const result = def.valueType._zod.run({ value: input[key], issues: [] }, ctx); + if (result instanceof Promise) { + proms.push(result.then((result) => { + if (result.issues.length) { + payload.issues.push(...prefixIssues(key, result.issues)); + } + payload.value[outKey] = result.value; + })); + } + else { + if (result.issues.length) { + payload.issues.push(...prefixIssues(key, result.issues)); + } + payload.value[outKey] = result.value; + } + } + if (unrecognized && unrecognized.length > 0) { + payload.issues.push({ + code: "unrecognized_keys", + input, + inst, + keys: unrecognized, + continue: true, + }); + } + } + if (proms.length) { + return Promise.all(proms).then(() => payload); + } + return payload; + }; +}); +const $ZodMap = /*@__PURE__*/ (/* unused pure expression or super */ null && (core.$constructor("$ZodMap", (inst, def) => { + $ZodType.init(inst, def); + const memo = core.globalConfig.memoizer; + memo?.attach(inst); + inst._zod.parse = (payload, ctx) => { + const input = payload.value; + if (!(input instanceof Map)) { + payload.issues.push({ + expected: "map", + code: "invalid_type", + input, + inst, + }); + return payload; + } + const proms = []; + payload.value = memo ? memo.alloc(inst, payload, new Map(), ctx) : new Map(); + for (const [key, value] of input) { + const keyResult = def.keyType._zod.run({ value: key, issues: [] }, ctx); + const valueResult = def.valueType._zod.run({ value: value, issues: [] }, ctx); + if (keyResult instanceof Promise || valueResult instanceof Promise) { + proms.push(Promise.all([keyResult, valueResult]).then(([keyResult, valueResult]) => { + handleMapResult(keyResult, valueResult, payload, key, input, inst, ctx); + })); + } + else { + handleMapResult(keyResult, valueResult, payload, key, input, inst, ctx); + } + } + if (proms.length) + return Promise.all(proms).then(() => payload); + return payload; + }; +}))); +function handleMapResult(keyResult, valueResult, final, key, input, inst, ctx) { + if (keyResult.issues.length) { + if (util.propertyKeyTypes.has(typeof key)) { + final.issues.push(...util.prefixIssues(key, keyResult.issues)); + } + else { + final.issues.push({ + code: "invalid_key", + origin: "map", + input, + inst, + issues: keyResult.issues.map((iss) => util.finalizeIssue(iss, ctx, core.config())), + }); + } + } + if (valueResult.issues.length) { + if (util.propertyKeyTypes.has(typeof key)) { + final.issues.push(...util.prefixIssues(key, valueResult.issues)); + } + else { + final.issues.push({ + origin: "map", + code: "invalid_element", + input, + inst, + key: key, + issues: valueResult.issues.map((iss) => util.finalizeIssue(iss, ctx, core.config())), + }); + } + } + final.value.set(keyResult.value, valueResult.value); +} +const $ZodSet = /*@__PURE__*/ (/* unused pure expression or super */ null && (core.$constructor("$ZodSet", (inst, def) => { + $ZodType.init(inst, def); + const memo = core.globalConfig.memoizer; + memo?.attach(inst); + inst._zod.parse = (payload, ctx) => { + const input = payload.value; + if (!(input instanceof Set)) { + payload.issues.push({ + input, + inst, + expected: "set", + code: "invalid_type", + }); + return payload; + } + const proms = []; + payload.value = memo ? memo.alloc(inst, payload, new Set(), ctx) : new Set(); + for (const item of input) { + const result = def.valueType._zod.run({ value: item, issues: [] }, ctx); + if (result instanceof Promise) { + proms.push(result.then((result) => handleSetResult(result, payload))); + } + else + handleSetResult(result, payload); + } + if (proms.length) + return Promise.all(proms).then(() => payload); + return payload; + }; +}))); +function handleSetResult(result, final) { + if (result.issues.length) { + final.issues.push(...result.issues); + } + final.value.add(result.value); +} +const $ZodEnum = /*@__PURE__*/ $constructor("$ZodEnum", (inst, def) => { + $ZodType.init(inst, def); + const values = getEnumValues(def.entries); + const valuesSet = new Set(values); + inst._zod.values = valuesSet; + const patternValues = values.filter((k) => propertyKeyTypes.has(typeof k)); + // unmatchable fallback, RE2-safe: an empty alternation would compile to /^()$/, which matches "" + inst._zod.pattern = new RegExp(patternValues.length ? `^(${patternValues.map((o) => escapeRegex(o.toString())).join("|")})$` : "^[^\\s\\S]$"); + inst._zod.parse = (payload, _ctx) => { + const input = payload.value; + if (valuesSet.has(input)) { + return payload; + } + payload.issues.push({ + code: "invalid_value", + values, + input, + inst, + }); + return payload; + }; +}); +const $ZodLiteral = /*@__PURE__*/ $constructor("$ZodLiteral", (inst, def) => { + $ZodType.init(inst, def); + const values = new Set(def.values); + inst._zod.values = values; + // unmatchable fallback, RE2-safe: an empty alternation would compile to /^()$/, which matches "" + inst._zod.pattern = new RegExp(def.values.length + ? `^(${def.values + .map((o) => (typeof o === "string" ? escapeRegex(o) : o ? escapeRegex(o.toString()) : String(o))) + .join("|")})$` + : "^[^\\s\\S]$"); + inst._zod.parse = (payload, _ctx) => { + const input = payload.value; + if (values.has(input)) { + return payload; + } + payload.issues.push({ + code: "invalid_value", + values: def.values, + input, + inst, + }); + return payload; + }; +}); +const $ZodFile = /*@__PURE__*/ (/* unused pure expression or super */ null && (core.$constructor("$ZodFile", (inst, def) => { + $ZodType.init(inst, def); + inst._zod.parse = (payload, _ctx) => { + const input = payload.value; + // @ts-ignore + if (input instanceof File) + return payload; + payload.issues.push({ + expected: "file", + code: "invalid_type", + input, + inst, + }); + return payload; + }; +}))); +const $ZodTransform = /*@__PURE__*/ $constructor("$ZodTransform", (inst, def) => { + $ZodType.init(inst, def); + inst._zod.optin = "optional"; + globalConfig.memoizer?.guard(inst); + inst._zod.parse = (payload, ctx) => { + if (ctx.direction === "backward") { + throw new $ZodEncodeError(inst.constructor.name); + } + const _out = def.transform(payload.value, payload); + if (ctx.async) { + const output = _out instanceof Promise ? _out : Promise.resolve(_out); + return output.then((output) => { + payload.value = output; + return payload; + }); + } + if (_out instanceof Promise) { + throw new $ZodAsyncError(); + } + payload.value = _out; + return payload; + }; +}); +function handleOptionalResult(payload, result) { + // A substituting schema that still failed has no usable answer; yield undefined. Its issues are simply dropped: it ran on a payload of its own, so there is no shared array to truncate and nothing of the caller's to lose with it. + payload.value = result.issues.length ? undefined : result.value; + return payload; +} +const $ZodOptional = /*@__PURE__*/ $constructor("$ZodOptional", (inst, def) => { + $ZodType.init(inst, def); + // .optional() propagates absence rather than substituting for it, so a defaulted inner keeps its rung. + defineLazyInternal(inst, "optin", (zod) => zod.def.innerType._zod.optin === "defaulted" ? "defaulted" : "optional"); + inst._zod.optout = "optional"; + defineLazyInternal(inst, "values", (zod) => { + const values = zod.def.innerType._zod.values; + return values ? new Set([...values, undefined]) : undefined; + }); + defineLazyInternal(inst, "pattern", (zod) => { + const pattern = zod.def.innerType._zod.pattern; + return pattern ? new RegExp(`^(${cleanRegex(pattern.source)})?$`) : undefined; + }); + inst._zod.parse = (payload, ctx) => { + if (payload.value === undefined) { + // Only the top rung substitutes a value for absence; everything else leaves it intact, which is what .optional() means. + if (def.innerType._zod.optin !== "defaulted") + return payload; + // Its own payload, for the same reason $ZodCatch gets one: a pipe forwards an unrecognized key through the caller's issues array, and this must not read that as the substituting schema failing and drop it. + const result = def.innerType._zod.run({ value: payload.value, issues: [] }, ctx); + if (result instanceof Promise) + return result.then((result) => handleOptionalResult(payload, result)); + return handleOptionalResult(payload, result); + } + return def.innerType._zod.run(payload, ctx); + }; +}); +const $ZodExactOptional = /*@__PURE__*/ $constructor("$ZodExactOptional", (inst, def) => { + // Call parent init - inherits optin/optout = "optional" + $ZodOptional.init(inst, def); + // Override values/pattern to NOT add undefined + defineLazyInternal(inst, "values", (zod) => zod.def.innerType._zod.values); + defineLazyInternal(inst, "pattern", (zod) => zod.def.innerType._zod.pattern); + // Override parse to just delegate (no undefined handling) + inst._zod.parse = (payload, ctx) => { + return def.innerType._zod.run(payload, ctx); + }; +}); +const $ZodNullable = /*@__PURE__*/ $constructor("$ZodNullable", (inst, def) => { + $ZodType.init(inst, def); + defineLazyInternal(inst, "optin", (zod) => zod.def.innerType._zod.optin); + defineLazyInternal(inst, "optout", (zod) => zod.def.innerType._zod.optout); + defineLazyInternal(inst, "pattern", (zod) => { + const pattern = zod.def.innerType._zod.pattern; + return pattern ? new RegExp(`^(${cleanRegex(pattern.source)}|null)$`) : undefined; + }); + defineLazyInternal(inst, "values", (zod) => { + return zod.def.innerType._zod.values ? new Set([...zod.def.innerType._zod.values, null]) : undefined; + }); + inst._zod.parse = (payload, ctx) => { + // Forward direction (decode): allow null to pass through + if (payload.value === null) + return payload; + return def.innerType._zod.run(payload, ctx); + }; +}); +const $ZodDefault = /*@__PURE__*/ $constructor("$ZodDefault", (inst, def) => { + $ZodType.init(inst, def); + // inst._zod.qin = "true"; + inst._zod.optin = "defaulted"; + defineLazyInternal(inst, "values", (zod) => zod.def.innerType._zod.values); + inst._zod.parse = (payload, ctx) => { + if (ctx.direction === "backward") { + return def.innerType._zod.run(payload, ctx); + } + // Forward direction (decode): apply defaults for undefined input + if (payload.value === undefined) { + payload.value = def.defaultValue; + /** + * $ZodDefault returns the default value immediately in forward direction. + * It doesn't pass the default value into the validator ("prefault"). There's no reason to pass the default value through validation. The validity of the default is enforced by TypeScript statically. Otherwise, it's the responsibility of the user to ensure the default is valid. In the case of pipes with divergent in/out types, you can specify the default on the `in` schema of your ZodPipe to set a "prefault" for the pipe. */ + return payload; + } + // Forward direction: continue with default handling + const result = def.innerType._zod.run(payload, ctx); + if (result instanceof Promise) { + return result.then((result) => handleDefaultResult(result, def)); + } + return handleDefaultResult(result, def); + }; +}); +function handleDefaultResult(payload, def) { + if (payload.value === undefined) { + payload.value = def.defaultValue; + } + return payload; +} +const $ZodPrefault = /*@__PURE__*/ $constructor("$ZodPrefault", (inst, def) => { + $ZodType.init(inst, def); + inst._zod.optin = "defaulted"; + defineLazyInternal(inst, "values", (zod) => zod.def.innerType._zod.values); + inst._zod.parse = (payload, ctx) => { + if (ctx.direction === "backward") { + return def.innerType._zod.run(payload, ctx); + } + // Forward direction (decode): apply prefault for undefined input + if (payload.value === undefined) { + payload.value = def.defaultValue; + } + return def.innerType._zod.run(payload, ctx); + }; +}); +const $ZodNonOptional = /*@__PURE__*/ $constructor("$ZodNonOptional", (inst, def) => { + $ZodType.init(inst, def); + defineLazyInternal(inst, "values", (zod) => { + const v = zod.def.innerType._zod.values; + return v ? new Set([...v].filter((x) => x !== undefined)) : undefined; + }); + inst._zod.parse = (payload, ctx) => { + const result = def.innerType._zod.run(payload, ctx); + if (result instanceof Promise) { + return result.then((result) => handleNonOptionalResult(result, inst)); + } + return handleNonOptionalResult(result, inst); + }; +}); +function handleNonOptionalResult(payload, inst) { + if (!payload.issues.length && payload.value === undefined) { + payload.issues.push({ + code: "invalid_type", + expected: "nonoptional", + input: payload.value, + inst, + }); + } + return payload; +} +const $ZodSuccess = /*@__PURE__*/ (/* unused pure expression or super */ null && (core.$constructor("$ZodSuccess", (inst, def) => { + $ZodType.init(inst, def); + inst._zod.parse = (payload, ctx) => { + if (ctx.direction === "backward") { + throw new core.$ZodEncodeError("ZodSuccess"); + } + const result = def.innerType._zod.run(payload, ctx); + if (result instanceof Promise) { + return result.then((result) => { + payload.value = result.issues.length === 0; + return payload; + }); + } + payload.value = result.issues.length === 0; + return payload; + }; +}))); +function handleCatchResult(payload, result, def, ctx) { + if (!result.issues.length) { + payload.value = result.value; + // The value carries up, so the flag describing it has to carry with it: a back-edge into a node still being parsed must not be frozen by an enclosing readonly, and its checks belong to the node itself. Guarded so the ordinary case adds no own property. + if (result.memo) + payload.memo = true; + return payload; + } + // Spread the inner's own payload, not ours: `value` has to stay the input the catch was handed, and the inner ran on a payload of its own so its issues are already private to this call. + payload.value = def.catchValue({ + ...result, + value: payload.value, + error: { + issues: result.issues.map((iss) => finalizeIssue(iss, ctx, core_config())), + }, + input: payload.value, + }); + return payload; +} +const $ZodCatch = /*@__PURE__*/ $constructor("$ZodCatch", (inst, def) => { + $ZodType.init(inst, def); + defineLazyInternal(inst, "optin", (zod) => zod.def.innerType._zod.optin === "defaulted" ? "defaulted" : "optional"); + defineLazyInternal(inst, "optout", (zod) => zod.def.innerType._zod.optout); + defineLazyInternal(inst, "values", (zod) => zod.def.innerType._zod.values); + inst._zod.parse = (payload, ctx) => { + if (ctx.direction === "backward") { + return def.innerType._zod.run(payload, ctx); + } + // Forward direction (decode): apply catch logic + const result = def.innerType._zod.run({ value: payload.value, issues: [] }, ctx); + if (result instanceof Promise) { + return result.then((result) => handleCatchResult(payload, result, def, ctx)); + } + return handleCatchResult(payload, result, def, ctx); + }; +}); +const $ZodNaN = /*@__PURE__*/ (/* unused pure expression or super */ null && (core.$constructor("$ZodNaN", (inst, def) => { + $ZodType.init(inst, def); + inst._zod.parse = (payload, _ctx) => { + if (typeof payload.value !== "number" || !Number.isNaN(payload.value)) { + payload.issues.push({ + input: payload.value, + inst, + expected: "nan", + code: "invalid_type", + }); + return payload; + } + return payload; + }; +}))); +const $ZodPipe = /*@__PURE__*/ $constructor("$ZodPipe", (inst, def) => { + $ZodType.init(inst, def); + defineLazyInternal(inst, "values", (zod) => zod.def.in._zod.values); + defineLazyInternal(inst, "optin", (zod) => zod.def.in._zod.optin); + defineLazyInternal(inst, "optout", (zod) => zod.def.out._zod.optout); + defineLazyInternal(inst, "propValues", (zod) => zod.def.in._zod.propValues); + inst._zod.parse = (payload, ctx) => { + if (ctx.direction === "backward") { + const right = def.out._zod.run(payload, ctx); + if (right instanceof Promise) { + return right.then((right) => handlePipeResult(right, def.in, ctx)); + } + return handlePipeResult(right, def.in, ctx); + } + const left = def.in._zod.run(payload, ctx); + if (left instanceof Promise) { + return left.then((left) => handlePipeResult(left, def.out, ctx)); + } + return handlePipeResult(left, def.out, ctx); + }; +}); +function handlePipeResult(left, next, ctx) { + // Any issue stops the pipe, so a failing refinement never feeds its transform. An unrecognized key is the exception: it describes the input's extra properties, not the value being piped, and an enclosing intersection may yet reconcile it. + if (left.issues.some((iss) => iss.code !== "unrecognized_keys")) { + // prevent further checks + left.aborted = true; + return left; + } + return next._zod.run({ value: left.value, issues: left.issues }, ctx); +} +const $ZodCodec = /*@__PURE__*/ (/* unused pure expression or super */ null && (core.$constructor("$ZodCodec", (inst, def) => { + $ZodType.init(inst, def); + util.defineLazyInternal(inst, "values", (zod) => zod.def.in._zod.values); + util.defineLazyInternal(inst, "optin", (zod) => zod.def.in._zod.optin); + util.defineLazyInternal(inst, "optout", (zod) => zod.def.out._zod.optout); + util.defineLazyInternal(inst, "propValues", (zod) => zod.def.in._zod.propValues); + inst._zod.parse = (payload, ctx) => { + const direction = ctx.direction || "forward"; + if (direction === "forward") { + const left = def.in._zod.run(payload, ctx); + if (left instanceof Promise) { + return left.then((left) => handleCodecAResult(left, def, ctx)); + } + return handleCodecAResult(left, def, ctx); + } + else { + const right = def.out._zod.run(payload, ctx); + if (right instanceof Promise) { + return right.then((right) => handleCodecAResult(right, def, ctx)); + } + return handleCodecAResult(right, def, ctx); + } + }; +}))); +function handleCodecAResult(result, def, ctx) { + if (result.issues.length) { + // prevent further checks + result.aborted = true; + return result; + } + const direction = ctx.direction || "forward"; + if (direction === "forward") { + const transformed = def.transform(result.value, result); + if (transformed instanceof Promise) { + return transformed.then((value) => handleCodecTxResult(result, value, def.out, ctx)); + } + return handleCodecTxResult(result, transformed, def.out, ctx); + } + else { + const transformed = def.reverseTransform(result.value, result); + if (transformed instanceof Promise) { + return transformed.then((value) => handleCodecTxResult(result, value, def.in, ctx)); + } + return handleCodecTxResult(result, transformed, def.in, ctx); + } +} +function handleCodecTxResult(left, value, nextSchema, ctx) { + // Check if transform added any issues + if (left.issues.length) { + left.aborted = true; + return left; + } + return nextSchema._zod.run({ value, issues: left.issues }, ctx); +} +const $ZodPreprocess = /*@__PURE__*/ $constructor("$ZodPreprocess", (inst, def) => { + $ZodPipe.init(inst, def); +}); +const $ZodReadonly = /*@__PURE__*/ $constructor("$ZodReadonly", (inst, def) => { + $ZodType.init(inst, def); + defineLazyInternal(inst, "propValues", (zod) => zod.def.innerType._zod.propValues); + defineLazyInternal(inst, "values", (zod) => zod.def.innerType._zod.values); + defineLazyInternal(inst, "optin", (zod) => zod.def.innerType?._zod?.optin); + defineLazyInternal(inst, "optout", (zod) => zod.def.innerType?._zod?.optout); + inst._zod.parse = (payload, ctx) => { + if (ctx.direction === "backward") { + return def.innerType._zod.run(payload, ctx); + } + const result = def.innerType._zod.run(payload, ctx); + if (result instanceof Promise) { + return result.then(handleReadonlyResult); + } + return handleReadonlyResult(result); + }; +}); +function handleReadonlyResult(payload) { + // A repeat visit hands back a node that is still being built; freezing it here would make the rest of its keys fail to assign. + if (!payload.memo) + payload.value = Object.freeze(payload.value); + return payload; +} +const $ZodTemplateLiteral = /*@__PURE__*/ (/* unused pure expression or super */ null && (core.$constructor("$ZodTemplateLiteral", (inst, def) => { + $ZodType.init(inst, def); + const regexParts = []; + for (const part of def.parts) { + if (typeof part === "object" && part !== null) { + // is Zod schema + if (!part._zod.pattern) { + // if (!source) + throw new Error(`Invalid template literal part, no pattern found: ${[...part._zod.traits].shift()}`); + } + const source = part._zod.pattern instanceof RegExp ? part._zod.pattern.source : part._zod.pattern; + if (!source) + throw new Error(`Invalid template literal part: ${part._zod.traits}`); + const start = source.startsWith("^") ? 1 : 0; + const end = source.endsWith("$") ? source.length - 1 : source.length; + regexParts.push(source.slice(start, end)); + } + else if (part === null || util.primitiveTypes.has(typeof part)) { + regexParts.push(util.escapeRegex(`${part}`)); + } + else { + throw new Error(`Invalid template literal part: ${part}`); + } + } + inst._zod.pattern = new RegExp(`^${regexParts.join("")}$`); + inst._zod.parse = (payload, _ctx) => { + if (typeof payload.value !== "string") { + payload.issues.push({ + input: payload.value, + inst, + expected: "string", + code: "invalid_type", + }); + return payload; + } + inst._zod.pattern.lastIndex = 0; + if (!inst._zod.pattern.test(payload.value)) { + payload.issues.push({ + input: payload.value, + inst, + code: "invalid_format", + format: def.format ?? "template_literal", + pattern: inst._zod.pattern.source, + }); + return payload; + } + return payload; + }; +}))); +const $ZodFunction = /*@__PURE__*/ (/* unused pure expression or super */ null && (core.$constructor("$ZodFunction", (inst, def) => { + $ZodType.init(inst, def); + // Defined, not assigned: the classic prototype exposes `_def` as a getter with no setter. + Object.defineProperty(inst, "_def", { value: def }); + inst._zod.def = def; + inst.implement = (func) => { + if (typeof func !== "function") { + throw new Error("implement() must be called with a function"); + } + // Defined inline so the closure stays anonymous: binding it to a `const` first names it, which costs 256 bytes per implemented function. + return Object.defineProperty(function (...args) { + const parsedArgs = inst._def.input ? parse(inst._def.input, args) : args; + const result = Reflect.apply(func, this, parsedArgs); + if (inst._def.output) { + return parse(inst._def.output, result); + } + return result; + }, "_zod", { value: inst._zod, enumerable: false }); + }; + inst.implementAsync = (func) => { + if (typeof func !== "function") { + throw new Error("implementAsync() must be called with a function"); + } + return Object.defineProperty(async function (...args) { + const parsedArgs = inst._def.input ? await parseAsync(inst._def.input, args) : args; + const result = await Reflect.apply(func, this, parsedArgs); + if (inst._def.output) { + return await parseAsync(inst._def.output, result); + } + return result; + }, "_zod", { value: inst._zod, enumerable: false }); + }; + inst._zod.parse = (payload, _ctx) => { + if (typeof payload.value !== "function") { + payload.issues.push({ + code: "invalid_type", + expected: "function", + input: payload.value, + inst, + }); + return payload; + } + // Check if output is a promise type to determine if we should use async implementation + const hasPromiseOutput = inst._def.output && inst._def.output._zod.def.type === "promise"; + if (hasPromiseOutput) { + payload.value = inst.implementAsync(payload.value); + } + else { + payload.value = inst.implement(payload.value); + } + return payload; + }; + inst.input = (...args) => { + const F = inst.constructor; + if (Array.isArray(args[0])) { + return new F({ + type: "function", + input: new $ZodTuple({ + type: "tuple", + items: args[0], + rest: args[1], + }), + output: inst._def.output, + }); + } + return new F({ + type: "function", + input: args[0], + output: inst._def.output, + }); + }; + inst.output = (output) => { + const F = inst.constructor; + return new F({ + type: "function", + input: inst._def.input, + output, + }); + }; + return inst; +}))); +const $ZodPromise = /*@__PURE__*/ (/* unused pure expression or super */ null && (core.$constructor("$ZodPromise", (inst, def) => { + $ZodType.init(inst, def); + inst._zod.parse = (payload, ctx) => { + return Promise.resolve(payload.value).then((inner) => def.innerType._zod.run({ value: inner, issues: [] }, ctx)); + }; +}))); +const $ZodLazy = /*@__PURE__*/ $constructor("$ZodLazy", (inst, def) => { + $ZodType.init(inst, def); + // Cache the resolved inner type on the shared `def` so all clones of this lazy (e.g. via `.describe()`/`.meta()`) share the same inner instance, preserving identity for cycle detection on recursive schemas. + defineLazy(inst._zod, "innerType", () => { + const d = def; + if (!d._cachedInner) + d._cachedInner = def.getter(); + return d._cachedInner; + }); + defineLazyInternal(inst, "pattern", (zod) => zod.innerType?._zod?.pattern); + defineLazyInternal(inst, "propValues", (zod) => zod.innerType?._zod?.propValues); + defineLazyInternal(inst, "optin", (zod) => zod.innerType?._zod?.optin ?? undefined); + defineLazyInternal(inst, "optout", (zod) => zod.innerType?._zod?.optout ?? undefined); + inst._zod.parse = (payload, ctx) => { + const inner = inst._zod.innerType; + return inner._zod.run(payload, ctx); + }; +}); +const $ZodCustom = /*@__PURE__*/ $constructor("$ZodCustom", (inst, def) => { + $ZodCheck.init(inst, def); + $ZodType.init(inst, def); + inst._zod.parse = (payload, _) => { + return payload; + }; + inst._zod.check = (payload) => { + const input = payload.value; + const r = def.fn(input); + if (r instanceof Promise) { + return r.then((r) => handleRefineResult(r, payload, input, inst)); + } + handleRefineResult(r, payload, input, inst); + return; + }; +}); +function handleRefineResult(result, payload, input, inst) { + if (!result) { + const _iss = { + code: "custom", + input, + inst, // incorporates params.error into issue reporting + path: [...(inst._zod.def.path ?? [])], // incorporates params.error into issue reporting + continue: !inst._zod.def.abort, + // params: inst._zod.def.params, + }; + if (inst._zod.def.params) + _iss.params = inst._zod.def.params; + payload.issues.push(util_issue(_iss)); + } +} + +var registries_a; +const $output = /*@__PURE__*/ (/* unused pure expression or super */ null && (Symbol("ZodOutput"))); +const $input = /*@__PURE__*/ (/* unused pure expression or super */ null && (Symbol("ZodInput"))); +class $ZodRegistry { + constructor() { + this._map = new WeakMap(); + this._idmap = new Map(); + } + add(schema, ..._meta) { + const meta = _meta[0]; + this._map.set(schema, meta); + if (meta && typeof meta === "object" && "id" in meta) { + this._idmap.set(meta.id, schema); + } + return this; + } + clear() { + this._map = new WeakMap(); + this._idmap = new Map(); + return this; + } + remove(schema) { + const meta = this._map.get(schema); + if (meta && typeof meta === "object" && "id" in meta) { + this._idmap.delete(meta.id); + } + this._map.delete(schema); + return this; + } + get(schema) { + // return this._map.get(schema) as any; + // inherit metadata + const p = schema._zod.parent; + if (p) { + const pm = { ...(this.get(p) ?? {}) }; + delete pm.id; // do not inherit id + const f = { ...pm, ...this._map.get(schema) }; + return Object.keys(f).length ? f : undefined; + } + return this._map.get(schema); + } + has(schema) { + return this._map.has(schema); + } +} +// registries +function registries_registry() { + return new $ZodRegistry(); +} +(registries_a = globalThis).__zod_globalRegistry ?? (registries_a.__zod_globalRegistry = registries_registry()); +const globalRegistry = globalThis.__zod_globalRegistry; + + + + + +// @__NO_SIDE_EFFECTS__ +function _string(Class, params) { + return new Class({ + type: "string", + ...normalizeParams(params), + }); +} +// @__NO_SIDE_EFFECTS__ +function _coercedString(Class, params) { + return new Class({ + type: "string", + coerce: true, + ...util.normalizeParams(params), + }); +} +// @__NO_SIDE_EFFECTS__ +function _email(Class, params) { + return new Class({ + type: "string", + format: "email", + check: "string_format", + abort: false, + ...normalizeParams(params), + }); +} +// @__NO_SIDE_EFFECTS__ +function _guid(Class, params) { + return new Class({ + type: "string", + format: "guid", + check: "string_format", + abort: false, + ...normalizeParams(params), + }); +} +// @__NO_SIDE_EFFECTS__ +function _uuid(Class, params) { + return new Class({ + type: "string", + format: "uuid", + check: "string_format", + abort: false, + ...normalizeParams(params), + }); +} +// @__NO_SIDE_EFFECTS__ +function _uuidv4(Class, params) { + return new Class({ + type: "string", + format: "uuid", + check: "string_format", + abort: false, + version: "v4", + ...normalizeParams(params), + }); +} +// @__NO_SIDE_EFFECTS__ +function _uuidv6(Class, params) { + return new Class({ + type: "string", + format: "uuid", + check: "string_format", + abort: false, + version: "v6", + ...normalizeParams(params), + }); +} +// @__NO_SIDE_EFFECTS__ +function _uuidv7(Class, params) { + return new Class({ + type: "string", + format: "uuid", + check: "string_format", + abort: false, + version: "v7", + ...normalizeParams(params), + }); +} +// @__NO_SIDE_EFFECTS__ +function _url(Class, params) { + return new Class({ + type: "string", + format: "url", + check: "string_format", + abort: false, + ...normalizeParams(params), + }); +} +// @__NO_SIDE_EFFECTS__ +function api_emoji(Class, params) { + return new Class({ + type: "string", + format: "emoji", + check: "string_format", + abort: false, + ...normalizeParams(params), + }); +} +// @__NO_SIDE_EFFECTS__ +function _nanoid(Class, params) { + return new Class({ + type: "string", + format: "nanoid", + check: "string_format", + abort: false, + ...normalizeParams(params), + }); +} +/** + * @deprecated CUID v1 is deprecated by its authors due to information leakage + * (timestamps embedded in the id). Use {@link _cuid2} instead. + * See https://github.com/paralleldrive/cuid. + */ +// @__NO_SIDE_EFFECTS__ +function _cuid(Class, params) { + return new Class({ + type: "string", + format: "cuid", + check: "string_format", + abort: false, + ...normalizeParams(params), + }); +} +// @__NO_SIDE_EFFECTS__ +function _cuid2(Class, params) { + return new Class({ + type: "string", + format: "cuid2", + check: "string_format", + abort: false, + ...normalizeParams(params), + }); +} +// @__NO_SIDE_EFFECTS__ +function _ulid(Class, params) { + return new Class({ + type: "string", + format: "ulid", + check: "string_format", + abort: false, + ...normalizeParams(params), + }); +} +// @__NO_SIDE_EFFECTS__ +function _xid(Class, params) { + return new Class({ + type: "string", + format: "xid", + check: "string_format", + abort: false, + ...normalizeParams(params), + }); +} +// @__NO_SIDE_EFFECTS__ +function _ksuid(Class, params) { + return new Class({ + type: "string", + format: "ksuid", + check: "string_format", + abort: false, + ...normalizeParams(params), + }); +} +// @__NO_SIDE_EFFECTS__ +function _ipv4(Class, params) { + return new Class({ + type: "string", + format: "ipv4", + check: "string_format", + abort: false, + ...normalizeParams(params), + }); +} +// @__NO_SIDE_EFFECTS__ +function _ipv6(Class, params) { + return new Class({ + type: "string", + format: "ipv6", + check: "string_format", + abort: false, + ...normalizeParams(params), + }); +} +// @__NO_SIDE_EFFECTS__ +function _mac(Class, params) { + return new Class({ + type: "string", + format: "mac", + check: "string_format", + abort: false, + ...util.normalizeParams(params), + }); +} +// @__NO_SIDE_EFFECTS__ +function _cidrv4(Class, params) { + return new Class({ + type: "string", + format: "cidrv4", + check: "string_format", + abort: false, + ...normalizeParams(params), + }); +} +// @__NO_SIDE_EFFECTS__ +function _cidrv6(Class, params) { + return new Class({ + type: "string", + format: "cidrv6", + check: "string_format", + abort: false, + ...normalizeParams(params), + }); +} +// @__NO_SIDE_EFFECTS__ +function _base64(Class, params) { + return new Class({ + type: "string", + format: "base64", + check: "string_format", + abort: false, + ...normalizeParams(params), + }); +} +// @__NO_SIDE_EFFECTS__ +function _base64url(Class, params) { + return new Class({ + type: "string", + format: "base64url", + check: "string_format", + abort: false, + ...normalizeParams(params), + }); +} +// @__NO_SIDE_EFFECTS__ +function _e164(Class, params) { + return new Class({ + type: "string", + format: "e164", + check: "string_format", + abort: false, + ...normalizeParams(params), + }); +} +// @__NO_SIDE_EFFECTS__ +function _creditCard(Class, params) { + return new Class({ + type: "string", + format: "credit_card", + check: "string_format", + abort: false, + ...util.normalizeParams(params), + }); +} +// @__NO_SIDE_EFFECTS__ +function _jwt(Class, params) { + return new Class({ + type: "string", + format: "jwt", + check: "string_format", + abort: false, + ...normalizeParams(params), + }); +} +const TimePrecision = (/* unused pure expression or super */ null && ({ + Any: null, + Minute: -1, + Second: 0, + Millisecond: 3, + Microsecond: 6, +})); +// @__NO_SIDE_EFFECTS__ +function _isoDateTime(Class, params) { + return new Class({ + type: "string", + format: "datetime", + check: "string_format", + offset: false, + local: false, + precision: null, + ...normalizeParams(params), + }); +} +// @__NO_SIDE_EFFECTS__ +function _isoDate(Class, params) { + return new Class({ + type: "string", + format: "date", + check: "string_format", + ...normalizeParams(params), + }); +} +// @__NO_SIDE_EFFECTS__ +function _isoTime(Class, params) { + return new Class({ + type: "string", + format: "time", + check: "string_format", + precision: null, + ...normalizeParams(params), + }); +} +// @__NO_SIDE_EFFECTS__ +function _isoDuration(Class, params) { + return new Class({ + type: "string", + format: "duration", + check: "string_format", + ...normalizeParams(params), + }); +} +// @__NO_SIDE_EFFECTS__ +function _number(Class, params) { + return new Class({ + type: "number", + checks: [], + ...normalizeParams(params), + }); +} +// @__NO_SIDE_EFFECTS__ +function _coercedNumber(Class, params) { + return new Class({ + type: "number", + coerce: true, + checks: [], + ...normalizeParams(params), + }); +} +// @__NO_SIDE_EFFECTS__ +function _int(Class, params) { + return new Class({ + type: "number", + check: "number_format", + abort: false, + format: "safeint", + ...normalizeParams(params), + }); +} +// @__NO_SIDE_EFFECTS__ +function _float32(Class, params) { + return new Class({ + type: "number", + check: "number_format", + abort: false, + format: "float32", + ...util.normalizeParams(params), + }); +} +// @__NO_SIDE_EFFECTS__ +function _float64(Class, params) { + return new Class({ + type: "number", + check: "number_format", + abort: false, + format: "float64", + ...util.normalizeParams(params), + }); +} +// @__NO_SIDE_EFFECTS__ +function _int32(Class, params) { + return new Class({ + type: "number", + check: "number_format", + abort: false, + format: "int32", + ...util.normalizeParams(params), + }); +} +// @__NO_SIDE_EFFECTS__ +function _uint32(Class, params) { + return new Class({ + type: "number", + check: "number_format", + abort: false, + format: "uint32", + ...util.normalizeParams(params), + }); +} +// @__NO_SIDE_EFFECTS__ +function _boolean(Class, params) { + return new Class({ + type: "boolean", + ...normalizeParams(params), + }); +} +// @__NO_SIDE_EFFECTS__ +function _coercedBoolean(Class, params) { + return new Class({ + type: "boolean", + coerce: true, + ...util.normalizeParams(params), + }); +} +// @__NO_SIDE_EFFECTS__ +function _bigint(Class, params) { + return new Class({ + type: "bigint", + ...util.normalizeParams(params), + }); +} +// @__NO_SIDE_EFFECTS__ +function _coercedBigint(Class, params) { + return new Class({ + type: "bigint", + coerce: true, + ...util.normalizeParams(params), + }); +} +// @__NO_SIDE_EFFECTS__ +function _int64(Class, params) { + return new Class({ + type: "bigint", + check: "bigint_format", + abort: false, + format: "int64", + ...util.normalizeParams(params), + }); +} +// @__NO_SIDE_EFFECTS__ +function _uint64(Class, params) { + return new Class({ + type: "bigint", + check: "bigint_format", + abort: false, + format: "uint64", + ...util.normalizeParams(params), + }); +} +// @__NO_SIDE_EFFECTS__ +function _symbol(Class, params) { + return new Class({ + type: "symbol", + ...util.normalizeParams(params), + }); +} +// @__NO_SIDE_EFFECTS__ +function api_undefined(Class, params) { + return new Class({ + type: "undefined", + ...util.normalizeParams(params), + }); +} +// @__NO_SIDE_EFFECTS__ +function api_null(Class, params) { + return new Class({ + type: "null", + ...normalizeParams(params), + }); +} +// @__NO_SIDE_EFFECTS__ +function _any(Class) { + return new Class({ + type: "any", + }); +} +// @__NO_SIDE_EFFECTS__ +function _unknown(Class) { + return new Class({ + type: "unknown", + }); +} +// @__NO_SIDE_EFFECTS__ +function _never(Class, params) { + return new Class({ + type: "never", + ...normalizeParams(params), + }); +} +// @__NO_SIDE_EFFECTS__ +function _void(Class, params) { + return new Class({ + type: "void", + ...util.normalizeParams(params), + }); +} +// @__NO_SIDE_EFFECTS__ +function _date(Class, params) { + return new Class({ + type: "date", + ...util.normalizeParams(params), + }); +} +// @__NO_SIDE_EFFECTS__ +function _coercedDate(Class, params) { + return new Class({ + type: "date", + coerce: true, + ...util.normalizeParams(params), + }); +} +// @__NO_SIDE_EFFECTS__ +function _nan(Class, params) { + return new Class({ + type: "nan", + ...util.normalizeParams(params), + }); +} +// @__NO_SIDE_EFFECTS__ +function _lt(value, params) { + return new $ZodCheckLessThan({ + check: "less_than", + ...normalizeParams(params), + value, + inclusive: false, + }); +} +// @__NO_SIDE_EFFECTS__ +function _lte(value, params) { + return new $ZodCheckLessThan({ + check: "less_than", + ...normalizeParams(params), + value, + inclusive: true, + }); +} + +// @__NO_SIDE_EFFECTS__ +function _gt(value, params) { + return new $ZodCheckGreaterThan({ + check: "greater_than", + ...normalizeParams(params), + value, + inclusive: false, + }); +} +// @__NO_SIDE_EFFECTS__ +function _gte(value, params) { + return new $ZodCheckGreaterThan({ + check: "greater_than", + ...normalizeParams(params), + value, + inclusive: true, + }); +} + +// @__NO_SIDE_EFFECTS__ +function _positive(params) { + return _gt(0, params); +} +// negative +// @__NO_SIDE_EFFECTS__ +function _negative(params) { + return _lt(0, params); +} +// nonpositive +// @__NO_SIDE_EFFECTS__ +function _nonpositive(params) { + return _lte(0, params); +} +// nonnegative +// @__NO_SIDE_EFFECTS__ +function _nonnegative(params) { + return _gte(0, params); +} +// @__NO_SIDE_EFFECTS__ +function _multipleOf(value, params) { + return new $ZodCheckMultipleOf({ + check: "multiple_of", + ...normalizeParams(params), + value, + }); +} +// @__NO_SIDE_EFFECTS__ +function _maxSize(maximum, params) { + return new checks.$ZodCheckMaxSize({ + check: "max_size", + ...util.normalizeParams(params), + maximum, + }); +} +// @__NO_SIDE_EFFECTS__ +function _minSize(minimum, params) { + return new checks.$ZodCheckMinSize({ + check: "min_size", + ...util.normalizeParams(params), + minimum, + }); +} +// @__NO_SIDE_EFFECTS__ +function _size(size, params) { + return new checks.$ZodCheckSizeEquals({ + check: "size_equals", + ...util.normalizeParams(params), + size, + }); +} +// @__NO_SIDE_EFFECTS__ +function _maxLength(maximum, params) { + const ch = new $ZodCheckMaxLength({ + check: "max_length", + ...normalizeParams(params), + maximum, + }); + return ch; +} +// @__NO_SIDE_EFFECTS__ +function _minLength(minimum, params) { + return new $ZodCheckMinLength({ + check: "min_length", + ...normalizeParams(params), + minimum, + }); +} +// @__NO_SIDE_EFFECTS__ +function _length(length, params) { + return new $ZodCheckLengthEquals({ + check: "length_equals", + ...normalizeParams(params), + length, + }); +} +// @__NO_SIDE_EFFECTS__ +function _regex(pattern, params) { + return new $ZodCheckRegex({ + check: "string_format", + format: "regex", + ...normalizeParams(params), + pattern, + }); +} +// @__NO_SIDE_EFFECTS__ +function _lowercase(params) { + return new $ZodCheckLowerCase({ + check: "string_format", + format: "lowercase", + ...normalizeParams(params), + }); +} +// @__NO_SIDE_EFFECTS__ +function _uppercase(params) { + return new $ZodCheckUpperCase({ + check: "string_format", + format: "uppercase", + ...normalizeParams(params), + }); +} +// @__NO_SIDE_EFFECTS__ +function _includes(includes, params) { + return new $ZodCheckIncludes({ + check: "string_format", + format: "includes", + ...normalizeParams(params), + includes, + }); +} +// @__NO_SIDE_EFFECTS__ +function _startsWith(prefix, params) { + return new $ZodCheckStartsWith({ + check: "string_format", + format: "starts_with", + ...normalizeParams(params), + prefix, + }); +} +// @__NO_SIDE_EFFECTS__ +function _endsWith(suffix, params) { + return new $ZodCheckEndsWith({ + check: "string_format", + format: "ends_with", + ...normalizeParams(params), + suffix, + }); +} +// @__NO_SIDE_EFFECTS__ +function _property(property, schema, params) { + return new checks.$ZodCheckProperty({ + check: "property", + property, + schema, + ...util.normalizeParams(params), + }); +} +// @__NO_SIDE_EFFECTS__ +function _properties(shape) { + return Object.entries(shape).map(([property, schema]) => new checks.$ZodCheckProperty({ check: "property", property, schema })); +} +// @__NO_SIDE_EFFECTS__ +function _mime(types, params) { + return new checks.$ZodCheckMimeType({ + check: "mime_type", + mime: types, + ...util.normalizeParams(params), + }); +} +// @__NO_SIDE_EFFECTS__ +function _overwrite(tx) { + return new $ZodCheckOverwrite({ + check: "overwrite", + tx, + }); +} +// normalize +// @__NO_SIDE_EFFECTS__ +function _normalize(form) { + return _overwrite((input) => input.normalize(form)); +} +// trim +// @__NO_SIDE_EFFECTS__ +function _trim() { + return _overwrite((input) => input.trim()); +} +// toLowerCase +// @__NO_SIDE_EFFECTS__ +function _toLowerCase() { + return _overwrite((input) => input.toLowerCase()); +} +// toUpperCase +// @__NO_SIDE_EFFECTS__ +function _toUpperCase() { + return _overwrite((input) => input.toUpperCase()); +} +// slugify +// @__NO_SIDE_EFFECTS__ +function _slugify() { + return _overwrite((input) => slugify(input)); +} +// @__NO_SIDE_EFFECTS__ +function _array(Class, element, params) { + return new Class({ + type: "array", + element, + // get element() { + // return element; + // }, + ...normalizeParams(params), + }); +} +// @__NO_SIDE_EFFECTS__ +function _union(Class, options, params) { + return new Class({ + type: "union", + options, + ...util.normalizeParams(params), + }); +} +function _xor(Class, options, params) { + return new Class({ + type: "union", + options, + inclusive: false, + ...util.normalizeParams(params), + }); +} +// @__NO_SIDE_EFFECTS__ +function _discriminatedUnion(Class, discriminator, options, params) { + return new Class({ + type: "union", + options: options, + discriminator, + ...util.normalizeParams(params), + }); +} +// @__NO_SIDE_EFFECTS__ +function _intersection(Class, left, right) { + return new Class({ + type: "intersection", + left, + right, + }); +} +// export function _tuple( +// Class: util.SchemaClass, +// items: [], +// params?: string | $ZodTupleParams +// ): schemas.$ZodTuple<[], null>; +// @__NO_SIDE_EFFECTS__ +function _tuple(Class, items, _paramsOrRest, _params) { + const hasRest = _paramsOrRest instanceof schemas.$ZodType; + const params = hasRest ? _params : _paramsOrRest; + const rest = hasRest ? _paramsOrRest : null; + return new Class({ + type: "tuple", + items, + rest, + ...util.normalizeParams(params), + }); +} +// @__NO_SIDE_EFFECTS__ +function _record(Class, keyType, valueType, params) { + return new Class({ + type: "record", + keyType, + valueType, + ...util.normalizeParams(params), + }); +} +// @__NO_SIDE_EFFECTS__ +function _map(Class, keyType, valueType, params) { + return new Class({ + type: "map", + keyType, + valueType, + ...util.normalizeParams(params), + }); +} +// @__NO_SIDE_EFFECTS__ +function _set(Class, valueType, params) { + return new Class({ + type: "set", + valueType, + ...util.normalizeParams(params), + }); +} +// @__NO_SIDE_EFFECTS__ +function _enum(Class, values, params) { + const entries = Array.isArray(values) ? Object.fromEntries(values.map((v) => [v, v])) : values; + // if (Array.isArray(values)) { + // for (const value of values) { + // entries[value] = value; + // } + // } else { + // Object.assign(entries, values); + // } + // const entries: util.EnumLike = {}; + // for (const val of values) { + // entries[val] = val; + // } + return new Class({ + type: "enum", + entries, + ...util.normalizeParams(params), + }); +} +// @__NO_SIDE_EFFECTS__ +/** @deprecated This API has been merged into `z.enum()`. Use `z.enum()` instead. + * + * ```ts + * enum Colors { red, green, blue } + * z.enum(Colors); + * ``` + */ +function _nativeEnum(Class, entries, params) { + return new Class({ + type: "enum", + entries, + ...util.normalizeParams(params), + }); +} +// @__NO_SIDE_EFFECTS__ +function _literal(Class, value, params) { + return new Class({ + type: "literal", + values: Array.isArray(value) ? value : [value], + ...util.normalizeParams(params), + }); +} +// @__NO_SIDE_EFFECTS__ +function _file(Class, params) { + return new Class({ + type: "file", + ...util.normalizeParams(params), + }); +} +// @__NO_SIDE_EFFECTS__ +function _transform(Class, fn) { + return new Class({ + type: "transform", + transform: fn, + }); +} +// @__NO_SIDE_EFFECTS__ +function _optional(Class, innerType) { + return new Class({ + type: "optional", + innerType, + }); +} +// @__NO_SIDE_EFFECTS__ +function _nullable(Class, innerType) { + return new Class({ + type: "nullable", + innerType, + }); +} +// @__NO_SIDE_EFFECTS__ +function _default(Class, innerType, defaultValue) { + return new Class({ + type: "default", + innerType, + get defaultValue() { + return typeof defaultValue === "function" ? defaultValue() : util.shallowClone(defaultValue); + }, + }); +} +// @__NO_SIDE_EFFECTS__ +function _nonoptional(Class, innerType, params) { + return new Class({ + type: "nonoptional", + innerType, + ...util.normalizeParams(params), + }); +} +// @__NO_SIDE_EFFECTS__ +function _success(Class, innerType) { + return new Class({ + type: "success", + innerType, + }); +} +// @__NO_SIDE_EFFECTS__ +function _catch(Class, innerType, catchValue) { + return new Class({ + type: "catch", + innerType, + catchValue: (typeof catchValue === "function" ? catchValue : util.constantCatch(catchValue)), + }); +} +// @__NO_SIDE_EFFECTS__ +function _pipe(Class, in_, out) { + return new Class({ + type: "pipe", + in: in_, + out, + }); +} +// @__NO_SIDE_EFFECTS__ +function _readonly(Class, innerType) { + return new Class({ + type: "readonly", + innerType, + }); +} +// @__NO_SIDE_EFFECTS__ +function _templateLiteral(Class, parts, params) { + return new Class({ + type: "template_literal", + parts, + ...util.normalizeParams(params), + }); +} +// @__NO_SIDE_EFFECTS__ +function _lazy(Class, getter) { + return new Class({ + type: "lazy", + getter, + }); +} +// @__NO_SIDE_EFFECTS__ +function _promise(Class, innerType) { + return new Class({ + type: "promise", + innerType, + }); +} +// @__NO_SIDE_EFFECTS__ +function _custom(Class, fn, _params) { + const norm = util.normalizeParams(_params); + norm.abort ?? (norm.abort = true); // default to abort:false + const schema = new Class({ + type: "custom", + check: "custom", + fn: fn, + ...norm, + }); + return schema; +} +// same as _custom but defaults to abort:false +// @__NO_SIDE_EFFECTS__ +function _refine(Class, fn, _params) { + const schema = new Class({ + type: "custom", + check: "custom", + fn: fn, + ...normalizeParams(_params), + }); + return schema; +} +// @__NO_SIDE_EFFECTS__ +function _superRefine(fn, params) { + const ch = _check((payload) => { + payload.addIssue = (issue) => { + if (typeof issue === "string") { + payload.issues.push(util_issue(issue, payload.value, ch._zod.def)); + } + else { + // for Zod 3 backwards compatibility + const _issue = issue; + if (_issue.fatal) + _issue.continue = false; + _issue.code ?? (_issue.code = "custom"); + if (!("input" in _issue)) + _issue.input = payload.value; + _issue.inst ?? (_issue.inst = ch); + _issue.continue ?? (_issue.continue = !ch._zod.def.abort); // abort is always undefined, so this is always true... + payload.issues.push(util_issue(_issue)); + } + }; + return fn(payload.value, payload); + }, params); + return ch; +} +// @__NO_SIDE_EFFECTS__ +function _check(fn, params) { + const ch = new $ZodCheck({ + check: "custom", + ...normalizeParams(params), + }); + ch._zod.check = fn; + return ch; +} +// @__NO_SIDE_EFFECTS__ +function describe(description) { + const ch = new $ZodCheck({ check: "describe" }); + ch._zod.onattach = [ + (inst) => { + const existing = globalRegistry.get(inst) ?? {}; + globalRegistry.add(inst, { ...existing, description }); + }, + ]; + ch._zod.check = () => { }; // no-op check + return ch; +} +// @__NO_SIDE_EFFECTS__ +function api_meta(metadata) { + const ch = new $ZodCheck({ check: "meta" }); + ch._zod.onattach = [ + (inst) => { + const existing = globalRegistry.get(inst) ?? {}; + globalRegistry.add(inst, { ...existing, ...metadata }); + }, + ]; + ch._zod.check = () => { }; // no-op check + return ch; +} +// @__NO_SIDE_EFFECTS__ +function _stringbool(Classes, _params) { + const params = util.normalizeParams(_params); + let truthyArray = params.truthy ?? ["true", "1", "yes", "on", "y", "enabled"]; + let falsyArray = params.falsy ?? ["false", "0", "no", "off", "n", "disabled"]; + if (params.case !== "sensitive") { + truthyArray = truthyArray.map((v) => (typeof v === "string" ? v.toLowerCase() : v)); + falsyArray = falsyArray.map((v) => (typeof v === "string" ? v.toLowerCase() : v)); + } + const truthySet = new Set(truthyArray); + const falsySet = new Set(falsyArray); + const _Codec = Classes.Codec ?? schemas.$ZodCodec; + const _Boolean = Classes.Boolean ?? schemas.$ZodBoolean; + const _String = Classes.String ?? schemas.$ZodString; + const stringSchema = new _String({ type: "string", error: params.error }); + const booleanSchema = new _Boolean({ type: "boolean", error: params.error }); + const codec = new _Codec({ + type: "pipe", + in: stringSchema, + out: booleanSchema, + transform: ((input, payload) => { + let data = input; + if (params.case !== "sensitive") + data = data.toLowerCase(); + if (truthySet.has(data)) { + return true; + } + else if (falsySet.has(data)) { + return false; + } + else { + payload.issues.push({ + code: "invalid_value", + expected: "stringbool", + values: [...truthySet, ...falsySet], + input: payload.value, + inst: codec, + continue: false, + }); + return {}; + } + }), + reverseTransform: ((input, _payload) => { + if (input === true) { + return truthyArray[0] || "true"; + } + else { + return falsyArray[0] || "false"; + } + }), + error: params.error, + }); + codec._zod.bag.truthy = truthyArray; + codec._zod.bag.falsy = falsyArray; + codec._zod.bag.case = params.case ?? "insensitive"; + return codec; +} +// @__NO_SIDE_EFFECTS__ +function _stringFormat(Class, format, fnOrRegex, _params = {}) { + const params = util.normalizeParams(_params); + const def = { + check: "string_format", + type: "string", + format, + fn: typeof fnOrRegex === "function" ? fnOrRegex : (val) => fnOrRegex.test(val), + ...params, + }; + if (fnOrRegex instanceof RegExp) { + def.pattern = fnOrRegex; + } + const inst = new Class(def); + return inst; +} + + + +function assignProps(target, ...sources) { + for (const source of sources) { + for (const key of Reflect.ownKeys(source)) { + if (Object.prototype.propertyIsEnumerable.call(source, key)) { + assignProp(target, key, source[key]); + } + } + } + return target; +} +// function initializeContext(inputs: JSONSchemaGeneratorParams): ToJSONSchemaContext { +// return { +// processor: inputs.processor, +// metadataRegistry: inputs.metadata ?? globalRegistry, +// target: inputs.target ?? "draft-2020-12", +// unrepresentable: inputs.unrepresentable ?? "throw", +// }; +// } +function initializeContext(params) { + // Normalize target: convert old non-hyphenated versions to hyphenated versions + let target = params?.target ?? "draft-2020-12"; + if (target === "draft-4") + target = "draft-04"; + if (target === "draft-7") + target = "draft-07"; + return { + processors: params.processors ?? {}, + metadataRegistry: params?.metadata ?? globalRegistry, + target, + unrepresentable: params?.unrepresentable ?? "throw", + override: params?.override ?? (() => { }), + io: params?.io ?? "output", + counter: 0, + seen: new Map(), + sharedDefsExtractedFor: undefined, + sharedEmitDoneFor: undefined, + cycles: params?.cycles ?? "ref", + reused: params?.reused ?? "inline", + intersections: [], + deferred: [], + external: params?.external ?? undefined, + }; +} +/** + * Applies the `unrepresentable` setting at a site that has no JSON Schema equivalent. Throws + * `message` unless the setting (or the handler's return value) says otherwise. Returns `true` if a + * custom JSON Schema was written into `json`, in which case the caller must not write its own. + */ +function handleUnrepresentable(schema, ctx, json, params, message) { + const result = typeof ctx.unrepresentable === "function" + ? ctx.unrepresentable({ zodSchema: schema, path: params.path, message }) + : ctx.unrepresentable; + if (result === "any") + return false; + if (result === undefined || result === "throw") + throw new Error(message); + Object.assign(json, result); + return true; +} +function to_json_schema_process(schema, ctx, _params = { path: [], schemaPath: [] }) { + var _a; + const def = schema._zod.def; + // check for schema in seens + const seen = ctx.seen.get(schema); + if (seen) { + seen.count++; + // check if cycle + const isCycle = _params.schemaPath.includes(schema); + if (isCycle) { + seen.cycle = _params.path; + } + return seen.schema; + } + // initialize + const result = { schema: {}, count: 1, cycle: undefined, path: _params.path }; + ctx.seen.set(schema, result); + ctx.sharedDefsExtractedFor = undefined; + ctx.sharedEmitDoneFor = undefined; + // custom method overrides default behavior + const overrideSchema = schema._zod.toJSONSchema?.(); + if (overrideSchema) { + result.schema = overrideSchema; + } + else { + const params = { + ..._params, + schemaPath: [..._params.schemaPath, schema], + path: _params.path, + }; + if (schema._zod.processJSONSchema) { + schema._zod.processJSONSchema(ctx, result.schema, params); + } + else { + const _json = result.schema; + const processor = ctx.processors[def.type]; + if (!processor) { + throw new Error(`[toJSONSchema]: Non-representable type encountered: ${def.type}`); + } + processor(schema, ctx, _json, params); + } + const parent = schema._zod.parent; + if (parent) { + // Also set ref if processor didn't (for inheritance) + if (!result.ref) + result.ref = parent; + to_json_schema_process(parent, ctx, params); + ctx.seen.get(parent).isParent = true; + } + } + // metadata + const meta = ctx.metadataRegistry.get(schema); + if (meta) + assignProps(result.schema, meta); + if (ctx.io === "input" && isTransforming(schema)) { + // examples/defaults only apply to output type of pipe + delete result.schema.examples; + delete result.schema.default; + } + // set prefault as default + if (ctx.io === "input" && "_prefault" in result.schema) + (_a = result.schema).default ?? (_a.default = result.schema._prefault); + delete result.schema._prefault; + // pulling fresh from ctx.seen in case it was overwritten + const _result = ctx.seen.get(schema); + return _result.schema; +} +// Escape a reference token for use in a JSON Pointer fragment (RFC 6901): `~` becomes `~0` and `/` becomes `~1`. The `~` replacement must run first. +function encodeJSONPointerSegment(segment) { + return segment.replace(/~/g, "~0").replace(/\//g, "~1"); +} +function extractDefs(ctx, schema +// params: EmitParams +) { + // iterate over seen map; + const root = ctx.seen.get(schema); + if (!root) + throw new Error("Unprocessed schema. This is a bug in Zod."); + // With `external` set, every registered schema resolves through the external branch of `makeURI`, so the root branch below produces the same ref the external branch would — this pass is identical whichever schema it is called with, and only needs to run once. + if (ctx.external && ctx.sharedDefsExtractedFor === ctx.external) + return; + // Track ids to detect duplicates across different schemas + const idToSchema = new Map(); + for (const entry of ctx.seen.entries()) { + const id = ctx.metadataRegistry.get(entry[0])?.id; + if (id) { + const existing = idToSchema.get(id); + if (existing && existing !== entry[0]) { + throw new Error(`Duplicate schema id "${id}" detected during JSON Schema conversion. Two different schemas cannot share the same id when converted together.`); + } + idToSchema.set(id, entry[0]); + } + } + // returns a ref to the schema defId will be empty if the ref points to an external schema (or #) + const makeURI = (entry) => { + // comparing the seen objects because sometimes multiple schemas map to the same seen object. e.g. lazy + // external is configured + const defsSegment = ctx.target === "draft-2020-12" ? "$defs" : "definitions"; + if (ctx.external) { + const externalId = ctx.external.registry.get(entry[0])?.id; // ?? "__shared";// `__schema${ctx.counter++}`; + // check if schema is in the external registry + const uriGenerator = ctx.external.uri ?? ((id) => id); + if (externalId) { + return { ref: uriGenerator(externalId) }; + } + // otherwise, add to __shared + const id = entry[1].defId ?? entry[1].schema.id ?? `schema${ctx.counter++}`; + entry[1].defId = id; // set defId so it will be reused if needed + return { defId: id, ref: `${uriGenerator("__shared")}#/${defsSegment}/${encodeJSONPointerSegment(id)}` }; + } + const uriPrefix = `#`; + const defUriPrefix = `${uriPrefix}/${defsSegment}/`; + // an id-less root has nowhere to be extracted to, so it stays inline and self-references as `#` + if (entry[1] === root && !entry[1].schema.id) { + return { ref: uriPrefix }; + } + // self-contained schema + const defId = entry[1].schema.id ?? `__schema${ctx.counter++}`; + return { defId, ref: defUriPrefix + encodeJSONPointerSegment(defId) }; + }; + // stored cached version in `def` property remove all properties, set $ref + const extractToDef = (entry) => { + // if the schema is already a reference, do not extract it + if (entry[1].schema.$ref) { + return; + } + const seen = entry[1]; + const { ref, defId } = makeURI(entry); + seen.def = { ...seen.schema }; + // defId won't be set if the schema is a reference to an external schema or if the schema is the root schema + if (defId) + seen.defId = defId; + // wipe away all properties except $ref + const schema = seen.schema; + for (const key in schema) { + delete schema[key]; + } + schema.$ref = ref; + }; + // throw on cycles + // break cycles + if (ctx.cycles === "throw") { + for (const entry of ctx.seen.entries()) { + const seen = entry[1]; + if (seen.cycle) { + throw new Error("Cycle detected: " + + `#/${seen.cycle?.join("/")}/` + + '\n\nSet the `cycles` parameter to `"ref"` to resolve cyclical schemas with defs.'); + } + } + } + // extract schemas into $defs + for (const entry of ctx.seen.entries()) { + const seen = entry[1]; + // convert root schema to # $ref + if (schema === entry[0]) { + extractToDef(entry); // this has special handling for the root schema + continue; + } + // extract schemas that are in the external registry + if (ctx.external) { + const ext = ctx.external.registry.get(entry[0])?.id; + if (schema !== entry[0] && ext) { + extractToDef(entry); + continue; + } + } + // extract schemas with `id` meta + const id = ctx.metadataRegistry.get(entry[0])?.id; + if (id) { + extractToDef(entry); + continue; + } + // break cycles + if (seen.cycle) { + // any + extractToDef(entry); + continue; + } + // extract reused schemas + if (seen.count > 1) { + if (ctx.reused === "ref") { + extractToDef(entry); + // biome-ignore lint: + continue; + } + } + } + if (ctx.external) + ctx.sharedDefsExtractedFor = ctx.external; +} +/** Rewrites `anyOf: [{type: "a"}, {type: "b"}]` to `type: ["a", "b"]`, which every JSON Schema draft treats as equivalent and most consumers render far better for the nullable case. Only branches that are a bare type assertion qualify — anything carrying a constraint, `$ref`, `const` or metadata is left alone. Runs after `flattenRef`, so a branch an override decorated or `$defs` extraction turned into a `$ref` is no longer bare and correctly stays in `anyOf`. `oneOf` is excluded: `integer` and `number` overlap, so "exactly one" and "at least one" are not the same there. OpenAPI 3.0 is excluded: its `type` must be a single string. */ +function compactTypeUnion(schema) { + const options = schema.anyOf; + if (!Array.isArray(options) || options.length === 0 || schema.type !== undefined) + return; + const types = []; + for (const option of options) { + if (!option || typeof option !== "object") + return; + // A branch that is itself a compactible union folds into this one — nested `anyOf` and a flat `type` array say the same thing. Compacting it first also makes the result independent of the order this pass walks the seen map in. + compactTypeUnion(option); + const keys = Object.keys(option); + if (keys.length !== 1 || keys[0] !== "type") + return; + const type = option.type; + for (const member of Array.isArray(type) ? type : [type]) { + if (typeof member !== "string") + return; + if (!types.includes(member)) + types.push(member); + } + } + delete schema.anyOf; + // A `type` array must be non-empty and unique (metaschema); a single member is spelled as a bare string. + schema.type = types.length === 1 ? types[0] : types; +} +/** Keywords `foldIntersection` knows how to combine. Anything else — `$ref`, `patternProperties`, + * an annotation like `description` — makes a member unfoldable, so a constraint this does not + * understand leaves the `allOf` alone instead of being silently dropped or misattributed. */ +const FOLDABLE_KEYS = new Set(["type", "properties", "required", "additionalProperties"]); +const UNION_KEYS = ["oneOf", "anyOf"]; +/** A member's constraint on a key it does not declare itself. A `catchall` states one; `false`, an absent `additionalProperties`, and the empty schema a loose object emits state nothing. */ +function undeclaredConstraint(member) { + const extra = member.additionalProperties; + if (extra === undefined || extra === false || typeof extra !== "object" || extra === null) + return null; + return Object.keys(extra).length ? extra : null; +} +/** Combines object members into the single object they describe together, or returns `null` if any of them carries a keyword outside {@link FOLDABLE_KEYS}. */ +function foldObjects(members) { + const objects = []; + for (const member of members) { + // A boolean subschema is legal JSON Schema and carries no keywords to fold. + if (typeof member !== "object" || member.type !== "object") + return null; + for (const key in member) { + if (!FOLDABLE_KEYS.has(key)) + return null; + } + objects.push(member); + } + const properties = {}; + const required = new Set(); + for (const object of objects) { + for (const key in object.properties) { + // `in` would report a `__proto__` key as already present via the prototype chain and skip it. + if (Object.prototype.hasOwnProperty.call(properties, key)) + continue; + // Every member constrains this key: the ones that declare it say how, and a `catchall` member constrains it too even though it does not name it. The key has to satisfy all of them, which is the same intersection one level down. + const parts = []; + for (const other of objects) { + const part = other.properties?.[key] ?? undeclaredConstraint(other); + if (part === null || part === undefined) + continue; + if (!parts.some((seen) => JSON.stringify(seen) === JSON.stringify(part))) + parts.push(part); + } + const merged = parts.length === 1 + ? parts[0] + : (foldObjects(parts) ?? { allOf: parts }); + assignProp(properties, key, merged); + } + for (const key of object.required ?? []) + required.add(key); + } + const folded = { type: "object", properties }; + if (required.size) + folded.required = [...required]; + // A key no member declares is rejected only when every member rejects it, so the fold is closed only when every member is. Otherwise it carries whatever the `catchall` members demand of such a key. + if (objects.every((object) => object.additionalProperties === false)) { + folded.additionalProperties = false; + } + else { + const constraints = []; + for (const object of objects) { + const constraint = undeclaredConstraint(object); + if (constraint && !constraints.some((seen) => JSON.stringify(seen) === JSON.stringify(constraint))) + constraints.push(constraint); + } + if (constraints.length === 1) + folded.additionalProperties = constraints[0]; + else if (constraints.length > 1) + folded.additionalProperties = { allOf: constraints }; + } + return folded; +} +/** `additionalProperties` in an `allOf` member sees only that member's own `properties`, so two + * closed object members reject each other's keys and the schema validates nothing. Zod's parser + * pools the key sets instead — `handleIntersectionResults` reports a key as unrecognized only when + * *every* side rejects it — so the emitted schema has to pool them too, and folding the members + * into one object is the encoding that says so on every target. + * + * This runs from `finalize`, after `extractDefs`, which is what keeps it clear of the `$ref` + * machinery: a member extracted into `$defs` is already a `$ref` by now and declines to fold, so it + * keeps its reference and its own closedness rather than being inlined as a stale copy. */ +function foldIntersection(json) { + const allOf = json.allOf; + if (!Array.isArray(allOf) || allOf.length < 2) + return; + // An `override` runs before this pass and may have written object keywords onto the intersection itself. Those are deliberate, so decline rather than overwrite them. + for (const key of FOLDABLE_KEYS) + if (key in json) + return; + // An intersection distributes over a union: `A & (X | Y)` is `(A & X) | (A & Y)`. Only the first union is distributed over; a second one stays among the members every branch folds against, where it fails the object check and declines the whole intersection rather than multiplying out. + const unions = allOf.filter((m) => UNION_KEYS.some((k) => Array.isArray(m[k]))); + let folded = null; + if (!unions.length) { + folded = foldObjects(allOf); + } + else { + const union = unions[0]; + const keyword = UNION_KEYS.find((k) => Array.isArray(union[k])); + if (Object.keys(union).length !== 1) + return; + const rest = allOf.filter((m) => m !== union); + const branches = union[keyword].map((branch) => foldObjects([...rest, branch])); + if (branches.some((b) => !b)) + return; + folded = { [keyword]: branches }; + } + if (!folded) + return; + delete json.allOf; + assignProps(json, folded); +} +function finalize(ctx, schema) { + const root = ctx.seen.get(schema); + if (!root) + throw new Error("Unprocessed schema. This is a bug in Zod."); + // flatten refs - inherit properties from parent schemas + const flattenRef = (zodSchema) => { + const seen = ctx.seen.get(zodSchema); + // already processed + if (seen.ref === null) + return; + const schema = seen.def ?? seen.schema; + const _cached = { ...schema }; + const ref = seen.ref; + seen.ref = null; // prevent infinite recursion + if (ref) { + flattenRef(ref); + const refSeen = ctx.seen.get(ref); + const refSchema = refSeen.schema; + // merge referenced schema into current + if (refSchema.$ref && (ctx.target === "draft-07" || ctx.target === "draft-04" || ctx.target === "openapi-3.0")) { + // older drafts can't combine $ref with other properties + schema.allOf = schema.allOf ?? []; + schema.allOf.push(refSchema); + } + else { + assignProps(schema, refSchema); + } + // restore child's own properties (child wins) + assignProps(schema, _cached); + const isParentRef = zodSchema._zod.parent === ref; + // For parent chain, child is a refinement - remove parent-only properties + if (isParentRef) { + for (const key in schema) { + if (key === "$ref" || key === "allOf") + continue; + if (!(key in _cached)) { + delete schema[key]; + } + } + } + // When ref was extracted to $defs, remove properties that match the definition + if (refSchema.$ref && refSeen.def) { + for (const key in schema) { + if (key === "$ref" || key === "allOf") + continue; + if (key in refSeen.def && JSON.stringify(schema[key]) === JSON.stringify(refSeen.def[key])) { + delete schema[key]; + } + } + } + } + // If parent was extracted (has $ref), propagate $ref to this schema. This handles cases like: readonly().meta({id}).describe() where processor sets ref to innerType but parent should be referenced + const parent = zodSchema._zod.parent; + if (parent && parent !== ref) { + // Ensure parent is processed first so its def has inherited properties + flattenRef(parent); + const parentSeen = ctx.seen.get(parent); + if (parentSeen?.schema.$ref) { + schema.$ref = parentSeen.schema.$ref; + // De-duplicate with parent's definition + if (parentSeen.def) { + for (const key in schema) { + if (key === "$ref" || key === "allOf") + continue; + if (key in parentSeen.def && JSON.stringify(schema[key]) === JSON.stringify(parentSeen.def[key])) { + delete schema[key]; + } + } + } + } + } + // execute overrides + ctx.override({ + zodSchema: zodSchema, + jsonSchema: schema, + path: seen.path ?? [], + }); + }; + // Flattening walks the whole map and clears each `ref` as it goes, so a second call over the same map is a no-op scan. Skip it outright once it has run for a registry conversion. + if (!ctx.external || ctx.sharedEmitDoneFor !== ctx.external) { + for (const entry of [...ctx.seen.entries()].reverse()) { + flattenRef(entry[0]); + } + if (ctx.target !== "openapi-3.0") { + for (const entry of ctx.seen.entries()) { + compactTypeUnion(entry[1].def ?? entry[1].schema); + } + } + for (const rewrite of ctx.deferred) + rewrite(); + // After flattening, every member that was extracted is a `$ref`, so the fold sees the final shape. A schema that inherits an intersection — through `z.lazy`, or any `ref` chain — holds the same `allOf` array, so fold by array identity to catch every copy. + if (ctx.intersections.length) { + const carriers = new Map(); + for (const seen of ctx.seen.values()) { + for (const json of [seen.schema, seen.def]) { + const allOf = json?.allOf; + if (!Array.isArray(allOf)) + continue; + const existing = carriers.get(allOf); + if (existing) + existing.push(json); + else + carriers.set(allOf, [json]); + } + } + for (const allOf of ctx.intersections) { + for (const json of carriers.get(allOf) ?? []) + foldIntersection(json); + } + } + } + const result = {}; + if (ctx.target === "draft-2020-12") { + result.$schema = "https://json-schema.org/draft/2020-12/schema"; + } + else if (ctx.target === "draft-07") { + result.$schema = "http://json-schema.org/draft-07/schema#"; + } + else if (ctx.target === "draft-04") { + result.$schema = "http://json-schema.org/draft-04/schema#"; + } + else if (ctx.target === "openapi-3.0") { + // OpenAPI 3.0 schema objects should not include a $schema property + } + else { + // Arbitrary string values are allowed but won't have a $schema property set + } + if (ctx.external?.uri) { + const id = ctx.external.registry.get(schema)?.id; + if (!id) + throw new Error("Schema is missing an `id` property"); + result.$id = ctx.external.uri(id); + } + // when the root was extracted into $defs, `root.schema` is the `$ref` wrapper and `root.def` is the body that now lives under $defs + assignProps(result, root.defId ? root.schema : (root.def ?? root.schema)); + // The `id` in `.meta()` is a Zod-specific registration tag used to extract schemas into $defs — it is not user-facing JSON Schema metadata. Strip it from the output body where it would otherwise leak. The id is preserved implicitly via the $defs key (and via $ref paths). + const rootMetaId = ctx.metadataRegistry.get(schema)?.id; + if (rootMetaId !== undefined && result.id === rootMetaId) + delete result.id; + // build defs object. With `external`, `defs` is the shared object every schema writes into, so the same entries are reassigned on every call. Without it, `defs` is fresh per call and must be rebuilt. + const defs = ctx.external?.defs ?? {}; + if (!ctx.external || ctx.sharedEmitDoneFor !== ctx.external) { + for (const entry of ctx.seen.entries()) { + const seen = entry[1]; + if (seen.def && seen.defId) { + if (seen.def.id === seen.defId) + delete seen.def.id; + assignProp(defs, seen.defId, seen.def); + } + } + } + if (ctx.external) + ctx.sharedEmitDoneFor = ctx.external; + // set definitions in result + if (ctx.external) { + } + else { + if (Object.keys(defs).length > 0) { + if (ctx.target === "draft-2020-12") { + result.$defs = defs; + } + else { + result.definitions = defs; + } + } + } + try { + // this "finalizes" this schema and ensures all cycles are removed each call to finalize() is functionally independent though the seen map is shared + const finalized = JSON.parse(JSON.stringify(result)); + Object.defineProperty(finalized, "~standard", { + value: { + ...schema["~standard"], + jsonSchema: { + input: createStandardJSONSchemaMethod(schema, "input", ctx.processors), + output: createStandardJSONSchemaMethod(schema, "output", ctx.processors), + }, + }, + enumerable: false, + writable: false, + }); + return finalized; + } + catch (_err) { + throw new Error("Error converting schema to JSON."); + } +} +function isTransforming(_schema, _ctx) { + const ctx = _ctx ?? { seen: new Set() }; + if (ctx.seen.has(_schema)) + return false; + ctx.seen.add(_schema); + const def = _schema._zod.def; + if (def.type === "transform") + return true; + if (def.type === "array") + return isTransforming(def.element, ctx); + if (def.type === "set") + return isTransforming(def.valueType, ctx); + if (def.type === "lazy") + return isTransforming(def.getter(), ctx); + if (def.type === "promise" || + def.type === "optional" || + def.type === "nonoptional" || + def.type === "nullable" || + def.type === "readonly" || + def.type === "default" || + def.type === "prefault" || + def.type === "catch") { + return isTransforming(def.innerType, ctx); + } + if (def.type === "intersection") { + return isTransforming(def.left, ctx) || isTransforming(def.right, ctx); + } + if (def.type === "record" || def.type === "map") { + return isTransforming(def.keyType, ctx) || isTransforming(def.valueType, ctx); + } + if (def.type === "pipe") { + if (_schema._zod.traits.has("$ZodCodec")) + return true; + return isTransforming(def.in, ctx) || isTransforming(def.out, ctx); + } + if (def.type === "object") { + for (const key in def.shape) { + if (isTransforming(def.shape[key], ctx)) + return true; + } + return false; + } + if (def.type === "union") { + for (const option of def.options) { + if (isTransforming(option, ctx)) + return true; + } + return false; + } + if (def.type === "tuple") { + for (const item of def.items) { + if (isTransforming(item, ctx)) + return true; + } + if (def.rest && isTransforming(def.rest, ctx)) + return true; + return false; + } + return false; +} +/** + * Creates a toJSONSchema method for a schema instance. + * This encapsulates the logic of initializing context, processing, extracting defs, and finalizing. + */ +const createToJSONSchemaMethod = (schema, processors = {}) => (params) => { + const ctx = initializeContext({ ...params, processors }); + to_json_schema_process(schema, ctx); + extractDefs(ctx, schema); + return finalize(ctx, schema); +}; +const createStandardJSONSchemaMethod = (schema, io, processors = {}) => (params) => { + const { libraryOptions, target } = params ?? {}; + const ctx = initializeContext({ ...(libraryOptions ?? {}), target, io, processors }); + to_json_schema_process(schema, ctx); + extractDefs(ctx, schema); + return finalize(ctx, schema); +}; + + + + +const formatMap = { + guid: "uuid", + url: "uri", + datetime: "date-time", + json_string: "json-string", + regex: "", // do not set +}; +// ==================== SIMPLE TYPE PROCESSORS ==================== +const stringProcessor = (schema, ctx, _json, _params) => { + const json = _json; + json.type = "string"; + const { minimum, maximum, format, patterns, contentEncoding, laxFormat } = schema._zod + .bag; + if (typeof minimum === "number") + json.minLength = minimum; + if (typeof maximum === "number") + json.maxLength = maximum; + // custom pattern overrides format + if (format) { + json.format = formatMap[format] ?? format; + if (json.format === "") + delete json.format; // empty format is not valid + // `z.iso.time()` is never full-time, and `laxFormat` carries the datetime shapes that also accept what their keyword forbids + if (format === "time" || laxFormat) { + delete json.format; + } + } + if (contentEncoding) + json.contentEncoding = contentEncoding; + if (patterns && patterns.size > 0) { + const patternList = [...patterns]; + if (patternList.length === 1) + json.pattern = patternList[0].source; + else if (patternList.length > 1) { + json.allOf = [ + ...patternList.map((regex) => ({ + ...(ctx.target === "draft-07" || ctx.target === "draft-04" || ctx.target === "openapi-3.0" + ? { type: "string" } + : {}), + pattern: regex.source, + })), + ]; + } + } +}; +const numberProcessor = (schema, ctx, _json, params) => { + const json = _json; + const { minimum, maximum, format, multipleOf, exclusiveMaximum, exclusiveMinimum } = schema._zod.bag; + if (typeof format === "string" && format.includes("int")) + json.type = "integer"; + else + json.type = "number"; + // when both minimum and exclusiveMinimum exist, pick the more restrictive one + const exMin = typeof exclusiveMinimum === "number" && exclusiveMinimum >= (minimum ?? Number.NEGATIVE_INFINITY); + const exMax = typeof exclusiveMaximum === "number" && exclusiveMaximum <= (maximum ?? Number.POSITIVE_INFINITY); + const legacy = ctx.target === "draft-04" || ctx.target === "openapi-3.0"; + if (exMin) { + if (legacy) { + json.minimum = exclusiveMinimum; + json.exclusiveMinimum = true; + } + else { + json.exclusiveMinimum = exclusiveMinimum; + } + } + else if (typeof minimum === "number") { + json.minimum = minimum; + } + if (exMax) { + if (legacy) { + json.maximum = exclusiveMaximum; + json.exclusiveMaximum = true; + } + else { + json.exclusiveMaximum = exclusiveMaximum; + } + } + else if (typeof maximum === "number") { + json.maximum = maximum; + } + if (typeof multipleOf === "number") { + // JSON Schema requires a divisor strictly greater than zero, and a non-finite one does not survive JSON at all. A negative divisor accepts exactly what its absolute value accepts, so it still maps; zero, NaN and Infinity have no keyword form. + if (Number.isFinite(multipleOf) && multipleOf !== 0) + json.multipleOf = Math.abs(multipleOf); + else + handleUnrepresentable(schema, ctx, json, params, `A multipleOf divisor of ${multipleOf} cannot be represented in JSON Schema`); + } +}; +const booleanProcessor = (_schema, _ctx, json, _params) => { + json.type = "boolean"; +}; +const bigintProcessor = (schema, ctx, json, params) => { + handleUnrepresentable(schema, ctx, json, params, "BigInt cannot be represented in JSON Schema"); +}; +const symbolProcessor = (schema, ctx, json, params) => { + handleUnrepresentable(schema, ctx, json, params, "Symbols cannot be represented in JSON Schema"); +}; +const nullProcessor = (_schema, ctx, json, _params) => { + if (ctx.target === "openapi-3.0") { + json.type = "string"; + json.nullable = true; + json.enum = [null]; + } + else { + json.type = "null"; + } +}; +const undefinedProcessor = (schema, ctx, json, params) => { + handleUnrepresentable(schema, ctx, json, params, "Undefined cannot be represented in JSON Schema"); +}; +const voidProcessor = (schema, ctx, json, params) => { + handleUnrepresentable(schema, ctx, json, params, "Void cannot be represented in JSON Schema"); +}; +const neverProcessor = (_schema, _ctx, json, _params) => { + json.not = {}; +}; +const anyProcessor = (_schema, _ctx, _json, _params) => { + // empty schema accepts anything +}; +const unknownProcessor = (_schema, _ctx, _json, _params) => { + // empty schema accepts anything +}; +const dateProcessor = (schema, ctx, json, params) => { + handleUnrepresentable(schema, ctx, json, params, "Date cannot be represented in JSON Schema"); +}; +const enumProcessor = (schema, _ctx, json, _params) => { + const def = schema._zod.def; + const values = getEnumValues(def.entries); + // an empty enum accepts nothing, same as z.never() + if (values.length === 0) { + json.not = {}; + return; + } + // Number enums can have both string and number values + if (values.every((v) => typeof v === "number")) + json.type = "number"; + if (values.every((v) => typeof v === "string")) + json.type = "string"; + json.enum = values; +}; +const literalProcessor = (schema, ctx, json, params) => { + const def = schema._zod.def; + // a literal with no values accepts nothing, same as z.never() + if (def.values.length === 0) { + json.not = {}; + return; + } + const vals = []; + for (const val of def.values) { + if (val === undefined) { + // a custom schema replaces the whole literal, so there is nothing left to accumulate + if (handleUnrepresentable(schema, ctx, json, params, "Literal `undefined` cannot be represented in JSON Schema")) + return; + // otherwise do not add to vals + } + else if (typeof val === "bigint") { + if (handleUnrepresentable(schema, ctx, json, params, "BigInt literals cannot be represented in JSON Schema")) + return; + vals.push(Number(val)); + } + else { + vals.push(val); + } + } + if (vals.length === 0) { + // do nothing (an undefined literal was stripped) + } + else if (vals.length === 1) { + const val = vals[0]; + json.type = val === null ? "null" : typeof val; + if (ctx.target === "draft-04" || ctx.target === "openapi-3.0") { + json.enum = [val]; + } + else { + json.const = val; + } + } + else { + if (vals.every((v) => typeof v === "number")) + json.type = "number"; + if (vals.every((v) => typeof v === "string")) + json.type = "string"; + if (vals.every((v) => typeof v === "boolean")) + json.type = "boolean"; + if (vals.every((v) => v === null)) + json.type = "null"; + json.enum = vals; + } +}; +const nanProcessor = (schema, ctx, json, params) => { + handleUnrepresentable(schema, ctx, json, params, "NaN cannot be represented in JSON Schema"); +}; +const templateLiteralProcessor = (schema, _ctx, json, _params) => { + const _json = json; + const pattern = schema._zod.pattern; + if (!pattern) + throw new Error("Pattern not found in template literal"); + _json.type = "string"; + _json.pattern = pattern.source; +}; +const fileProcessor = (schema, _ctx, json, _params) => { + const _json = json; + const file = { + type: "string", + format: "binary", + contentEncoding: "binary", + }; + const { minimum, maximum, mime } = schema._zod.bag; + if (minimum !== undefined) + file.minLength = minimum; + if (maximum !== undefined) + file.maxLength = maximum; + if (mime) { + if (mime.length === 1) { + file.contentMediaType = mime[0]; + Object.assign(_json, file); + } + else { + Object.assign(_json, file); // shared props at root + _json.anyOf = mime.map((m) => ({ contentMediaType: m })); // only contentMediaType differs + } + } + else { + Object.assign(_json, file); + } +}; +const successProcessor = (_schema, _ctx, json, _params) => { + json.type = "boolean"; +}; +const customProcessor = (schema, ctx, json, params) => { + handleUnrepresentable(schema, ctx, json, params, "Custom types cannot be represented in JSON Schema"); +}; +const functionProcessor = (schema, ctx, json, params) => { + handleUnrepresentable(schema, ctx, json, params, "Function types cannot be represented in JSON Schema"); +}; +const transformProcessor = (schema, ctx, json, params) => { + handleUnrepresentable(schema, ctx, json, params, "Transforms cannot be represented in JSON Schema"); +}; +const mapProcessor = (schema, ctx, json, params) => { + handleUnrepresentable(schema, ctx, json, params, "Map cannot be represented in JSON Schema"); +}; +const setProcessor = (schema, ctx, json, params) => { + handleUnrepresentable(schema, ctx, json, params, "Set cannot be represented in JSON Schema"); +}; +// ==================== COMPOSITE TYPE PROCESSORS ==================== +const arrayProcessor = (schema, ctx, _json, params) => { + const json = _json; + const def = schema._zod.def; + const { minimum, maximum } = schema._zod.bag; + if (typeof minimum === "number") + json.minItems = minimum; + if (typeof maximum === "number") + json.maxItems = maximum; + json.type = "array"; + json.items = to_json_schema_process(def.element, ctx, { + ...params, + path: [...params.path, "items"], + }); +}; +// Transform and catch set `optin = "optional"` at runtime so the parser lets them observe an +// absent key, but their declared input type stays required. An input JSON Schema describes the +// declared type, so resolve past them to the schema that actually carries the optionality. +// Used by both `objectProcessor` (for `required`) and `tupleProcessor` (for `minItems`); see +// wiki/optionality.md, "The JSON Schema emitter reads the *static* value". +function inputOptin(schema) { + const def = schema._zod.def; + if (def.type === "pipe" && def.in._zod.traits.has("$ZodTransform")) { + return inputOptin(def.out); + } + if (def.type === "catch") { + return inputOptin(def.innerType); + } + return schema._zod.optin; +} +const objectProcessor = (schema, ctx, _json, params) => { + const json = _json; + const def = schema._zod.def; + const shape = def.shape; + // dropping it while still emitting `additionalProperties: false` would emit a schema that rejects data this one requires + const symbolKeys = Object.getOwnPropertySymbols(shape); + if (symbolKeys.length && + handleUnrepresentable(schema, ctx, json, params, "Symbol keys cannot be represented in JSON Schema")) { + return; + } + json.type = "object"; + json.properties = {}; + for (const key in shape) { + // assignProp so a __proto__ key becomes an own property instead of hitting the inherited setter on the plain {} we build into + assignProp(json.properties, key, to_json_schema_process(shape[key], ctx, { + ...params, + path: [...params.path, "properties", key], + })); + } + // required keys + const allKeys = new Set(Object.keys(shape)); + const requiredKeys = new Set([...allKeys].filter((key) => { + const field = def.shape[key]; + if (ctx.io === "input") { + return inputOptin(field) === undefined; + } + else { + return field._zod.optout === undefined; + } + })); + if (requiredKeys.size > 0) { + json.required = Array.from(requiredKeys); + } + // catchall + if (def.catchall?._zod.def.type === "never") { + // strict + json.additionalProperties = false; + } + else if (!def.catchall) { + // regular + if (ctx.io === "output") + json.additionalProperties = false; + } + else if (def.catchall) { + json.additionalProperties = to_json_schema_process(def.catchall, ctx, { + ...params, + path: [...params.path, "additionalProperties"], + }); + } +}; +const unionProcessor = (schema, ctx, json, params) => { + const def = schema._zod.def; + // Exclusive unions (inclusive === false) use oneOf (exactly one match) instead of anyOf (one or more matches). This includes both z.xor() and discriminated unions + const isExclusive = def.inclusive === false; + const options = def.options.map((x, i) => to_json_schema_process(x, ctx, { + ...params, + path: [...params.path, isExclusive ? "oneOf" : "anyOf", i], + })); + if (isExclusive) { + json.oneOf = options; + } + else { + json.anyOf = options; + } +}; +const intersectionProcessor = (schema, ctx, json, params) => { + const def = schema._zod.def; + const a = to_json_schema_process(def.left, ctx, { + ...params, + path: [...params.path, "allOf", 0], + }); + const b = to_json_schema_process(def.right, ctx, { + ...params, + path: [...params.path, "allOf", 1], + }); + const isSimpleIntersection = (val) => "allOf" in val && Object.keys(val).length === 1; + const allOf = [ + ...(isSimpleIntersection(a) ? a.allOf : [a]), + ...(isSimpleIntersection(b) ? b.allOf : [b]), + ]; + json.allOf = allOf; + // Recorded innermost first, so a nested intersection has already folded by the time this one is considered. The array is the handle rather than the schema, because a wrapper that inherits this schema shares the same array; `finalize` folds every object holding it. See `foldIntersection`. + ctx.intersections.push(allOf); +}; +const tupleProcessor = (schema, ctx, _json, params) => { + const json = _json; + const def = schema._zod.def; + json.type = "array"; + const prefixPath = ctx.target === "draft-2020-12" ? "prefixItems" : "items"; + const restPath = ctx.target === "draft-2020-12" ? "items" : ctx.target === "openapi-3.0" ? "items" : "additionalItems"; + const prefixItems = def.items.map((x, i) => to_json_schema_process(x, ctx, { + ...params, + path: [...params.path, prefixPath, i], + })); + const rest = def.rest + ? to_json_schema_process(def.rest, ctx, { + ...params, + path: [...params.path, restPath, ...(ctx.target === "openapi-3.0" ? [def.items.length] : [])], + }) + : null; + let minItems = def.items.length; + while (minItems > 0) { + const item = def.items[minItems - 1]; + const optional = ctx.io === "input" ? inputOptin(item) !== undefined : item._zod.optout === "optional"; + if (!optional) + break; + minItems--; + } + const maxItems = def.items.length; + const isClosed = !def.rest; + if (ctx.target === "draft-2020-12") { + json.prefixItems = prefixItems; + if (isClosed) { + json.items = false; + } + else if (rest) { + json.items = rest; + } + if (minItems > 0) + json.minItems = minItems; + if (isClosed) + json.maxItems = maxItems; + } + else if (ctx.target === "openapi-3.0") { + json.items = { + anyOf: prefixItems, + }; + if (rest) { + json.items.anyOf.push(rest); + } + if (minItems > 0) + json.minItems = minItems; + if (isClosed) + json.maxItems = maxItems; + } + else { + json.items = prefixItems; + if (isClosed) { + json.additionalItems = false; + } + else if (rest) { + json.additionalItems = rest; + } + if (minItems > 0) + json.minItems = minItems; + if (isClosed) + json.maxItems = maxItems; + } + // explicit user-defined length checks take precedence + const { minimum, maximum } = schema._zod.bag; + if (typeof minimum === "number") + json.minItems = minimum; + if (typeof maximum === "number") + json.maxItems = maximum; +}; +/** JSON object keys are always strings, so a numeric record key schema is re-expressed over the + * numeric-string form the record parser matches. Deferred to `finalize`, after the flatten: a key + * behind a wrapper only carries its own `type` before then, and a union key only has its branches. + * + * A numeric bound cannot apply to a property name, so `minimum` and its siblings are dropped rather + * than carried over: keeping them beside `type: "string"` reproduces the match-nothing schema this + * exists to fix. A key that carries one therefore emits wider than the record parses — `z.record(z.number().min(5), V)` + * accepts `"3"` — which is the deliberate trade, since throwing on it would reject an ordinary schema + * outright. */ +function stringifyKeyNames(bySchema, json, visited) { + // an extracted key that rewrites cannot go on sharing its definition — the string form a key position needs is not the number form every other reference wants — so it inlines. One that does not rewrite keeps the `$ref`. + if (json.$ref) { + // a recursive key holds its own reference inside its definition, so a node already on the path is left alone rather than resolved again + if (visited.has(json)) + return json; + visited.add(json); + const def = bySchema.get(json)?.def; + if (!def) + return json; + const inlined = stringifyKeyNames(bySchema, def, visited); + return inlined === def ? json : inlined; + } + for (const keyword of ["anyOf", "oneOf"]) { + const branches = json[keyword]; + if (!Array.isArray(branches)) + continue; + const mapped = branches.map((branch) => stringifyKeyNames(bySchema, branch, visited)); + // rebuilding regardless would detach a key that had nothing to re-express, dropping its `$ref` and leaking the internal `id` + if (mapped.some((branch, i) => branch !== branches[i])) + json = { ...json, [keyword]: mapped }; + } + // a member that already admits a string leaves the key unconstrained, so the node's own type re-expresses only when every member is numeric + const types = Array.isArray(json.type) ? json.type : [json.type]; + const numericType = !types.includes("string") && types.some((t) => t === "number" || t === "integer"); + // a heterogeneous key carries no type at all, so its numeric members are caught here instead + const values = json.enum ?? (json.const !== undefined ? [json.const] : undefined); + if (!numericType && !values?.some((v) => typeof v === "number")) + return json; + const { minimum, maximum, exclusiveMinimum, exclusiveMaximum, multipleOf, format, id, ...rest } = json; + if (rest.enum) + rest.enum = rest.enum.map((v) => (typeof v === "number" ? String(v) : v)); + else if (typeof rest.const === "number") + rest.const = String(rest.const); + // a heterogeneous key keeps its absent type: the stringified members already say what a key may be + if (!numericType) + return rest; + rest.type = "string"; + if (!values) + rest.pattern = (types.includes("number") ? number : integer).source; + return rest; +} +/** Every record of one conversion, so the carriers are found in a single pass rather than once per record. */ +const pendingRecords = new WeakMap(); +function rewriteKeyNames(ctx) { + // an extracted key is resolved by the object `extractToDef` left in its place, so the map is built once rather than searched per reference. `_zod.toJSONSchema` can hand the same object to two schemas, so the first entry carrying a body wins, as a search would have found it. + const bySchema = new Map(); + for (const entry of ctx.seen.values()) { + if (entry.def && !bySchema.has(entry.schema)) + bySchema.set(entry.schema, entry); + } + const rewrites = new Map(); + for (const record of pendingRecords.get(ctx) ?? []) { + const seen = ctx.seen.get(record); + const names = (seen?.def ?? seen?.schema)?.propertyNames; + if (!names || names === true || rewrites.has(names)) + continue; + const rewritten = stringifyKeyNames(bySchema, names, new Set()); + if (rewritten !== names) + rewrites.set(names, rewritten); + } + if (!rewrites.size) + return; + // the flatten has already copied each record's own properties onto every wrapper by reference, and an extracted body is another such copy, so every carrier holding a rewritten key is updated together + for (const entry of ctx.seen.values()) { + for (const carrier of [entry.schema, entry.def]) { + const rewritten = carrier && rewrites.get(carrier.propertyNames); + if (rewritten) + carrier.propertyNames = rewritten; + } + } +} +const recordProcessor = (schema, ctx, _json, params) => { + const json = _json; + const def = schema._zod.def; + json.type = "object"; + // For looseRecord with regex patterns, use patternProperties. This correctly represents "only validate keys matching the pattern" semantics and composes well with allOf (intersections) + const keyType = def.keyType; + const keyBag = keyType._zod.bag; + const patterns = keyBag?.patterns; + if (def.mode === "loose" && patterns && patterns.size > 0) { + // Use patternProperties for looseRecord with regex patterns + const valueSchema = to_json_schema_process(def.valueType, ctx, { + ...params, + path: [...params.path, "patternProperties", "*"], + }); + json.patternProperties = {}; + for (const pattern of patterns) { + assignProp(json.patternProperties, pattern.source, valueSchema); + } + } + else { + // Default behavior: use propertyNames + additionalProperties + if (ctx.target === "draft-07" || ctx.target === "draft-2020-12") { + json.propertyNames = to_json_schema_process(def.keyType, ctx, { + ...params, + path: [...params.path, "propertyNames"], + }); + let pending = pendingRecords.get(ctx); + if (!pending) { + pending = []; + pendingRecords.set(ctx, pending); + ctx.deferred.push(() => rewriteKeyNames(ctx)); + } + pending.push(schema); + } + json.additionalProperties = to_json_schema_process(def.valueType, ctx, { + ...params, + path: [...params.path, "additionalProperties"], + }); + } + // Add required for keys with discrete values (enum, literal, etc.) + const keyValues = keyType._zod.values; + // Every key shares one value schema, so an optional-in value makes the whole key set omittable on input. Output keeps them: the exhaustive branch assigns every key, even one whose value came back undefined. + const omittableOnInput = ctx.io === "input" && inputOptin(def.valueType) !== undefined; + if (keyValues && !def.partial && !omittableOnInput) { + const validKeyValues = [...keyValues].filter((v) => typeof v === "string" || typeof v === "number"); + if (validKeyValues.length > 0) { + json.required = validKeyValues.map(String); + } + } +}; +const nullableProcessor = (schema, ctx, json, params) => { + const def = schema._zod.def; + const inner = to_json_schema_process(def.innerType, ctx, params); + const seen = ctx.seen.get(schema); + if (ctx.target === "openapi-3.0") { + seen.ref = def.innerType; + json.nullable = true; + } + else { + json.anyOf = [inner, { type: "null" }]; + } +}; +const nonoptionalProcessor = (schema, ctx, _json, params) => { + const def = schema._zod.def; + to_json_schema_process(def.innerType, ctx, params); + const seen = ctx.seen.get(schema); + seen.ref = def.innerType; +}; +/** Round-trips a default value through JSON so the emitted schema is guaranteed to be valid JSON. + * A BigInt has no reliable encoding, so it goes through `unrepresentable` like any other + * unrepresentable value. Returns a sentinel when the caller must not write a default of its own. */ +const UNREPRESENTABLE_DEFAULT = Symbol(); +function serializeDefaultValue(value, schema, ctx, json, params) { + let unrepresentable = false; + const serialized = JSON.stringify(value, (_, val) => { + if (typeof val !== "bigint") + return val; + unrepresentable = true; + return null; + }); + if (!unrepresentable) + return JSON.parse(serialized); + handleUnrepresentable(schema, ctx, json, params, "BigInt defaults cannot be represented in JSON Schema"); + return UNREPRESENTABLE_DEFAULT; +} +const defaultProcessor = (schema, ctx, json, params) => { + const def = schema._zod.def; + to_json_schema_process(def.innerType, ctx, params); + const seen = ctx.seen.get(schema); + seen.ref = def.innerType; + const value = serializeDefaultValue(def.defaultValue, schema, ctx, json, params); + if (value !== UNREPRESENTABLE_DEFAULT) + json.default = value; +}; +const prefaultProcessor = (schema, ctx, json, params) => { + const def = schema._zod.def; + to_json_schema_process(def.innerType, ctx, params); + const seen = ctx.seen.get(schema); + seen.ref = def.innerType; + if (ctx.io !== "input") + return; + const value = serializeDefaultValue(def.defaultValue, schema, ctx, json, params); + if (value !== UNREPRESENTABLE_DEFAULT) + json._prefault = value; +}; +const catchProcessor = (schema, ctx, json, params) => { + const def = schema._zod.def; + to_json_schema_process(def.innerType, ctx, params); + const seen = ctx.seen.get(schema); + seen.ref = def.innerType; + let catchValue; + try { + catchValue = def.catchValue(undefined); + } + catch { + handleUnrepresentable(schema, ctx, json, params, "Dynamic catch values are not supported in JSON Schema"); + return; + } + json.default = catchValue; +}; +const pipeProcessor = (schema, ctx, _json, params) => { + const def = schema._zod.def; + const inIsTransform = def.in._zod.traits.has("$ZodTransform"); + const innerType = ctx.io === "input" ? (inIsTransform ? def.out : def.in) : def.out; + to_json_schema_process(innerType, ctx, params); + const seen = ctx.seen.get(schema); + seen.ref = innerType; +}; +const readonlyProcessor = (schema, ctx, json, params) => { + const def = schema._zod.def; + to_json_schema_process(def.innerType, ctx, params); + const seen = ctx.seen.get(schema); + seen.ref = def.innerType; + json.readOnly = true; +}; +const promiseProcessor = (schema, ctx, _json, params) => { + const def = schema._zod.def; + to_json_schema_process(def.innerType, ctx, params); + const seen = ctx.seen.get(schema); + seen.ref = def.innerType; +}; +const optionalProcessor = (schema, ctx, _json, params) => { + const def = schema._zod.def; + to_json_schema_process(def.innerType, ctx, params); + const seen = ctx.seen.get(schema); + seen.ref = def.innerType; +}; +const lazyProcessor = (schema, ctx, _json, params) => { + const innerType = schema._zod.innerType; + to_json_schema_process(innerType, ctx, params); + const seen = ctx.seen.get(schema); + seen.ref = innerType; +}; +// ==================== ALL PROCESSORS ==================== +const allProcessors = { + string: stringProcessor, + number: numberProcessor, + boolean: booleanProcessor, + bigint: bigintProcessor, + symbol: symbolProcessor, + null: nullProcessor, + undefined: undefinedProcessor, + void: voidProcessor, + never: neverProcessor, + any: anyProcessor, + unknown: unknownProcessor, + date: dateProcessor, + enum: enumProcessor, + literal: literalProcessor, + nan: nanProcessor, + template_literal: templateLiteralProcessor, + file: fileProcessor, + success: successProcessor, + custom: customProcessor, + function: functionProcessor, + transform: transformProcessor, + map: mapProcessor, + set: setProcessor, + array: arrayProcessor, + object: objectProcessor, + union: unionProcessor, + intersection: intersectionProcessor, + tuple: tupleProcessor, + record: recordProcessor, + nullable: nullableProcessor, + nonoptional: nonoptionalProcessor, + default: defaultProcessor, + prefault: prefaultProcessor, + catch: catchProcessor, + pipe: pipeProcessor, + readonly: readonlyProcessor, + promise: promiseProcessor, + optional: optionalProcessor, + lazy: lazyProcessor, +}; +function toJSONSchema(input, params) { + if ("_idmap" in input) { + // Registry case + const registry = input; + const ctx = initializeContext({ ...params, processors: allProcessors }); + const defs = {}; + // First pass: process all schemas to build the seen map + for (const entry of registry._idmap.entries()) { + const [_, schema] = entry; + to_json_schema_process(schema, ctx); + } + const schemas = {}; + const external = { + registry, + uri: params?.uri, + defs, + }; + // Update the context with external configuration + ctx.external = external; + // Second pass: emit each schema + for (const entry of registry._idmap.entries()) { + const [key, schema] = entry; + extractDefs(ctx, schema); + assignProp(schemas, key, finalize(ctx, schema)); + } + if (Object.keys(defs).length > 0) { + const defsSegment = ctx.target === "draft-2020-12" ? "$defs" : "definitions"; + schemas.__shared = { + [defsSegment]: defs, + }; + } + return { schemas }; + } + // Single schema case + const ctx = initializeContext({ ...params, processors: allProcessors }); + to_json_schema_process(input, ctx); + extractDefs(ctx, input); + return finalize(ctx, input); +} + + +const en_error = () => { + const Sizable = { + string: { unit: "characters", verb: "to have" }, + file: { unit: "bytes", verb: "to have" }, + array: { unit: "items", verb: "to have" }, + set: { unit: "items", verb: "to have" }, + map: { unit: "entries", verb: "to have" }, + }; + function getSizing(origin) { + return Sizable[origin] ?? null; + } + const FormatDictionary = { + 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", + credit_card: "credit card number", + jwt: "JWT", + template_literal: "input", + }; + // type names: missing keys = do not translate (use raw value via ?? fallback) + const TypeDictionary = { + // Compatibility: "nan" -> "NaN" for display + nan: "NaN", + // All other type names omitted - they fall back to raw values via ?? operator + }; + function getTypeName(type, input) { + if (type === "number" && typeof input === "number" && !Number.isFinite(input)) { + return String(input); + } + return TypeDictionary[type] ?? type; + } + return (issue) => { + switch (issue.code) { + case "invalid_type": { + const expected = getTypeName(issue.expected); + const receivedType = parsedType(issue.input); + const received = getTypeName(receivedType, issue.input); + return `Invalid input: expected ${expected}, received ${received}`; + } + case "invalid_value": + if (issue.values.length === 1) + return `Invalid input: expected ${stringifyPrimitive(issue.values[0])}`; + return `Invalid option: expected one of ${joinValues(issue.values, "|")}`; + case "too_big": { + const adj = issue.exact ? "exactly " : issue.inclusive ? "<=" : "<"; + const sizing = getSizing(issue.origin); + if (sizing) + return `Too big: expected ${issue.origin ?? "value"} to have ${adj}${issue.maximum.toString()} ${sizing.unit ?? "elements"}`; + return `Too big: expected ${issue.origin ?? "value"} to be ${adj}${issue.maximum.toString()}`; + } + case "too_small": { + const adj = issue.exact ? "exactly " : issue.inclusive ? ">=" : ">"; + const sizing = getSizing(issue.origin); + if (sizing) { + return `Too small: expected ${issue.origin} to have ${adj}${issue.minimum.toString()} ${sizing.unit}`; + } + return `Too small: expected ${issue.origin} to be ${adj}${issue.minimum.toString()}`; + } + case "invalid_format": { + const _issue = issue; + if (_issue.format === "starts_with") { + return `Invalid string: must start with "${_issue.prefix}"`; + } + if (_issue.format === "ends_with") + return `Invalid string: must end with "${_issue.suffix}"`; + if (_issue.format === "includes") + return `Invalid string: must include "${_issue.includes}"`; + if (_issue.format === "regex") + return `Invalid string: must match pattern ${_issue.pattern}`; + return `Invalid ${FormatDictionary[_issue.format] ?? issue.format}`; + } + case "not_multiple_of": + return `Invalid number: must be a multiple of ${issue.divisor}`; + case "unrecognized_keys": + return `Unrecognized key${issue.keys.length > 1 ? "s" : ""}: ${joinValues(issue.keys, ", ")}`; + case "invalid_key": + return `Invalid key in ${issue.origin}`; + case "invalid_union": + if (issue.options && Array.isArray(issue.options) && issue.options.length > 0) { + const opts = issue.options.map((o) => `'${o}'`).join(" | "); + return `Invalid discriminator value. Expected ${opts}`; + } + if (issue.inclusive === false) { + return "Invalid input: more than one option matched"; + } + return "Invalid input"; + case "invalid_element": + return `Invalid value in ${issue.origin}`; + default: + return `Invalid input`; + } + }; +}; +/* export default */ function en() { + return { + localeError: en_error(), + }; +} + + + + +/* Prototypes that already carry the lazy helper methods. Seeded with the + * intrinsics so that `init` on a foreign object — it accepts any object — + * can never install an accessor onto a prototype we do not own. */ +const _installedErrorProtos = /* @__PURE__ */ new WeakSet([Object.prototype, Error.prototype]); +/* Helper methods live as non-enumerable lazy getters on the shared + * prototype instead of own properties on every instance. On first + * access the getter allocates the per-instance closure and caches it + * as a non-enumerable own property, so detached usage still works and + * the allocation only happens for methods actually touched. */ +function _lazyMethod(proto, key, make) { + Object.defineProperty(proto, key, { + configurable: true, + enumerable: false, + get() { + const value = make(this); + Object.defineProperty(this, key, { value, configurable: true, writable: true }); + return value; + }, + set(value) { + Object.defineProperty(this, key, { value, configurable: true, writable: true }); + }, + }); +} +const classic_errors_initializer = (inst, issues) => { + $ZodError.init(inst, issues); + inst.name = "ZodError"; + const proto = Object.getPrototypeOf(inst); + if (_installedErrorProtos.has(proto)) + return; + _installedErrorProtos.add(proto); + _lazyMethod(proto, "format", (self) => (mapper) => formatError(self, mapper)); + _lazyMethod(proto, "flatten", (self) => (mapper) => flattenError(self, mapper)); + _lazyMethod(proto, "addIssue", (self) => (issue) => { + self.issues.push(issue); + self.message = JSON.stringify(self.issues, jsonStringifyReplacer, 2); + }); + _lazyMethod(proto, "addIssues", (self) => (issues) => { + self.issues.push(...issues); + self.message = JSON.stringify(self.issues, jsonStringifyReplacer, 2); + }); + Object.defineProperty(proto, "isEmpty", { + configurable: true, + enumerable: false, + get() { + return this.issues.length === 0; + }, + }); +}; +const ZodError = /*@__PURE__*/ (/* unused pure expression or super */ null && (core.$constructor("ZodError", classic_errors_initializer))); +const ZodRealError = /*@__PURE__*/ $constructor("ZodError", classic_errors_initializer, undefined, { + Parent: Error, +}); +// /** @deprecated Use `z.core.$ZodErrorMapCtx` instead. */ +// export type ErrorMapCtx = core.$ZodErrorMapCtx; + + + +const classic_parse_parse = /* @__PURE__ */ parse_parse(ZodRealError); +const classic_parse_parseAsync = /* @__PURE__ */ parse_parseAsync(ZodRealError); +const parse_safeParse = /* @__PURE__ */ _safeParse(ZodRealError); +const parse_safeParseAsync = /* @__PURE__ */ _safeParseAsync(ZodRealError); + +// Codec functions +const classic_parse_encode = /* @__PURE__ */ parse_encode(ZodRealError); +const classic_parse_decode = /* @__PURE__ */ parse_decode(ZodRealError); +const classic_parse_encodeAsync = /* @__PURE__ */ parse_encodeAsync(ZodRealError); +const classic_parse_decodeAsync = /* @__PURE__ */ parse_decodeAsync(ZodRealError); +const parse_safeEncode = /* @__PURE__ */ _safeEncode(ZodRealError); +const parse_safeDecode = /* @__PURE__ */ _safeDecode(ZodRealError); +const parse_safeEncodeAsync = /* @__PURE__ */ _safeEncodeAsync(ZodRealError); +const parse_safeDecodeAsync = /* @__PURE__ */ _safeDecodeAsync(ZodRealError); + + + + + + + + +// Register English as the default locale on first ZodType construction. Hooked into the `ZodType` `$constructor` (rather than a top-level `config(en())` in `external.ts`) so bundlers honoring `sideEffects: false` can't tree-shake it out — see #5953, #5725. An explicit `z.config(z.locales.xx())` call wins regardless of order, since this only sets the default when none is present. +function _ensureDefaultLocale() { + if (!globalConfig.localeError) + core_config(en()); +} +// the default memoizer is read by the core container init, which runs before `ZodType.init`, so each container calls this first +function _ensureDefaultMemoizer() { + if (!globalConfig.memoizer) + core_config({ memoizer: memoizer() }); +} +const ZodType = /*@__PURE__*/ $constructor("ZodType", (inst, def) => { + _ensureDefaultLocale(); + $ZodType.init(inst, def); + inst.def = def; + inst.type = def.type; + return inst; +}, { + check(...chks) { + const def = this.def; + return this.clone(mergeDefs(def, { + checks: [ + ...(def.checks ?? []), + ...chks.map((ch) => typeof ch === "function" ? { _zod: { check: ch, def: { check: "custom" }, onattach: [] } } : ch), + ], + }), { parent: true }); + }, + with(...chks) { + return this.check(...chks); + }, + clone(def, params) { + return clone(this, def, params); + }, + brand() { + return this; + }, + register(reg, meta) { + reg.add(this, meta); + return this; + }, + refine(check, params) { + return this.check(refine(check, params)); + }, + superRefine(refinement, params) { + return this.check(superRefine(refinement, params)); + }, + overwrite(fn) { + return this.check(_overwrite(fn)); + }, + optional() { + return schemas_optional(this); + }, + exactOptional() { + return exactOptional(this); + }, + nullable() { + return nullable(this); + }, + nullish() { + return schemas_optional(nullable(this)); + }, + nonoptional(params) { + return nonoptional(this, params); + }, + array() { + return schemas_array(this); + }, + or(arg) { + return schemas_union([this, arg]); + }, + and(arg) { + return intersection(this, arg); + }, + transform(tx) { + return pipe(this, transform(tx)); + }, + default(d) { + return schemas_default(this, d); + }, + prefault(d) { + return prefault(this, d); + }, + catch(params) { + return schemas_catch(this, params); + }, + pipe(target) { + return pipe(this, target); + }, + readonly() { + return readonly(this); + }, + describe(description) { + const cl = this.clone(); + globalRegistry.add(cl, { description }); + return cl; + }, + meta(...args) { + // overloaded: meta() returns the registered metadata, meta(data) returns a clone with `data` registered. The mapped type picks up the second overload, so we accept variadic any-args and return `any` to satisfy both at runtime. + if (args.length === 0) + return globalRegistry.get(this); + const cl = this.clone(); + globalRegistry.add(cl, args[0]); + return cl; + }, + isOptional() { + return this.safeParse(undefined).success; + }, + isNullable() { + return this.safeParse(null).success; + }, + apply(fn, ...args) { + return args.length === 0 ? fn(this) : fn(this, ...args); + }, + // Overrides core's `~standard` to add `jsonSchema`. Must stay a prototype entry: redefining it per instance demotes instances to dictionary mode. + get "~standard"() { + return hide(this, "~standard", { + ...standardProps(this), + jsonSchema: { + input: createStandardJSONSchemaMethod(this, "input"), + output: createStandardJSONSchemaMethod(this, "output"), + }, + }); + }, + set "~standard"(value) { + util_own(this, "~standard", value); + }, + parse: function _parse(data, params) { + return classic_parse_parse(this, data, params, { callee: _parse }); + }, + parseAsync: async function _parseAsync(data, params) { + return await classic_parse_parseAsync(this, data, params, { callee: _parseAsync }); + }, + safeParse(data, params) { + return parse_safeParse(this, data, params); + }, + async safeParseAsync(data, params) { + return parse_safeParseAsync(this, data, params); + }, + // `spa` is an alias: same function object as `safeParseAsync`, as before. + get spa() { + return this?.safeParseAsync; + }, + set spa(value) { + util_own(this, "spa", value); + }, + encode: function _encode(data, params) { + return classic_parse_encode(this, data, params, { callee: _encode }); + }, + decode: function _decode(data, params) { + return classic_parse_decode(this, data, params, { callee: _decode }); + }, + encodeAsync: async function _encodeAsync(data, params) { + return await classic_parse_encodeAsync(this, data, params, { callee: _encodeAsync }); + }, + decodeAsync: async function _decodeAsync(data, params) { + return await classic_parse_decodeAsync(this, data, params, { callee: _decodeAsync }); + }, + safeEncode(data, params) { + return parse_safeEncode(this, data, params); + }, + safeDecode(data, params) { + return parse_safeDecode(this, data, params); + }, + async safeEncodeAsync(data, params) { + return parse_safeEncodeAsync(this, data, params); + }, + async safeDecodeAsync(data, params) { + return parse_safeDecodeAsync(this, data, params); + }, + toJSONSchema(params) { + return createToJSONSchemaMethod(this, {})(params); + }, + // Reads through to the registry on every access, so it must not cache. + get description() { + return globalRegistry.get(this)?.description; + }, + // No setter: `schema._def = x` throws, as it did when `_def` was a non-writable own property. + get _def() { + return this._zod.def; + }, +}); +/** @internal */ +const _ZodString = /*@__PURE__*/ $constructor("_ZodString", (inst, def) => { + $ZodString.init(inst, def); + ZodType.init(inst, def); + inst._zod.processJSONSchema = (ctx, json, params) => stringProcessor(inst, ctx, json, params); + const bag = inst._zod.bag; + inst.format = bag.format ?? null; + inst.minLength = bag.minimum ?? null; + inst.maxLength = bag.maximum ?? null; +}, { + regex(...args) { + return this.check(_regex(...args)); + }, + includes(...args) { + return this.check(_includes(...args)); + }, + startsWith(...args) { + return this.check(_startsWith(...args)); + }, + endsWith(...args) { + return this.check(_endsWith(...args)); + }, + min(...args) { + return this.check(_minLength(...args)); + }, + max(...args) { + return this.check(_maxLength(...args)); + }, + length(...args) { + return this.check(_length(...args)); + }, + nonempty(...args) { + return this.check(_minLength(1, ...args)); + }, + lowercase(params) { + return this.check(_lowercase(params)); + }, + uppercase(params) { + return this.check(_uppercase(params)); + }, + trim() { + return this.check(_trim()); + }, + normalize(...args) { + return this.check(_normalize(...args)); + }, + toLowerCase() { + return this.check(_toLowerCase()); + }, + toUpperCase() { + return this.check(_toUpperCase()); + }, + slugify() { + return this.check(_slugify()); + }, +}); +const ZodString = /*@__PURE__*/ $constructor("ZodString", (inst, def) => { + $ZodString.init(inst, def); + _ZodString.init(inst, def); +}, { + email(params) { + return this.check(_email(ZodEmail, params)); + }, + url(params) { + return this.check(_url(ZodURL, params)); + }, + jwt(params) { + return this.check(_jwt(ZodJWT, params)); + }, + emoji(params) { + return this.check(api_emoji(ZodEmoji, params)); + }, + guid(params) { + return this.check(_guid(ZodGUID, params)); + }, + uuid(params) { + return this.check(_uuid(ZodUUID, params)); + }, + uuidv4(params) { + return this.check(_uuidv4(ZodUUID, params)); + }, + uuidv6(params) { + return this.check(_uuidv6(ZodUUID, params)); + }, + uuidv7(params) { + return this.check(_uuidv7(ZodUUID, params)); + }, + nanoid(params) { + return this.check(_nanoid(ZodNanoID, params)); + }, + cuid(params) { + return this.check(_cuid(ZodCUID, params)); + }, + cuid2(params) { + return this.check(_cuid2(ZodCUID2, params)); + }, + ulid(params) { + return this.check(_ulid(ZodULID, params)); + }, + base64(params) { + return this.check(_base64(ZodBase64, params)); + }, + base64url(params) { + return this.check(_base64url(ZodBase64URL, params)); + }, + xid(params) { + return this.check(_xid(ZodXID, params)); + }, + ksuid(params) { + return this.check(_ksuid(ZodKSUID, params)); + }, + ipv4(params) { + return this.check(_ipv4(ZodIPv4, params)); + }, + ipv6(params) { + return this.check(_ipv6(ZodIPv6, params)); + }, + cidrv4(params) { + return this.check(_cidrv4(ZodCIDRv4, params)); + }, + cidrv6(params) { + return this.check(_cidrv6(ZodCIDRv6, params)); + }, + e164(params) { + return this.check(_e164(ZodE164, params)); + }, + datetime(params) { + return this.check(_isoDateTime(ZodISODateTime, params)); + }, + date(params) { + return this.check(_isoDate(ZodISODate, params)); + }, + time(params) { + return this.check(_isoTime(schemas_ZodISOTime, params)); + }, + duration(params) { + return this.check(_isoDuration(schemas_ZodISODuration, params)); + }, +}); +function schemas_string(params) { + return _string(ZodString, params); +} +const ZodStringFormat = /*@__PURE__*/ $constructor("ZodStringFormat", (inst, def) => { + $ZodStringFormat.init(inst, def); + _ZodString.init(inst, def); +}); +const ZodISODateTime = /*@__PURE__*/ $constructor("ZodISODateTime", (inst, def) => { + $ZodISODateTime.init(inst, def); + ZodStringFormat.init(inst, def); +}); +const ZodISODate = /*@__PURE__*/ $constructor("ZodISODate", (inst, def) => { + $ZodISODate.init(inst, def); + ZodStringFormat.init(inst, def); +}); +const schemas_ZodISOTime = /*@__PURE__*/ $constructor("ZodISOTime", (inst, def) => { + $ZodISOTime.init(inst, def); + ZodStringFormat.init(inst, def); +}); +const schemas_ZodISODuration = /*@__PURE__*/ $constructor("ZodISODuration", (inst, def) => { + $ZodISODuration.init(inst, def); + ZodStringFormat.init(inst, def); +}); +const ZodEmail = /*@__PURE__*/ $constructor("ZodEmail", (inst, def) => { + // ZodStringFormat.init(inst, def); + $ZodEmail.init(inst, def); + ZodStringFormat.init(inst, def); +}); +function schemas_email(params) { + return _email(ZodEmail, params); +} +const ZodGUID = /*@__PURE__*/ $constructor("ZodGUID", (inst, def) => { + // ZodStringFormat.init(inst, def); + $ZodGUID.init(inst, def); + ZodStringFormat.init(inst, def); +}); +function schemas_guid(params) { + return core._guid(ZodGUID, params); +} +const ZodUUID = /*@__PURE__*/ $constructor("ZodUUID", (inst, def) => { + // ZodStringFormat.init(inst, def); + $ZodUUID.init(inst, def); + ZodStringFormat.init(inst, def); +}); +function schemas_uuid(params) { + return core._uuid(ZodUUID, params); +} +function uuidv4(params) { + return core._uuidv4(ZodUUID, params); +} +// ZodUUIDv6 +function uuidv6(params) { + return core._uuidv6(ZodUUID, params); +} +// ZodUUIDv7 +function uuidv7(params) { + return core._uuidv7(ZodUUID, params); +} +const ZodURL = /*@__PURE__*/ $constructor("ZodURL", (inst, def) => { + // ZodStringFormat.init(inst, def); + $ZodURL.init(inst, def); + ZodStringFormat.init(inst, def); +}); +function schemas_url(params) { + return _url(ZodURL, params); +} +function httpUrl(params) { + return core._url(ZodURL, { + protocol: core.regexes.httpProtocol, + hostname: core.regexes.domain, + ...util.normalizeParams(params), + }); +} +const ZodEmoji = /*@__PURE__*/ $constructor("ZodEmoji", (inst, def) => { + // ZodStringFormat.init(inst, def); + $ZodEmoji.init(inst, def); + ZodStringFormat.init(inst, def); +}); +function schemas_emoji(params) { + return core._emoji(ZodEmoji, params); +} +const ZodNanoID = /*@__PURE__*/ $constructor("ZodNanoID", (inst, def) => { + // ZodStringFormat.init(inst, def); + $ZodNanoID.init(inst, def); + ZodStringFormat.init(inst, def); +}); +function schemas_nanoid(params) { + return core._nanoid(ZodNanoID, params); +} +/** + * @deprecated CUID v1 is deprecated by its authors due to information leakage + * (timestamps embedded in the id). Use {@link ZodCUID2} instead. + * See https://github.com/paralleldrive/cuid. + */ +const ZodCUID = /*@__PURE__*/ $constructor("ZodCUID", (inst, def) => { + // ZodStringFormat.init(inst, def); + $ZodCUID.init(inst, def); + ZodStringFormat.init(inst, def); +}); +/** + * Validates a CUID v1 string. + * + * @deprecated CUID v1 is deprecated by its authors due to information leakage + * (timestamps embedded in the id). Use {@link cuid2 | `z.cuid2()`} instead. + * See https://github.com/paralleldrive/cuid. + */ +function schemas_cuid(params) { + return core._cuid(ZodCUID, params); +} +const ZodCUID2 = /*@__PURE__*/ $constructor("ZodCUID2", (inst, def) => { + // ZodStringFormat.init(inst, def); + $ZodCUID2.init(inst, def); + ZodStringFormat.init(inst, def); +}); +function schemas_cuid2(params) { + return core._cuid2(ZodCUID2, params); +} +const ZodULID = /*@__PURE__*/ $constructor("ZodULID", (inst, def) => { + // ZodStringFormat.init(inst, def); + $ZodULID.init(inst, def); + ZodStringFormat.init(inst, def); +}); +function schemas_ulid(params) { + return core._ulid(ZodULID, params); +} +const ZodXID = /*@__PURE__*/ $constructor("ZodXID", (inst, def) => { + // ZodStringFormat.init(inst, def); + $ZodXID.init(inst, def); + ZodStringFormat.init(inst, def); +}); +function schemas_xid(params) { + return core._xid(ZodXID, params); +} +const ZodKSUID = /*@__PURE__*/ $constructor("ZodKSUID", (inst, def) => { + // ZodStringFormat.init(inst, def); + $ZodKSUID.init(inst, def); + ZodStringFormat.init(inst, def); +}); +function schemas_ksuid(params) { + return core._ksuid(ZodKSUID, params); +} +const ZodIPv4 = /*@__PURE__*/ $constructor("ZodIPv4", (inst, def) => { + // ZodStringFormat.init(inst, def); + $ZodIPv4.init(inst, def); + ZodStringFormat.init(inst, def); +}); +function schemas_ipv4(params) { + return core._ipv4(ZodIPv4, params); +} +const ZodMAC = /*@__PURE__*/ (/* unused pure expression or super */ null && (core.$constructor("ZodMAC", (inst, def) => { + // ZodStringFormat.init(inst, def); + core.$ZodMAC.init(inst, def); + ZodStringFormat.init(inst, def); +}))); +function schemas_mac(params) { + return core._mac(ZodMAC, params); +} +const ZodIPv6 = /*@__PURE__*/ $constructor("ZodIPv6", (inst, def) => { + // ZodStringFormat.init(inst, def); + $ZodIPv6.init(inst, def); + ZodStringFormat.init(inst, def); +}); +function schemas_ipv6(params) { + return core._ipv6(ZodIPv6, params); +} +const ZodCIDRv4 = /*@__PURE__*/ $constructor("ZodCIDRv4", (inst, def) => { + $ZodCIDRv4.init(inst, def); + ZodStringFormat.init(inst, def); +}); +function schemas_cidrv4(params) { + return core._cidrv4(ZodCIDRv4, params); +} +const ZodCIDRv6 = /*@__PURE__*/ $constructor("ZodCIDRv6", (inst, def) => { + $ZodCIDRv6.init(inst, def); + ZodStringFormat.init(inst, def); +}); +function schemas_cidrv6(params) { + return core._cidrv6(ZodCIDRv6, params); +} +const ZodBase64 = /*@__PURE__*/ $constructor("ZodBase64", (inst, def) => { + // ZodStringFormat.init(inst, def); + $ZodBase64.init(inst, def); + ZodStringFormat.init(inst, def); +}); +function schemas_base64(params) { + return core._base64(ZodBase64, params); +} +const ZodBase64URL = /*@__PURE__*/ $constructor("ZodBase64URL", (inst, def) => { + // ZodStringFormat.init(inst, def); + $ZodBase64URL.init(inst, def); + ZodStringFormat.init(inst, def); +}); +function schemas_base64url(params) { + return core._base64url(ZodBase64URL, params); +} +const ZodE164 = /*@__PURE__*/ $constructor("ZodE164", (inst, def) => { + // ZodStringFormat.init(inst, def); + $ZodE164.init(inst, def); + ZodStringFormat.init(inst, def); +}); +function schemas_e164(params) { + return core._e164(ZodE164, params); +} +const ZodCreditCard = /*@__PURE__*/ (/* unused pure expression or super */ null && (core.$constructor("ZodCreditCard", (inst, def) => { + core.$ZodCreditCard.init(inst, def); + ZodStringFormat.init(inst, def); +}))); +function schemas_creditCard(params) { + return core._creditCard(ZodCreditCard, params); +} +const ZodJWT = /*@__PURE__*/ $constructor("ZodJWT", (inst, def) => { + // ZodStringFormat.init(inst, def); + $ZodJWT.init(inst, def); + ZodStringFormat.init(inst, def); +}); +function jwt(params) { + return core._jwt(ZodJWT, params); +} +const ZodCustomStringFormat = /*@__PURE__*/ (/* unused pure expression or super */ null && (core.$constructor("ZodCustomStringFormat", (inst, def) => { + // ZodStringFormat.init(inst, def); + core.$ZodCustomStringFormat.init(inst, def); + ZodStringFormat.init(inst, def); +}))); +function stringFormat(format, fnOrRegex, _params = {}) { + return core._stringFormat(ZodCustomStringFormat, format, fnOrRegex, _params); +} +function schemas_hostname(_params) { + return core._stringFormat(ZodCustomStringFormat, "hostname", core.regexes.hostname, _params); +} +function schemas_hex(_params) { + return core._stringFormat(ZodCustomStringFormat, "hex", core.regexes.hex, _params); +} +function schemas_hash(alg, params) { + const enc = params?.enc ?? "hex"; + const format = `${alg}_${enc}`; + const regex = core.regexes[format]; + if (!regex) + throw new Error(`Unrecognized hash format: ${format}`); + return core._stringFormat(ZodCustomStringFormat, format, regex, params); +} +const ZodNumber = /*@__PURE__*/ $constructor("ZodNumber", (inst, def) => { + $ZodNumber.init(inst, def); + ZodType.init(inst, def); + inst._zod.processJSONSchema = (ctx, json, params) => numberProcessor(inst, ctx, json, params); + const bag = inst._zod.bag; + inst.minValue = + Math.max(bag.minimum ?? Number.NEGATIVE_INFINITY, bag.exclusiveMinimum ?? Number.NEGATIVE_INFINITY) ?? null; + inst.maxValue = + Math.min(bag.maximum ?? Number.POSITIVE_INFINITY, bag.exclusiveMaximum ?? Number.POSITIVE_INFINITY) ?? null; + inst.isInt = (bag.format ?? "").includes("int") || Number.isSafeInteger(bag.multipleOf ?? 0.5); + inst.isFinite = true; + inst.format = bag.format ?? null; +}, { + gt(value, params) { + return this.check(_gt(value, params)); + }, + gte(value, params) { + return this.check(_gte(value, params)); + }, + min(value, params) { + return this.check(_gte(value, params)); + }, + lt(value, params) { + return this.check(_lt(value, params)); + }, + lte(value, params) { + return this.check(_lte(value, params)); + }, + max(value, params) { + return this.check(_lte(value, params)); + }, + int(params) { + return this.check(schemas_int(params)); + }, + safe(params) { + return this.check(schemas_int(params)); + }, + positive(params) { + return this.check(_gt(0, params)); + }, + nonnegative(params) { + return this.check(_gte(0, params)); + }, + negative(params) { + return this.check(_lt(0, params)); + }, + nonpositive(params) { + return this.check(_lte(0, params)); + }, + multipleOf(value, params) { + return this.check(_multipleOf(value, params)); + }, + step(value, params) { + return this.check(_multipleOf(value, params)); + }, + finite() { + return this; + }, +}); +function schemas_number(params) { + return _number(ZodNumber, params); +} +const ZodNumberFormat = /*@__PURE__*/ $constructor("ZodNumberFormat", (inst, def) => { + $ZodNumberFormat.init(inst, def); + ZodNumber.init(inst, def); +}); +function schemas_int(params) { + return _int(ZodNumberFormat, params); +} +function float32(params) { + return core._float32(ZodNumberFormat, params); +} +function float64(params) { + return core._float64(ZodNumberFormat, params); +} +function int32(params) { + return core._int32(ZodNumberFormat, params); +} +function uint32(params) { + return core._uint32(ZodNumberFormat, params); +} +const ZodBoolean = /*@__PURE__*/ $constructor("ZodBoolean", (inst, def) => { + $ZodBoolean.init(inst, def); + ZodType.init(inst, def); + inst._zod.processJSONSchema = (ctx, json, params) => booleanProcessor(inst, ctx, json, params); +}); +function schemas_boolean(params) { + return _boolean(ZodBoolean, params); +} +const ZodBigInt = /*@__PURE__*/ (/* unused pure expression or super */ null && (core.$constructor("ZodBigInt", (inst, def) => { + core.$ZodBigInt.init(inst, def); + ZodType.init(inst, def); + inst._zod.processJSONSchema = (ctx, json, params) => processors.bigintProcessor(inst, ctx, json, params); + const bag = inst._zod.bag; + inst.minValue = bag.minimum ?? null; + inst.maxValue = bag.maximum ?? null; + inst.format = bag.format ?? null; +}, { + gte(value, params) { + return this.check(checks.gte(value, params)); + }, + min(value, params) { + return this.check(checks.gte(value, params)); + }, + gt(value, params) { + return this.check(checks.gt(value, params)); + }, + lt(value, params) { + return this.check(checks.lt(value, params)); + }, + lte(value, params) { + return this.check(checks.lte(value, params)); + }, + max(value, params) { + return this.check(checks.lte(value, params)); + }, + positive(params) { + return this.check(checks.gt(BigInt(0), params)); + }, + negative(params) { + return this.check(checks.lt(BigInt(0), params)); + }, + nonpositive(params) { + return this.check(checks.lte(BigInt(0), params)); + }, + nonnegative(params) { + return this.check(checks.gte(BigInt(0), params)); + }, + multipleOf(value, params) { + return this.check(checks.multipleOf(value, params)); + }, +}))); +function schemas_bigint(params) { + return core._bigint(ZodBigInt, params); +} +const ZodBigIntFormat = /*@__PURE__*/ (/* unused pure expression or super */ null && (core.$constructor("ZodBigIntFormat", (inst, def) => { + core.$ZodBigIntFormat.init(inst, def); + ZodBigInt.init(inst, def); +}))); +function int64(params) { + return core._int64(ZodBigIntFormat, params); +} +function uint64(params) { + return core._uint64(ZodBigIntFormat, params); +} +const ZodSymbol = /*@__PURE__*/ (/* unused pure expression or super */ null && (core.$constructor("ZodSymbol", (inst, def) => { + core.$ZodSymbol.init(inst, def); + ZodType.init(inst, def); + inst._zod.processJSONSchema = (ctx, json, params) => processors.symbolProcessor(inst, ctx, json, params); +}))); +function symbol(params) { + return core._symbol(ZodSymbol, params); +} +const ZodUndefined = /*@__PURE__*/ (/* unused pure expression or super */ null && (core.$constructor("ZodUndefined", (inst, def) => { + core.$ZodUndefined.init(inst, def); + ZodType.init(inst, def); + inst._zod.processJSONSchema = (ctx, json, params) => processors.undefinedProcessor(inst, ctx, json, params); +}))); +function schemas_undefined(params) { + return core._undefined(ZodUndefined, params); +} + +const ZodNull = /*@__PURE__*/ $constructor("ZodNull", (inst, def) => { + $ZodNull.init(inst, def); + ZodType.init(inst, def); + inst._zod.processJSONSchema = (ctx, json, params) => nullProcessor(inst, ctx, json, params); +}); +function schemas_null(params) { + return api_null(ZodNull, params); +} + +const ZodAny = /*@__PURE__*/ $constructor("ZodAny", (inst, def) => { + $ZodAny.init(inst, def); + ZodType.init(inst, def); + inst._zod.processJSONSchema = (ctx, json, params) => anyProcessor(inst, ctx, json, params); +}); +function any() { + return _any(ZodAny); +} +const ZodUnknown = /*@__PURE__*/ $constructor("ZodUnknown", (inst, def) => { + $ZodUnknown.init(inst, def); + ZodType.init(inst, def); + inst._zod.processJSONSchema = (ctx, json, params) => unknownProcessor(inst, ctx, json, params); +}); +function unknown() { + return _unknown(ZodUnknown); +} +const ZodNever = /*@__PURE__*/ $constructor("ZodNever", (inst, def) => { + $ZodNever.init(inst, def); + ZodType.init(inst, def); + inst._zod.processJSONSchema = (ctx, json, params) => neverProcessor(inst, ctx, json, params); +}); +function never(params) { + return _never(ZodNever, params); +} +const ZodVoid = /*@__PURE__*/ (/* unused pure expression or super */ null && (core.$constructor("ZodVoid", (inst, def) => { + core.$ZodVoid.init(inst, def); + ZodType.init(inst, def); + inst._zod.processJSONSchema = (ctx, json, params) => processors.voidProcessor(inst, ctx, json, params); +}))); +function schemas_void(params) { + return core._void(ZodVoid, params); +} + +const ZodDate = /*@__PURE__*/ (/* unused pure expression or super */ null && (core.$constructor("ZodDate", (inst, def) => { + core.$ZodDate.init(inst, def); + ZodType.init(inst, def); + inst._zod.processJSONSchema = (ctx, json, params) => processors.dateProcessor(inst, ctx, json, params); + inst.min = (value, params) => inst.check(checks.gte(value, params)); + inst.max = (value, params) => inst.check(checks.lte(value, params)); + const c = inst._zod.bag; + inst.minDate = c.minimum ? new Date(c.minimum) : null; + inst.maxDate = c.maximum ? new Date(c.maximum) : null; +}))); +function schemas_date(params) { + return core._date(ZodDate, params); +} +const ZodArray = /*@__PURE__*/ $constructor("ZodArray", (inst, def) => { + _ensureDefaultMemoizer(); + $ZodArray.init(inst, def); + ZodType.init(inst, def); + inst._zod.processJSONSchema = (ctx, json, params) => arrayProcessor(inst, ctx, json, params); + inst.element = def.element; +}, { + min(n, params) { + return this.check(_minLength(n, params)); + }, + nonempty(params) { + return this.check(_minLength(1, params)); + }, + max(n, params) { + return this.check(_maxLength(n, params)); + }, + length(n, params) { + return this.check(_length(n, params)); + }, + unwrap() { + return this.element; + }, +}); +function schemas_array(element, params) { + return _array(ZodArray, element, params); +} +// .keyof +function keyof(schema) { + const shape = schema._zod.def.shape; + return schemas_enum(Object.keys(shape)); +} +const ZodObject = /*@__PURE__*/ $constructor("ZodObject", (inst, def) => { + _ensureDefaultMemoizer(); + $ZodObjectJIT.init(inst, def); + ZodType.init(inst, def); + inst._zod.processJSONSchema = (ctx, json, params) => objectProcessor(inst, ctx, json, params); + installLazyProp(inst, "shape", (self) => self._zod.def.shape, false); +}, { + keyof() { + return schemas_enum(Object.keys(this._zod.def.shape)); + }, + catchall(catchall) { + return this.clone({ ...this._zod.def, catchall: catchall }); + }, + passthrough() { + return this.clone({ ...this._zod.def, catchall: unknown() }); + }, + loose() { + return this.clone({ ...this._zod.def, catchall: unknown() }); + }, + strict() { + return this.clone({ ...this._zod.def, catchall: never() }); + }, + strip() { + return this.clone({ ...this._zod.def, catchall: undefined }); + }, + extend(incoming) { + return extend(this, incoming); + }, + safeExtend(incoming) { + return safeExtend(this, incoming); + }, + merge(other) { + return merge(this, other); + }, + pick(mask) { + return pick(this, mask); + }, + omit(mask) { + return omit(this, mask); + }, + partial(...args) { + return partial(ZodOptional, this, args[0]); + }, + exactPartial(...args) { + return partial(ZodExactOptional, this, args[0], "exactPartial"); + }, + required(...args) { + return util_required(ZodNonOptional, this, args[0]); + }, +}); +function schemas_object(shape, params) { + const def = { + type: "object", + shape: shape ?? {}, + ...normalizeParams(params), + }; + return new ZodObject(def); +} +// strictObject +function strictObject(shape, params) { + return new ZodObject({ + type: "object", + shape, + catchall: never(), + ...util.normalizeParams(params), + }); +} +// looseObject +function looseObject(shape, params) { + return new ZodObject({ + type: "object", + shape, + catchall: unknown(), + ...normalizeParams(params), + }); +} +const ZodUnion = /*@__PURE__*/ $constructor("ZodUnion", (inst, def) => { + $ZodUnion.init(inst, def); + ZodType.init(inst, def); + inst._zod.processJSONSchema = (ctx, json, params) => unionProcessor(inst, ctx, json, params); + inst.options = def.options; +}); +function schemas_union(options, params) { + return new ZodUnion({ + type: "union", + options: options, + ...normalizeParams(params), + }); +} +const ZodXor = /*@__PURE__*/ (/* unused pure expression or super */ null && (core.$constructor("ZodXor", (inst, def) => { + ZodUnion.init(inst, def); + core.$ZodXor.init(inst, def); + inst._zod.processJSONSchema = (ctx, json, params) => processors.unionProcessor(inst, ctx, json, params); + inst.options = def.options; +}))); +/** Creates an exclusive union (XOR) where exactly one option must match. + * Unlike regular unions that succeed when any option matches, xor fails if + * zero or more than one option matches the input. */ +function xor(options, params) { + return new ZodXor({ + type: "union", + options: options, + inclusive: false, + ...util.normalizeParams(params), + }); +} +const ZodDiscriminatedUnion = /*@__PURE__*/ $constructor("ZodDiscriminatedUnion", (inst, def) => { + ZodUnion.init(inst, def); + $ZodDiscriminatedUnion.init(inst, def); +}); +function discriminatedUnion(discriminator, options, params) { + // const [options, params] = args; + return new ZodDiscriminatedUnion({ + type: "union", + options: options, + discriminator, + ...normalizeParams(params), + }); +} +const ZodIntersection = /*@__PURE__*/ $constructor("ZodIntersection", (inst, def) => { + $ZodIntersection.init(inst, def); + ZodType.init(inst, def); + inst._zod.processJSONSchema = (ctx, json, params) => intersectionProcessor(inst, ctx, json, params); +}); +function intersection(left, right) { + return new ZodIntersection({ + type: "intersection", + left: left, + right: right, + }); +} +const ZodTuple = /*@__PURE__*/ (/* unused pure expression or super */ null && (core.$constructor("ZodTuple", (inst, def) => { + _ensureDefaultMemoizer(); + core.$ZodTuple.init(inst, def); + ZodType.init(inst, def); + inst._zod.processJSONSchema = (ctx, json, params) => processors.tupleProcessor(inst, ctx, json, params); +}, { + rest(rest) { + return this.clone({ + ...this._zod.def, + rest: rest, + }); + }, + partial() { + const def = this._zod.def; + // a refinement was authored against the full arity; partialing would run it on a shorter array + if (def.checks?.length) + throw new Error(".partial() cannot be used on tuple schemas containing refinements"); + return this.clone({ + ...def, + items: def.items.map((item) => new ZodOptional({ type: "optional", innerType: item })), + }); + }, +}))); +function tuple(items, _paramsOrRest, _params) { + const hasRest = _paramsOrRest instanceof core.$ZodType; + const params = hasRest ? _params : _paramsOrRest; + const rest = hasRest ? _paramsOrRest : null; + return new ZodTuple({ + type: "tuple", + items: items, + rest, + ...util.normalizeParams(params), + }); +} +const ZodRecord = /*@__PURE__*/ $constructor("ZodRecord", (inst, def) => { + _ensureDefaultMemoizer(); + $ZodRecord.init(inst, def); + ZodType.init(inst, def); + inst._zod.processJSONSchema = (ctx, json, params) => recordProcessor(inst, ctx, json, params); + inst.keyType = def.keyType; + inst.valueType = def.valueType; +}); +function schemas_record(keyType, valueType, params) { + // v3-compat: z.record(valueType, params?) — defaults keyType to z.string() + if (!valueType || !valueType._zod) { + return new ZodRecord({ + type: "record", + keyType: schemas_string(), + valueType: keyType, + ...normalizeParams(valueType), + }); + } + return new ZodRecord({ + type: "record", + keyType, + valueType: valueType, + ...normalizeParams(params), + }); +} +// type alksjf = core.output; +function partialRecord(keyType, valueType, params) { + return new ZodRecord({ + type: "record", + keyType, + valueType: valueType, + ...util.normalizeParams(params), + partial: true, + }); +} +function looseRecord(keyType, valueType, params) { + return new ZodRecord({ + type: "record", + keyType, + valueType: valueType, + mode: "loose", + ...util.normalizeParams(params), + }); +} +const ZodMap = /*@__PURE__*/ (/* unused pure expression or super */ null && (core.$constructor("ZodMap", (inst, def) => { + _ensureDefaultMemoizer(); + core.$ZodMap.init(inst, def); + ZodType.init(inst, def); + inst._zod.processJSONSchema = (ctx, json, params) => processors.mapProcessor(inst, ctx, json, params); + inst.keyType = def.keyType; + inst.valueType = def.valueType; + inst.min = (...args) => inst.check(core._minSize(...args)); + inst.nonempty = (params) => inst.check(core._minSize(1, params)); + inst.max = (...args) => inst.check(core._maxSize(...args)); + inst.size = (...args) => inst.check(core._size(...args)); +}))); +function schemas_map(keyType, valueType, params) { + return new ZodMap({ + type: "map", + keyType: keyType, + valueType: valueType, + ...util.normalizeParams(params), + }); +} +const ZodSet = /*@__PURE__*/ (/* unused pure expression or super */ null && (core.$constructor("ZodSet", (inst, def) => { + _ensureDefaultMemoizer(); + core.$ZodSet.init(inst, def); + ZodType.init(inst, def); + inst._zod.processJSONSchema = (ctx, json, params) => processors.setProcessor(inst, ctx, json, params); + inst.min = (...args) => inst.check(core._minSize(...args)); + inst.nonempty = (params) => inst.check(core._minSize(1, params)); + inst.max = (...args) => inst.check(core._maxSize(...args)); + inst.size = (...args) => inst.check(core._size(...args)); +}))); +function schemas_set(valueType, params) { + return new ZodSet({ + type: "set", + valueType: valueType, + ...util.normalizeParams(params), + }); +} +const ZodEnum = /*@__PURE__*/ $constructor("ZodEnum", (inst, def) => { + $ZodEnum.init(inst, def); + ZodType.init(inst, def); + inst._zod.processJSONSchema = (ctx, json, params) => enumProcessor(inst, ctx, json, params); + inst.enum = def.entries; + inst.options = Object.values(def.entries); + const keys = new Set(Object.keys(def.entries)); + inst.extract = (values, params) => { + const newEntries = {}; + for (const value of values) { + if (keys.has(value)) { + newEntries[value] = def.entries[value]; + } + else + throw new Error(`Key ${value} not found in enum`); + } + return new ZodEnum({ + ...def, + checks: [], + ...normalizeParams(params), + entries: newEntries, + }); + }; + inst.exclude = (values, params) => { + const newEntries = { ...def.entries }; + for (const value of values) { + if (keys.has(value)) { + delete newEntries[value]; + } + else + throw new Error(`Key ${value} not found in enum`); + } + return new ZodEnum({ + ...def, + checks: [], + ...normalizeParams(params), + entries: newEntries, + }); + }; +}); +function schemas_enum(values, params) { + const entries = Array.isArray(values) ? Object.fromEntries(values.map((v) => [v, v])) : values; + return new ZodEnum({ + type: "enum", + entries, + ...normalizeParams(params), + }); +} + +/** @deprecated This API has been merged into `z.enum()`. Use `z.enum()` instead. + * + * ```ts + * enum Colors { red, green, blue } + * z.enum(Colors); + * ``` + */ +function nativeEnum(entries, params) { + return new ZodEnum({ + type: "enum", + entries, + ...util.normalizeParams(params), + }); +} +const ZodLiteral = /*@__PURE__*/ $constructor("ZodLiteral", (inst, def) => { + $ZodLiteral.init(inst, def); + ZodType.init(inst, def); + inst._zod.processJSONSchema = (ctx, json, params) => literalProcessor(inst, ctx, json, params); + inst.values = new Set(def.values); + Object.defineProperty(inst, "value", { + get() { + if (def.values.length > 1) { + throw new Error("This schema contains multiple valid literal values. Use `.values` instead."); + } + return def.values[0]; + }, + }); +}); +function literal(value, params) { + return new ZodLiteral({ + type: "literal", + values: Array.isArray(value) ? value : [value], + ...normalizeParams(params), + }); +} +const ZodFile = /*@__PURE__*/ (/* unused pure expression or super */ null && (core.$constructor("ZodFile", (inst, def) => { + core.$ZodFile.init(inst, def); + ZodType.init(inst, def); + inst._zod.processJSONSchema = (ctx, json, params) => processors.fileProcessor(inst, ctx, json, params); + inst.min = (size, params) => inst.check(core._minSize(size, params)); + inst.max = (size, params) => inst.check(core._maxSize(size, params)); + inst.mime = (types, params) => inst.check(core._mime(Array.isArray(types) ? types : [types], params)); +}))); +function schemas_file(params) { + return core._file(ZodFile, params); +} +const ZodTransform = /*@__PURE__*/ $constructor("ZodTransform", (inst, def) => { + _ensureDefaultMemoizer(); + $ZodTransform.init(inst, def); + ZodType.init(inst, def); + inst._zod.processJSONSchema = (ctx, json, params) => transformProcessor(inst, ctx, json, params); + inst._zod.parse = (payload, _ctx) => { + if (_ctx.direction === "backward") { + throw new $ZodEncodeError(inst.constructor.name); + } + payload.addIssue = (issue) => { + if (typeof issue === "string") { + payload.issues.push(util_issue(issue, payload.value, def)); + } + else { + // for Zod 3 backwards compatibility + const _issue = issue; + if (_issue.fatal) + _issue.continue = false; + _issue.code ?? (_issue.code = "custom"); + if (!("input" in _issue)) + _issue.input = payload.value; + _issue.inst ?? (_issue.inst = inst); + // _issue.continue ??= true; + payload.issues.push(util_issue(_issue)); + } + }; + const output = def.transform(payload.value, payload); + if (output instanceof Promise) { + return output.then((output) => { + payload.value = output; + return payload; + }); + } + payload.value = output; + return payload; + }; +}); +function transform(fn) { + return new ZodTransform({ + type: "transform", + transform: fn, + }); +} +const ZodOptional = /*@__PURE__*/ $constructor("ZodOptional", (inst, def) => { + $ZodOptional.init(inst, def); + ZodType.init(inst, def); + inst._zod.processJSONSchema = (ctx, json, params) => optionalProcessor(inst, ctx, json, params); + inst.unwrap = () => inst._zod.def.innerType; +}); +function schemas_optional(innerType) { + return new ZodOptional({ + type: "optional", + innerType: innerType, + }); +} +const ZodExactOptional = /*@__PURE__*/ $constructor("ZodExactOptional", (inst, def) => { + $ZodExactOptional.init(inst, def); + ZodType.init(inst, def); + inst._zod.processJSONSchema = (ctx, json, params) => optionalProcessor(inst, ctx, json, params); + inst.unwrap = () => inst._zod.def.innerType; +}); +function exactOptional(innerType) { + return new ZodExactOptional({ + type: "optional", + innerType: innerType, + }); +} +const ZodNullable = /*@__PURE__*/ $constructor("ZodNullable", (inst, def) => { + $ZodNullable.init(inst, def); + ZodType.init(inst, def); + inst._zod.processJSONSchema = (ctx, json, params) => nullableProcessor(inst, ctx, json, params); + inst.unwrap = () => inst._zod.def.innerType; +}); +function nullable(innerType) { + return new ZodNullable({ + type: "nullable", + innerType: innerType, + }); +} +// nullish +function schemas_nullish(innerType) { + return schemas_optional(nullable(innerType)); +} +const ZodDefault = /*@__PURE__*/ $constructor("ZodDefault", (inst, def) => { + $ZodDefault.init(inst, def); + ZodType.init(inst, def); + inst._zod.processJSONSchema = (ctx, json, params) => defaultProcessor(inst, ctx, json, params); + inst.unwrap = () => inst._zod.def.innerType; + inst.removeDefault = inst.unwrap; +}); +function schemas_default(innerType, defaultValue) { + return new ZodDefault({ + type: "default", + innerType: innerType, + get defaultValue() { + return typeof defaultValue === "function" ? defaultValue() : shallowClone(defaultValue); + }, + }); +} +const ZodPrefault = /*@__PURE__*/ $constructor("ZodPrefault", (inst, def) => { + $ZodPrefault.init(inst, def); + ZodType.init(inst, def); + inst._zod.processJSONSchema = (ctx, json, params) => prefaultProcessor(inst, ctx, json, params); + inst.unwrap = () => inst._zod.def.innerType; +}); +function prefault(innerType, defaultValue) { + return new ZodPrefault({ + type: "prefault", + innerType: innerType, + get defaultValue() { + return typeof defaultValue === "function" ? defaultValue() : shallowClone(defaultValue); + }, + }); +} +const ZodNonOptional = /*@__PURE__*/ $constructor("ZodNonOptional", (inst, def) => { + $ZodNonOptional.init(inst, def); + ZodType.init(inst, def); + inst._zod.processJSONSchema = (ctx, json, params) => nonoptionalProcessor(inst, ctx, json, params); + inst.unwrap = () => inst._zod.def.innerType; +}); +function nonoptional(innerType, params) { + return new ZodNonOptional({ + type: "nonoptional", + innerType: innerType, + ...normalizeParams(params), + }); +} +const ZodSuccess = /*@__PURE__*/ (/* unused pure expression or super */ null && (core.$constructor("ZodSuccess", (inst, def) => { + core.$ZodSuccess.init(inst, def); + ZodType.init(inst, def); + inst._zod.processJSONSchema = (ctx, json, params) => processors.successProcessor(inst, ctx, json, params); + inst.unwrap = () => inst._zod.def.innerType; +}))); +function success(innerType) { + return new ZodSuccess({ + type: "success", + innerType: innerType, + }); +} +const ZodCatch = /*@__PURE__*/ $constructor("ZodCatch", (inst, def) => { + $ZodCatch.init(inst, def); + ZodType.init(inst, def); + inst._zod.processJSONSchema = (ctx, json, params) => catchProcessor(inst, ctx, json, params); + inst.unwrap = () => inst._zod.def.innerType; + inst.removeCatch = inst.unwrap; +}); +function schemas_catch(innerType, catchValue) { + return new ZodCatch({ + type: "catch", + innerType: innerType, + catchValue: (typeof catchValue === "function" ? catchValue : constantCatch(catchValue)), + }); +} + +const ZodNaN = /*@__PURE__*/ (/* unused pure expression or super */ null && (core.$constructor("ZodNaN", (inst, def) => { + core.$ZodNaN.init(inst, def); + ZodType.init(inst, def); + inst._zod.processJSONSchema = (ctx, json, params) => processors.nanProcessor(inst, ctx, json, params); +}))); +function nan(params) { + return core._nan(ZodNaN, params); +} +const ZodPipe = /*@__PURE__*/ $constructor("ZodPipe", (inst, def) => { + $ZodPipe.init(inst, def); + ZodType.init(inst, def); + inst._zod.processJSONSchema = (ctx, json, params) => pipeProcessor(inst, ctx, json, params); + inst.in = def.in; + inst.out = def.out; +}); +function pipe(in_, out) { + return new ZodPipe({ + type: "pipe", + in: in_, + out: out, + // ...util.normalizeParams(params), + }); +} +const ZodCodec = /*@__PURE__*/ (/* unused pure expression or super */ null && (core.$constructor("ZodCodec", (inst, def) => { + ZodPipe.init(inst, def); + core.$ZodCodec.init(inst, def); +}))); +function schemas_codec(in_, out, params) { + return new ZodCodec({ + type: "pipe", + in: in_, + out: out, + transform: params.decode, + reverseTransform: params.encode, + }); +} +function invertCodec(codec) { + const def = codec._zod.def; + return new ZodCodec({ + type: "pipe", + in: def.out, + out: def.in, + transform: def.reverseTransform, + reverseTransform: def.transform, + }); +} +const ZodPreprocess = /*@__PURE__*/ $constructor("ZodPreprocess", (inst, def) => { + ZodPipe.init(inst, def); + $ZodPreprocess.init(inst, def); +}); +const ZodReadonly = /*@__PURE__*/ $constructor("ZodReadonly", (inst, def) => { + $ZodReadonly.init(inst, def); + ZodType.init(inst, def); + inst._zod.processJSONSchema = (ctx, json, params) => readonlyProcessor(inst, ctx, json, params); + inst.unwrap = () => inst._zod.def.innerType; +}); +function readonly(innerType) { + return new ZodReadonly({ + type: "readonly", + innerType: innerType, + }); +} +const ZodTemplateLiteral = /*@__PURE__*/ (/* unused pure expression or super */ null && (core.$constructor("ZodTemplateLiteral", (inst, def) => { + core.$ZodTemplateLiteral.init(inst, def); + ZodType.init(inst, def); + inst._zod.processJSONSchema = (ctx, json, params) => processors.templateLiteralProcessor(inst, ctx, json, params); +}))); +function templateLiteral(parts, params) { + return new ZodTemplateLiteral({ + type: "template_literal", + parts, + ...util.normalizeParams(params), + }); +} +const ZodLazy = /*@__PURE__*/ $constructor("ZodLazy", (inst, def) => { + $ZodLazy.init(inst, def); + ZodType.init(inst, def); + inst._zod.processJSONSchema = (ctx, json, params) => lazyProcessor(inst, ctx, json, params); + inst.unwrap = () => inst._zod.def.getter(); +}); +function lazy(getter) { + return new ZodLazy({ + type: "lazy", + getter: getter, + }); +} +const ZodPromise = /*@__PURE__*/ (/* unused pure expression or super */ null && (core.$constructor("ZodPromise", (inst, def) => { + core.$ZodPromise.init(inst, def); + ZodType.init(inst, def); + inst._zod.processJSONSchema = (ctx, json, params) => processors.promiseProcessor(inst, ctx, json, params); + inst.unwrap = () => inst._zod.def.innerType; +}))); +function schemas_promise(innerType) { + return new ZodPromise({ + type: "promise", + innerType: innerType, + }); +} +const ZodFunction = /*@__PURE__*/ (/* unused pure expression or super */ null && (core.$constructor("ZodFunction", (inst, def) => { + core.$ZodFunction.init(inst, def); + ZodType.init(inst, def); + inst._zod.processJSONSchema = (ctx, json, params) => processors.functionProcessor(inst, ctx, json, params); +}))); +function _function(params) { + return new ZodFunction({ + type: "function", + input: Array.isArray(params?.input) ? tuple(params?.input) : (params?.input ?? schemas_array(unknown())), + output: params?.output ?? unknown(), + }); +} + +const ZodCustom = /*@__PURE__*/ $constructor("ZodCustom", (inst, def) => { + $ZodCustom.init(inst, def); + ZodType.init(inst, def); + inst._zod.processJSONSchema = (ctx, json, params) => customProcessor(inst, ctx, json, params); +}); +// custom checks +function schemas_check(fn) { + const ch = new core.$ZodCheck({ + check: "custom", + // ...util.normalizeParams(params), + }); + ch._zod.check = fn; + return ch; +} +function custom(fn, _params) { + return core._custom(ZodCustom, fn ?? (() => true), _params); +} +function refine(fn, _params = {}) { + return _refine(ZodCustom, fn, _params); +} +// superRefine +function superRefine(fn, params) { + return _superRefine(fn, params); +} +// Re-export describe and meta from core +const schemas_describe = describe; +const schemas_meta = api_meta; +function _instanceof(cls, params = {}) { + const inst = new ZodCustom({ + type: "custom", + check: "custom", + fn: (data) => data instanceof cls, + abort: true, + ...util.normalizeParams(params), + }); + inst._zod.bag.Class = cls; + // Override check to emit invalid_type instead of custom + inst._zod.check = (payload) => { + if (!(payload.value instanceof cls)) { + payload.issues.push({ + code: "invalid_type", + expected: cls.name, + input: payload.value, + inst, + path: [...(inst._zod.def.path ?? [])], + }); + } + }; + return inst; +} + +// stringbool +const stringbool = (...args) => core._stringbool({ + Codec: ZodCodec, + Boolean: ZodBoolean, + String: ZodString, +}, ...args); +function schemas_json(params) { + const jsonSchema = lazy(() => { + return schemas_union([schemas_string(params), schemas_number(), schemas_boolean(), schemas_null(), schemas_array(jsonSchema), schemas_record(schemas_string(), jsonSchema)]); + }); + return jsonSchema; +} +// preprocess +function preprocess(fn, schema) { + return new ZodPreprocess({ + type: "pipe", + in: transform(fn), + out: schema, + }); +} + + + + +function iso_datetime(params) { + return _isoDateTime(ZodISODateTime, params); +} +function iso_date(params) { + return _isoDate(ZodISODate, params); +} +function iso_time(params) { + return core._isoTime(ZodISOTime, params); +} +function iso_duration(params) { + return core._isoDuration(ZodISODuration, params); +} + +// Zod 3 compat layer + +/** @deprecated Use the raw string literal codes instead, e.g. "invalid_type". */ +const ZodIssueCode = { + 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", +}; + +/** @deprecated Use `z.config(params)` instead. */ +function setErrorMap(map) { + core.config({ + customError: map, + }); +} +/** @deprecated Use `z.config()` instead. */ +function getErrorMap() { + return core.config().customError; +} +/** @deprecated Do not use. Stub definition, only included for zod-to-json-schema compatibility. */ +var compat_ZodFirstPartyTypeKind; +(function (ZodFirstPartyTypeKind) { +})(compat_ZodFirstPartyTypeKind || (compat_ZodFirstPartyTypeKind = {})); + + + +function coerce_string(params) { + return core._coercedString(schemas.ZodString, params); +} +function coerce_number(params) { + return _coercedNumber(ZodNumber, params); +} +function coerce_boolean(params) { + return core._coercedBoolean(schemas.ZodBoolean, params); +} +function coerce_bigint(params) { + return core._coercedBigint(schemas.ZodBigInt, params); +} +function coerce_date(params) { + return core._coercedDate(schemas.ZodDate, params); +} + + + +//#region src/constants.ts +const LATEST_PROTOCOL_VERSION = "2025-11-25"; +const auth_CUe6YdwF_DEFAULT_NEGOTIATED_PROTOCOL_VERSION = "2025-03-26"; +const auth_CUe6YdwF_SUPPORTED_PROTOCOL_VERSIONS = [ + LATEST_PROTOCOL_VERSION, + "2025-06-18", + "2025-03-26", + "2024-11-05", + "2024-10-07" +]; +/** +* `_meta` key associating a message with a 2025-11-25 task. +* +* @deprecated 2025-11-25 wire vocabulary with no SDK runtime; kept importable for interoperability only. +*/ +const RELATED_TASK_META_KEY = "io.modelcontextprotocol/related-task"; +/** +* `_meta` key carrying the MCP protocol version governing a request. +* +* For the HTTP transport, the value must match the `MCP-Protocol-Version` header. +*/ +const auth_CUe6YdwF_PROTOCOL_VERSION_META_KEY = "io.modelcontextprotocol/protocolVersion"; +/** +* `_meta` key identifying the client software making a request. +* +* Clients SHOULD include it on every request; the value is self-reported and +* intended for display, logging, and debugging — servers should not rely on +* it for behavior or security decisions. +*/ +const auth_CUe6YdwF_CLIENT_INFO_META_KEY = "io.modelcontextprotocol/clientInfo"; +/** +* `_meta` key identifying the server software producing a response. +* +* Servers SHOULD include it on every response; the value is self-reported and +* intended for display, logging, and debugging — clients should not rely on +* it for behavior or security decisions. +*/ +const auth_CUe6YdwF_SERVER_INFO_META_KEY = "io.modelcontextprotocol/serverInfo"; +/** +* `_meta` key carrying the client's capabilities for a request. +* +* Capabilities are declared per request rather than once at initialization; +* servers must not infer capabilities from prior requests. +*/ +const auth_CUe6YdwF_CLIENT_CAPABILITIES_META_KEY = "io.modelcontextprotocol/clientCapabilities"; +/** +* `_meta` key carrying the JSON-RPC ID of the `subscriptions/listen` request +* that opened the stream a notification was delivered on. +* +* Stamped by the server on every notification delivered via a +* `subscriptions/listen` stream (including the leading +* `notifications/subscriptions/acknowledged`); on stdio, where all messages +* share one channel, clients use it to correlate notifications with their +* originating subscription. The value is the listen request's JSON-RPC ID +* verbatim. +*/ +const auth_CUe6YdwF_SUBSCRIPTION_ID_META_KEY = "io.modelcontextprotocol/subscriptionId"; +/** +* `_meta` key carrying the desired log level for a request. +* +* When absent, the server must not send `notifications/message` notifications +* for the request. +* +* @deprecated Deprecated as of protocol version 2026-07-28 (SEP-2577); remains +* in the specification for at least twelve months. +*/ +const LOG_LEVEL_META_KEY = "io.modelcontextprotocol/logLevel"; +/** +* `_meta` key carrying W3C Trace Context for distributed tracing (SEP-414). +* +* When present, the value MUST follow the W3C `traceparent` header format, +* e.g. `00-4bf92f3577b34da6a3ce929d0e0e4736-00f067aa0ba902b7-01`. +* +* @see https://www.w3.org/TR/trace-context/#traceparent-header +*/ +const TRACEPARENT_META_KEY = "traceparent"; +/** +* `_meta` key carrying vendor-specific trace state for distributed tracing (SEP-414). +* +* When present, the value MUST follow the W3C `tracestate` header format, +* e.g. `vendor1=value1,vendor2=value2`. +* +* @see https://www.w3.org/TR/trace-context/#tracestate-header +*/ +const TRACESTATE_META_KEY = "tracestate"; +/** +* `_meta` key carrying cross-cutting propagation values for distributed tracing (SEP-414). +* +* When present, the value MUST follow the W3C Baggage header format, +* e.g. `userId=alice,serverRegion=us-east-1`. +* +* @see https://www.w3.org/TR/baggage/ +*/ +const BAGGAGE_META_KEY = "baggage"; +const JSONRPC_VERSION = "2.0"; +const PARSE_ERROR = (/* unused pure expression or super */ null && (-32700)); +const INVALID_REQUEST = (/* unused pure expression or super */ null && (-32600)); +const METHOD_NOT_FOUND = (/* unused pure expression or super */ null && (-32601)); +const INVALID_PARAMS = (/* unused pure expression or super */ null && (-32602)); +const INTERNAL_ERROR = (/* unused pure expression or super */ null && (-32603)); + +//#endregion +//#region src/schemas.ts +const JSONValueSchema = lazy(() => schemas_union([ + schemas_string(), + schemas_number(), + schemas_boolean(), + schemas_null(), + schemas_record(schemas_string(), JSONValueSchema), + schemas_array(JSONValueSchema) +])); +const JSONObjectSchema = schemas_record(schemas_string(), JSONValueSchema); +const JSONArraySchema = schemas_array(JSONValueSchema); +/** +* A progress token, used to associate progress notifications with the original request. +*/ +const ProgressTokenSchema = schemas_union([schemas_string(), schemas_number().int()]); +/** +* An opaque token used to represent a cursor for pagination. +*/ +const CursorSchema = schemas_string(); +/** @deprecated 2025-11-25 wire vocabulary with no SDK runtime; kept importable for interoperability only. */ +const TaskMetadataSchema = schemas_object({ ttl: schemas_number().optional() }); +/** +* Metadata for associating messages with a task. +* Include this in the `_meta` field under the key `io.modelcontextprotocol/related-task`. +* +* @deprecated 2025-11-25 wire vocabulary with no SDK runtime; kept importable for interoperability only. +*/ +const RelatedTaskMetadataSchema = schemas_object({ taskId: schemas_string() }); +const RequestMetaSchema = looseObject({ + progressToken: ProgressTokenSchema.optional(), + [RELATED_TASK_META_KEY]: RelatedTaskMetadataSchema.optional() +}); +/** +* Common params for any request. +*/ +const BaseRequestParamsSchema = schemas_object({ _meta: RequestMetaSchema.optional() }); +/** +* Common params for any task-augmented request. +* +* @deprecated 2025-11-25 wire vocabulary with no SDK runtime; kept importable for interoperability only. +*/ +const auth_CUe6YdwF_TaskAugmentedRequestParamsSchema = BaseRequestParamsSchema.extend({ task: TaskMetadataSchema.optional() }); +const RequestSchema = schemas_object({ + method: schemas_string(), + params: BaseRequestParamsSchema.loose().optional() +}); +const NotificationsParamsSchema = schemas_object({ _meta: RequestMetaSchema.optional() }); +const NotificationSchema = schemas_object({ + method: schemas_string(), + params: NotificationsParamsSchema.loose().optional() +}); +/** +* The contents of a result's `_meta` field (the 2026-07-28 `ResultMetaObject`). +* Loose — implementation-specific keys pass through. +* +* The serverInfo key identifies the server software producing the response +* (servers SHOULD include it on every response; the value is self-reported +* and intended for display, logging, and debugging). The getter defers the +* `ImplementationSchema` reference, which is declared later in this file. +*/ +const ResultMetaObjectSchema = looseObject({ get [auth_CUe6YdwF_SERVER_INFO_META_KEY]() { + return ImplementationSchema.optional().catch(void 0); +} }); +const ResultSchema = looseObject({ _meta: ResultMetaObjectSchema.optional() }); +/** +* A uniquely identifying ID for a request in JSON-RPC. +*/ +const RequestIdSchema = schemas_union([schemas_string(), schemas_number().int()]); +/** +* A request that expects a response. +*/ +const JSONRPCRequestSchema = schemas_object({ + jsonrpc: literal(JSONRPC_VERSION), + id: RequestIdSchema, + ...RequestSchema.shape +}).strict(); +/** +* A notification which does not expect a response. +*/ +const JSONRPCNotificationSchema = schemas_object({ + jsonrpc: literal(JSONRPC_VERSION), + ...NotificationSchema.shape +}).strict(); +/** +* A successful (non-error) response to a request. +*/ +const JSONRPCResultResponseSchema = schemas_object({ + jsonrpc: literal(JSONRPC_VERSION), + id: RequestIdSchema, + result: ResultSchema +}).strict(); +/** +* A response to a request that indicates an error occurred. +*/ +const JSONRPCErrorResponseSchema = schemas_object({ + jsonrpc: literal(JSONRPC_VERSION), + id: RequestIdSchema.optional(), + error: schemas_object({ + code: schemas_number().int(), + message: schemas_string(), + data: unknown().optional() + }) +}).strict(); +const auth_CUe6YdwF_JSONRPCMessageSchema = schemas_union([ + JSONRPCRequestSchema, + JSONRPCNotificationSchema, + JSONRPCResultResponseSchema, + JSONRPCErrorResponseSchema +]); +const auth_CUe6YdwF_JSONRPCResponseSchema = schemas_union([JSONRPCResultResponseSchema, JSONRPCErrorResponseSchema]); +/** +* A response that indicates success but carries no data. +*/ +const EmptyResultSchema = ResultSchema.strict(); +const CancelledNotificationParamsSchema = NotificationsParamsSchema.extend({ + requestId: RequestIdSchema.optional(), + reason: schemas_string().optional() +}); +/** +* This notification can be sent by either side to indicate that it is cancelling a previously-issued request. +* +* The request SHOULD still be in-flight, but due to communication latency, it is always possible that this notification MAY arrive after the request has already finished. +* +* This notification indicates that the result will be unused, so any associated processing SHOULD cease. +* +* A client MUST NOT attempt to cancel its {@linkcode InitializeRequest | initialize} request. +*/ +const CancelledNotificationSchema = NotificationSchema.extend({ + method: literal("notifications/cancelled"), + params: CancelledNotificationParamsSchema +}); +/** +* Icon schema for use in {@link Tool | tools}, {@link Prompt | prompts}, {@link Resource | resources}, and {@link Implementation | implementations}. +*/ +const IconSchema = schemas_object({ + src: schemas_string(), + mimeType: schemas_string().optional(), + sizes: schemas_array(schemas_string()).optional(), + theme: schemas_enum(["light", "dark"]).optional() +}); +/** +* Base schema to add `icons` property. +* +*/ +const IconsSchema = schemas_object({ icons: schemas_array(IconSchema).optional() }); +/** +* Base metadata interface for common properties across {@link Resource | resources}, {@link Tool | tools}, {@link Prompt | prompts}, and {@link Implementation | implementations}. +*/ +const BaseMetadataSchema = schemas_object({ + name: schemas_string(), + title: schemas_string().optional() +}); +/** +* Describes the name and version of an MCP implementation. +*/ +const ImplementationSchema = BaseMetadataSchema.extend({ + ...BaseMetadataSchema.shape, + ...IconsSchema.shape, + version: schemas_string(), + websiteUrl: schemas_string().optional(), + description: schemas_string().optional() +}); +const auth_CUe6YdwF_FormElicitationCapabilitySchema = intersection(schemas_object({ applyDefaults: schemas_boolean().optional() }), JSONObjectSchema); +const auth_CUe6YdwF_ElicitationCapabilitySchema = preprocess((value) => { + if (value && typeof value === "object" && !Array.isArray(value) && Object.keys(value).length === 0) return { form: {} }; + return value; +}, intersection(schemas_object({ + form: auth_CUe6YdwF_FormElicitationCapabilitySchema.optional(), + url: JSONObjectSchema.optional() +}), JSONObjectSchema.optional())); +/** +* Task capabilities for clients, indicating which request types support task creation. +* +* @deprecated 2025-11-25 wire vocabulary with no SDK runtime; kept importable for interoperability only. +*/ +const ClientTasksCapabilitySchema = looseObject({ + list: JSONObjectSchema.optional(), + cancel: JSONObjectSchema.optional(), + requests: looseObject({ + sampling: looseObject({ createMessage: JSONObjectSchema.optional() }).optional(), + elicitation: looseObject({ create: JSONObjectSchema.optional() }).optional() + }).optional() +}); +/** +* Task capabilities for servers, indicating which request types support task creation. +* +* @deprecated 2025-11-25 wire vocabulary with no SDK runtime; kept importable for interoperability only. +*/ +const ServerTasksCapabilitySchema = looseObject({ + list: JSONObjectSchema.optional(), + cancel: JSONObjectSchema.optional(), + requests: looseObject({ tools: looseObject({ call: JSONObjectSchema.optional() }).optional() }).optional() +}); +/** +* Capabilities a client may support. Known capabilities are defined here, in this schema, but this is not a closed set: any client can define its own, additional capabilities. +*/ +const ClientCapabilitiesSchema = schemas_object({ + experimental: schemas_record(schemas_string(), JSONObjectSchema).optional(), + sampling: schemas_object({ + context: JSONObjectSchema.optional(), + tools: JSONObjectSchema.optional() + }).optional(), + elicitation: auth_CUe6YdwF_ElicitationCapabilitySchema.optional(), + roots: schemas_object({ listChanged: schemas_boolean().optional() }).optional(), + tasks: ClientTasksCapabilitySchema.optional(), + extensions: schemas_record(schemas_string(), JSONObjectSchema).optional() +}); +const InitializeRequestParamsSchema = BaseRequestParamsSchema.extend({ + protocolVersion: schemas_string(), + capabilities: ClientCapabilitiesSchema, + clientInfo: ImplementationSchema +}); +/** +* This request is sent from the client to the server when it first connects, asking it to begin initialization. +*/ +const auth_CUe6YdwF_InitializeRequestSchema = RequestSchema.extend({ + method: literal("initialize"), + params: InitializeRequestParamsSchema +}); +/** +* Capabilities that a server may support. Known capabilities are defined here, in this schema, but this is not a closed set: any server can define its own, additional capabilities. +*/ +const ServerCapabilitiesSchema = schemas_object({ + experimental: schemas_record(schemas_string(), JSONObjectSchema).optional(), + logging: JSONObjectSchema.optional(), + completions: JSONObjectSchema.optional(), + prompts: schemas_object({ listChanged: schemas_boolean().optional() }).optional(), + resources: schemas_object({ + subscribe: schemas_boolean().optional(), + listChanged: schemas_boolean().optional() + }).optional(), + tools: schemas_object({ listChanged: schemas_boolean().optional() }).optional(), + tasks: ServerTasksCapabilitySchema.optional(), + extensions: schemas_record(schemas_string(), JSONObjectSchema).optional() +}); +/** +* After receiving an initialize request from the client, the server sends this response. +*/ +const InitializeResultSchema = ResultSchema.extend({ + protocolVersion: schemas_string(), + capabilities: ServerCapabilitiesSchema, + serverInfo: ImplementationSchema, + instructions: schemas_string().optional() +}); +/** +* This notification is sent from the client to the server after initialization has finished. +*/ +const auth_CUe6YdwF_InitializedNotificationSchema = NotificationSchema.extend({ + method: literal("notifications/initialized"), + params: NotificationsParamsSchema.optional() +}); +/** +* A request from the client asking the server to advertise its supported protocol +* versions, capabilities, and other metadata (protocol revision 2026-07-28). Servers +* MUST implement `server/discover`. Clients MAY call it but are not required to — +* version negotiation can also happen inline via the per-request `_meta` envelope. +*/ +const DiscoverRequestSchema = RequestSchema.extend({ + method: literal("server/discover"), + params: BaseRequestParamsSchema.optional() +}); +/** +* The result returned by the server for a `server/discover` request. +*/ +const DiscoverResultSchema = ResultSchema.extend({ + supportedVersions: schemas_array(schemas_string()), + capabilities: ServerCapabilitiesSchema, + instructions: schemas_string().optional() +}); +/** +* A ping, issued by either the server or the client, to check that the other party is still alive. The receiver must promptly respond, or else may be disconnected. +*/ +const PingRequestSchema = RequestSchema.extend({ + method: literal("ping"), + params: BaseRequestParamsSchema.optional() +}); +const ProgressSchema = schemas_object({ + progress: schemas_number(), + total: schemas_optional(schemas_number()), + message: schemas_optional(schemas_string()) +}); +const ProgressNotificationParamsSchema = schemas_object({ + ...NotificationsParamsSchema.shape, + ...ProgressSchema.shape, + progressToken: ProgressTokenSchema +}); +/** +* An out-of-band notification used to inform the receiver of a progress update for a long-running request. +* +* @category notifications/progress +*/ +const ProgressNotificationSchema = NotificationSchema.extend({ + method: literal("notifications/progress"), + params: ProgressNotificationParamsSchema +}); +const PaginatedRequestParamsSchema = BaseRequestParamsSchema.extend({ cursor: CursorSchema.optional() }); +const PaginatedRequestSchema = RequestSchema.extend({ params: PaginatedRequestParamsSchema.optional() }); +const PaginatedResultSchema = ResultSchema.extend({ nextCursor: CursorSchema.optional() }); +/** +* The contents of a specific resource or sub-resource. +*/ +const ResourceContentsSchema = schemas_object({ + uri: schemas_string(), + mimeType: schemas_optional(schemas_string()), + _meta: schemas_record(schemas_string(), unknown()).optional() +}); +const TextResourceContentsSchema = ResourceContentsSchema.extend({ text: schemas_string() }); +/** +* A Zod schema for validating Base64 strings that is more performant and +* robust for very large inputs than the default regex-based check. It avoids +* stack overflows by using the native `atob` function for validation. +*/ +const auth_CUe6YdwF_Base64Schema = schemas_string().refine((val) => { + try { + atob(val); + return true; + } catch { + return false; + } +}, { message: "Invalid Base64 string" }); +const BlobResourceContentsSchema = ResourceContentsSchema.extend({ blob: auth_CUe6YdwF_Base64Schema }); +/** +* The sender or recipient of messages and data in a conversation. +*/ +const RoleSchema = schemas_enum(["user", "assistant"]); +/** +* Optional annotations providing clients additional context about a resource. +*/ +const AnnotationsSchema = schemas_object({ + audience: schemas_array(RoleSchema).optional(), + priority: schemas_number().min(0).max(1).optional(), + lastModified: iso_datetime({ offset: true }).optional() +}); +/** +* A known resource that the server is capable of reading. +*/ +const ResourceSchema = schemas_object({ + ...BaseMetadataSchema.shape, + ...IconsSchema.shape, + uri: schemas_string(), + description: schemas_optional(schemas_string()), + mimeType: schemas_optional(schemas_string()), + size: schemas_optional(schemas_number()), + annotations: AnnotationsSchema.optional(), + _meta: schemas_optional(looseObject({})) +}); +/** +* A template description for resources available on the server. +*/ +const ResourceTemplateSchema = schemas_object({ + ...BaseMetadataSchema.shape, + ...IconsSchema.shape, + uriTemplate: schemas_string(), + description: schemas_optional(schemas_string()), + mimeType: schemas_optional(schemas_string()), + annotations: AnnotationsSchema.optional(), + _meta: schemas_optional(looseObject({})) +}); +/** +* Sent from the client to request a list of resources the server has. +*/ +const ListResourcesRequestSchema = PaginatedRequestSchema.extend({ method: literal("resources/list") }); +/** +* The server's response to a {@linkcode ListResourcesRequest | resources/list} request from the client. +*/ +const ListResourcesResultSchema = PaginatedResultSchema.extend({ resources: schemas_array(ResourceSchema) }); +/** +* Sent from the client to request a list of resource templates the server has. +*/ +const ListResourceTemplatesRequestSchema = PaginatedRequestSchema.extend({ method: literal("resources/templates/list") }); +/** +* The server's response to a {@linkcode ListResourceTemplatesRequest | resources/templates/list} request from the client. +*/ +const ListResourceTemplatesResultSchema = PaginatedResultSchema.extend({ resourceTemplates: schemas_array(ResourceTemplateSchema) }); +const ResourceRequestParamsSchema = BaseRequestParamsSchema.extend({ uri: schemas_string() }); +/** +* Parameters for a {@linkcode ReadResourceRequest | resources/read} request. +*/ +const ReadResourceRequestParamsSchema = ResourceRequestParamsSchema; +/** +* Sent from the client to the server, to read a specific resource URI. +*/ +const ReadResourceRequestSchema = RequestSchema.extend({ + method: literal("resources/read"), + params: ReadResourceRequestParamsSchema +}); +/** +* The server's response to a {@linkcode ReadResourceRequest | resources/read} request from the client. +*/ +const ReadResourceResultSchema = ResultSchema.extend({ contents: schemas_array(schemas_union([TextResourceContentsSchema, BlobResourceContentsSchema])) }); +/** +* An optional notification from the server to the client, informing it that the list of resources it can read from has changed. This may be issued by servers without any previous subscription from the client. +*/ +const ResourceListChangedNotificationSchema = NotificationSchema.extend({ + method: literal("notifications/resources/list_changed"), + params: NotificationsParamsSchema.optional() +}); +const SubscribeRequestParamsSchema = ResourceRequestParamsSchema; +/** +* Sent from the client to request `resources/updated` notifications from the server whenever a particular resource changes. +*/ +const SubscribeRequestSchema = RequestSchema.extend({ + method: literal("resources/subscribe"), + params: SubscribeRequestParamsSchema +}); +const UnsubscribeRequestParamsSchema = ResourceRequestParamsSchema; +/** +* Sent from the client to request cancellation of {@linkcode ResourceUpdatedNotification | resources/updated} notifications from the server. This should follow a previous {@linkcode SubscribeRequest | resources/subscribe} request. +*/ +const UnsubscribeRequestSchema = RequestSchema.extend({ + method: literal("resources/unsubscribe"), + params: UnsubscribeRequestParamsSchema +}); +/** +* The set of notification types a client opts in to on a `subscriptions/listen` +* request. Each type is opt-in; the server MUST NOT send a notification type +* the client has not explicitly requested here. +*/ +const SubscriptionFilterSchema = schemas_object({ + toolsListChanged: schemas_boolean().optional(), + promptsListChanged: schemas_boolean().optional(), + resourcesListChanged: schemas_boolean().optional(), + resourceSubscriptions: schemas_array(schemas_string()).optional() +}); +const SubscriptionsListenRequestParamsSchema = BaseRequestParamsSchema.extend({ notifications: SubscriptionFilterSchema }); +/** +* Sent from the client to open a long-lived channel for receiving notifications +* outside the context of a specific request (protocol revision 2026-07-28). +* Replaces the previous HTTP GET endpoint and `resources/subscribe`. +*/ +const SubscriptionsListenRequestSchema = RequestSchema.extend({ + method: literal("subscriptions/listen"), + params: SubscriptionsListenRequestParamsSchema +}); +const SubscriptionsAcknowledgedNotificationParamsSchema = NotificationsParamsSchema.extend({ notifications: SubscriptionFilterSchema }); +/** +* Sent by the server as the first message on a `subscriptions/listen` stream +* to acknowledge that the subscription has been established and report which +* notification types it agreed to honor (protocol revision 2026-07-28). +*/ +const SubscriptionsAcknowledgedNotificationSchema = NotificationSchema.extend({ + method: literal("notifications/subscriptions/acknowledged"), + params: SubscriptionsAcknowledgedNotificationParamsSchema +}); +/** +* `_meta` for a {@linkcode SubscriptionsListenResult}: the listen request's +* JSON-RPC ID under the canonical subscription-id key (mirroring the same key +* on every notification delivered on the stream). Extends +* {@linkcode ResultMetaObjectSchema}, so the optional serverInfo key is typed +* here too. +*/ +const SubscriptionsListenResultMetaSchema = ResultMetaObjectSchema.extend({ [auth_CUe6YdwF_SUBSCRIPTION_ID_META_KEY]: RequestIdSchema }); +/** +* The response to a `subscriptions/listen` request, signalling that the +* subscription has ended gracefully (for example, during server shutdown). +* Because the listen stream is long-lived, this result is sent only when the +* server tears the subscription down; an abrupt transport close carries no +* response. The result body is otherwise empty. +*/ +const SubscriptionsListenResultSchema = ResultSchema.extend({ _meta: SubscriptionsListenResultMetaSchema }); +/** +* Parameters for a {@linkcode ResourceUpdatedNotification | notifications/resources/updated} notification. +*/ +const ResourceUpdatedNotificationParamsSchema = NotificationsParamsSchema.extend({ uri: schemas_string() }); +/** +* A notification from the server to the client, informing it that a resource has changed and may need to be read again. This should only be sent if the client previously sent a {@linkcode SubscribeRequest | resources/subscribe} request. +*/ +const ResourceUpdatedNotificationSchema = NotificationSchema.extend({ + method: literal("notifications/resources/updated"), + params: ResourceUpdatedNotificationParamsSchema +}); +/** +* Describes an argument that a prompt can accept. +*/ +const PromptArgumentSchema = schemas_object({ + name: schemas_string(), + description: schemas_optional(schemas_string()), + required: schemas_optional(schemas_boolean()) +}); +/** +* A prompt or prompt template that the server offers. +*/ +const PromptSchema = schemas_object({ + ...BaseMetadataSchema.shape, + ...IconsSchema.shape, + description: schemas_optional(schemas_string()), + arguments: schemas_optional(schemas_array(PromptArgumentSchema)), + _meta: schemas_optional(looseObject({})) +}); +/** +* Sent from the client to request a list of prompts and prompt templates the server has. +*/ +const ListPromptsRequestSchema = PaginatedRequestSchema.extend({ method: literal("prompts/list") }); +/** +* The server's response to a {@linkcode ListPromptsRequest | prompts/list} request from the client. +*/ +const ListPromptsResultSchema = PaginatedResultSchema.extend({ prompts: schemas_array(PromptSchema) }); +/** +* Parameters for a {@linkcode GetPromptRequest | prompts/get} request. +*/ +const GetPromptRequestParamsSchema = BaseRequestParamsSchema.extend({ + name: schemas_string(), + arguments: schemas_record(schemas_string(), schemas_string()).optional() +}); +/** +* Used by the client to get a prompt provided by the server. +*/ +const GetPromptRequestSchema = RequestSchema.extend({ + method: literal("prompts/get"), + params: GetPromptRequestParamsSchema +}); +/** +* Text provided to or from an LLM. +*/ +const TextContentSchema = schemas_object({ + type: literal("text"), + text: schemas_string(), + annotations: AnnotationsSchema.optional(), + _meta: schemas_record(schemas_string(), unknown()).optional() +}); +/** +* An image provided to or from an LLM. +*/ +const ImageContentSchema = schemas_object({ + type: literal("image"), + data: auth_CUe6YdwF_Base64Schema, + mimeType: schemas_string(), + annotations: AnnotationsSchema.optional(), + _meta: schemas_record(schemas_string(), unknown()).optional() +}); +/** +* Audio content provided to or from an LLM. +*/ +const AudioContentSchema = schemas_object({ + type: literal("audio"), + data: auth_CUe6YdwF_Base64Schema, + mimeType: schemas_string(), + annotations: AnnotationsSchema.optional(), + _meta: schemas_record(schemas_string(), unknown()).optional() +}); +/** +* A tool call request from an assistant (LLM). +* Represents the assistant's request to use a tool. +* +* @deprecated Deprecated as of protocol version 2026-07-28 (SEP-2577); remains +* in the specification for at least twelve months. Migrate to calling LLM +* provider APIs directly. +*/ +const ToolUseContentSchema = schemas_object({ + type: literal("tool_use"), + name: schemas_string(), + id: schemas_string(), + input: schemas_record(schemas_string(), unknown()), + _meta: schemas_record(schemas_string(), unknown()).optional() +}); +/** +* The contents of a resource, embedded into a prompt or tool call result. +*/ +const EmbeddedResourceSchema = schemas_object({ + type: literal("resource"), + resource: schemas_union([TextResourceContentsSchema, BlobResourceContentsSchema]), + annotations: AnnotationsSchema.optional(), + _meta: schemas_record(schemas_string(), unknown()).optional() +}); +/** +* A resource that the server is capable of reading, included in a prompt or tool call result. +* +* Note: resource links returned by tools are not guaranteed to appear in the results of {@linkcode ListResourcesRequest | resources/list} requests. +*/ +const ResourceLinkSchema = ResourceSchema.extend({ type: literal("resource_link") }); +/** +* A content block that can be used in prompts and tool results. +*/ +const ContentBlockSchema = schemas_union([ + TextContentSchema, + ImageContentSchema, + AudioContentSchema, + ResourceLinkSchema, + EmbeddedResourceSchema +]); +/** +* Describes a message returned as part of a prompt. +*/ +const PromptMessageSchema = schemas_object({ + role: RoleSchema, + content: ContentBlockSchema +}); +/** +* The server's response to a {@linkcode GetPromptRequest | prompts/get} request from the client. +*/ +const GetPromptResultSchema = ResultSchema.extend({ + description: schemas_string().optional(), + messages: schemas_array(PromptMessageSchema) +}); +/** +* An optional notification from the server to the client, informing it that the list of prompts it offers has changed. This may be issued by servers without any previous subscription from the client. +*/ +const PromptListChangedNotificationSchema = NotificationSchema.extend({ + method: literal("notifications/prompts/list_changed"), + params: NotificationsParamsSchema.optional() +}); +/** +* Additional properties describing a `Tool` to clients. +* +* NOTE: all properties in {@linkcode ToolAnnotations} are **hints**. +* They are not guaranteed to provide a faithful description of +* tool behavior (including descriptive properties like `title`). +* +* Clients should never make tool use decisions based on `ToolAnnotations` +* received from untrusted servers. +*/ +const ToolAnnotationsSchema = schemas_object({ + title: schemas_string().optional(), + readOnlyHint: schemas_boolean().optional(), + destructiveHint: schemas_boolean().optional(), + idempotentHint: schemas_boolean().optional(), + openWorldHint: schemas_boolean().optional() +}); +/** +* Execution-related properties for a tool. +*/ +const ToolExecutionSchema = schemas_object({ taskSupport: schemas_enum([ + "required", + "optional", + "forbidden" +]).optional() }); +/** +* Definition for a tool the client can call. +*/ +const ToolSchema = schemas_object({ + ...BaseMetadataSchema.shape, + ...IconsSchema.shape, + description: schemas_string().optional(), + inputSchema: schemas_object({ + type: literal("object"), + properties: schemas_record(schemas_string(), JSONValueSchema).optional(), + required: schemas_array(schemas_string()).optional() + }).catchall(unknown()), + outputSchema: looseObject({ $schema: schemas_string().optional() }).optional(), + annotations: ToolAnnotationsSchema.optional(), + execution: ToolExecutionSchema.optional(), + _meta: schemas_record(schemas_string(), unknown()).optional() +}); +/** +* Sent from the client to request a list of tools the server has. +*/ +const ListToolsRequestSchema = PaginatedRequestSchema.extend({ method: literal("tools/list") }); +/** +* The server's response to a {@linkcode ListToolsRequest | tools/list} request from the client. +*/ +const ListToolsResultSchema = PaginatedResultSchema.extend({ tools: schemas_array(ToolSchema) }); +/** +* The server's response to a tool call. +*/ +const auth_CUe6YdwF_CallToolResultSchema = ResultSchema.extend({ + content: schemas_array(ContentBlockSchema).default([]), + structuredContent: unknown().optional(), + isError: schemas_boolean().optional() +}); +/** +* {@linkcode CallToolResultSchema} extended with backwards compatibility to protocol version 2024-10-07. +*/ +const CompatibilityCallToolResultSchema = auth_CUe6YdwF_CallToolResultSchema.or(ResultSchema.extend({ toolResult: unknown() })); +/** +* Parameters for a `tools/call` request. +*/ +const CallToolRequestParamsSchema = auth_CUe6YdwF_TaskAugmentedRequestParamsSchema.extend({ + name: schemas_string(), + arguments: schemas_record(schemas_string(), unknown()).optional() +}); +/** +* Used by the client to invoke a tool provided by the server. +*/ +const CallToolRequestSchema = RequestSchema.extend({ + method: literal("tools/call"), + params: CallToolRequestParamsSchema +}); +/** +* An optional notification from the server to the client, informing it that the list of tools it offers has changed. This may be issued by servers without any previous subscription from the client. +*/ +const ToolListChangedNotificationSchema = NotificationSchema.extend({ + method: literal("notifications/tools/list_changed"), + params: NotificationsParamsSchema.optional() +}); +/** +* Base schema for list changed subscription options (without callback). +* Used internally for Zod validation of `autoRefresh` and `debounceMs`. +*/ +const ListChangedOptionsBaseSchema = schemas_object({ + autoRefresh: schemas_boolean().default(true), + debounceMs: schemas_number().int().nonnegative().default(300) +}); +/** +* The severity of a log message. +* +* @deprecated Deprecated as of protocol version 2026-07-28 (SEP-2577); remains +* in the specification for at least twelve months. Migrate to stderr logging +* (STDIO servers) or OpenTelemetry. +*/ +const LoggingLevelSchema = schemas_enum([ + "debug", + "info", + "notice", + "warning", + "error", + "critical", + "alert", + "emergency" +]); +/** +* Parameters for a `logging/setLevel` request. +* +* @deprecated Deprecated as of protocol version 2026-07-28 (SEP-2577); remains +* in the specification for at least twelve months. Migrate to stderr logging +* (STDIO servers) or OpenTelemetry. +*/ +const SetLevelRequestParamsSchema = BaseRequestParamsSchema.extend({ level: LoggingLevelSchema }); +/** +* A request from the client to the server, to enable or adjust logging. +* +* @deprecated Deprecated as of protocol version 2026-07-28 (SEP-2577); remains +* in the specification for at least twelve months. Migrate to stderr logging +* (STDIO servers) or OpenTelemetry. +*/ +const SetLevelRequestSchema = RequestSchema.extend({ + method: literal("logging/setLevel"), + params: SetLevelRequestParamsSchema +}); +/** +* Parameters for a `notifications/message` notification. +* +* @deprecated Deprecated as of protocol version 2026-07-28 (SEP-2577); remains +* in the specification for at least twelve months. Migrate to stderr logging +* (STDIO servers) or OpenTelemetry. +*/ +const LoggingMessageNotificationParamsSchema = NotificationsParamsSchema.extend({ + level: LoggingLevelSchema, + logger: schemas_string().optional(), + data: unknown() +}); +/** +* Notification of a log message passed from server to client. If no `logging/setLevel` request has been sent from the client, the server MAY decide which messages to send automatically. +* +* @deprecated Deprecated as of protocol version 2026-07-28 (SEP-2577); remains +* in the specification for at least twelve months. Migrate to stderr logging +* (STDIO servers) or OpenTelemetry. +*/ +const LoggingMessageNotificationSchema = NotificationSchema.extend({ + method: literal("notifications/message"), + params: LoggingMessageNotificationParamsSchema +}); +/** +* Hints to use for model selection. +* +* @deprecated Deprecated as of protocol version 2026-07-28 (SEP-2577); remains +* in the specification for at least twelve months. Migrate to calling LLM +* provider APIs directly. +*/ +const ModelHintSchema = schemas_object({ name: schemas_string().optional() }); +/** +* The server's preferences for model selection, requested of the client during sampling. +* +* @deprecated Deprecated as of protocol version 2026-07-28 (SEP-2577); remains +* in the specification for at least twelve months. Migrate to calling LLM +* provider APIs directly. +*/ +const ModelPreferencesSchema = schemas_object({ + hints: schemas_array(ModelHintSchema).optional(), + costPriority: schemas_number().min(0).max(1).optional(), + speedPriority: schemas_number().min(0).max(1).optional(), + intelligencePriority: schemas_number().min(0).max(1).optional() +}); +/** +* Controls tool usage behavior in sampling requests. +* +* @deprecated Deprecated as of protocol version 2026-07-28 (SEP-2577); remains +* in the specification for at least twelve months. Migrate to calling LLM +* provider APIs directly. +*/ +const ToolChoiceSchema = schemas_object({ mode: schemas_enum([ + "auto", + "required", + "none" +]).optional() }); +/** +* The result of a tool execution, provided by the user (server). +* Represents the outcome of invoking a tool requested via `ToolUseContent`. +* +* @deprecated Deprecated as of protocol version 2026-07-28 (SEP-2577); remains +* in the specification for at least twelve months. Migrate to calling LLM +* provider APIs directly. +*/ +const ToolResultContentSchema = schemas_object({ + type: literal("tool_result"), + toolUseId: schemas_string().describe("The unique identifier for the corresponding tool call."), + content: schemas_array(ContentBlockSchema), + structuredContent: unknown().optional(), + isError: schemas_boolean().optional(), + _meta: schemas_record(schemas_string(), unknown()).optional() +}); +/** +* Basic content types for sampling responses (without tool use). +* Used for backwards-compatible {@linkcode CreateMessageResult} when tools are not used. +* +* @deprecated Deprecated as of protocol version 2026-07-28 (SEP-2577); remains +* in the specification for at least twelve months. Migrate to calling LLM +* provider APIs directly. +*/ +const SamplingContentSchema = discriminatedUnion("type", [ + TextContentSchema, + ImageContentSchema, + AudioContentSchema +]); +/** +* Content block types allowed in sampling messages. +* This includes text, image, audio, tool use requests, and tool results. +* +* @deprecated Deprecated as of protocol version 2026-07-28 (SEP-2577); remains +* in the specification for at least twelve months. Migrate to calling LLM +* provider APIs directly. +*/ +const SamplingMessageContentBlockSchema = discriminatedUnion("type", [ + TextContentSchema, + ImageContentSchema, + AudioContentSchema, + ToolUseContentSchema, + ToolResultContentSchema +]); +/** +* Describes a message issued to or received from an LLM API. +* +* @deprecated Deprecated as of protocol version 2026-07-28 (SEP-2577); remains +* in the specification for at least twelve months. Migrate to calling LLM +* provider APIs directly. +*/ +const SamplingMessageSchema = schemas_object({ + role: RoleSchema, + content: schemas_union([SamplingMessageContentBlockSchema, schemas_array(SamplingMessageContentBlockSchema)]), + _meta: schemas_record(schemas_string(), unknown()).optional() +}); +/** +* Parameters for a `sampling/createMessage` request. +* +* @deprecated Deprecated as of protocol version 2026-07-28 (SEP-2577); remains +* in the specification for at least twelve months. Migrate to calling LLM +* provider APIs directly. +*/ +const CreateMessageRequestParamsSchema = auth_CUe6YdwF_TaskAugmentedRequestParamsSchema.extend({ + messages: schemas_array(SamplingMessageSchema), + modelPreferences: ModelPreferencesSchema.optional(), + systemPrompt: schemas_string().optional(), + includeContext: schemas_enum([ + "none", + "thisServer", + "allServers" + ]).optional(), + temperature: schemas_number().optional(), + maxTokens: schemas_number().int(), + stopSequences: schemas_array(schemas_string()).optional(), + metadata: JSONObjectSchema.optional(), + tools: schemas_array(ToolSchema).optional(), + toolChoice: ToolChoiceSchema.optional() +}); +/** +* A request from the server to sample an LLM via the client. The client has full discretion over which model to select. The client should also inform the user before beginning sampling, to allow them to inspect the request (human in the loop) and decide whether to approve it. +* +* @deprecated Deprecated as of protocol version 2026-07-28 (SEP-2577); remains +* in the specification for at least twelve months. Migrate to calling LLM +* provider APIs directly. +*/ +const CreateMessageRequestSchema = RequestSchema.extend({ + method: literal("sampling/createMessage"), + params: CreateMessageRequestParamsSchema +}); +/** +* The client's response to a `sampling/create_message` request from the server. +* This is the backwards-compatible version that returns single content (no arrays). +* Used when the request does not include tools. +* +* @deprecated Deprecated as of protocol version 2026-07-28 (SEP-2577); remains +* in the specification for at least twelve months. Migrate to calling LLM +* provider APIs directly. +*/ +const CreateMessageResultSchema = ResultSchema.extend({ + model: schemas_string(), + stopReason: schemas_optional(schemas_enum([ + "endTurn", + "stopSequence", + "maxTokens" + ]).or(schemas_string())), + role: RoleSchema, + content: SamplingContentSchema +}); +/** +* The client's response to a `sampling/create_message` request when tools were provided. +* This version supports array content for tool use flows. +* +* @deprecated Deprecated as of protocol version 2026-07-28 (SEP-2577); remains +* in the specification for at least twelve months. Migrate to calling LLM +* provider APIs directly. +*/ +const CreateMessageResultWithToolsSchema = ResultSchema.extend({ + model: schemas_string(), + stopReason: schemas_optional(schemas_enum([ + "endTurn", + "stopSequence", + "maxTokens", + "toolUse" + ]).or(schemas_string())), + role: RoleSchema, + content: schemas_union([SamplingMessageContentBlockSchema, schemas_array(SamplingMessageContentBlockSchema)]) +}); +/** +* Primitive schema definition for boolean fields. +*/ +const BooleanSchemaSchema = schemas_object({ + type: literal("boolean"), + title: schemas_string().optional(), + description: schemas_string().optional(), + default: schemas_boolean().optional() +}); +/** +* Primitive schema definition for string fields. +*/ +const StringSchemaSchema = schemas_object({ + type: literal("string"), + title: schemas_string().optional(), + description: schemas_string().optional(), + minLength: schemas_number().optional(), + maxLength: schemas_number().optional(), + format: schemas_enum([ + "email", + "uri", + "date", + "date-time" + ]).optional(), + default: schemas_string().optional() +}); +/** +* Primitive schema definition for number fields. +*/ +const NumberSchemaSchema = schemas_object({ + type: schemas_enum(["number", "integer"]), + title: schemas_string().optional(), + description: schemas_string().optional(), + minimum: schemas_number().optional(), + maximum: schemas_number().optional(), + default: schemas_number().optional() +}); +/** +* Schema for single-selection enumeration without display titles for options. +*/ +const UntitledSingleSelectEnumSchemaSchema = schemas_object({ + type: literal("string"), + title: schemas_string().optional(), + description: schemas_string().optional(), + enum: schemas_array(schemas_string()), + default: schemas_string().optional() +}); +/** +* Schema for single-selection enumeration with display titles for each option. +*/ +const TitledSingleSelectEnumSchemaSchema = schemas_object({ + type: literal("string"), + title: schemas_string().optional(), + description: schemas_string().optional(), + oneOf: schemas_array(schemas_object({ + const: schemas_string(), + title: schemas_string() + })), + default: schemas_string().optional() +}); +/** +* Use {@linkcode TitledSingleSelectEnumSchema} instead. +* This interface will be removed in a future version. +*/ +const LegacyTitledEnumSchemaSchema = schemas_object({ + type: literal("string"), + title: schemas_string().optional(), + description: schemas_string().optional(), + enum: schemas_array(schemas_string()), + enumNames: schemas_array(schemas_string()).optional(), + default: schemas_string().optional() +}); +const SingleSelectEnumSchemaSchema = schemas_union([UntitledSingleSelectEnumSchemaSchema, TitledSingleSelectEnumSchemaSchema]); +/** +* Schema for multiple-selection enumeration without display titles for options. +*/ +const UntitledMultiSelectEnumSchemaSchema = schemas_object({ + type: literal("array"), + title: schemas_string().optional(), + description: schemas_string().optional(), + minItems: schemas_number().optional(), + maxItems: schemas_number().optional(), + items: schemas_object({ + type: literal("string"), + enum: schemas_array(schemas_string()) + }), + default: schemas_array(schemas_string()).optional() +}); +/** +* Schema for multiple-selection enumeration with display titles for each option. +*/ +const TitledMultiSelectEnumSchemaSchema = schemas_object({ + type: literal("array"), + title: schemas_string().optional(), + description: schemas_string().optional(), + minItems: schemas_number().optional(), + maxItems: schemas_number().optional(), + items: schemas_object({ anyOf: schemas_array(schemas_object({ + const: schemas_string(), + title: schemas_string() + })) }), + default: schemas_array(schemas_string()).optional() +}); +/** +* Combined schema for multiple-selection enumeration +*/ +const MultiSelectEnumSchemaSchema = schemas_union([UntitledMultiSelectEnumSchemaSchema, TitledMultiSelectEnumSchemaSchema]); +/** +* Primitive schema definition for enum fields. +*/ +const EnumSchemaSchema = schemas_union([ + LegacyTitledEnumSchemaSchema, + SingleSelectEnumSchemaSchema, + MultiSelectEnumSchemaSchema +]); +/** +* Union of all primitive schema definitions. +*/ +const PrimitiveSchemaDefinitionSchema = schemas_union([ + EnumSchemaSchema, + BooleanSchemaSchema, + StringSchemaSchema, + NumberSchemaSchema +]); +/** +* Parameters for an `elicitation/create` request for form-based elicitation. +*/ +const ElicitRequestFormParamsSchema = auth_CUe6YdwF_TaskAugmentedRequestParamsSchema.extend({ + mode: literal("form").optional(), + message: schemas_string(), + requestedSchema: schemas_object({ + type: literal("object"), + properties: schemas_record(schemas_string(), PrimitiveSchemaDefinitionSchema), + required: schemas_array(schemas_string()).optional() + }).catchall(unknown()) +}); +/** +* Parameters for an {@linkcode ElicitRequest | elicitation/create} request for URL-based elicitation. +*/ +const ElicitRequestURLParamsSchema = auth_CUe6YdwF_TaskAugmentedRequestParamsSchema.extend({ + mode: literal("url"), + message: schemas_string(), + elicitationId: schemas_string(), + url: schemas_string().url() +}); +/** +* The parameters for a request to elicit additional information from the user via the client. +*/ +const ElicitRequestParamsSchema = schemas_union([ElicitRequestFormParamsSchema, ElicitRequestURLParamsSchema]); +/** +* A request from the server to elicit user input via the client. +* The client should present the message and form fields to the user (form mode) +* or navigate to a URL (URL mode). +*/ +const ElicitRequestSchema = RequestSchema.extend({ + method: literal("elicitation/create"), + params: ElicitRequestParamsSchema +}); +/** +* Parameters for a {@linkcode ElicitationCompleteNotification | notifications/elicitation/complete} notification. +* +* @deprecated Removed from the spec by #2891 (2026-07-28). The client learns the outcome +* of an out-of-band interaction by retrying the original request; no server-initiated +* completion signal exists in the 2026-07-28 revision. Kept here for the 2025-era flow +* only. The 2026-07-28 wire codec excludes this notification. +* @category notifications/elicitation/complete +*/ +const ElicitationCompleteNotificationParamsSchema = NotificationsParamsSchema.extend({ elicitationId: schemas_string() }); +/** +* A notification from the server to the client, informing it of a completion of an out-of-band elicitation request. +* +* @deprecated Removed from the spec by #2891 (2026-07-28). The client learns the outcome +* of an out-of-band interaction by retrying the original request; no server-initiated +* completion signal exists in the 2026-07-28 revision. Kept here for the 2025-era flow +* only. The 2026-07-28 wire codec excludes this notification. +* @category notifications/elicitation/complete +*/ +const ElicitationCompleteNotificationSchema = NotificationSchema.extend({ + method: literal("notifications/elicitation/complete"), + params: ElicitationCompleteNotificationParamsSchema +}); +/** +* The client's response to an {@linkcode ElicitRequest | elicitation/create} request from the server. +*/ +const ElicitResultSchema = ResultSchema.extend({ + action: schemas_enum([ + "accept", + "decline", + "cancel" + ]), + content: preprocess((val) => val === null ? void 0 : val, schemas_record(schemas_string(), schemas_union([ + schemas_string(), + schemas_number(), + schemas_boolean(), + schemas_array(schemas_string()) + ])).optional()) +}); +/** +* A reference to a resource or resource template definition. +*/ +const ResourceTemplateReferenceSchema = schemas_object({ + type: literal("ref/resource"), + uri: schemas_string() +}); +/** +* Identifies a prompt. +*/ +const PromptReferenceSchema = schemas_object({ + type: literal("ref/prompt"), + name: schemas_string() +}); +/** +* Parameters for a {@linkcode CompleteRequest | completion/complete} request. +*/ +const CompleteRequestParamsSchema = BaseRequestParamsSchema.extend({ + ref: schemas_union([PromptReferenceSchema, ResourceTemplateReferenceSchema]), + argument: schemas_object({ + name: schemas_string(), + value: schemas_string() + }), + context: schemas_object({ arguments: schemas_record(schemas_string(), schemas_string()).optional() }).optional() +}); +/** +* A request from the client to the server, to ask for completion options. +*/ +const CompleteRequestSchema = RequestSchema.extend({ + method: literal("completion/complete"), + params: CompleteRequestParamsSchema +}); +/** +* The server's response to a {@linkcode CompleteRequest | completion/complete} request +*/ +const CompleteResultSchema = ResultSchema.extend({ completion: looseObject({ + values: schemas_array(schemas_string()).max(100), + total: schemas_optional(schemas_number().int()), + hasMore: schemas_optional(schemas_boolean()) +}) }); +/** +* Represents a root directory or file that the server can operate on. +* +* @deprecated Deprecated as of protocol version 2026-07-28 (SEP-2577); remains +* in the specification for at least twelve months. Migrate to passing paths via +* tool parameters, resource URIs, or configuration. +*/ +const RootSchema = schemas_object({ + uri: schemas_string().startsWith("file://"), + name: schemas_string().optional(), + _meta: schemas_record(schemas_string(), unknown()).optional() +}); +/** +* Sent from the server to request a list of root URIs from the client. +* +* @deprecated Deprecated as of protocol version 2026-07-28 (SEP-2577); remains +* in the specification for at least twelve months. Migrate to passing paths via +* tool parameters, resource URIs, or configuration. +*/ +const ListRootsRequestSchema = RequestSchema.extend({ + method: literal("roots/list"), + params: BaseRequestParamsSchema.optional() +}); +/** +* The client's response to a `roots/list` request from the server. +* +* @deprecated Deprecated as of protocol version 2026-07-28 (SEP-2577); remains +* in the specification for at least twelve months. Migrate to passing paths via +* tool parameters, resource URIs, or configuration. +*/ +const ListRootsResultSchema = ResultSchema.extend({ roots: schemas_array(RootSchema) }); +/** +* A notification from the client to the server, informing it that the list of roots has changed. +* +* @deprecated Deprecated as of protocol version 2026-07-28 (SEP-2577); remains +* in the specification for at least twelve months. Migrate to passing paths via +* tool parameters, resource URIs, or configuration. +*/ +const RootsListChangedNotificationSchema = NotificationSchema.extend({ + method: literal("notifications/roots/list_changed"), + params: NotificationsParamsSchema.optional() +}); +/** +* Task creation parameters, used to ask that the server create a task to represent a request. +* +* @deprecated 2025-11-25 wire vocabulary with no SDK runtime; kept importable for interoperability only. +*/ +const TaskCreationParamsSchema = looseObject({ + ttl: schemas_number().optional(), + pollInterval: schemas_number().optional() +}); +/** +* The status of a task. +* +* @deprecated 2025-11-25 wire vocabulary with no SDK runtime; kept importable for interoperability only. +*/ +const TaskStatusSchema = schemas_enum([ + "working", + "input_required", + "completed", + "failed", + "cancelled" +]); +/** +* A pollable state object associated with a request. +* +* @deprecated 2025-11-25 wire vocabulary with no SDK runtime; kept importable for interoperability only. +*/ +const TaskSchema = schemas_object({ + taskId: schemas_string(), + status: TaskStatusSchema, + ttl: schemas_union([schemas_number(), schemas_null()]), + createdAt: schemas_string(), + lastUpdatedAt: schemas_string(), + pollInterval: schemas_optional(schemas_number()), + statusMessage: schemas_optional(schemas_string()) +}); +/** +* Result returned when a task is created, containing the task data wrapped in a `task` field. +* +* @deprecated 2025-11-25 wire vocabulary with no SDK runtime; kept importable for interoperability only. +*/ +const CreateTaskResultSchema = ResultSchema.extend({ task: TaskSchema }); +/** +* Parameters for task status notification. +* +* @deprecated 2025-11-25 wire vocabulary with no SDK runtime; kept importable for interoperability only. +*/ +const TaskStatusNotificationParamsSchema = NotificationsParamsSchema.merge(TaskSchema); +/** +* A notification sent when a task's status changes. +* +* @deprecated 2025-11-25 wire vocabulary with no SDK runtime; kept importable for interoperability only. +*/ +const TaskStatusNotificationSchema = NotificationSchema.extend({ + method: literal("notifications/tasks/status"), + params: TaskStatusNotificationParamsSchema +}); +/** +* A request to get the state of a specific task. +* +* @deprecated 2025-11-25 wire vocabulary with no SDK runtime; kept importable for interoperability only. +*/ +const GetTaskRequestSchema = RequestSchema.extend({ + method: literal("tasks/get"), + params: BaseRequestParamsSchema.extend({ taskId: schemas_string() }) +}); +/** +* The response to a {@linkcode GetTaskRequest | tasks/get} request. +* +* @deprecated 2025-11-25 wire vocabulary with no SDK runtime; kept importable for interoperability only. +*/ +const GetTaskResultSchema = ResultSchema.merge(TaskSchema); +/** +* A request to get the result of a specific task. +* +* @deprecated 2025-11-25 wire vocabulary with no SDK runtime; kept importable for interoperability only. +*/ +const GetTaskPayloadRequestSchema = RequestSchema.extend({ + method: literal("tasks/result"), + params: BaseRequestParamsSchema.extend({ taskId: schemas_string() }) +}); +/** +* The response to a `tasks/result` request. +* The structure matches the result type of the original request. +* For example, a {@linkcode CallToolRequest | tools/call} task would return the `CallToolResult` structure. +* +* +* @deprecated 2025-11-25 wire vocabulary with no SDK runtime; kept importable for interoperability only. +*/ +const GetTaskPayloadResultSchema = ResultSchema.loose(); +/** +* A request to list tasks. +* +* @deprecated 2025-11-25 wire vocabulary with no SDK runtime; kept importable for interoperability only. +*/ +const ListTasksRequestSchema = PaginatedRequestSchema.extend({ method: literal("tasks/list") }); +/** +* The response to a {@linkcode ListTasksRequest | tasks/list} request. +* +* @deprecated 2025-11-25 wire vocabulary with no SDK runtime; kept importable for interoperability only. +*/ +const ListTasksResultSchema = PaginatedResultSchema.extend({ tasks: schemas_array(TaskSchema) }); +/** +* A request to cancel a specific task. +* +* @deprecated 2025-11-25 wire vocabulary with no SDK runtime; kept importable for interoperability only. +*/ +const CancelTaskRequestSchema = RequestSchema.extend({ + method: literal("tasks/cancel"), + params: BaseRequestParamsSchema.extend({ taskId: schemas_string() }) +}); +/** +* The response to a {@linkcode CancelTaskRequest | tasks/cancel} request. +* +* @deprecated 2025-11-25 wire vocabulary with no SDK runtime; kept importable for interoperability only. +*/ +const CancelTaskResultSchema = ResultSchema.merge(TaskSchema); +const ClientRequestSchema = schemas_union([ + PingRequestSchema, + auth_CUe6YdwF_InitializeRequestSchema, + DiscoverRequestSchema, + CompleteRequestSchema, + SetLevelRequestSchema, + GetPromptRequestSchema, + ListPromptsRequestSchema, + ListResourcesRequestSchema, + ListResourceTemplatesRequestSchema, + ReadResourceRequestSchema, + SubscribeRequestSchema, + UnsubscribeRequestSchema, + SubscriptionsListenRequestSchema, + CallToolRequestSchema, + ListToolsRequestSchema +]); +const ClientNotificationSchema = schemas_union([ + CancelledNotificationSchema, + ProgressNotificationSchema, + auth_CUe6YdwF_InitializedNotificationSchema, + RootsListChangedNotificationSchema +]); +const ClientResultSchema = schemas_union([ + EmptyResultSchema, + CreateMessageResultSchema, + CreateMessageResultWithToolsSchema, + ElicitResultSchema, + ListRootsResultSchema +]); +const ServerRequestSchema = schemas_union([ + PingRequestSchema, + CreateMessageRequestSchema, + ElicitRequestSchema, + ListRootsRequestSchema +]); +const ServerNotificationSchema = schemas_union([ + CancelledNotificationSchema, + ProgressNotificationSchema, + LoggingMessageNotificationSchema, + ResourceUpdatedNotificationSchema, + ResourceListChangedNotificationSchema, + ToolListChangedNotificationSchema, + PromptListChangedNotificationSchema, + SubscriptionsAcknowledgedNotificationSchema, + ElicitationCompleteNotificationSchema +]); +const ServerResultSchema = schemas_union([ + EmptyResultSchema, + InitializeResultSchema, + DiscoverResultSchema, + CompleteResultSchema, + GetPromptResultSchema, + ListPromptsResultSchema, + ListResourcesResultSchema, + ListResourceTemplatesResultSchema, + ReadResourceResultSchema, + auth_CUe6YdwF_CallToolResultSchema, + ListToolsResultSchema, + SubscriptionsListenResultSchema +]); + +//#endregion +//#region src/auth.ts +/** +* Reusable URL validation that disallows `javascript:` scheme +*/ +const SafeUrlSchema = schemas_url().superRefine((val, ctx) => { + if (!URL.canParse(val)) { + ctx.addIssue({ + code: ZodIssueCode.custom, + message: "URL must be parseable", + fatal: true + }); + return NEVER; + } +}).refine((url) => { + const u = new URL(url); + return u.protocol !== "javascript:" && u.protocol !== "data:" && u.protocol !== "vbscript:"; +}, { message: "URL cannot use javascript:, data:, or vbscript: scheme" }); +/** +* RFC 9728 OAuth Protected Resource Metadata +*/ +const OAuthProtectedResourceMetadataSchema = looseObject({ + resource: schemas_string().url(), + authorization_servers: schemas_array(SafeUrlSchema).optional(), + jwks_uri: schemas_string().url().optional(), + scopes_supported: schemas_array(schemas_string()).optional(), + bearer_methods_supported: schemas_array(schemas_string()).optional(), + resource_signing_alg_values_supported: schemas_array(schemas_string()).optional(), + resource_name: schemas_string().optional(), + resource_documentation: schemas_string().optional(), + resource_policy_uri: schemas_string().url().optional(), + resource_tos_uri: schemas_string().url().optional(), + tls_client_certificate_bound_access_tokens: schemas_boolean().optional(), + authorization_details_types_supported: schemas_array(schemas_string()).optional(), + dpop_signing_alg_values_supported: schemas_array(schemas_string()).optional(), + dpop_bound_access_tokens_required: schemas_boolean().optional() +}); +/** +* RFC 8414 OAuth 2.0 Authorization Server Metadata +*/ +const OAuthMetadataSchema = looseObject({ + issuer: schemas_string(), + authorization_endpoint: SafeUrlSchema, + token_endpoint: SafeUrlSchema, + registration_endpoint: SafeUrlSchema.optional(), + scopes_supported: schemas_array(schemas_string()).optional(), + response_types_supported: schemas_array(schemas_string()), + response_modes_supported: schemas_array(schemas_string()).optional(), + grant_types_supported: schemas_array(schemas_string()).optional(), + token_endpoint_auth_methods_supported: schemas_array(schemas_string()).optional(), + token_endpoint_auth_signing_alg_values_supported: schemas_array(schemas_string()).optional(), + service_documentation: SafeUrlSchema.optional(), + revocation_endpoint: SafeUrlSchema.optional(), + revocation_endpoint_auth_methods_supported: schemas_array(schemas_string()).optional(), + revocation_endpoint_auth_signing_alg_values_supported: schemas_array(schemas_string()).optional(), + introspection_endpoint: schemas_string().optional(), + introspection_endpoint_auth_methods_supported: schemas_array(schemas_string()).optional(), + introspection_endpoint_auth_signing_alg_values_supported: schemas_array(schemas_string()).optional(), + code_challenge_methods_supported: schemas_array(schemas_string()).optional(), + client_id_metadata_document_supported: schemas_boolean().optional(), + authorization_response_iss_parameter_supported: schemas_boolean().optional().catch(void 0) +}); +/** +* OpenID Connect Discovery 1.0 Provider Metadata +* +* @see https://openid.net/specs/openid-connect-discovery-1_0.html#ProviderMetadata +*/ +const OpenIdProviderMetadataSchema = looseObject({ + issuer: schemas_string(), + authorization_endpoint: SafeUrlSchema, + token_endpoint: SafeUrlSchema, + userinfo_endpoint: SafeUrlSchema.optional(), + jwks_uri: SafeUrlSchema, + registration_endpoint: SafeUrlSchema.optional(), + scopes_supported: schemas_array(schemas_string()).optional(), + response_types_supported: schemas_array(schemas_string()), + response_modes_supported: schemas_array(schemas_string()).optional(), + grant_types_supported: schemas_array(schemas_string()).optional(), + acr_values_supported: schemas_array(schemas_string()).optional(), + subject_types_supported: schemas_array(schemas_string()), + id_token_signing_alg_values_supported: schemas_array(schemas_string()), + id_token_encryption_alg_values_supported: schemas_array(schemas_string()).optional(), + id_token_encryption_enc_values_supported: schemas_array(schemas_string()).optional(), + userinfo_signing_alg_values_supported: schemas_array(schemas_string()).optional(), + userinfo_encryption_alg_values_supported: schemas_array(schemas_string()).optional(), + userinfo_encryption_enc_values_supported: schemas_array(schemas_string()).optional(), + request_object_signing_alg_values_supported: schemas_array(schemas_string()).optional(), + request_object_encryption_alg_values_supported: schemas_array(schemas_string()).optional(), + request_object_encryption_enc_values_supported: schemas_array(schemas_string()).optional(), + token_endpoint_auth_methods_supported: schemas_array(schemas_string()).optional(), + token_endpoint_auth_signing_alg_values_supported: schemas_array(schemas_string()).optional(), + display_values_supported: schemas_array(schemas_string()).optional(), + claim_types_supported: schemas_array(schemas_string()).optional(), + claims_supported: schemas_array(schemas_string()).optional(), + service_documentation: schemas_string().optional(), + claims_locales_supported: schemas_array(schemas_string()).optional(), + ui_locales_supported: schemas_array(schemas_string()).optional(), + claims_parameter_supported: schemas_boolean().optional(), + request_parameter_supported: schemas_boolean().optional(), + request_uri_parameter_supported: schemas_boolean().optional(), + require_request_uri_registration: schemas_boolean().optional(), + op_policy_uri: SafeUrlSchema.optional(), + op_tos_uri: SafeUrlSchema.optional(), + client_id_metadata_document_supported: schemas_boolean().optional(), + authorization_response_iss_parameter_supported: schemas_boolean().optional().catch(void 0) +}); +/** +* OpenID Connect Discovery metadata that may include OAuth 2.0 fields +* This schema represents the real-world scenario where OIDC providers +* return a mix of OpenID Connect and OAuth 2.0 metadata fields +*/ +const OpenIdProviderDiscoveryMetadataSchema = schemas_object({ + ...OpenIdProviderMetadataSchema.shape, + ...OAuthMetadataSchema.pick({ code_challenge_methods_supported: true }).shape +}); +/** +* OAuth 2.1 token response +*/ +const OAuthTokensSchema = schemas_object({ + access_token: schemas_string(), + id_token: schemas_string().optional(), + token_type: schemas_string(), + expires_in: coerce_number().optional(), + scope: schemas_string().optional(), + refresh_token: schemas_string().optional() +}).strip(); +/** +* RFC 8693 §2.2.1 Token Exchange response for ID-JAG tokens. +* +* `token_type` is intentionally optional: per RFC 8693 §2.2.1 it is informational when +* the issued token is not an access token, and per RFC 6749 §5.1 it is case-insensitive, +* so strict checking rejects conformant IdPs. +*/ +const IdJagTokenExchangeResponseSchema = schemas_object({ + issued_token_type: literal("urn:ietf:params:oauth:token-type:id-jag"), + access_token: schemas_string(), + token_type: schemas_string().optional(), + expires_in: schemas_number().optional(), + scope: schemas_string().optional() +}).strip(); +/** +* OAuth 2.1 error response +*/ +const OAuthErrorResponseSchema = schemas_object({ + error: schemas_string(), + error_description: schemas_string().optional(), + error_uri: schemas_string().optional() +}); +/** +* Optional version of {@linkcode SafeUrlSchema} that allows empty string for backward compatibility on `tos_uri` and `logo_uri` +*/ +const OptionalSafeUrlSchema = SafeUrlSchema.optional().or(literal("").transform(() => void 0)); +/** +* RFC 7591 OAuth 2.0 Dynamic Client Registration metadata +*/ +const OAuthClientMetadataSchema = schemas_object({ + redirect_uris: schemas_array(SafeUrlSchema), + token_endpoint_auth_method: schemas_string().optional(), + grant_types: schemas_array(schemas_string()).optional(), + response_types: schemas_array(schemas_string()).optional(), + application_type: schemas_string().optional(), + client_name: schemas_string().optional(), + client_uri: SafeUrlSchema.optional(), + logo_uri: OptionalSafeUrlSchema, + scope: schemas_string().optional(), + contacts: schemas_array(schemas_string()).optional(), + tos_uri: OptionalSafeUrlSchema, + policy_uri: schemas_string().optional(), + jwks_uri: SafeUrlSchema.optional(), + jwks: any().optional(), + software_id: schemas_string().optional(), + software_version: schemas_string().optional(), + software_statement: schemas_string().optional() +}).strip(); +/** +* RFC 7591 OAuth 2.0 Dynamic Client Registration client information +*/ +const OAuthClientInformationSchema = schemas_object({ + client_id: schemas_string(), + client_secret: schemas_string().optional(), + client_id_issued_at: schemas_number().optional(), + client_secret_expires_at: schemas_number().optional() +}).strip(); +/** +* RFC 7591 OAuth 2.0 Dynamic Client Registration full response (client information plus metadata) +*/ +const OAuthClientInformationFullSchema = OAuthClientMetadataSchema.merge(OAuthClientInformationSchema); +/** +* RFC 7591 OAuth 2.0 Dynamic Client Registration error response +*/ +const OAuthClientRegistrationErrorSchema = schemas_object({ + error: schemas_string(), + error_description: schemas_string().optional() +}).strip(); +/** +* RFC 7009 OAuth 2.0 Token Revocation request +*/ +const OAuthTokenRevocationRequestSchema = schemas_object({ + token: schemas_string(), + token_type_hint: schemas_string().optional() +}).strip(); + +//#endregion + +//# sourceMappingURL=auth-CUe6YdwF.mjs.map + + + + + + + + +//#region ../core-internal/src/errors/crossBundleBrand.ts +/** +* Cross-bundle `instanceof` support for the SDK error classes. +* +* `@modelcontextprotocol/client` and `@modelcontextprotocol/server` each bundle their +* own copy of `core-internal`, so an error constructed by one package fails a +* prototype-identity `instanceof` against the same class re-exported by the other — +* exactly the check a dual-role process (gateway, host, in-process test) writes. +* +* Instead of prototype identity, branded classes stamp every instance with the brand +* strings of its class chain under a registry symbol (`Symbol.for`, shared across +* bundles and realms), and resolve `instanceof` via `Symbol.hasInstance` against the +* brand set. Ordinary prototype-based `instanceof` is kept as a fallback so behavior +* is unchanged for anything unbranded. +* +* A class participates by defining an **own** `mcpBrand` static (via a `static {}` +* block, so nothing reaches the declaration files — a declared `protected static` +* field would make the constructor types nominally incompatible across the bundled +* copies) and (for hierarchy roots) installing {@linkcode brandedHasInstance} as +* `Symbol.hasInstance`. User-defined subclasses that do not declare their own brand +* keep plain prototype semantics — a foreign base-class instance never satisfies +* `instanceof UserSubclass`. +* +* Prior art — the same stamp-and-hook shape ships at scale elsewhere: Node core +* (stream.Writable since 2017, Console via a marker symbol, diagnostics_channel), +* undici's whole error hierarchy (vendored into Node as fetch), googleapis/gaxios +* (GaxiosError, Symbol.for marker), AWS SDK v3's ServiceException (which pairs a +* Symbol.hasInstance override with a static isInstance guard, as we do), and zod v4 +* (Symbol.hasInstance on every schema class for cross-version interop). +* +* Contract notes: +* - Participation criterion: **every error class exported from a public package that +* callers are documented to `instanceof` must be branded.** The per-package +* errorBrandConformance tests walk the export surfaces and fail naming any +* exported Error subclass that has not opted in. +* - Brands assert **identity, not shape**: brand strings are version-less, so an +* instance from one SDK version matches the class of another. Members added to a +* branded class in a later version may be absent on a matched instance — read +* fields defensively, and treat branded classes as additive-only. The escape +* hatch when a release must break a branded class's read contract: change that +* class's brand string in the same release, which cleanly severs cross-version +* matching for that class. The per-package brand pins make the rename +* deliberate: errorSurfacePins.test.ts owns the core-internal brands, and each +* package's errorBrandConformance test pins its package-local ones. +* - Cross-bundle matching requires **both** copies to be at or after the release +* that introduced branding; against an older copy, behavior degrades to plain +* prototype `instanceof` in both directions. +* - A consumer re-bundling the SDK with property mangling (`mangle.props`) would +* break the brand statics; default esbuild/webpack/terser settings do not. +*/ +/** Registry symbol — identical across bundled copies and realms. */ +const BRANDS = Symbol.for("mcp.sdk.errorBrands"); +/** +* Stamp `instance` with the brand of every class in `ctor`'s chain that declares an +* own `mcpBrand`. Call once from the hierarchy root's constructor with `new.target` — +* subclasses inherit the stamping without touching their constructors. +* +* Constructor-time only: never stamp arbitrary objects. A stamped non-instance would +* satisfy `instanceof` while lacking the prototype members (getters like `.status`) +* that callers reach for after the check. +*/ +function stampErrorBrands(instance, ctor) { + const brands = /* @__PURE__ */ new Set(); + let current = ctor; + while (typeof current === "function") { + const brand = current.mcpBrand; + if (Object.prototype.hasOwnProperty.call(current, "mcpBrand") && typeof brand === "string") brands.add(brand); + current = Object.getPrototypeOf(current); + } + if (brands.size === 0) return; + Object.defineProperty(instance, BRANDS, { + value: brands, + enumerable: false, + configurable: true + }); +} +/** +* `Symbol.hasInstance` implementation for branded hierarchy roots. Matches when the +* value carries the **own** brand of the class being tested against (cross-bundle +* path), falling back to ordinary prototype-based `instanceof` otherwise. +*/ +function brandedHasInstance(cls, value) { + try { + if (typeof value === "object" && value !== null && Object.prototype.hasOwnProperty.call(cls, "mcpBrand") && typeof cls.mcpBrand === "string" && Object.prototype.hasOwnProperty.call(value, BRANDS)) { + const carried = value[BRANDS]; + if (carried && typeof carried.has === "function" && carried.has(cls.mcpBrand)) return true; + } + } catch {} + return Function.prototype[Symbol.hasInstance].call(cls, value); +} + +//#endregion +//#region ../core-internal/src/auth/errors.ts +/** +* OAuth error codes as defined by {@link https://datatracker.ietf.org/doc/html/rfc6749#section-5.2 | RFC 6749} +* and extensions. +*/ +let src_CX2iR2pK_OAuthErrorCode = /* @__PURE__ */ (/* unused pure expression or super */ null && (function(OAuthErrorCode$1) { + /** + * The request is missing a required parameter, includes an invalid parameter value, + * includes a parameter more than once, or is otherwise malformed. + */ + OAuthErrorCode$1["InvalidRequest"] = "invalid_request"; + /** + * Client authentication failed (e.g., unknown client, no client authentication included, + * or unsupported authentication method). + */ + OAuthErrorCode$1["InvalidClient"] = "invalid_client"; + /** + * The provided authorization grant or refresh token is invalid, expired, revoked, + * does not match the redirection URI used in the authorization request, or was issued to another client. + */ + OAuthErrorCode$1["InvalidGrant"] = "invalid_grant"; + /** + * The authenticated client is not authorized to use this authorization grant type. + */ + OAuthErrorCode$1["UnauthorizedClient"] = "unauthorized_client"; + /** + * The authorization grant type is not supported by the authorization server. + */ + OAuthErrorCode$1["UnsupportedGrantType"] = "unsupported_grant_type"; + /** + * The requested scope is invalid, unknown, malformed, or exceeds the scope granted by the resource owner. + */ + OAuthErrorCode$1["InvalidScope"] = "invalid_scope"; + /** + * The resource owner or authorization server denied the request. + */ + OAuthErrorCode$1["AccessDenied"] = "access_denied"; + /** + * The authorization server encountered an unexpected condition that prevented it from fulfilling the request. + */ + OAuthErrorCode$1["ServerError"] = "server_error"; + /** + * The authorization server is currently unable to handle the request due to temporary overloading or maintenance. + */ + OAuthErrorCode$1["TemporarilyUnavailable"] = "temporarily_unavailable"; + /** + * The authorization server does not support obtaining an authorization code using this method. + */ + OAuthErrorCode$1["UnsupportedResponseType"] = "unsupported_response_type"; + /** + * The authorization server does not support the requested token type. + */ + OAuthErrorCode$1["UnsupportedTokenType"] = "unsupported_token_type"; + /** + * The access token provided is expired, revoked, malformed, or invalid for other reasons. + */ + OAuthErrorCode$1["InvalidToken"] = "invalid_token"; + /** + * The HTTP method used is not allowed for this endpoint. (Custom, non-standard error) + */ + OAuthErrorCode$1["MethodNotAllowed"] = "method_not_allowed"; + /** + * Rate limit exceeded. (Custom, non-standard error based on RFC 6585) + */ + OAuthErrorCode$1["TooManyRequests"] = "too_many_requests"; + /** + * The client metadata is invalid. (Custom error for dynamic client registration - RFC 7591) + */ + OAuthErrorCode$1["InvalidClientMetadata"] = "invalid_client_metadata"; + /** + * The value of one or more redirection URIs is invalid. (Dynamic client registration - RFC 7591 §3.2.2) + */ + OAuthErrorCode$1["InvalidRedirectUri"] = "invalid_redirect_uri"; + /** + * The request requires higher privileges than provided by the access token. + */ + OAuthErrorCode$1["InsufficientScope"] = "insufficient_scope"; + /** + * The requested resource is invalid, missing, unknown, or malformed. (Custom error for resource indicators - RFC 8707) + */ + OAuthErrorCode$1["InvalidTarget"] = "invalid_target"; + return OAuthErrorCode$1; +}({}))); +/** +* OAuth error class for all OAuth-related errors. +*/ +var src_CX2iR2pK_OAuthError = class OAuthError extends Error { + static { + Object.defineProperty(this, "mcpBrand", { value: "mcp.OAuthError" }); + } + static [Symbol.hasInstance](value) { + return brandedHasInstance(this, value); + } + /** + * Brand-based type guard: equivalent to `value instanceof this`, as an + * explicit static predicate (the axios/AWS-SDK `isInstance` style). Reads + * the caller's own brand via `this`, so every branded subclass gets a + * correctly-scoped guard by inheritance. Must be invoked on the class — + * in callback position write `v => SdkError.isInstance(v)`, not + * `.filter(SdkError.isInstance)` (detached calls throw rather than + * silently matching nothing). + */ + static isInstance(value) { + 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 brandedHasInstance(this, value); + } + constructor(code, message, errorUri) { + super(message); + this.code = code; + this.errorUri = errorUri; + this.name = "OAuthError"; + stampErrorBrands(this, new.target); + } + /** + * Converts the error to a standard OAuth error response object. + */ + toResponseObject() { + const response = { + error: this.code, + error_description: this.message + }; + if (this.errorUri) response.error_uri = this.errorUri; + return response; + } + /** + * Creates an {@linkcode OAuthError} from an OAuth error response. + */ + static fromResponse(response) { + return new OAuthError(response.error, response.error_description ?? response.error, response.error_uri); + } +}; + +//#endregion +//#region ../core-internal/src/errors/sdkErrors.ts +/** +* Error codes for SDK errors (local errors that never cross the wire). +* Unlike {@linkcode ProtocolErrorCode} which uses numeric JSON-RPC codes, `SdkErrorCode` uses +* descriptive string values for better developer experience. +* +* These errors are thrown locally by the SDK and are never serialized as +* JSON-RPC error responses. +*/ +let src_CX2iR2pK_SdkErrorCode = /* @__PURE__ */ function(SdkErrorCode$1) { + /** Transport is not connected */ + SdkErrorCode$1["NotConnected"] = "NOT_CONNECTED"; + /** Transport is already connected */ + SdkErrorCode$1["AlreadyConnected"] = "ALREADY_CONNECTED"; + /** Protocol is not initialized */ + SdkErrorCode$1["NotInitialized"] = "NOT_INITIALIZED"; + /** Required capability is not supported by the remote side */ + SdkErrorCode$1["CapabilityNotSupported"] = "CAPABILITY_NOT_SUPPORTED"; + /** Request timed out waiting for response */ + SdkErrorCode$1["RequestTimeout"] = "REQUEST_TIMEOUT"; + /** Connection was closed */ + SdkErrorCode$1["ConnectionClosed"] = "CONNECTION_CLOSED"; + /** Failed to send message */ + SdkErrorCode$1["SendFailed"] = "SEND_FAILED"; + /** Response result failed local schema validation */ + SdkErrorCode$1["InvalidResult"] = "INVALID_RESULT"; + /** + * The response carried a `resultType` discriminator (protocol revision + * 2026-07-28) naming a result kind this client cannot consume yet, e.g. + * `input_required`. The kind is carried in `data.resultType`. + */ + SdkErrorCode$1["UnsupportedResultType"] = "UNSUPPORTED_RESULT_TYPE"; + /** + * The multi-round-trip auto-fulfilment driver exhausted its round cap + * (`inputRequired.maxRounds`) without the server returning a complete + * result. `data.rounds` carries the cap that was hit and + * `data.lastResult` carries the last `input_required` payload received + * (`{ inputRequests, requestState? }`), so callers can inspect or resume + * the flow manually. + */ + SdkErrorCode$1["InputRequiredRoundsExceeded"] = "INPUT_REQUIRED_ROUNDS_EXCEEDED"; + /** + * The auto-aggregating no-`cursor` `listTools()` / `listPrompts()` / + * `listResources()` / `listResourceTemplates()` walk hit the + * `ClientOptions.listMaxPages` cap without the server's pagination + * converging. `data.method` carries the list verb and + * `data.listMaxPages` the cap that was hit; raise the cap or fall back to + * explicit per-page `{ cursor }` calls. + */ + SdkErrorCode$1["ListPaginationExceeded"] = "LIST_PAGINATION_EXCEEDED"; + /** + * The spec method being sent does not exist on the negotiated protocol + * version's wire era (e.g. `tasks/get` toward a 2026-07-28 peer, or + * `server/discover` toward a 2025-era peer). Raised locally, before + * anything reaches the transport. The method and era are carried in + * `data.method` / `data.era`. + */ + SdkErrorCode$1["MethodNotSupportedByProtocolVersion"] = "METHOD_NOT_SUPPORTED_BY_PROTOCOL_VERSION"; + /** + * Protocol-era negotiation at connect time failed without producing either a + * usable modern (2026-07-28+) era or a definitive legacy fallback signal — + * e.g. the negotiation mode forbids falling back (`pin`), the probe hit a + * network failure, or the server answered the probe with a 5xx (a typed + * connect error, never an era verdict). + * + * Negotiation-phase only: this code is never used once an era is + * established. Auth walls never carry it: a 401/403 rejecting the probe + * uses {@linkcode ClientHttpAuthentication} / {@linkcode ClientHttpForbidden} + * instead, so era-recovery flows keyed on this code (e.g. cached-verdict + * gateways) can never persist a verdict for an unauthorized exchange. + */ + SdkErrorCode$1["EraNegotiationFailed"] = "ERA_NEGOTIATION_FAILED"; + SdkErrorCode$1["ClientHttpNotImplemented"] = "CLIENT_HTTP_NOT_IMPLEMENTED"; + /** + * HTTP 401 authentication failure: the transport's re-auth retry still got + * 401 (`Server returned 401 after re-authentication`), or the version + * negotiation probe was rejected 401 with no `authProvider` configured + * (`Version negotiation failed: the server requires authorization (HTTP 401)`). + * Carried on an {@linkcode SdkHttpError} with `status: 401`. + */ + SdkErrorCode$1["ClientHttpAuthentication"] = "CLIENT_HTTP_AUTHENTICATION"; + /** + * HTTP 403 denial: the step-up re-authorization retry limit was reached, + * or the version negotiation probe was rejected 403 + * (`Version negotiation failed: the server denied access (HTTP 403)`). + * Carried on an {@linkcode SdkHttpError} with `status: 403`. + */ + SdkErrorCode$1["ClientHttpForbidden"] = "CLIENT_HTTP_FORBIDDEN"; + SdkErrorCode$1["ClientHttpUnexpectedContent"] = "CLIENT_HTTP_UNEXPECTED_CONTENT"; + SdkErrorCode$1["ClientHttpFailedToOpenStream"] = "CLIENT_HTTP_FAILED_TO_OPEN_STREAM"; + SdkErrorCode$1["ClientHttpFailedToTerminateSession"] = "CLIENT_HTTP_FAILED_TO_TERMINATE_SESSION"; + return SdkErrorCode$1; +}({}); +/** +* SDK errors are local errors that never cross the wire. +* They are distinct from {@linkcode ProtocolError} which represents JSON-RPC protocol errors +* that are serialized and sent as error responses. +* +* @example +* ```ts source="./sdkErrors.examples.ts#SdkError_basicUsage" +* try { +* // Throwing an SDK error +* throw new SdkError(SdkErrorCode.NotConnected, 'Transport is not connected'); +* } catch (error) { +* // Checking error type by code +* if (error instanceof SdkError && error.code === SdkErrorCode.RequestTimeout) { +* // Handle timeout +* } +* } +* ``` +*/ +var src_CX2iR2pK_SdkError = class extends Error { + static { + Object.defineProperty(this, "mcpBrand", { value: "mcp.SdkError" }); + } + static [Symbol.hasInstance](value) { + return brandedHasInstance(this, value); + } + /** + * Brand-based type guard: equivalent to `value instanceof this`, as an + * explicit static predicate (the axios/AWS-SDK `isInstance` style). Reads + * the caller's own brand via `this`, so every branded subclass gets a + * correctly-scoped guard by inheritance. Must be invoked on the class — + * in callback position write `v => SdkError.isInstance(v)`, not + * `.filter(SdkError.isInstance)` (detached calls throw rather than + * silently matching nothing). + */ + static isInstance(value) { + 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 brandedHasInstance(this, value); + } + constructor(code, message, data) { + super(message); + this.code = code; + this.data = data; + this.name = "SdkError"; + stampErrorBrands(this, new.target); + } +}; +/** +* An {@linkcode SdkError} subclass for HTTP transport failures. +* +* Thrown by the streamable HTTP transport when the server responds with a +* non-OK status code. Narrows {@linkcode SdkError.data | data} to +* {@linkcode SdkHttpErrorData} so consumers can inspect the HTTP status +* without unsafe casting. +* +* @example +* ```ts source="./sdkErrors.examples.ts#SdkHttpError_basicUsage" +* if (error instanceof SdkHttpError) { +* console.log(error.status); // number +* console.log(error.statusText); // string | undefined +* } +* ``` +*/ +var SdkHttpError = class extends src_CX2iR2pK_SdkError { + static { + Object.defineProperty(this, "mcpBrand", { value: "mcp.SdkHttpError" }); + } + constructor(code, message, data) { + super(code, message, data); + this.name = "SdkHttpError"; + } + get status() { + return this.data.status; + } + get statusText() { + return this.data.statusText; + } +}; + +//#endregion +//#region ../core-internal/src/shared/authUtils.ts +/** +* Utilities for handling OAuth resource URIs. +*/ +/** +* Converts a server URL to a resource URL by removing the fragment. +* {@link https://datatracker.ietf.org/doc/html/rfc8707#section-2 | RFC 8707 section 2} +* states that resource URIs "MUST NOT include a fragment component". +* Keeps everything else unchanged (scheme, domain, port, path, query). +*/ +function resourceUrlFromServerUrl(url) { + const resourceURL = typeof url === "string" ? new URL(url) : new URL(url.href); + resourceURL.hash = ""; + return resourceURL; +} +/** +* Checks if a requested resource URL matches a configured resource URL. +* A requested resource matches if it has the same scheme, domain, port, +* and its path starts with the configured resource's path. +* +* @param options - The options object +* @param options.requestedResource - The resource URL being requested +* @param options.configuredResource - The resource URL that has been configured +* @returns true if the requested resource matches the configured resource, false otherwise +*/ +function checkResourceAllowed({ requestedResource, configuredResource }) { + const requested = typeof requestedResource === "string" ? new URL(requestedResource) : new URL(requestedResource.href); + const configured = typeof configuredResource === "string" ? new URL(configuredResource) : new URL(configuredResource.href); + if (requested.origin !== configured.origin) return false; + if (requested.pathname.length < configured.pathname.length) return false; + const requestedPath = requested.pathname.endsWith("/") ? requested.pathname : requested.pathname + "/"; + const configuredPath = configured.pathname.endsWith("/") ? configured.pathname : configured.pathname + "/"; + return requestedPath.startsWith(configuredPath); +} + +//#endregion +//#region ../core-internal/src/shared/clientCapabilityRequirements.ts +/** +* Inbound request methods whose processing structurally requires a client +* capability, keyed by method, valued by the capabilities required. +* +* Currently empty: none of the request methods served on the 2026-07-28 +* registry unconditionally requires a client capability. Entries appear here +* when such methods exist — for example requests whose handling embeds +* elicitation or sampling input requests (the input-request engine), or +* opt-in subscription delivery. Handler-conditional requirements (a specific +* tool that needs sampling) are not expressible as a static method table and +* are enforced at the point the requirement arises instead. +*/ +const REQUIRED_CLIENT_CAPABILITIES_BY_METHOD = (/* unused pure expression or super */ null && ({})); +/** +* The client capabilities a request method structurally requires, or +* `undefined` when the method has no static requirement. +*/ +function src_CX2iR2pK_requiredClientCapabilitiesForRequest(method) { + return Object.hasOwn(REQUIRED_CLIENT_CAPABILITIES_BY_METHOD, method) ? REQUIRED_CLIENT_CAPABILITIES_BY_METHOD[method] : void 0; +} +function isPlainObject$7(value) { + return value !== null && typeof value === "object" && !Array.isArray(value); +} +/** +* Whether a required nested member counts as declared even though it is not +* spelled out: a bare `elicitation: {}` declaration (no mode sub-capability at +* all) is read as form support — the pre-mode (2025) meaning of a bare +* declaration — so an `elicitation.form` requirement treats it as satisfied. +* Declaring any mode explicitly (for example `elicitation: { url: {} }`) +* removes the implication. +*/ +function isImpliedCapabilityMember(capability, member, declaredValue) { + return capability === "elicitation" && member === "form" && declaredValue["form"] === void 0 && declaredValue["url"] === void 0; +} +/** +* The client capabilities an embedded multi-round-trip input request requires +* (call site 2 — the outbound input-request leg): a server MUST NOT send an +* `inputRequests` kind the request's declared client capabilities do not +* cover. Returns `undefined` for entries whose method is not one of the +* embedded input-request kinds (those are a server bug handled separately, +* not a capability question). +* +* The requirement is mode-aware where the capability is: URL-mode elicitation +* requires `elicitation.url`; form-mode (or mode-omitted) elicitation requires +* `elicitation.form` (modes are sub-capabilities, and a server MUST NOT send a +* mode the client did not declare); sampling with `tools`/`toolChoice` +* requires `sampling.tools`. A bare `elicitation: {}` declaration satisfies +* the form requirement — see {@linkcode missingClientCapabilities}. +*/ +function requiredClientCapabilitiesForInputRequest(entry) { + switch (entry.method) { + case "elicitation/create": + if (entry.params?.["mode"] === "url") return { elicitation: { url: {} } }; + return { elicitation: { form: {} } }; + case "sampling/createMessage": { + const params = entry.params; + if (params !== void 0 && (params["tools"] !== void 0 || params["toolChoice"] !== void 0)) return { sampling: { tools: {} } }; + return { sampling: {} }; + } + case "roots/list": return { roots: {} }; + default: return; + } +} +/** +* Computes the subset of `required` client capabilities the client did not +* declare. Returns `undefined` when every required capability is declared; +* otherwise returns an object in the `ClientCapabilities` shape containing +* exactly the missing capabilities (suitable for +* `data.requiredCapabilities` on the `-32021` error). +* +* A capability counts as declared when its top-level key is present on the +* declared capabilities; when the requirement names nested members (for +* example `elicitation: { url: {} }`), each named member must also be present +* under the declared capability. One lenient reading applies: a bare +* `elicitation: {}` declaration (no mode sub-capability at all) counts as +* declaring `elicitation.form` — the pre-mode (2025) meaning of a bare +* declaration. An absent or empty `declared` value means +* nothing is declared — every required capability is missing (the structural +* clean-refusal posture for sessions with no per-request capability view). +*/ +function src_CX2iR2pK_missingClientCapabilities(required, declared) { + const missing = {}; + for (const [capability, requirement] of Object.entries(required)) { + if (requirement === void 0) continue; + const declaredValue = declared === void 0 ? void 0 : declared[capability]; + if (declaredValue === void 0) { + missing[capability] = requirement; + continue; + } + if (isPlainObject$7(requirement) && isPlainObject$7(declaredValue)) { + const missingMembers = {}; + for (const [member, memberRequirement] of Object.entries(requirement)) if (memberRequirement !== void 0 && declaredValue[member] === void 0 && !isImpliedCapabilityMember(capability, member, declaredValue)) missingMembers[member] = memberRequirement; + if (Object.keys(missingMembers).length > 0) missing[capability] = missingMembers; + } + } + return Object.keys(missing).length > 0 ? missing : void 0; +} + +//#endregion +//#region ../core-internal/src/shared/protocolEras.ts +/** +* The first protocol revision of the modern (2026-07-28) era. Revision identifiers +* are ISO dates, so lexicographic comparison orders them chronologically. +*/ +const FIRST_MODERN_PROTOCOL_VERSION = "2026-07-28"; +/** +* Modern-era protocol revisions this SDK can negotiate via `server/discover`. +* Deliberately separate from {@linkcode SUPPORTED_PROTOCOL_VERSIONS} (the legacy +* `initialize` list), so adding a revision here can never leak a modern version +* string into a 2025-era handshake. Internal — not part of the public API surface. +*/ +const src_CX2iR2pK_SUPPORTED_MODERN_PROTOCOL_VERSIONS = (/* unused pure expression or super */ null && ([FIRST_MODERN_PROTOCOL_VERSION])); +/** Whether the given protocol revision belongs to the modern (2026-07-28+) era. */ +function isModernProtocolVersion(version) { + return version >= FIRST_MODERN_PROTOCOL_VERSION; +} +/** The legacy-era (pre-2026-07-28) subset of a supported-versions list, in the list's own preference order. */ +function legacyProtocolVersions(versions) { + return versions.filter((version) => !isModernProtocolVersion(version)); +} +/** The modern-era (2026-07-28+) subset of a supported-versions list, in the list's own preference order. */ +function modernProtocolVersions(versions) { + return versions.filter((version) => isModernProtocolVersion(version)); +} + +//#endregion +//#region ../core-internal/src/wire/textFallback.ts +/** +* SEP-2106 §4.3 TextContent auto-append, era-agnostic, called from BOTH +* codecs' {@link WireCodec.projectCallToolResult}: when `structuredContent` +* is a non-object value (array/primitive/`null`) and the handler authored no +* `type:'text'` block, append `{type:'text', text: JSON.stringify(value)}`. +* Object-shaped (or absent) `structuredContent` returns the same reference. +* +* Leaf module: imported by both era codec modules, so it must NOT import from +* `./codec.js` (which value-imports the rev codecs at top level — that would +* make a runtime cycle and a TDZ hazard for entries that evaluate a rev codec +* module first). +*/ +function appendTextFallbackForNonObject(result) { + const sc = result.structuredContent; + if (sc === void 0) return result; + if (!(typeof sc !== "object" || sc === null || Array.isArray(sc))) return result; + if (result.content?.some((c) => c.type === "text") ?? false) return result; + return { + ...result, + content: [...result.content ?? [], { + type: "text", + text: JSON.stringify(sc) + }] + }; +} + +//#endregion +//#region ../core-internal/src/wire/resultFamilies.ts +/** +* Result-family keys that must never default into a `{content: []}` tools/call +* success. Shared by the 2025 wire-seam schema and server normalization. +* Leaf module (like `textFallback.ts`): imported by registry/server paths, so +* it must NOT import from `./codec.js` — that would close a runtime cycle. +*/ +const TOOL_RESULT_FOREIGN_FAMILY_KEYS = [ + "task", + "inputRequests", + "requestState" +]; +/** +* Single owner of the v1-parity ruling: a plain-object tool result without `content` (and +* without foreign-family keys) gains `content: []`. Shared by the 2025 wire seam and server-side handler normalization. +*/ +function normalizeContentlessToolResult(value) { + if (value === null || typeof value !== "object" || Array.isArray(value) || value.content !== void 0 || TOOL_RESULT_FOREIGN_FAMILY_KEYS.some((key) => key in value)) return value; + return { + ...value, + content: [] + }; +} + +//#endregion +//#region ../core-internal/src/wire/rev2025-11-25/buildSchemas.ts +/** +* Complete frozen 2025-11-25 wire schemas. Self-contained — no imports from +* the public/neutral types/schemas.ts. The neutral layer is the public-API +* superset and is free to evolve (e.g., SEP-2106 widening); this file is the +* 2025 wire-parse contract (Q10-L2 byte-identity) and is BEHAVIOR-FROZEN. +* +* This is the era's complete frozen wire-parse contract — both the 2025-only +* delta (the deprecated task family, the era role unions) AND frozen copies of +* every era-shared shape (Tool, CallToolResult, Initialize*, ContentBlock, +* prompts/resources/completion/elicitation, …). The 2026-era codec +* (`wire/rev2026-07-28/`) is symmetrically self-contained in the same way. +* +* The 2025-only delta (the task message surface, restored types-only by #2248 +* for interop with task-capable 2025 peers) is parsed ONLY through this era's +* registry; the deprecated Task* schemas also live (marked `@deprecated`) in +* the neutral schema layer so the public types stay nameable without a +* cross-layer import — nameability is constant, runtime availability is +* version-keyed — but appear in no API signature. Q1 increment 2 — deletions +* are physical: the +* 2026-era REGISTRY has no Task* methods (its frozen building-block copies do +* carry the deprecated Task* sub-schemas by composition — soft contamination, +* tracked for anchor-exactness adjudication). +* +* The only cross-layer dependency is `import type { JSONObject, JSONValue }` +* from the neutral types barrel — pure structural type aliases with no parse +* behavior. No runtime schema is shared with the neutral layer. +*/ +function build$1() { + const JSONValueSchema$1 = lazy(() => schemas_union([ + schemas_string(), + schemas_number(), + schemas_boolean(), + schemas_null(), + schemas_record(schemas_string(), JSONValueSchema$1), + schemas_array(JSONValueSchema$1) + ])); + const JSONObjectSchema$1 = schemas_record(schemas_string(), JSONValueSchema$1); + /** + * A progress token, used to associate progress notifications with the original request. + */ + const ProgressTokenSchema$1 = schemas_union([schemas_string(), schemas_number().int()]); + /** + * An opaque token used to represent a cursor for pagination. + */ + const CursorSchema$1 = schemas_string(); + /** @deprecated 2025-11-25 wire vocabulary with no SDK runtime; kept importable for interoperability only. */ + const TaskMetadataSchema$1 = schemas_object({ ttl: schemas_number().optional() }); + /** + * Metadata for associating messages with a task. + * Include this in the `_meta` field under the key `io.modelcontextprotocol/related-task`. + * + * @deprecated 2025-11-25 wire vocabulary with no SDK runtime; kept importable for interoperability only. + */ + const RelatedTaskMetadataSchema$1 = schemas_object({ taskId: schemas_string() }); + const RequestMetaSchema$1 = looseObject({ + progressToken: ProgressTokenSchema$1.optional(), + "io.modelcontextprotocol/related-task": RelatedTaskMetadataSchema$1.optional() + }); + /** + * Common params for any request. + */ + const BaseRequestParamsSchema$1 = schemas_object({ _meta: RequestMetaSchema$1.optional() }); + /** + * Common params for any task-augmented request. + * + * @deprecated 2025-11-25 wire vocabulary with no SDK runtime; kept importable for interoperability only. + */ + const TaskAugmentedRequestParamsSchema$1 = BaseRequestParamsSchema$1.extend({ task: TaskMetadataSchema$1.optional() }); + const RequestSchema$1 = schemas_object({ + method: schemas_string(), + params: BaseRequestParamsSchema$1.loose().optional() + }); + const NotificationsParamsSchema$1 = schemas_object({ _meta: RequestMetaSchema$1.optional() }); + const NotificationSchema$1 = schemas_object({ + method: schemas_string(), + params: NotificationsParamsSchema$1.loose().optional() + }); + const ResultSchema$1 = looseObject({ _meta: RequestMetaSchema$1.optional() }); + /** + * A uniquely identifying ID for a request in JSON-RPC. + */ + const RequestIdSchema$1 = schemas_union([schemas_string(), schemas_number().int()]); + /** + * A response that indicates success but carries no data. + */ + const EmptyResultSchema$1 = ResultSchema$1.strict(); + const CancelledNotificationParamsSchema$1 = NotificationsParamsSchema$1.extend({ + requestId: RequestIdSchema$1.optional(), + reason: schemas_string().optional() + }); + /** + * This notification can be sent by either side to indicate that it is cancelling a previously-issued request. + * + * The request SHOULD still be in-flight, but due to communication latency, it is always possible that this notification MAY arrive after the request has already finished. + * + * This notification indicates that the result will be unused, so any associated processing SHOULD cease. + * + * A client MUST NOT attempt to cancel its {@linkcode InitializeRequest | initialize} request. + */ + const CancelledNotificationSchema$1 = NotificationSchema$1.extend({ + method: literal("notifications/cancelled"), + params: CancelledNotificationParamsSchema$1 + }); + /** + * Icon schema for use in {@link Tool | tools}, {@link Prompt | prompts}, {@link Resource | resources}, and {@link Implementation | implementations}. + */ + const IconSchema$1 = schemas_object({ + src: schemas_string(), + mimeType: schemas_string().optional(), + sizes: schemas_array(schemas_string()).optional(), + theme: schemas_enum(["light", "dark"]).optional() + }); + /** + * Base schema to add `icons` property. + * + */ + const IconsSchema$1 = schemas_object({ icons: schemas_array(IconSchema$1).optional() }); + /** + * Base metadata interface for common properties across {@link Resource | resources}, {@link Tool | tools}, {@link Prompt | prompts}, and {@link Implementation | implementations}. + */ + const BaseMetadataSchema$1 = schemas_object({ + name: schemas_string(), + title: schemas_string().optional() + }); + /** + * Describes the name and version of an MCP implementation. + */ + const ImplementationSchema$1 = BaseMetadataSchema$1.extend({ + ...BaseMetadataSchema$1.shape, + ...IconsSchema$1.shape, + version: schemas_string(), + websiteUrl: schemas_string().optional(), + description: schemas_string().optional() + }); + const FormElicitationCapabilitySchema = intersection(schemas_object({ applyDefaults: schemas_boolean().optional() }), JSONObjectSchema$1); + const ElicitationCapabilitySchema = preprocess((value) => { + if (value && typeof value === "object" && !Array.isArray(value) && Object.keys(value).length === 0) return { form: {} }; + return value; + }, intersection(schemas_object({ + form: FormElicitationCapabilitySchema.optional(), + url: JSONObjectSchema$1.optional() + }), JSONObjectSchema$1.optional())); + /** + * Task capabilities for clients, indicating which request types support task creation. + * + * @deprecated 2025-11-25 wire vocabulary with no SDK runtime; kept importable for interoperability only. + */ + const ClientTasksCapabilitySchema$1 = looseObject({ + list: JSONObjectSchema$1.optional(), + cancel: JSONObjectSchema$1.optional(), + requests: looseObject({ + sampling: looseObject({ createMessage: JSONObjectSchema$1.optional() }).optional(), + elicitation: looseObject({ create: JSONObjectSchema$1.optional() }).optional() + }).optional() + }); + /** + * Task capabilities for servers, indicating which request types support task creation. + * + * @deprecated 2025-11-25 wire vocabulary with no SDK runtime; kept importable for interoperability only. + */ + const ServerTasksCapabilitySchema$1 = looseObject({ + list: JSONObjectSchema$1.optional(), + cancel: JSONObjectSchema$1.optional(), + requests: looseObject({ tools: looseObject({ call: JSONObjectSchema$1.optional() }).optional() }).optional() + }); + /** + * Capabilities a client may support. Known capabilities are defined here, in this schema, but this is not a closed set: any client can define its own, additional capabilities. + */ + const ClientCapabilitiesSchema$1 = schemas_object({ + experimental: schemas_record(schemas_string(), JSONObjectSchema$1).optional(), + sampling: schemas_object({ + context: JSONObjectSchema$1.optional(), + tools: JSONObjectSchema$1.optional() + }).optional(), + elicitation: ElicitationCapabilitySchema.optional(), + roots: schemas_object({ listChanged: schemas_boolean().optional() }).optional(), + tasks: ClientTasksCapabilitySchema$1.optional(), + extensions: schemas_record(schemas_string(), JSONObjectSchema$1).optional() + }); + const InitializeRequestParamsSchema$1 = BaseRequestParamsSchema$1.extend({ + protocolVersion: schemas_string(), + capabilities: ClientCapabilitiesSchema$1, + clientInfo: ImplementationSchema$1 + }); + /** + * This request is sent from the client to the server when it first connects, asking it to begin initialization. + */ + const InitializeRequestSchema$1 = RequestSchema$1.extend({ + method: literal("initialize"), + params: InitializeRequestParamsSchema$1 + }); + /** + * Capabilities that a server may support. Known capabilities are defined here, in this schema, but this is not a closed set: any server can define its own, additional capabilities. + */ + const ServerCapabilitiesSchema$1 = schemas_object({ + experimental: schemas_record(schemas_string(), JSONObjectSchema$1).optional(), + logging: JSONObjectSchema$1.optional(), + completions: JSONObjectSchema$1.optional(), + prompts: schemas_object({ listChanged: schemas_boolean().optional() }).optional(), + resources: schemas_object({ + subscribe: schemas_boolean().optional(), + listChanged: schemas_boolean().optional() + }).optional(), + tools: schemas_object({ listChanged: schemas_boolean().optional() }).optional(), + tasks: ServerTasksCapabilitySchema$1.optional(), + extensions: schemas_record(schemas_string(), JSONObjectSchema$1).optional() + }); + /** + * After receiving an initialize request from the client, the server sends this response. + */ + const InitializeResultSchema$1 = ResultSchema$1.extend({ + protocolVersion: schemas_string(), + capabilities: ServerCapabilitiesSchema$1, + serverInfo: ImplementationSchema$1, + instructions: schemas_string().optional() + }); + /** + * This notification is sent from the client to the server after initialization has finished. + */ + const InitializedNotificationSchema$1 = NotificationSchema$1.extend({ + method: literal("notifications/initialized"), + params: NotificationsParamsSchema$1.optional() + }); + /** + * A ping, issued by either the server or the client, to check that the other party is still alive. The receiver must promptly respond, or else may be disconnected. + */ + const PingRequestSchema$1 = RequestSchema$1.extend({ + method: literal("ping"), + params: BaseRequestParamsSchema$1.optional() + }); + const ProgressSchema$1 = schemas_object({ + progress: schemas_number(), + total: schemas_optional(schemas_number()), + message: schemas_optional(schemas_string()) + }); + const ProgressNotificationParamsSchema$1 = schemas_object({ + ...NotificationsParamsSchema$1.shape, + ...ProgressSchema$1.shape, + progressToken: ProgressTokenSchema$1 + }); + /** + * An out-of-band notification used to inform the receiver of a progress update for a long-running request. + * + * @category notifications/progress + */ + const ProgressNotificationSchema$1 = NotificationSchema$1.extend({ + method: literal("notifications/progress"), + params: ProgressNotificationParamsSchema$1 + }); + const PaginatedRequestParamsSchema$1 = BaseRequestParamsSchema$1.extend({ cursor: CursorSchema$1.optional() }); + const PaginatedRequestSchema$1 = RequestSchema$1.extend({ params: PaginatedRequestParamsSchema$1.optional() }); + const PaginatedResultSchema$1 = ResultSchema$1.extend({ nextCursor: CursorSchema$1.optional() }); + /** + * The contents of a specific resource or sub-resource. + */ + const ResourceContentsSchema$1 = schemas_object({ + uri: schemas_string(), + mimeType: schemas_optional(schemas_string()), + _meta: schemas_record(schemas_string(), unknown()).optional() + }); + const TextResourceContentsSchema$1 = ResourceContentsSchema$1.extend({ text: schemas_string() }); + /** + * A Zod schema for validating Base64 strings that is more performant and + * robust for very large inputs than the default regex-based check. It avoids + * stack overflows by using the native `atob` function for validation. + */ + const Base64Schema = schemas_string().refine((val) => { + try { + atob(val); + return true; + } catch { + return false; + } + }, { message: "Invalid Base64 string" }); + const BlobResourceContentsSchema$1 = ResourceContentsSchema$1.extend({ blob: Base64Schema }); + /** + * The sender or recipient of messages and data in a conversation. + */ + const RoleSchema$1 = schemas_enum(["user", "assistant"]); + /** + * Optional annotations providing clients additional context about a resource. + */ + const AnnotationsSchema$1 = schemas_object({ + audience: schemas_array(RoleSchema$1).optional(), + priority: schemas_number().min(0).max(1).optional(), + lastModified: iso_datetime({ offset: true }).optional() + }); + /** + * A known resource that the server is capable of reading. + */ + const ResourceSchema$1 = schemas_object({ + ...BaseMetadataSchema$1.shape, + ...IconsSchema$1.shape, + uri: schemas_string(), + description: schemas_optional(schemas_string()), + mimeType: schemas_optional(schemas_string()), + size: schemas_optional(schemas_number()), + annotations: AnnotationsSchema$1.optional(), + _meta: schemas_optional(looseObject({})) + }); + /** + * A template description for resources available on the server. + */ + const ResourceTemplateSchema$1 = schemas_object({ + ...BaseMetadataSchema$1.shape, + ...IconsSchema$1.shape, + uriTemplate: schemas_string(), + description: schemas_optional(schemas_string()), + mimeType: schemas_optional(schemas_string()), + annotations: AnnotationsSchema$1.optional(), + _meta: schemas_optional(looseObject({})) + }); + /** + * Sent from the client to request a list of resources the server has. + */ + const ListResourcesRequestSchema$1 = PaginatedRequestSchema$1.extend({ method: literal("resources/list") }); + /** + * The server's response to a {@linkcode ListResourcesRequest | resources/list} request from the client. + */ + const ListResourcesResultSchema$1 = PaginatedResultSchema$1.extend({ resources: schemas_array(ResourceSchema$1) }); + /** + * Sent from the client to request a list of resource templates the server has. + */ + const ListResourceTemplatesRequestSchema$1 = PaginatedRequestSchema$1.extend({ method: literal("resources/templates/list") }); + /** + * The server's response to a {@linkcode ListResourceTemplatesRequest | resources/templates/list} request from the client. + */ + const ListResourceTemplatesResultSchema$1 = PaginatedResultSchema$1.extend({ resourceTemplates: schemas_array(ResourceTemplateSchema$1) }); + const ResourceRequestParamsSchema$1 = BaseRequestParamsSchema$1.extend({ uri: schemas_string() }); + /** + * Parameters for a {@linkcode ReadResourceRequest | resources/read} request. + */ + const ReadResourceRequestParamsSchema$1 = ResourceRequestParamsSchema$1; + /** + * Sent from the client to the server, to read a specific resource URI. + */ + const ReadResourceRequestSchema$1 = RequestSchema$1.extend({ + method: literal("resources/read"), + params: ReadResourceRequestParamsSchema$1 + }); + /** + * The server's response to a {@linkcode ReadResourceRequest | resources/read} request from the client. + */ + const ReadResourceResultSchema$1 = ResultSchema$1.extend({ contents: schemas_array(schemas_union([TextResourceContentsSchema$1, BlobResourceContentsSchema$1])) }); + /** + * An optional notification from the server to the client, informing it that the list of resources it can read from has changed. This may be issued by servers without any previous subscription from the client. + */ + const ResourceListChangedNotificationSchema$1 = NotificationSchema$1.extend({ + method: literal("notifications/resources/list_changed"), + params: NotificationsParamsSchema$1.optional() + }); + const SubscribeRequestParamsSchema$1 = ResourceRequestParamsSchema$1; + /** + * Sent from the client to request `resources/updated` notifications from the server whenever a particular resource changes. + */ + const SubscribeRequestSchema$1 = RequestSchema$1.extend({ + method: literal("resources/subscribe"), + params: SubscribeRequestParamsSchema$1 + }); + const UnsubscribeRequestParamsSchema$1 = ResourceRequestParamsSchema$1; + /** + * Sent from the client to request cancellation of {@linkcode ResourceUpdatedNotification | resources/updated} notifications from the server. This should follow a previous {@linkcode SubscribeRequest | resources/subscribe} request. + */ + const UnsubscribeRequestSchema$1 = RequestSchema$1.extend({ + method: literal("resources/unsubscribe"), + params: UnsubscribeRequestParamsSchema$1 + }); + /** + * Parameters for a {@linkcode ResourceUpdatedNotification | notifications/resources/updated} notification. + */ + const ResourceUpdatedNotificationParamsSchema$1 = NotificationsParamsSchema$1.extend({ uri: schemas_string() }); + /** + * A notification from the server to the client, informing it that a resource has changed and may need to be read again. This should only be sent if the client previously sent a {@linkcode SubscribeRequest | resources/subscribe} request. + */ + const ResourceUpdatedNotificationSchema$1 = NotificationSchema$1.extend({ + method: literal("notifications/resources/updated"), + params: ResourceUpdatedNotificationParamsSchema$1 + }); + /** + * Describes an argument that a prompt can accept. + */ + const PromptArgumentSchema$1 = schemas_object({ + name: schemas_string(), + description: schemas_optional(schemas_string()), + required: schemas_optional(schemas_boolean()) + }); + /** + * A prompt or prompt template that the server offers. + */ + const PromptSchema$1 = schemas_object({ + ...BaseMetadataSchema$1.shape, + ...IconsSchema$1.shape, + description: schemas_optional(schemas_string()), + arguments: schemas_optional(schemas_array(PromptArgumentSchema$1)), + _meta: schemas_optional(looseObject({})) + }); + /** + * Sent from the client to request a list of prompts and prompt templates the server has. + */ + const ListPromptsRequestSchema$1 = PaginatedRequestSchema$1.extend({ method: literal("prompts/list") }); + /** + * The server's response to a {@linkcode ListPromptsRequest | prompts/list} request from the client. + */ + const ListPromptsResultSchema$1 = PaginatedResultSchema$1.extend({ prompts: schemas_array(PromptSchema$1) }); + /** + * Parameters for a {@linkcode GetPromptRequest | prompts/get} request. + */ + const GetPromptRequestParamsSchema$1 = BaseRequestParamsSchema$1.extend({ + name: schemas_string(), + arguments: schemas_record(schemas_string(), schemas_string()).optional() + }); + /** + * Used by the client to get a prompt provided by the server. + */ + const GetPromptRequestSchema$1 = RequestSchema$1.extend({ + method: literal("prompts/get"), + params: GetPromptRequestParamsSchema$1 + }); + /** + * Text provided to or from an LLM. + */ + const TextContentSchema$1 = schemas_object({ + type: literal("text"), + text: schemas_string(), + annotations: AnnotationsSchema$1.optional(), + _meta: schemas_record(schemas_string(), unknown()).optional() + }); + /** + * An image provided to or from an LLM. + */ + const ImageContentSchema$1 = schemas_object({ + type: literal("image"), + data: Base64Schema, + mimeType: schemas_string(), + annotations: AnnotationsSchema$1.optional(), + _meta: schemas_record(schemas_string(), unknown()).optional() + }); + /** + * Audio content provided to or from an LLM. + */ + const AudioContentSchema$1 = schemas_object({ + type: literal("audio"), + data: Base64Schema, + mimeType: schemas_string(), + annotations: AnnotationsSchema$1.optional(), + _meta: schemas_record(schemas_string(), unknown()).optional() + }); + /** + * A tool call request from an assistant (LLM). + * Represents the assistant's request to use a tool. + * + * @deprecated Deprecated as of protocol version 2026-07-28 (SEP-2577); remains + * in the specification for at least twelve months. Migrate to calling LLM + * provider APIs directly. + */ + const ToolUseContentSchema$1 = schemas_object({ + type: literal("tool_use"), + name: schemas_string(), + id: schemas_string(), + input: schemas_record(schemas_string(), unknown()), + _meta: schemas_record(schemas_string(), unknown()).optional() + }); + /** + * The contents of a resource, embedded into a prompt or tool call result. + */ + const EmbeddedResourceSchema$1 = schemas_object({ + type: literal("resource"), + resource: schemas_union([TextResourceContentsSchema$1, BlobResourceContentsSchema$1]), + annotations: AnnotationsSchema$1.optional(), + _meta: schemas_record(schemas_string(), unknown()).optional() + }); + /** + * A resource that the server is capable of reading, included in a prompt or tool call result. + * + * Note: resource links returned by tools are not guaranteed to appear in the results of {@linkcode ListResourcesRequest | resources/list} requests. + */ + const ResourceLinkSchema$1 = ResourceSchema$1.extend({ type: literal("resource_link") }); + /** + * A content block that can be used in prompts and tool results. + */ + const ContentBlockSchema$1 = schemas_union([ + TextContentSchema$1, + ImageContentSchema$1, + AudioContentSchema$1, + ResourceLinkSchema$1, + EmbeddedResourceSchema$1 + ]); + /** + * Describes a message returned as part of a prompt. + */ + const PromptMessageSchema$1 = schemas_object({ + role: RoleSchema$1, + content: ContentBlockSchema$1 + }); + /** + * The server's response to a {@linkcode GetPromptRequest | prompts/get} request from the client. + */ + const GetPromptResultSchema$1 = ResultSchema$1.extend({ + description: schemas_string().optional(), + messages: schemas_array(PromptMessageSchema$1) + }); + /** + * An optional notification from the server to the client, informing it that the list of prompts it offers has changed. This may be issued by servers without any previous subscription from the client. + */ + const PromptListChangedNotificationSchema$1 = NotificationSchema$1.extend({ + method: literal("notifications/prompts/list_changed"), + params: NotificationsParamsSchema$1.optional() + }); + /** + * Additional properties describing a `Tool` to clients. + * + * NOTE: all properties in {@linkcode ToolAnnotations} are **hints**. + * They are not guaranteed to provide a faithful description of + * tool behavior (including descriptive properties like `title`). + * + * Clients should never make tool use decisions based on `ToolAnnotations` + * received from untrusted servers. + */ + const ToolAnnotationsSchema$1 = schemas_object({ + title: schemas_string().optional(), + readOnlyHint: schemas_boolean().optional(), + destructiveHint: schemas_boolean().optional(), + idempotentHint: schemas_boolean().optional(), + openWorldHint: schemas_boolean().optional() + }); + /** + * Execution-related properties for a tool. + */ + const ToolExecutionSchema$1 = schemas_object({ taskSupport: schemas_enum([ + "required", + "optional", + "forbidden" + ]).optional() }); + /** + * Definition for a tool the client can call. + */ + const ToolSchema$1 = schemas_object({ + ...BaseMetadataSchema$1.shape, + ...IconsSchema$1.shape, + description: schemas_string().optional(), + inputSchema: schemas_object({ + type: literal("object"), + properties: schemas_record(schemas_string(), JSONValueSchema$1).optional(), + required: schemas_array(schemas_string()).optional() + }).catchall(unknown()), + outputSchema: schemas_object({ + type: literal("object"), + properties: schemas_record(schemas_string(), JSONValueSchema$1).optional(), + required: schemas_array(schemas_string()).optional() + }).catchall(unknown()).optional(), + annotations: ToolAnnotationsSchema$1.optional(), + execution: ToolExecutionSchema$1.optional(), + _meta: schemas_record(schemas_string(), unknown()).optional() + }); + /** + * Sent from the client to request a list of tools the server has. + */ + const ListToolsRequestSchema$1 = PaginatedRequestSchema$1.extend({ method: literal("tools/list") }); + /** + * The server's response to a {@linkcode ListToolsRequest | tools/list} request from the client. + */ + const ListToolsResultSchema$1 = PaginatedResultSchema$1.extend({ tools: schemas_array(ToolSchema$1) }); + /** + * The server's response to a tool call. + */ + const CallToolResultSchema$1 = ResultSchema$1.extend({ + content: schemas_array(ContentBlockSchema$1), + structuredContent: schemas_record(schemas_string(), unknown()).optional(), + isError: schemas_boolean().optional() + }); + /** + * Parameters for a `tools/call` request. + */ + const CallToolRequestParamsSchema$1 = TaskAugmentedRequestParamsSchema$1.extend({ + name: schemas_string(), + arguments: schemas_record(schemas_string(), unknown()).optional() + }); + /** + * Used by the client to invoke a tool provided by the server. + */ + const CallToolRequestSchema$1 = RequestSchema$1.extend({ + method: literal("tools/call"), + params: CallToolRequestParamsSchema$1 + }); + /** + * An optional notification from the server to the client, informing it that the list of tools it offers has changed. This may be issued by servers without any previous subscription from the client. + */ + const ToolListChangedNotificationSchema$1 = NotificationSchema$1.extend({ + method: literal("notifications/tools/list_changed"), + params: NotificationsParamsSchema$1.optional() + }); + /** + * The severity of a log message. + * + * @deprecated Deprecated as of protocol version 2026-07-28 (SEP-2577); remains + * in the specification for at least twelve months. Migrate to stderr logging + * (STDIO servers) or OpenTelemetry. + */ + const LoggingLevelSchema$1 = schemas_enum([ + "debug", + "info", + "notice", + "warning", + "error", + "critical", + "alert", + "emergency" + ]); + /** + * Parameters for a `logging/setLevel` request. + * + * @deprecated Deprecated as of protocol version 2026-07-28 (SEP-2577); remains + * in the specification for at least twelve months. Migrate to stderr logging + * (STDIO servers) or OpenTelemetry. + */ + const SetLevelRequestParamsSchema$1 = BaseRequestParamsSchema$1.extend({ level: LoggingLevelSchema$1 }); + /** + * A request from the client to the server, to enable or adjust logging. + * + * @deprecated Deprecated as of protocol version 2026-07-28 (SEP-2577); remains + * in the specification for at least twelve months. Migrate to stderr logging + * (STDIO servers) or OpenTelemetry. + */ + const SetLevelRequestSchema$1 = RequestSchema$1.extend({ + method: literal("logging/setLevel"), + params: SetLevelRequestParamsSchema$1 + }); + /** + * Parameters for a `notifications/message` notification. + * + * @deprecated Deprecated as of protocol version 2026-07-28 (SEP-2577); remains + * in the specification for at least twelve months. Migrate to stderr logging + * (STDIO servers) or OpenTelemetry. + */ + const LoggingMessageNotificationParamsSchema$1 = NotificationsParamsSchema$1.extend({ + level: LoggingLevelSchema$1, + logger: schemas_string().optional(), + data: unknown() + }); + /** + * Notification of a log message passed from server to client. If no `logging/setLevel` request has been sent from the client, the server MAY decide which messages to send automatically. + * + * @deprecated Deprecated as of protocol version 2026-07-28 (SEP-2577); remains + * in the specification for at least twelve months. Migrate to stderr logging + * (STDIO servers) or OpenTelemetry. + */ + const LoggingMessageNotificationSchema$1 = NotificationSchema$1.extend({ + method: literal("notifications/message"), + params: LoggingMessageNotificationParamsSchema$1 + }); + /** + * Hints to use for model selection. + * + * @deprecated Deprecated as of protocol version 2026-07-28 (SEP-2577); remains + * in the specification for at least twelve months. Migrate to calling LLM + * provider APIs directly. + */ + const ModelHintSchema$1 = schemas_object({ name: schemas_string().optional() }); + /** + * The server's preferences for model selection, requested of the client during sampling. + * + * @deprecated Deprecated as of protocol version 2026-07-28 (SEP-2577); remains + * in the specification for at least twelve months. Migrate to calling LLM + * provider APIs directly. + */ + const ModelPreferencesSchema$1 = schemas_object({ + hints: schemas_array(ModelHintSchema$1).optional(), + costPriority: schemas_number().min(0).max(1).optional(), + speedPriority: schemas_number().min(0).max(1).optional(), + intelligencePriority: schemas_number().min(0).max(1).optional() + }); + /** + * Controls tool usage behavior in sampling requests. + * + * @deprecated Deprecated as of protocol version 2026-07-28 (SEP-2577); remains + * in the specification for at least twelve months. Migrate to calling LLM + * provider APIs directly. + */ + const ToolChoiceSchema$1 = schemas_object({ mode: schemas_enum([ + "auto", + "required", + "none" + ]).optional() }); + /** + * The result of a tool execution, provided by the user (server). + * Represents the outcome of invoking a tool requested via `ToolUseContent`. + * + * @deprecated Deprecated as of protocol version 2026-07-28 (SEP-2577); remains + * in the specification for at least twelve months. Migrate to calling LLM + * provider APIs directly. + */ + const ToolResultContentSchema$1 = schemas_object({ + type: literal("tool_result"), + toolUseId: schemas_string().describe("The unique identifier for the corresponding tool call."), + content: schemas_array(ContentBlockSchema$1), + structuredContent: schemas_object({}).loose().optional(), + isError: schemas_boolean().optional(), + _meta: schemas_record(schemas_string(), unknown()).optional() + }); + /** + * Basic content types for sampling responses (without tool use). + * Used for backwards-compatible {@linkcode CreateMessageResult} when tools are not used. + * + * @deprecated Deprecated as of protocol version 2026-07-28 (SEP-2577); remains + * in the specification for at least twelve months. Migrate to calling LLM + * provider APIs directly. + */ + const SamplingContentSchema$1 = discriminatedUnion("type", [ + TextContentSchema$1, + ImageContentSchema$1, + AudioContentSchema$1 + ]); + /** + * Content block types allowed in sampling messages. + * This includes text, image, audio, tool use requests, and tool results. + * + * @deprecated Deprecated as of protocol version 2026-07-28 (SEP-2577); remains + * in the specification for at least twelve months. Migrate to calling LLM + * provider APIs directly. + */ + const SamplingMessageContentBlockSchema$1 = discriminatedUnion("type", [ + TextContentSchema$1, + ImageContentSchema$1, + AudioContentSchema$1, + ToolUseContentSchema$1, + ToolResultContentSchema$1 + ]); + /** + * Describes a message issued to or received from an LLM API. + * + * @deprecated Deprecated as of protocol version 2026-07-28 (SEP-2577); remains + * in the specification for at least twelve months. Migrate to calling LLM + * provider APIs directly. + */ + const SamplingMessageSchema$1 = schemas_object({ + role: RoleSchema$1, + content: schemas_union([SamplingMessageContentBlockSchema$1, schemas_array(SamplingMessageContentBlockSchema$1)]), + _meta: schemas_record(schemas_string(), unknown()).optional() + }); + /** + * Parameters for a `sampling/createMessage` request. + * + * @deprecated Deprecated as of protocol version 2026-07-28 (SEP-2577); remains + * in the specification for at least twelve months. Migrate to calling LLM + * provider APIs directly. + */ + const CreateMessageRequestParamsSchema$1 = TaskAugmentedRequestParamsSchema$1.extend({ + messages: schemas_array(SamplingMessageSchema$1), + modelPreferences: ModelPreferencesSchema$1.optional(), + systemPrompt: schemas_string().optional(), + includeContext: schemas_enum([ + "none", + "thisServer", + "allServers" + ]).optional(), + temperature: schemas_number().optional(), + maxTokens: schemas_number().int(), + stopSequences: schemas_array(schemas_string()).optional(), + metadata: JSONObjectSchema$1.optional(), + tools: schemas_array(ToolSchema$1).optional(), + toolChoice: ToolChoiceSchema$1.optional() + }); + /** + * A request from the server to sample an LLM via the client. The client has full discretion over which model to select. The client should also inform the user before beginning sampling, to allow them to inspect the request (human in the loop) and decide whether to approve it. + * + * @deprecated Deprecated as of protocol version 2026-07-28 (SEP-2577); remains + * in the specification for at least twelve months. Migrate to calling LLM + * provider APIs directly. + */ + const CreateMessageRequestSchema$1 = RequestSchema$1.extend({ + method: literal("sampling/createMessage"), + params: CreateMessageRequestParamsSchema$1 + }); + /** + * The client's response to a `sampling/create_message` request from the server. + * This is the backwards-compatible version that returns single content (no arrays). + * Used when the request does not include tools. + * + * @deprecated Deprecated as of protocol version 2026-07-28 (SEP-2577); remains + * in the specification for at least twelve months. Migrate to calling LLM + * provider APIs directly. + */ + const CreateMessageResultSchema$1 = ResultSchema$1.extend({ + model: schemas_string(), + stopReason: schemas_optional(schemas_enum([ + "endTurn", + "stopSequence", + "maxTokens" + ]).or(schemas_string())), + role: RoleSchema$1, + content: SamplingContentSchema$1 + }); + /** + * The client's response to a `sampling/create_message` request when tools were provided. + * This version supports array content for tool use flows. + * + * @deprecated Deprecated as of protocol version 2026-07-28 (SEP-2577); remains + * in the specification for at least twelve months. Migrate to calling LLM + * provider APIs directly. + */ + const CreateMessageResultWithToolsSchema$1 = ResultSchema$1.extend({ + model: schemas_string(), + stopReason: schemas_optional(schemas_enum([ + "endTurn", + "stopSequence", + "maxTokens", + "toolUse" + ]).or(schemas_string())), + role: RoleSchema$1, + content: schemas_union([SamplingMessageContentBlockSchema$1, schemas_array(SamplingMessageContentBlockSchema$1)]) + }); + /** + * Primitive schema definition for boolean fields. + */ + const BooleanSchemaSchema$1 = schemas_object({ + type: literal("boolean"), + title: schemas_string().optional(), + description: schemas_string().optional(), + default: schemas_boolean().optional() + }); + /** + * Primitive schema definition for string fields. + */ + const StringSchemaSchema$1 = schemas_object({ + type: literal("string"), + title: schemas_string().optional(), + description: schemas_string().optional(), + minLength: schemas_number().optional(), + maxLength: schemas_number().optional(), + format: schemas_enum([ + "email", + "uri", + "date", + "date-time" + ]).optional(), + default: schemas_string().optional() + }); + /** + * Primitive schema definition for number fields. + */ + const NumberSchemaSchema$1 = schemas_object({ + type: schemas_enum(["number", "integer"]), + title: schemas_string().optional(), + description: schemas_string().optional(), + minimum: schemas_number().optional(), + maximum: schemas_number().optional(), + default: schemas_number().optional() + }); + /** + * Schema for single-selection enumeration without display titles for options. + */ + const UntitledSingleSelectEnumSchemaSchema$1 = schemas_object({ + type: literal("string"), + title: schemas_string().optional(), + description: schemas_string().optional(), + enum: schemas_array(schemas_string()), + default: schemas_string().optional() + }); + /** + * Schema for single-selection enumeration with display titles for each option. + */ + const TitledSingleSelectEnumSchemaSchema$1 = schemas_object({ + type: literal("string"), + title: schemas_string().optional(), + description: schemas_string().optional(), + oneOf: schemas_array(schemas_object({ + const: schemas_string(), + title: schemas_string() + })), + default: schemas_string().optional() + }); + /** + * Use {@linkcode TitledSingleSelectEnumSchema} instead. + * This interface will be removed in a future version. + */ + const LegacyTitledEnumSchemaSchema$1 = schemas_object({ + type: literal("string"), + title: schemas_string().optional(), + description: schemas_string().optional(), + enum: schemas_array(schemas_string()), + enumNames: schemas_array(schemas_string()).optional(), + default: schemas_string().optional() + }); + const SingleSelectEnumSchemaSchema$1 = schemas_union([UntitledSingleSelectEnumSchemaSchema$1, TitledSingleSelectEnumSchemaSchema$1]); + /** + * Schema for multiple-selection enumeration without display titles for options. + */ + const UntitledMultiSelectEnumSchemaSchema$1 = schemas_object({ + type: literal("array"), + title: schemas_string().optional(), + description: schemas_string().optional(), + minItems: schemas_number().optional(), + maxItems: schemas_number().optional(), + items: schemas_object({ + type: literal("string"), + enum: schemas_array(schemas_string()) + }), + default: schemas_array(schemas_string()).optional() + }); + /** + * Schema for multiple-selection enumeration with display titles for each option. + */ + const TitledMultiSelectEnumSchemaSchema$1 = schemas_object({ + type: literal("array"), + title: schemas_string().optional(), + description: schemas_string().optional(), + minItems: schemas_number().optional(), + maxItems: schemas_number().optional(), + items: schemas_object({ anyOf: schemas_array(schemas_object({ + const: schemas_string(), + title: schemas_string() + })) }), + default: schemas_array(schemas_string()).optional() + }); + /** + * Combined schema for multiple-selection enumeration + */ + const MultiSelectEnumSchemaSchema$1 = schemas_union([UntitledMultiSelectEnumSchemaSchema$1, TitledMultiSelectEnumSchemaSchema$1]); + /** + * Primitive schema definition for enum fields. + */ + const EnumSchemaSchema$1 = schemas_union([ + LegacyTitledEnumSchemaSchema$1, + SingleSelectEnumSchemaSchema$1, + MultiSelectEnumSchemaSchema$1 + ]); + /** + * Union of all primitive schema definitions. + */ + const PrimitiveSchemaDefinitionSchema$1 = schemas_union([ + EnumSchemaSchema$1, + BooleanSchemaSchema$1, + StringSchemaSchema$1, + NumberSchemaSchema$1 + ]); + /** + * Parameters for an `elicitation/create` request for form-based elicitation. + */ + const ElicitRequestFormParamsSchema$1 = TaskAugmentedRequestParamsSchema$1.extend({ + mode: literal("form").optional(), + message: schemas_string(), + requestedSchema: schemas_object({ + type: literal("object"), + properties: schemas_record(schemas_string(), PrimitiveSchemaDefinitionSchema$1), + required: schemas_array(schemas_string()).optional() + }).catchall(unknown()) + }); + /** + * Parameters for an {@linkcode ElicitRequest | elicitation/create} request for URL-based elicitation. + */ + const ElicitRequestURLParamsSchema$1 = TaskAugmentedRequestParamsSchema$1.extend({ + mode: literal("url"), + message: schemas_string(), + elicitationId: schemas_string(), + url: schemas_string().url() + }); + /** + * The parameters for a request to elicit additional information from the user via the client. + */ + const ElicitRequestParamsSchema$1 = schemas_union([ElicitRequestFormParamsSchema$1, ElicitRequestURLParamsSchema$1]); + /** + * A request from the server to elicit user input via the client. + * The client should present the message and form fields to the user (form mode) + * or navigate to a URL (URL mode). + */ + const ElicitRequestSchema$1 = RequestSchema$1.extend({ + method: literal("elicitation/create"), + params: ElicitRequestParamsSchema$1 + }); + /** + * Parameters for a {@linkcode ElicitationCompleteNotification | notifications/elicitation/complete} notification. + * + * @category notifications/elicitation/complete + */ + const ElicitationCompleteNotificationParamsSchema$1 = NotificationsParamsSchema$1.extend({ elicitationId: schemas_string() }); + /** + * A notification from the server to the client, informing it of a completion of an out-of-band elicitation request. + * + * @category notifications/elicitation/complete + */ + const ElicitationCompleteNotificationSchema$1 = NotificationSchema$1.extend({ + method: literal("notifications/elicitation/complete"), + params: ElicitationCompleteNotificationParamsSchema$1 + }); + /** + * The client's response to an {@linkcode ElicitRequest | elicitation/create} request from the server. + */ + const ElicitResultSchema$1 = ResultSchema$1.extend({ + action: schemas_enum([ + "accept", + "decline", + "cancel" + ]), + content: preprocess((val) => val === null ? void 0 : val, schemas_record(schemas_string(), schemas_union([ + schemas_string(), + schemas_number(), + schemas_boolean(), + schemas_array(schemas_string()) + ])).optional()) + }); + /** + * A reference to a resource or resource template definition. + */ + const ResourceTemplateReferenceSchema$1 = schemas_object({ + type: literal("ref/resource"), + uri: schemas_string() + }); + /** + * Identifies a prompt. + */ + const PromptReferenceSchema$1 = schemas_object({ + type: literal("ref/prompt"), + name: schemas_string() + }); + /** + * Parameters for a {@linkcode CompleteRequest | completion/complete} request. + */ + const CompleteRequestParamsSchema$1 = BaseRequestParamsSchema$1.extend({ + ref: schemas_union([PromptReferenceSchema$1, ResourceTemplateReferenceSchema$1]), + argument: schemas_object({ + name: schemas_string(), + value: schemas_string() + }), + context: schemas_object({ arguments: schemas_record(schemas_string(), schemas_string()).optional() }).optional() + }); + /** + * A request from the client to the server, to ask for completion options. + */ + const CompleteRequestSchema$1 = RequestSchema$1.extend({ + method: literal("completion/complete"), + params: CompleteRequestParamsSchema$1 + }); + /** + * The server's response to a {@linkcode CompleteRequest | completion/complete} request + */ + const CompleteResultSchema$1 = ResultSchema$1.extend({ completion: looseObject({ + values: schemas_array(schemas_string()).max(100), + total: schemas_optional(schemas_number().int()), + hasMore: schemas_optional(schemas_boolean()) + }) }); + /** + * Represents a root directory or file that the server can operate on. + * + * @deprecated Deprecated as of protocol version 2026-07-28 (SEP-2577); remains + * in the specification for at least twelve months. Migrate to passing paths via + * tool parameters, resource URIs, or configuration. + */ + const RootSchema$1 = schemas_object({ + uri: schemas_string().startsWith("file://"), + name: schemas_string().optional(), + _meta: schemas_record(schemas_string(), unknown()).optional() + }); + /** + * Sent from the server to request a list of root URIs from the client. + * + * @deprecated Deprecated as of protocol version 2026-07-28 (SEP-2577); remains + * in the specification for at least twelve months. Migrate to passing paths via + * tool parameters, resource URIs, or configuration. + */ + const ListRootsRequestSchema$1 = RequestSchema$1.extend({ + method: literal("roots/list"), + params: BaseRequestParamsSchema$1.optional() + }); + /** + * The client's response to a `roots/list` request from the server. + * + * @deprecated Deprecated as of protocol version 2026-07-28 (SEP-2577); remains + * in the specification for at least twelve months. Migrate to passing paths via + * tool parameters, resource URIs, or configuration. + */ + const ListRootsResultSchema$1 = ResultSchema$1.extend({ roots: schemas_array(RootSchema$1) }); + /** + * A notification from the client to the server, informing it that the list of roots has changed. + * + * @deprecated Deprecated as of protocol version 2026-07-28 (SEP-2577); remains + * in the specification for at least twelve months. Migrate to passing paths via + * tool parameters, resource URIs, or configuration. + */ + const RootsListChangedNotificationSchema$1 = NotificationSchema$1.extend({ + method: literal("notifications/roots/list_changed"), + params: NotificationsParamsSchema$1.optional() + }); + /** + * Task creation parameters, used to ask that the server create a task to represent a request. + * + * @deprecated 2025-11-25 wire vocabulary with no SDK runtime; kept importable for interoperability only. + */ + const TaskCreationParamsSchema$1 = looseObject({ + ttl: schemas_number().optional(), + pollInterval: schemas_number().optional() + }); + /** + * The status of a task. + * + * @deprecated 2025-11-25 wire vocabulary with no SDK runtime; kept importable for interoperability only. + */ + const TaskStatusSchema$1 = schemas_enum([ + "working", + "input_required", + "completed", + "failed", + "cancelled" + ]); + /** + * A pollable state object associated with a request. + * + * @deprecated 2025-11-25 wire vocabulary with no SDK runtime; kept importable for interoperability only. + */ + const TaskSchema$1 = schemas_object({ + taskId: schemas_string(), + status: TaskStatusSchema$1, + ttl: schemas_union([schemas_number(), schemas_null()]), + createdAt: schemas_string(), + lastUpdatedAt: schemas_string(), + pollInterval: schemas_optional(schemas_number()), + statusMessage: schemas_optional(schemas_string()) + }); + /** + * Result returned when a task is created, containing the task data wrapped in a `task` field. + * + * @deprecated 2025-11-25 wire vocabulary with no SDK runtime; kept importable for interoperability only. + */ + const CreateTaskResultSchema$1 = ResultSchema$1.extend({ task: TaskSchema$1 }); + /** + * Parameters for task status notification. + * + * @deprecated 2025-11-25 wire vocabulary with no SDK runtime; kept importable for interoperability only. + */ + const TaskStatusNotificationParamsSchema$1 = NotificationsParamsSchema$1.merge(TaskSchema$1); + /** + * A notification sent when a task's status changes. + * + * @deprecated 2025-11-25 wire vocabulary with no SDK runtime; kept importable for interoperability only. + */ + const TaskStatusNotificationSchema$1 = NotificationSchema$1.extend({ + method: literal("notifications/tasks/status"), + params: TaskStatusNotificationParamsSchema$1 + }); + /** + * A request to get the state of a specific task. + * + * @deprecated 2025-11-25 wire vocabulary with no SDK runtime; kept importable for interoperability only. + */ + const GetTaskRequestSchema$1 = RequestSchema$1.extend({ + method: literal("tasks/get"), + params: BaseRequestParamsSchema$1.extend({ taskId: schemas_string() }) + }); + /** + * The response to a {@linkcode GetTaskRequest | tasks/get} request. + * + * @deprecated 2025-11-25 wire vocabulary with no SDK runtime; kept importable for interoperability only. + */ + const GetTaskResultSchema$1 = ResultSchema$1.merge(TaskSchema$1); + /** + * A request to get the result of a specific task. + * + * @deprecated 2025-11-25 wire vocabulary with no SDK runtime; kept importable for interoperability only. + */ + const GetTaskPayloadRequestSchema$1 = RequestSchema$1.extend({ + method: literal("tasks/result"), + params: BaseRequestParamsSchema$1.extend({ taskId: schemas_string() }) + }); + /** + * The response to a `tasks/result` request. + * The structure matches the result type of the original request. + * For example, a {@linkcode CallToolRequest | tools/call} task would return the `CallToolResult` structure. + * + * + * @deprecated 2025-11-25 wire vocabulary with no SDK runtime; kept importable for interoperability only. + */ + const GetTaskPayloadResultSchema$1 = ResultSchema$1.loose(); + /** + * A request to list tasks. + * + * @deprecated 2025-11-25 wire vocabulary with no SDK runtime; kept importable for interoperability only. + */ + const ListTasksRequestSchema$1 = PaginatedRequestSchema$1.extend({ method: literal("tasks/list") }); + /** + * The response to a {@linkcode ListTasksRequest | tasks/list} request. + * + * @deprecated 2025-11-25 wire vocabulary with no SDK runtime; kept importable for interoperability only. + */ + const ListTasksResultSchema$1 = PaginatedResultSchema$1.extend({ tasks: schemas_array(TaskSchema$1) }); + /** + * A request to cancel a specific task. + * + * @deprecated 2025-11-25 wire vocabulary with no SDK runtime; kept importable for interoperability only. + */ + const CancelTaskRequestSchema$1 = RequestSchema$1.extend({ + method: literal("tasks/cancel"), + params: BaseRequestParamsSchema$1.extend({ taskId: schemas_string() }) + }); + return { + JSONValueSchema: JSONValueSchema$1, + JSONObjectSchema: JSONObjectSchema$1, + ProgressTokenSchema: ProgressTokenSchema$1, + CursorSchema: CursorSchema$1, + TaskMetadataSchema: TaskMetadataSchema$1, + RelatedTaskMetadataSchema: RelatedTaskMetadataSchema$1, + RequestMetaSchema: RequestMetaSchema$1, + BaseRequestParamsSchema: BaseRequestParamsSchema$1, + TaskAugmentedRequestParamsSchema: TaskAugmentedRequestParamsSchema$1, + RequestSchema: RequestSchema$1, + NotificationsParamsSchema: NotificationsParamsSchema$1, + NotificationSchema: NotificationSchema$1, + ResultSchema: ResultSchema$1, + RequestIdSchema: RequestIdSchema$1, + EmptyResultSchema: EmptyResultSchema$1, + CancelledNotificationParamsSchema: CancelledNotificationParamsSchema$1, + CancelledNotificationSchema: CancelledNotificationSchema$1, + IconSchema: IconSchema$1, + IconsSchema: IconsSchema$1, + BaseMetadataSchema: BaseMetadataSchema$1, + ImplementationSchema: ImplementationSchema$1, + ClientTasksCapabilitySchema: ClientTasksCapabilitySchema$1, + ServerTasksCapabilitySchema: ServerTasksCapabilitySchema$1, + ClientCapabilitiesSchema: ClientCapabilitiesSchema$1, + InitializeRequestParamsSchema: InitializeRequestParamsSchema$1, + InitializeRequestSchema: InitializeRequestSchema$1, + ServerCapabilitiesSchema: ServerCapabilitiesSchema$1, + InitializeResultSchema: InitializeResultSchema$1, + InitializedNotificationSchema: InitializedNotificationSchema$1, + PingRequestSchema: PingRequestSchema$1, + ProgressSchema: ProgressSchema$1, + ProgressNotificationParamsSchema: ProgressNotificationParamsSchema$1, + ProgressNotificationSchema: ProgressNotificationSchema$1, + PaginatedRequestParamsSchema: PaginatedRequestParamsSchema$1, + PaginatedRequestSchema: PaginatedRequestSchema$1, + PaginatedResultSchema: PaginatedResultSchema$1, + ResourceContentsSchema: ResourceContentsSchema$1, + TextResourceContentsSchema: TextResourceContentsSchema$1, + BlobResourceContentsSchema: BlobResourceContentsSchema$1, + RoleSchema: RoleSchema$1, + AnnotationsSchema: AnnotationsSchema$1, + ResourceSchema: ResourceSchema$1, + ResourceTemplateSchema: ResourceTemplateSchema$1, + ListResourcesRequestSchema: ListResourcesRequestSchema$1, + ListResourcesResultSchema: ListResourcesResultSchema$1, + ListResourceTemplatesRequestSchema: ListResourceTemplatesRequestSchema$1, + ListResourceTemplatesResultSchema: ListResourceTemplatesResultSchema$1, + ResourceRequestParamsSchema: ResourceRequestParamsSchema$1, + ReadResourceRequestParamsSchema: ReadResourceRequestParamsSchema$1, + ReadResourceRequestSchema: ReadResourceRequestSchema$1, + ReadResourceResultSchema: ReadResourceResultSchema$1, + ResourceListChangedNotificationSchema: ResourceListChangedNotificationSchema$1, + SubscribeRequestParamsSchema: SubscribeRequestParamsSchema$1, + SubscribeRequestSchema: SubscribeRequestSchema$1, + UnsubscribeRequestParamsSchema: UnsubscribeRequestParamsSchema$1, + UnsubscribeRequestSchema: UnsubscribeRequestSchema$1, + ResourceUpdatedNotificationParamsSchema: ResourceUpdatedNotificationParamsSchema$1, + ResourceUpdatedNotificationSchema: ResourceUpdatedNotificationSchema$1, + PromptArgumentSchema: PromptArgumentSchema$1, + PromptSchema: PromptSchema$1, + ListPromptsRequestSchema: ListPromptsRequestSchema$1, + ListPromptsResultSchema: ListPromptsResultSchema$1, + GetPromptRequestParamsSchema: GetPromptRequestParamsSchema$1, + GetPromptRequestSchema: GetPromptRequestSchema$1, + TextContentSchema: TextContentSchema$1, + ImageContentSchema: ImageContentSchema$1, + AudioContentSchema: AudioContentSchema$1, + ToolUseContentSchema: ToolUseContentSchema$1, + EmbeddedResourceSchema: EmbeddedResourceSchema$1, + ResourceLinkSchema: ResourceLinkSchema$1, + ContentBlockSchema: ContentBlockSchema$1, + PromptMessageSchema: PromptMessageSchema$1, + GetPromptResultSchema: GetPromptResultSchema$1, + PromptListChangedNotificationSchema: PromptListChangedNotificationSchema$1, + ToolAnnotationsSchema: ToolAnnotationsSchema$1, + ToolExecutionSchema: ToolExecutionSchema$1, + ToolSchema: ToolSchema$1, + ListToolsRequestSchema: ListToolsRequestSchema$1, + ListToolsResultSchema: ListToolsResultSchema$1, + CallToolResultSchema: CallToolResultSchema$1, + CallToolRequestParamsSchema: CallToolRequestParamsSchema$1, + CallToolRequestSchema: CallToolRequestSchema$1, + ToolListChangedNotificationSchema: ToolListChangedNotificationSchema$1, + LoggingLevelSchema: LoggingLevelSchema$1, + SetLevelRequestParamsSchema: SetLevelRequestParamsSchema$1, + SetLevelRequestSchema: SetLevelRequestSchema$1, + LoggingMessageNotificationParamsSchema: LoggingMessageNotificationParamsSchema$1, + LoggingMessageNotificationSchema: LoggingMessageNotificationSchema$1, + ModelHintSchema: ModelHintSchema$1, + ModelPreferencesSchema: ModelPreferencesSchema$1, + ToolChoiceSchema: ToolChoiceSchema$1, + ToolResultContentSchema: ToolResultContentSchema$1, + SamplingContentSchema: SamplingContentSchema$1, + SamplingMessageContentBlockSchema: SamplingMessageContentBlockSchema$1, + SamplingMessageSchema: SamplingMessageSchema$1, + CreateMessageRequestParamsSchema: CreateMessageRequestParamsSchema$1, + CreateMessageRequestSchema: CreateMessageRequestSchema$1, + CreateMessageResultSchema: CreateMessageResultSchema$1, + CreateMessageResultWithToolsSchema: CreateMessageResultWithToolsSchema$1, + BooleanSchemaSchema: BooleanSchemaSchema$1, + StringSchemaSchema: StringSchemaSchema$1, + NumberSchemaSchema: NumberSchemaSchema$1, + UntitledSingleSelectEnumSchemaSchema: UntitledSingleSelectEnumSchemaSchema$1, + TitledSingleSelectEnumSchemaSchema: TitledSingleSelectEnumSchemaSchema$1, + LegacyTitledEnumSchemaSchema: LegacyTitledEnumSchemaSchema$1, + SingleSelectEnumSchemaSchema: SingleSelectEnumSchemaSchema$1, + UntitledMultiSelectEnumSchemaSchema: UntitledMultiSelectEnumSchemaSchema$1, + TitledMultiSelectEnumSchemaSchema: TitledMultiSelectEnumSchemaSchema$1, + MultiSelectEnumSchemaSchema: MultiSelectEnumSchemaSchema$1, + EnumSchemaSchema: EnumSchemaSchema$1, + PrimitiveSchemaDefinitionSchema: PrimitiveSchemaDefinitionSchema$1, + ElicitRequestFormParamsSchema: ElicitRequestFormParamsSchema$1, + ElicitRequestURLParamsSchema: ElicitRequestURLParamsSchema$1, + ElicitRequestParamsSchema: ElicitRequestParamsSchema$1, + ElicitRequestSchema: ElicitRequestSchema$1, + ElicitationCompleteNotificationParamsSchema: ElicitationCompleteNotificationParamsSchema$1, + ElicitationCompleteNotificationSchema: ElicitationCompleteNotificationSchema$1, + ElicitResultSchema: ElicitResultSchema$1, + ResourceTemplateReferenceSchema: ResourceTemplateReferenceSchema$1, + PromptReferenceSchema: PromptReferenceSchema$1, + CompleteRequestParamsSchema: CompleteRequestParamsSchema$1, + CompleteRequestSchema: CompleteRequestSchema$1, + CompleteResultSchema: CompleteResultSchema$1, + RootSchema: RootSchema$1, + ListRootsRequestSchema: ListRootsRequestSchema$1, + ListRootsResultSchema: ListRootsResultSchema$1, + RootsListChangedNotificationSchema: RootsListChangedNotificationSchema$1, + TaskCreationParamsSchema: TaskCreationParamsSchema$1, + TaskStatusSchema: TaskStatusSchema$1, + TaskSchema: TaskSchema$1, + CreateTaskResultSchema: CreateTaskResultSchema$1, + TaskStatusNotificationParamsSchema: TaskStatusNotificationParamsSchema$1, + TaskStatusNotificationSchema: TaskStatusNotificationSchema$1, + GetTaskRequestSchema: GetTaskRequestSchema$1, + GetTaskResultSchema: GetTaskResultSchema$1, + GetTaskPayloadRequestSchema: GetTaskPayloadRequestSchema$1, + GetTaskPayloadResultSchema: GetTaskPayloadResultSchema$1, + ListTasksRequestSchema: ListTasksRequestSchema$1, + ListTasksResultSchema: ListTasksResultSchema$1, + CancelTaskRequestSchema: CancelTaskRequestSchema$1, + CancelTaskResultSchema: ResultSchema$1.merge(TaskSchema$1), + ClientRequestSchema: schemas_union([ + PingRequestSchema$1, + InitializeRequestSchema$1, + CompleteRequestSchema$1, + SetLevelRequestSchema$1, + GetPromptRequestSchema$1, + ListPromptsRequestSchema$1, + ListResourcesRequestSchema$1, + ListResourceTemplatesRequestSchema$1, + ReadResourceRequestSchema$1, + SubscribeRequestSchema$1, + UnsubscribeRequestSchema$1, + CallToolRequestSchema$1, + ListToolsRequestSchema$1, + GetTaskRequestSchema$1, + GetTaskPayloadRequestSchema$1, + ListTasksRequestSchema$1, + CancelTaskRequestSchema$1 + ]), + ClientNotificationSchema: schemas_union([ + CancelledNotificationSchema$1, + ProgressNotificationSchema$1, + InitializedNotificationSchema$1, + RootsListChangedNotificationSchema$1, + TaskStatusNotificationSchema$1 + ]), + ClientResultSchema: schemas_union([ + EmptyResultSchema$1, + CreateMessageResultSchema$1, + CreateMessageResultWithToolsSchema$1, + ElicitResultSchema$1, + ListRootsResultSchema$1, + GetTaskResultSchema$1, + ListTasksResultSchema$1, + CreateTaskResultSchema$1 + ]), + ServerRequestSchema: schemas_union([ + PingRequestSchema$1, + CreateMessageRequestSchema$1, + ElicitRequestSchema$1, + ListRootsRequestSchema$1, + GetTaskRequestSchema$1, + GetTaskPayloadRequestSchema$1, + ListTasksRequestSchema$1, + CancelTaskRequestSchema$1 + ]), + ServerNotificationSchema: schemas_union([ + CancelledNotificationSchema$1, + ProgressNotificationSchema$1, + LoggingMessageNotificationSchema$1, + ResourceUpdatedNotificationSchema$1, + ResourceListChangedNotificationSchema$1, + ToolListChangedNotificationSchema$1, + PromptListChangedNotificationSchema$1, + TaskStatusNotificationSchema$1, + ElicitationCompleteNotificationSchema$1 + ]), + ServerResultSchema: schemas_union([ + EmptyResultSchema$1, + InitializeResultSchema$1, + CompleteResultSchema$1, + GetPromptResultSchema$1, + ListPromptsResultSchema$1, + ListResourcesResultSchema$1, + ListResourceTemplatesResultSchema$1, + ReadResourceResultSchema$1, + CallToolResultSchema$1, + ListToolsResultSchema$1, + GetTaskResultSchema$1, + ListTasksResultSchema$1, + CreateTaskResultSchema$1 + ]), + CallToolResultWireSchema: unknown().superRefine((value, ctx) => { + if (typeof value !== "object" || value === null || Array.isArray(value) || value.content !== void 0) return; + for (const key of TOOL_RESULT_FOREIGN_FAMILY_KEYS) if (key in value) { + ctx.addIssue({ + code: "custom", + message: `content is required when the body carries '${key}' — another result family cannot default into an empty tools/call success` + }); + return; + } + }).transform(normalizeContentlessToolResult).pipe(CallToolResultSchema$1) + }; +} +let memo$1; +/** +* Builds the era wire-schema set on first call and returns the same object +* thereafter. Module evaluation stays construction-free so importing the +* era codec/registry costs nothing until the first validation actually +* needs a schema; the registry, the codec, and the eager `schemas.ts` +* shim all pull through this memo, so reference identity holds across +* every consumer. +*/ +function buildSchemas2025() { + return memo$1 ??= build$1(); +} + +//#endregion +//#region ../core-internal/src/wire/rev2025-11-25/legacyWrap.ts +/** +* SEP-2106 legacy `outputSchema` wrap helpers (2025-era projection only). +* +* The neutral / 2026-07-28 model lets a tool's `outputSchema` carry any JSON +* Schema root. The 2025-11-25 wire shape requires `type:'object'` at the root, +* so when an era-blind handler advertises a non-object root, the 2025 codec's +* `encodeResult('tools/list', …)` projects it down to +* `{type:'object', properties:{result:}, required:['result']}`, and +* `projectCallToolResult` wraps the matching `structuredContent` as +* `{result:}`. The 2026 codec's projections are the identity. +* +* These helpers are wire-layer property — they exist so the projection can +* live behind {@link WireCodec.encodeResult} / {@link WireCodec.projectCallToolResult} +* and never be re-derived in shared/ or server-side code. +*/ +/** +* Whether a JSON Schema's root is non-object: either an explicit non-object +* `type`, or a typeless root such as `{anyOf:[…]}`. Object-shaped typeless +* roots that the schema-conversion layer can prove are objects are stamped +* `type:'object'` upstream, so they reach this predicate as object roots. +*/ +function isNonObjectJsonSchemaRoot(json) { + return json["type"] !== "object"; +} +/** +* Keyword-position keys whose values are instance data (not subschemas). A +* `{$ref:…}` appearing inside one is a literal value, not a JSON Pointer to +* rewrite. Only consulted when the current object is in keyword position — +* a PROPERTY named `default`/`const` (under `properties`/`$defs`/…) is a name +* position whose value IS a subschema and is recursed into. +*/ +const REF_REWRITE_DATA_POSITION_KEYS = new Set([ + "const", + "enum", + "default", + "examples" +]); +/** +* Keyword-position keys whose value is a name→subschema map. Entries inside +* such a map are in NAME position: their keys are author-chosen property +* names (which may collide with JSON Schema keywords), their values are +* subschemas to recurse into. +*/ +const REF_REWRITE_NAME_MAP_KEYS = new Set([ + "properties", + "patternProperties", + "$defs", + "definitions", + "dependentSchemas", + "dependencies" +]); +/** +* Whether a subtree's `$id` establishes a new resolution base. A fragment-only +* `$id` (`"#item"`, the draft-07/06 spelling of 2020-12's `$anchor`) does not +* change the RFC 3986 base URI — same-document pointers inside still resolve +* against the document root and must be rewritten. +*/ +function establishesNewBase(id) { + return id !== void 0 && !(typeof id === "string" && id.startsWith("#")); +} +/** +* Wrap a non-object output schema in the 2025-era envelope: +* `{type:'object', properties:{result:}, required:['result']}`. +* +* Same-document `$ref` / `$dynamicRef` JSON Pointers inside the natural schema +* (e.g. `#/properties/foo` produced by zod for de-duplicated/recursive types) +* are rewritten to account for the new `#/properties/result` root: bare `#` → +* `#/properties/result`, `#/…` → `#/properties/result/…`. Cross-document refs +* (anything not starting with `#`) are left untouched. +* +* The rewrite is position-aware: data-valued keywords +* (`const`/`enum`/`default`/`examples`) in keyword position are NOT descended +* into; the same names appearing as property names under +* `properties`/`patternProperties`/`$defs`/`definitions`/`dependentSchemas`/ +* `dependencies` ARE descended into (they're subschemas). The rewrite is also +* `$id`-scoped: if the natural root carries a base-establishing `$id` no +* pointer is rewritten (same-document refs inside resolve against the embedded +* `$id` base, not the wrapper root), and any subtree that establishes its own +* `$id` is left untouched for the same reason. Fragment-only `$id` (`"#item"`, +* draft-07's anchor spelling) does not establish a base and IS descended into. +*/ +function wrapOutputSchemaForLegacy(natural) { + const $schema = typeof natural["$schema"] === "string" ? natural["$schema"] : void 0; + if (establishesNewBase(natural["$id"])) return { + ...$schema !== void 0 && { $schema }, + type: "object", + properties: { result: natural }, + required: ["result"] + }; + const convertRecursiveRefs = declares2019Dialect(natural["$schema"]) && natural["$recursiveAnchor"] !== true; + const rewriteRefs = (node, parentIsNameMap) => { + if (Array.isArray(node)) return node.map((item) => rewriteRefs(item, false)); + if (node === null || typeof node !== "object") return node; + if (!parentIsNameMap && establishesNewBase(node["$id"])) return node; + const out = {}; + let convertedRecursion = false; + for (const [k, v] of Object.entries(node)) if (parentIsNameMap) out[k] = rewriteRefs(v, false); + else if ((k === "$ref" || k === "$dynamicRef") && typeof v === "string") out[k] = v === "#" ? "#/properties/result" : v.startsWith("#/") ? `#/properties/result${v.slice(1)}` : v; + else if (k === "$recursiveRef" && v === "#" && convertRecursiveRefs) convertedRecursion = true; + else if (REF_REWRITE_DATA_POSITION_KEYS.has(k)) out[k] = v; + else if (REF_REWRITE_NAME_MAP_KEYS.has(k)) out[k] = rewriteRefs(v, true); + else out[k] = rewriteRefs(v, false); + if (convertedRecursion) if ("$ref" in out) out["allOf"] = [...Array.isArray(out["allOf"]) ? out["allOf"] : [], { $ref: "#/properties/result" }]; + else out["$ref"] = "#/properties/result"; + return out; + }; + return { + ...$schema !== void 0 && { $schema }, + type: "object", + properties: { result: rewriteRefs(natural, false) }, + required: ["result"] + }; +} + +//#endregion +//#region ../core-internal/src/wire/rev2025-11-25/registry.ts +const requestMethodKeys$1 = { + 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 +}; +const notificationMethodKeys$1 = { + "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 +}; +const resultMethodKeys = { + 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 +}; +let maps$1; +function registryMaps() { + if (maps$1) return maps$1; + const s = buildSchemas2025(); + maps$1 = { + requestSchemas: { + ping: s.PingRequestSchema, + initialize: s.InitializeRequestSchema, + "completion/complete": s.CompleteRequestSchema, + "logging/setLevel": s.SetLevelRequestSchema, + "prompts/get": s.GetPromptRequestSchema, + "prompts/list": s.ListPromptsRequestSchema, + "resources/list": s.ListResourcesRequestSchema, + "resources/templates/list": s.ListResourceTemplatesRequestSchema, + "resources/read": s.ReadResourceRequestSchema, + "resources/subscribe": s.SubscribeRequestSchema, + "resources/unsubscribe": s.UnsubscribeRequestSchema, + "tools/call": s.CallToolRequestSchema, + "tools/list": s.ListToolsRequestSchema, + "tasks/get": s.GetTaskRequestSchema, + "tasks/result": s.GetTaskPayloadRequestSchema, + "tasks/list": s.ListTasksRequestSchema, + "tasks/cancel": s.CancelTaskRequestSchema, + "sampling/createMessage": s.CreateMessageRequestSchema, + "elicitation/create": s.ElicitRequestSchema, + "roots/list": s.ListRootsRequestSchema + }, + notificationSchemas: { + "notifications/cancelled": s.CancelledNotificationSchema, + "notifications/progress": s.ProgressNotificationSchema, + "notifications/initialized": s.InitializedNotificationSchema, + "notifications/roots/list_changed": s.RootsListChangedNotificationSchema, + "notifications/tasks/status": s.TaskStatusNotificationSchema, + "notifications/message": s.LoggingMessageNotificationSchema, + "notifications/resources/updated": s.ResourceUpdatedNotificationSchema, + "notifications/resources/list_changed": s.ResourceListChangedNotificationSchema, + "notifications/tools/list_changed": s.ToolListChangedNotificationSchema, + "notifications/prompts/list_changed": s.PromptListChangedNotificationSchema, + "notifications/elicitation/complete": s.ElicitationCompleteNotificationSchema + }, + resultSchemas: { + ping: s.EmptyResultSchema, + initialize: s.InitializeResultSchema, + "completion/complete": s.CompleteResultSchema, + "logging/setLevel": s.EmptyResultSchema, + "prompts/get": s.GetPromptResultSchema, + "prompts/list": s.ListPromptsResultSchema, + "resources/list": s.ListResourcesResultSchema, + "resources/templates/list": s.ListResourceTemplatesResultSchema, + "resources/read": s.ReadResourceResultSchema, + "resources/subscribe": s.EmptyResultSchema, + "resources/unsubscribe": s.EmptyResultSchema, + "tools/call": s.CallToolResultWireSchema, + "tools/list": s.ListToolsResultSchema, + "sampling/createMessage": s.CreateMessageResultWithToolsSchema, + "elicitation/create": s.ElicitResultSchema, + "roots/list": s.ListRootsResultSchema + } + }; + return maps$1; +} +/** +* Forces the lazy registry maps (and, through them, the era's schema memo). +* Warm-up hook for `preloadSchemas()` — no-op once the maps exist. +*/ +function warmRegistryMaps2025() { + registryMaps(); +} +/** The 2025-era request-method set (registry membership = the deletion story). */ +function hasRequestMethod2025(method) { + return Object.prototype.hasOwnProperty.call(requestMethodKeys$1, method); +} +/** The 2025-era notification-method set. */ +function hasNotificationMethod2025(method) { + return Object.prototype.hasOwnProperty.call(notificationMethodKeys$1, method); +} +/** Result-map membership: exactly the era's typed-method subset (no task entries, no 2026-only methods). */ +function hasResultMethod(method) { + return Object.prototype.hasOwnProperty.call(resultMethodKeys, method); +} +function getResultSchema(method) { + return hasResultMethod(method) ? registryMaps().resultSchemas[method] : void 0; +} +function getRequestSchema(method) { + return hasRequestMethod2025(method) ? registryMaps().requestSchemas[method] : void 0; +} +function getNotificationSchema(method) { + return hasNotificationMethod2025(method) ? registryMaps().notificationSchemas[method] : void 0; +} +/** Registry method lists (for the spec-method universe and the CI registry-diff oracle). */ +const rev2025RequestMethods = Object.keys(requestMethodKeys$1); +const rev2025NotificationMethods = Object.keys(notificationMethodKeys$1); + +//#endregion +//#region ../core-internal/src/wire/rev2025-11-25/codec.ts +function isPlainObject$6(value) { + return value !== null && typeof value === "object" && !Array.isArray(value); +} +/** Tri-state wrap of an optional Zod schema lookup (the function-only contract). */ +function triState$1(schema, raw) { + if (schema === void 0) return { + ok: false, + reason: "not-in-era" + }; + const parsed = schema.safeParse(raw); + return parsed.success ? { + ok: true, + value: parsed.data + } : { + ok: false, + reason: "invalid", + message: String(parsed.error) + }; +} +const NOT_IN_ERA$1 = { + ok: false, + reason: "not-in-era" +}; +/** Whether a `tools/list` entry advertises a non-object `outputSchema` root that needs the SEP-2106 legacy wrap. */ +function toolNeedsLegacyWrap(t) { + return isPlainObject$6(t) && isPlainObject$6(t["outputSchema"]) && isNonObjectJsonSchemaRoot(t["outputSchema"]); +} +/** The wire→neutral trust boundary: a decoded 2025-era wire result is adopted as the neutral `Result` here (the module's single deliberate assertion). */ +function toNeutralResult(value) { + return value; +} +const rev2025Codec = { + era: "2025-11-25", + hasRequestMethod: hasRequestMethod2025, + hasNotificationMethod: hasNotificationMethod2025, + validateRequest: (method, raw) => triState$1(getRequestSchema(method), raw), + validateResult: (method, raw) => triState$1(getResultSchema(method), raw), + validateNotification: (method, raw) => triState$1(getNotificationSchema(method), raw), + hasInputRequestMethod: () => false, + validateInputRequest: () => NOT_IN_ERA$1, + validateInputResponse: () => NOT_IN_ERA$1, + samplingResultVariant: ((hasTools, raw) => { + const s = buildSchemas2025(); + return triState$1(hasTools ? s.CreateMessageResultWithToolsSchema : s.CreateMessageResultSchema, raw); + }), + outboundEnvelope: (_material) => void 0, + validateEnvelopeMeta: (_meta) => [], + projectCallToolResult(result, advertisedOutputSchema) { + const withText = appendTextFallbackForNonObject(result); + const sc = withText.structuredContent; + if (sc === void 0) return withText; + const valueIsNonObject = typeof sc !== "object" || sc === null || Array.isArray(sc); + const schemaWrapped = advertisedOutputSchema !== void 0 && isNonObjectJsonSchemaRoot(advertisedOutputSchema); + if (!valueIsNonObject && !schemaWrapped) return withText; + return { + ...withText, + structuredContent: { result: sc } + }; + }, + decodeResult(_method, raw) { + if (isPlainObject$6(raw) && "resultType" in raw) { + const stripped = { ...raw }; + delete stripped["resultType"]; + return { + kind: "complete", + result: toNeutralResult(stripped) + }; + } + return { + kind: "complete", + result: toNeutralResult(raw) + }; + }, + encodeResult(method, result) { + if (method !== "tools/list") return result; + const tools = result.tools; + if (!Array.isArray(tools) || !tools.some((t) => toolNeedsLegacyWrap(t))) return result; + return { + ...result, + tools: tools.map((t) => toolNeedsLegacyWrap(t) ? { + ...t, + outputSchema: wrapOutputSchemaForLegacy(t.outputSchema) + } : t) + }; + }, + encodeErrorCode: (code) => code === -32002 ? -32602 : code, + checkInboundEnvelope: (_material) => void 0 +}; + +//#endregion +//#region ../core-internal/src/wire/rev2026-07-28/buildSchemas.ts +/** +* 2026-era wire schemas (protocol revision 2026-07-28). +* +* Fully self-contained — no runtime imports from types/schemas.ts. The +* neutral types/schemas.ts layer is the public-API superset and is free to +* evolve; this file is the 2026 wire-parse contract and is BEHAVIOR-FROZEN +* against the 2026-07-28 anchor. Every era-shared building block (content +* blocks, resources, prompts, capabilities, notifications, …) that the wire +* shapes compose is a frozen LOCAL copy — verbatim from the neutral layer at +* the point this revision was sealed, dependencies first. The only cross-layer +* dependency is `import type { JSONObject, JSONValue }` from the neutral types +* barrel — pure structural type aliases with no parse behavior. +* +* This module is the only place the per-request `_meta` envelope is modeled. +* The envelope is wire-only vocabulary: the protocol layer lifts it off +* inbound requests before any handler runs and surfaces it at +* `ctx.mcpReq.envelope`; the 2026-era codec enforces its requiredness at +* dispatch time (`checkInboundEnvelope`) - the former neutral-schema JSDoc +* deferral ("enforced per request at dispatch time, not here") is now +* discharged by that codec step. +* +* No 2025-era traffic ever touches this module, so requiredness here is +* bare and spec-exact (the shared-schema `.catch` hazards do not apply). +* +* SPEC-CURRENCY RE-SEAL (2026-07-17): the 2026-07-28 revision was re-sealed +* upstream by spec PR #3002 (commit 71e30695, merged 2026-07-15 — after the +* previous anchor pin f68d864a): the envelope's `clientInfo` demoted from +* required to SHOULD, and `DiscoverResult.serverInfo` moved from the result +* body to the new `ResultMetaObject` key +* `_meta['io.modelcontextprotocol/serverInfo']` (optional on every result). +* The shapes below are the re-sealed anchor, exactly — no pre-#3002 shape is +* modeled anywhere (per ruling: the final revision is the only 2026-07-28). +*/ +function build() { + const JSONValueSchema$1 = lazy(() => schemas_union([ + schemas_string(), + schemas_number(), + schemas_boolean(), + schemas_null(), + schemas_record(schemas_string(), JSONValueSchema$1), + schemas_array(JSONValueSchema$1) + ])); + const JSONObjectSchema$1 = schemas_record(schemas_string(), JSONValueSchema$1); + /** + * A progress token, used to associate progress notifications with the original request. + */ + const ProgressTokenSchema$1 = schemas_union([schemas_string(), schemas_number().int()]); + /** + * An opaque token used to represent a cursor for pagination. + */ + const CursorSchema$1 = schemas_string(); + /** + * A uniquely identifying ID for a request in JSON-RPC. + */ + const RequestIdSchema$1 = schemas_union([schemas_string(), schemas_number().int()]); + /** + * The sender or recipient of messages and data in a conversation. + */ + const RoleSchema$1 = schemas_enum(["user", "assistant"]); + /** + * The severity of a log message. + */ + const LoggingLevelSchema$1 = schemas_enum([ + "debug", + "info", + "notice", + "warning", + "error", + "critical", + "alert", + "emergency" + ]); + /** + * A Zod schema for validating Base64 strings that is more performant and + * robust for very large inputs than the default regex-based check. It avoids + * stack overflows by using the native `atob` function for validation. + */ + const Base64Schema = schemas_string().refine((val) => { + try { + atob(val); + return true; + } catch { + return false; + } + }, { message: "Invalid Base64 string" }); + /** @deprecated 2025-11-25 wire vocabulary with no SDK runtime; kept importable for interoperability only. */ + const TaskMetadataSchema$1 = schemas_object({ ttl: schemas_number().optional() }); + /** @deprecated 2025-11-25 wire vocabulary with no SDK runtime; kept importable for interoperability only. */ + const RelatedTaskMetadataSchema$1 = schemas_object({ taskId: schemas_string() }); + const RequestMetaSchema$1 = looseObject({ + progressToken: ProgressTokenSchema$1.optional(), + "io.modelcontextprotocol/related-task": RelatedTaskMetadataSchema$1.optional() + }); + const BaseRequestParamsSchema$1 = schemas_object({ _meta: RequestMetaSchema$1.optional() }); + /** @deprecated 2025-11-25 wire vocabulary with no SDK runtime; kept importable for interoperability only. */ + const TaskAugmentedRequestParamsSchema$1 = BaseRequestParamsSchema$1.extend({ task: TaskMetadataSchema$1.optional() }); + const NotificationsParamsSchema$1 = schemas_object({ _meta: RequestMetaSchema$1.optional() }); + const NotificationSchema$1 = schemas_object({ + method: schemas_string(), + params: NotificationsParamsSchema$1.loose().optional() + }); + const IconSchema$1 = schemas_object({ + src: schemas_string(), + mimeType: schemas_string().optional(), + sizes: schemas_array(schemas_string()).optional(), + theme: schemas_enum(["light", "dark"]).optional() + }); + const IconsSchema$1 = schemas_object({ icons: schemas_array(IconSchema$1).optional() }); + const BaseMetadataSchema$1 = schemas_object({ + name: schemas_string(), + title: schemas_string().optional() + }); + const ImplementationSchema$1 = BaseMetadataSchema$1.extend({ + ...BaseMetadataSchema$1.shape, + ...IconsSchema$1.shape, + version: schemas_string(), + websiteUrl: schemas_string().optional(), + description: schemas_string().optional() + }); + const FormElicitationCapabilitySchema = intersection(schemas_object({ applyDefaults: schemas_boolean().optional() }), JSONObjectSchema$1); + const ElicitationCapabilitySchema = preprocess((value) => { + if (value && typeof value === "object" && !Array.isArray(value) && Object.keys(value).length === 0) return { form: {} }; + return value; + }, intersection(schemas_object({ + form: FormElicitationCapabilitySchema.optional(), + url: JSONObjectSchema$1.optional() + }), JSONObjectSchema$1.optional())); + /** @deprecated 2025-11-25 wire vocabulary with no SDK runtime; kept importable for interoperability only. */ + const ClientTasksCapabilitySchema$1 = looseObject({ + list: JSONObjectSchema$1.optional(), + cancel: JSONObjectSchema$1.optional(), + requests: looseObject({ + sampling: looseObject({ createMessage: JSONObjectSchema$1.optional() }).optional(), + elicitation: looseObject({ create: JSONObjectSchema$1.optional() }).optional() + }).optional() + }); + /** @deprecated 2025-11-25 wire vocabulary with no SDK runtime; kept importable for interoperability only. */ + const ServerTasksCapabilitySchema$1 = looseObject({ + list: JSONObjectSchema$1.optional(), + cancel: JSONObjectSchema$1.optional(), + requests: looseObject({ tools: looseObject({ call: JSONObjectSchema$1.optional() }).optional() }).optional() + }); + const ClientCapabilitiesSchema$1 = schemas_object({ + experimental: schemas_record(schemas_string(), JSONObjectSchema$1).optional(), + sampling: schemas_object({ + context: JSONObjectSchema$1.optional(), + tools: JSONObjectSchema$1.optional() + }).optional(), + elicitation: ElicitationCapabilitySchema.optional(), + roots: schemas_object({ listChanged: schemas_boolean().optional() }).optional(), + tasks: ClientTasksCapabilitySchema$1.optional(), + extensions: schemas_record(schemas_string(), JSONObjectSchema$1).optional() + }); + const ServerCapabilitiesSchema$1 = schemas_object({ + experimental: schemas_record(schemas_string(), JSONObjectSchema$1).optional(), + logging: JSONObjectSchema$1.optional(), + completions: JSONObjectSchema$1.optional(), + prompts: schemas_object({ listChanged: schemas_boolean().optional() }).optional(), + resources: schemas_object({ + subscribe: schemas_boolean().optional(), + listChanged: schemas_boolean().optional() + }).optional(), + tools: schemas_object({ listChanged: schemas_boolean().optional() }).optional(), + tasks: ServerTasksCapabilitySchema$1.optional(), + extensions: schemas_record(schemas_string(), JSONObjectSchema$1).optional() + }); + const ProgressSchema$1 = schemas_object({ + progress: schemas_number(), + total: schemas_optional(schemas_number()), + message: schemas_optional(schemas_string()) + }); + const ProgressNotificationParamsSchema$1 = schemas_object({ + ...NotificationsParamsSchema$1.shape, + ...ProgressSchema$1.shape, + progressToken: ProgressTokenSchema$1 + }); + const ProgressNotificationSchema$1 = NotificationSchema$1.extend({ + method: literal("notifications/progress"), + params: ProgressNotificationParamsSchema$1 + }); + const LoggingMessageNotificationParamsSchema$1 = NotificationsParamsSchema$1.extend({ + level: LoggingLevelSchema$1, + logger: schemas_string().optional(), + data: unknown() + }); + const LoggingMessageNotificationSchema$1 = NotificationSchema$1.extend({ + method: literal("notifications/message"), + params: LoggingMessageNotificationParamsSchema$1 + }); + const ResourceContentsSchema$1 = schemas_object({ + uri: schemas_string(), + mimeType: schemas_optional(schemas_string()), + _meta: schemas_record(schemas_string(), unknown()).optional() + }); + const TextResourceContentsSchema$1 = ResourceContentsSchema$1.extend({ text: schemas_string() }); + const BlobResourceContentsSchema$1 = ResourceContentsSchema$1.extend({ blob: Base64Schema }); + const AnnotationsSchema$1 = schemas_object({ + audience: schemas_array(RoleSchema$1).optional(), + priority: schemas_number().min(0).max(1).optional(), + lastModified: iso_datetime({ offset: true }).optional() + }); + const ResourceSchema$1 = schemas_object({ + ...BaseMetadataSchema$1.shape, + ...IconsSchema$1.shape, + uri: schemas_string(), + description: schemas_optional(schemas_string()), + mimeType: schemas_optional(schemas_string()), + size: schemas_optional(schemas_number()), + annotations: AnnotationsSchema$1.optional(), + _meta: schemas_optional(looseObject({})) + }); + const ResourceTemplateSchema$1 = schemas_object({ + ...BaseMetadataSchema$1.shape, + ...IconsSchema$1.shape, + uriTemplate: schemas_string(), + description: schemas_optional(schemas_string()), + mimeType: schemas_optional(schemas_string()), + annotations: AnnotationsSchema$1.optional(), + _meta: schemas_optional(looseObject({})) + }); + const ResourceListChangedNotificationSchema$1 = NotificationSchema$1.extend({ + method: literal("notifications/resources/list_changed"), + params: NotificationsParamsSchema$1.optional() + }); + const ResourceUpdatedNotificationParamsSchema$1 = NotificationsParamsSchema$1.extend({ uri: schemas_string() }); + const ResourceUpdatedNotificationSchema$1 = NotificationSchema$1.extend({ + method: literal("notifications/resources/updated"), + params: ResourceUpdatedNotificationParamsSchema$1 + }); + const PromptArgumentSchema$1 = schemas_object({ + name: schemas_string(), + description: schemas_optional(schemas_string()), + required: schemas_optional(schemas_boolean()) + }); + const PromptSchema$1 = schemas_object({ + ...BaseMetadataSchema$1.shape, + ...IconsSchema$1.shape, + description: schemas_optional(schemas_string()), + arguments: schemas_optional(schemas_array(PromptArgumentSchema$1)), + _meta: schemas_optional(looseObject({})) + }); + const PromptListChangedNotificationSchema$1 = NotificationSchema$1.extend({ + method: literal("notifications/prompts/list_changed"), + params: NotificationsParamsSchema$1.optional() + }); + const TextContentSchema$1 = schemas_object({ + type: literal("text"), + text: schemas_string(), + annotations: AnnotationsSchema$1.optional(), + _meta: schemas_record(schemas_string(), unknown()).optional() + }); + const ImageContentSchema$1 = schemas_object({ + type: literal("image"), + data: Base64Schema, + mimeType: schemas_string(), + annotations: AnnotationsSchema$1.optional(), + _meta: schemas_record(schemas_string(), unknown()).optional() + }); + const AudioContentSchema$1 = schemas_object({ + type: literal("audio"), + data: Base64Schema, + mimeType: schemas_string(), + annotations: AnnotationsSchema$1.optional(), + _meta: schemas_record(schemas_string(), unknown()).optional() + }); + const ToolUseContentSchema$1 = schemas_object({ + type: literal("tool_use"), + name: schemas_string(), + id: schemas_string(), + input: schemas_record(schemas_string(), unknown()), + _meta: schemas_record(schemas_string(), unknown()).optional() + }); + const EmbeddedResourceSchema$1 = schemas_object({ + type: literal("resource"), + resource: schemas_union([TextResourceContentsSchema$1, BlobResourceContentsSchema$1]), + annotations: AnnotationsSchema$1.optional(), + _meta: schemas_record(schemas_string(), unknown()).optional() + }); + const ResourceLinkSchema$1 = ResourceSchema$1.extend({ type: literal("resource_link") }); + const ContentBlockSchema$1 = schemas_union([ + TextContentSchema$1, + ImageContentSchema$1, + AudioContentSchema$1, + ResourceLinkSchema$1, + EmbeddedResourceSchema$1 + ]); + const PromptMessageSchema$1 = schemas_object({ + role: RoleSchema$1, + content: ContentBlockSchema$1 + }); + const ToolAnnotationsSchema$1 = schemas_object({ + title: schemas_string().optional(), + readOnlyHint: schemas_boolean().optional(), + destructiveHint: schemas_boolean().optional(), + idempotentHint: schemas_boolean().optional(), + openWorldHint: schemas_boolean().optional() + }); + const ToolListChangedNotificationSchema$1 = NotificationSchema$1.extend({ + method: literal("notifications/tools/list_changed"), + params: NotificationsParamsSchema$1.optional() + }); + const ModelHintSchema$1 = schemas_object({ name: schemas_string().optional() }); + const ModelPreferencesSchema$1 = schemas_object({ + hints: schemas_array(ModelHintSchema$1).optional(), + costPriority: schemas_number().min(0).max(1).optional(), + speedPriority: schemas_number().min(0).max(1).optional(), + intelligencePriority: schemas_number().min(0).max(1).optional() + }); + const ToolChoiceSchema$1 = schemas_object({ mode: schemas_enum([ + "auto", + "required", + "none" + ]).optional() }); + const BooleanSchemaSchema$1 = schemas_object({ + type: literal("boolean"), + title: schemas_string().optional(), + description: schemas_string().optional(), + default: schemas_boolean().optional() + }); + const StringSchemaSchema$1 = schemas_object({ + type: literal("string"), + title: schemas_string().optional(), + description: schemas_string().optional(), + minLength: schemas_number().optional(), + maxLength: schemas_number().optional(), + format: schemas_enum([ + "email", + "uri", + "date", + "date-time" + ]).optional(), + default: schemas_string().optional() + }); + const NumberSchemaSchema$1 = schemas_object({ + type: schemas_enum(["number", "integer"]), + title: schemas_string().optional(), + description: schemas_string().optional(), + minimum: schemas_number().optional(), + maximum: schemas_number().optional(), + default: schemas_number().optional() + }); + const UntitledSingleSelectEnumSchemaSchema$1 = schemas_object({ + type: literal("string"), + title: schemas_string().optional(), + description: schemas_string().optional(), + enum: schemas_array(schemas_string()), + default: schemas_string().optional() + }); + const TitledSingleSelectEnumSchemaSchema$1 = schemas_object({ + type: literal("string"), + title: schemas_string().optional(), + description: schemas_string().optional(), + oneOf: schemas_array(schemas_object({ + const: schemas_string(), + title: schemas_string() + })), + default: schemas_string().optional() + }); + const LegacyTitledEnumSchemaSchema$1 = schemas_object({ + type: literal("string"), + title: schemas_string().optional(), + description: schemas_string().optional(), + enum: schemas_array(schemas_string()), + enumNames: schemas_array(schemas_string()).optional(), + default: schemas_string().optional() + }); + const SingleSelectEnumSchemaSchema$1 = schemas_union([UntitledSingleSelectEnumSchemaSchema$1, TitledSingleSelectEnumSchemaSchema$1]); + const UntitledMultiSelectEnumSchemaSchema$1 = schemas_object({ + type: literal("array"), + title: schemas_string().optional(), + description: schemas_string().optional(), + minItems: schemas_number().optional(), + maxItems: schemas_number().optional(), + items: schemas_object({ + type: literal("string"), + enum: schemas_array(schemas_string()) + }), + default: schemas_array(schemas_string()).optional() + }); + const TitledMultiSelectEnumSchemaSchema$1 = schemas_object({ + type: literal("array"), + title: schemas_string().optional(), + description: schemas_string().optional(), + minItems: schemas_number().optional(), + maxItems: schemas_number().optional(), + items: schemas_object({ anyOf: schemas_array(schemas_object({ + const: schemas_string(), + title: schemas_string() + })) }), + default: schemas_array(schemas_string()).optional() + }); + const MultiSelectEnumSchemaSchema$1 = schemas_union([UntitledMultiSelectEnumSchemaSchema$1, TitledMultiSelectEnumSchemaSchema$1]); + const EnumSchemaSchema$1 = schemas_union([ + LegacyTitledEnumSchemaSchema$1, + SingleSelectEnumSchemaSchema$1, + MultiSelectEnumSchemaSchema$1 + ]); + const PrimitiveSchemaDefinitionSchema$1 = schemas_union([ + EnumSchemaSchema$1, + BooleanSchemaSchema$1, + StringSchemaSchema$1, + NumberSchemaSchema$1 + ]); + const ElicitRequestFormParamsSchema$1 = TaskAugmentedRequestParamsSchema$1.extend({ + mode: literal("form").optional(), + message: schemas_string(), + requestedSchema: schemas_object({ + type: literal("object"), + properties: schemas_record(schemas_string(), PrimitiveSchemaDefinitionSchema$1), + required: schemas_array(schemas_string()).optional() + }).catchall(unknown()) + }); + const ResourceTemplateReferenceSchema$1 = schemas_object({ + type: literal("ref/resource"), + uri: schemas_string() + }); + const PromptReferenceSchema$1 = schemas_object({ + type: literal("ref/prompt"), + name: schemas_string() + }); + const RootSchema$1 = schemas_object({ + uri: schemas_string().startsWith("file://"), + name: schemas_string().optional(), + _meta: schemas_record(schemas_string(), unknown()).optional() + }); + const sharedClientCapabilityShape = ClientCapabilitiesSchema$1.shape; + const ClientCapabilities2026Schema = schemas_object({ + experimental: sharedClientCapabilityShape.experimental, + sampling: sharedClientCapabilityShape.sampling, + elicitation: sharedClientCapabilityShape.elicitation, + roots: sharedClientCapabilityShape.roots, + extensions: sharedClientCapabilityShape.extensions + }); + const sharedServerCapabilityShape = ServerCapabilitiesSchema$1.shape; + const ServerCapabilities2026Schema = schemas_object({ + experimental: sharedServerCapabilityShape.experimental, + logging: sharedServerCapabilityShape.logging, + completions: sharedServerCapabilityShape.completions, + prompts: sharedServerCapabilityShape.prompts, + resources: sharedServerCapabilityShape.resources, + tools: sharedServerCapabilityShape.tools, + extensions: sharedServerCapabilityShape.extensions + }); + /** + * The per-request `_meta` envelope carried by every request under protocol revision + * 2026-07-28: the protocol version governing the request, the client implementation + * info, and the client's capabilities — declared per request rather than once at + * initialization — plus the optional log-level opt-in. + * + * This schema models the complete envelope on its own (loose: foreign keys + * pass through - the lift extracts exactly the reserved keys, so enforcement + * never sees extension material). Requiredness is enforced per request at + * dispatch time by the 2026-era codec's `checkInboundEnvelope` step. + */ + const RequestMetaEnvelopeSchema = looseObject({ + progressToken: ProgressTokenSchema$1.optional(), + [auth_CUe6YdwF_PROTOCOL_VERSION_META_KEY]: schemas_string(), + [auth_CUe6YdwF_CLIENT_INFO_META_KEY]: ImplementationSchema$1.optional(), + [auth_CUe6YdwF_CLIENT_CAPABILITIES_META_KEY]: ClientCapabilities2026Schema, + [LOG_LEVEL_META_KEY]: LoggingLevelSchema$1.optional() + }); + /** 2026-era Tool: anchor-exact — no `execution` (deleted vocabulary). */ + const ToolSchema$1 = schemas_object({ + ...BaseMetadataSchema$1.shape, + ...IconsSchema$1.shape, + description: schemas_string().optional(), + inputSchema: looseObject({ + $schema: schemas_string().optional(), + type: literal("object") + }), + outputSchema: looseObject({ $schema: schemas_string().optional() }).optional(), + annotations: ToolAnnotationsSchema$1.optional(), + _meta: schemas_record(schemas_string(), unknown()).optional() + }); + /** 2026-era ToolResultContent (anchor-exact: `structuredContent?: unknown`). */ + const ToolResultContentSchema$1 = schemas_object({ + type: literal("tool_result"), + toolUseId: schemas_string(), + content: schemas_array(ContentBlockSchema$1), + structuredContent: unknown().optional(), + isError: schemas_boolean().optional(), + _meta: schemas_record(schemas_string(), unknown()).optional() + }); + /** 2026-era sampling content union (composes the forked tool-result shape). */ + const SamplingMessageContentBlockSchema$1 = schemas_union([ + TextContentSchema$1, + ImageContentSchema$1, + AudioContentSchema$1, + ToolUseContentSchema$1, + ToolResultContentSchema$1 + ]); + /** 2026-era SamplingMessage (anchor-exact: single block or array). */ + const SamplingMessageSchema$1 = schemas_object({ + role: RoleSchema$1, + content: schemas_union([SamplingMessageContentBlockSchema$1, schemas_array(SamplingMessageContentBlockSchema$1)]), + _meta: schemas_record(schemas_string(), unknown()).optional() + }); + /** Open union per the anchor: 'complete' | 'input_required' | string. */ + const ResultTypeSchema = schemas_string(); + /** + * Result `_meta` (anchor `ResultMetaObject`, added by spec PR #3002): + * loose, with the serverInfo key typed when present; the outbound stamp + * is the encode contract's `stampServerInfoMeta` step. + */ + const ResultMetaSchema = looseObject({ [auth_CUe6YdwF_SERVER_INFO_META_KEY]: ImplementationSchema$1.optional().catch(void 0) }); + const wireMeta = ResultMetaSchema.optional(); + function wireResult(shape) { + return looseObject({ + _meta: wireMeta, + resultType: ResultTypeSchema.default("complete"), + ...shape + }); + } + const ResultSchema$1 = wireResult({}); + const PaginatedResultSchema$1 = wireResult({ nextCursor: CursorSchema$1.optional() }); + const CallToolResultSchema$1 = wireResult({ + content: schemas_array(ContentBlockSchema$1), + structuredContent: unknown().optional(), + isError: schemas_boolean().optional() + }); + const ListToolsResultSchema$1 = wireResult({ + ttlMs: schemas_number().int().min(0), + cacheScope: schemas_enum(["public", "private"]), + tools: schemas_array(ToolSchema$1), + nextCursor: CursorSchema$1.optional() + }); + const ListPromptsResultSchema$1 = wireResult({ + ttlMs: schemas_number().int().min(0), + cacheScope: schemas_enum(["public", "private"]), + prompts: schemas_array(PromptSchema$1), + nextCursor: CursorSchema$1.optional() + }); + const GetPromptResultSchema$1 = wireResult({ + description: schemas_string().optional(), + messages: schemas_array(PromptMessageSchema$1) + }); + const ListResourcesResultSchema$1 = wireResult({ + ttlMs: schemas_number().int().min(0), + cacheScope: schemas_enum(["public", "private"]), + resources: schemas_array(ResourceSchema$1), + nextCursor: CursorSchema$1.optional() + }); + const ListResourceTemplatesResultSchema$1 = wireResult({ + ttlMs: schemas_number().int().min(0), + cacheScope: schemas_enum(["public", "private"]), + resourceTemplates: schemas_array(ResourceTemplateSchema$1), + nextCursor: CursorSchema$1.optional() + }); + const ReadResourceResultSchema$1 = wireResult({ + ttlMs: schemas_number().int().min(0), + cacheScope: schemas_enum(["public", "private"]), + contents: schemas_array(schemas_union([TextResourceContentsSchema$1, BlobResourceContentsSchema$1])) + }); + const CompleteResultSchema$1 = wireResult({ completion: schemas_object({ + values: schemas_array(schemas_string()).max(100), + total: schemas_number().int().optional(), + hasMore: schemas_boolean().optional() + }).loose() }); + /** CacheableResult (SEP-2549): ttlMs and cacheScope REQUIRED per the anchor. */ + const CacheableResultSchema = wireResult({ + ttlMs: schemas_number().int().min(0), + cacheScope: schemas_enum(["public", "private"]) + }); + const DiscoverResultSchema$1 = wireResult({ + ttlMs: schemas_number().int().min(0).catch(0), + cacheScope: schemas_enum(["public", "private"]).catch("private"), + supportedVersions: schemas_array(schemas_string()), + capabilities: ServerCapabilities2026Schema, + instructions: schemas_string().optional() + }); + /** 2026-era CreateMessageRequestParams (anchor-exact: forked SamplingMessage/Tool, no task augmentation). */ + const CreateMessageRequestParamsSchema$1 = schemas_object({ + messages: schemas_array(SamplingMessageSchema$1), + modelPreferences: ModelPreferencesSchema$1.optional(), + systemPrompt: schemas_string().optional(), + includeContext: schemas_enum([ + "none", + "thisServer", + "allServers" + ]).optional(), + temperature: schemas_number().optional(), + maxTokens: schemas_number().int(), + stopSequences: schemas_array(schemas_string()).optional(), + metadata: JSONObjectSchema$1.optional(), + tools: schemas_array(ToolSchema$1).optional(), + toolChoice: ToolChoiceSchema$1.optional() + }); + /** 2026-era embedded sampling request (de-JSON-RPC'd). */ + const CreateMessageRequestSchema$1 = schemas_object({ + method: literal("sampling/createMessage"), + params: CreateMessageRequestParamsSchema$1 + }); + /** + * 2026-era embedded roots listing request (de-JSON-RPC'd). Embedded input + * requests do NOT carry the per-request `_meta` envelope on this revision — + * the anchor declares a bare optional `_meta` on `params`. + */ + const ListRootsRequestSchema$1 = schemas_object({ + method: literal("roots/list"), + params: schemas_object({ _meta: schemas_record(schemas_string(), unknown()).optional() }).optional() + }); + /** 2026-era embedded sampling response (anchor-exact: extends the forked SamplingMessage). */ + const CreateMessageResultSchema$1 = schemas_object({ + ...SamplingMessageSchema$1.shape, + model: schemas_string(), + stopReason: schemas_string().optional() + }); + /** 2026-era embedded roots listing response (anchor-exact: bare `roots` array). */ + const ListRootsResultSchema$1 = schemas_object({ roots: schemas_array(RootSchema$1) }); + /** 2026-era embedded elicitation response (anchor-exact: bare result, restricted content value types). */ + const ElicitResultSchema$1 = schemas_object({ + action: schemas_enum([ + "accept", + "decline", + "cancel" + ]), + content: schemas_record(schemas_string(), schemas_union([ + schemas_string(), + schemas_number(), + schemas_boolean(), + schemas_array(schemas_string()) + ])).optional() + }); + /** + * 2026-era URL-mode elicitation params (anchor-exact fork): the draft removed + * `elicitationId` (and the `notifications/elicitation/complete` channel it + * keyed) — the shared schema keeps the field because it is required on the + * frozen 2025-11-25 revision. + */ + const ElicitRequestURLParamsSchema$1 = schemas_object({ + mode: literal("url"), + message: schemas_string(), + url: schemas_string().url() + }); + /** 2026-era elicitation params (form mode is revision-identical; URL mode is the fork above). */ + const ElicitRequestParamsSchema$1 = schemas_union([ElicitRequestFormParamsSchema$1, ElicitRequestURLParamsSchema$1]); + /** 2026-era embedded elicitation request (de-JSON-RPC'd; see the URL-mode fork above). */ + const ElicitRequestSchema$1 = schemas_object({ + method: literal("elicitation/create"), + params: ElicitRequestParamsSchema$1 + }); + /** A single embedded input request (one of the three demoted server→client requests). */ + const InputRequestSchema = schemas_union([ + CreateMessageRequestSchema$1, + ListRootsRequestSchema$1, + ElicitRequestSchema$1 + ]); + /** A single embedded input response — the BARE result union (never a `{method, result}` wrapper). */ + const InputResponseSchema = schemas_union([ + CreateMessageResultSchema$1, + ListRootsResultSchema$1, + ElicitResultSchema$1 + ]); + /** Map of embedded input requests, keyed by server-assigned identifiers. */ + const InputRequestsSchema = schemas_record(schemas_string(), InputRequestSchema); + /** Map of embedded input responses, keyed by the corresponding request identifiers. */ + const InputResponsesSchema = schemas_record(schemas_string(), InputResponseSchema); + /** + * The wire InputRequiredResult: `resultType: 'input_required'` plus at least + * one of `inputRequests` / `requestState` (the at-least-one rule is enforced + * at the server seam, not by this parse shape). + */ + const InputRequiredResultSchema = wireResult({ + inputRequests: InputRequestsSchema.optional(), + requestState: schemas_string().optional() + }); + /** The retry-channel members carried by client-initiated requests on this revision. */ + const retryParamsShape = { + inputResponses: InputResponsesSchema.optional(), + requestState: schemas_string().optional() + }; + /** Anchor InputResponseRequestParams: the retry channel on top of the required request `_meta` envelope. */ + const InputResponseRequestParamsSchema = schemas_object({ + _meta: RequestMetaEnvelopeSchema, + ...retryParamsShape + }); + /** Post-lift request `_meta` (progressToken + extension keys; loose). */ + const DispatchRequestMetaSchema = looseObject({ progressToken: ProgressTokenSchema$1.optional() }); + function wireRequest(method, paramsShape) { + return schemas_object({ + method: literal(method), + params: schemas_object({ + _meta: RequestMetaEnvelopeSchema, + ...paramsShape + }) + }); + } + function dispatchRequest(method, paramsShape) { + return schemas_object({ + method: literal(method), + params: schemas_object({ + _meta: DispatchRequestMetaSchema.optional(), + ...paramsShape + }).optional() + }); + } + const callToolParamsShape = { + name: schemas_string(), + arguments: schemas_record(schemas_string(), unknown()).optional(), + ...retryParamsShape + }; + const paginatedParamsShape = { cursor: CursorSchema$1.optional() }; + const CallToolRequestSchema$1 = wireRequest("tools/call", callToolParamsShape); + const ListToolsRequestSchema$1 = wireRequest("tools/list", paginatedParamsShape); + const ListPromptsRequestSchema$1 = wireRequest("prompts/list", paginatedParamsShape); + const GetPromptRequestSchema$1 = wireRequest("prompts/get", { + name: schemas_string(), + arguments: schemas_record(schemas_string(), schemas_string()).optional(), + ...retryParamsShape + }); + const ListResourcesRequestSchema$1 = wireRequest("resources/list", paginatedParamsShape); + const ListResourceTemplatesRequestSchema$1 = wireRequest("resources/templates/list", paginatedParamsShape); + const ReadResourceRequestSchema$1 = wireRequest("resources/read", { + uri: schemas_string(), + ...retryParamsShape + }); + const completeParamsShape = { + ref: schemas_union([PromptReferenceSchema$1, ResourceTemplateReferenceSchema$1]), + argument: schemas_object({ + name: schemas_string(), + value: schemas_string() + }), + context: schemas_object({ arguments: schemas_record(schemas_string(), schemas_string()).optional() }).optional() + }; + const CompleteRequestSchema$1 = wireRequest("completion/complete", completeParamsShape); + const DiscoverRequestSchema$1 = wireRequest("server/discover", {}); + /** Anchor SubscriptionFilter (2026-only). */ + const SubscriptionFilterSchema$1 = schemas_object({ + toolsListChanged: schemas_boolean().optional(), + promptsListChanged: schemas_boolean().optional(), + resourcesListChanged: schemas_boolean().optional(), + resourceSubscriptions: schemas_array(schemas_string()).optional() + }); + const subscriptionsListenParamsShape = { notifications: SubscriptionFilterSchema$1 }; + const SubscriptionsListenRequestSchema$1 = wireRequest("subscriptions/listen", subscriptionsListenParamsShape); + /** + * Anchor SubscriptionsListenResultMeta — required subscriptionId stamp on + * the graceful-close result. Extends `ResultMetaObject` since spec PR + * #3002 (composed, so the serverInfo key and its leniency stay single-sourced). + */ + const SubscriptionsListenResultMetaSchema$1 = ResultMetaSchema.extend({ "io.modelcontextprotocol/subscriptionId": RequestIdSchema$1 }); + /** + * Anchor SubscriptionsListenResult (2026-only). The empty `subscriptions/listen` + * response signalling that the subscription has ended gracefully (server + * shutdown). An abrupt transport close carries no response — the client treats + * stream-close-without-result as a disconnect. + */ + const SubscriptionsListenResultSchema$1 = looseObject({ + _meta: SubscriptionsListenResultMetaSchema$1, + resultType: ResultTypeSchema.default("complete") + }); + /** Dispatch (post-lift) request schemas, keyed by method — registry-internal. */ + const dispatchRequestSchemas = { + "tools/call": dispatchRequest("tools/call", callToolParamsShape), + "tools/list": dispatchRequest("tools/list", paginatedParamsShape), + "prompts/get": dispatchRequest("prompts/get", { + name: schemas_string(), + arguments: schemas_record(schemas_string(), schemas_string()).optional() + }), + "prompts/list": dispatchRequest("prompts/list", paginatedParamsShape), + "resources/list": dispatchRequest("resources/list", paginatedParamsShape), + "resources/templates/list": dispatchRequest("resources/templates/list", paginatedParamsShape), + "resources/read": dispatchRequest("resources/read", { uri: schemas_string() }), + "completion/complete": dispatchRequest("completion/complete", completeParamsShape), + "server/discover": dispatchRequest("server/discover", {}), + "subscriptions/listen": dispatchRequest("subscriptions/listen", subscriptionsListenParamsShape) + }; + /** Dispatch (post-lift) result schemas, keyed by method — what the funnel + * validates AFTER `decodeResult` consumed `resultType`. */ + function liftedResult(shape) { + return looseObject({ + _meta: wireMeta, + ...shape + }); + } + const dispatchResultSchemas = { + "tools/call": liftedResult({ + content: schemas_array(ContentBlockSchema$1), + structuredContent: unknown().optional(), + isError: schemas_boolean().optional() + }), + "tools/list": liftedResult({ + ttlMs: schemas_number().int().min(0), + cacheScope: schemas_enum(["public", "private"]), + tools: schemas_array(ToolSchema$1), + nextCursor: CursorSchema$1.optional() + }), + "prompts/get": liftedResult({ + description: schemas_string().optional(), + messages: schemas_array(PromptMessageSchema$1) + }), + "prompts/list": liftedResult({ + ttlMs: schemas_number().int().min(0), + cacheScope: schemas_enum(["public", "private"]), + prompts: schemas_array(PromptSchema$1), + nextCursor: CursorSchema$1.optional() + }), + "resources/list": liftedResult({ + ttlMs: schemas_number().int().min(0), + cacheScope: schemas_enum(["public", "private"]), + resources: schemas_array(ResourceSchema$1), + nextCursor: CursorSchema$1.optional() + }), + "resources/templates/list": liftedResult({ + ttlMs: schemas_number().int().min(0), + cacheScope: schemas_enum(["public", "private"]), + resourceTemplates: schemas_array(ResourceTemplateSchema$1), + nextCursor: CursorSchema$1.optional() + }), + "resources/read": liftedResult({ + ttlMs: schemas_number().int().min(0), + cacheScope: schemas_enum(["public", "private"]), + contents: schemas_array(schemas_union([TextResourceContentsSchema$1, BlobResourceContentsSchema$1])) + }), + "completion/complete": liftedResult({ completion: schemas_object({ + values: schemas_array(schemas_string()).max(100), + total: schemas_number().int().optional(), + hasMore: schemas_boolean().optional() + }).loose() }), + "server/discover": liftedResult({ + ttlMs: schemas_number().int().min(0).catch(0), + cacheScope: schemas_enum(["public", "private"]).catch("private"), + supportedVersions: schemas_array(schemas_string()), + capabilities: ServerCapabilities2026Schema, + instructions: schemas_string().optional() + }), + "subscriptions/listen": liftedResult({}) + }; + /** + * Notification `_meta` (anchor `NotificationMetaObject`): loose, with the + * subscriptions/listen demux key typed when present. Only the anchor-exact + * SHAPE is modeled here — listen delivery itself (filter gating, demux, + * teardown) is #14 scope and not implemented by this module. + */ + const NotificationMetaSchema = looseObject({ "io.modelcontextprotocol/subscriptionId": RequestIdSchema$1.optional() }); + /** Anchor SubscriptionsAcknowledgedNotification (2026-only). */ + const SubscriptionsAcknowledgedNotificationSchema$1 = schemas_object({ + method: literal("notifications/subscriptions/acknowledged"), + params: schemas_object({ + _meta: NotificationMetaSchema.optional(), + notifications: SubscriptionFilterSchema$1 + }) + }); + /** + * 2026-era `notifications/cancelled` params (anchor-exact fork): `requestId` + * is REQUIRED on this revision — the shared schema keeps it optional because + * the frozen 2025-11-25 shape declares it optional (task cancellation goes + * through `tasks/cancel` there). Requiredness is bare because no 2025-era + * traffic touches this module. + */ + const CancelledNotificationParamsSchema$1 = schemas_object({ + _meta: NotificationMetaSchema.optional(), + requestId: RequestIdSchema$1, + reason: schemas_string().optional() + }); + /** 2026-era `notifications/cancelled` (see the params fork above). */ + const CancelledNotificationSchema$1 = schemas_object({ + method: literal("notifications/cancelled"), + params: CancelledNotificationParamsSchema$1 + }); + const notificationSchemas2026 = { + "notifications/cancelled": CancelledNotificationSchema$1, + "notifications/progress": ProgressNotificationSchema$1, + "notifications/message": LoggingMessageNotificationSchema$1, + "notifications/resources/updated": ResourceUpdatedNotificationSchema$1, + "notifications/resources/list_changed": ResourceListChangedNotificationSchema$1, + "notifications/tools/list_changed": ToolListChangedNotificationSchema$1, + "notifications/prompts/list_changed": PromptListChangedNotificationSchema$1, + "notifications/subscriptions/acknowledged": SubscriptionsAcknowledgedNotificationSchema$1 + }; + const wireResultResponse = (result) => schemas_object({ + jsonrpc: literal("2.0"), + id: schemas_union([schemas_string(), schemas_number().int()]), + result + }).strict(); + return { + JSONValueSchema: JSONValueSchema$1, + JSONObjectSchema: JSONObjectSchema$1, + ProgressTokenSchema: ProgressTokenSchema$1, + CursorSchema: CursorSchema$1, + RequestIdSchema: RequestIdSchema$1, + RoleSchema: RoleSchema$1, + LoggingLevelSchema: LoggingLevelSchema$1, + TaskMetadataSchema: TaskMetadataSchema$1, + RelatedTaskMetadataSchema: RelatedTaskMetadataSchema$1, + RequestMetaSchema: RequestMetaSchema$1, + BaseRequestParamsSchema: BaseRequestParamsSchema$1, + TaskAugmentedRequestParamsSchema: TaskAugmentedRequestParamsSchema$1, + NotificationsParamsSchema: NotificationsParamsSchema$1, + NotificationSchema: NotificationSchema$1, + IconSchema: IconSchema$1, + IconsSchema: IconsSchema$1, + BaseMetadataSchema: BaseMetadataSchema$1, + ImplementationSchema: ImplementationSchema$1, + ClientTasksCapabilitySchema: ClientTasksCapabilitySchema$1, + ServerTasksCapabilitySchema: ServerTasksCapabilitySchema$1, + ClientCapabilitiesSchema: ClientCapabilitiesSchema$1, + ServerCapabilitiesSchema: ServerCapabilitiesSchema$1, + ProgressSchema: ProgressSchema$1, + ProgressNotificationParamsSchema: ProgressNotificationParamsSchema$1, + ProgressNotificationSchema: ProgressNotificationSchema$1, + LoggingMessageNotificationParamsSchema: LoggingMessageNotificationParamsSchema$1, + LoggingMessageNotificationSchema: LoggingMessageNotificationSchema$1, + ResourceContentsSchema: ResourceContentsSchema$1, + TextResourceContentsSchema: TextResourceContentsSchema$1, + BlobResourceContentsSchema: BlobResourceContentsSchema$1, + AnnotationsSchema: AnnotationsSchema$1, + ResourceSchema: ResourceSchema$1, + ResourceTemplateSchema: ResourceTemplateSchema$1, + ResourceListChangedNotificationSchema: ResourceListChangedNotificationSchema$1, + ResourceUpdatedNotificationParamsSchema: ResourceUpdatedNotificationParamsSchema$1, + ResourceUpdatedNotificationSchema: ResourceUpdatedNotificationSchema$1, + PromptArgumentSchema: PromptArgumentSchema$1, + PromptSchema: PromptSchema$1, + PromptListChangedNotificationSchema: PromptListChangedNotificationSchema$1, + TextContentSchema: TextContentSchema$1, + ImageContentSchema: ImageContentSchema$1, + AudioContentSchema: AudioContentSchema$1, + ToolUseContentSchema: ToolUseContentSchema$1, + EmbeddedResourceSchema: EmbeddedResourceSchema$1, + ResourceLinkSchema: ResourceLinkSchema$1, + ContentBlockSchema: ContentBlockSchema$1, + PromptMessageSchema: PromptMessageSchema$1, + ToolAnnotationsSchema: ToolAnnotationsSchema$1, + ToolListChangedNotificationSchema: ToolListChangedNotificationSchema$1, + ModelHintSchema: ModelHintSchema$1, + ModelPreferencesSchema: ModelPreferencesSchema$1, + ToolChoiceSchema: ToolChoiceSchema$1, + BooleanSchemaSchema: BooleanSchemaSchema$1, + StringSchemaSchema: StringSchemaSchema$1, + NumberSchemaSchema: NumberSchemaSchema$1, + UntitledSingleSelectEnumSchemaSchema: UntitledSingleSelectEnumSchemaSchema$1, + TitledSingleSelectEnumSchemaSchema: TitledSingleSelectEnumSchemaSchema$1, + LegacyTitledEnumSchemaSchema: LegacyTitledEnumSchemaSchema$1, + SingleSelectEnumSchemaSchema: SingleSelectEnumSchemaSchema$1, + UntitledMultiSelectEnumSchemaSchema: UntitledMultiSelectEnumSchemaSchema$1, + TitledMultiSelectEnumSchemaSchema: TitledMultiSelectEnumSchemaSchema$1, + MultiSelectEnumSchemaSchema: MultiSelectEnumSchemaSchema$1, + EnumSchemaSchema: EnumSchemaSchema$1, + PrimitiveSchemaDefinitionSchema: PrimitiveSchemaDefinitionSchema$1, + ElicitRequestFormParamsSchema: ElicitRequestFormParamsSchema$1, + ResourceTemplateReferenceSchema: ResourceTemplateReferenceSchema$1, + PromptReferenceSchema: PromptReferenceSchema$1, + RootSchema: RootSchema$1, + ClientCapabilities2026Schema, + ServerCapabilities2026Schema, + RequestMetaEnvelopeSchema, + ToolSchema: ToolSchema$1, + ToolResultContentSchema: ToolResultContentSchema$1, + SamplingMessageContentBlockSchema: SamplingMessageContentBlockSchema$1, + SamplingMessageSchema: SamplingMessageSchema$1, + ResultTypeSchema, + ResultMetaSchema, + ResultSchema: ResultSchema$1, + PaginatedResultSchema: PaginatedResultSchema$1, + CallToolResultSchema: CallToolResultSchema$1, + ListToolsResultSchema: ListToolsResultSchema$1, + ListPromptsResultSchema: ListPromptsResultSchema$1, + GetPromptResultSchema: GetPromptResultSchema$1, + ListResourcesResultSchema: ListResourcesResultSchema$1, + ListResourceTemplatesResultSchema: ListResourceTemplatesResultSchema$1, + ReadResourceResultSchema: ReadResourceResultSchema$1, + CompleteResultSchema: CompleteResultSchema$1, + CacheableResultSchema, + DiscoverResultSchema: DiscoverResultSchema$1, + CreateMessageRequestParamsSchema: CreateMessageRequestParamsSchema$1, + CreateMessageRequestSchema: CreateMessageRequestSchema$1, + ListRootsRequestSchema: ListRootsRequestSchema$1, + CreateMessageResultSchema: CreateMessageResultSchema$1, + ListRootsResultSchema: ListRootsResultSchema$1, + ElicitResultSchema: ElicitResultSchema$1, + ElicitRequestURLParamsSchema: ElicitRequestURLParamsSchema$1, + ElicitRequestParamsSchema: ElicitRequestParamsSchema$1, + ElicitRequestSchema: ElicitRequestSchema$1, + InputRequestSchema, + InputResponseSchema, + InputRequestsSchema, + InputResponsesSchema, + InputRequiredResultSchema, + InputResponseRequestParamsSchema, + CallToolRequestSchema: CallToolRequestSchema$1, + ListToolsRequestSchema: ListToolsRequestSchema$1, + ListPromptsRequestSchema: ListPromptsRequestSchema$1, + GetPromptRequestSchema: GetPromptRequestSchema$1, + ListResourcesRequestSchema: ListResourcesRequestSchema$1, + ListResourceTemplatesRequestSchema: ListResourceTemplatesRequestSchema$1, + ReadResourceRequestSchema: ReadResourceRequestSchema$1, + CompleteRequestSchema: CompleteRequestSchema$1, + DiscoverRequestSchema: DiscoverRequestSchema$1, + SubscriptionFilterSchema: SubscriptionFilterSchema$1, + SubscriptionsListenRequestSchema: SubscriptionsListenRequestSchema$1, + SubscriptionsListenResultMetaSchema: SubscriptionsListenResultMetaSchema$1, + SubscriptionsListenResultSchema: SubscriptionsListenResultSchema$1, + dispatchRequestSchemas, + dispatchResultSchemas, + NotificationMetaSchema, + SubscriptionsAcknowledgedNotificationSchema: SubscriptionsAcknowledgedNotificationSchema$1, + CancelledNotificationParamsSchema: CancelledNotificationParamsSchema$1, + CancelledNotificationSchema: CancelledNotificationSchema$1, + notificationSchemas2026, + JSONRPCResultResponseSchema: wireResultResponse(ResultSchema$1), + CallToolResultResponseSchema: wireResultResponse(schemas_union([CallToolResultSchema$1, InputRequiredResultSchema])), + ListToolsResultResponseSchema: wireResultResponse(ListToolsResultSchema$1), + ListPromptsResultResponseSchema: wireResultResponse(ListPromptsResultSchema$1), + GetPromptResultResponseSchema: wireResultResponse(schemas_union([GetPromptResultSchema$1, InputRequiredResultSchema])), + ListResourcesResultResponseSchema: wireResultResponse(ListResourcesResultSchema$1), + ListResourceTemplatesResultResponseSchema: wireResultResponse(ListResourceTemplatesResultSchema$1), + ReadResourceResultResponseSchema: wireResultResponse(schemas_union([ReadResourceResultSchema$1, InputRequiredResultSchema])), + CompleteResultResponseSchema: wireResultResponse(CompleteResultSchema$1), + DiscoverResultResponseSchema: wireResultResponse(DiscoverResultSchema$1) + }; +} +let src_CX2iR2pK_memo; +/** +* Builds the era wire-schema set on first call and returns the same object +* thereafter. Module evaluation stays construction-free so importing the +* era codec/registry costs nothing until the first validation actually +* needs a schema; the registry, the codec, and the eager `schemas.ts` +* shim all pull through this memo, so reference identity holds across +* every consumer. +*/ +function buildSchemas2026() { + return src_CX2iR2pK_memo ??= build(); +} + +//#endregion +//#region ../core-internal/src/shared/resultCacheHints.ts +/** +* The operations whose results are cacheable on the 2026-07-28 revision (the +* `CacheableResult` extenders). This list is closed: no other operation's +* result ever receives cache fields from the SDK. +*/ +const CACHEABLE_RESULT_METHODS = [ + "tools/list", + "prompts/list", + "resources/list", + "resources/templates/list", + "resources/read", + "server/discover" +]; +/** Whether the given method's result is cacheable on the 2026-07-28 revision. */ +function isCacheableResultMethod(method) { + return CACHEABLE_RESULT_METHODS.includes(method); +} +/** +* The symbol-keyed carrier for a configured cache hint on a result object. +* Symbol properties are invisible to JSON serialization, so the carrier can be +* attached era-blind: only the 2026-era encode seam consumes it. +*/ +const RESULT_CACHE_HINT_FALLBACK = Symbol("modelcontextprotocol.resultCacheHintFallback"); +/** +* Attaches a configured cache hint to a result as the encode-time fallback. +* Returns the result unchanged when there is nothing to attach. When a more +* specific hint is already attached, the two hints are combined per field +* (most-specific-author-wins for each of `ttlMs` and `cacheScope`): the +* per-registration hint attached by the feature layer keeps every field it +* sets, and the server-level per-operation hint only fills the fields the +* more specific hint leaves unset. +*/ +function attachCacheHintFallback(result, hint) { + if (hint === void 0) return result; + const attached = result[RESULT_CACHE_HINT_FALLBACK]; + if (attached === void 0) return { + ...result, + [RESULT_CACHE_HINT_FALLBACK]: hint + }; + const merged = {}; + const ttlMs = attached.ttlMs ?? hint.ttlMs; + if (ttlMs !== void 0) merged.ttlMs = ttlMs; + const cacheScope = attached.cacheScope ?? hint.cacheScope; + if (cacheScope !== void 0) merged.cacheScope = cacheScope; + return { + ...result, + [RESULT_CACHE_HINT_FALLBACK]: merged + }; +} +/** Reads the configured cache-hint fallback attached to a result, if any. */ +function cacheHintFallbackOf(result) { + return result[RESULT_CACHE_HINT_FALLBACK]; +} +/** +* Whether a value is a valid `ttlMs`: a non-negative safe integer. Safe +* integers are required because the wire schemas validate `ttlMs` as an +* integer within `Number.MIN_SAFE_INTEGER`/`Number.MAX_SAFE_INTEGER`; a value +* outside that range is treated as invalid here so it falls through to the +* next author instead of being emitted and rejected downstream. +*/ +function isValidCacheTtlMs(value) { + return typeof value === "number" && Number.isSafeInteger(value) && value >= 0; +} +/** Whether a value is a valid `cacheScope`. */ +function isValidCacheScope(value) { + return value === "public" || value === "private"; +} +/** +* Validates a configured cache hint at configuration time. Throws a +* `RangeError` naming the offending field, so misconfiguration fails at +* startup/registration rather than silently degrading at encode time. +*/ +function assertValidCacheHint(hint, context) { + if (hint.ttlMs !== void 0 && !isValidCacheTtlMs(hint.ttlMs)) throw new RangeError(`Invalid cache hint for ${context}: ttlMs must be a non-negative safe integer (got ${String(hint.ttlMs)})`); + if (hint.cacheScope !== void 0 && !isValidCacheScope(hint.cacheScope)) throw new RangeError(`Invalid cache hint for ${context}: cacheScope must be 'public' or 'private' (got ${String(hint.cacheScope)})`); +} + +//#endregion +//#region ../core-internal/src/types/enums.ts +/** +* Error codes for protocol errors that cross the wire as JSON-RPC error responses. +* These follow the JSON-RPC specification and MCP-specific extensions. +*/ +let src_CX2iR2pK_ProtocolErrorCode = /* @__PURE__ */ function(ProtocolErrorCode$1) { + ProtocolErrorCode$1[ProtocolErrorCode$1["ParseError"] = -32700] = "ParseError"; + ProtocolErrorCode$1[ProtocolErrorCode$1["InvalidRequest"] = -32600] = "InvalidRequest"; + ProtocolErrorCode$1[ProtocolErrorCode$1["MethodNotFound"] = -32601] = "MethodNotFound"; + ProtocolErrorCode$1[ProtocolErrorCode$1["InvalidParams"] = -32602] = "InvalidParams"; + ProtocolErrorCode$1[ProtocolErrorCode$1["InternalError"] = -32603] = "InternalError"; + /** + * Resource not found. + * + * Receive-tolerated only: the SDK never EMITS `-32002` — `resources/read` + * misses answer `-32602` (Invalid Params) on every protocol revision per + * the 2026-07-28 spec MUST, and a handler-thrown `-32002` is mapped to + * `-32602` at the era encode seam. The member stays importable so clients + * can recognise `-32002` from peers built on earlier SDK releases (the + * spec's "clients SHOULD also accept `-32002`" backwards-compatibility + * clause). Throw `ResourceNotFoundError` instead. + */ + ProtocolErrorCode$1[ProtocolErrorCode$1["ResourceNotFound"] = -32002] = "ResourceNotFound"; + /** + * Processing the request requires a capability the client did not declare + * in the request's `clientCapabilities` (protocol revision 2026-07-28). + */ + ProtocolErrorCode$1[ProtocolErrorCode$1["MissingRequiredClientCapability"] = -32021] = "MissingRequiredClientCapability"; + /** + * The request's protocol version is unknown to the server or unsupported + * by it (protocol revision 2026-07-28). + */ + ProtocolErrorCode$1[ProtocolErrorCode$1["UnsupportedProtocolVersion"] = -32022] = "UnsupportedProtocolVersion"; + ProtocolErrorCode$1[ProtocolErrorCode$1["UrlElicitationRequired"] = -32042] = "UrlElicitationRequired"; + return ProtocolErrorCode$1; +}({}); + +//#endregion +//#region ../core-internal/src/types/errors.ts +/** +* Protocol errors are JSON-RPC errors that cross the wire as error responses. +* They use numeric error codes from the {@linkcode ProtocolErrorCode} enum. +* +* `instanceof` on this class (and its subclasses) is brand-matched, so it works +* across separately bundled copies of the SDK — e.g. an error constructed by +* `@modelcontextprotocol/client` matches the class re-exported by +* `@modelcontextprotocol/server` in the same process. +*/ +var src_CX2iR2pK_ProtocolError = class ProtocolError extends Error { + static { + Object.defineProperty(this, "mcpBrand", { value: "mcp.ProtocolError" }); + } + static [Symbol.hasInstance](value) { + return brandedHasInstance(this, value); + } + /** + * Brand-based type guard: equivalent to `value instanceof this`, as an + * explicit static predicate (the axios/AWS-SDK `isInstance` style). Reads + * the caller's own brand via `this`, so every branded subclass gets a + * correctly-scoped guard by inheritance. Must be invoked on the class — + * in callback position write `v => SdkError.isInstance(v)`, not + * `.filter(SdkError.isInstance)` (detached calls throw rather than + * silently matching nothing). + */ + static isInstance(value) { + 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 brandedHasInstance(this, value); + } + constructor(code, message, data) { + super(message); + this.code = code; + this.data = data; + this.name = "ProtocolError"; + stampErrorBrands(this, new.target); + } + /** + * Factory method to create the appropriate error type based on the error code and data + */ + static fromError(code, message, data) { + if (code === src_CX2iR2pK_ProtocolErrorCode.UrlElicitationRequired && data) { + const errorData = data; + if (errorData.elicitations) return new UrlElicitationRequiredError(errorData.elicitations, message); + } + if (code === src_CX2iR2pK_ProtocolErrorCode.UnsupportedProtocolVersion && data) { + const errorData = data; + if (Array.isArray(errorData.supported) && typeof errorData.requested === "string") return new src_CX2iR2pK_UnsupportedProtocolVersionError({ + supported: errorData.supported, + requested: errorData.requested + }, message); + } + if (code === src_CX2iR2pK_ProtocolErrorCode.InvalidParams || code === src_CX2iR2pK_ProtocolErrorCode.ResourceNotFound) { + const errorData = data; + if (typeof errorData?.uri === "string" && (code === src_CX2iR2pK_ProtocolErrorCode.ResourceNotFound || Object.keys(errorData).length === 1)) return new ResourceNotFoundError(errorData.uri, message); + } + if (code === src_CX2iR2pK_ProtocolErrorCode.MissingRequiredClientCapability && data) { + const errorData = data; + if (errorData.requiredCapabilities !== null && typeof errorData.requiredCapabilities === "object" && !Array.isArray(errorData.requiredCapabilities)) return new src_CX2iR2pK_MissingRequiredClientCapabilityError({ requiredCapabilities: errorData.requiredCapabilities }, message); + } + return new ProtocolError(code, message, data); + } +}; +/** +* Error type for a `resources/read` miss: the requested resource does not +* exist. The wire code is `-32602` (Invalid Params) on every protocol +* revision — the spec MUST for revision 2026-07-28, and the value the v1.x +* SDK has always emitted on earlier revisions. The error data echoes the +* requested URI. +* +* Recognise this error by checking `error.data` is exactly `{ uri: string }` +* (a `-32602` whose data carries `uri` and nothing else is resource-not-found; +* any other `-32602` is an ordinary Invalid Params). For backwards compatibility, clients should also +* accept `-32002` as resource not found — earlier SDK builds emitted that +* code, and {@linkcode ProtocolError.fromError} reconstructs this class for +* either code **when `error.data` carries `uri`** (a bare `-32002` without +* `data.uri` stays a generic {@linkcode ProtocolError}). `instanceof` checks +* are brand-matched and work across separately bundled copies of the SDK. +*/ +var ResourceNotFoundError = class extends src_CX2iR2pK_ProtocolError { + static { + Object.defineProperty(this, "mcpBrand", { value: "mcp.ResourceNotFoundError" }); + } + constructor(uri, message = `Resource not found: ${uri}`) { + super(src_CX2iR2pK_ProtocolErrorCode.InvalidParams, message, { uri }); + } + /** The URI that was requested and not found. */ + get uri() { + return this.data.uri; + } +}; +/** +* Specialized error type when a tool requires a URL mode elicitation. +* This makes it nicer for the client to handle since there is specific data to work with instead of just a code to check against. +*/ +var UrlElicitationRequiredError = class extends src_CX2iR2pK_ProtocolError { + static { + Object.defineProperty(this, "mcpBrand", { value: "mcp.UrlElicitationRequiredError" }); + } + constructor(elicitations, message = `URL elicitation${elicitations.length > 1 ? "s" : ""} required`) { + super(src_CX2iR2pK_ProtocolErrorCode.UrlElicitationRequired, message, { elicitations }); + } + get elicitations() { + return this.data?.elicitations ?? []; + } +}; +/** +* Error type for the `-32022` UnsupportedProtocolVersion protocol error (protocol +* revision 2026-07-28): the request's protocol version is unknown to the server or +* unsupported by it. +* +* The error data lists the protocol versions the receiver supports (`supported`), +* so the sender can choose a mutually supported version and retry, and echoes the +* version that was requested (`requested`). +*/ +var src_CX2iR2pK_UnsupportedProtocolVersionError = class extends src_CX2iR2pK_ProtocolError { + static { + Object.defineProperty(this, "mcpBrand", { value: "mcp.UnsupportedProtocolVersionError" }); + } + constructor(data, message = `Unsupported protocol version: ${data.requested}`) { + super(src_CX2iR2pK_ProtocolErrorCode.UnsupportedProtocolVersion, message, data); + } + /** + * Protocol versions the receiver supports. + */ + get supported() { + return this.data.supported; + } + /** + * The protocol version that was requested. + */ + get requested() { + return this.data.requested; + } +}; +/** +* Error type for the `-32021` MissingRequiredClientCapability protocol error +* (protocol revision 2026-07-28): processing the request requires a capability +* the client did not declare in the request's `clientCapabilities`. +* +* The error data lists the missing capabilities (`requiredCapabilities`) in +* the `ClientCapabilities` shape, so the client can see exactly what it would +* have to declare for the request to be served. On HTTP, the response status +* is `400 Bad Request`. +* +* Recognize this error by its code and `data.requiredCapabilities`, or by +* `instanceof` — checks are brand-matched and work across separately bundled +* copies of the SDK. +*/ +var src_CX2iR2pK_MissingRequiredClientCapabilityError = class extends src_CX2iR2pK_ProtocolError { + static { + Object.defineProperty(this, "mcpBrand", { value: "mcp.MissingRequiredClientCapabilityError" }); + } + constructor(data, message = `Missing required client capabilities: ${Object.keys(data.requiredCapabilities).join(", ")}`) { + super(src_CX2iR2pK_ProtocolErrorCode.MissingRequiredClientCapability, message, data); + } + /** + * The capabilities the server requires from the client to process the + * request (only the missing capabilities are listed). + */ + get requiredCapabilities() { + return this.data.requiredCapabilities; + } +}; + +//#endregion +//#region ../core-internal/src/wire/rev2026-07-28/encodeContract.ts +/** The default cache policy when neither the handler nor configuration provides one. */ +const DEFAULT_CACHE_TTL_MS = 0; +const DEFAULT_CACHE_SCOPE = "private"; +/** +* Request methods whose spec result vocabulary goes beyond `'complete'` on the +* 2026-07-28 revision: their results may be `input_required` (multi +* round-trip requests), so a handler-provided `resultType` passes through the +* stamp untouched. `subscriptions/listen` is NOT in this set: it never emits +* a JSON-RPC result — termination is stream close (HTTP) or +* `notifications/cancelled` (stdio) per the spec. +*/ +const EXTENDED_RESULT_TYPE_METHODS = [ + "tools/call", + "prompts/get", + "resources/read" +]; +/** +* Step 1 of the encode contract: ensure the outbound result carries the +* required `resultType` discriminator. +* +* - No handler-provided value → stamp `'complete'`. +* - Handler-provided `'complete'` → kept as-is. +* - Handler-provided non-`'complete'` value on a method whose vocabulary +* allows it ({@linkcode EXTENDED_RESULT_TYPE_METHODS}) → passes through. +* The value is forwarded verbatim — the wire vocabulary is an open union and +* the SDK does not validate the string, so emitting a `resultType` the +* negotiated revision does not define is the handler author's +* responsibility. +* - Handler-provided non-`'complete'` value on any other method → internal +* error (loud): the value would be mis-typed on the wire, and silently +* rewriting it would hide a server bug. +*/ +function stampResultType(method, result) { + const provided = result["resultType"]; + if (provided === void 0) return { + ...result, + resultType: "complete" + }; + if (provided === "complete") return result; + if (EXTENDED_RESULT_TYPE_METHODS.includes(method)) return result; + throw new src_CX2iR2pK_ProtocolError(src_CX2iR2pK_ProtocolErrorCode.InternalError, `Handler for ${method} returned resultType '${String(provided)}', but results of ${method} only support 'complete' on protocol revision 2026-07-28`); +} +/** +* Step 2 of the encode contract: fill the required `ttlMs`/`cacheScope` fields +* on cacheable results. +* +* Applies only when the (post-stamp) `resultType` is `'complete'` and the +* method is one of the cacheable operations; everything else is returned +* untouched apart from removing the configured-hint carrier. Field resolution +* is per field, most specific author first: a valid handler-returned value, +* then the configured cache hint attached by the server layer, then the +* defaults. Handler-returned values are validated at encode time (`ttlMs` +* must be a non-negative integer, `cacheScope` must be `'public'` or +* `'private'`); invalid values are ignored rather than emitted. +*/ +function fillCacheFields(method, result) { + const fallback = cacheHintFallbackOf(result); + if (result["resultType"] !== "complete" || !isCacheableResultMethod(method)) return fallback === void 0 ? result : stripCacheHintFallback(result); + const provided = result; + const ttlMs = isValidCacheTtlMs(provided["ttlMs"]) ? provided["ttlMs"] : resolveTtlMs(fallback); + const cacheScope = isValidCacheScope(provided["cacheScope"]) ? provided["cacheScope"] : resolveCacheScope(fallback); + const filled = { + ...provided, + ttlMs, + cacheScope + }; + delete filled[RESULT_CACHE_HINT_FALLBACK]; + return filled; +} +function isPlainObject$5(value) { + return value !== null && typeof value === "object" && !Array.isArray(value); +} +/** +* Step 3 of the encode contract: stamp the server's identity into the +* result's `_meta` under `io.modelcontextprotocol/serverInfo` (spec PR #3002: +* servers SHOULD include it on every response). +* +* - No `serverInfo` supplied (a client instance, or a hand-constructed +* protocol object) → identity function. +* - The result's `_meta` already carries the key → kept as-is (the handler +* is the more specific author; mirrors the cache-fill resolution order). +* - A present-but-non-object `_meta` (a dynamic-caller bug) → kept as-is: +* the stamp never rewrites handler material, and the malformed value fails +* loudly at the peer instead of being silently replaced here. +* - Otherwise → the key is added, preserving any other `_meta` entries. +* +* Runs for every result regardless of `resultType`: the anchor types +* `Result._meta` as `ResultMetaObject` on all results, `input_required` +* included. +*/ +function stampServerInfoMeta(result, serverInfo) { + if (serverInfo === void 0) return result; + const meta = result["_meta"]; + if (meta === void 0) return { + ...result, + _meta: { [auth_CUe6YdwF_SERVER_INFO_META_KEY]: serverInfo } + }; + if (!isPlainObject$5(meta)) return result; + if (meta[auth_CUe6YdwF_SERVER_INFO_META_KEY] !== void 0) return result; + return { + ...result, + _meta: { + ...meta, + [auth_CUe6YdwF_SERVER_INFO_META_KEY]: serverInfo + } + }; +} +function resolveTtlMs(fallback) { + return fallback !== void 0 && isValidCacheTtlMs(fallback.ttlMs) ? fallback.ttlMs : DEFAULT_CACHE_TTL_MS; +} +function resolveCacheScope(fallback) { + return fallback !== void 0 && isValidCacheScope(fallback.cacheScope) ? fallback.cacheScope : DEFAULT_CACHE_SCOPE; +} +function stripCacheHintFallback(result) { + const copy = { ...result }; + delete copy[RESULT_CACHE_HINT_FALLBACK]; + return copy; +} + +//#endregion +//#region ../core-internal/src/wire/rev2026-07-28/inputRequired.ts +/** +* In-band input-request vocabulary of the 2026-07-28 revision (SEP-2322 +* multi round-trip requests), dispatch view. +* +* The three former server→client wire requests (`elicitation/create`, +* `sampling/createMessage`, `roots/list`) are NOT wire request methods on +* this revision — they are demoted to de-JSON-RPC'd payloads embedded in an +* `input_required` result. The multi-round-trip driver dispatches those +* embedded payloads to the client's registered handlers through the normal +* handler machinery, and these are the schemas that dispatch parses them +* with: lenient where the anchor's wire-true artifacts are strict (an +* embedded request never carries the per-request `_meta` envelope), exact +* where the vocabulary forks (the sampling shapes compose the forked +* SamplingMessage/Tool payloads). +* +* Registry membership is intentionally NOT granted here — these methods stay +* absent from the 2026-era request registry (a peer sending one as a wire +* request still gets −32601 by absence). Only the codec's +* `inputRequestSchema`/`inputResponseSchema` accessors expose them. +*/ +/** The embedded input-request methods of the 2026-07-28 revision. */ +const INPUT_REQUEST_METHODS_2026 = [ + "elicitation/create", + "sampling/createMessage", + "roots/list" +]; +let maps; +function inputSchemaMaps() { + if (maps) return maps; + const s = buildSchemas2026(); + maps = { + request: { + "elicitation/create": schemas_object({ + method: literal("elicitation/create"), + params: s.ElicitRequestParamsSchema + }), + "sampling/createMessage": schemas_object({ + method: literal("sampling/createMessage"), + params: s.CreateMessageRequestParamsSchema + }), + "roots/list": schemas_object({ + method: literal("roots/list"), + params: looseObject({}).optional() + }) + }, + response: { + "elicitation/create": s.ElicitResultSchema, + "sampling/createMessage": s.CreateMessageResultSchema, + "roots/list": s.ListRootsResultSchema + } + }; + return maps; +} +/** +* Forces the lazy embedded-request maps (and, through them, the era's schema +* memo). Warm-up hook for `preloadSchemas()` — no-op once the maps exist. +*/ +function warmInputSchemaMaps2026() { + inputSchemaMaps(); +} +function isInputRequestMethod2026(method) { + return INPUT_REQUEST_METHODS_2026.includes(method); +} +function getInputRequestSchema2026(method) { + return isInputRequestMethod2026(method) ? inputSchemaMaps().request[method] : void 0; +} +function getInputResponseSchema2026(method) { + return isInputRequestMethod2026(method) ? inputSchemaMaps().response[method] : void 0; +} + +//#endregion +//#region ../core-internal/src/wire/rev2026-07-28/registry.ts +const requestMethodKeys = { + "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 +}; +const notificationMethodKeys = { + "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 +}; +/** The 2026-era request-method set (registry membership = the deletion story). */ +function hasRequestMethod2026(method) { + return Object.prototype.hasOwnProperty.call(requestMethodKeys, method); +} +/** The 2026-era notification-method set. */ +function hasNotificationMethod2026(method) { + return Object.prototype.hasOwnProperty.call(notificationMethodKeys, method); +} +/** Result-map membership (same key set as the request map on this era). */ +function hasResultMethod2026(method) { + return Object.prototype.hasOwnProperty.call(requestMethodKeys, method); +} +function getRequestSchema2026(method) { + return hasRequestMethod2026(method) ? buildSchemas2026().dispatchRequestSchemas[method] : void 0; +} +function getResultSchema2026(method) { + return hasResultMethod2026(method) ? buildSchemas2026().dispatchResultSchemas[method] : void 0; +} +function getNotificationSchema2026(method) { + return hasNotificationMethod2026(method) ? buildSchemas2026().notificationSchemas2026[method] : void 0; +} +/** Registry method lists (for the spec-method universe and the CI registry-diff oracle). */ +const rev2026RequestMethods = Object.keys(requestMethodKeys); +const rev2026NotificationMethods = Object.keys(notificationMethodKeys); + +//#endregion +//#region ../core-internal/src/wire/rev2026-07-28/codec.ts +function isPlainObject$4(value) { + return value !== null && typeof value === "object" && !Array.isArray(value); +} +/** Tri-state wrap of an optional Zod schema lookup (the function-only contract). */ +function triState(schema, raw) { + if (schema === void 0) return { + ok: false, + reason: "not-in-era" + }; + const parsed = schema.safeParse(raw); + return parsed.success ? { + ok: true, + value: parsed.data + } : { + ok: false, + reason: "invalid", + message: String(parsed.error) + }; +} +const NOT_IN_ERA = { + ok: false, + reason: "not-in-era" +}; +/** +* The reserved `_meta` keys an envelope must carry on this era (in reporting +* order). `clientInfo` is NOT here: spec PR #3002 demoted it to SHOULD, so a +* request without it is accepted (a present-but-malformed value still fails +* the envelope schema parse below). +*/ +const REQUIRED_ENVELOPE_KEYS = [auth_CUe6YdwF_PROTOCOL_VERSION_META_KEY, auth_CUe6YdwF_CLIENT_CAPABILITIES_META_KEY]; +/** Strip the known deleted-field set from an outbound result (Q1-SD3 iii). */ +function enforceDeletedFields(method, result) { + let next = result; + let copied = false; + const copy = () => { + if (!copied) { + next = { ...next }; + copied = true; + } + return next; + }; + const tools = result.tools; + if (method === "tools/list" && Array.isArray(tools) && tools.some((tool) => isPlainObject$4(tool) && "execution" in tool)) copy().tools = tools.map((tool) => { + if (!isPlainObject$4(tool) || !("execution" in tool)) return tool; + const rest = { ...tool }; + delete rest["execution"]; + return rest; + }); + const capabilities = result.capabilities; + if (isPlainObject$4(capabilities) && "tasks" in capabilities) { + const rest = { ...capabilities }; + delete rest["tasks"]; + copy().capabilities = rest; + } + return next; +} +const rev2026Codec = { + era: "2026-07-28", + hasRequestMethod: hasRequestMethod2026, + hasNotificationMethod: hasNotificationMethod2026, + hasInputRequestMethod: (method) => getInputRequestSchema2026(method) !== void 0, + validateRequest: (method, raw) => triState(getRequestSchema2026(method), raw), + validateResult: (method, raw) => triState(getResultSchema2026(method), raw), + validateNotification: (method, raw) => triState(getNotificationSchema2026(method), raw), + validateInputRequest: (method, raw) => triState(getInputRequestSchema2026(method), raw), + validateInputResponse: (method, raw) => triState(getInputResponseSchema2026(method), raw), + samplingResultVariant: () => NOT_IN_ERA, + outboundEnvelope(material) { + return { + [auth_CUe6YdwF_PROTOCOL_VERSION_META_KEY]: material.protocolVersion, + [auth_CUe6YdwF_CLIENT_INFO_META_KEY]: material.clientInfo, + [auth_CUe6YdwF_CLIENT_CAPABILITIES_META_KEY]: material.clientCapabilities, + ...material.logLevel !== void 0 && { [LOG_LEVEL_META_KEY]: material.logLevel } + }; + }, + validateEnvelopeMeta(meta) { + const issues = []; + for (const key of REQUIRED_ENVELOPE_KEYS) if (!(key in meta)) issues.push({ + key, + problem: "missing" + }); + const parsed = buildSchemas2026().RequestMetaEnvelopeSchema.safeParse(meta); + if (!parsed.success) for (const issue of parsed.error.issues) { + const path = issue.path.map(String); + const key = path.length > 0 ? path.join(".") : "_meta"; + if (path.length === 1 && issues.some((existing) => existing.key === key && existing.problem === "missing")) continue; + issues.push({ + key, + problem: issue.message + }); + } + return issues; + }, + projectCallToolResult: (result) => appendTextFallbackForNonObject(result), + inputRequestSchema: getInputRequestSchema2026, + decodeResult(method, raw) { + if (!isPlainObject$4(raw)) return { + kind: "invalid", + error: new src_CX2iR2pK_SdkError(src_CX2iR2pK_SdkErrorCode.InvalidResult, `Invalid result for ${method}: not an object`, { method }) + }; + const rawResultType = raw["resultType"]; + if (rawResultType === void 0) return { + kind: "invalid", + error: new src_CX2iR2pK_SdkError(src_CX2iR2pK_SdkErrorCode.InvalidResult, `Invalid result for ${method}: missing required resultType — servers implementing protocol revision 2026-07-28 MUST include it (the absent-means-complete bridge applies only to earlier-revision servers)`, { + method, + violation: "missing-resultType" + }) + }; + if (typeof rawResultType !== "string") return { + kind: "invalid", + error: new src_CX2iR2pK_SdkError(src_CX2iR2pK_SdkErrorCode.InvalidResult, `Invalid result for ${method}: non-string resultType`, { + method, + resultType: rawResultType + }) + }; + if (rawResultType === "input_required") { + const rawInputRequests = raw["inputRequests"]; + const inputRequests = isPlainObject$4(rawInputRequests) ? rawInputRequests : {}; + const requestState = raw["requestState"]; + if (Object.keys(inputRequests).length === 0 && typeof requestState !== "string") return { + kind: "invalid", + error: new src_CX2iR2pK_SdkError(src_CX2iR2pK_SdkErrorCode.InvalidResult, `Invalid result for ${method}: input_required carries neither inputRequests nor requestState (every input_required result must include at least one of the two)`, { + method, + violation: "input-required-missing-both" + }) + }; + return { + kind: "input_required", + inputRequests, + ...typeof requestState === "string" && { requestState } + }; + } + if (rawResultType !== "complete") return { + kind: "invalid", + error: new src_CX2iR2pK_SdkError(src_CX2iR2pK_SdkErrorCode.UnsupportedResultType, `Unsupported result type '${rawResultType}' for ${method}`, { + resultType: rawResultType, + method + }) + }; + const wireResultSchemas = getWireResultSchemas(); + const wireSchema = Object.hasOwn(wireResultSchemas, method) ? wireResultSchemas[method] : void 0; + if (wireSchema !== void 0) { + const parsed = wireSchema.safeParse(raw); + if (!parsed.success) return { + kind: "invalid", + error: new src_CX2iR2pK_SdkError(src_CX2iR2pK_SdkErrorCode.InvalidResult, `Invalid result for ${method}: ${parsed.error}`, { method }) + }; + } + const lifted = { ...raw }; + delete lifted["resultType"]; + return { + kind: "complete", + result: lifted + }; + }, + encodeResult(method, result, serverInfo) { + return stampServerInfoMeta(fillCacheFields(method, stampResultType(method, enforceDeletedFields(method, result))), serverInfo); + }, + encodeErrorCode: (code) => code === -32002 ? -32602 : code, + checkInboundEnvelope(material) { + if (material.envelope === void 0) return "Request is missing the required _meta envelope for protocol revision 2026-07-28 (io.modelcontextprotocol/protocolVersion, io.modelcontextprotocol/clientCapabilities)"; + const parsed = buildSchemas2026().RequestMetaEnvelopeSchema.safeParse(material.envelope); + if (!parsed.success) return `Invalid _meta envelope for protocol revision 2026-07-28: ${parsed.error.issues.map((issue) => issue.message).join("; ")}`; + } +}; +/** Wire-true result wrappers consulted by decode step 2, keyed by method — +* built once through the era's schema memo on the first decode. */ +let wireResultSchemasMemo; +function getWireResultSchemas() { + if (wireResultSchemasMemo) return wireResultSchemasMemo; + const s = buildSchemas2026(); + wireResultSchemasMemo = { + "tools/call": s.CallToolResultSchema, + "tools/list": s.ListToolsResultSchema, + "prompts/get": s.GetPromptResultSchema, + "prompts/list": s.ListPromptsResultSchema, + "resources/list": s.ListResourcesResultSchema, + "resources/templates/list": s.ListResourceTemplatesResultSchema, + "resources/read": s.ReadResourceResultSchema, + "completion/complete": s.CompleteResultSchema, + "server/discover": s.DiscoverResultSchema + }; + return wireResultSchemasMemo; +} +/** +* Forces the lazy wire-result wrapper map (and, through it, the era's schema +* memo). Warm-up hook for `preloadSchemas()` — no-op once the map exists. +*/ +function warmWireResultSchemas2026() { + getWireResultSchemas(); +} + +//#endregion +//#region ../core-internal/src/wire/codec.ts +/** +* The modern wire revision literal. Internal only — deliberately NOT a public +* constant (G-D2-4: no public modern-version constant ships before era-aware +* list semantics exist). +*/ +const src_CX2iR2pK_MODERN_WIRE_REVISION = "2026-07-28"; +/** +* Era resolution, many-to-one (Q1-SD1): every modern-era revision +* (`>= 2026-07-28`) → the 2026-era codec; every legacy revision (the five +* `SUPPORTED_PROTOCOL_VERSIONS`) and `undefined`/unknown → the 2025-era +* codec (the DV-13 default posture — hand-constructed instances and +* unclassified traffic are legacy-era). This is the same era predicate the +* rest of the SDK uses ({@link isModernProtocolVersion}); a pinned modern +* revision other than the literal '2026-07-28' must still resolve modern. +*/ +function src_CX2iR2pK_codecForVersion(version) { + return version !== void 0 && isModernProtocolVersion(version) ? rev2026Codec : rev2025Codec; +} +/** +* The wire era an edge classification names (Q2 — produced at the +* transport/entry edge; this layer only CONSUMES it). The dispatch funnel no +* longer resolves a codec FROM the classification: era is instance state, and +* a classified inbound message is VALIDATED against the instance era — a +* mismatch is an entry/routing error, never a per-message era switch. The +* exact `revision` wins over the coarse era flag when both are present. +*/ +function classifiedWireEra(classification) { + if (classification.revision !== void 0) return src_CX2iR2pK_codecForVersion(classification.revision).era; + return classification.era === "modern" ? rev2026Codec.era : rev2025Codec.era; +} +/** +* The derived spec-method universe: the union of every codec registry. A +* method in this set is era-gated at dispatch and send time; a method outside +* it is a consumer-owned extension method (era-blind, schema-explicit). +* Derived from the registries — never hand-curated (the LEGACY_ONLY_METHODS +* table class is exactly what registry membership replaces). +*/ +function isSpecRequestMethod(method) { + return ALL_CODECS.some((codec) => codec.hasRequestMethod(method)); +} +function isSpecNotificationMethod(method) { + return ALL_CODECS.some((codec) => codec.hasNotificationMethod(method)); +} +const ALL_CODECS = [rev2025Codec, rev2026Codec]; + +//#endregion +//#region ../core-internal/src/shared/envelope.ts +/** +* Per-request `_meta` envelope claim helpers (protocol revision 2026-07-28). +* +* Pure, value-returning helpers used by the inbound HTTP classifier +* (`classifyInboundRequest`): claim detection and envelope validation with +* self-identifying issues. The envelope schema itself stays the wire layer's +* single source of truth (`RequestMetaEnvelopeSchema`); this module only maps +* its outcomes into the shapes the validation ladder emits. +* +* Claim detection is deliberately narrow: a message claims the 2026-07-28 +* envelope mechanism if and only if the reserved protocol-version `_meta` key +* is present in `params._meta`. Other reserved keys (client info, client +* capabilities, log level), a bare `progressToken`, or unrelated keys under +* the `io.modelcontextprotocol/` prefix do NOT constitute a claim on their +* own — but once the claim key is present, a malformed envelope is a +* validation error, never a silent fall back to legacy handling. +* +* The wire-exact envelope schema, the required-key set, and the per-key issue +* mapping live in the wire layer (the 2026-era codec's `validateEnvelopeMeta`). +* This module never reaches into a per-revision wire module directly. +*/ +function isPlainObject$3(value) { + return value !== null && typeof value === "object" && !Array.isArray(value); +} +/** The `_meta` object of a message's params, when present. */ +function src_CX2iR2pK_requestMetaOf(params) { + if (!isPlainObject$3(params)) return void 0; + const meta = params["_meta"]; + return isPlainObject$3(meta) ? meta : void 0; +} +/** +* Whether a message's params carry the per-request envelope claim: the +* reserved protocol-version `_meta` key is present (regardless of whether the +* rest of the envelope is valid — validation is a separate, later step). +*/ +function src_CX2iR2pK_hasEnvelopeClaim(params) { + const meta = src_CX2iR2pK_requestMetaOf(params); + return meta !== void 0 && PROTOCOL_VERSION_META_KEY in meta; +} +/** +* The protocol version named by a message's envelope claim, when the claim is +* present and carries a string value. A present claim with a non-string value +* still counts as a claim ({@linkcode hasEnvelopeClaim}); it surfaces as a +* validation issue instead of a version. +*/ +function src_CX2iR2pK_envelopeClaimVersion(params) { + const value = src_CX2iR2pK_requestMetaOf(params)?.[PROTOCOL_VERSION_META_KEY]; + return typeof value === "string" ? value : void 0; +} +/** +* Validates a request's `_meta` object as a 2026-07-28 per-request envelope +* and reports problems as self-identifying issues (which key, what problem). +* +* Returns an empty array when the envelope is valid. Missing required keys are +* reported first (as `problem: 'missing'`), then schema violations inside +* present keys, in a stable order. +*/ +function src_CX2iR2pK_validateEnvelopeMeta(meta) { + return src_CX2iR2pK_codecForVersion(src_CX2iR2pK_MODERN_WIRE_REVISION).validateEnvelopeMeta(meta); +} + +//#endregion +//#region ../core-internal/src/types/schemas.ts +var schemas_exports = /* @__PURE__ */ __exportAll({ + AnnotationsSchema: () => AnnotationsSchema, + AudioContentSchema: () => AudioContentSchema, + BaseMetadataSchema: () => BaseMetadataSchema, + BaseRequestParamsSchema: () => BaseRequestParamsSchema, + BlobResourceContentsSchema: () => BlobResourceContentsSchema, + BooleanSchemaSchema: () => BooleanSchemaSchema, + CallToolRequestParamsSchema: () => CallToolRequestParamsSchema, + CallToolRequestSchema: () => CallToolRequestSchema, + CallToolResultSchema: () => auth_CUe6YdwF_CallToolResultSchema, + CancelTaskRequestSchema: () => CancelTaskRequestSchema, + CancelTaskResultSchema: () => CancelTaskResultSchema, + CancelledNotificationParamsSchema: () => CancelledNotificationParamsSchema, + CancelledNotificationSchema: () => CancelledNotificationSchema, + ClientCapabilitiesSchema: () => ClientCapabilitiesSchema, + ClientNotificationSchema: () => ClientNotificationSchema, + ClientRequestSchema: () => ClientRequestSchema, + ClientResultSchema: () => ClientResultSchema, + ClientTasksCapabilitySchema: () => ClientTasksCapabilitySchema, + CompatibilityCallToolResultSchema: () => CompatibilityCallToolResultSchema, + CompleteRequestParamsSchema: () => CompleteRequestParamsSchema, + CompleteRequestSchema: () => CompleteRequestSchema, + CompleteResultSchema: () => CompleteResultSchema, + ContentBlockSchema: () => ContentBlockSchema, + CreateMessageRequestParamsSchema: () => CreateMessageRequestParamsSchema, + CreateMessageRequestSchema: () => CreateMessageRequestSchema, + CreateMessageResultSchema: () => CreateMessageResultSchema, + CreateMessageResultWithToolsSchema: () => CreateMessageResultWithToolsSchema, + CreateTaskResultSchema: () => CreateTaskResultSchema, + CursorSchema: () => CursorSchema, + DiscoverRequestSchema: () => DiscoverRequestSchema, + DiscoverResultSchema: () => DiscoverResultSchema, + ElicitRequestFormParamsSchema: () => ElicitRequestFormParamsSchema, + ElicitRequestParamsSchema: () => ElicitRequestParamsSchema, + ElicitRequestSchema: () => ElicitRequestSchema, + ElicitRequestURLParamsSchema: () => ElicitRequestURLParamsSchema, + ElicitResultSchema: () => ElicitResultSchema, + ElicitationCompleteNotificationParamsSchema: () => ElicitationCompleteNotificationParamsSchema, + ElicitationCompleteNotificationSchema: () => ElicitationCompleteNotificationSchema, + EmbeddedResourceSchema: () => EmbeddedResourceSchema, + EmptyResultSchema: () => EmptyResultSchema, + EnumSchemaSchema: () => EnumSchemaSchema, + GetPromptRequestParamsSchema: () => GetPromptRequestParamsSchema, + GetPromptRequestSchema: () => GetPromptRequestSchema, + GetPromptResultSchema: () => GetPromptResultSchema, + GetTaskPayloadRequestSchema: () => GetTaskPayloadRequestSchema, + GetTaskPayloadResultSchema: () => GetTaskPayloadResultSchema, + GetTaskRequestSchema: () => GetTaskRequestSchema, + GetTaskResultSchema: () => GetTaskResultSchema, + IconSchema: () => IconSchema, + IconsSchema: () => IconsSchema, + ImageContentSchema: () => ImageContentSchema, + ImplementationSchema: () => ImplementationSchema, + InitializeRequestParamsSchema: () => InitializeRequestParamsSchema, + InitializeRequestSchema: () => auth_CUe6YdwF_InitializeRequestSchema, + InitializeResultSchema: () => InitializeResultSchema, + InitializedNotificationSchema: () => auth_CUe6YdwF_InitializedNotificationSchema, + JSONArraySchema: () => JSONArraySchema, + JSONObjectSchema: () => JSONObjectSchema, + JSONRPCErrorResponseSchema: () => JSONRPCErrorResponseSchema, + JSONRPCMessageSchema: () => auth_CUe6YdwF_JSONRPCMessageSchema, + JSONRPCNotificationSchema: () => JSONRPCNotificationSchema, + JSONRPCRequestSchema: () => JSONRPCRequestSchema, + JSONRPCResponseSchema: () => auth_CUe6YdwF_JSONRPCResponseSchema, + JSONRPCResultResponseSchema: () => JSONRPCResultResponseSchema, + JSONValueSchema: () => JSONValueSchema, + LegacyTitledEnumSchemaSchema: () => LegacyTitledEnumSchemaSchema, + ListChangedOptionsBaseSchema: () => ListChangedOptionsBaseSchema, + ListPromptsRequestSchema: () => ListPromptsRequestSchema, + ListPromptsResultSchema: () => ListPromptsResultSchema, + ListResourceTemplatesRequestSchema: () => ListResourceTemplatesRequestSchema, + ListResourceTemplatesResultSchema: () => ListResourceTemplatesResultSchema, + ListResourcesRequestSchema: () => ListResourcesRequestSchema, + ListResourcesResultSchema: () => ListResourcesResultSchema, + ListRootsRequestSchema: () => ListRootsRequestSchema, + ListRootsResultSchema: () => ListRootsResultSchema, + ListTasksRequestSchema: () => ListTasksRequestSchema, + ListTasksResultSchema: () => ListTasksResultSchema, + ListToolsRequestSchema: () => ListToolsRequestSchema, + ListToolsResultSchema: () => ListToolsResultSchema, + LoggingLevelSchema: () => LoggingLevelSchema, + LoggingMessageNotificationParamsSchema: () => LoggingMessageNotificationParamsSchema, + LoggingMessageNotificationSchema: () => LoggingMessageNotificationSchema, + ModelHintSchema: () => ModelHintSchema, + ModelPreferencesSchema: () => ModelPreferencesSchema, + MultiSelectEnumSchemaSchema: () => MultiSelectEnumSchemaSchema, + NotificationSchema: () => NotificationSchema, + NotificationsParamsSchema: () => NotificationsParamsSchema, + NumberSchemaSchema: () => NumberSchemaSchema, + PaginatedRequestParamsSchema: () => PaginatedRequestParamsSchema, + PaginatedRequestSchema: () => PaginatedRequestSchema, + PaginatedResultSchema: () => PaginatedResultSchema, + PingRequestSchema: () => PingRequestSchema, + PrimitiveSchemaDefinitionSchema: () => PrimitiveSchemaDefinitionSchema, + ProgressNotificationParamsSchema: () => ProgressNotificationParamsSchema, + ProgressNotificationSchema: () => ProgressNotificationSchema, + ProgressSchema: () => ProgressSchema, + ProgressTokenSchema: () => ProgressTokenSchema, + PromptArgumentSchema: () => PromptArgumentSchema, + PromptListChangedNotificationSchema: () => PromptListChangedNotificationSchema, + PromptMessageSchema: () => PromptMessageSchema, + PromptReferenceSchema: () => PromptReferenceSchema, + PromptSchema: () => PromptSchema, + ReadResourceRequestParamsSchema: () => ReadResourceRequestParamsSchema, + ReadResourceRequestSchema: () => ReadResourceRequestSchema, + ReadResourceResultSchema: () => ReadResourceResultSchema, + RelatedTaskMetadataSchema: () => RelatedTaskMetadataSchema, + RequestIdSchema: () => RequestIdSchema, + RequestMetaSchema: () => RequestMetaSchema, + RequestSchema: () => RequestSchema, + ResourceContentsSchema: () => ResourceContentsSchema, + ResourceLinkSchema: () => ResourceLinkSchema, + ResourceListChangedNotificationSchema: () => ResourceListChangedNotificationSchema, + ResourceRequestParamsSchema: () => ResourceRequestParamsSchema, + ResourceSchema: () => ResourceSchema, + ResourceTemplateReferenceSchema: () => ResourceTemplateReferenceSchema, + ResourceTemplateSchema: () => ResourceTemplateSchema, + ResourceUpdatedNotificationParamsSchema: () => ResourceUpdatedNotificationParamsSchema, + ResourceUpdatedNotificationSchema: () => ResourceUpdatedNotificationSchema, + ResultMetaObjectSchema: () => ResultMetaObjectSchema, + ResultSchema: () => ResultSchema, + RoleSchema: () => RoleSchema, + RootSchema: () => RootSchema, + RootsListChangedNotificationSchema: () => RootsListChangedNotificationSchema, + SamplingContentSchema: () => SamplingContentSchema, + SamplingMessageContentBlockSchema: () => SamplingMessageContentBlockSchema, + SamplingMessageSchema: () => SamplingMessageSchema, + ServerCapabilitiesSchema: () => ServerCapabilitiesSchema, + ServerNotificationSchema: () => ServerNotificationSchema, + ServerRequestSchema: () => ServerRequestSchema, + ServerResultSchema: () => ServerResultSchema, + ServerTasksCapabilitySchema: () => ServerTasksCapabilitySchema, + SetLevelRequestParamsSchema: () => SetLevelRequestParamsSchema, + SetLevelRequestSchema: () => SetLevelRequestSchema, + SingleSelectEnumSchemaSchema: () => SingleSelectEnumSchemaSchema, + StringSchemaSchema: () => StringSchemaSchema, + SubscribeRequestParamsSchema: () => SubscribeRequestParamsSchema, + SubscribeRequestSchema: () => SubscribeRequestSchema, + SubscriptionFilterSchema: () => SubscriptionFilterSchema, + SubscriptionsAcknowledgedNotificationParamsSchema: () => SubscriptionsAcknowledgedNotificationParamsSchema, + SubscriptionsAcknowledgedNotificationSchema: () => SubscriptionsAcknowledgedNotificationSchema, + SubscriptionsListenRequestParamsSchema: () => SubscriptionsListenRequestParamsSchema, + SubscriptionsListenRequestSchema: () => SubscriptionsListenRequestSchema, + SubscriptionsListenResultMetaSchema: () => SubscriptionsListenResultMetaSchema, + SubscriptionsListenResultSchema: () => SubscriptionsListenResultSchema, + TaskAugmentedRequestParamsSchema: () => auth_CUe6YdwF_TaskAugmentedRequestParamsSchema, + TaskCreationParamsSchema: () => TaskCreationParamsSchema, + TaskMetadataSchema: () => TaskMetadataSchema, + TaskSchema: () => TaskSchema, + TaskStatusNotificationParamsSchema: () => TaskStatusNotificationParamsSchema, + TaskStatusNotificationSchema: () => TaskStatusNotificationSchema, + TaskStatusSchema: () => TaskStatusSchema, + TextContentSchema: () => TextContentSchema, + TextResourceContentsSchema: () => TextResourceContentsSchema, + TitledMultiSelectEnumSchemaSchema: () => TitledMultiSelectEnumSchemaSchema, + TitledSingleSelectEnumSchemaSchema: () => TitledSingleSelectEnumSchemaSchema, + ToolAnnotationsSchema: () => ToolAnnotationsSchema, + ToolChoiceSchema: () => ToolChoiceSchema, + ToolExecutionSchema: () => ToolExecutionSchema, + ToolListChangedNotificationSchema: () => ToolListChangedNotificationSchema, + ToolResultContentSchema: () => ToolResultContentSchema, + ToolSchema: () => ToolSchema, + ToolUseContentSchema: () => ToolUseContentSchema, + UnsubscribeRequestParamsSchema: () => UnsubscribeRequestParamsSchema, + UnsubscribeRequestSchema: () => UnsubscribeRequestSchema, + UntitledMultiSelectEnumSchemaSchema: () => UntitledMultiSelectEnumSchemaSchema, + UntitledSingleSelectEnumSchemaSchema: () => UntitledSingleSelectEnumSchemaSchema +}); + +//#endregion +//#region ../core-internal/src/types/guards.ts +/** +* Validates and parses an unknown value as a JSON-RPC message. +* +* Use this to validate incoming messages in custom transport implementations. +* Throws if the value does not conform to the JSON-RPC message schema. +* +* @param value - The value to validate (typically a parsed JSON object). +* @returns The validated {@linkcode JSONRPCMessage}. +* @throws If validation fails. +*/ +function parseJSONRPCMessage(value) { + return JSONRPCMessageSchema.parse(value); +} +const src_CX2iR2pK_isJSONRPCRequest = (value) => JSONRPCRequestSchema.safeParse(value).success; +const src_CX2iR2pK_isJSONRPCNotification = (value) => JSONRPCNotificationSchema.safeParse(value).success; +/** +* Checks if a value is a valid {@linkcode JSONRPCResultResponse}. +* @param value - The value to check. +* +* @returns True if the value is a valid {@linkcode JSONRPCResultResponse}, false otherwise. +*/ +const src_CX2iR2pK_isJSONRPCResultResponse = (value) => JSONRPCResultResponseSchema.safeParse(value).success; +/** +* Checks if a value is a valid {@linkcode JSONRPCErrorResponse}. +* @param value - The value to check. +* +* @returns True if the value is a valid {@linkcode JSONRPCErrorResponse}, false otherwise. +*/ +const src_CX2iR2pK_isJSONRPCErrorResponse = (value) => JSONRPCErrorResponseSchema.safeParse(value).success; +/** +* Checks if a value is a valid {@linkcode JSONRPCResponse} (either a result or error response). +* @param value - The value to check. +* +* @returns True if the value is a valid {@linkcode JSONRPCResponse}, false otherwise. +*/ +const isJSONRPCResponse = (value) => JSONRPCResponseSchema.safeParse(value).success; +/** +* Checks if a value is a valid {@linkcode CallToolResult}. +* +* This is a consumer-side VALUE check against the neutral model, not a wire +* validator: a raw wire object that additionally carries wire-only members +* (e.g. `resultType`) still passes through the loose index signature. Use a +* transport-level parse to validate raw wire traffic. +* +* @param value - The value to check. +* +* @returns True if the value is a valid {@linkcode CallToolResult}, false otherwise. +*/ +const isCallToolResult = (value) => { + if (typeof value !== "object" || value === null || value.content === void 0) return false; + return CallToolResultSchema.safeParse(value).success; +}; +/** +* Checks whether a value is an input-required result (protocol revision +* 2026-07-28): the multi-round-trip return shape discriminated by +* `resultType: 'input_required'`. +* +* This is a discriminator check, not a full validator — the at-least-one rule +* (`inputRequests` or `requestState`) is enforced by the `inputRequired()` +* builder and re-checked by the server seam for hand-built values. +* +* @param value - The value to check. +* @returns True if the value carries the `input_required` discriminator. +*/ +const isInputRequiredResult = (value) => typeof value === "object" && value !== null && !Array.isArray(value) && value.resultType === "input_required"; +/** +* Checks if a value is a valid {@linkcode TaskAugmentedRequestParams}. +* @param value - The value to check. +* +* @returns True if the value is a valid {@linkcode TaskAugmentedRequestParams}, false otherwise. +* +* @deprecated Recognizes 2025-11-25 task wire vocabulary, which has no SDK +* runtime; kept importable for interoperability only. +*/ +const isTaskAugmentedRequestParams = (value) => TaskAugmentedRequestParamsSchema.safeParse(value).success; +const src_CX2iR2pK_isInitializeRequest = (value) => InitializeRequestSchema.safeParse(value).success; +const isInitializedNotification = (value) => InitializedNotificationSchema.safeParse(value).success; +function assertCompleteRequestPrompt(request) { + if (request.params.ref.type !== "ref/prompt") throw new TypeError(`Expected CompleteRequestPrompt, but got ${request.params.ref.type}`); +} +function assertCompleteRequestResourceTemplate(request) { + if (request.params.ref.type !== "ref/resource") throw new TypeError(`Expected CompleteRequestResourceTemplate, but got ${request.params.ref.type}`); +} + +//#endregion +//#region ../core-internal/src/shared/mcpParamHeaders.ts +/** The fixed prefix every custom-parameter header carries. */ +const MCP_PARAM_HEADER_PREFIX = "Mcp-Param-"; +/** The schema-extension property name a tool's `inputSchema` carries. */ +const X_MCP_HEADER_KEY = "x-mcp-header"; +/** +* RFC 9110 §5.1 `token` syntax (`1*tchar`). Rejects empty, space, control +* characters (including CR/LF), and the listed delimiters. +*/ +const RFC9110_TOKEN = /^[!#$%&'*+\-.^_`|~0-9A-Za-z]+$/; +/** +* JSON Schema `type` values the spec admits on an `x-mcp-header` property. +* +* The spec text names `integer`, `string`, `boolean` and explicitly excludes +* `number`. The published conformance referee at the pinned release ships its +* `http-custom-headers` scenario with two `type: "number"` `x-mcp-header` +* parameters and expects the client to mirror them, so `number` is accepted +* here so that the conformance gate passes; the discrepancy is tracked +* upstream. Everything else (`object`, `array`, `null`, absent) is rejected. +*/ +const PERMITTED_X_MCP_HEADER_TYPES = new Set([ + "string", + "integer", + "boolean", + "number" +]); +/** +* Scan a tool's JSON-serialized `inputSchema` for `x-mcp-header` declarations +* and validate every constraint the spec places on them. Returns either the +* collected declarations (possibly empty) or the first violated constraint. +* +* The walk descends through `properties` at any depth (the spec's "any nesting +* depth" clause). The static-reachability MUST is enforced as a structural +* sweep: every position the chain MUST NOT pass through (`items`/ +* `additionalProperties`, `oneOf`/`anyOf`/`allOf`/`not`, `if`/`then`/`else`, +* `$defs`, `$ref` targets within `$defs`) is visited too, and an +* `x-mcp-header` found anywhere on that path invalidates the schema — "an +* annotation anywhere else makes the tool definition invalid". +*/ +function src_CX2iR2pK_scanXMcpHeaderDeclarations(inputSchema) { + const declarations = []; + const seenLower = /* @__PURE__ */ new Map(); + const visit = (node, path, reachable) => { + if (node === null || typeof node !== "object") return void 0; + const schema = node; + if (X_MCP_HEADER_KEY in schema) { + if (!reachable || path.length === 0) return `${pathName(path)}: x-mcp-header is only permitted on properties statically reachable via a chain of 'properties' keys (not under items, additionalProperties, oneOf/anyOf/allOf/not, if/then/else, or $ref)`; + const raw = schema[X_MCP_HEADER_KEY]; + if (typeof raw !== "string" || raw.length === 0) return `${pathName(path)}: x-mcp-header MUST be a non-empty string`; + if (!RFC9110_TOKEN.test(raw)) return `${pathName(path)}: x-mcp-header '${raw}' is not a valid RFC 9110 token (no spaces, control characters or HTTP delimiters)`; + const type = typeof schema.type === "string" ? schema.type : void 0; + if (type === void 0 || !PERMITTED_X_MCP_HEADER_TYPES.has(type)) return `${pathName(path)}: x-mcp-header is only permitted on primitive-typed properties (string, integer, boolean); got ${type ?? ""}`; + const lower = raw.toLowerCase(); + const prior = seenLower.get(lower); + if (prior !== void 0) return `x-mcp-header '${raw}' is not case-insensitively unique (also declared as '${prior}')`; + seenLower.set(lower, raw); + declarations.push({ + path, + headerName: raw, + type + }); + } + const properties = schema.properties; + if (properties !== null && typeof properties === "object") for (const [key, child] of Object.entries(properties)) { + const fault$1 = visit(child, [...path, key], reachable); + if (fault$1 !== void 0) return fault$1; + } + for (const k of NON_REACHABLE_SUBSCHEMA_KEYWORDS) { + const sub = schema[k]; + if (sub === void 0) continue; + const branches = Array.isArray(sub) ? sub : sub !== null && typeof sub === "object" && OBJECT_VALUED_SUBSCHEMA_KEYWORDS.has(k) ? Object.values(sub) : [sub]; + for (const branch of branches) { + const fault$1 = visit(branch, [...path, `<${k}>`], false); + if (fault$1 !== void 0) return fault$1; + } + } + }; + const fault = visit(inputSchema, [], true); + return fault === void 0 ? { + valid: true, + declarations + } : { + valid: false, + reason: fault + }; +} +/** +* JSON Schema keywords whose subschemas the SEP-2243 static-reachability +* constraint excludes from the `properties`-only chain. An `x-mcp-header` +* found under any of these invalidates the tool definition. +*/ +const NON_REACHABLE_SUBSCHEMA_KEYWORDS = [ + "items", + "prefixItems", + "contains", + "additionalProperties", + "unevaluatedProperties", + "unevaluatedItems", + "propertyNames", + "patternProperties", + "dependentSchemas", + "oneOf", + "anyOf", + "allOf", + "not", + "if", + "then", + "else", + "$defs", + "definitions" +]; +/** +* Subschema-carrying keywords whose value is a `name → subschema` object +* (not a single subschema or array of subschemas). The visit branches over +* `Object.values()` for these. +*/ +const OBJECT_VALUED_SUBSCHEMA_KEYWORDS = new Set([ + "patternProperties", + "dependentSchemas", + "$defs", + "definitions" +]); +function pathName(path) { + return path.length === 0 ? "" : path.join("."); +} +const BASE64_SENTINEL_PREFIX = "=?base64?"; +const BASE64_SENTINEL_SUFFIX = "?="; +const BASE64_CANONICAL = /^(?:[A-Za-z0-9+/]{4})*(?:[A-Za-z0-9+/]{2}==|[A-Za-z0-9+/]{3}=)?$/; +const CANONICAL_DECIMAL = /^-?\d+(\.\d+)?$/; +/** +* Convert a primitive argument value to its string representation per the +* spec's type-conversion rules: strings pass through, integers and numbers +* become their decimal string, booleans become lowercase `'true'` / `'false'`. +* Non-finite numbers and integers outside the safe range are refused (the +* caller treats `undefined` as "do not emit a header for this value"). +*/ +function mcpParamPrimitiveToString(value) { + if (typeof value === "string") return value; + if (typeof value === "boolean") return value ? "true" : "false"; + if (typeof value === "number") { + if (!Number.isFinite(value)) return void 0; + if (Number.isInteger(value) && !Number.isSafeInteger(value)) return void 0; + return String(value); + } +} +function base64ToUtf8(b64) { + const bin = atob(b64); + const bytes = new Uint8Array(bin.length); + for (let i = 0; i < bin.length; i++) bytes[i] = bin.codePointAt(i); + return new TextDecoder("utf-8", { fatal: true }).decode(bytes); +} +/** +* Decode an `Mcp-Param-*` header value: when it carries the Base64 sentinel, +* the payload is decoded as UTF-8; otherwise the value is returned as-is. +* Returns `undefined` when the sentinel is present but the payload is not +* canonical Base64 (or not valid UTF-8) — the spec requires servers to reject +* such values. +*/ +function decodeMcpParamValue(value) { + if (!(value.startsWith(BASE64_SENTINEL_PREFIX) && value.endsWith(BASE64_SENTINEL_SUFFIX))) return value; + const b64 = value.slice(9, value.length - 2); + if (!BASE64_CANONICAL.test(b64)) return void 0; + try { + return base64ToUtf8(b64); + } catch { + return; + } +} +function valueAtPath(root, path) { + let node = root; + for (const key of path) { + if (node === null || typeof node !== "object") return void 0; + node = node[key]; + } + return node; +} +/** +* The header/body comparison the server performs at tool-resolution time. +* +* For each `x-mcp-header` declaration on the named tool: when the body +* `arguments` carries a value, the matching `Mcp-Param-{Name}` header MUST be +* present and decode to an equal value; when the body value is `null` or +* absent the server MUST NOT expect the header (a present header is ignored). +* A sentinel-carrying header whose payload is not canonical Base64 / valid +* UTF-8 is rejected as invalid characters. +* +* Integer-typed declarations are compared numerically (the spec's SHOULD — +* `42.0` and `42` are equal); everything else is compared as decoded strings. +* +* Returns `undefined` when every check passes, or an +* {@linkcode InboundLadderRejection} carrying the same `-32020` +* (`HeaderMismatch`) shape the inbound classifier emits for the +* standard-header cross-checks — `400 Bad Request` with the disagreeing pair +* in `data.mismatch`. +*/ +function src_CX2iR2pK_validateMcpParamHeaders(declarations, args, headers) { + for (const decl of declarations) { + const headerKey = `${MCP_PARAM_HEADER_PREFIX}${decl.headerName}`; + const headerValue = headers.get(headerKey); + const bodyRaw = valueAtPath(args, decl.path); + if (bodyRaw === void 0 || bodyRaw === null) continue; + const bodyString = mcpParamPrimitiveToString(bodyRaw); + if (bodyString === void 0) continue; + if (headerValue === null) return paramHeaderMismatchRejection("param-header-missing", headerKey, `the body carries ${pathName(decl.path)}=${JSON.stringify(bodyRaw)} but the ${headerKey} header is absent`); + const decoded = decodeMcpParamValue(headerValue); + if (decoded === void 0) return paramHeaderMismatchRejection("param-header-invalid-encoding", headerKey, `the ${headerKey} header carries an invalid Base64 sentinel value`); + if (!((decl.type === "integer" || decl.type === "number") && CANONICAL_DECIMAL.test(decoded) && typeof bodyRaw === "number" ? Number(decoded) === bodyRaw : decoded === bodyString)) return paramHeaderMismatchRejection("param-header-mismatch", headerKey, `the ${headerKey} header decodes to ${JSON.stringify(decoded)} but the body carries ${pathName(decl.path)}=${JSON.stringify(bodyRaw)}`); + } +} +/** +* Build the `-32020` (`HeaderMismatch`) rejection for an `Mcp-Param-*` +* disagreement. Same shape as the inbound classifier's standard-header +* cross-check mismatch (HTTP `400`, `data.mismatch` naming the disagreeing +* pair, `settled: true`); only the rung differs because this check runs at the +* pre-dispatch step against a known tool's schema rather than at the edge. +*/ +function paramHeaderMismatchRejection(cell, header, body) { + return { + kind: "reject", + rung: "param-header-validation", + cell, + httpStatus: 400, + code: HEADER_MISMATCH_ERROR_CODE, + message: `Bad Request: the request headers and body disagree: ${body}`, + data: { mismatch: { + header, + body + } }, + settled: true + }; +} + +//#endregion +//#region ../core-internal/src/shared/inboundClassification.ts +/** +* Inbound HTTP request classification and the inbound validation ladder +* (protocol revision 2026-07-28). +* +* `classifyInboundRequest` is the body-primary era predicate for an HTTP +* entry that serves both protocol eras on one endpoint. It is evaluated +* exactly once, at the entry boundary, on the already-parsed request body: +* +* - `initialize` is a legacy-era request by definition (the modern era has no +* `initialize` handshake) — unless it carries a valid envelope claim naming +* a modern revision, in which case the claim wins and the request is +* classified like any other enveloped request (the modern era then answers +* it with method-not-found, exactly like every other method it does not +* define). +* - A request whose `params._meta` carries the reserved protocol-version key +* claims the per-request envelope mechanism and classifies into the era the +* named revision belongs to (a malformed envelope behind a present claim is +* a validation error, never a silent fall back to legacy handling). +* - A request without a claim is legacy-era traffic. +* - The `MCP-Protocol-Version` header is a cross-check only: it never +* upgrades or downgrades a body-derived classification, and a disagreement +* between header and body is an explicit ladder outcome. +* - Notifications carry no envelope claim of their own under the current +* spec, so for notification POSTs without a body claim the modern header is +* determinative; the `Mcp-Method` header is validated against the body when +* the message classifies modern and is never enforced on legacy traffic. +* A notification that does carry a claim is treated body-primary like a +* request, and a malformed claim is rejected the same way a request's +* malformed claim is — never silently resolved against the header. +* The notification-POST header cross-checks here are an SDK-defensive +* posture, not a spec requirement: the spec leaves header rules for posted +* notifications undefined (core client notifications do not occur over +* Streamable HTTP); applying the request rules symmetrically is what an +* ecosystem custom-notification POST expects, and the −32020 cells stay +* passing for them. +* - `GET`/`DELETE` (and any other non-`POST` method) are body-less 2025-era +* session operations: the modern era is `POST`-only, so they are routed to +* legacy serving when it is configured and rejected otherwise. +* - Array (batch) bodies are classified element-wise: an array containing a +* modern-claiming or invalid element is rejected, an all-legacy array is +* legacy traffic unchanged, and a single-element array is still an array. +* +* The classifier returns plain values (it never throws and never touches a +* transport): a routing outcome (`legacy`/`modern`) or a ladder rejection +* carrying the JSON-RPC error to emit and the HTTP status to emit it with. +* Legacy routing outcomes deliberately carry NO `MessageClassification` — +* legacy and hand-wired traffic is never classified, which keeps its +* dispatch behavior byte-identical to today's. +* +* Error codes for the modern-path rejection cells follow the published +* conformance suite (and the spec text it asserts): +* +* - A header/body cross-check mismatch (the `MCP-Protocol-Version` header +* disagreeing with the body, or the `Mcp-Method` header disagreeing with the +* body method) is rejected with `-32020` (`HeaderMismatch`) on HTTP 400. +* - A request whose protocol-version header names a modern revision but whose +* body carries no `_meta` envelope claim — including an envelope present but +* missing the required protocol-version key — is rejected with `-32602` +* (invalid params) naming the missing key(s), on HTTP 400. +* +* Should a future spec revision or conformance release change these +* assignments, the affected cells are re-derived against that release; the +* `settled` flag on {@linkcode InboundLadderRejection} stays available to mark +* a cell provisional again while such a change is in flight. +*/ +/** +* The error code emitted for header/body cross-check mismatches: the +* `MCP-Protocol-Version` header disagreeing with the body's envelope claim (or +* with the body's classification), and the `Mcp-Method` header disagreeing +* with the body method. +* +* `-32020` is the draft schema's `HEADER_MISMATCH` constant (the SEP-2243 +* `HeaderMismatch` code; the spec requires HTTP 400 for it), as also asserted +* by the published conformance suite for header-validation failures. It has no +* {@linkcode ProtocolErrorCode} member because it is not part of the 2025-era +* wire vocabulary; the validation ladder is its only emitter. +*/ +const HEADER_MISMATCH_ERROR_CODE = -32020; +/** +* The inbound validation ladder, expressed as data rather than control flow. +* +* The edge rungs are evaluated by {@linkcode classifyInboundRequest}; the +* dispatch rungs are evaluated by the protocol layer once the classified +* message is injected into a per-request server instance (the era registry +* gate, the envelope requiredness check, and per-method params validation). +* The client-capability rung is evaluated by the HTTP entry itself, +* pre-dispatch, on the validated envelope the classifier produced — see that +* rung's rationale for the ordering caveat. The order is the precedence: a +* request that fails several rungs is answered by the earliest one. +*/ +const INBOUND_VALIDATION_LADDER = [ + { + 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: [src_CX2iR2pK_ProtocolErrorCode.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: [HEADER_MISMATCH_ERROR_CODE, src_CX2iR2pK_ProtocolErrorCode.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: [src_CX2iR2pK_ProtocolErrorCode.InvalidParams], + conformance: ["server-stateless"], + rationale: "A present envelope claim with a malformed envelope — and a missing envelope on a request whose protocol-version header names a modern revision — 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: [src_CX2iR2pK_ProtocolErrorCode.MethodNotFound], + conformance: ["server-stateless"], + rationale: "Method existence outranks parameter validity: a method absent from the negotiated revision’s 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: [src_CX2iR2pK_ProtocolErrorCode.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: [HEADER_MISMATCH_ERROR_CODE], + conformance: ["http-header-validation"], + rationale: "SEP-2243 standard `Mcp-Method` / `Mcp-Name` headers — presence, sentinel decoding, and `Mcp-Name` ↔ body cross-check — are validated by the HTTP entry on a modern-classified request after the supported-revision gate and before dispatch. The classifier’s 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–6) are consulted." + }, + { + rung: "client-capabilities", + order: 8, + evaluatedAt: "pre-dispatch", + codes: [src_CX2iR2pK_ProtocolErrorCode.MissingRequiredClientCapability], + conformance: ["server-stateless"], + rationale: "The capability requirement is checked by the HTTP entry, pre-dispatch, against the validated envelope the classifier produced — 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: [HEADER_MISMATCH_ERROR_CODE], + conformance: ["http-custom-header-server-validation"], + rationale: "SEP-2243 `Mcp-Param-*` headers are validated against the named tool’s `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." + } +]; +/** +* HTTP status for ladder-originated JSON-RPC error codes. +* +* Keyed on origin, not on the bare code: this table only applies to errors +* the ladder (or a pre-handler protocol gate) produced. Errors produced by +* request handlers — whatever their code — stay in-band on HTTP 200, and are +* never mapped to an HTTP status by this table; in particular `-32603` and +* domain-specific codes never become a blanket 500. The single exception is +* `MissingRequiredClientCapability` (-32021) — see +* {@linkcode httpStatusForErrorCode}. +* +* `-32602` (invalid params) deliberately has NO entry: the only invalid-params +* rejection that maps to HTTP 400 is the classifier's own envelope rung +* short-circuit, which carries its HTTP status directly. A dispatch- or +* handler-produced invalid-params error is always in-band. +*/ +const src_CX2iR2pK_LADDER_ERROR_HTTP_STATUS = { + [src_CX2iR2pK_ProtocolErrorCode.ParseError]: 400, + [src_CX2iR2pK_ProtocolErrorCode.InvalidRequest]: 400, + [src_CX2iR2pK_ProtocolErrorCode.MethodNotFound]: 404, + [src_CX2iR2pK_ProtocolErrorCode.UnsupportedProtocolVersion]: 400, + [src_CX2iR2pK_ProtocolErrorCode.MissingRequiredClientCapability]: 400, + [HEADER_MISMATCH_ERROR_CODE]: 400 +}; +/** +* The HTTP status to answer a JSON-RPC error with, keyed on the error's +* origin. `in-band` errors (anything produced by a request handler) are +* HTTP 200 — the JSON-RPC error response is the payload, not an HTTP +* failure — with ONE exception: `MissingRequiredClientCapability` (-32021), +* whose 400 the spec mandates on the error itself with no origin condition, +* and which the SDK genuinely produces after dispatch (the `input_required` +* capability gate). A handler relaying some downstream peer's `-32020`/`-32022` +* is NOT that peer's spec error and stays in-band like every other handler +* code. `ladder` errors map through {@linkcode LADDER_ERROR_HTTP_STATUS}. +* +* The per-request transport intentionally does NOT delegate to this function: +* its `?? 400` ladder fallback is only correct for entry-gate codes known to +* the table, and would wrongly map dispatch-window errors outside it (a +* window `-32602` must stay in-band on 200). The transport indexes the table +* directly; keep the two in agreement when editing either. +*/ +function src_CX2iR2pK_httpStatusForErrorCode(code, origin) { + if (origin === "in-band") return code === src_CX2iR2pK_ProtocolErrorCode.MissingRequiredClientCapability ? 400 : 200; + return src_CX2iR2pK_LADDER_ERROR_HTTP_STATUS[code] ?? 400; +} +function src_CX2iR2pK_rejection(rung, cell, httpStatus, error, settled) { + return { + kind: "reject", + rung, + cell, + httpStatus, + code: error.code, + message: error.message, + ...error.data !== void 0 && { data: error.data }, + settled + }; +} +function crossCheckMismatch(cell, header, body, rung = "era-classification") { + return src_CX2iR2pK_rejection(rung, cell, 400, new src_CX2iR2pK_ProtocolError(HEADER_MISMATCH_ERROR_CODE, `Bad Request: the request headers and body disagree: ${body}`, { mismatch: { + header, + body + } }), true); +} +/** +* The methods whose body carries a `params.name` / `params.uri` value the +* `Mcp-Name` header must mirror, and which body field supplies it (SEP-2243 +* § Standard Request Headers, `Required For` column). +*/ +const MCP_NAME_HEADER_SOURCE = (/* unused pure expression or super */ null && ({ + "tools/call": "name", + "prompts/get": "name", + "resources/read": "uri" +})); +/** Strip RFC 9110 optional whitespace (SP / HTAB) around a field value in linear time. */ +function stripHttpOws(value) { + let start = 0; + while (start < value.length) { + const code = value.codePointAt(start); + if (code !== 9 && code !== 32) break; + start += 1; + } + let end = value.length; + while (end > start) { + const code = value.codePointAt(end - 1); + if (code !== 9 && code !== 32) break; + end -= 1; + } + return start === 0 && end === value.length ? value : value.slice(start, end); +} +/** +* SEP-2243 standard-header server-side validation, evaluated by the HTTP +* entry on a modern-classified request immediately after +* {@linkcode classifyInboundRequest} returns a modern route. +* +* Returns the `-32020` (`HeaderMismatch`) ladder rejection (HTTP `400`, +* `standard-header-validation` rung — the same shape +* {@linkcode classifyInboundRequest} already emits on the edge +* `era-classification` rung for the `MCP-Protocol-Version` and +* `Mcp-Method` *mismatch* cells) when: +* +* - the required `Mcp-Method` header is absent; +* - the required `Mcp-Name` header is absent on a `tools/call`, +* `prompts/get`, or `resources/read` request whose body carries the +* `params.name` / `params.uri` value the header mirrors; +* - the `Mcp-Name` header carries an invalid `=?base64?…?=` sentinel; or +* - the (decoded) `Mcp-Name` value disagrees with the body's +* `params.name` / `params.uri`. +* +* Returns `undefined` (pass) for notifications (the spec table reads +* "All requests"), for methods that have no `Mcp-Name` source, and when the +* headers agree with the body. Never enforced on legacy traffic — the entry +* only calls this on a modern route. +* +* Kept separate from {@linkcode classifyInboundRequest} so that a body-only +* call to the classifier (no headers passed) keeps routing a modern request +* unchanged: the classifier remains a pure body-primary router, and this +* function is the presence/`Mcp-Name` half of the standard-header rung the +* entry layers on top. +*/ +function src_CX2iR2pK_validateStandardRequestHeaders(request, route) { + if (route.messageKind !== "request") return; + const method = route.message.method; + if (request.mcpMethodHeader === void 0) return crossCheckMismatch("method-header-missing", "(missing)", `the body names method ${method} but the required Mcp-Method header is absent`, "standard-header-validation"); + const sourceField = Object.hasOwn(MCP_NAME_HEADER_SOURCE, method) ? MCP_NAME_HEADER_SOURCE[method] : void 0; + if (sourceField === void 0) return; + const sourceValue = route.message.params?.[sourceField]; + const bodyValue = typeof sourceValue === "string" ? sourceValue : void 0; + if (request.mcpNameHeader === void 0) { + if (bodyValue === void 0) return; + return crossCheckMismatch("name-header-missing", "(missing)", `the body carries params.${sourceField}="${bodyValue}" but the required Mcp-Name header is absent`, "standard-header-validation"); + } + const normalizedNameHeader = stripHttpOws(request.mcpNameHeader); + const decoded = decodeMcpParamValue(normalizedNameHeader); + if (decoded === void 0) return crossCheckMismatch("name-header-invalid-encoding", normalizedNameHeader, "the Mcp-Name header carries an invalid Base64 sentinel value", "standard-header-validation"); + if (bodyValue !== void 0 && decoded !== bodyValue) return crossCheckMismatch("name-header-mismatch", normalizedNameHeader, `the body carries params.${sourceField}="${bodyValue}" but the Mcp-Name header names "${decoded}"`, "standard-header-validation"); +} +function isPlainObject$2(value) { + return value !== null && typeof value === "object" && !Array.isArray(value); +} +function classificationForClaim(claimedVersion) { + if (claimedVersion === void 0) return { era: "modern" }; + return { + era: isModernProtocolVersion(claimedVersion) ? "modern" : "legacy", + revision: claimedVersion + }; +} +/** +* Whether a request's params carry a per-request envelope claim that is both +* well-formed and names a modern protocol revision. +* +* Used by the `initialize` precedence rule: only such a claim overrides the +* `initialize` ⇒ legacy-handshake classification — a request carrying a valid +* modern envelope is a modern request regardless of its method name, and the +* modern era then answers `initialize` exactly like any other method it does +* not define (method-not-found). A malformed claim, or one naming a pre-2026 +* revision, keeps the legacy-handshake routing unchanged. +* +* Exported on the core internal barrel for the stdio serving entry, which +* applies the same precedence rule to a connection's opening message; not +* public API. +*/ +function src_CX2iR2pK_carriesValidModernEnvelopeClaim(params) { + if (!src_CX2iR2pK_hasEnvelopeClaim(params)) return false; + const claimedVersion = src_CX2iR2pK_envelopeClaimVersion(params); + if (claimedVersion === void 0 || !isModernProtocolVersion(claimedVersion)) return false; + const meta = src_CX2iR2pK_requestMetaOf(params); + return meta !== void 0 && src_CX2iR2pK_validateEnvelopeMeta(meta).length === 0; +} +function classifyBatch(body) { + if (body.length === 0) return src_CX2iR2pK_rejection("jsonrpc-shape", "empty-batch", 400, new src_CX2iR2pK_ProtocolError(src_CX2iR2pK_ProtocolErrorCode.InvalidRequest, "Bad Request: empty JSON-RPC batch"), true); + for (const element of body) { + if (src_CX2iR2pK_hasEnvelopeClaim(isPlainObject$2(element) ? element["params"] : void 0)) return src_CX2iR2pK_rejection("jsonrpc-shape", "batch-with-modern-element", 400, new src_CX2iR2pK_ProtocolError(src_CX2iR2pK_ProtocolErrorCode.InvalidRequest, "Bad Request: JSON-RPC batches may not contain requests for protocol revision 2026-07-28 or later"), true); + if (!(src_CX2iR2pK_isJSONRPCRequest(element) || src_CX2iR2pK_isJSONRPCNotification(element) || src_CX2iR2pK_isJSONRPCResultResponse(element) || src_CX2iR2pK_isJSONRPCErrorResponse(element))) return src_CX2iR2pK_rejection("jsonrpc-shape", "batch-with-invalid-element", 400, new src_CX2iR2pK_ProtocolError(src_CX2iR2pK_ProtocolErrorCode.InvalidRequest, "Bad Request: JSON-RPC batch contains an invalid message"), true); + } + return { + kind: "legacy", + reason: "batch" + }; +} +function classifyRequestBody(request, body) { + const params = body.params; + const method = body.method; + const headerVersion = request.protocolVersionHeader; + const headerNamesModern = headerVersion !== void 0 && isModernProtocolVersion(headerVersion); + if (method === "initialize" && !src_CX2iR2pK_carriesValidModernEnvelopeClaim(params)) { + if (headerNamesModern) return crossCheckMismatch("initialize-with-modern-header", headerVersion, "an initialize request (legacy handshake) was sent with a modern MCP-Protocol-Version header"); + const requestedVersion = isPlainObject$2(params) && typeof params["protocolVersion"] === "string" ? params["protocolVersion"] : void 0; + return { + kind: "legacy", + reason: "initialize", + ...requestedVersion !== void 0 && { requestedVersion } + }; + } + if (src_CX2iR2pK_hasEnvelopeClaim(params)) { + const meta = src_CX2iR2pK_requestMetaOf(params); + const firstIssue = (meta === void 0 ? [] : src_CX2iR2pK_validateEnvelopeMeta(meta))[0]; + if (firstIssue !== void 0) return src_CX2iR2pK_rejection("envelope", "envelope-invalid", 400, new src_CX2iR2pK_ProtocolError(src_CX2iR2pK_ProtocolErrorCode.InvalidParams, `Invalid _meta envelope for protocol revision 2026-07-28: ${firstIssue.key}: ${firstIssue.problem}`, { envelope: firstIssue }), true); + const claimedVersion = src_CX2iR2pK_envelopeClaimVersion(params); + if (headerVersion !== void 0 && claimedVersion !== void 0 && headerVersion !== claimedVersion) return crossCheckMismatch("header-body-version-mismatch", headerVersion, `the body envelope names protocol version ${claimedVersion} but the MCP-Protocol-Version header names ${headerVersion}`); + if (request.mcpMethodHeader !== void 0 && request.mcpMethodHeader !== method) return crossCheckMismatch("method-header-mismatch", request.mcpMethodHeader, `the body names method ${method} but the Mcp-Method header names ${request.mcpMethodHeader}`); + return { + kind: "modern", + messageKind: "request", + message: body, + classification: classificationForClaim(claimedVersion) + }; + } + if (headerNamesModern) { + const meta = src_CX2iR2pK_requestMetaOf(params); + const missingFromEnvelope = src_CX2iR2pK_validateEnvelopeMeta(meta ?? {}).filter((issue) => issue.problem === "missing").map((issue) => issue.key); + const missing = meta === void 0 ? ["_meta"] : missingFromEnvelope.length > 0 ? missingFromEnvelope : [PROTOCOL_VERSION_META_KEY]; + return src_CX2iR2pK_rejection("envelope", "modern-header-without-claim", 400, new src_CX2iR2pK_ProtocolError(src_CX2iR2pK_ProtocolErrorCode.InvalidParams, `Invalid params: the MCP-Protocol-Version header names protocol revision ${headerVersion}, but the request is missing the required per-request envelope key(s): ${missing.join(", ")}`, { envelope: { missing } }), true); + } + return { + kind: "legacy", + reason: "no-claim", + ...headerVersion !== void 0 && { requestedVersion: headerVersion } + }; +} +function classifyNotificationBody(request, body) { + const params = body.params; + const method = body.method; + const headerVersion = request.protocolVersionHeader; + const headerNamesModern = headerVersion !== void 0 && isModernProtocolVersion(headerVersion); + if (src_CX2iR2pK_hasEnvelopeClaim(params)) { + const claimedVersion = src_CX2iR2pK_envelopeClaimVersion(params); + if (claimedVersion === void 0) { + const meta = src_CX2iR2pK_requestMetaOf(params); + const claimIssue = (meta === void 0 ? [] : src_CX2iR2pK_validateEnvelopeMeta(meta)).find((issue) => issue.key === PROTOCOL_VERSION_META_KEY) ?? { + key: PROTOCOL_VERSION_META_KEY, + problem: "expected a protocol version string" + }; + return src_CX2iR2pK_rejection("envelope", "notification-envelope-invalid", 400, new src_CX2iR2pK_ProtocolError(src_CX2iR2pK_ProtocolErrorCode.InvalidParams, `Invalid _meta envelope for protocol revision 2026-07-28: ${claimIssue.key}: ${claimIssue.problem}`, { envelope: claimIssue }), true); + } + if (headerVersion !== void 0 && headerVersion !== claimedVersion) return crossCheckMismatch("notification-header-body-version-mismatch", headerVersion, `the notification envelope names protocol version ${claimedVersion} but the MCP-Protocol-Version header names ${headerVersion}`); + const classification = classificationForClaim(claimedVersion); + if (classification.era === "modern" && request.mcpMethodHeader !== void 0 && request.mcpMethodHeader !== method) return crossCheckMismatch("notification-method-header-mismatch", request.mcpMethodHeader, `the notification body names method ${method} but the Mcp-Method header names ${request.mcpMethodHeader}`); + return { + kind: "modern", + messageKind: "notification", + message: body, + classification + }; + } + if (headerNamesModern) { + if (request.mcpMethodHeader !== void 0 && request.mcpMethodHeader !== method) return crossCheckMismatch("notification-method-header-mismatch", request.mcpMethodHeader, `the notification body names method ${method} but the Mcp-Method header names ${request.mcpMethodHeader}`); + return { + kind: "modern", + messageKind: "notification", + message: body, + classification: { + era: "modern", + revision: headerVersion + } + }; + } + return { + kind: "legacy", + reason: "notification", + ...headerVersion !== void 0 && { requestedVersion: headerVersion } + }; +} +/** +* Classifies one inbound HTTP request for dual-era serving. +* +* The body-primary predicate, evaluated once at the entry boundary: see the +* module documentation for the rules. Returns a routing outcome (`legacy` or +* `modern`) or a ladder rejection; it never throws. +*/ +function src_CX2iR2pK_classifyInboundRequest(request) { + request = { + ...request, + ...request.protocolVersionHeader !== void 0 && { protocolVersionHeader: stripHttpOws(request.protocolVersionHeader) }, + ...request.mcpMethodHeader !== void 0 && { mcpMethodHeader: stripHttpOws(request.mcpMethodHeader) }, + ...request.mcpNameHeader !== void 0 && { mcpNameHeader: stripHttpOws(request.mcpNameHeader) } + }; + if (request.httpMethod.toUpperCase() !== "POST") return { + kind: "legacy", + reason: "http-method" + }; + const body = request.body; + if (Array.isArray(body)) return classifyBatch(body); + if (src_CX2iR2pK_isJSONRPCResultResponse(body) || src_CX2iR2pK_isJSONRPCErrorResponse(body)) return { + kind: "legacy", + reason: "response" + }; + if (isPlainObject$2(body) && src_CX2iR2pK_isJSONRPCRequest(body)) return classifyRequestBody(request, body); + if (isPlainObject$2(body) && src_CX2iR2pK_isJSONRPCNotification(body)) return classifyNotificationBody(request, body); + return src_CX2iR2pK_rejection("jsonrpc-shape", "invalid-json-rpc-body", 400, new src_CX2iR2pK_ProtocolError(src_CX2iR2pK_ProtocolErrorCode.InvalidRequest, "Bad Request: the request body is not a valid JSON-RPC message"), true); +} +/** +* The rejection a modern-only endpoint (no legacy serving configured) +* answers a legacy-classified request with. +* +* - Envelope-less requests (including `initialize`) are answered with the +* unsupported-protocol-version error carrying the endpoint's supported +* versions and echoing the version the request named (when it named one — +* `requested` is omitted rather than fabricated when the request named no +* version at all), so a legacy client can discover what the endpoint serves +* from the error alone. +* - Posted responses and batch arrays are invalid requests on the modern era. +* - Non-`POST` methods are not allowed. +* - Legacy-classified notifications return `undefined`: the caller answers +* 202 with no body and does not dispatch the notification (accept-and-drop). +*/ +function src_CX2iR2pK_modernOnlyStrictRejection(route, supportedVersions) { + switch (route.reason) { + case "http-method": return src_CX2iR2pK_rejection("http-method", "modern-only-method-not-allowed", 405, new src_CX2iR2pK_ProtocolError(-32e3, "Method not allowed."), true); + case "batch": return src_CX2iR2pK_rejection("jsonrpc-shape", "modern-only-batch-not-supported", 400, new src_CX2iR2pK_ProtocolError(src_CX2iR2pK_ProtocolErrorCode.InvalidRequest, "Bad Request: JSON-RPC batches are not supported by this endpoint"), true); + case "response": return src_CX2iR2pK_rejection("jsonrpc-shape", "modern-only-response-post", 400, new src_CX2iR2pK_ProtocolError(src_CX2iR2pK_ProtocolErrorCode.InvalidRequest, "Bad Request: JSON-RPC responses cannot be posted to this endpoint"), true); + case "notification": return; + case "initialize": + case "no-claim": { + const requested = route.requestedVersion; + return src_CX2iR2pK_rejection("era-classification", "modern-only-missing-envelope", 400, requested === void 0 ? new src_CX2iR2pK_ProtocolError(src_CX2iR2pK_ProtocolErrorCode.UnsupportedProtocolVersion, "Unsupported protocol version: the request did not name a protocol version", { supported: [...supportedVersions] }) : new src_CX2iR2pK_UnsupportedProtocolVersionError({ + supported: [...supportedVersions], + requested + }), true); + } + } +} + +//#endregion +//#region ../core-internal/src/util/schema.ts +/** +* Internal Zod schema utilities for protocol handling. +* These are used internally by the SDK for protocol message validation. +*/ +/** +* Parses data against a Zod schema (synchronous). +* Returns a discriminated union with success/error. +*/ +function parseSchema(schema, data) { + return parse_safeParse(schema, data); +} +/** +* Union of the declared shape keys across several Zod object schemas. +*/ +function shapeKeys(schemas) { + return new Set(schemas.flatMap((schema) => Object.keys(schema.shape))); +} + +//#endregion +//#region ../core-internal/src/util/standardSchema.ts +/** +* Standard Schema utilities for user-provided schemas. +* Supports Zod v4, Valibot, ArkType, and other Standard Schema implementations. +* @see https://standardschema.dev +*/ +function isStandardSchema(schema) { + if (schema == null) return false; + const schemaType = typeof schema; + if (schemaType !== "object" && schemaType !== "function") return false; + if (!("~standard" in schema)) return false; + return typeof schema["~standard"]?.validate === "function"; +} +let warnedZodFallback = false; +/** JSON Schema draft targeted by every conversion; shared so pattern references above stay in lockstep. */ +const JSON_SCHEMA_CONVERSION_TARGET = "draft-2020-12"; +/** +* Converts a StandardSchema to JSON Schema for use as an MCP tool/prompt schema. +* +* MCP requires `type: "object"` at the root of tool `inputSchema` and prompt +* argument schemas; `outputSchema` may have any JSON Schema root (SEP-2106). +* Zod's discriminated unions emit `{oneOf: [...]}` without a top-level `type`, +* so for `io: 'input'` this function defaults `type` to `"object"` when absent +* and throws on an explicit non-object `type` (e.g. `z.string()`). For +* `io: 'output'` a non-object root is returned as-is; the `"object"` default is +* applied only when the root is provably object-shaped. +*/ +function standardSchemaToJsonSchema(schema, io = "input") { + const std = schema["~standard"]; + let result; + if (std.jsonSchema) result = std.jsonSchema[io]({ target: JSON_SCHEMA_CONVERSION_TARGET }); + else if (std.vendor === "zod") { + if (!("_zod" in schema)) 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()."); + if (!warnedZodFallback) { + warnedZodFallback = true; + 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."); + } + result = toJSONSchema(schema, { + target: JSON_SCHEMA_CONVERSION_TARGET, + io + }); + } else throw new Error(`Schema library "${std.vendor}" does not implement StandardJSONSchemaV1 (\`~standard.jsonSchema\`). Upgrade to a version that does, or wrap your JSON Schema with fromJsonSchema().`); + if (io === "output") { + if (result.type !== void 0) return result; + return isProvablyObjectShapedRoot(result) ? { + type: "object", + ...result + } : result; + } + if (result.type !== void 0 && result.type !== "object") throw new Error(`MCP tool and prompt schemas must describe objects (got type: ${JSON.stringify(result.type)}). Wrap your schema in z.object({...}) or equivalent.`); + return { + type: "object", + ...result + }; +} +/** +* A typeless JSON Schema root is "provably object-shaped" when either it carries object keywords +* directly (`properties`/`patternProperties`/`additionalProperties`/`required`), or it is a +* composition (`oneOf`/`anyOf`/`allOf`) whose every member is itself `type:'object'` or recursively +* provably object-shaped (e.g. a nested `discriminatedUnion`). `$ref` is not followed. Used to +* decide whether stamping `type:'object'` is safe (redundant-but-valid) versus self-contradictory. +*/ +function isProvablyObjectShapedRoot(schema) { + if ("properties" in schema || "patternProperties" in schema || "additionalProperties" in schema || "required" in schema) return true; + for (const key of [ + "oneOf", + "anyOf", + "allOf" + ]) { + const members = schema[key]; + if (Array.isArray(members) && members.length > 0) return members.every((m) => m !== null && typeof m === "object" && (m.type === "object" || isProvablyObjectShapedRoot(m))); + } + return false; +} +function formatIssue(issue) { + if (!issue.path?.length) return issue.message; + return `${issue.path.map((p) => String(typeof p === "object" ? p.key : p)).join(".")}: ${issue.message}`; +} +async function validateStandardSchema(schema, data) { + const result = await schema["~standard"].validate(data); + if (result.issues && result.issues.length > 0) return { + success: false, + error: result.issues.map((i) => formatIssue(i)).join(", ") + }; + return { + success: true, + data: result.value + }; +} +function zodEmittedPattern(schema) { + const jsonSchema = toJSONSchema(schema, { + target: JSON_SCHEMA_CONVERSION_TARGET, + io: "input" + }); + return typeof jsonSchema.pattern === "string" ? jsonSchema.pattern : void 0; +} +const DATETIME_FRACTION_DIGITS = /\\\.\\d\{(\d+)\}/; +function datetimeReferenceSchemas(pattern) { + const fractionDigits = DATETIME_FRACTION_DIGITS.exec(pattern); + const precisions = [ + void 0, + -1, + 0 + ]; + if (fractionDigits) precisions.push(Number(fractionDigits[1])); + return [false, true].flatMap((local) => [false, true].flatMap((offset) => precisions.map((precision) => iso_datetime({ + local, + offset, + precision + })))); +} +function referencePatternsForFormat(format, pattern) { + let referenceSchemas; + switch (format) { + case "email": + referenceSchemas = [schemas_email()]; + break; + case "uri": + referenceSchemas = [schemas_url()]; + break; + case "date": + referenceSchemas = [iso_date()]; + break; + case "date-time": + referenceSchemas = datetimeReferenceSchemas(pattern); + break; + } + return new Set(referenceSchemas.map((schema) => zodEmittedPattern(schema)).filter((emitted) => emitted !== void 0)); +} +/** Whether `pattern` is the library's own realization of `format` (droppable) rather than a user customization. */ +function isLibraryFormatPattern(format, pattern, vendor) { + if (vendor !== "zod") return true; + return referencePatternsForFormat(format, pattern).has(pattern); +} +function promptArgumentsFromStandardSchema(schema) { + const jsonSchema = standardSchemaToJsonSchema(schema, "input"); + const properties = jsonSchema.properties || {}; + const required = jsonSchema.required || []; + return Object.entries(properties).map(([name, prop]) => ({ + name, + description: prop?.description, + required: required.includes(name) + })); +} + +//#endregion +//#region ../core-internal/src/shared/elicitation.ts +function isJsonObject(value) { + return typeof value === "object" && value !== null && !Array.isArray(value); +} +function convertStandardElicitationSchema(schema) { + try { + return standardSchemaToJsonSchema(schema, "input"); + } catch (error) { + const detail = error instanceof Error ? error.message : String(error); + throw new src_CX2iR2pK_ProtocolError(src_CX2iR2pK_ProtocolErrorCode.InvalidParams, `Elicitation requestedSchema must describe an object with flat primitive properties: ${detail}`); + } +} +const ANNOTATION_ONLY_JSON_SCHEMA_KEYWORDS = new Set([ + "$comment", + "deprecated", + "description", + "examples", + "readOnly", + "title", + "writeOnly" +]); +function isAnnotationOnlyJsonSchemaKeyword(key) { + return ANNOTATION_ONLY_JSON_SCHEMA_KEYWORDS.has(key) || key.startsWith("x-"); +} +const ROOT_KEYS = new Set(["$schema", ...Object.keys(ElicitRequestFormParamsSchema.shape.requestedSchema.shape)]); +const PROPERTY_KEYS_BY_TYPE = { + string: shapeKeys([ + StringSchemaSchema, + UntitledSingleSelectEnumSchemaSchema, + TitledSingleSelectEnumSchemaSchema, + LegacyTitledEnumSchemaSchema + ]), + number: shapeKeys([NumberSchemaSchema]), + integer: shapeKeys([NumberSchemaSchema]), + boolean: shapeKeys([BooleanSchemaSchema]), + array: shapeKeys([UntitledMultiSelectEnumSchemaSchema, TitledMultiSelectEnumSchemaSchema]) +}; +const SUPPORTED_STRING_FORMATS = new Set(StringSchemaSchema.shape.format.unwrap().options); +/** Walks one property node: keeps grammar keys, drops the library format pattern, rejects unknown constraints. */ +function walkProperty(node, path, vendor, unsupported) { + if (!isJsonObject(node)) return node; + const allowedKeys = typeof node.type === "string" && Object.hasOwn(PROPERTY_KEYS_BY_TYPE, node.type) ? PROPERTY_KEYS_BY_TYPE[node.type] : void 0; + if (allowedKeys === void 0) return node; + const pruned = {}; + for (const [key, value] of Object.entries(node)) if (allowedKeys.has(key) || isAnnotationOnlyJsonSchemaKeyword(key)) pruned[key] = value; + else if (key === "pattern" && node.type === "string" && typeof node.format === "string") { + if (!SUPPORTED_STRING_FORMATS.has(node.format)) pruned[key] = value; + else if (typeof value !== "string" || !isLibraryFormatPattern(node.format, value, vendor)) unsupported.push(`${path}.${key}`); + } else unsupported.push(`${path}.${key}`); + return pruned; +} +/** Walks the schema root: keeps the spec root keys, drops annotations, rejects the rest. */ +function walkRequestedSchema(converted, vendor) { + const pruned = {}; + const unsupported = []; + for (const [key, value] of Object.entries(converted)) if (key === "properties" && isJsonObject(value)) pruned[key] = Object.fromEntries(Object.entries(value).map(([name, node]) => [name, walkProperty(node, `properties.${name}`, vendor, unsupported)])); + else if (ROOT_KEYS.has(key)) pruned[key] = value; + else if (!isAnnotationOnlyJsonSchemaKeyword(key)) unsupported.push(key); + if (unsupported.length > 0) throw new src_CX2iR2pK_ProtocolError(src_CX2iR2pK_ProtocolErrorCode.InvalidParams, `Elicitation requestedSchema contains unsupported JSON Schema constraint(s) after Standard Schema conversion: ${unsupported.join(", ")}`); + return pruned; +} +/** Names the properties that fail value validation, instead of surfacing a raw union dump. */ +function describeUnsupportedProperties(pruned, fallback) { + if (!isJsonObject(pruned.properties)) return fallback; + const offenders = Object.entries(pruned.properties).filter(([, node]) => !parseSchema(PrimitiveSchemaDefinitionSchema, node).success).map(([name]) => `properties.${name}`); + return offenders.length > 0 ? offenders.join(", ") : fallback; +} +function findDroppedConstraintPaths(original, parsed, path = "") { + if (Array.isArray(original) && Array.isArray(parsed)) return original.flatMap((item, index) => findDroppedConstraintPaths(item, parsed[index], `${path}[${index}]`)); + if (!isJsonObject(original) || !isJsonObject(parsed)) return []; + return Object.entries(original).flatMap(([key, value]) => { + const childPath = path ? `${path}.${key}` : key; + if (!Object.prototype.hasOwnProperty.call(parsed, key)) return isAnnotationOnlyJsonSchemaKeyword(key) ? [] : [childPath]; + return findDroppedConstraintPaths(value, parsed[key], childPath); + }); +} +/** Converts an authoring-friendly elicitation input into its wire-ready form. */ +function normalizeElicitInputParams(input) { + if (!isStandardSchema(input.requestedSchema)) return { + ...input, + mode: "form", + requestedSchema: input.requestedSchema + }; + const vendor = input.requestedSchema["~standard"].vendor; + const pruned = walkRequestedSchema(convertStandardElicitationSchema(input.requestedSchema), vendor); + const parsed = parseSchema(ElicitRequestFormParamsSchema.shape.requestedSchema, pruned); + if (!parsed.success) throw new src_CX2iR2pK_ProtocolError(src_CX2iR2pK_ProtocolErrorCode.InvalidParams, `Elicitation requestedSchema only supports flat primitive properties (string, number, integer, boolean, and string enums): ${describeUnsupportedProperties(pruned, parsed.error.message)}`); + const droppedConstraints = findDroppedConstraintPaths(pruned, parsed.data); + if (droppedConstraints.length > 0) throw new src_CX2iR2pK_ProtocolError(src_CX2iR2pK_ProtocolErrorCode.InvalidParams, `Elicitation requestedSchema contains unsupported JSON Schema constraint(s) after Standard Schema conversion: ${droppedConstraints.join(", ")}`); + const danglingRequired = (parsed.data.required ?? []).filter((key) => !Object.prototype.hasOwnProperty.call(parsed.data.properties, key)); + if (danglingRequired.length > 0) throw new src_CX2iR2pK_ProtocolError(src_CX2iR2pK_ProtocolErrorCode.InvalidParams, `Elicitation requestedSchema lists required properties that are not defined in properties: ${danglingRequired.join(", ")}`); + return { + ...input, + mode: "form", + requestedSchema: parsed.data + }; +} + +//#endregion +//#region ../core-internal/src/shared/inputRequired.ts +/** +* Authoring helpers for multi-round-trip requests (protocol revision +* 2026-07-28). +* +* A handler for one of the multi-round-trip methods (`tools/call`, +* `prompts/get`, `resources/read`) requests additional client input by +* returning an {@linkcode InputRequiredResult} instead of a final result. The +* helpers here build that return value and its embedded requests as NEUTRAL +* values; only the 2026-07-28 wire codec maps them to/from the wire. The +* 2025-era codec has no input-required vocabulary — on a 2025-era request the +* server's legacy shim (on by default) fulfils the embedded requests as real +* server→client requests and re-enters the handler, so the same return shape +* serves both eras; `ServerOptions.inputRequired.legacyShim: false` restores +* the pre-shim loud failure. +* +* There is no nominal brand: `resultType: 'input_required'` is the +* discriminator, and hand-built result literals are equally legal — the +* server seam re-checks the at-least-one rule for them. +*/ +function buildInputRequired(spec) { + const hasInputRequests = spec.inputRequests !== void 0 && Object.keys(spec.inputRequests).length > 0; + const hasRequestState = typeof spec.requestState === "string"; + if (!hasInputRequests && !hasRequestState) 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", + ...spec.inputRequests !== void 0 && { inputRequests: spec.inputRequests }, + ...spec.requestState !== void 0 && { requestState: spec.requestState } + }; +} +/** +* Builder for the input-required return value of multi-round-trip handlers, +* with per-kind constructors for the embedded requests +* (`inputRequired.elicit`, `inputRequired.elicitUrl`, +* `inputRequired.createMessage`, `inputRequired.listRoots`). +* +* @example Write-once tool requesting confirmation +* ```ts +* server.registerTool('deploy', { inputSchema: z.object({ env: z.string() }) }, async ({ env }, ctx) => { +* const confirmed = acceptedContent<{ confirm: boolean }>(ctx.mcpReq.inputResponses, 'confirm'); +* if (!confirmed) { +* return inputRequired({ +* inputRequests: { +* confirm: inputRequired.elicit({ +* message: `Deploy to ${env}?`, +* requestedSchema: { type: 'object', properties: { confirm: { type: 'boolean' } }, required: ['confirm'] } +* }) +* } +* }); +* } +* return { content: [{ type: 'text', text: `deployed to ${env}` }] }; +* }); +* ``` +*/ +const inputRequired = Object.assign(buildInputRequired, { + elicit(params) { + try { + return { + method: "elicitation/create", + params: normalizeElicitInputParams(params) + }; + } catch (error) { + throw error instanceof src_CX2iR2pK_ProtocolError ? new TypeError(error.message, { cause: error }) : error; + } + }, + elicitUrl(params) { + return { + method: "elicitation/create", + params: { + ...params, + mode: "url" + } + }; + }, + createMessage(params) { + return { + method: "sampling/createMessage", + params + }; + }, + listRoots() { + return { method: "roots/list" }; + } +}); +function acceptedContent(responses, key, schema) { + const view = inputResponse(responses, key); + if (view.kind !== "elicit" || view.action !== "accept" || view.content === void 0) return void 0; + if (schema === void 0) return view.content; + const outcome = schema["~standard"].validate(view.content); + if (outcome instanceof Promise) throw new TypeError("acceptedContent(responses, key, schema) requires a synchronously-validating schema"); + return outcome.issues === void 0 ? outcome.value : void 0; +} +/** +* Reads one entry of a retried request's `inputResponses` +* (`ctx.mcpReq.inputResponses`) as a discriminated view, covering +* decline/cancel detection and the non-elicitation response kinds that +* {@linkcode acceptedContent} does not surface. +* +* The values arrive from the client and are not re-validated here — treat +* them as untrusted input (validate elicitation content with the +* schema-aware {@linkcode acceptedContent} overload where it matters). +*/ +function inputResponse(responses, key) { + if (responses === void 0 || typeof responses !== "object" || responses === null) return { kind: "missing" }; + const entry = responses[key]; + if (entry === null || typeof entry !== "object" || Array.isArray(entry)) return { kind: "missing" }; + const candidate = entry; + if (candidate["action"] === "accept" || candidate["action"] === "decline" || candidate["action"] === "cancel") { + const content = candidate["content"]; + return { + kind: "elicit", + action: candidate["action"], + ...content !== null && typeof content === "object" && !Array.isArray(content) && { content } + }; + } + if (Array.isArray(candidate["roots"])) return { + kind: "roots", + roots: candidate["roots"] + }; + if (typeof candidate["role"] === "string" && candidate["content"] !== void 0) return { + kind: "sampling", + result: candidate + }; + return { kind: "missing" }; +} + +//#endregion +//#region ../core-internal/src/shared/inputRequiredDriver.ts +/** +* The multi-round-trip auto-fulfilment driver (protocol revision 2026-07-28). +* +* When a request to one of the multi-round-trip methods comes back as +* `input_required`, the driver fulfils the embedded input requests by +* dispatching them to the client's already-registered handlers (elicitation, +* sampling, roots — one generic engine, no per-feature API), then retries the +* original request with the collected `inputResponses` and a byte-exact echo +* of `requestState`, on a fresh request id, until the server returns a +* complete result or the round cap is exhausted. +* +* The driver is a LAYER OVER THE MANUAL PATH: each retry is issued with the +* same primitive a manual caller uses (`allowInputRequired` semantics — the +* retry hands back the next `input_required` payload instead of recursing), +* so the loop, the cap, and the pacing live in one place and disabling +* auto-fulfilment (`inputRequired.autoFulfill: false`) simply skips this +* module. Timeouts ride the EXISTING knobs: the per-leg `timeout` applies to +* every wire leg unchanged, and `maxTotalTimeout` bounds the whole flow by +* shrinking the budget passed to each leg — no new timer system. +*/ +/** +* Fixed pacing applied before retrying a requestState-only (load-shedding) +* leg — a leg that carries no embedded input requests, so nothing slows the +* loop down naturally. Counted in the same round cap. +*/ +const REQUEST_STATE_ONLY_LEG_PACING_MS = 250; +/** +* The message both multi-round-trip loops emit when the round cap is +* exhausted — the client driver as a typed error, the server-side legacy +* shim as its per-family failure. One formatter so the texts cannot drift +* (hosts and models read the tool-result copy verbatim). +*/ +function inputRequiredRoundsExceededMessage(method, maxRounds) { + return `Multi-round-trip request '${method}' still required input after ${maxRounds} rounds (inputRequired.maxRounds)`; +} +/** +* Abortable delay: resolves after `ms`, or rejects with the signal's reason +* (wrapped in an `SdkError` when it isn't already one) if the signal aborts +* first. Aborting after resolution is a no-op. Shared with the server-side +* legacy shim (the pacing semantics must match per era). +*/ +function sleep(ms, signal) { + return new Promise((resolve, reject) => { + if (signal?.aborted) { + reject(signal.reason instanceof src_CX2iR2pK_SdkError ? signal.reason : new src_CX2iR2pK_SdkError(src_CX2iR2pK_SdkErrorCode.RequestTimeout, String(signal.reason))); + return; + } + const timer = setTimeout(() => { + signal?.removeEventListener("abort", onAbort); + resolve(); + }, ms); + const onAbort = () => { + clearTimeout(timer); + reject(signal?.reason instanceof src_CX2iR2pK_SdkError ? signal.reason : new src_CX2iR2pK_SdkError(src_CX2iR2pK_SdkErrorCode.RequestTimeout, String(signal?.reason))); + }; + signal?.addEventListener("abort", onAbort, { once: true }); + }); +} +/** +* A per-round abort linked to the caller's signal: the embedded sibling +* dispatches share it, so the first failure (or a caller abort) cancels the +* others instead of leaving them running. Shared with the server-side legacy +* shim (the abort-linkage semantics must match per era). +*/ +function linkedRoundAbort(outer) { + const controller = new AbortController(); + const onOuterAbort = () => controller.abort(outer?.reason); + outer?.addEventListener("abort", onOuterAbort, { once: true }); + if (outer?.aborted) controller.abort(outer.reason); + return { + signal: controller.signal, + abort: (reason) => controller.abort(reason), + dispose: () => outer?.removeEventListener("abort", onOuterAbort) + }; +} + +//#endregion +//#region ../core-internal/src/types/specTypeSchema.ts +/** +* Explicit allowlist of protocol Zod schemas that correspond to a public spec type in `types.ts`. +* +* This intentionally excludes internal helper schemas exported from `schemas.ts` that have no +* matching public type (e.g. `ListChangedOptionsBaseSchema`, `BaseRequestParamsSchema`, +* `NotificationsParamsSchema`, `ClientTasksCapabilitySchema`, `ServerTasksCapabilitySchema`). +* Keeping the list explicit means new public spec types must be added here deliberately, and +* internals never leak into `SpecTypeName`. +* +* `ResourceTemplateSchema` is included; its public type is exported as `ResourceTemplateType` +* (the bare name collides with the server package's `ResourceTemplate` class), so +* `SpecTypes['ResourceTemplate']` is structurally equal to `ResourceTemplateType` rather than to +* a type literally named `ResourceTemplate`. +*/ +const SPEC_SCHEMA_KEYS = [ + "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" +]; +const authSchemas = { + IdJagTokenExchangeResponseSchema: IdJagTokenExchangeResponseSchema, + OAuthClientInformationFullSchema: OAuthClientInformationFullSchema, + OAuthClientInformationSchema: OAuthClientInformationSchema, + OAuthClientMetadataSchema: OAuthClientMetadataSchema, + OAuthClientRegistrationErrorSchema: OAuthClientRegistrationErrorSchema, + OAuthErrorResponseSchema: OAuthErrorResponseSchema, + OAuthMetadataSchema: OAuthMetadataSchema, + OAuthProtectedResourceMetadataSchema: OAuthProtectedResourceMetadataSchema, + OAuthTokenRevocationRequestSchema: OAuthTokenRevocationRequestSchema, + OAuthTokensSchema: OAuthTokensSchema, + OpenIdProviderDiscoveryMetadataSchema: OpenIdProviderDiscoveryMetadataSchema, + OpenIdProviderMetadataSchema: OpenIdProviderMetadataSchema +}; +const _specTypeSchemas = {}; +const _isSpecType = {}; +function register(key, schema) { + const name = key.slice(0, -6); + _specTypeSchemas[name] = schema; + _isSpecType[name] = (v) => schema.safeParse(v).success; +} +for (const key of SPEC_SCHEMA_KEYS) register(key, schemas_exports[key]); +for (const [key, schema] of Object.entries(authSchemas)) register(key, schema); +/** +* Runtime validators for every MCP spec type, keyed by type name. +* +* Use this when you need to validate a spec-defined shape at a boundary the SDK does not own, for +* example an extension's custom-method payload that embeds a `CallToolResult`, or a value read from +* storage that should be a `Tool`. +* +* Each entry implements the Standard Schema interface, so it composes with any +* Standard-Schema-aware library. For a simple boolean check, use {@linkcode isSpecType} instead. +* +* @example +* ```ts source="./specTypeSchema.examples.ts#specTypeSchemas_basicUsage" +* const result = specTypeSchemas.CallToolResult['~standard'].validate(untrusted); +* if (result.issues === undefined) { +* // result.value is CallToolResult +* } +* ``` +*/ +const specTypeSchemas = Object.freeze(_specTypeSchemas); +/** +* Type predicates for every MCP spec type, keyed by type name. +* +* Returns `true` if the value satisfies the schema's input type (`z.input<>`, before defaults and +* transforms are applied), and narrows to that input type. For schemas with `.default()` or +* `.preprocess()`, this may accept values that do not structurally match the named output type; +* for example `isSpecType.CallToolResult({})` is `true` because `content` has a default. Use +* `specTypeSchemas.X['~standard'].validate(value)` when you need the validated output value. +* +* Each guard is a standalone function, so it can be passed directly as a callback. +* +* @example +* ```ts source="./specTypeSchema.examples.ts#isSpecType_basicUsage" +* if (isSpecType.ContentBlock(value)) { +* // value is ContentBlock +* } +* +* const blocks = mixed.filter(isSpecType.ContentBlock); +* ``` +*/ +const isSpecType = Object.freeze(_isSpecType); + +//#endregion +//#region ../core-internal/src/wire/bootstrap.ts +function bootstrapOutboundCodec(method) { + switch (method) { + case "initialize": + case "notifications/initialized": return src_CX2iR2pK_codecForVersion(void 0); + case "server/discover": return src_CX2iR2pK_codecForVersion(src_CX2iR2pK_MODERN_WIRE_REVISION); + default: return; + } +} + +//#endregion +//#region ../core-internal/src/shared/protocol.ts +/** +* The default request timeout, in milliseconds. +*/ +const DEFAULT_REQUEST_TIMEOUT_MSEC = 6e4; +/** +* The reserved per-request `_meta` envelope keys (protocol revision +* 2026-07-28). The protocol layer lifts these out of inbound `_meta` before +* handlers run and surfaces them at `ctx.mcpReq.envelope` — they are +* wire-level bookkeeping, not handler material. +*/ +const RESERVED_ENVELOPE_META_KEYS = [ + auth_CUe6YdwF_PROTOCOL_VERSION_META_KEY, + auth_CUe6YdwF_CLIENT_INFO_META_KEY, + auth_CUe6YdwF_CLIENT_CAPABILITIES_META_KEY, + LOG_LEVEL_META_KEY +]; +/** +* Top-level params members carrying multi-round-trip driver material +* (protocol revision 2026-07-28). The spec reserves these names on +* client-initiated REQUESTS only — notification params keep them untouched +* (a vendor notification may legitimately use the same names). +*/ +const RETRY_PARAMS_KEYS = ["inputResponses", "requestState"]; +/** +* Lift wire-only material out of an inbound message so handlers see exactly +* the 2025-era shape, and surface it for the protocol layer (requests: via +* `ctx.mcpReq`). What counts as wire-only depends on the message kind: the +* reserved envelope `_meta` keys are reserved on every message, while the +* multi-round-trip retry fields (`inputResponses`/`requestState`) are +* reserved on client-initiated requests only — so notifications get only the +* envelope lift, and their top-level params stay untouched. Messages without +* wire-only material are returned unchanged (same reference). +*/ +function liftWireOnlyMaterial(message, kind) { + const params = message.params; + if (!isPlainObject$1(params)) return { + message, + lifted: {} + }; + const meta = params._meta; + const envelopeKeys = isPlainObject$1(meta) ? RESERVED_ENVELOPE_META_KEYS.filter((key) => key in meta) : []; + const retryKeys = kind === "request" ? RETRY_PARAMS_KEYS.filter((key) => key in params) : []; + if (envelopeKeys.length === 0 && retryKeys.length === 0) return { + message, + lifted: {} + }; + const lifted = {}; + const nextParams = { ...params }; + if (envelopeKeys.length > 0 && isPlainObject$1(meta)) { + const envelope = {}; + const nextMeta = { ...meta }; + for (const key of envelopeKeys) { + envelope[key] = meta[key]; + delete nextMeta[key]; + } + lifted.envelope = envelope; + if (Object.keys(nextMeta).length > 0) nextParams._meta = nextMeta; + else delete nextParams._meta; + } + for (const key of retryKeys) { + if (key === "inputResponses") lifted.inputResponses = nextParams[key]; + if (key === "requestState") lifted.requestState = nextParams[key]; + delete nextParams[key]; + } + return { + message: { + ...message, + params: nextParams + }, + lifted + }; +} +/** +* Standard Schema adapter over the era codec's `validateResult` function (the +* function-only WireCodec contract exposes no schema objects). Used by the +* spec-method `request()` overload so the request funnel keeps a single +* `StandardSchemaV1`-shaped validation seam for both spec and explicit-schema +* paths. +* +* Returns `undefined` when the method has no result entry on this era's +* registry — the caller maps that to the synchronous "pass a result schema" +* TypeError, exactly matching the pre-function-only behavior the +* typedMapAlignment suite pins (the result map deliberately excludes the +* `tasks/*` methods, so the spec-method overload refuses them up front). +*/ +function codecResultValidator(codec, method) { + const probe = codec.validateResult(method, void 0); + if (!probe.ok && probe.reason === "not-in-era") return void 0; + return { "~standard": { + version: 1, + vendor: "mcp-wire-codec", + validate(value) { + const outcome = codec.validateResult(method, value); + if (outcome.ok) return { value: outcome.value }; + return { issues: [{ message: outcome.reason === "invalid" ? outcome.message : `not-in-era: ${method}` }] }; + } + } }; +} +/** +* Builds the `ctx.mcpReq.requestState` accessor for a resolved value. The +* `as T` below is the one place {@linkcode RequestStateAccessor}'s +* caller-asserted typing is implemented — no implementation can produce an +* arbitrary `T` from a runtime value honestly. +*/ +function requestStateAccessor(value) { + return () => value; +} +/** Shared no-state accessor: the common case allocates nothing per request. */ +const NO_REQUEST_STATE = requestStateAccessor(void 0); +/** +* Returns a context whose `requestState` accessor reads the given value — +* how the server seam hands a verify hook's decoded payload (or the legacy +* shim's per-round echo) to the handler without mutating the original +* context. +*/ +function withRequestStateValue(ctx, value) { + return { + ...ctx, + mcpReq: { + ...ctx.mcpReq, + requestState: requestStateAccessor(value) + } + }; +} +let writeNegotiatedProtocolVersion; +/** +* Package-internal write channel for a {@linkcode Protocol} instance's +* negotiated protocol version, for callers outside the class hierarchy: +* tests and the (future) modern-era server entry that marks a factory +* instance modern at binding time. Exported on the core internal barrel +* only — never public API. +*/ +function src_CX2iR2pK_setNegotiatedProtocolVersion(instance, version) { + writeNegotiatedProtocolVersion(instance, version); +} +/** +* Implements MCP protocol framing on top of a pluggable transport, including +* features like request/response linking, notifications, and progress. +* +* `Protocol` is abstract; `Client` and `Server` are the concrete role-specific +* implementations most code should use. +*/ +var Protocol = class { + _transport; + _requestMessageId = 0; + _requestHandlers = /* @__PURE__ */ new Map(); + _requestHandlerAbortControllers = /* @__PURE__ */ new Map(); + _notificationHandlers = /* @__PURE__ */ new Map(); + _responseHandlers = /* @__PURE__ */ new Map(); + _progressHandlers = /* @__PURE__ */ new Map(); + _timeoutInfo = /* @__PURE__ */ new Map(); + _pendingDebouncedNotifications = /* @__PURE__ */ new Set(); + /** + * The protocol version negotiated for the current connection (`undefined` + * before negotiation completes), which determines the wire era this + * instance speaks. Set by the SDK's negotiation and initialize paths + * (`Client.connect`, `Server._oninitialize`). + */ + _negotiatedProtocolVersion; + static { + writeNegotiatedProtocolVersion = (instance, version) => { + instance._negotiatedProtocolVersion = version; + }; + } + _supportedProtocolVersions; + /** + * Callback for when the connection is closed for any reason. + * + * This is invoked when {@linkcode Protocol.close | close()} is called as well. + */ + onclose; + /** + * Callback for when an error occurs. + * + * Note that errors are not necessarily fatal; they are used for reporting any kind of exceptional condition out of band. + */ + onerror; + /** + * A handler to invoke for any request types that do not have their own handler installed. + */ + fallbackRequestHandler; + /** + * A handler to invoke for any notification types that do not have their own handler installed. + */ + fallbackNotificationHandler; + constructor(_options) { + this._options = _options; + this._supportedProtocolVersions = _options?.supportedProtocolVersions ?? auth_CUe6YdwF_SUPPORTED_PROTOCOL_VERSIONS; + this.setNotificationHandler("notifications/cancelled", (notification) => { + this._oncancel(notification); + }); + this.setNotificationHandler("notifications/progress", (notification) => { + this._onprogress(notification); + }); + this.setRequestHandler("ping", (_request) => ({})); + } + /** + * Drop consult for inbound messages whose transport did not classify them + * at the edge — long-lived channels such as stdio, where a role class may + * need to decline traffic the negotiated era has no answer for (the + * client-side inbound-request drop on modern-era connections: the + * 2026-07-28 era has no server→client request channel, and on stdio the + * client must never write JSON-RPC responses). + * + * Consulted ONLY when the transport supplied no + * {@linkcode MessageExtraInfo.classification}: edge-classified traffic + * never reaches the hook. Returning `'drop'` discards the message without + * writing any response (requests are surfaced via `onerror`). The base + * implementation returns `undefined`: unclassified traffic keeps today's + * dispatch path unchanged. Era selection never happens here — era is + * instance state, owned by the serving entry that constructed and + * connected the instance. + */ + _shouldDropInbound(_message) {} + /** + * The per-request `_meta` envelope this instance attaches to every outgoing + * request and notification, when one applies. The base implementation + * returns `undefined` (no envelope — the 2025-era posture, so legacy-era + * outbound traffic is byte-identical to a build without this seam). + * `Client` overrides it on a connection that negotiated a modern (2026-07-28+) + * era to return the reserved protocol-version / client-info / + * client-capabilities keys. User-supplied `_meta` keys take precedence over + * the auto-attached ones. + */ + _outboundMetaEnvelope() {} + /** + * Attach this instance's outbound `_meta` envelope (when one is configured) + * to a request or notification. A no-op when the seam returns `undefined` + * — the message returns by reference, so the legacy-era wire stays + * byte-identical. User-supplied `_meta` keys are spread last so they win + * over the auto-attached envelope keys. + */ + _envelopeOutbound(message) { + const envelope = this._outboundMetaEnvelope(); + if (envelope === void 0) return message; + const params = message.params ?? {}; + return { + ...message, + params: { + ...params, + _meta: { + ...envelope, + ...params._meta + } + } + }; + } + /** + * Extension point for non-`complete` decoded results in the response + * funnel: a result the wire codec discriminated into a kind other than + * `'complete'` or `'invalid'` is handed here for the role class to + * resolve. The base default surfaces it as a typed + * {@linkcode SdkErrorCode.UnsupportedResultType} error (no retry). + * + * Intended consumers (named so the seam stays accountable): + * - the `Client`'s multi-round-trip auto-fulfilment engine, which fulfils + * `'input_required'` results through the registered + * elicitation/sampling/roots handlers and retries via `flow.retry`; + * - a future client-side terminal-result handler for + * `subscriptions/listen`, when the spec defines one. + * + * `Server` instances never receive `input_required` responses on their + * outbound legs and leave the base behavior in place. + */ + _resolveNonCompleteResult(decoded, flow) { + return Promise.reject(new src_CX2iR2pK_SdkError(src_CX2iR2pK_SdkErrorCode.UnsupportedResultType, `Unsupported result type '${decoded.kind}' for ${flow.request.method}`, { + resultType: decoded.kind, + method: flow.request.method + })); + } + /** + * Protected accessor for a registered request handler. Used by role + * classes that dispatch synthesized requests through the same stored + * handler chain (e.g. the `Client` fulfilling an embedded multi-round-trip + * input request). + */ + _getRequestHandler(method) { + return this._requestHandlers.get(method); + } + async _oncancel(notification) { + if (!notification.params.requestId) return; + this._requestHandlerAbortControllers.get(notification.params.requestId)?.abort(notification.params.reason); + } + _setupTimeout(messageId, timeout, maxTotalTimeout, onTimeout, resetTimeoutOnProgress = false) { + this._timeoutInfo.set(messageId, { + timeoutId: setTimeout(onTimeout, timeout), + startTime: Date.now(), + timeout, + maxTotalTimeout, + resetTimeoutOnProgress, + onTimeout + }); + } + _resetTimeout(messageId) { + const info = this._timeoutInfo.get(messageId); + if (!info) return false; + const totalElapsed = Date.now() - info.startTime; + if (info.maxTotalTimeout && totalElapsed >= info.maxTotalTimeout) { + this._timeoutInfo.delete(messageId); + throw new src_CX2iR2pK_SdkError(src_CX2iR2pK_SdkErrorCode.RequestTimeout, "Maximum total timeout exceeded", { + maxTotalTimeout: info.maxTotalTimeout, + totalElapsed + }); + } + clearTimeout(info.timeoutId); + info.timeoutId = setTimeout(info.onTimeout, info.timeout); + return true; + } + _cleanupTimeout(messageId) { + const info = this._timeoutInfo.get(messageId); + if (info) { + clearTimeout(info.timeoutId); + this._timeoutInfo.delete(messageId); + } + } + /** + * Attaches to the given transport, starts it, and starts listening for messages. + * + * The caller assumes ownership of the {@linkcode Transport}, replacing any callbacks that have already been set, and expects that it is the only user of the {@linkcode Transport} instance going forward. + */ + async connect(transport) { + this._transport = transport; + const _onclose = this.transport?.onclose; + this._transport.onclose = () => { + try { + _onclose?.(); + } finally { + this._onclose(); + } + }; + const _onerror = this.transport?.onerror; + this._transport.onerror = (error) => { + _onerror?.(error); + this._onerror(error); + }; + const _onmessage = this._transport?.onmessage; + this._transport.onmessage = (message, extra) => { + _onmessage?.(message, extra); + if (src_CX2iR2pK_isJSONRPCResultResponse(message) || src_CX2iR2pK_isJSONRPCErrorResponse(message)) this._onresponse(message); + else if (src_CX2iR2pK_isJSONRPCRequest(message)) this._onrequest(message, extra); + else if (src_CX2iR2pK_isJSONRPCNotification(message)) this._onnotification(message, extra); + else this._onerror(/* @__PURE__ */ new Error(`Unknown message type: ${JSON.stringify(message)}`)); + }; + transport.setSupportedProtocolVersions?.(this._supportedProtocolVersions); + await this._transport.start(); + } + /** + * Transport-close hook. Subclass overrides MUST call `super._onclose()` + * after their own cleanup — base teardown (response-handler settlement, + * timeout clearing, in-flight request abort) does not run otherwise. + */ + _onclose() { + const responseHandlers = this._responseHandlers; + this._responseHandlers = /* @__PURE__ */ new Map(); + this._progressHandlers.clear(); + this._pendingDebouncedNotifications.clear(); + for (const info of this._timeoutInfo.values()) clearTimeout(info.timeoutId); + this._timeoutInfo.clear(); + const requestHandlerAbortControllers = this._requestHandlerAbortControllers; + this._requestHandlerAbortControllers = /* @__PURE__ */ new Map(); + const error = new src_CX2iR2pK_SdkError(src_CX2iR2pK_SdkErrorCode.ConnectionClosed, "Connection closed"); + this._transport = void 0; + try { + this.onclose?.(); + } finally { + for (const handler of responseHandlers.values()) handler(error); + for (const controller of requestHandlerAbortControllers.values()) controller.abort(error); + } + } + _onerror(error) { + this.onerror?.(error); + } + /** + * Inbound-notification dispatch. Subclass overrides MUST delegate + * unmatched traffic to `super._onnotification(rawNotification, extra)` — + * an override that consumes only what it owns and falls through to base + * dispatch for everything else. + */ + _onnotification(rawNotification, extra) { + const { message: notification } = liftWireOnlyMaterial(rawNotification, "notification"); + const codec = this._negotiatedWireCodec(); + if (extra?.classification === void 0 && this._shouldDropInbound(rawNotification) === "drop") return; + if (extra?.classification !== void 0) { + const classified = classifiedWireEra(extra.classification); + if (classified !== codec.era) { + this._onerror(/* @__PURE__ */ new Error(`Era mismatch on inbound notification '${notification.method}': classified as ${classified} but this instance serves ${codec.era}`)); + return; + } + } + if (isSpecNotificationMethod(notification.method) && !codec.hasNotificationMethod(notification.method)) return; + const handler = this._notificationHandlers.get(notification.method); + const fallback = this.fallbackNotificationHandler; + if (handler === void 0 && fallback === void 0) return; + Promise.resolve().then(() => handler === void 0 ? fallback(notification) : handler(notification, codec)).catch((error) => this._onerror(/* @__PURE__ */ new Error(`Uncaught error in notification handler: ${error}`))); + } + _onrequest(rawRequest, extra) { + const { message: request, lifted } = liftWireOnlyMaterial(rawRequest, "request"); + const codec = this._negotiatedWireCodec(); + if (extra?.classification === void 0 && this._shouldDropInbound(rawRequest) === "drop") { + this._onerror(/* @__PURE__ */ new Error(`Dropped inbound request '${rawRequest.method}': not servable on this connection's protocol era`)); + return; + } + const capturedTransport = this._transport; + const sendErrorResponse = (code, message, data) => { + const errorResponse = { + jsonrpc: "2.0", + id: request.id, + error: { + code, + message, + ...data !== void 0 && { data } + } + }; + capturedTransport?.send(errorResponse).catch((error) => this._onerror(/* @__PURE__ */ new Error(`Failed to send an error response: ${error}`))); + }; + if (extra?.classification !== void 0) { + const classified = classifiedWireEra(extra.classification); + if (classified !== codec.era) { + this._onerror(/* @__PURE__ */ new Error(`Era mismatch on inbound request '${request.method}': classified as ${classified} but this instance serves ${codec.era}`)); + const requested = extra.classification.revision ?? classified; + sendErrorResponse(src_CX2iR2pK_ProtocolErrorCode.UnsupportedProtocolVersion, `Unsupported protocol version: ${requested}`, { + supported: this._supportedProtocolVersions, + requested + }); + return; + } + } + if (isSpecRequestMethod(request.method) && !codec.hasRequestMethod(request.method)) { + sendErrorResponse(src_CX2iR2pK_ProtocolErrorCode.MethodNotFound, "Method not found"); + return; + } + const handler = this._requestHandlers.get(request.method) ?? this.fallbackRequestHandler; + if (handler === void 0) { + sendErrorResponse(src_CX2iR2pK_ProtocolErrorCode.MethodNotFound, "Method not found"); + return; + } + const envelopeError = codec.checkInboundEnvelope(lifted); + if (envelopeError !== void 0) { + sendErrorResponse(src_CX2iR2pK_ProtocolErrorCode.InvalidParams, envelopeError); + return; + } + const sendNotification = (notification, options) => this._notificationViaCodec(this._resolveOutboundCodec(notification.method), notification, { + ...options, + relatedRequestId: request.id + }); + const sendRequest = (r, resultSchema, options) => this._requestWithSchemaViaCodec(this._resolveOutboundCodec(r.method), r, resultSchema, { + ...options, + relatedRequestId: request.id + }); + const abortController = new AbortController(); + this._requestHandlerAbortControllers.set(request.id, abortController); + const partitionedInputResponses = lifted.inputResponses === void 0 ? void 0 : partitionInputResponses(lifted.inputResponses); + const baseCtx = { + sessionId: capturedTransport?.sessionId, + mcpReq: { + id: request.id, + method: request.method, + _meta: request.params?._meta, + ...lifted.envelope !== void 0 && { envelope: lifted.envelope }, + ...partitionedInputResponses !== void 0 && { inputResponses: partitionedInputResponses.accepted }, + ...partitionedInputResponses !== void 0 && partitionedInputResponses.droppedKeys.length > 0 && { droppedInputResponseKeys: partitionedInputResponses.droppedKeys }, + requestState: lifted.requestState === void 0 ? NO_REQUEST_STATE : requestStateAccessor(lifted.requestState), + signal: abortController.signal, + send: ((r, schemaOrOptions, maybeOptions) => { + const sendCodec = this._resolveOutboundCodec(r.method); + this._assertOutboundRequestInEra(sendCodec, r.method); + if (isStandardSchema(schemaOrOptions)) return sendRequest(r, schemaOrOptions, maybeOptions); + const validate = codecResultValidator(sendCodec, r.method); + if (validate === void 0) throw new TypeError(`'${r.method}' is not a spec method; pass a result schema as the second argument to ctx.mcpReq.send().`); + return sendRequest(r, validate, schemaOrOptions); + }), + notify: sendNotification + }, + http: extra?.authInfo ? { authInfo: extra.authInfo } : void 0 + }; + const ctx = this.buildContext(baseCtx, extra); + Promise.resolve().then(() => handler(request, ctx)).then(async (result) => { + if (abortController.signal.aborted) return; + let encoded; + try { + encoded = codec.encodeResult(request.method, result, this._outboundServerInfo()); + } catch (error) { + this._onerror(/* @__PURE__ */ new Error(`Failed to encode result for ${request.method}: ${error}`)); + sendErrorResponse(src_CX2iR2pK_ProtocolErrorCode.InternalError, "Internal error"); + return; + } + const response = { + result: encoded, + jsonrpc: "2.0", + id: request.id + }; + await capturedTransport?.send(response); + }, async (error) => { + if (abortController.signal.aborted) return; + const thrownCode = Number.isSafeInteger(error["code"]) ? error["code"] : src_CX2iR2pK_ProtocolErrorCode.InternalError; + const errorResponse = { + jsonrpc: "2.0", + id: request.id, + error: { + code: codec.encodeErrorCode(thrownCode), + message: error.message ?? "Internal error", + ...error["data"] !== void 0 && { data: error["data"] } + } + }; + await capturedTransport?.send(errorResponse); + }).catch((error) => this._onerror(/* @__PURE__ */ new Error(`Failed to send response: ${error}`))).finally(() => { + if (this._requestHandlerAbortControllers.get(request.id) === abortController) this._requestHandlerAbortControllers.delete(request.id); + }); + } + _onprogress(notification) { + const { progressToken, ...params } = notification.params; + const messageId = Number(progressToken); + const handler = this._progressHandlers.get(messageId); + if (!handler) { + this._onerror(/* @__PURE__ */ new Error(`Received a progress notification for an unknown token: ${JSON.stringify(notification)}`)); + return; + } + const responseHandler = this._responseHandlers.get(messageId); + const timeoutInfo = this._timeoutInfo.get(messageId); + if (timeoutInfo && responseHandler && timeoutInfo.resetTimeoutOnProgress) try { + this._resetTimeout(messageId); + } catch (error) { + this._responseHandlers.delete(messageId); + this._progressHandlers.delete(messageId); + this._cleanupTimeout(messageId); + responseHandler(error); + return; + } + handler(params); + } + /** + * Inbound-response dispatch. Subclass overrides MUST delegate unmatched + * traffic to `super._onresponse(response)` — an override that consumes + * only what it owns and falls through to base dispatch for everything + * else. + */ + _onresponse(response) { + const messageId = Number(response.id); + const handler = this._responseHandlers.get(messageId); + if (handler === void 0) { + this._onerror(/* @__PURE__ */ new Error(`Received a response for an unknown message ID: ${JSON.stringify(response)}`)); + return; + } + this._responseHandlers.delete(messageId); + this._cleanupTimeout(messageId); + this._progressHandlers.delete(messageId); + if (src_CX2iR2pK_isJSONRPCResultResponse(response)) handler(response); + else handler(src_CX2iR2pK_ProtocolError.fromError(response.error.code, response.error.message, response.error.data)); + } + get transport() { + return this._transport; + } + /** + * Closes the connection. + */ + async close() { + await this._transport?.close(); + } + request(request, schemaOrOptions, maybeOptions) { + const codec = this._resolveOutboundCodec(request.method); + this._assertOutboundRequestInEra(codec, request.method); + if (isStandardSchema(schemaOrOptions)) return this._requestWithSchemaViaCodec(codec, request, schemaOrOptions, maybeOptions); + const validate = codecResultValidator(codec, request.method); + if (validate === void 0) throw new TypeError(`'${request.method}' is not a spec method; pass a result schema as the second argument to request().`); + return this._requestWithSchemaViaCodec(codec, request, validate, schemaOrOptions); + } + /** + * The wire codec for this instance's negotiated era — the phase-2 truth: + * everything an established connection sends and receives resolves + * through it. Legacy until a version has been negotiated. + */ + _negotiatedWireCodec() { + return src_CX2iR2pK_codecForVersion(this._negotiatedProtocolVersion); + } + /** + * Protected accessor for the instance's negotiated wire codec, for role + * classes (Client/Server/McpServer) routing era-dependent behavior + * through the codec's function-only surface — `samplingResultVariant`, + * `outboundEnvelope`, `projectCallToolResult` — instead of branching on + * the protocol version themselves. + */ + _wireCodec() { + return this._negotiatedWireCodec(); + } + /** + * Outbound codec resolution: while the negotiated version is still unset + * (the negotiation window), lifecycle messages are bootstrap-pinned BY + * METHOD — they self-identify their era (`initialize` IS the legacy + * handshake, `server/discover` IS the modern probe). Once a version has + * been negotiated, the instance era is authoritative for everything — a + * negotiated session never re-routes a method onto the other era. + */ + _resolveOutboundCodec(method) { + if (this._negotiatedProtocolVersion === void 0) { + const pinned = bootstrapOutboundCodec(method); + if (pinned) return pinned; + } + return this._negotiatedWireCodec(); + } + /** + * Era gate for outbound requests — deletions are physical in BOTH + * directions: sending a spec method that the resolved era does not define + * dies locally with a typed error before anything reaches the transport. + * Methods outside the spec universe are consumer-owned extension methods + * and stay era-blind. + */ + _assertOutboundRequestInEra(codec, method) { + if (isSpecRequestMethod(method) && !codec.hasRequestMethod(method)) throw new src_CX2iR2pK_SdkError(src_CX2iR2pK_SdkErrorCode.MethodNotSupportedByProtocolVersion, `Method '${method}' is not supported by the negotiated protocol version (wire era ${codec.era})`, { + method, + era: codec.era + }); + } + /** + * Sends a request and waits for a response, using the provided schema for + * validation instead of the era registry's method-keyed entry. + * + * This is the internal implementation used by SDK methods whose result + * schema cannot be expressed as a method-keyed registry entry — the one + * surviving case is `server.createMessage`, whose result schema depends + * on the REQUEST params (tools vs no tools) — and by callers passing + * explicit compatibility schemas. Spec methods are still era-gated here: + * an explicit schema never smuggles a deleted method onto the wire. + */ + _requestWithSchema(request, resultSchema, options) { + const codec = this._resolveOutboundCodec(request.method); + this._assertOutboundRequestInEra(codec, request.method); + return this._requestWithSchemaViaCodec(codec, request, resultSchema, options); + } + /** + * The request funnel proper, keyed by the resolved era codec: the codec + * owns result decoding (raw-first `resultType` discrimination — V-1 — + * and the era's lift posture) before the schema validation step. + */ + _requestWithSchemaViaCodec(codec, request, resultSchema, options) { + const { relatedRequestId, resumptionToken, onresumptiontoken, headers } = options ?? {}; + const flowStartedAt = Date.now(); + let onAbort; + let cleanupMessageId; + return new Promise((resolve, reject) => { + const earlyReject = (error) => { + reject(error); + }; + if (!this._transport) { + earlyReject(/* @__PURE__ */ new Error("Not connected")); + return; + } + if (this._options?.enforceStrictCapabilities === true) try { + this.assertCapabilityForMethod(request.method); + } catch (error) { + earlyReject(error); + return; + } + if (options?.signal?.aborted) { + const reason = options.signal.reason; + throw reason instanceof src_CX2iR2pK_SdkError ? reason : new src_CX2iR2pK_SdkError(src_CX2iR2pK_SdkErrorCode.RequestTimeout, String(reason)); + } + const requestAbort = codec.era === src_CX2iR2pK_MODERN_WIRE_REVISION && this._transport.hasPerRequestStream === true ? new AbortController() : void 0; + const messageId = this._requestMessageId++; + cleanupMessageId = messageId; + const jsonrpcRequest = { + ...request, + jsonrpc: "2.0", + id: messageId + }; + if (options?.onprogress) { + this._progressHandlers.set(messageId, options.onprogress); + jsonrpcRequest.params = { + ...request.params, + _meta: { + ...request.params?._meta, + progressToken: messageId + } + }; + } + const outbound = this._envelopeOutbound(jsonrpcRequest); + let responseReceived = false; + const cancel = (reason) => { + if (responseReceived) return; + this._progressHandlers.delete(messageId); + if (requestAbort === void 0) this._transport?.send(this._envelopeOutbound({ + jsonrpc: "2.0", + method: "notifications/cancelled", + params: { + requestId: messageId, + reason: String(reason) + } + }), { + relatedRequestId, + resumptionToken, + onresumptiontoken + }).catch((error) => this._onerror(/* @__PURE__ */ new Error(`Failed to send cancellation: ${error}`))); + else requestAbort.abort(); + reject(reason instanceof src_CX2iR2pK_SdkError ? reason : new src_CX2iR2pK_SdkError(src_CX2iR2pK_SdkErrorCode.RequestTimeout, String(reason))); + }; + this._responseHandlers.set(messageId, (response) => { + if (options?.signal?.aborted) return; + responseReceived = true; + if (response instanceof Error) return reject(response); + let decoded; + try { + decoded = codec.decodeResult(request.method, response.result); + } catch (error) { + return reject(error instanceof Error ? error : new Error(String(error))); + } + if (decoded.kind === "invalid") return reject(decoded.error); + if (decoded.kind === "input_required") { + if (options?.allowInputRequired === true) return resolve(manualInputRequiredValue(decoded)); + const flow = { + codec, + request, + resultSchema, + options, + flowStartedAt, + retry: (params, legOptions) => this._requestWithSchemaViaCodec(codec, params === void 0 ? { method: request.method } : { + method: request.method, + params + }, resultSchema, legOptions) + }; + return resolve(this._resolveNonCompleteResult(decoded, flow)); + } + const result = decoded.result; + validateStandardSchema(resultSchema, result).then((parseResult) => { + if (parseResult.success) resolve(parseResult.data); + else reject(new src_CX2iR2pK_SdkError(src_CX2iR2pK_SdkErrorCode.InvalidResult, `Invalid result for ${request.method}: ${parseResult.error}`)); + }, reject); + }); + onAbort = () => cancel(options?.signal?.reason); + options?.signal?.addEventListener("abort", onAbort, { once: true }); + const timeout = options?.timeout ?? DEFAULT_REQUEST_TIMEOUT_MSEC; + const timeoutHandler = () => cancel(new src_CX2iR2pK_SdkError(src_CX2iR2pK_SdkErrorCode.RequestTimeout, "Request timed out", { timeout })); + this._setupTimeout(messageId, timeout, options?.maxTotalTimeout, timeoutHandler, options?.resetTimeoutOnProgress ?? false); + this._transport.send(outbound, { + relatedRequestId, + resumptionToken, + onresumptiontoken, + headers, + requestSignal: requestAbort?.signal + }).catch((error) => { + this._progressHandlers.delete(messageId); + reject(error); + }); + }).finally(() => { + if (onAbort) options?.signal?.removeEventListener("abort", onAbort); + if (cleanupMessageId !== void 0) { + this._responseHandlers.delete(cleanupMessageId); + this._cleanupTimeout(cleanupMessageId); + } + }); + } + /** + * Emits a notification, which is a one-way message that does not expect a response. + */ + async notification(notification, options) { + return this._notificationViaCodec(this._resolveOutboundCodec(notification.method), notification, options); + } + /** + * The notification funnel proper, keyed by the resolved era codec — + * direct sends and related notifications (`ctx.mcpReq.notify`) alike + * resolve through the instance's negotiated era at send time. + */ + async _notificationViaCodec(codec, notification, options) { + if (!this._transport) throw new src_CX2iR2pK_SdkError(src_CX2iR2pK_SdkErrorCode.NotConnected, "Not connected"); + if (isSpecNotificationMethod(notification.method) && !codec.hasNotificationMethod(notification.method)) throw new src_CX2iR2pK_SdkError(src_CX2iR2pK_SdkErrorCode.MethodNotSupportedByProtocolVersion, `Notification '${notification.method}' is not supported by the negotiated protocol version (wire era ${codec.era})`, { + method: notification.method, + era: codec.era + }); + this.assertNotificationCapability(notification.method); + const jsonrpcNotification = this._envelopeOutbound({ + jsonrpc: "2.0", + ...notification + }); + if ((this._options?.debouncedNotificationMethods ?? []).includes(notification.method) && !notification.params && !options?.relatedRequestId) { + if (this._pendingDebouncedNotifications.has(notification.method)) return; + this._pendingDebouncedNotifications.add(notification.method); + Promise.resolve().then(() => { + this._pendingDebouncedNotifications.delete(notification.method); + if (!this._transport) return; + this._transport?.send(jsonrpcNotification, options).catch((error) => this._onerror(error)); + }); + return; + } + await this._transport.send(jsonrpcNotification, options); + } + setRequestHandler(method, schemasOrHandler, maybeHandler) { + this.assertRequestHandlerCapability(method); + let stored; + if (typeof schemasOrHandler === "function") { + if (!isSpecRequestMethod(method)) throw new TypeError(`'${method}' is not a spec request method; pass schemas as the second argument to setRequestHandler().`); + stored = (request, ctx) => { + const dispatchCodec = this._negotiatedWireCodec(); + let outcome = dispatchCodec.validateRequest(method, request); + if (!outcome.ok && outcome.reason === "not-in-era") outcome = dispatchCodec.validateInputRequest(method, request); + if (!outcome.ok) { + if (outcome.reason === "not-in-era") throw new src_CX2iR2pK_ProtocolError(src_CX2iR2pK_ProtocolErrorCode.InternalError, `No wire schema for ${method} in the resolved era`); + throw new Error(outcome.message); + } + return Promise.resolve(schemasOrHandler(outcome.value, ctx)); + }; + } else if (maybeHandler) stored = async (request, ctx) => { + const parsed = await validateStandardSchema(schemasOrHandler.params, { ...request.params }); + if (!parsed.success) throw new src_CX2iR2pK_ProtocolError(src_CX2iR2pK_ProtocolErrorCode.InvalidParams, `Invalid params for ${method}: ${parsed.error}`); + return maybeHandler(parsed.data, ctx); + }; + else throw new TypeError("setRequestHandler: handler is required"); + this._requestHandlers.set(method, this._wrapHandler(method, stored)); + } + /** + * Hook for subclasses to wrap a registered request handler with role-specific + * validation or behavior (e.g. `Server` validates `tools/call` results, `Client` + * validates `elicitation/create` mode and result). Runs for both the 2-arg and + * 3-arg registration paths. The default implementation is identity. + * + * Subclasses overriding this hook avoid redeclaring `setRequestHandler`'s overload set. + */ + _wrapHandler(_method, handler) { + return handler; + } + /** + * Hook for subclasses to supply the implementation identity the 2026-era + * encode seam stamps into outbound result `_meta` under + * `io.modelcontextprotocol/serverInfo` (spec PR #3002: servers SHOULD + * identify themselves on every response). The default is `undefined` — no + * stamp. Only `Server` overrides this: the key identifies the software + * producing a response, and the 2025-era codec never stamps anything + * regardless (the never-stamp guarantee). + */ + _outboundServerInfo() {} + /** + * Removes the request handler for the given method. + */ + removeRequestHandler(method) { + this._requestHandlers.delete(method); + } + /** + * Asserts that a request handler has not already been set for the given method, in preparation for a new one being automatically installed. + */ + assertCanSetRequestHandler(method) { + if (this._requestHandlers.has(method)) throw new Error(`A request handler for ${method} already exists, which would be overridden`); + } + setNotificationHandler(method, schemasOrHandler, maybeHandler) { + if (typeof schemasOrHandler === "function") { + if (!isSpecNotificationMethod(method)) throw new TypeError(`'${method}' is not a spec notification method; pass schemas as the second argument to setNotificationHandler().`); + this._notificationHandlers.set(method, (notification, codec) => { + const outcome = codec.validateNotification(method, notification); + if (!outcome.ok) { + if (outcome.reason === "not-in-era") throw new src_CX2iR2pK_ProtocolError(src_CX2iR2pK_ProtocolErrorCode.InternalError, `No wire schema for ${method} in the resolved era`); + throw new Error(outcome.message); + } + return Promise.resolve(schemasOrHandler(outcome.value)); + }); + return; + } + if (!maybeHandler) throw new TypeError("setNotificationHandler: handler is required"); + this._notificationHandlers.set(method, async (notification) => { + const parsed = await validateStandardSchema(schemasOrHandler.params, { ...notification.params }); + if (!parsed.success) throw new src_CX2iR2pK_ProtocolError(src_CX2iR2pK_ProtocolErrorCode.InvalidParams, `Invalid params for notification ${method}: ${parsed.error}`); + await maybeHandler(parsed.data, notification); + }); + } + /** + * Removes the notification handler for the given method. + */ + removeNotificationHandler(method) { + this._notificationHandlers.delete(method); + } +}; +function isPlainObject$1(value) { + return value !== null && typeof value === "object" && !Array.isArray(value); +} +function mergeCapabilities(base, additional) { + const result = { ...base }; + for (const key in additional) { + const k = key; + const addValue = additional[k]; + if (addValue === void 0) continue; + const baseValue = result[k]; + result[k] = isPlainObject$1(baseValue) && isPlainObject$1(addValue) ? { + ...baseValue, + ...addValue + } : addValue; + } + return result; +} + +//#endregion +//#region ../core-internal/src/shared/inputRequiredEngine.ts +function src_CX2iR2pK_isPlainObject(value) { + return typeof value === "object" && value !== null && !Array.isArray(value); +} +/** +* Splits a retried request's `inputResponses` map into the BARE response +* entries the spec defines and everything else. The spec's embedded responses +* are the bare result objects (an `ElicitResult`, `CreateMessageResult`, or +* `ListRootsResult`); a wrapped `{method, result}` envelope (a shape some +* peers emit) is never accepted as a response — its key is recorded so the +* handler can re-issue the corresponding input request. +*/ +function partitionInputResponses(inputResponses) { + const accepted = {}; + const droppedKeys = []; + if (!src_CX2iR2pK_isPlainObject(inputResponses)) return { + accepted, + droppedKeys + }; + for (const [key, entry] of Object.entries(inputResponses)) { + if (!src_CX2iR2pK_isPlainObject(entry) || "method" in entry || "result" in entry) { + droppedKeys.push(key); + continue; + } + accepted[key] = entry; + } + return { + accepted, + droppedKeys + }; +} +/** +* Builds the manual-mode {@linkcode InputRequiredResult} value from the +* codec's decoded payload — what an `allowInputRequired: true` caller +* receives instead of the auto-fulfilled complete result. +*/ +function manualInputRequiredValue(decoded) { + return { + resultType: "input_required", + inputRequests: decoded.inputRequests, + ...decoded.requestState !== void 0 && { requestState: decoded.requestState } + }; +} + +//#endregion +//#region ../../node_modules/.pnpm/content-type@1.0.5/node_modules/content-type/index.js +/*! +* content-type +* Copyright(c) 2015 Douglas Christopher Wilson +* MIT Licensed +*/ +var require_content_type = /* @__PURE__ */ __commonJSMin(((exports) => { + /** + * RegExp to match *( ";" parameter ) in RFC 7231 sec 3.1.1.1 + * + * parameter = token "=" ( token / quoted-string ) + * token = 1*tchar + * tchar = "!" / "#" / "$" / "%" / "&" / "'" / "*" + * / "+" / "-" / "." / "^" / "_" / "`" / "|" / "~" + * / DIGIT / ALPHA + * ; any VCHAR, except delimiters + * quoted-string = DQUOTE *( qdtext / quoted-pair ) DQUOTE + * qdtext = HTAB / SP / %x21 / %x23-5B / %x5D-7E / obs-text + * obs-text = %x80-FF + * quoted-pair = "\" ( HTAB / SP / VCHAR / obs-text ) + */ + var PARAM_REGEXP = /; *([!#$%&'*+.^_`|~0-9A-Za-z-]+) *= *("(?:[\u000b\u0020\u0021\u0023-\u005b\u005d-\u007e\u0080-\u00ff]|\\[\u000b\u0020-\u00ff])*"|[!#$%&'*+.^_`|~0-9A-Za-z-]+) */g; + /** + * RegExp to match quoted-pair in RFC 7230 sec 3.2.6 + * + * quoted-pair = "\" ( HTAB / SP / VCHAR / obs-text ) + * obs-text = %x80-FF + */ + var QESC_REGEXP = /\\([\u000b\u0020-\u00ff])/g; + /** + * RegExp to match type in RFC 7231 sec 3.1.1.1 + * + * media-type = type "/" subtype + * type = token + * subtype = token + */ + var TYPE_REGEXP = /^[!#$%&'*+.^_`|~0-9A-Za-z-]+\/[!#$%&'*+.^_`|~0-9A-Za-z-]+$/; + exports.parse = parse; + /** + * Parse media type to object. + * + * @param {string|object} string + * @return {Object} + * @public + */ + function parse(string) { + if (!string) throw new TypeError("argument string is required"); + var header = typeof string === "object" ? getcontenttype(string) : string; + if (typeof header !== "string") throw new TypeError("argument string is required to be a string"); + var index = header.indexOf(";"); + var type = index !== -1 ? header.slice(0, index).trim() : header.trim(); + if (!TYPE_REGEXP.test(type)) throw new TypeError("invalid media type"); + var obj = new ContentType(type.toLowerCase()); + if (index !== -1) { + var key; + var match; + var value; + PARAM_REGEXP.lastIndex = index; + while (match = PARAM_REGEXP.exec(header)) { + if (match.index !== index) throw new TypeError("invalid parameter format"); + index += match[0].length; + key = match[1].toLowerCase(); + value = match[2]; + if (value.charCodeAt(0) === 34) { + value = value.slice(1, -1); + if (value.indexOf("\\") !== -1) value = value.replace(QESC_REGEXP, "$1"); + } + obj.parameters[key] = value; + } + if (index !== header.length) throw new TypeError("invalid parameter format"); + } + return obj; + } + /** + * Get content-type from req/res objects. + * + * @param {object} + * @return {Object} + * @private + */ + function getcontenttype(obj) { + var header; + if (typeof obj.getHeader === "function") header = obj.getHeader("content-type"); + else if (typeof obj.headers === "object") header = obj.headers && obj.headers["content-type"]; + if (typeof header !== "string") throw new TypeError("content-type header is missing from object"); + return header; + } + /** + * Class to represent a content type. + * @private + */ + function ContentType(type) { + this.parameters = Object.create(null); + this.type = type; + } +})); + +//#endregion +//#region ../core-internal/src/shared/mediaType.ts +var import_content_type = /* @__PURE__ */ __toESM(require_content_type(), 1); +/** +* Extracts the media type (the lowercased `type/subtype` pair, without +* parameters) from a raw `Content-Type` header value, or `undefined` when the +* header is missing or empty. +* +* Content-Type comparisons must use the parsed media type, never a substring +* search of the raw header: a value like `text/plain; a=application/json` +* contains the substring `application/json` but its media type is +* `text/plain`, and case variants or parameters make naive string comparison +* wrong in both directions. +* +* "Essence" is the WHATWG MIME Sniffing standard's term for the bare +* `type/subtype` pair (https://mimesniff.spec.whatwg.org/#mime-type-essence); +* the Fetch standard's request classification is defined against it +* (https://fetch.spec.whatwg.org/#cors-safelisted-request-header). +* +* Parsing is RFC 9110 (`content-type` package) first. When the parameter +* section is malformed (`application/json;`, `application/json; charset=`), +* browsers and most HTTP stacks still derive the media type from the segment +* before the first `;` — the fallback matches that widely-implemented +* behavior, so a header whose media type is unambiguous is not rejected for +* a sloppy parameter section. +*/ +function src_CX2iR2pK_mediaTypeEssence(header) { + if (!header) return; + try { + return import_content_type.parse(header).type; + } catch { + const essence = (header.split(";", 1)[0] ?? "").trim().toLowerCase(); + if (essence === "" || header.slice(essence.length).includes(",")) return; + return essence; + } +} +/** +* Whether a raw `Content-Type` header value denotes `application/json`. +* Parameters (for example `charset=utf-8`) are allowed and ignored; malformed +* parameter sections do not reject a header whose media type is unambiguously +* `application/json` (see `mediaTypeEssence` for the exact grammar). +*/ +function src_CX2iR2pK_isJsonContentType(header) { + if (header === "application/json") return true; + return src_CX2iR2pK_mediaTypeEssence(header) === "application/json"; +} + +//#endregion +//#region ../core-internal/src/shared/metadataUtils.ts +/** +* Utilities for working with {@linkcode BaseMetadata} objects. +*/ +/** +* Gets the display name for an object with {@linkcode BaseMetadata}. +* For tools, the precedence is: `title` → {@linkcode index.ToolAnnotations | annotations}.`title` → `name` +* For other objects: `title` → `name` +* This implements the spec requirement: "if no title is provided, name should be used for display purposes" +*/ +function getDisplayName(metadata) { + if (metadata.title !== void 0 && metadata.title !== "") return metadata.title; + if ("annotations" in metadata && metadata.annotations?.title) return metadata.annotations.title; + return metadata.name; +} + +//#endregion +//#region ../core-internal/src/shared/stdio.ts +const STDIO_DEFAULT_MAX_BUFFER_SIZE = 10 * 1024 * 1024; +/** +* Buffers a continuous stdio stream into discrete JSON-RPC messages. +*/ +var ReadBuffer = class { + _buffer; + _maxBufferSize; + constructor(options) { + this._maxBufferSize = options?.maxBufferSize ?? STDIO_DEFAULT_MAX_BUFFER_SIZE; + } + append(chunk) { + if ((this._buffer?.length ?? 0) + chunk.length > this._maxBufferSize) { + this.clear(); + throw new Error(`ReadBuffer exceeded maximum size of ${this._maxBufferSize} bytes`); + } + this._buffer = this._buffer ? Buffer.concat([this._buffer, chunk]) : chunk; + } + readMessage() { + while (this._buffer) { + const index = this._buffer.indexOf("\n"); + if (index === -1) return null; + const line = this._buffer.toString("utf8", 0, index).replace(/\r$/, ""); + this._buffer = this._buffer.subarray(index + 1); + try { + return deserializeMessage(line); + } catch (error) { + if (error instanceof SyntaxError) continue; + throw error; + } + } + return null; + } + clear() { + this._buffer = void 0; + } +}; +function deserializeMessage(line) { + return auth_CUe6YdwF_JSONRPCMessageSchema.parse(JSON.parse(line)); +} +function serializeMessage(message) { + return JSON.stringify(message) + "\n"; +} + +//#endregion +//#region ../core-internal/src/shared/toolNameValidation.ts +/** +* Tool name validation utilities according to SEP: Specify Format for Tool Names +* +* Tool names SHOULD be between 1 and 128 characters in length (inclusive). +* Tool names are case-sensitive. +* Allowed characters: uppercase and lowercase ASCII letters (`A-Z`, `a-z`), digits +* (`0-9`), underscore (`_`), dash (`-`), and dot (`.`). +* Tool names SHOULD NOT contain spaces, commas, or other special characters. +* +* @see {@link https://github.com/modelcontextprotocol/modelcontextprotocol/issues/986 | SEP-986: Specify Format for Tool Names} +*/ +/** +* Regular expression for valid tool names according to SEP-986 specification +*/ +const TOOL_NAME_REGEX = /^[A-Za-z0-9._-]{1,128}$/; +/** +* Validates a tool name according to the SEP specification +* @param name - The tool name to validate +* @returns An object containing validation result and any warnings +*/ +function validateToolName(name) { + const warnings = []; + if (name.length === 0) return { + isValid: false, + warnings: ["Tool name cannot be empty"] + }; + if (name.length > 128) return { + isValid: false, + warnings: [`Tool name exceeds maximum length of 128 characters (current: ${name.length})`] + }; + if (name.includes(" ")) warnings.push("Tool name contains spaces, which may cause parsing issues"); + if (name.includes(",")) warnings.push("Tool name contains commas, which may cause parsing issues"); + if (name.startsWith("-") || name.endsWith("-")) warnings.push("Tool name starts or ends with a dash, which may cause parsing issues in some contexts"); + if (name.startsWith(".") || name.endsWith(".")) warnings.push("Tool name starts or ends with a dot, which may cause parsing issues in some contexts"); + if (!TOOL_NAME_REGEX.test(name)) { + const invalidChars = [...name].filter((char) => !/[A-Za-z0-9._-]/.test(char)).filter((char, index, arr) => arr.indexOf(char) === index); + warnings.push(`Tool name contains invalid characters: ${invalidChars.map((c) => `"${c}"`).join(", ")}`, "Allowed characters are: A-Z, a-z, 0-9, underscore (_), dash (-), and dot (.)"); + return { + isValid: false, + warnings + }; + } + return { + isValid: true, + warnings + }; +} +/** +* Issues warnings for non-conforming tool names +* @param name - The tool name that triggered the warnings +* @param warnings - Array of warning messages +*/ +function issueToolNameWarning(name, warnings) { + if (warnings.length > 0) { + console.warn(`Tool name validation warning for "${name}":`); + for (const warning of warnings) console.warn(` - ${warning}`); + console.warn("Tool registration will proceed, but this may cause compatibility issues."); + console.warn("Consider updating the tool name to conform to the MCP tool naming standard."); + console.warn("See SEP: Specify Format for Tool Names (https://github.com/modelcontextprotocol/modelcontextprotocol/issues/986) for more details."); + } +} +/** +* Validates a tool name and issues warnings for non-conforming names +* @param name - The tool name to validate +* @returns `true` if the name is valid, `false` otherwise +*/ +function validateAndWarnToolName(name) { + const result = validateToolName(name); + issueToolNameWarning(name, result.warnings); + return result.isValid; +} + +//#endregion +//#region ../core-internal/src/shared/transport.ts +/** +* Normalizes `HeadersInit` to a plain `Record` for manipulation. +* Handles `Headers` objects, arrays of tuples, and plain objects. +*/ +function normalizeHeaders(headers) { + if (!headers) return {}; + if (headers instanceof Headers) return Object.fromEntries(headers.entries()); + if (Array.isArray(headers)) return Object.fromEntries(headers); + return { ...headers }; +} +/** +* Creates a fetch function that includes base `RequestInit` options. +* This ensures requests inherit settings like credentials, mode, headers, etc. from the base init. +* +* @param baseFetch - The base fetch function to wrap (defaults to global `fetch`) +* @param baseInit - The base `RequestInit` to merge with each request +* @returns A wrapped fetch function that merges base options with call-specific options +*/ +function createFetchWithInit(baseFetch = fetch, baseInit) { + if (!baseInit) return baseFetch; + return async (url, init) => { + return baseFetch(url, { + ...baseInit, + ...init, + headers: init?.headers ? { + ...normalizeHeaders(baseInit.headers), + ...normalizeHeaders(init.headers) + } : baseInit.headers + }); + }; +} + +//#endregion +//#region ../core-internal/src/shared/uriTemplate.ts +const MAX_TEMPLATE_LENGTH = 1e6; +const MAX_VARIABLE_LENGTH = 1e6; +const MAX_TEMPLATE_EXPRESSIONS = 1e4; +const MAX_REGEX_LENGTH = 1e6; +var src_CX2iR2pK_UriTemplate = class UriTemplate { + /** + * Returns true if the given string contains any URI template expressions. + * A template expression is a sequence of characters enclosed in curly braces, + * like `{foo}` or `{?bar}`. + */ + static isTemplate(str) { + return /\{[^}\s]+\}/.test(str); + } + static validateLength(str, max, context) { + if (str.length > max) throw new Error(`${context} exceeds maximum length of ${max} characters (got ${str.length})`); + } + template; + parts; + get variableNames() { + return this.parts.flatMap((part) => typeof part === "string" ? [] : part.names); + } + constructor(template) { + UriTemplate.validateLength(template, MAX_TEMPLATE_LENGTH, "Template"); + this.template = template; + this.parts = this.parse(template); + } + toString() { + return this.template; + } + parse(template) { + const parts = []; + let currentText = ""; + let i = 0; + let expressionCount = 0; + while (i < template.length) if (template[i] === "{") { + if (currentText) { + parts.push(currentText); + currentText = ""; + } + const end = template.indexOf("}", i); + if (end === -1) throw new Error("Unclosed template expression"); + expressionCount++; + if (expressionCount > MAX_TEMPLATE_EXPRESSIONS) throw new Error(`Template contains too many expressions (max ${MAX_TEMPLATE_EXPRESSIONS})`); + const expr = template.slice(i + 1, end); + const operator = this.getOperator(expr); + const exploded = expr.includes("*"); + const names = this.getNames(expr); + const name = names[0]; + for (const name$1 of names) UriTemplate.validateLength(name$1, MAX_VARIABLE_LENGTH, "Variable name"); + parts.push({ + name, + operator, + names, + exploded + }); + i = end + 1; + } else { + currentText += template[i]; + i++; + } + if (currentText) parts.push(currentText); + return parts; + } + getOperator(expr) { + return [ + "+", + "#", + ".", + "/", + "?", + "&" + ].find((op) => expr.startsWith(op)) || ""; + } + getNames(expr) { + const operator = this.getOperator(expr); + return expr.slice(operator.length).split(",").map((name) => name.replace("*", "").trim()).filter((name) => name.length > 0); + } + encodeValue(value, operator) { + UriTemplate.validateLength(value, MAX_VARIABLE_LENGTH, "Variable value"); + if (operator === "+" || operator === "#") return encodeURI(value); + return encodeURIComponent(value); + } + expandPart(part, variables) { + if (part.operator === "?" || part.operator === "&") { + const pairs = part.names.map((name) => { + const value$1 = variables[name]; + if (value$1 === void 0) return ""; + return `${name}=${Array.isArray(value$1) ? value$1.map((v) => this.encodeValue(v, part.operator)).join(",") : this.encodeValue(value$1.toString(), part.operator)}`; + }).filter((pair) => pair.length > 0); + if (pairs.length === 0) return ""; + return (part.operator === "?" ? "?" : "&") + pairs.join("&"); + } + if (part.names.length > 1) { + const values = part.names.map((name) => variables[name]).filter((v) => v !== void 0); + if (values.length === 0) return ""; + return values.map((v) => Array.isArray(v) ? v[0] : v).join(","); + } + const value = variables[part.name]; + if (value === void 0) return ""; + const encoded = (Array.isArray(value) ? value : [value]).map((v) => this.encodeValue(v, part.operator)); + switch (part.operator) { + case "": return encoded.join(","); + case "+": return encoded.join(","); + case "#": return "#" + encoded.join(","); + case ".": return "." + encoded.join("."); + case "/": return "/" + encoded.join("/"); + default: return encoded.join(","); + } + } + expand(variables) { + let result = ""; + let hasQueryParam = false; + for (const part of this.parts) { + if (typeof part === "string") { + result += part; + continue; + } + const expanded = this.expandPart(part, variables); + if (!expanded) continue; + result += (part.operator === "?" || part.operator === "&") && hasQueryParam ? expanded.replace("?", "&") : expanded; + if (part.operator === "?" || part.operator === "&") hasQueryParam = true; + } + return result; + } + escapeRegExp(str) { + return str.replaceAll(/[.*+?^${}()|[\]\\]/g, String.raw`\$&`); + } + partToRegExp(part) { + const patterns = []; + for (const name$1 of part.names) UriTemplate.validateLength(name$1, MAX_VARIABLE_LENGTH, "Variable name"); + if (part.operator === "?" || part.operator === "&") { + for (let i = 0; i < part.names.length; i++) { + const name$1 = part.names[i]; + const prefix = i === 0 ? "\\" + part.operator : "&"; + patterns.push({ + pattern: prefix + this.escapeRegExp(name$1) + "=([^&]+)", + name: name$1 + }); + } + return patterns; + } + let pattern; + const name = part.name; + switch (part.operator) { + case "": + pattern = part.exploded ? "([^/,]+(?:,[^/,]+)*)" : "([^/,]+)"; + break; + case "+": + case "#": + pattern = "(.+)"; + break; + case ".": + pattern = String.raw`\.([^/,]+)`; + break; + case "/": + pattern = "/" + (part.exploded ? "([^/,]+(?:,[^/,]+)*)" : "([^/,]+)"); + break; + default: pattern = "([^/]+)"; + } + patterns.push({ + pattern, + name + }); + return patterns; + } + match(uri) { + UriTemplate.validateLength(uri, MAX_TEMPLATE_LENGTH, "URI"); + let pattern = "^"; + const names = []; + for (const part of this.parts) if (typeof part === "string") pattern += this.escapeRegExp(part); + else { + const patterns = this.partToRegExp(part); + for (const { pattern: partPattern, name } of patterns) { + pattern += partPattern; + names.push({ + name, + exploded: part.exploded + }); + } + } + pattern += "$"; + UriTemplate.validateLength(pattern, MAX_REGEX_LENGTH, "Generated regex pattern"); + const regex = new RegExp(pattern); + const match = uri.match(regex); + if (!match) return null; + const result = {}; + for (const [i, name_] of names.entries()) { + const { name, exploded } = name_; + const value = match[i + 1]; + const cleanName = name.replace("*", ""); + result[cleanName] = exploded && value.includes(",") ? value.split(",") : value; + } + return result; + } +}; + +//#endregion +//#region ../core-internal/src/util/inMemory.ts +/** +* In-memory transport for creating clients and servers that talk to each other within the same process. +* +* Intended for testing and development. For production in-process connections, use +* `StreamableHTTPClientTransport` against a local server URL. +*/ +var src_CX2iR2pK_InMemoryTransport = class InMemoryTransport { + _otherTransport; + _messageQueue = []; + _closed = false; + onclose; + onerror; + onmessage; + sessionId; + /** + * Creates a pair of linked in-memory transports that can communicate with each other. One should be passed to a {@linkcode @modelcontextprotocol/client!client/client.Client | Client} and one to a {@linkcode @modelcontextprotocol/server!server/server.Server | Server}. + */ + static createLinkedPair() { + const clientTransport = new InMemoryTransport(); + const serverTransport = new InMemoryTransport(); + clientTransport._otherTransport = serverTransport; + serverTransport._otherTransport = clientTransport; + return [clientTransport, serverTransport]; + } + async start() { + while (this._messageQueue.length > 0) { + const queuedMessage = this._messageQueue.shift(); + this.onmessage?.(queuedMessage.message, queuedMessage.extra); + } + } + async close() { + if (this._closed) return; + this._closed = true; + const other = this._otherTransport; + this._otherTransport = void 0; + try { + await other?.close(); + } finally { + this.onclose?.(); + } + } + /** + * Sends a message with optional auth info. + * This is useful for testing authentication scenarios. + */ + async send(message, options) { + if (!this._otherTransport) throw new src_CX2iR2pK_SdkError(src_CX2iR2pK_SdkErrorCode.NotConnected, "Not connected"); + if (this._otherTransport.onmessage) this._otherTransport.onmessage(message, { authInfo: options?.authInfo }); + else this._otherTransport._messageQueue.push({ + message, + extra: { authInfo: options?.authInfo } + }); + } +}; + +//#endregion +//#region ../core-internal/src/util/zodCompat.ts +/** +* Zod-specific helpers for the v1-compat raw-shape shorthand on +* `registerTool`/`registerPrompt`. Kept separate from `standardSchema.ts` so +* that file stays library-agnostic per the Standard Schema spec. +*/ +function isZodV4Schema(v) { + return typeof v === "object" && v !== null && "_zod" in v; +} +function looksLikeZodV3(v) { + return typeof v === "object" && v !== null && !("_zod" in v) && "_def" in v && typeof v._def?.typeName === "string"; +} +/** +* Detects a "raw shape" — a plain object whose values are Zod field schemas, +* e.g. `{ name: z.string() }`. Powers the auto-wrap in +* {@linkcode normalizeRawShapeSchema}, which wraps with `z.object()`, so only +* Zod values are supported. +* +* @internal +*/ +function isZodRawShape(obj) { + if (typeof obj !== "object" || obj === null) return false; + if (isStandardSchema(obj)) return false; + const proto = Object.getPrototypeOf(obj); + if (proto !== Object.prototype && proto !== null) return false; + return Object.values(obj).every((v) => isZodV4Schema(v)); +} +/** +* Accepts either a {@linkcode StandardSchemaWithJSON} or a raw Zod shape +* `{ field: z.string() }` and returns a {@linkcode StandardSchemaWithJSON}. +* Raw shapes are wrapped with `z.object()` so the rest of the pipeline sees a +* uniform schema type; already-wrapped schemas pass through unchanged. +* +* @internal +*/ +function normalizeRawShapeSchema(schema) { + if (schema === void 0) return void 0; + if (isZodRawShape(schema)) return schemas_object(schema); + if (typeof schema === "object" && schema !== null && !isStandardSchema(schema) && Object.values(schema).some((v) => looksLikeZodV3(v))) throw new TypeError("Raw-shape inputSchema/outputSchema/argsSchema fields must be Zod v4 schemas. Got a Zod v3 field schema. Import from `zod/v4` (or upgrade your zod import), or wrap with `z.object({...})` yourself."); + if (!isStandardSchema(schema)) throw new TypeError("inputSchema/outputSchema/argsSchema must be a Standard Schema (e.g. z.object({...})) or a raw Zod shape ({ field: z.string() })."); + return schema; +} + +//#endregion +//#region ../core-internal/src/wire/preload.ts +/** +* Explicit warm-up entry for the lazy wire-schema layers. +* +* The per-revision wire schemas are built lazily: each era's schema set sits +* behind a memoized factory (`buildSchemas2025`/`buildSchemas2026`), and the +* registry/codec lookup maps above those factories are memoized the same way. +* That laziness is the right default on process-per-invocation runtimes (CLI +* tools, dev servers), where module evaluation IS startup latency and most +* short-lived processes never validate a message on both eras. +* +* On platforms that bill request CPU but not module evaluation — isolate-based +* edge/serverless runtimes such as Cloudflare Workers — the trade inverts: +* module-scope work runs during isolate warm-up outside any request, while +* lazy construction lands inside the first request's billed (and latency +* budgeted) CPU. `preloadSchemas()` lets deployments on such platforms move +* the one-time construction cost back to module scope by calling it at module +* scope themselves. The packages' own workerd shims already do this, so +* Workers deployments get eager construction automatically. +*/ +/** +* Eagerly builds every lazily-constructed wire-schema layer, so that no later +* validation pays schema-construction cost. +* +* Synchronous and idempotent: every layer is a memo, so the first call does +* all the work and subsequent calls return immediately. Reference identity is +* unaffected — this forces the same memos every lazy consumer pulls through. +* +* Call it at module scope on platforms that bill per-request CPU but not +* module evaluation (isolate-based edge/serverless runtimes), where deferring +* construction would move it into the first request of every fresh isolate: +* +* ```ts +* // from '@modelcontextprotocol/server' or '@modelcontextprotocol/client' — +* // each package bundles its own schema copy, so warm the one(s) you import. +* preloadSchemas(); // module scope — runs during isolate warm-up +* ``` +* +* On Node CLIs and other process-per-invocation runtimes, prefer the lazy +* default — there, module-scope construction is pure added boot latency. +*/ +function preloadSchemas() { + buildSchemas2025(); + buildSchemas2026(); + warmRegistryMaps2025(); + warmInputSchemaMaps2026(); + warmWireResultSchemas2026(); +} + +//#endregion +//#region ../core-internal/src/validators/fromJsonSchema.ts +/** +* Wrap a raw JSON Schema object as a {@linkcode StandardSchemaWithJSON} so it can be +* passed to `registerTool` / `registerPrompt`. Use this when you already have JSON +* Schema (e.g. from TypeBox, or hand-written) and want to register it without going +* through a Standard Schema library. +* +* The callback arguments will be typed `unknown` (raw JSON Schema has no TypeScript +* types attached). Cast at the call site, or use the generic `fromJsonSchema(...)`. +* +* @param schema - A JSON Schema object describing the expected shape +* @param validator - A validator provider. When importing `fromJsonSchema` from +* `@modelcontextprotocol/server` or `@modelcontextprotocol/client`, a runtime-appropriate +* default is provided automatically (AJV on Node.js, CfWorker on edge runtimes). +* +* @example +* ```ts source="./fromJsonSchema.examples.ts#fromJsonSchema_basicUsage" +* const inputSchema = fromJsonSchema<{ name: string }>( +* { type: 'object', properties: { name: { type: 'string' } }, required: ['name'] }, +* validator +* ); +* // Use with server.registerTool('greet', { inputSchema }, handler) +* ``` +*/ +function fromJsonSchema(schema, validator) { + const check = validator.getValidator(schema); + return { "~standard": { + version: 1, + vendor: "mcp", + jsonSchema: { + input: () => schema, + output: () => schema + }, + validate: (data) => { + const result = check(data); + return result.valid ? { value: result.data } : { issues: [{ message: result.errorMessage }] }; + } + } }; +} + +//#endregion + +//# sourceMappingURL=src-CX2iR2pK.mjs.map + + + +//#region ../../node_modules/.pnpm/ajv@8.18.0/node_modules/ajv/dist/compile/codegen/code.js +var require_code$1 = /* @__PURE__ */ __commonJSMin(((exports) => { + Object.defineProperty(exports, "__esModule", { value: true }); + exports.regexpCode = exports.getEsmExportName = exports.getProperty = exports.safeStringify = exports.stringify = exports.strConcat = exports.addCodeArg = exports.str = exports._ = exports.nil = exports._Code = exports.Name = exports.IDENTIFIER = exports._CodeOrName = void 0; + var _CodeOrName = class {}; + exports._CodeOrName = _CodeOrName; + exports.IDENTIFIER = /^[a-z$_][a-z$_0-9]*$/i; + var Name = class extends _CodeOrName { + constructor(s) { + super(); + if (!exports.IDENTIFIER.test(s)) throw new Error("CodeGen: name must be a valid identifier"); + this.str = s; + } + toString() { + return this.str; + } + emptyStr() { + return false; + } + get names() { + return { [this.str]: 1 }; + } + }; + exports.Name = Name; + var _Code = class extends _CodeOrName { + constructor(code) { + super(); + this._items = typeof code === "string" ? [code] : code; + } + toString() { + return this.str; + } + emptyStr() { + if (this._items.length > 1) return false; + const item = this._items[0]; + return item === "" || item === "\"\""; + } + get str() { + var _a; + return (_a = this._str) !== null && _a !== void 0 ? _a : this._str = this._items.reduce((s, c) => `${s}${c}`, ""); + } + get names() { + var _a; + return (_a = this._names) !== null && _a !== void 0 ? _a : this._names = this._items.reduce((names, c) => { + if (c instanceof Name) names[c.str] = (names[c.str] || 0) + 1; + return names; + }, {}); + } + }; + exports._Code = _Code; + exports.nil = new _Code(""); + function _(strs, ...args) { + const code = [strs[0]]; + let i = 0; + while (i < args.length) { + addCodeArg(code, args[i]); + code.push(strs[++i]); + } + return new _Code(code); + } + exports._ = _; + const plus = new _Code("+"); + function str(strs, ...args) { + const expr = [safeStringify(strs[0])]; + let i = 0; + while (i < args.length) { + expr.push(plus); + addCodeArg(expr, args[i]); + expr.push(plus, safeStringify(strs[++i])); + } + optimize(expr); + return new _Code(expr); + } + exports.str = str; + function addCodeArg(code, arg) { + if (arg instanceof _Code) code.push(...arg._items); + else if (arg instanceof Name) code.push(arg); + else code.push(interpolate(arg)); + } + exports.addCodeArg = addCodeArg; + function optimize(expr) { + let i = 1; + while (i < expr.length - 1) { + if (expr[i] === plus) { + const res = mergeExprItems(expr[i - 1], expr[i + 1]); + if (res !== void 0) { + expr.splice(i - 1, 3, res); + continue; + } + expr[i++] = "+"; + } + i++; + } + } + function mergeExprItems(a, b) { + if (b === "\"\"") return a; + if (a === "\"\"") return b; + if (typeof a == "string") { + if (b instanceof Name || a[a.length - 1] !== "\"") return; + if (typeof b != "string") return `${a.slice(0, -1)}${b}"`; + if (b[0] === "\"") return a.slice(0, -1) + b.slice(1); + return; + } + if (typeof b == "string" && b[0] === "\"" && !(a instanceof Name)) return `"${a}${b.slice(1)}`; + } + function strConcat(c1, c2) { + return c2.emptyStr() ? c1 : c1.emptyStr() ? c2 : str`${c1}${c2}`; + } + exports.strConcat = strConcat; + function interpolate(x) { + return typeof x == "number" || typeof x == "boolean" || x === null ? x : safeStringify(Array.isArray(x) ? x.join(",") : x); + } + function stringify(x) { + return new _Code(safeStringify(x)); + } + exports.stringify = stringify; + function safeStringify(x) { + return JSON.stringify(x).replace(/\u2028/g, "\\u2028").replace(/\u2029/g, "\\u2029"); + } + exports.safeStringify = safeStringify; + function getProperty(key) { + return typeof key == "string" && exports.IDENTIFIER.test(key) ? new _Code(`.${key}`) : _`[${key}]`; + } + exports.getProperty = getProperty; + function getEsmExportName(key) { + if (typeof key == "string" && exports.IDENTIFIER.test(key)) return new _Code(`${key}`); + throw new Error(`CodeGen: invalid export name: ${key}, use explicit $id name mapping`); + } + exports.getEsmExportName = getEsmExportName; + function regexpCode(rx) { + return new _Code(rx.toString()); + } + exports.regexpCode = regexpCode; +})); + +//#endregion +//#region ../../node_modules/.pnpm/ajv@8.18.0/node_modules/ajv/dist/compile/codegen/scope.js +var require_scope = /* @__PURE__ */ __commonJSMin(((exports) => { + Object.defineProperty(exports, "__esModule", { value: true }); + exports.ValueScope = exports.ValueScopeName = exports.Scope = exports.varKinds = exports.UsedValueState = void 0; + const code_1 = require_code$1(); + var ValueError = class extends Error { + constructor(name) { + super(`CodeGen: "code" for ${name} not defined`); + this.value = name.value; + } + }; + var UsedValueState; + (function(UsedValueState) { + UsedValueState[UsedValueState["Started"] = 0] = "Started"; + UsedValueState[UsedValueState["Completed"] = 1] = "Completed"; + })(UsedValueState || (exports.UsedValueState = UsedValueState = {})); + exports.varKinds = { + const: new code_1.Name("const"), + let: new code_1.Name("let"), + var: new code_1.Name("var") + }; + var Scope = class { + constructor({ prefixes, parent } = {}) { + this._names = {}; + this._prefixes = prefixes; + this._parent = parent; + } + toName(nameOrPrefix) { + return nameOrPrefix instanceof code_1.Name ? nameOrPrefix : this.name(nameOrPrefix); + } + name(prefix) { + return new code_1.Name(this._newName(prefix)); + } + _newName(prefix) { + const ng = this._names[prefix] || this._nameGroup(prefix); + return `${prefix}${ng.index++}`; + } + _nameGroup(prefix) { + var _a, _b; + if (((_b = (_a = this._parent) === null || _a === void 0 ? void 0 : _a._prefixes) === null || _b === void 0 ? void 0 : _b.has(prefix)) || this._prefixes && !this._prefixes.has(prefix)) throw new Error(`CodeGen: prefix "${prefix}" is not allowed in this scope`); + return this._names[prefix] = { + prefix, + index: 0 + }; + } + }; + exports.Scope = Scope; + var ValueScopeName = class extends code_1.Name { + constructor(prefix, nameStr) { + super(nameStr); + this.prefix = prefix; + } + setValue(value, { property, itemIndex }) { + this.value = value; + this.scopePath = (0, code_1._)`.${new code_1.Name(property)}[${itemIndex}]`; + } + }; + exports.ValueScopeName = ValueScopeName; + const line = (0, code_1._)`\n`; + var ValueScope = class extends Scope { + constructor(opts) { + super(opts); + this._values = {}; + this._scope = opts.scope; + this.opts = { + ...opts, + _n: opts.lines ? line : code_1.nil + }; + } + get() { + return this._scope; + } + name(prefix) { + return new ValueScopeName(prefix, this._newName(prefix)); + } + value(nameOrPrefix, value) { + var _a; + if (value.ref === void 0) throw new Error("CodeGen: ref must be passed in value"); + const name = this.toName(nameOrPrefix); + const { prefix } = name; + const valueKey = (_a = value.key) !== null && _a !== void 0 ? _a : value.ref; + let vs = this._values[prefix]; + if (vs) { + const _name = vs.get(valueKey); + if (_name) return _name; + } else vs = this._values[prefix] = /* @__PURE__ */ new Map(); + vs.set(valueKey, name); + const s = this._scope[prefix] || (this._scope[prefix] = []); + const itemIndex = s.length; + s[itemIndex] = value.ref; + name.setValue(value, { + property: prefix, + itemIndex + }); + return name; + } + getValue(prefix, keyOrRef) { + const vs = this._values[prefix]; + if (!vs) return; + return vs.get(keyOrRef); + } + scopeRefs(scopeName, values = this._values) { + return this._reduceValues(values, (name) => { + if (name.scopePath === void 0) throw new Error(`CodeGen: name "${name}" has no value`); + return (0, code_1._)`${scopeName}${name.scopePath}`; + }); + } + scopeCode(values = this._values, usedValues, getCode) { + return this._reduceValues(values, (name) => { + if (name.value === void 0) throw new Error(`CodeGen: name "${name}" has no value`); + return name.value.code; + }, usedValues, getCode); + } + _reduceValues(values, valueCode, usedValues = {}, getCode) { + let code = code_1.nil; + for (const prefix in values) { + const vs = values[prefix]; + if (!vs) continue; + const nameSet = usedValues[prefix] = usedValues[prefix] || /* @__PURE__ */ new Map(); + vs.forEach((name) => { + if (nameSet.has(name)) return; + nameSet.set(name, UsedValueState.Started); + let c = valueCode(name); + if (c) { + const def = this.opts.es5 ? exports.varKinds.var : exports.varKinds.const; + code = (0, code_1._)`${code}${def} ${name} = ${c};${this.opts._n}`; + } else if (c = getCode === null || getCode === void 0 ? void 0 : getCode(name)) code = (0, code_1._)`${code}${c}${this.opts._n}`; + else throw new ValueError(name); + nameSet.set(name, UsedValueState.Completed); + }); + } + return code; + } + }; + exports.ValueScope = ValueScope; +})); + +//#endregion +//#region ../../node_modules/.pnpm/ajv@8.18.0/node_modules/ajv/dist/compile/codegen/index.js +var require_codegen = /* @__PURE__ */ __commonJSMin(((exports) => { + Object.defineProperty(exports, "__esModule", { value: true }); + exports.or = exports.and = exports.not = exports.CodeGen = exports.operators = exports.varKinds = exports.ValueScopeName = exports.ValueScope = exports.Scope = exports.Name = exports.regexpCode = exports.stringify = exports.getProperty = exports.nil = exports.strConcat = exports.str = exports._ = void 0; + const code_1 = require_code$1(); + const scope_1 = require_scope(); + var code_2 = require_code$1(); + Object.defineProperty(exports, "_", { + enumerable: true, + get: function() { + return code_2._; + } + }); + Object.defineProperty(exports, "str", { + enumerable: true, + get: function() { + return code_2.str; + } + }); + Object.defineProperty(exports, "strConcat", { + enumerable: true, + get: function() { + return code_2.strConcat; + } + }); + Object.defineProperty(exports, "nil", { + enumerable: true, + get: function() { + return code_2.nil; + } + }); + Object.defineProperty(exports, "getProperty", { + enumerable: true, + get: function() { + return code_2.getProperty; + } + }); + Object.defineProperty(exports, "stringify", { + enumerable: true, + get: function() { + return code_2.stringify; + } + }); + Object.defineProperty(exports, "regexpCode", { + enumerable: true, + get: function() { + return code_2.regexpCode; + } + }); + Object.defineProperty(exports, "Name", { + enumerable: true, + get: function() { + return code_2.Name; + } + }); + var scope_2 = require_scope(); + Object.defineProperty(exports, "Scope", { + enumerable: true, + get: function() { + return scope_2.Scope; + } + }); + Object.defineProperty(exports, "ValueScope", { + enumerable: true, + get: function() { + return scope_2.ValueScope; + } + }); + Object.defineProperty(exports, "ValueScopeName", { + enumerable: true, + get: function() { + return scope_2.ValueScopeName; + } + }); + Object.defineProperty(exports, "varKinds", { + enumerable: true, + get: function() { + return scope_2.varKinds; + } + }); + exports.operators = { + GT: new code_1._Code(">"), + GTE: new code_1._Code(">="), + LT: new code_1._Code("<"), + LTE: new code_1._Code("<="), + EQ: new code_1._Code("==="), + NEQ: new code_1._Code("!=="), + NOT: new code_1._Code("!"), + OR: new code_1._Code("||"), + AND: new code_1._Code("&&"), + ADD: new code_1._Code("+") + }; + var Node = class { + optimizeNodes() { + return this; + } + optimizeNames(_names, _constants) { + return this; + } + }; + var Def = class extends Node { + constructor(varKind, name, rhs) { + super(); + this.varKind = varKind; + this.name = name; + this.rhs = rhs; + } + render({ es5, _n }) { + const varKind = es5 ? scope_1.varKinds.var : this.varKind; + const rhs = this.rhs === void 0 ? "" : ` = ${this.rhs}`; + return `${varKind} ${this.name}${rhs};` + _n; + } + optimizeNames(names, constants) { + if (!names[this.name.str]) return; + if (this.rhs) this.rhs = optimizeExpr(this.rhs, names, constants); + return this; + } + get names() { + return this.rhs instanceof code_1._CodeOrName ? this.rhs.names : {}; + } + }; + var Assign = class extends Node { + constructor(lhs, rhs, sideEffects) { + super(); + this.lhs = lhs; + this.rhs = rhs; + this.sideEffects = sideEffects; + } + render({ _n }) { + return `${this.lhs} = ${this.rhs};` + _n; + } + optimizeNames(names, constants) { + if (this.lhs instanceof code_1.Name && !names[this.lhs.str] && !this.sideEffects) return; + this.rhs = optimizeExpr(this.rhs, names, constants); + return this; + } + get names() { + return addExprNames(this.lhs instanceof code_1.Name ? {} : { ...this.lhs.names }, this.rhs); + } + }; + var AssignOp = class extends Assign { + constructor(lhs, op, rhs, sideEffects) { + super(lhs, rhs, sideEffects); + this.op = op; + } + render({ _n }) { + return `${this.lhs} ${this.op}= ${this.rhs};` + _n; + } + }; + var Label = class extends Node { + constructor(label) { + super(); + this.label = label; + this.names = {}; + } + render({ _n }) { + return `${this.label}:` + _n; + } + }; + var Break = class extends Node { + constructor(label) { + super(); + this.label = label; + this.names = {}; + } + render({ _n }) { + return `break${this.label ? ` ${this.label}` : ""};` + _n; + } + }; + var Throw = class extends Node { + constructor(error) { + super(); + this.error = error; + } + render({ _n }) { + return `throw ${this.error};` + _n; + } + get names() { + return this.error.names; + } + }; + var AnyCode = class extends Node { + constructor(code) { + super(); + this.code = code; + } + render({ _n }) { + return `${this.code};` + _n; + } + optimizeNodes() { + return `${this.code}` ? this : void 0; + } + optimizeNames(names, constants) { + this.code = optimizeExpr(this.code, names, constants); + return this; + } + get names() { + return this.code instanceof code_1._CodeOrName ? this.code.names : {}; + } + }; + var ParentNode = class extends Node { + constructor(nodes = []) { + super(); + this.nodes = nodes; + } + render(opts) { + return this.nodes.reduce((code, n) => code + n.render(opts), ""); + } + optimizeNodes() { + const { nodes } = this; + let i = nodes.length; + while (i--) { + const n = nodes[i].optimizeNodes(); + if (Array.isArray(n)) nodes.splice(i, 1, ...n); + else if (n) nodes[i] = n; + else nodes.splice(i, 1); + } + return nodes.length > 0 ? this : void 0; + } + optimizeNames(names, constants) { + const { nodes } = this; + let i = nodes.length; + while (i--) { + const n = nodes[i]; + if (n.optimizeNames(names, constants)) continue; + subtractNames(names, n.names); + nodes.splice(i, 1); + } + return nodes.length > 0 ? this : void 0; + } + get names() { + return this.nodes.reduce((names, n) => addNames(names, n.names), {}); + } + }; + var BlockNode = class extends ParentNode { + render(opts) { + return "{" + opts._n + super.render(opts) + "}" + opts._n; + } + }; + var Root = class extends ParentNode {}; + var Else = class extends BlockNode {}; + Else.kind = "else"; + var If = class If extends BlockNode { + constructor(condition, nodes) { + super(nodes); + this.condition = condition; + } + render(opts) { + let code = `if(${this.condition})` + super.render(opts); + if (this.else) code += "else " + this.else.render(opts); + return code; + } + optimizeNodes() { + super.optimizeNodes(); + const cond = this.condition; + if (cond === true) return this.nodes; + let e = this.else; + if (e) { + const ns = e.optimizeNodes(); + e = this.else = Array.isArray(ns) ? new Else(ns) : ns; + } + if (e) { + if (cond === false) return e instanceof If ? e : e.nodes; + if (this.nodes.length) return this; + return new If(not(cond), e instanceof If ? [e] : e.nodes); + } + if (cond === false || !this.nodes.length) return void 0; + return this; + } + optimizeNames(names, constants) { + var _a; + this.else = (_a = this.else) === null || _a === void 0 ? void 0 : _a.optimizeNames(names, constants); + if (!(super.optimizeNames(names, constants) || this.else)) return; + this.condition = optimizeExpr(this.condition, names, constants); + return this; + } + get names() { + const names = super.names; + addExprNames(names, this.condition); + if (this.else) addNames(names, this.else.names); + return names; + } + }; + If.kind = "if"; + var For = class extends BlockNode {}; + For.kind = "for"; + var ForLoop = class extends For { + constructor(iteration) { + super(); + this.iteration = iteration; + } + render(opts) { + return `for(${this.iteration})` + super.render(opts); + } + optimizeNames(names, constants) { + if (!super.optimizeNames(names, constants)) return; + this.iteration = optimizeExpr(this.iteration, names, constants); + return this; + } + get names() { + return addNames(super.names, this.iteration.names); + } + }; + var ForRange = class extends For { + constructor(varKind, name, from, to) { + super(); + this.varKind = varKind; + this.name = name; + this.from = from; + this.to = to; + } + render(opts) { + const varKind = opts.es5 ? scope_1.varKinds.var : this.varKind; + const { name, from, to } = this; + return `for(${varKind} ${name}=${from}; ${name}<${to}; ${name}++)` + super.render(opts); + } + get names() { + return addExprNames(addExprNames(super.names, this.from), this.to); + } + }; + var ForIter = class extends For { + constructor(loop, varKind, name, iterable) { + super(); + this.loop = loop; + this.varKind = varKind; + this.name = name; + this.iterable = iterable; + } + render(opts) { + return `for(${this.varKind} ${this.name} ${this.loop} ${this.iterable})` + super.render(opts); + } + optimizeNames(names, constants) { + if (!super.optimizeNames(names, constants)) return; + this.iterable = optimizeExpr(this.iterable, names, constants); + return this; + } + get names() { + return addNames(super.names, this.iterable.names); + } + }; + var Func = class extends BlockNode { + constructor(name, args, async) { + super(); + this.name = name; + this.args = args; + this.async = async; + } + render(opts) { + return `${this.async ? "async " : ""}function ${this.name}(${this.args})` + super.render(opts); + } + }; + Func.kind = "func"; + var Return = class extends ParentNode { + render(opts) { + return "return " + super.render(opts); + } + }; + Return.kind = "return"; + var Try = class extends BlockNode { + render(opts) { + let code = "try" + super.render(opts); + if (this.catch) code += this.catch.render(opts); + if (this.finally) code += this.finally.render(opts); + return code; + } + optimizeNodes() { + var _a, _b; + super.optimizeNodes(); + (_a = this.catch) === null || _a === void 0 || _a.optimizeNodes(); + (_b = this.finally) === null || _b === void 0 || _b.optimizeNodes(); + return this; + } + optimizeNames(names, constants) { + var _a, _b; + super.optimizeNames(names, constants); + (_a = this.catch) === null || _a === void 0 || _a.optimizeNames(names, constants); + (_b = this.finally) === null || _b === void 0 || _b.optimizeNames(names, constants); + return this; + } + get names() { + const names = super.names; + if (this.catch) addNames(names, this.catch.names); + if (this.finally) addNames(names, this.finally.names); + return names; + } + }; + var Catch = class extends BlockNode { + constructor(error) { + super(); + this.error = error; + } + render(opts) { + return `catch(${this.error})` + super.render(opts); + } + }; + Catch.kind = "catch"; + var Finally = class extends BlockNode { + render(opts) { + return "finally" + super.render(opts); + } + }; + Finally.kind = "finally"; + var CodeGen = class { + constructor(extScope, opts = {}) { + this._values = {}; + this._blockStarts = []; + this._constants = {}; + this.opts = { + ...opts, + _n: opts.lines ? "\n" : "" + }; + this._extScope = extScope; + this._scope = new scope_1.Scope({ parent: extScope }); + this._nodes = [new Root()]; + } + toString() { + return this._root.render(this.opts); + } + name(prefix) { + return this._scope.name(prefix); + } + scopeName(prefix) { + return this._extScope.name(prefix); + } + scopeValue(prefixOrName, value) { + const name = this._extScope.value(prefixOrName, value); + (this._values[name.prefix] || (this._values[name.prefix] = /* @__PURE__ */ new Set())).add(name); + return name; + } + getScopeValue(prefix, keyOrRef) { + return this._extScope.getValue(prefix, keyOrRef); + } + scopeRefs(scopeName) { + return this._extScope.scopeRefs(scopeName, this._values); + } + scopeCode() { + return this._extScope.scopeCode(this._values); + } + _def(varKind, nameOrPrefix, rhs, constant) { + const name = this._scope.toName(nameOrPrefix); + if (rhs !== void 0 && constant) this._constants[name.str] = rhs; + this._leafNode(new Def(varKind, name, rhs)); + return name; + } + const(nameOrPrefix, rhs, _constant) { + return this._def(scope_1.varKinds.const, nameOrPrefix, rhs, _constant); + } + let(nameOrPrefix, rhs, _constant) { + return this._def(scope_1.varKinds.let, nameOrPrefix, rhs, _constant); + } + var(nameOrPrefix, rhs, _constant) { + return this._def(scope_1.varKinds.var, nameOrPrefix, rhs, _constant); + } + assign(lhs, rhs, sideEffects) { + return this._leafNode(new Assign(lhs, rhs, sideEffects)); + } + add(lhs, rhs) { + return this._leafNode(new AssignOp(lhs, exports.operators.ADD, rhs)); + } + code(c) { + if (typeof c == "function") c(); + else if (c !== code_1.nil) this._leafNode(new AnyCode(c)); + return this; + } + object(...keyValues) { + const code = ["{"]; + for (const [key, value] of keyValues) { + if (code.length > 1) code.push(","); + code.push(key); + if (key !== value || this.opts.es5) { + code.push(":"); + (0, code_1.addCodeArg)(code, value); + } + } + code.push("}"); + return new code_1._Code(code); + } + if(condition, thenBody, elseBody) { + this._blockNode(new If(condition)); + if (thenBody && elseBody) this.code(thenBody).else().code(elseBody).endIf(); + else if (thenBody) this.code(thenBody).endIf(); + else if (elseBody) throw new Error("CodeGen: \"else\" body without \"then\" body"); + return this; + } + elseIf(condition) { + return this._elseNode(new If(condition)); + } + else() { + return this._elseNode(new Else()); + } + endIf() { + return this._endBlockNode(If, Else); + } + _for(node, forBody) { + this._blockNode(node); + if (forBody) this.code(forBody).endFor(); + return this; + } + for(iteration, forBody) { + return this._for(new ForLoop(iteration), forBody); + } + forRange(nameOrPrefix, from, to, forBody, varKind = this.opts.es5 ? scope_1.varKinds.var : scope_1.varKinds.let) { + const name = this._scope.toName(nameOrPrefix); + return this._for(new ForRange(varKind, name, from, to), () => forBody(name)); + } + forOf(nameOrPrefix, iterable, forBody, varKind = scope_1.varKinds.const) { + const name = this._scope.toName(nameOrPrefix); + if (this.opts.es5) { + const arr = iterable instanceof code_1.Name ? iterable : this.var("_arr", iterable); + return this.forRange("_i", 0, (0, code_1._)`${arr}.length`, (i) => { + this.var(name, (0, code_1._)`${arr}[${i}]`); + forBody(name); + }); + } + return this._for(new ForIter("of", varKind, name, iterable), () => forBody(name)); + } + forIn(nameOrPrefix, obj, forBody, varKind = this.opts.es5 ? scope_1.varKinds.var : scope_1.varKinds.const) { + if (this.opts.ownProperties) return this.forOf(nameOrPrefix, (0, code_1._)`Object.keys(${obj})`, forBody); + const name = this._scope.toName(nameOrPrefix); + return this._for(new ForIter("in", varKind, name, obj), () => forBody(name)); + } + endFor() { + return this._endBlockNode(For); + } + label(label) { + return this._leafNode(new Label(label)); + } + break(label) { + return this._leafNode(new Break(label)); + } + return(value) { + const node = new Return(); + this._blockNode(node); + this.code(value); + if (node.nodes.length !== 1) throw new Error("CodeGen: \"return\" should have one node"); + return this._endBlockNode(Return); + } + try(tryBody, catchCode, finallyCode) { + if (!catchCode && !finallyCode) throw new Error("CodeGen: \"try\" without \"catch\" and \"finally\""); + const node = new Try(); + this._blockNode(node); + this.code(tryBody); + if (catchCode) { + const error = this.name("e"); + this._currNode = node.catch = new Catch(error); + catchCode(error); + } + if (finallyCode) { + this._currNode = node.finally = new Finally(); + this.code(finallyCode); + } + return this._endBlockNode(Catch, Finally); + } + throw(error) { + return this._leafNode(new Throw(error)); + } + block(body, nodeCount) { + this._blockStarts.push(this._nodes.length); + if (body) this.code(body).endBlock(nodeCount); + return this; + } + endBlock(nodeCount) { + const len = this._blockStarts.pop(); + if (len === void 0) throw new Error("CodeGen: not in self-balancing block"); + const toClose = this._nodes.length - len; + if (toClose < 0 || nodeCount !== void 0 && toClose !== nodeCount) throw new Error(`CodeGen: wrong number of nodes: ${toClose} vs ${nodeCount} expected`); + this._nodes.length = len; + return this; + } + func(name, args = code_1.nil, async, funcBody) { + this._blockNode(new Func(name, args, async)); + if (funcBody) this.code(funcBody).endFunc(); + return this; + } + endFunc() { + return this._endBlockNode(Func); + } + optimize(n = 1) { + while (n-- > 0) { + this._root.optimizeNodes(); + this._root.optimizeNames(this._root.names, this._constants); + } + } + _leafNode(node) { + this._currNode.nodes.push(node); + return this; + } + _blockNode(node) { + this._currNode.nodes.push(node); + this._nodes.push(node); + } + _endBlockNode(N1, N2) { + const n = this._currNode; + if (n instanceof N1 || N2 && n instanceof N2) { + this._nodes.pop(); + return this; + } + throw new Error(`CodeGen: not in block "${N2 ? `${N1.kind}/${N2.kind}` : N1.kind}"`); + } + _elseNode(node) { + const n = this._currNode; + if (!(n instanceof If)) throw new Error("CodeGen: \"else\" without \"if\""); + this._currNode = n.else = node; + return this; + } + get _root() { + return this._nodes[0]; + } + get _currNode() { + const ns = this._nodes; + return ns[ns.length - 1]; + } + set _currNode(node) { + const ns = this._nodes; + ns[ns.length - 1] = node; + } + }; + exports.CodeGen = CodeGen; + function addNames(names, from) { + for (const n in from) names[n] = (names[n] || 0) + (from[n] || 0); + return names; + } + function addExprNames(names, from) { + return from instanceof code_1._CodeOrName ? addNames(names, from.names) : names; + } + function optimizeExpr(expr, names, constants) { + if (expr instanceof code_1.Name) return replaceName(expr); + if (!canOptimize(expr)) return expr; + return new code_1._Code(expr._items.reduce((items, c) => { + if (c instanceof code_1.Name) c = replaceName(c); + if (c instanceof code_1._Code) items.push(...c._items); + else items.push(c); + return items; + }, [])); + function replaceName(n) { + const c = constants[n.str]; + if (c === void 0 || names[n.str] !== 1) return n; + delete names[n.str]; + return c; + } + function canOptimize(e) { + return e instanceof code_1._Code && e._items.some((c) => c instanceof code_1.Name && names[c.str] === 1 && constants[c.str] !== void 0); + } + } + function subtractNames(names, from) { + for (const n in from) names[n] = (names[n] || 0) - (from[n] || 0); + } + function not(x) { + return typeof x == "boolean" || typeof x == "number" || x === null ? !x : (0, code_1._)`!${par(x)}`; + } + exports.not = not; + const andCode = mappend(exports.operators.AND); + function and(...args) { + return args.reduce(andCode); + } + exports.and = and; + const orCode = mappend(exports.operators.OR); + function or(...args) { + return args.reduce(orCode); + } + exports.or = or; + function mappend(op) { + return (x, y) => x === code_1.nil ? y : y === code_1.nil ? x : (0, code_1._)`${par(x)} ${op} ${par(y)}`; + } + function par(x) { + return x instanceof code_1.Name ? x : (0, code_1._)`(${x})`; + } +})); + +//#endregion +//#region ../../node_modules/.pnpm/ajv@8.18.0/node_modules/ajv/dist/compile/util.js +var require_util = /* @__PURE__ */ __commonJSMin(((exports) => { + Object.defineProperty(exports, "__esModule", { value: true }); + exports.checkStrictMode = exports.getErrorPath = exports.Type = exports.useFunc = exports.setEvaluated = exports.evaluatedPropsToName = exports.mergeEvaluated = exports.eachItem = exports.unescapeJsonPointer = exports.escapeJsonPointer = exports.escapeFragment = exports.unescapeFragment = exports.schemaRefOrVal = exports.schemaHasRulesButRef = exports.schemaHasRules = exports.checkUnknownRules = exports.alwaysValidSchema = exports.toHash = void 0; + const codegen_1 = require_codegen(); + const code_1 = require_code$1(); + function toHash(arr) { + const hash = {}; + for (const item of arr) hash[item] = true; + return hash; + } + exports.toHash = toHash; + function alwaysValidSchema(it, schema) { + if (typeof schema == "boolean") return schema; + if (Object.keys(schema).length === 0) return true; + checkUnknownRules(it, schema); + return !schemaHasRules(schema, it.self.RULES.all); + } + exports.alwaysValidSchema = alwaysValidSchema; + function checkUnknownRules(it, schema = it.schema) { + const { opts, self } = it; + if (!opts.strictSchema) return; + if (typeof schema === "boolean") return; + const rules = self.RULES.keywords; + for (const key in schema) if (!rules[key]) checkStrictMode(it, `unknown keyword: "${key}"`); + } + exports.checkUnknownRules = checkUnknownRules; + function schemaHasRules(schema, rules) { + if (typeof schema == "boolean") return !schema; + for (const key in schema) if (rules[key]) return true; + return false; + } + exports.schemaHasRules = schemaHasRules; + function schemaHasRulesButRef(schema, RULES) { + if (typeof schema == "boolean") return !schema; + for (const key in schema) if (key !== "$ref" && RULES.all[key]) return true; + return false; + } + exports.schemaHasRulesButRef = schemaHasRulesButRef; + function schemaRefOrVal({ topSchemaRef, schemaPath }, schema, keyword, $data) { + if (!$data) { + if (typeof schema == "number" || typeof schema == "boolean") return schema; + if (typeof schema == "string") return (0, codegen_1._)`${schema}`; + } + return (0, codegen_1._)`${topSchemaRef}${schemaPath}${(0, codegen_1.getProperty)(keyword)}`; + } + exports.schemaRefOrVal = schemaRefOrVal; + function unescapeFragment(str) { + return unescapeJsonPointer(decodeURIComponent(str)); + } + exports.unescapeFragment = unescapeFragment; + function escapeFragment(str) { + return encodeURIComponent(escapeJsonPointer(str)); + } + exports.escapeFragment = escapeFragment; + function escapeJsonPointer(str) { + if (typeof str == "number") return `${str}`; + return str.replace(/~/g, "~0").replace(/\//g, "~1"); + } + exports.escapeJsonPointer = escapeJsonPointer; + function unescapeJsonPointer(str) { + return str.replace(/~1/g, "/").replace(/~0/g, "~"); + } + exports.unescapeJsonPointer = unescapeJsonPointer; + function eachItem(xs, f) { + if (Array.isArray(xs)) for (const x of xs) f(x); + else f(xs); + } + exports.eachItem = eachItem; + function makeMergeEvaluated({ mergeNames, mergeToName, mergeValues, resultToName }) { + return (gen, from, to, toName) => { + const res = to === void 0 ? from : to instanceof codegen_1.Name ? (from instanceof codegen_1.Name ? mergeNames(gen, from, to) : mergeToName(gen, from, to), to) : from instanceof codegen_1.Name ? (mergeToName(gen, to, from), from) : mergeValues(from, to); + return toName === codegen_1.Name && !(res instanceof codegen_1.Name) ? resultToName(gen, res) : res; + }; + } + exports.mergeEvaluated = { + props: makeMergeEvaluated({ + mergeNames: (gen, from, to) => gen.if((0, codegen_1._)`${to} !== true && ${from} !== undefined`, () => { + gen.if((0, codegen_1._)`${from} === true`, () => gen.assign(to, true), () => gen.assign(to, (0, codegen_1._)`${to} || {}`).code((0, codegen_1._)`Object.assign(${to}, ${from})`)); + }), + mergeToName: (gen, from, to) => gen.if((0, codegen_1._)`${to} !== true`, () => { + if (from === true) gen.assign(to, true); + else { + gen.assign(to, (0, codegen_1._)`${to} || {}`); + setEvaluated(gen, to, from); + } + }), + mergeValues: (from, to) => from === true ? true : { + ...from, + ...to + }, + resultToName: evaluatedPropsToName + }), + items: makeMergeEvaluated({ + mergeNames: (gen, from, to) => gen.if((0, codegen_1._)`${to} !== true && ${from} !== undefined`, () => gen.assign(to, (0, codegen_1._)`${from} === true ? true : ${to} > ${from} ? ${to} : ${from}`)), + mergeToName: (gen, from, to) => gen.if((0, codegen_1._)`${to} !== true`, () => gen.assign(to, from === true ? true : (0, codegen_1._)`${to} > ${from} ? ${to} : ${from}`)), + mergeValues: (from, to) => from === true ? true : Math.max(from, to), + resultToName: (gen, items) => gen.var("items", items) + }) + }; + function evaluatedPropsToName(gen, ps) { + if (ps === true) return gen.var("props", true); + const props = gen.var("props", (0, codegen_1._)`{}`); + if (ps !== void 0) setEvaluated(gen, props, ps); + return props; + } + exports.evaluatedPropsToName = evaluatedPropsToName; + function setEvaluated(gen, props, ps) { + Object.keys(ps).forEach((p) => gen.assign((0, codegen_1._)`${props}${(0, codegen_1.getProperty)(p)}`, true)); + } + exports.setEvaluated = setEvaluated; + const snippets = {}; + function useFunc(gen, f) { + return gen.scopeValue("func", { + ref: f, + code: snippets[f.code] || (snippets[f.code] = new code_1._Code(f.code)) + }); + } + exports.useFunc = useFunc; + var Type; + (function(Type) { + Type[Type["Num"] = 0] = "Num"; + Type[Type["Str"] = 1] = "Str"; + })(Type || (exports.Type = Type = {})); + function getErrorPath(dataProp, dataPropType, jsPropertySyntax) { + if (dataProp instanceof codegen_1.Name) { + const isNumber = dataPropType === Type.Num; + return jsPropertySyntax ? isNumber ? (0, codegen_1._)`"[" + ${dataProp} + "]"` : (0, codegen_1._)`"['" + ${dataProp} + "']"` : isNumber ? (0, codegen_1._)`"/" + ${dataProp}` : (0, codegen_1._)`"/" + ${dataProp}.replace(/~/g, "~0").replace(/\\//g, "~1")`; + } + return jsPropertySyntax ? (0, codegen_1.getProperty)(dataProp).toString() : "/" + escapeJsonPointer(dataProp); + } + exports.getErrorPath = getErrorPath; + function checkStrictMode(it, msg, mode = it.opts.strictSchema) { + if (!mode) return; + msg = `strict mode: ${msg}`; + if (mode === true) throw new Error(msg); + it.self.logger.warn(msg); + } + exports.checkStrictMode = checkStrictMode; +})); + +//#endregion +//#region ../../node_modules/.pnpm/ajv@8.18.0/node_modules/ajv/dist/compile/names.js +var require_names = /* @__PURE__ */ __commonJSMin(((exports) => { + Object.defineProperty(exports, "__esModule", { value: true }); + const codegen_1 = require_codegen(); + const names = { + data: new codegen_1.Name("data"), + valCxt: new codegen_1.Name("valCxt"), + instancePath: new codegen_1.Name("instancePath"), + parentData: new codegen_1.Name("parentData"), + parentDataProperty: new codegen_1.Name("parentDataProperty"), + rootData: new codegen_1.Name("rootData"), + dynamicAnchors: new codegen_1.Name("dynamicAnchors"), + vErrors: new codegen_1.Name("vErrors"), + errors: new codegen_1.Name("errors"), + this: new codegen_1.Name("this"), + self: new codegen_1.Name("self"), + scope: new codegen_1.Name("scope"), + json: new codegen_1.Name("json"), + jsonPos: new codegen_1.Name("jsonPos"), + jsonLen: new codegen_1.Name("jsonLen"), + jsonPart: new codegen_1.Name("jsonPart") + }; + exports.default = names; +})); + +//#endregion +//#region ../../node_modules/.pnpm/ajv@8.18.0/node_modules/ajv/dist/compile/errors.js +var require_errors = /* @__PURE__ */ __commonJSMin(((exports) => { + Object.defineProperty(exports, "__esModule", { value: true }); + exports.extendErrors = exports.resetErrorsCount = exports.reportExtraError = exports.reportError = exports.keyword$DataError = exports.keywordError = void 0; + const codegen_1 = require_codegen(); + const util_1 = require_util(); + const names_1 = require_names(); + exports.keywordError = { message: ({ keyword }) => (0, codegen_1.str)`must pass "${keyword}" keyword validation` }; + exports.keyword$DataError = { message: ({ keyword, schemaType }) => schemaType ? (0, codegen_1.str)`"${keyword}" keyword must be ${schemaType} ($data)` : (0, codegen_1.str)`"${keyword}" keyword is invalid ($data)` }; + function reportError(cxt, error = exports.keywordError, errorPaths, overrideAllErrors) { + const { it } = cxt; + const { gen, compositeRule, allErrors } = it; + const errObj = errorObjectCode(cxt, error, errorPaths); + if (overrideAllErrors !== null && overrideAllErrors !== void 0 ? overrideAllErrors : compositeRule || allErrors) addError(gen, errObj); + else returnErrors(it, (0, codegen_1._)`[${errObj}]`); + } + exports.reportError = reportError; + function reportExtraError(cxt, error = exports.keywordError, errorPaths) { + const { it } = cxt; + const { gen, compositeRule, allErrors } = it; + addError(gen, errorObjectCode(cxt, error, errorPaths)); + if (!(compositeRule || allErrors)) returnErrors(it, names_1.default.vErrors); + } + exports.reportExtraError = reportExtraError; + function resetErrorsCount(gen, errsCount) { + gen.assign(names_1.default.errors, errsCount); + gen.if((0, codegen_1._)`${names_1.default.vErrors} !== null`, () => gen.if(errsCount, () => gen.assign((0, codegen_1._)`${names_1.default.vErrors}.length`, errsCount), () => gen.assign(names_1.default.vErrors, null))); + } + exports.resetErrorsCount = resetErrorsCount; + function extendErrors({ gen, keyword, schemaValue, data, errsCount, it }) { + /* istanbul ignore if */ + if (errsCount === void 0) throw new Error("ajv implementation error"); + const err = gen.name("err"); + gen.forRange("i", errsCount, names_1.default.errors, (i) => { + gen.const(err, (0, codegen_1._)`${names_1.default.vErrors}[${i}]`); + gen.if((0, codegen_1._)`${err}.instancePath === undefined`, () => gen.assign((0, codegen_1._)`${err}.instancePath`, (0, codegen_1.strConcat)(names_1.default.instancePath, it.errorPath))); + gen.assign((0, codegen_1._)`${err}.schemaPath`, (0, codegen_1.str)`${it.errSchemaPath}/${keyword}`); + if (it.opts.verbose) { + gen.assign((0, codegen_1._)`${err}.schema`, schemaValue); + gen.assign((0, codegen_1._)`${err}.data`, data); + } + }); + } + exports.extendErrors = extendErrors; + function addError(gen, errObj) { + const err = gen.const("err", errObj); + gen.if((0, codegen_1._)`${names_1.default.vErrors} === null`, () => gen.assign(names_1.default.vErrors, (0, codegen_1._)`[${err}]`), (0, codegen_1._)`${names_1.default.vErrors}.push(${err})`); + gen.code((0, codegen_1._)`${names_1.default.errors}++`); + } + function returnErrors(it, errs) { + const { gen, validateName, schemaEnv } = it; + if (schemaEnv.$async) gen.throw((0, codegen_1._)`new ${it.ValidationError}(${errs})`); + else { + gen.assign((0, codegen_1._)`${validateName}.errors`, errs); + gen.return(false); + } + } + const E = { + keyword: new codegen_1.Name("keyword"), + schemaPath: new codegen_1.Name("schemaPath"), + params: new codegen_1.Name("params"), + propertyName: new codegen_1.Name("propertyName"), + message: new codegen_1.Name("message"), + schema: new codegen_1.Name("schema"), + parentSchema: new codegen_1.Name("parentSchema") + }; + function errorObjectCode(cxt, error, errorPaths) { + const { createErrors } = cxt.it; + if (createErrors === false) return (0, codegen_1._)`{}`; + return errorObject(cxt, error, errorPaths); + } + function errorObject(cxt, error, errorPaths = {}) { + const { gen, it } = cxt; + const keyValues = [errorInstancePath(it, errorPaths), errorSchemaPath(cxt, errorPaths)]; + extraErrorProps(cxt, error, keyValues); + return gen.object(...keyValues); + } + function errorInstancePath({ errorPath }, { instancePath }) { + const instPath = instancePath ? (0, codegen_1.str)`${errorPath}${(0, util_1.getErrorPath)(instancePath, util_1.Type.Str)}` : errorPath; + return [names_1.default.instancePath, (0, codegen_1.strConcat)(names_1.default.instancePath, instPath)]; + } + function errorSchemaPath({ keyword, it: { errSchemaPath } }, { schemaPath, parentSchema }) { + let schPath = parentSchema ? errSchemaPath : (0, codegen_1.str)`${errSchemaPath}/${keyword}`; + if (schemaPath) schPath = (0, codegen_1.str)`${schPath}${(0, util_1.getErrorPath)(schemaPath, util_1.Type.Str)}`; + return [E.schemaPath, schPath]; + } + function extraErrorProps(cxt, { params, message }, keyValues) { + const { keyword, data, schemaValue, it } = cxt; + const { opts, propertyName, topSchemaRef, schemaPath } = it; + keyValues.push([E.keyword, keyword], [E.params, typeof params == "function" ? params(cxt) : params || (0, codegen_1._)`{}`]); + if (opts.messages) keyValues.push([E.message, typeof message == "function" ? message(cxt) : message]); + if (opts.verbose) keyValues.push([E.schema, schemaValue], [E.parentSchema, (0, codegen_1._)`${topSchemaRef}${schemaPath}`], [names_1.default.data, data]); + if (propertyName) keyValues.push([E.propertyName, propertyName]); + } +})); + +//#endregion +//#region ../../node_modules/.pnpm/ajv@8.18.0/node_modules/ajv/dist/compile/validate/boolSchema.js +var require_boolSchema = /* @__PURE__ */ __commonJSMin(((exports) => { + Object.defineProperty(exports, "__esModule", { value: true }); + exports.boolOrEmptySchema = exports.topBoolOrEmptySchema = void 0; + const errors_1 = require_errors(); + const codegen_1 = require_codegen(); + const names_1 = require_names(); + const boolError = { message: "boolean schema is false" }; + function topBoolOrEmptySchema(it) { + const { gen, schema, validateName } = it; + if (schema === false) falseSchemaError(it, false); + else if (typeof schema == "object" && schema.$async === true) gen.return(names_1.default.data); + else { + gen.assign((0, codegen_1._)`${validateName}.errors`, null); + gen.return(true); + } + } + exports.topBoolOrEmptySchema = topBoolOrEmptySchema; + function boolOrEmptySchema(it, valid) { + const { gen, schema } = it; + if (schema === false) { + gen.var(valid, false); + falseSchemaError(it); + } else gen.var(valid, true); + } + exports.boolOrEmptySchema = boolOrEmptySchema; + function falseSchemaError(it, overrideAllErrors) { + const { gen, data } = it; + const cxt = { + gen, + keyword: "false schema", + data, + schema: false, + schemaCode: false, + schemaValue: false, + params: {}, + it + }; + (0, errors_1.reportError)(cxt, boolError, void 0, overrideAllErrors); + } +})); + +//#endregion +//#region ../../node_modules/.pnpm/ajv@8.18.0/node_modules/ajv/dist/compile/rules.js +var require_rules = /* @__PURE__ */ __commonJSMin(((exports) => { + Object.defineProperty(exports, "__esModule", { value: true }); + exports.getRules = exports.isJSONType = void 0; + const jsonTypes = new Set([ + "string", + "number", + "integer", + "boolean", + "null", + "object", + "array" + ]); + function isJSONType(x) { + return typeof x == "string" && jsonTypes.has(x); + } + exports.isJSONType = isJSONType; + function getRules() { + const groups = { + number: { + type: "number", + rules: [] + }, + string: { + type: "string", + rules: [] + }, + array: { + type: "array", + rules: [] + }, + object: { + type: "object", + rules: [] + } + }; + return { + types: { + ...groups, + integer: true, + boolean: true, + null: true + }, + rules: [ + { rules: [] }, + groups.number, + groups.string, + groups.array, + groups.object + ], + post: { rules: [] }, + all: {}, + keywords: {} + }; + } + exports.getRules = getRules; +})); + +//#endregion +//#region ../../node_modules/.pnpm/ajv@8.18.0/node_modules/ajv/dist/compile/validate/applicability.js +var require_applicability = /* @__PURE__ */ __commonJSMin(((exports) => { + Object.defineProperty(exports, "__esModule", { value: true }); + exports.shouldUseRule = exports.shouldUseGroup = exports.schemaHasRulesForType = void 0; + function schemaHasRulesForType({ schema, self }, type) { + const group = self.RULES.types[type]; + return group && group !== true && shouldUseGroup(schema, group); + } + exports.schemaHasRulesForType = schemaHasRulesForType; + function shouldUseGroup(schema, group) { + return group.rules.some((rule) => shouldUseRule(schema, rule)); + } + exports.shouldUseGroup = shouldUseGroup; + function shouldUseRule(schema, rule) { + var _a; + return schema[rule.keyword] !== void 0 || ((_a = rule.definition.implements) === null || _a === void 0 ? void 0 : _a.some((kwd) => schema[kwd] !== void 0)); + } + exports.shouldUseRule = shouldUseRule; +})); + +//#endregion +//#region ../../node_modules/.pnpm/ajv@8.18.0/node_modules/ajv/dist/compile/validate/dataType.js +var require_dataType = /* @__PURE__ */ __commonJSMin(((exports) => { + Object.defineProperty(exports, "__esModule", { value: true }); + exports.reportTypeError = exports.checkDataTypes = exports.checkDataType = exports.coerceAndCheckDataType = exports.getJSONTypes = exports.getSchemaTypes = exports.DataType = void 0; + const rules_1 = require_rules(); + const applicability_1 = require_applicability(); + const errors_1 = require_errors(); + const codegen_1 = require_codegen(); + const util_1 = require_util(); + var DataType; + (function(DataType) { + DataType[DataType["Correct"] = 0] = "Correct"; + DataType[DataType["Wrong"] = 1] = "Wrong"; + })(DataType || (exports.DataType = DataType = {})); + function getSchemaTypes(schema) { + const types = getJSONTypes(schema.type); + if (types.includes("null")) { + if (schema.nullable === false) throw new Error("type: null contradicts nullable: false"); + } else { + if (!types.length && schema.nullable !== void 0) throw new Error("\"nullable\" cannot be used without \"type\""); + if (schema.nullable === true) types.push("null"); + } + return types; + } + exports.getSchemaTypes = getSchemaTypes; + function getJSONTypes(ts) { + const types = Array.isArray(ts) ? ts : ts ? [ts] : []; + if (types.every(rules_1.isJSONType)) return types; + throw new Error("type must be JSONType or JSONType[]: " + types.join(",")); + } + exports.getJSONTypes = getJSONTypes; + function coerceAndCheckDataType(it, types) { + const { gen, data, opts } = it; + const coerceTo = coerceToTypes(types, opts.coerceTypes); + const checkTypes = types.length > 0 && !(coerceTo.length === 0 && types.length === 1 && (0, applicability_1.schemaHasRulesForType)(it, types[0])); + if (checkTypes) { + const wrongType = checkDataTypes(types, data, opts.strictNumbers, DataType.Wrong); + gen.if(wrongType, () => { + if (coerceTo.length) coerceData(it, types, coerceTo); + else reportTypeError(it); + }); + } + return checkTypes; + } + exports.coerceAndCheckDataType = coerceAndCheckDataType; + const COERCIBLE = new Set([ + "string", + "number", + "integer", + "boolean", + "null" + ]); + function coerceToTypes(types, coerceTypes) { + return coerceTypes ? types.filter((t) => COERCIBLE.has(t) || coerceTypes === "array" && t === "array") : []; + } + function coerceData(it, types, coerceTo) { + const { gen, data, opts } = it; + const dataType = gen.let("dataType", (0, codegen_1._)`typeof ${data}`); + const coerced = gen.let("coerced", (0, codegen_1._)`undefined`); + if (opts.coerceTypes === "array") gen.if((0, codegen_1._)`${dataType} == 'object' && Array.isArray(${data}) && ${data}.length == 1`, () => gen.assign(data, (0, codegen_1._)`${data}[0]`).assign(dataType, (0, codegen_1._)`typeof ${data}`).if(checkDataTypes(types, data, opts.strictNumbers), () => gen.assign(coerced, data))); + gen.if((0, codegen_1._)`${coerced} !== undefined`); + for (const t of coerceTo) if (COERCIBLE.has(t) || t === "array" && opts.coerceTypes === "array") coerceSpecificType(t); + gen.else(); + reportTypeError(it); + gen.endIf(); + gen.if((0, codegen_1._)`${coerced} !== undefined`, () => { + gen.assign(data, coerced); + assignParentData(it, coerced); + }); + function coerceSpecificType(t) { + switch (t) { + case "string": + gen.elseIf((0, codegen_1._)`${dataType} == "number" || ${dataType} == "boolean"`).assign(coerced, (0, codegen_1._)`"" + ${data}`).elseIf((0, codegen_1._)`${data} === null`).assign(coerced, (0, codegen_1._)`""`); + return; + case "number": + gen.elseIf((0, codegen_1._)`${dataType} == "boolean" || ${data} === null + || (${dataType} == "string" && ${data} && ${data} == +${data})`).assign(coerced, (0, codegen_1._)`+${data}`); + return; + case "integer": + gen.elseIf((0, codegen_1._)`${dataType} === "boolean" || ${data} === null + || (${dataType} === "string" && ${data} && ${data} == +${data} && !(${data} % 1))`).assign(coerced, (0, codegen_1._)`+${data}`); + return; + case "boolean": + gen.elseIf((0, codegen_1._)`${data} === "false" || ${data} === 0 || ${data} === null`).assign(coerced, false).elseIf((0, codegen_1._)`${data} === "true" || ${data} === 1`).assign(coerced, true); + return; + case "null": + gen.elseIf((0, codegen_1._)`${data} === "" || ${data} === 0 || ${data} === false`); + gen.assign(coerced, null); + return; + case "array": gen.elseIf((0, codegen_1._)`${dataType} === "string" || ${dataType} === "number" + || ${dataType} === "boolean" || ${data} === null`).assign(coerced, (0, codegen_1._)`[${data}]`); + } + } + } + function assignParentData({ gen, parentData, parentDataProperty }, expr) { + gen.if((0, codegen_1._)`${parentData} !== undefined`, () => gen.assign((0, codegen_1._)`${parentData}[${parentDataProperty}]`, expr)); + } + function checkDataType(dataType, data, strictNums, correct = DataType.Correct) { + const EQ = correct === DataType.Correct ? codegen_1.operators.EQ : codegen_1.operators.NEQ; + let cond; + switch (dataType) { + case "null": return (0, codegen_1._)`${data} ${EQ} null`; + case "array": + cond = (0, codegen_1._)`Array.isArray(${data})`; + break; + case "object": + cond = (0, codegen_1._)`${data} && typeof ${data} == "object" && !Array.isArray(${data})`; + break; + case "integer": + cond = numCond((0, codegen_1._)`!(${data} % 1) && !isNaN(${data})`); + break; + case "number": + cond = numCond(); + break; + default: return (0, codegen_1._)`typeof ${data} ${EQ} ${dataType}`; + } + return correct === DataType.Correct ? cond : (0, codegen_1.not)(cond); + function numCond(_cond = codegen_1.nil) { + return (0, codegen_1.and)((0, codegen_1._)`typeof ${data} == "number"`, _cond, strictNums ? (0, codegen_1._)`isFinite(${data})` : codegen_1.nil); + } + } + exports.checkDataType = checkDataType; + function checkDataTypes(dataTypes, data, strictNums, correct) { + if (dataTypes.length === 1) return checkDataType(dataTypes[0], data, strictNums, correct); + let cond; + const types = (0, util_1.toHash)(dataTypes); + if (types.array && types.object) { + const notObj = (0, codegen_1._)`typeof ${data} != "object"`; + cond = types.null ? notObj : (0, codegen_1._)`!${data} || ${notObj}`; + delete types.null; + delete types.array; + delete types.object; + } else cond = codegen_1.nil; + if (types.number) delete types.integer; + for (const t in types) cond = (0, codegen_1.and)(cond, checkDataType(t, data, strictNums, correct)); + return cond; + } + exports.checkDataTypes = checkDataTypes; + const typeError = { + message: ({ schema }) => `must be ${schema}`, + params: ({ schema, schemaValue }) => typeof schema == "string" ? (0, codegen_1._)`{type: ${schema}}` : (0, codegen_1._)`{type: ${schemaValue}}` + }; + function reportTypeError(it) { + const cxt = getTypeErrorContext(it); + (0, errors_1.reportError)(cxt, typeError); + } + exports.reportTypeError = reportTypeError; + function getTypeErrorContext(it) { + const { gen, data, schema } = it; + const schemaCode = (0, util_1.schemaRefOrVal)(it, schema, "type"); + return { + gen, + keyword: "type", + data, + schema: schema.type, + schemaCode, + schemaValue: schemaCode, + parentSchema: schema, + params: {}, + it + }; + } +})); + +//#endregion +//#region ../../node_modules/.pnpm/ajv@8.18.0/node_modules/ajv/dist/compile/validate/defaults.js +var require_defaults = /* @__PURE__ */ __commonJSMin(((exports) => { + Object.defineProperty(exports, "__esModule", { value: true }); + exports.assignDefaults = void 0; + const codegen_1 = require_codegen(); + const util_1 = require_util(); + function assignDefaults(it, ty) { + const { properties, items } = it.schema; + if (ty === "object" && properties) for (const key in properties) assignDefault(it, key, properties[key].default); + else if (ty === "array" && Array.isArray(items)) items.forEach((sch, i) => assignDefault(it, i, sch.default)); + } + exports.assignDefaults = assignDefaults; + function assignDefault(it, prop, defaultValue) { + const { gen, compositeRule, data, opts } = it; + if (defaultValue === void 0) return; + const childData = (0, codegen_1._)`${data}${(0, codegen_1.getProperty)(prop)}`; + if (compositeRule) { + (0, util_1.checkStrictMode)(it, `default is ignored for: ${childData}`); + return; + } + let condition = (0, codegen_1._)`${childData} === undefined`; + if (opts.useDefaults === "empty") condition = (0, codegen_1._)`${condition} || ${childData} === null || ${childData} === ""`; + gen.if(condition, (0, codegen_1._)`${childData} = ${(0, codegen_1.stringify)(defaultValue)}`); + } +})); + +//#endregion +//#region ../../node_modules/.pnpm/ajv@8.18.0/node_modules/ajv/dist/vocabularies/code.js +var require_code = /* @__PURE__ */ __commonJSMin(((exports) => { + Object.defineProperty(exports, "__esModule", { value: true }); + exports.validateUnion = exports.validateArray = exports.usePattern = exports.callValidateCode = exports.schemaProperties = exports.allSchemaProperties = exports.noPropertyInData = exports.propertyInData = exports.isOwnProperty = exports.hasPropFunc = exports.reportMissingProp = exports.checkMissingProp = exports.checkReportMissingProp = void 0; + const codegen_1 = require_codegen(); + const util_1 = require_util(); + const names_1 = require_names(); + const util_2 = require_util(); + function checkReportMissingProp(cxt, prop) { + const { gen, data, it } = cxt; + gen.if(noPropertyInData(gen, data, prop, it.opts.ownProperties), () => { + cxt.setParams({ missingProperty: (0, codegen_1._)`${prop}` }, true); + cxt.error(); + }); + } + exports.checkReportMissingProp = checkReportMissingProp; + function checkMissingProp({ gen, data, it: { opts } }, properties, missing) { + return (0, codegen_1.or)(...properties.map((prop) => (0, codegen_1.and)(noPropertyInData(gen, data, prop, opts.ownProperties), (0, codegen_1._)`${missing} = ${prop}`))); + } + exports.checkMissingProp = checkMissingProp; + function reportMissingProp(cxt, missing) { + cxt.setParams({ missingProperty: missing }, true); + cxt.error(); + } + exports.reportMissingProp = reportMissingProp; + function hasPropFunc(gen) { + return gen.scopeValue("func", { + ref: Object.prototype.hasOwnProperty, + code: (0, codegen_1._)`Object.prototype.hasOwnProperty` + }); + } + exports.hasPropFunc = hasPropFunc; + function isOwnProperty(gen, data, property) { + return (0, codegen_1._)`${hasPropFunc(gen)}.call(${data}, ${property})`; + } + exports.isOwnProperty = isOwnProperty; + function propertyInData(gen, data, property, ownProperties) { + const cond = (0, codegen_1._)`${data}${(0, codegen_1.getProperty)(property)} !== undefined`; + return ownProperties ? (0, codegen_1._)`${cond} && ${isOwnProperty(gen, data, property)}` : cond; + } + exports.propertyInData = propertyInData; + function noPropertyInData(gen, data, property, ownProperties) { + const cond = (0, codegen_1._)`${data}${(0, codegen_1.getProperty)(property)} === undefined`; + return ownProperties ? (0, codegen_1.or)(cond, (0, codegen_1.not)(isOwnProperty(gen, data, property))) : cond; + } + exports.noPropertyInData = noPropertyInData; + function allSchemaProperties(schemaMap) { + return schemaMap ? Object.keys(schemaMap).filter((p) => p !== "__proto__") : []; + } + exports.allSchemaProperties = allSchemaProperties; + function schemaProperties(it, schemaMap) { + return allSchemaProperties(schemaMap).filter((p) => !(0, util_1.alwaysValidSchema)(it, schemaMap[p])); + } + exports.schemaProperties = schemaProperties; + function callValidateCode({ schemaCode, data, it: { gen, topSchemaRef, schemaPath, errorPath }, it }, func, context, passSchema) { + const dataAndSchema = passSchema ? (0, codegen_1._)`${schemaCode}, ${data}, ${topSchemaRef}${schemaPath}` : data; + const valCxt = [ + [names_1.default.instancePath, (0, codegen_1.strConcat)(names_1.default.instancePath, errorPath)], + [names_1.default.parentData, it.parentData], + [names_1.default.parentDataProperty, it.parentDataProperty], + [names_1.default.rootData, names_1.default.rootData] + ]; + if (it.opts.dynamicRef) valCxt.push([names_1.default.dynamicAnchors, names_1.default.dynamicAnchors]); + const args = (0, codegen_1._)`${dataAndSchema}, ${gen.object(...valCxt)}`; + return context !== codegen_1.nil ? (0, codegen_1._)`${func}.call(${context}, ${args})` : (0, codegen_1._)`${func}(${args})`; + } + exports.callValidateCode = callValidateCode; + const newRegExp = (0, codegen_1._)`new RegExp`; + function usePattern({ gen, it: { opts } }, pattern) { + const u = opts.unicodeRegExp ? "u" : ""; + const { regExp } = opts.code; + const rx = regExp(pattern, u); + return gen.scopeValue("pattern", { + key: rx.toString(), + ref: rx, + code: (0, codegen_1._)`${regExp.code === "new RegExp" ? newRegExp : (0, util_2.useFunc)(gen, regExp)}(${pattern}, ${u})` + }); + } + exports.usePattern = usePattern; + function validateArray(cxt) { + const { gen, data, keyword, it } = cxt; + const valid = gen.name("valid"); + if (it.allErrors) { + const validArr = gen.let("valid", true); + validateItems(() => gen.assign(validArr, false)); + return validArr; + } + gen.var(valid, true); + validateItems(() => gen.break()); + return valid; + function validateItems(notValid) { + const len = gen.const("len", (0, codegen_1._)`${data}.length`); + gen.forRange("i", 0, len, (i) => { + cxt.subschema({ + keyword, + dataProp: i, + dataPropType: util_1.Type.Num + }, valid); + gen.if((0, codegen_1.not)(valid), notValid); + }); + } + } + exports.validateArray = validateArray; + function validateUnion(cxt) { + const { gen, schema, keyword, it } = cxt; + /* istanbul ignore if */ + if (!Array.isArray(schema)) throw new Error("ajv implementation error"); + if (schema.some((sch) => (0, util_1.alwaysValidSchema)(it, sch)) && !it.opts.unevaluated) return; + const valid = gen.let("valid", false); + const schValid = gen.name("_valid"); + gen.block(() => schema.forEach((_sch, i) => { + const schCxt = cxt.subschema({ + keyword, + schemaProp: i, + compositeRule: true + }, schValid); + gen.assign(valid, (0, codegen_1._)`${valid} || ${schValid}`); + if (!cxt.mergeValidEvaluated(schCxt, schValid)) gen.if((0, codegen_1.not)(valid)); + })); + cxt.result(valid, () => cxt.reset(), () => cxt.error(true)); + } + exports.validateUnion = validateUnion; +})); + +//#endregion +//#region ../../node_modules/.pnpm/ajv@8.18.0/node_modules/ajv/dist/compile/validate/keyword.js +var require_keyword = /* @__PURE__ */ __commonJSMin(((exports) => { + Object.defineProperty(exports, "__esModule", { value: true }); + exports.validateKeywordUsage = exports.validSchemaType = exports.funcKeywordCode = exports.macroKeywordCode = void 0; + const codegen_1 = require_codegen(); + const names_1 = require_names(); + const code_1 = require_code(); + const errors_1 = require_errors(); + function macroKeywordCode(cxt, def) { + const { gen, keyword, schema, parentSchema, it } = cxt; + const macroSchema = def.macro.call(it.self, schema, parentSchema, it); + const schemaRef = useKeyword(gen, keyword, macroSchema); + if (it.opts.validateSchema !== false) it.self.validateSchema(macroSchema, true); + const valid = gen.name("valid"); + cxt.subschema({ + schema: macroSchema, + schemaPath: codegen_1.nil, + errSchemaPath: `${it.errSchemaPath}/${keyword}`, + topSchemaRef: schemaRef, + compositeRule: true + }, valid); + cxt.pass(valid, () => cxt.error(true)); + } + exports.macroKeywordCode = macroKeywordCode; + function funcKeywordCode(cxt, def) { + var _a; + const { gen, keyword, schema, parentSchema, $data, it } = cxt; + checkAsyncKeyword(it, def); + const validateRef = useKeyword(gen, keyword, !$data && def.compile ? def.compile.call(it.self, schema, parentSchema, it) : def.validate); + const valid = gen.let("valid"); + cxt.block$data(valid, validateKeyword); + cxt.ok((_a = def.valid) !== null && _a !== void 0 ? _a : valid); + function validateKeyword() { + if (def.errors === false) { + assignValid(); + if (def.modifying) modifyData(cxt); + reportErrs(() => cxt.error()); + } else { + const ruleErrs = def.async ? validateAsync() : validateSync(); + if (def.modifying) modifyData(cxt); + reportErrs(() => addErrs(cxt, ruleErrs)); + } + } + function validateAsync() { + const ruleErrs = gen.let("ruleErrs", null); + gen.try(() => assignValid((0, codegen_1._)`await `), (e) => gen.assign(valid, false).if((0, codegen_1._)`${e} instanceof ${it.ValidationError}`, () => gen.assign(ruleErrs, (0, codegen_1._)`${e}.errors`), () => gen.throw(e))); + return ruleErrs; + } + function validateSync() { + const validateErrs = (0, codegen_1._)`${validateRef}.errors`; + gen.assign(validateErrs, null); + assignValid(codegen_1.nil); + return validateErrs; + } + function assignValid(_await = def.async ? (0, codegen_1._)`await ` : codegen_1.nil) { + const passCxt = it.opts.passContext ? names_1.default.this : names_1.default.self; + const passSchema = !("compile" in def && !$data || def.schema === false); + gen.assign(valid, (0, codegen_1._)`${_await}${(0, code_1.callValidateCode)(cxt, validateRef, passCxt, passSchema)}`, def.modifying); + } + function reportErrs(errors) { + var _a$1; + gen.if((0, codegen_1.not)((_a$1 = def.valid) !== null && _a$1 !== void 0 ? _a$1 : valid), errors); + } + } + exports.funcKeywordCode = funcKeywordCode; + function modifyData(cxt) { + const { gen, data, it } = cxt; + gen.if(it.parentData, () => gen.assign(data, (0, codegen_1._)`${it.parentData}[${it.parentDataProperty}]`)); + } + function addErrs(cxt, errs) { + const { gen } = cxt; + gen.if((0, codegen_1._)`Array.isArray(${errs})`, () => { + gen.assign(names_1.default.vErrors, (0, codegen_1._)`${names_1.default.vErrors} === null ? ${errs} : ${names_1.default.vErrors}.concat(${errs})`).assign(names_1.default.errors, (0, codegen_1._)`${names_1.default.vErrors}.length`); + (0, errors_1.extendErrors)(cxt); + }, () => cxt.error()); + } + function checkAsyncKeyword({ schemaEnv }, def) { + if (def.async && !schemaEnv.$async) throw new Error("async keyword in sync schema"); + } + function useKeyword(gen, keyword, result) { + if (result === void 0) throw new Error(`keyword "${keyword}" failed to compile`); + return gen.scopeValue("keyword", typeof result == "function" ? { ref: result } : { + ref: result, + code: (0, codegen_1.stringify)(result) + }); + } + function validSchemaType(schema, schemaType, allowUndefined = false) { + return !schemaType.length || schemaType.some((st) => st === "array" ? Array.isArray(schema) : st === "object" ? schema && typeof schema == "object" && !Array.isArray(schema) : typeof schema == st || allowUndefined && typeof schema == "undefined"); + } + exports.validSchemaType = validSchemaType; + function validateKeywordUsage({ schema, opts, self, errSchemaPath }, def, keyword) { + /* istanbul ignore if */ + if (Array.isArray(def.keyword) ? !def.keyword.includes(keyword) : def.keyword !== keyword) throw new Error("ajv implementation error"); + const deps = def.dependencies; + if (deps === null || deps === void 0 ? void 0 : deps.some((kwd) => !Object.prototype.hasOwnProperty.call(schema, kwd))) throw new Error(`parent schema must have dependencies of ${keyword}: ${deps.join(",")}`); + if (def.validateSchema) { + if (!def.validateSchema(schema[keyword])) { + const msg = `keyword "${keyword}" value is invalid at path "${errSchemaPath}": ` + self.errorsText(def.validateSchema.errors); + if (opts.validateSchema === "log") self.logger.error(msg); + else throw new Error(msg); + } + } + } + exports.validateKeywordUsage = validateKeywordUsage; +})); + +//#endregion +//#region ../../node_modules/.pnpm/ajv@8.18.0/node_modules/ajv/dist/compile/validate/subschema.js +var require_subschema = /* @__PURE__ */ __commonJSMin(((exports) => { + Object.defineProperty(exports, "__esModule", { value: true }); + exports.extendSubschemaMode = exports.extendSubschemaData = exports.getSubschema = void 0; + const codegen_1 = require_codegen(); + const util_1 = require_util(); + function getSubschema(it, { keyword, schemaProp, schema, schemaPath, errSchemaPath, topSchemaRef }) { + if (keyword !== void 0 && schema !== void 0) throw new Error("both \"keyword\" and \"schema\" passed, only one allowed"); + if (keyword !== void 0) { + const sch = it.schema[keyword]; + return schemaProp === void 0 ? { + schema: sch, + schemaPath: (0, codegen_1._)`${it.schemaPath}${(0, codegen_1.getProperty)(keyword)}`, + errSchemaPath: `${it.errSchemaPath}/${keyword}` + } : { + schema: sch[schemaProp], + schemaPath: (0, codegen_1._)`${it.schemaPath}${(0, codegen_1.getProperty)(keyword)}${(0, codegen_1.getProperty)(schemaProp)}`, + errSchemaPath: `${it.errSchemaPath}/${keyword}/${(0, util_1.escapeFragment)(schemaProp)}` + }; + } + if (schema !== void 0) { + if (schemaPath === void 0 || errSchemaPath === void 0 || topSchemaRef === void 0) throw new Error("\"schemaPath\", \"errSchemaPath\" and \"topSchemaRef\" are required with \"schema\""); + return { + schema, + schemaPath, + topSchemaRef, + errSchemaPath + }; + } + throw new Error("either \"keyword\" or \"schema\" must be passed"); + } + exports.getSubschema = getSubschema; + function extendSubschemaData(subschema, it, { dataProp, dataPropType: dpType, data, dataTypes, propertyName }) { + if (data !== void 0 && dataProp !== void 0) throw new Error("both \"data\" and \"dataProp\" passed, only one allowed"); + const { gen } = it; + if (dataProp !== void 0) { + const { errorPath, dataPathArr, opts } = it; + dataContextProps(gen.let("data", (0, codegen_1._)`${it.data}${(0, codegen_1.getProperty)(dataProp)}`, true)); + subschema.errorPath = (0, codegen_1.str)`${errorPath}${(0, util_1.getErrorPath)(dataProp, dpType, opts.jsPropertySyntax)}`; + subschema.parentDataProperty = (0, codegen_1._)`${dataProp}`; + subschema.dataPathArr = [...dataPathArr, subschema.parentDataProperty]; + } + if (data !== void 0) { + dataContextProps(data instanceof codegen_1.Name ? data : gen.let("data", data, true)); + if (propertyName !== void 0) subschema.propertyName = propertyName; + } + if (dataTypes) subschema.dataTypes = dataTypes; + function dataContextProps(_nextData) { + subschema.data = _nextData; + subschema.dataLevel = it.dataLevel + 1; + subschema.dataTypes = []; + it.definedProperties = /* @__PURE__ */ new Set(); + subschema.parentData = it.data; + subschema.dataNames = [...it.dataNames, _nextData]; + } + } + exports.extendSubschemaData = extendSubschemaData; + function extendSubschemaMode(subschema, { jtdDiscriminator, jtdMetadata, compositeRule, createErrors, allErrors }) { + if (compositeRule !== void 0) subschema.compositeRule = compositeRule; + if (createErrors !== void 0) subschema.createErrors = createErrors; + if (allErrors !== void 0) subschema.allErrors = allErrors; + subschema.jtdDiscriminator = jtdDiscriminator; + subschema.jtdMetadata = jtdMetadata; + } + exports.extendSubschemaMode = extendSubschemaMode; +})); + +//#endregion +//#region ../../node_modules/.pnpm/fast-deep-equal@3.1.3/node_modules/fast-deep-equal/index.js +var require_fast_deep_equal = /* @__PURE__ */ __commonJSMin(((exports, module) => { + module.exports = function equal(a, b) { + if (a === b) return true; + if (a && b && typeof a == "object" && typeof b == "object") { + if (a.constructor !== b.constructor) return false; + var length, i, keys; + if (Array.isArray(a)) { + length = a.length; + if (length != b.length) return false; + for (i = length; i-- !== 0;) if (!equal(a[i], b[i])) return false; + return true; + } + if (a.constructor === RegExp) return a.source === b.source && a.flags === b.flags; + if (a.valueOf !== Object.prototype.valueOf) return a.valueOf() === b.valueOf(); + if (a.toString !== Object.prototype.toString) return a.toString() === b.toString(); + keys = Object.keys(a); + length = keys.length; + if (length !== Object.keys(b).length) return false; + for (i = length; i-- !== 0;) if (!Object.prototype.hasOwnProperty.call(b, keys[i])) return false; + for (i = length; i-- !== 0;) { + var key = keys[i]; + if (!equal(a[key], b[key])) return false; + } + return true; + } + return a !== a && b !== b; + }; +})); + +//#endregion +//#region ../../node_modules/.pnpm/json-schema-traverse@1.0.0/node_modules/json-schema-traverse/index.js +var require_json_schema_traverse = /* @__PURE__ */ __commonJSMin(((exports, module) => { + var traverse = module.exports = function(schema, opts, cb) { + if (typeof opts == "function") { + cb = opts; + opts = {}; + } + cb = opts.cb || cb; + var pre = typeof cb == "function" ? cb : cb.pre || function() {}; + var post = cb.post || function() {}; + _traverse(opts, pre, post, schema, "", schema); + }; + traverse.keywords = { + additionalItems: true, + items: true, + contains: true, + additionalProperties: true, + propertyNames: true, + not: true, + if: true, + then: true, + else: true + }; + traverse.arrayKeywords = { + items: true, + allOf: true, + anyOf: true, + oneOf: true + }; + traverse.propsKeywords = { + $defs: true, + definitions: true, + properties: true, + patternProperties: true, + dependencies: true + }; + traverse.skipKeywords = { + default: true, + enum: true, + const: true, + required: true, + maximum: true, + minimum: true, + exclusiveMaximum: true, + exclusiveMinimum: true, + multipleOf: true, + maxLength: true, + minLength: true, + pattern: true, + format: true, + maxItems: true, + minItems: true, + uniqueItems: true, + maxProperties: true, + minProperties: true + }; + function _traverse(opts, pre, post, schema, jsonPtr, rootSchema, parentJsonPtr, parentKeyword, parentSchema, keyIndex) { + if (schema && typeof schema == "object" && !Array.isArray(schema)) { + pre(schema, jsonPtr, rootSchema, parentJsonPtr, parentKeyword, parentSchema, keyIndex); + for (var key in schema) { + var sch = schema[key]; + if (Array.isArray(sch)) { + if (key in traverse.arrayKeywords) for (var i = 0; i < sch.length; i++) _traverse(opts, pre, post, sch[i], jsonPtr + "/" + key + "/" + i, rootSchema, jsonPtr, key, schema, i); + } else if (key in traverse.propsKeywords) { + if (sch && typeof sch == "object") for (var prop in sch) _traverse(opts, pre, post, sch[prop], jsonPtr + "/" + key + "/" + escapeJsonPtr(prop), rootSchema, jsonPtr, key, schema, prop); + } else if (key in traverse.keywords || opts.allKeys && !(key in traverse.skipKeywords)) _traverse(opts, pre, post, sch, jsonPtr + "/" + key, rootSchema, jsonPtr, key, schema); + } + post(schema, jsonPtr, rootSchema, parentJsonPtr, parentKeyword, parentSchema, keyIndex); + } + } + function escapeJsonPtr(str) { + return str.replace(/~/g, "~0").replace(/\//g, "~1"); + } +})); + +//#endregion +//#region ../../node_modules/.pnpm/ajv@8.18.0/node_modules/ajv/dist/compile/resolve.js +var require_resolve = /* @__PURE__ */ __commonJSMin(((exports) => { + Object.defineProperty(exports, "__esModule", { value: true }); + exports.getSchemaRefs = exports.resolveUrl = exports.normalizeId = exports._getFullPath = exports.getFullPath = exports.inlineRef = void 0; + const util_1 = require_util(); + const equal = require_fast_deep_equal(); + const traverse = require_json_schema_traverse(); + const SIMPLE_INLINED = new Set([ + "type", + "format", + "pattern", + "maxLength", + "minLength", + "maxProperties", + "minProperties", + "maxItems", + "minItems", + "maximum", + "minimum", + "uniqueItems", + "multipleOf", + "required", + "enum", + "const" + ]); + function inlineRef(schema, limit = true) { + if (typeof schema == "boolean") return true; + if (limit === true) return !hasRef(schema); + if (!limit) return false; + return countKeys(schema) <= limit; + } + exports.inlineRef = inlineRef; + const REF_KEYWORDS = new Set([ + "$ref", + "$recursiveRef", + "$recursiveAnchor", + "$dynamicRef", + "$dynamicAnchor" + ]); + function hasRef(schema) { + for (const key in schema) { + if (REF_KEYWORDS.has(key)) return true; + const sch = schema[key]; + if (Array.isArray(sch) && sch.some(hasRef)) return true; + if (typeof sch == "object" && hasRef(sch)) return true; + } + return false; + } + function countKeys(schema) { + let count = 0; + for (const key in schema) { + if (key === "$ref") return Infinity; + count++; + if (SIMPLE_INLINED.has(key)) continue; + if (typeof schema[key] == "object") (0, util_1.eachItem)(schema[key], (sch) => count += countKeys(sch)); + if (count === Infinity) return Infinity; + } + return count; + } + function getFullPath(resolver, id = "", normalize) { + if (normalize !== false) id = normalizeId(id); + return _getFullPath(resolver, resolver.parse(id)); + } + exports.getFullPath = getFullPath; + function _getFullPath(resolver, p) { + return resolver.serialize(p).split("#")[0] + "#"; + } + exports._getFullPath = _getFullPath; + const TRAILING_SLASH_HASH = /#\/?$/; + function normalizeId(id) { + return id ? id.replace(TRAILING_SLASH_HASH, "") : ""; + } + exports.normalizeId = normalizeId; + function resolveUrl(resolver, baseId, id) { + id = normalizeId(id); + return resolver.resolve(baseId, id); + } + exports.resolveUrl = resolveUrl; + const ANCHOR = /^[a-z_][-a-z0-9._]*$/i; + function getSchemaRefs(schema, baseId) { + if (typeof schema == "boolean") return {}; + const { schemaId, uriResolver } = this.opts; + const schId = normalizeId(schema[schemaId] || baseId); + const baseIds = { "": schId }; + const pathPrefix = getFullPath(uriResolver, schId, false); + const localRefs = {}; + const schemaRefs = /* @__PURE__ */ new Set(); + traverse(schema, { allKeys: true }, (sch, jsonPtr, _, parentJsonPtr) => { + if (parentJsonPtr === void 0) return; + const fullPath = pathPrefix + jsonPtr; + let innerBaseId = baseIds[parentJsonPtr]; + if (typeof sch[schemaId] == "string") innerBaseId = addRef.call(this, sch[schemaId]); + addAnchor.call(this, sch.$anchor); + addAnchor.call(this, sch.$dynamicAnchor); + baseIds[jsonPtr] = innerBaseId; + function addRef(ref) { + const _resolve = this.opts.uriResolver.resolve; + ref = normalizeId(innerBaseId ? _resolve(innerBaseId, ref) : ref); + if (schemaRefs.has(ref)) throw ambiguos(ref); + schemaRefs.add(ref); + let schOrRef = this.refs[ref]; + if (typeof schOrRef == "string") schOrRef = this.refs[schOrRef]; + if (typeof schOrRef == "object") checkAmbiguosRef(sch, schOrRef.schema, ref); + else if (ref !== normalizeId(fullPath)) if (ref[0] === "#") { + checkAmbiguosRef(sch, localRefs[ref], ref); + localRefs[ref] = sch; + } else this.refs[ref] = fullPath; + return ref; + } + function addAnchor(anchor) { + if (typeof anchor == "string") { + if (!ANCHOR.test(anchor)) throw new Error(`invalid anchor "${anchor}"`); + addRef.call(this, `#${anchor}`); + } + } + }); + return localRefs; + function checkAmbiguosRef(sch1, sch2, ref) { + if (sch2 !== void 0 && !equal(sch1, sch2)) throw ambiguos(ref); + } + function ambiguos(ref) { + return /* @__PURE__ */ new Error(`reference "${ref}" resolves to more than one schema`); + } + } + exports.getSchemaRefs = getSchemaRefs; +})); + +//#endregion +//#region ../../node_modules/.pnpm/ajv@8.18.0/node_modules/ajv/dist/compile/validate/index.js +var require_validate = /* @__PURE__ */ __commonJSMin(((exports) => { + Object.defineProperty(exports, "__esModule", { value: true }); + exports.getData = exports.KeywordCxt = exports.validateFunctionCode = void 0; + const boolSchema_1 = require_boolSchema(); + const dataType_1 = require_dataType(); + const applicability_1 = require_applicability(); + const dataType_2 = require_dataType(); + const defaults_1 = require_defaults(); + const keyword_1 = require_keyword(); + const subschema_1 = require_subschema(); + const codegen_1 = require_codegen(); + const names_1 = require_names(); + const resolve_1 = require_resolve(); + const util_1 = require_util(); + const errors_1 = require_errors(); + function validateFunctionCode(it) { + if (isSchemaObj(it)) { + checkKeywords(it); + if (schemaCxtHasRules(it)) { + topSchemaObjCode(it); + return; + } + } + validateFunction(it, () => (0, boolSchema_1.topBoolOrEmptySchema)(it)); + } + exports.validateFunctionCode = validateFunctionCode; + function validateFunction({ gen, validateName, schema, schemaEnv, opts }, body) { + if (opts.code.es5) gen.func(validateName, (0, codegen_1._)`${names_1.default.data}, ${names_1.default.valCxt}`, schemaEnv.$async, () => { + gen.code((0, codegen_1._)`"use strict"; ${funcSourceUrl(schema, opts)}`); + destructureValCxtES5(gen, opts); + gen.code(body); + }); + else gen.func(validateName, (0, codegen_1._)`${names_1.default.data}, ${destructureValCxt(opts)}`, schemaEnv.$async, () => gen.code(funcSourceUrl(schema, opts)).code(body)); + } + function destructureValCxt(opts) { + return (0, codegen_1._)`{${names_1.default.instancePath}="", ${names_1.default.parentData}, ${names_1.default.parentDataProperty}, ${names_1.default.rootData}=${names_1.default.data}${opts.dynamicRef ? (0, codegen_1._)`, ${names_1.default.dynamicAnchors}={}` : codegen_1.nil}}={}`; + } + function destructureValCxtES5(gen, opts) { + gen.if(names_1.default.valCxt, () => { + gen.var(names_1.default.instancePath, (0, codegen_1._)`${names_1.default.valCxt}.${names_1.default.instancePath}`); + gen.var(names_1.default.parentData, (0, codegen_1._)`${names_1.default.valCxt}.${names_1.default.parentData}`); + gen.var(names_1.default.parentDataProperty, (0, codegen_1._)`${names_1.default.valCxt}.${names_1.default.parentDataProperty}`); + gen.var(names_1.default.rootData, (0, codegen_1._)`${names_1.default.valCxt}.${names_1.default.rootData}`); + if (opts.dynamicRef) gen.var(names_1.default.dynamicAnchors, (0, codegen_1._)`${names_1.default.valCxt}.${names_1.default.dynamicAnchors}`); + }, () => { + gen.var(names_1.default.instancePath, (0, codegen_1._)`""`); + gen.var(names_1.default.parentData, (0, codegen_1._)`undefined`); + gen.var(names_1.default.parentDataProperty, (0, codegen_1._)`undefined`); + gen.var(names_1.default.rootData, names_1.default.data); + if (opts.dynamicRef) gen.var(names_1.default.dynamicAnchors, (0, codegen_1._)`{}`); + }); + } + function topSchemaObjCode(it) { + const { schema, opts, gen } = it; + validateFunction(it, () => { + if (opts.$comment && schema.$comment) commentKeyword(it); + checkNoDefault(it); + gen.let(names_1.default.vErrors, null); + gen.let(names_1.default.errors, 0); + if (opts.unevaluated) resetEvaluated(it); + typeAndKeywords(it); + returnResults(it); + }); + } + function resetEvaluated(it) { + const { gen, validateName } = it; + it.evaluated = gen.const("evaluated", (0, codegen_1._)`${validateName}.evaluated`); + gen.if((0, codegen_1._)`${it.evaluated}.dynamicProps`, () => gen.assign((0, codegen_1._)`${it.evaluated}.props`, (0, codegen_1._)`undefined`)); + gen.if((0, codegen_1._)`${it.evaluated}.dynamicItems`, () => gen.assign((0, codegen_1._)`${it.evaluated}.items`, (0, codegen_1._)`undefined`)); + } + function funcSourceUrl(schema, opts) { + const schId = typeof schema == "object" && schema[opts.schemaId]; + return schId && (opts.code.source || opts.code.process) ? (0, codegen_1._)`/*# sourceURL=${schId} */` : codegen_1.nil; + } + function subschemaCode(it, valid) { + if (isSchemaObj(it)) { + checkKeywords(it); + if (schemaCxtHasRules(it)) { + subSchemaObjCode(it, valid); + return; + } + } + (0, boolSchema_1.boolOrEmptySchema)(it, valid); + } + function schemaCxtHasRules({ schema, self }) { + if (typeof schema == "boolean") return !schema; + for (const key in schema) if (self.RULES.all[key]) return true; + return false; + } + function isSchemaObj(it) { + return typeof it.schema != "boolean"; + } + function subSchemaObjCode(it, valid) { + const { schema, gen, opts } = it; + if (opts.$comment && schema.$comment) commentKeyword(it); + updateContext(it); + checkAsyncSchema(it); + const errsCount = gen.const("_errs", names_1.default.errors); + typeAndKeywords(it, errsCount); + gen.var(valid, (0, codegen_1._)`${errsCount} === ${names_1.default.errors}`); + } + function checkKeywords(it) { + (0, util_1.checkUnknownRules)(it); + checkRefsAndKeywords(it); + } + function typeAndKeywords(it, errsCount) { + if (it.opts.jtd) return schemaKeywords(it, [], false, errsCount); + const types = (0, dataType_1.getSchemaTypes)(it.schema); + schemaKeywords(it, types, !(0, dataType_1.coerceAndCheckDataType)(it, types), errsCount); + } + function checkRefsAndKeywords(it) { + const { schema, errSchemaPath, opts, self } = it; + if (schema.$ref && opts.ignoreKeywordsWithRef && (0, util_1.schemaHasRulesButRef)(schema, self.RULES)) self.logger.warn(`$ref: keywords ignored in schema at path "${errSchemaPath}"`); + } + function checkNoDefault(it) { + const { schema, opts } = it; + if (schema.default !== void 0 && opts.useDefaults && opts.strictSchema) (0, util_1.checkStrictMode)(it, "default is ignored in the schema root"); + } + function updateContext(it) { + const schId = it.schema[it.opts.schemaId]; + if (schId) it.baseId = (0, resolve_1.resolveUrl)(it.opts.uriResolver, it.baseId, schId); + } + function checkAsyncSchema(it) { + if (it.schema.$async && !it.schemaEnv.$async) throw new Error("async schema in sync schema"); + } + function commentKeyword({ gen, schemaEnv, schema, errSchemaPath, opts }) { + const msg = schema.$comment; + if (opts.$comment === true) gen.code((0, codegen_1._)`${names_1.default.self}.logger.log(${msg})`); + else if (typeof opts.$comment == "function") { + const schemaPath = (0, codegen_1.str)`${errSchemaPath}/$comment`; + const rootName = gen.scopeValue("root", { ref: schemaEnv.root }); + gen.code((0, codegen_1._)`${names_1.default.self}.opts.$comment(${msg}, ${schemaPath}, ${rootName}.schema)`); + } + } + function returnResults(it) { + const { gen, schemaEnv, validateName, ValidationError, opts } = it; + if (schemaEnv.$async) gen.if((0, codegen_1._)`${names_1.default.errors} === 0`, () => gen.return(names_1.default.data), () => gen.throw((0, codegen_1._)`new ${ValidationError}(${names_1.default.vErrors})`)); + else { + gen.assign((0, codegen_1._)`${validateName}.errors`, names_1.default.vErrors); + if (opts.unevaluated) assignEvaluated(it); + gen.return((0, codegen_1._)`${names_1.default.errors} === 0`); + } + } + function assignEvaluated({ gen, evaluated, props, items }) { + if (props instanceof codegen_1.Name) gen.assign((0, codegen_1._)`${evaluated}.props`, props); + if (items instanceof codegen_1.Name) gen.assign((0, codegen_1._)`${evaluated}.items`, items); + } + function schemaKeywords(it, types, typeErrors, errsCount) { + const { gen, schema, data, allErrors, opts, self } = it; + const { RULES } = self; + if (schema.$ref && (opts.ignoreKeywordsWithRef || !(0, util_1.schemaHasRulesButRef)(schema, RULES))) { + gen.block(() => keywordCode(it, "$ref", RULES.all.$ref.definition)); + return; + } + if (!opts.jtd) checkStrictTypes(it, types); + gen.block(() => { + for (const group of RULES.rules) groupKeywords(group); + groupKeywords(RULES.post); + }); + function groupKeywords(group) { + if (!(0, applicability_1.shouldUseGroup)(schema, group)) return; + if (group.type) { + gen.if((0, dataType_2.checkDataType)(group.type, data, opts.strictNumbers)); + iterateKeywords(it, group); + if (types.length === 1 && types[0] === group.type && typeErrors) { + gen.else(); + (0, dataType_2.reportTypeError)(it); + } + gen.endIf(); + } else iterateKeywords(it, group); + if (!allErrors) gen.if((0, codegen_1._)`${names_1.default.errors} === ${errsCount || 0}`); + } + } + function iterateKeywords(it, group) { + const { gen, schema, opts: { useDefaults } } = it; + if (useDefaults) (0, defaults_1.assignDefaults)(it, group.type); + gen.block(() => { + for (const rule of group.rules) if ((0, applicability_1.shouldUseRule)(schema, rule)) keywordCode(it, rule.keyword, rule.definition, group.type); + }); + } + function checkStrictTypes(it, types) { + if (it.schemaEnv.meta || !it.opts.strictTypes) return; + checkContextTypes(it, types); + if (!it.opts.allowUnionTypes) checkMultipleTypes(it, types); + checkKeywordTypes(it, it.dataTypes); + } + function checkContextTypes(it, types) { + if (!types.length) return; + if (!it.dataTypes.length) { + it.dataTypes = types; + return; + } + types.forEach((t) => { + if (!includesType(it.dataTypes, t)) strictTypesError(it, `type "${t}" not allowed by context "${it.dataTypes.join(",")}"`); + }); + narrowSchemaTypes(it, types); + } + function checkMultipleTypes(it, ts) { + if (ts.length > 1 && !(ts.length === 2 && ts.includes("null"))) strictTypesError(it, "use allowUnionTypes to allow union type keyword"); + } + function checkKeywordTypes(it, ts) { + const rules = it.self.RULES.all; + for (const keyword in rules) { + const rule = rules[keyword]; + if (typeof rule == "object" && (0, applicability_1.shouldUseRule)(it.schema, rule)) { + const { type } = rule.definition; + if (type.length && !type.some((t) => hasApplicableType(ts, t))) strictTypesError(it, `missing type "${type.join(",")}" for keyword "${keyword}"`); + } + } + } + function hasApplicableType(schTs, kwdT) { + return schTs.includes(kwdT) || kwdT === "number" && schTs.includes("integer"); + } + function includesType(ts, t) { + return ts.includes(t) || t === "integer" && ts.includes("number"); + } + function narrowSchemaTypes(it, withTypes) { + const ts = []; + for (const t of it.dataTypes) if (includesType(withTypes, t)) ts.push(t); + else if (withTypes.includes("integer") && t === "number") ts.push("integer"); + it.dataTypes = ts; + } + function strictTypesError(it, msg) { + const schemaPath = it.schemaEnv.baseId + it.errSchemaPath; + msg += ` at "${schemaPath}" (strictTypes)`; + (0, util_1.checkStrictMode)(it, msg, it.opts.strictTypes); + } + var KeywordCxt = class { + constructor(it, def, keyword) { + (0, keyword_1.validateKeywordUsage)(it, def, keyword); + this.gen = it.gen; + this.allErrors = it.allErrors; + this.keyword = keyword; + this.data = it.data; + this.schema = it.schema[keyword]; + this.$data = def.$data && it.opts.$data && this.schema && this.schema.$data; + this.schemaValue = (0, util_1.schemaRefOrVal)(it, this.schema, keyword, this.$data); + this.schemaType = def.schemaType; + this.parentSchema = it.schema; + this.params = {}; + this.it = it; + this.def = def; + if (this.$data) this.schemaCode = it.gen.const("vSchema", getData(this.$data, it)); + else { + this.schemaCode = this.schemaValue; + if (!(0, keyword_1.validSchemaType)(this.schema, def.schemaType, def.allowUndefined)) throw new Error(`${keyword} value must be ${JSON.stringify(def.schemaType)}`); + } + if ("code" in def ? def.trackErrors : def.errors !== false) this.errsCount = it.gen.const("_errs", names_1.default.errors); + } + result(condition, successAction, failAction) { + this.failResult((0, codegen_1.not)(condition), successAction, failAction); + } + failResult(condition, successAction, failAction) { + this.gen.if(condition); + if (failAction) failAction(); + else this.error(); + if (successAction) { + this.gen.else(); + successAction(); + if (this.allErrors) this.gen.endIf(); + } else if (this.allErrors) this.gen.endIf(); + else this.gen.else(); + } + pass(condition, failAction) { + this.failResult((0, codegen_1.not)(condition), void 0, failAction); + } + fail(condition) { + if (condition === void 0) { + this.error(); + if (!this.allErrors) this.gen.if(false); + return; + } + this.gen.if(condition); + this.error(); + if (this.allErrors) this.gen.endIf(); + else this.gen.else(); + } + fail$data(condition) { + if (!this.$data) return this.fail(condition); + const { schemaCode } = this; + this.fail((0, codegen_1._)`${schemaCode} !== undefined && (${(0, codegen_1.or)(this.invalid$data(), condition)})`); + } + error(append, errorParams, errorPaths) { + if (errorParams) { + this.setParams(errorParams); + this._error(append, errorPaths); + this.setParams({}); + return; + } + this._error(append, errorPaths); + } + _error(append, errorPaths) { + (append ? errors_1.reportExtraError : errors_1.reportError)(this, this.def.error, errorPaths); + } + $dataError() { + (0, errors_1.reportError)(this, this.def.$dataError || errors_1.keyword$DataError); + } + reset() { + if (this.errsCount === void 0) throw new Error("add \"trackErrors\" to keyword definition"); + (0, errors_1.resetErrorsCount)(this.gen, this.errsCount); + } + ok(cond) { + if (!this.allErrors) this.gen.if(cond); + } + setParams(obj, assign) { + if (assign) Object.assign(this.params, obj); + else this.params = obj; + } + block$data(valid, codeBlock, $dataValid = codegen_1.nil) { + this.gen.block(() => { + this.check$data(valid, $dataValid); + codeBlock(); + }); + } + check$data(valid = codegen_1.nil, $dataValid = codegen_1.nil) { + if (!this.$data) return; + const { gen, schemaCode, schemaType, def } = this; + gen.if((0, codegen_1.or)((0, codegen_1._)`${schemaCode} === undefined`, $dataValid)); + if (valid !== codegen_1.nil) gen.assign(valid, true); + if (schemaType.length || def.validateSchema) { + gen.elseIf(this.invalid$data()); + this.$dataError(); + if (valid !== codegen_1.nil) gen.assign(valid, false); + } + gen.else(); + } + invalid$data() { + const { gen, schemaCode, schemaType, def, it } = this; + return (0, codegen_1.or)(wrong$DataType(), invalid$DataSchema()); + function wrong$DataType() { + if (schemaType.length) { + /* istanbul ignore if */ + if (!(schemaCode instanceof codegen_1.Name)) throw new Error("ajv implementation error"); + const st = Array.isArray(schemaType) ? schemaType : [schemaType]; + return (0, codegen_1._)`${(0, dataType_2.checkDataTypes)(st, schemaCode, it.opts.strictNumbers, dataType_2.DataType.Wrong)}`; + } + return codegen_1.nil; + } + function invalid$DataSchema() { + if (def.validateSchema) { + const validateSchemaRef = gen.scopeValue("validate$data", { ref: def.validateSchema }); + return (0, codegen_1._)`!${validateSchemaRef}(${schemaCode})`; + } + return codegen_1.nil; + } + } + subschema(appl, valid) { + const subschema = (0, subschema_1.getSubschema)(this.it, appl); + (0, subschema_1.extendSubschemaData)(subschema, this.it, appl); + (0, subschema_1.extendSubschemaMode)(subschema, appl); + const nextContext = { + ...this.it, + ...subschema, + items: void 0, + props: void 0 + }; + subschemaCode(nextContext, valid); + return nextContext; + } + mergeEvaluated(schemaCxt, toName) { + const { it, gen } = this; + if (!it.opts.unevaluated) return; + if (it.props !== true && schemaCxt.props !== void 0) it.props = util_1.mergeEvaluated.props(gen, schemaCxt.props, it.props, toName); + if (it.items !== true && schemaCxt.items !== void 0) it.items = util_1.mergeEvaluated.items(gen, schemaCxt.items, it.items, toName); + } + mergeValidEvaluated(schemaCxt, valid) { + const { it, gen } = this; + if (it.opts.unevaluated && (it.props !== true || it.items !== true)) { + gen.if(valid, () => this.mergeEvaluated(schemaCxt, codegen_1.Name)); + return true; + } + } + }; + exports.KeywordCxt = KeywordCxt; + function keywordCode(it, keyword, def, ruleType) { + const cxt = new KeywordCxt(it, def, keyword); + if ("code" in def) def.code(cxt, ruleType); + else if (cxt.$data && def.validate) (0, keyword_1.funcKeywordCode)(cxt, def); + else if ("macro" in def) (0, keyword_1.macroKeywordCode)(cxt, def); + else if (def.compile || def.validate) (0, keyword_1.funcKeywordCode)(cxt, def); + } + const JSON_POINTER = /^\/(?:[^~]|~0|~1)*$/; + const RELATIVE_JSON_POINTER = /^([0-9]+)(#|\/(?:[^~]|~0|~1)*)?$/; + function getData($data, { dataLevel, dataNames, dataPathArr }) { + let jsonPointer; + let data; + if ($data === "") return names_1.default.rootData; + if ($data[0] === "/") { + if (!JSON_POINTER.test($data)) throw new Error(`Invalid JSON-pointer: ${$data}`); + jsonPointer = $data; + data = names_1.default.rootData; + } else { + const matches = RELATIVE_JSON_POINTER.exec($data); + if (!matches) throw new Error(`Invalid JSON-pointer: ${$data}`); + const up = +matches[1]; + jsonPointer = matches[2]; + if (jsonPointer === "#") { + if (up >= dataLevel) throw new Error(errorMsg("property/index", up)); + return dataPathArr[dataLevel - up]; + } + if (up > dataLevel) throw new Error(errorMsg("data", up)); + data = dataNames[dataLevel - up]; + if (!jsonPointer) return data; + } + let expr = data; + const segments = jsonPointer.split("/"); + for (const segment of segments) if (segment) { + data = (0, codegen_1._)`${data}${(0, codegen_1.getProperty)((0, util_1.unescapeJsonPointer)(segment))}`; + expr = (0, codegen_1._)`${expr} && ${data}`; + } + return expr; + function errorMsg(pointerType, up) { + return `Cannot access ${pointerType} ${up} levels up, current level is ${dataLevel}`; + } + } + exports.getData = getData; +})); + +//#endregion +//#region ../../node_modules/.pnpm/ajv@8.18.0/node_modules/ajv/dist/runtime/validation_error.js +var require_validation_error = /* @__PURE__ */ __commonJSMin(((exports) => { + Object.defineProperty(exports, "__esModule", { value: true }); + var ValidationError = class extends Error { + constructor(errors) { + super("validation failed"); + this.errors = errors; + this.ajv = this.validation = true; + } + }; + exports.default = ValidationError; +})); + +//#endregion +//#region ../../node_modules/.pnpm/ajv@8.18.0/node_modules/ajv/dist/compile/ref_error.js +var require_ref_error = /* @__PURE__ */ __commonJSMin(((exports) => { + Object.defineProperty(exports, "__esModule", { value: true }); + const resolve_1 = require_resolve(); + var MissingRefError = class extends Error { + constructor(resolver, baseId, ref, msg) { + super(msg || `can't resolve reference ${ref} from id ${baseId}`); + this.missingRef = (0, resolve_1.resolveUrl)(resolver, baseId, ref); + this.missingSchema = (0, resolve_1.normalizeId)((0, resolve_1.getFullPath)(resolver, this.missingRef)); + } + }; + exports.default = MissingRefError; +})); + +//#endregion +//#region ../../node_modules/.pnpm/ajv@8.18.0/node_modules/ajv/dist/compile/index.js +var require_compile = /* @__PURE__ */ __commonJSMin(((exports) => { + Object.defineProperty(exports, "__esModule", { value: true }); + exports.resolveSchema = exports.getCompilingSchema = exports.resolveRef = exports.compileSchema = exports.SchemaEnv = void 0; + const codegen_1 = require_codegen(); + const validation_error_1 = require_validation_error(); + const names_1 = require_names(); + const resolve_1 = require_resolve(); + const util_1 = require_util(); + const validate_1 = require_validate(); + var SchemaEnv = class { + constructor(env) { + var _a; + this.refs = {}; + this.dynamicAnchors = {}; + let schema; + if (typeof env.schema == "object") schema = env.schema; + this.schema = env.schema; + this.schemaId = env.schemaId; + this.root = env.root || this; + this.baseId = (_a = env.baseId) !== null && _a !== void 0 ? _a : (0, resolve_1.normalizeId)(schema === null || schema === void 0 ? void 0 : schema[env.schemaId || "$id"]); + this.schemaPath = env.schemaPath; + this.localRefs = env.localRefs; + this.meta = env.meta; + this.$async = schema === null || schema === void 0 ? void 0 : schema.$async; + this.refs = {}; + } + }; + exports.SchemaEnv = SchemaEnv; + function compileSchema(sch) { + const _sch = getCompilingSchema.call(this, sch); + if (_sch) return _sch; + const rootId = (0, resolve_1.getFullPath)(this.opts.uriResolver, sch.root.baseId); + const { es5, lines } = this.opts.code; + const { ownProperties } = this.opts; + const gen = new codegen_1.CodeGen(this.scope, { + es5, + lines, + ownProperties + }); + let _ValidationError; + if (sch.$async) _ValidationError = gen.scopeValue("Error", { + ref: validation_error_1.default, + code: (0, codegen_1._)`require("ajv/dist/runtime/validation_error").default` + }); + const validateName = gen.scopeName("validate"); + sch.validateName = validateName; + const schemaCxt = { + gen, + allErrors: this.opts.allErrors, + data: names_1.default.data, + parentData: names_1.default.parentData, + parentDataProperty: names_1.default.parentDataProperty, + dataNames: [names_1.default.data], + dataPathArr: [codegen_1.nil], + dataLevel: 0, + dataTypes: [], + definedProperties: /* @__PURE__ */ new Set(), + topSchemaRef: gen.scopeValue("schema", this.opts.code.source === true ? { + ref: sch.schema, + code: (0, codegen_1.stringify)(sch.schema) + } : { ref: sch.schema }), + validateName, + ValidationError: _ValidationError, + schema: sch.schema, + schemaEnv: sch, + rootId, + baseId: sch.baseId || rootId, + schemaPath: codegen_1.nil, + errSchemaPath: sch.schemaPath || (this.opts.jtd ? "" : "#"), + errorPath: (0, codegen_1._)`""`, + opts: this.opts, + self: this + }; + let sourceCode; + try { + this._compilations.add(sch); + (0, validate_1.validateFunctionCode)(schemaCxt); + gen.optimize(this.opts.code.optimize); + const validateCode = gen.toString(); + sourceCode = `${gen.scopeRefs(names_1.default.scope)}return ${validateCode}`; + if (this.opts.code.process) sourceCode = this.opts.code.process(sourceCode, sch); + const validate = new Function(`${names_1.default.self}`, `${names_1.default.scope}`, sourceCode)(this, this.scope.get()); + this.scope.value(validateName, { ref: validate }); + validate.errors = null; + validate.schema = sch.schema; + validate.schemaEnv = sch; + if (sch.$async) validate.$async = true; + if (this.opts.code.source === true) validate.source = { + validateName, + validateCode, + scopeValues: gen._values + }; + if (this.opts.unevaluated) { + const { props, items } = schemaCxt; + validate.evaluated = { + props: props instanceof codegen_1.Name ? void 0 : props, + items: items instanceof codegen_1.Name ? void 0 : items, + dynamicProps: props instanceof codegen_1.Name, + dynamicItems: items instanceof codegen_1.Name + }; + if (validate.source) validate.source.evaluated = (0, codegen_1.stringify)(validate.evaluated); + } + sch.validate = validate; + return sch; + } catch (e) { + delete sch.validate; + delete sch.validateName; + if (sourceCode) this.logger.error("Error compiling schema, function code:", sourceCode); + throw e; + } finally { + this._compilations.delete(sch); + } + } + exports.compileSchema = compileSchema; + function resolveRef(root, baseId, ref) { + var _a; + ref = (0, resolve_1.resolveUrl)(this.opts.uriResolver, baseId, ref); + const schOrFunc = root.refs[ref]; + if (schOrFunc) return schOrFunc; + let _sch = resolve.call(this, root, ref); + if (_sch === void 0) { + const schema = (_a = root.localRefs) === null || _a === void 0 ? void 0 : _a[ref]; + const { schemaId } = this.opts; + if (schema) _sch = new SchemaEnv({ + schema, + schemaId, + root, + baseId + }); + } + if (_sch === void 0) return; + return root.refs[ref] = inlineOrCompile.call(this, _sch); + } + exports.resolveRef = resolveRef; + function inlineOrCompile(sch) { + if ((0, resolve_1.inlineRef)(sch.schema, this.opts.inlineRefs)) return sch.schema; + return sch.validate ? sch : compileSchema.call(this, sch); + } + function getCompilingSchema(schEnv) { + for (const sch of this._compilations) if (sameSchemaEnv(sch, schEnv)) return sch; + } + exports.getCompilingSchema = getCompilingSchema; + function sameSchemaEnv(s1, s2) { + return s1.schema === s2.schema && s1.root === s2.root && s1.baseId === s2.baseId; + } + function resolve(root, ref) { + let sch; + while (typeof (sch = this.refs[ref]) == "string") ref = sch; + return sch || this.schemas[ref] || resolveSchema.call(this, root, ref); + } + function resolveSchema(root, ref) { + const p = this.opts.uriResolver.parse(ref); + const refPath = (0, resolve_1._getFullPath)(this.opts.uriResolver, p); + let baseId = (0, resolve_1.getFullPath)(this.opts.uriResolver, root.baseId, void 0); + if (Object.keys(root.schema).length > 0 && refPath === baseId) return getJsonPointer.call(this, p, root); + const id = (0, resolve_1.normalizeId)(refPath); + const schOrRef = this.refs[id] || this.schemas[id]; + if (typeof schOrRef == "string") { + const sch = resolveSchema.call(this, root, schOrRef); + if (typeof (sch === null || sch === void 0 ? void 0 : sch.schema) !== "object") return; + return getJsonPointer.call(this, p, sch); + } + if (typeof (schOrRef === null || schOrRef === void 0 ? void 0 : schOrRef.schema) !== "object") return; + if (!schOrRef.validate) compileSchema.call(this, schOrRef); + if (id === (0, resolve_1.normalizeId)(ref)) { + const { schema } = schOrRef; + const { schemaId } = this.opts; + const schId = schema[schemaId]; + if (schId) baseId = (0, resolve_1.resolveUrl)(this.opts.uriResolver, baseId, schId); + return new SchemaEnv({ + schema, + schemaId, + root, + baseId + }); + } + return getJsonPointer.call(this, p, schOrRef); + } + exports.resolveSchema = resolveSchema; + const PREVENT_SCOPE_CHANGE = new Set([ + "properties", + "patternProperties", + "enum", + "dependencies", + "definitions" + ]); + function getJsonPointer(parsedRef, { baseId, schema, root }) { + var _a; + if (((_a = parsedRef.fragment) === null || _a === void 0 ? void 0 : _a[0]) !== "/") return; + for (const part of parsedRef.fragment.slice(1).split("/")) { + if (typeof schema === "boolean") return; + const partSchema = schema[(0, util_1.unescapeFragment)(part)]; + if (partSchema === void 0) return; + schema = partSchema; + const schId = typeof schema === "object" && schema[this.opts.schemaId]; + if (!PREVENT_SCOPE_CHANGE.has(part) && schId) baseId = (0, resolve_1.resolveUrl)(this.opts.uriResolver, baseId, schId); + } + let env; + if (typeof schema != "boolean" && schema.$ref && !(0, util_1.schemaHasRulesButRef)(schema, this.RULES)) { + const $ref = (0, resolve_1.resolveUrl)(this.opts.uriResolver, baseId, schema.$ref); + env = resolveSchema.call(this, root, $ref); + } + const { schemaId } = this.opts; + env = env || new SchemaEnv({ + schema, + schemaId, + root, + baseId + }); + if (env.schema !== env.root.schema) return env; + } +})); + +//#endregion +//#region ../../node_modules/.pnpm/ajv@8.18.0/node_modules/ajv/dist/refs/data.json +var require_data = /* @__PURE__ */ __commonJSMin(((exports, module) => { + module.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": false + }; +})); + +//#endregion +//#region ../../node_modules/.pnpm/fast-uri@3.1.0/node_modules/fast-uri/lib/utils.js +var require_utils = /* @__PURE__ */ __commonJSMin(((exports, module) => { + /** @type {(value: string) => boolean} */ + const isUUID = RegExp.prototype.test.bind(/^[\da-f]{8}-[\da-f]{4}-[\da-f]{4}-[\da-f]{4}-[\da-f]{12}$/iu); + /** @type {(value: string) => boolean} */ + const isIPv4 = 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); + /** + * @param {Array} input + * @returns {string} + */ + function stringArrayToHexStripped(input) { + let acc = ""; + let code = 0; + let i = 0; + for (i = 0; i < input.length; i++) { + code = input[i].charCodeAt(0); + if (code === 48) continue; + if (!(code >= 48 && code <= 57 || code >= 65 && code <= 70 || code >= 97 && code <= 102)) return ""; + acc += input[i]; + break; + } + for (i += 1; i < input.length; i++) { + code = input[i].charCodeAt(0); + if (!(code >= 48 && code <= 57 || code >= 65 && code <= 70 || code >= 97 && code <= 102)) return ""; + acc += input[i]; + } + return acc; + } + /** + * @typedef {Object} GetIPV6Result + * @property {boolean} error - Indicates if there was an error parsing the IPv6 address. + * @property {string} address - The parsed IPv6 address. + * @property {string} [zone] - The zone identifier, if present. + */ + /** + * @param {string} value + * @returns {boolean} + */ + const nonSimpleDomain = RegExp.prototype.test.bind(/[^!"$&'()*+,\-.;=_`a-z{}~]/u); + /** + * @param {Array} buffer + * @returns {boolean} + */ + function consumeIsZone(buffer) { + buffer.length = 0; + return true; + } + /** + * @param {Array} buffer + * @param {Array} address + * @param {GetIPV6Result} output + * @returns {boolean} + */ + function consumeHextets(buffer, address, output) { + if (buffer.length) { + const hex = stringArrayToHexStripped(buffer); + if (hex !== "") address.push(hex); + else { + output.error = true; + return false; + } + buffer.length = 0; + } + return true; + } + /** + * @param {string} input + * @returns {GetIPV6Result} + */ + function getIPV6(input) { + let tokenCount = 0; + const output = { + error: false, + address: "", + zone: "" + }; + /** @type {Array} */ + const address = []; + /** @type {Array} */ + const buffer = []; + let endipv6Encountered = false; + let endIpv6 = false; + let consume = consumeHextets; + for (let i = 0; i < input.length; i++) { + const cursor = input[i]; + if (cursor === "[" || cursor === "]") continue; + if (cursor === ":") { + if (endipv6Encountered === true) endIpv6 = true; + if (!consume(buffer, address, output)) break; + if (++tokenCount > 7) { + output.error = true; + break; + } + if (i > 0 && input[i - 1] === ":") endipv6Encountered = true; + address.push(":"); + continue; + } else if (cursor === "%") { + if (!consume(buffer, address, output)) break; + consume = consumeIsZone; + } else { + buffer.push(cursor); + continue; + } + } + if (buffer.length) if (consume === consumeIsZone) output.zone = buffer.join(""); + else if (endIpv6) address.push(buffer.join("")); + else address.push(stringArrayToHexStripped(buffer)); + output.address = address.join(""); + return output; + } + /** + * @typedef {Object} NormalizeIPv6Result + * @property {string} host - The normalized host. + * @property {string} [escapedHost] - The escaped host. + * @property {boolean} isIPV6 - Indicates if the host is an IPv6 address. + */ + /** + * @param {string} host + * @returns {NormalizeIPv6Result} + */ + function normalizeIPv6(host) { + if (findToken(host, ":") < 2) return { + host, + isIPV6: false + }; + const ipv6 = getIPV6(host); + if (!ipv6.error) { + let newHost = ipv6.address; + let escapedHost = ipv6.address; + if (ipv6.zone) { + newHost += "%" + ipv6.zone; + escapedHost += "%25" + ipv6.zone; + } + return { + host: newHost, + isIPV6: true, + escapedHost + }; + } else return { + host, + isIPV6: false + }; + } + /** + * @param {string} str + * @param {string} token + * @returns {number} + */ + function findToken(str, token) { + let ind = 0; + for (let i = 0; i < str.length; i++) if (str[i] === token) ind++; + return ind; + } + /** + * @param {string} path + * @returns {string} + * + * @see https://datatracker.ietf.org/doc/html/rfc3986#section-5.2.4 + */ + function removeDotSegments(path) { + let input = path; + const output = []; + let nextSlash = -1; + let len = 0; + while (len = input.length) { + if (len === 1) if (input === ".") break; + else if (input === "/") { + output.push("/"); + break; + } else { + output.push(input); + break; + } + else if (len === 2) { + if (input[0] === ".") { + if (input[1] === ".") break; + else if (input[1] === "/") { + input = input.slice(2); + continue; + } + } else if (input[0] === "/") { + if (input[1] === "." || input[1] === "/") { + output.push("/"); + break; + } + } + } else if (len === 3) { + if (input === "/..") { + if (output.length !== 0) output.pop(); + output.push("/"); + break; + } + } + if (input[0] === ".") { + if (input[1] === ".") { + if (input[2] === "/") { + input = input.slice(3); + continue; + } + } else if (input[1] === "/") { + input = input.slice(2); + continue; + } + } else if (input[0] === "/") { + if (input[1] === ".") { + if (input[2] === "/") { + input = input.slice(2); + continue; + } else if (input[2] === ".") { + if (input[3] === "/") { + input = input.slice(3); + if (output.length !== 0) output.pop(); + continue; + } + } + } + } + if ((nextSlash = input.indexOf("/", 1)) === -1) { + output.push(input); + break; + } else { + output.push(input.slice(0, nextSlash)); + input = input.slice(nextSlash); + } + } + return output.join(""); + } + /** + * @param {import('../types/index').URIComponent} component + * @param {boolean} esc + * @returns {import('../types/index').URIComponent} + */ + function normalizeComponentEncoding(component, esc) { + const func = esc !== true ? escape : unescape; + if (component.scheme !== void 0) component.scheme = func(component.scheme); + if (component.userinfo !== void 0) component.userinfo = func(component.userinfo); + if (component.host !== void 0) component.host = func(component.host); + if (component.path !== void 0) component.path = func(component.path); + if (component.query !== void 0) component.query = func(component.query); + if (component.fragment !== void 0) component.fragment = func(component.fragment); + return component; + } + /** + * @param {import('../types/index').URIComponent} component + * @returns {string|undefined} + */ + function recomposeAuthority(component) { + const uriTokens = []; + if (component.userinfo !== void 0) { + uriTokens.push(component.userinfo); + uriTokens.push("@"); + } + if (component.host !== void 0) { + let host = unescape(component.host); + if (!isIPv4(host)) { + const ipV6res = normalizeIPv6(host); + if (ipV6res.isIPV6 === true) host = `[${ipV6res.escapedHost}]`; + else host = component.host; + } + uriTokens.push(host); + } + if (typeof component.port === "number" || typeof component.port === "string") { + uriTokens.push(":"); + uriTokens.push(String(component.port)); + } + return uriTokens.length ? uriTokens.join("") : void 0; + } + module.exports = { + nonSimpleDomain, + recomposeAuthority, + normalizeComponentEncoding, + removeDotSegments, + isIPv4, + isUUID, + normalizeIPv6, + stringArrayToHexStripped + }; +})); + +//#endregion +//#region ../../node_modules/.pnpm/fast-uri@3.1.0/node_modules/fast-uri/lib/schemes.js +var require_schemes = /* @__PURE__ */ __commonJSMin(((exports, module) => { + const { isUUID } = require_utils(); + const URN_REG = /([\da-z][\d\-a-z]{0,31}):((?:[\w!$'()*+,\-.:;=@]|%[\da-f]{2})+)/iu; + const supportedSchemeNames = [ + "http", + "https", + "ws", + "wss", + "urn", + "urn:uuid" + ]; + /** @typedef {supportedSchemeNames[number]} SchemeName */ + /** + * @param {string} name + * @returns {name is SchemeName} + */ + function isValidSchemeName(name) { + return supportedSchemeNames.indexOf(name) !== -1; + } + /** + * @callback SchemeFn + * @param {import('../types/index').URIComponent} component + * @param {import('../types/index').Options} options + * @returns {import('../types/index').URIComponent} + */ + /** + * @typedef {Object} SchemeHandler + * @property {SchemeName} scheme - The scheme name. + * @property {boolean} [domainHost] - Indicates if the scheme supports domain hosts. + * @property {SchemeFn} parse - Function to parse the URI component for this scheme. + * @property {SchemeFn} serialize - Function to serialize the URI component for this scheme. + * @property {boolean} [skipNormalize] - Indicates if normalization should be skipped for this scheme. + * @property {boolean} [absolutePath] - Indicates if the scheme uses absolute paths. + * @property {boolean} [unicodeSupport] - Indicates if the scheme supports Unicode. + */ + /** + * @param {import('../types/index').URIComponent} wsComponent + * @returns {boolean} + */ + function wsIsSecure(wsComponent) { + if (wsComponent.secure === true) return true; + else if (wsComponent.secure === false) return false; + else if (wsComponent.scheme) return wsComponent.scheme.length === 3 && (wsComponent.scheme[0] === "w" || wsComponent.scheme[0] === "W") && (wsComponent.scheme[1] === "s" || wsComponent.scheme[1] === "S") && (wsComponent.scheme[2] === "s" || wsComponent.scheme[2] === "S"); + else return false; + } + /** @type {SchemeFn} */ + function httpParse(component) { + if (!component.host) component.error = component.error || "HTTP URIs must have a host."; + return component; + } + /** @type {SchemeFn} */ + function httpSerialize(component) { + const secure = String(component.scheme).toLowerCase() === "https"; + if (component.port === (secure ? 443 : 80) || component.port === "") component.port = void 0; + if (!component.path) component.path = "/"; + return component; + } + /** @type {SchemeFn} */ + function wsParse(wsComponent) { + wsComponent.secure = wsIsSecure(wsComponent); + wsComponent.resourceName = (wsComponent.path || "/") + (wsComponent.query ? "?" + wsComponent.query : ""); + wsComponent.path = void 0; + wsComponent.query = void 0; + return wsComponent; + } + /** @type {SchemeFn} */ + function wsSerialize(wsComponent) { + if (wsComponent.port === (wsIsSecure(wsComponent) ? 443 : 80) || wsComponent.port === "") wsComponent.port = void 0; + if (typeof wsComponent.secure === "boolean") { + wsComponent.scheme = wsComponent.secure ? "wss" : "ws"; + wsComponent.secure = void 0; + } + if (wsComponent.resourceName) { + const [path, query] = wsComponent.resourceName.split("?"); + wsComponent.path = path && path !== "/" ? path : void 0; + wsComponent.query = query; + wsComponent.resourceName = void 0; + } + wsComponent.fragment = void 0; + return wsComponent; + } + /** @type {SchemeFn} */ + function urnParse(urnComponent, options) { + if (!urnComponent.path) { + urnComponent.error = "URN can not be parsed"; + return urnComponent; + } + const matches = urnComponent.path.match(URN_REG); + if (matches) { + const scheme = options.scheme || urnComponent.scheme || "urn"; + urnComponent.nid = matches[1].toLowerCase(); + urnComponent.nss = matches[2]; + const schemeHandler = getSchemeHandler(`${scheme}:${options.nid || urnComponent.nid}`); + urnComponent.path = void 0; + if (schemeHandler) urnComponent = schemeHandler.parse(urnComponent, options); + } else urnComponent.error = urnComponent.error || "URN can not be parsed."; + return urnComponent; + } + /** @type {SchemeFn} */ + function urnSerialize(urnComponent, options) { + if (urnComponent.nid === void 0) throw new Error("URN without nid cannot be serialized"); + const scheme = options.scheme || urnComponent.scheme || "urn"; + const nid = urnComponent.nid.toLowerCase(); + const schemeHandler = getSchemeHandler(`${scheme}:${options.nid || nid}`); + if (schemeHandler) urnComponent = schemeHandler.serialize(urnComponent, options); + const uriComponent = urnComponent; + const nss = urnComponent.nss; + uriComponent.path = `${nid || options.nid}:${nss}`; + options.skipEscape = true; + return uriComponent; + } + /** @type {SchemeFn} */ + function urnuuidParse(urnComponent, options) { + const uuidComponent = urnComponent; + uuidComponent.uuid = uuidComponent.nss; + uuidComponent.nss = void 0; + if (!options.tolerant && (!uuidComponent.uuid || !isUUID(uuidComponent.uuid))) uuidComponent.error = uuidComponent.error || "UUID is not valid."; + return uuidComponent; + } + /** @type {SchemeFn} */ + function urnuuidSerialize(uuidComponent) { + const urnComponent = uuidComponent; + urnComponent.nss = (uuidComponent.uuid || "").toLowerCase(); + return urnComponent; + } + const http = { + scheme: "http", + domainHost: true, + parse: httpParse, + serialize: httpSerialize + }; + const https = { + scheme: "https", + domainHost: http.domainHost, + parse: httpParse, + serialize: httpSerialize + }; + const ws = { + scheme: "ws", + domainHost: true, + parse: wsParse, + serialize: wsSerialize + }; + const wss = { + scheme: "wss", + domainHost: ws.domainHost, + parse: ws.parse, + serialize: ws.serialize + }; + const urn = { + scheme: "urn", + parse: urnParse, + serialize: urnSerialize, + skipNormalize: true + }; + const urnuuid = { + scheme: "urn:uuid", + parse: urnuuidParse, + serialize: urnuuidSerialize, + skipNormalize: true + }; + const SCHEMES = { + http, + https, + ws, + wss, + urn, + "urn:uuid": urnuuid + }; + Object.setPrototypeOf(SCHEMES, null); + /** + * @param {string|undefined} scheme + * @returns {SchemeHandler|undefined} + */ + function getSchemeHandler(scheme) { + return scheme && (SCHEMES[scheme] || SCHEMES[scheme.toLowerCase()]) || void 0; + } + module.exports = { + wsIsSecure, + SCHEMES, + isValidSchemeName, + getSchemeHandler + }; +})); + +//#endregion +//#region ../../node_modules/.pnpm/fast-uri@3.1.0/node_modules/fast-uri/index.js +var require_fast_uri = /* @__PURE__ */ __commonJSMin(((exports, module) => { + const { normalizeIPv6, removeDotSegments, recomposeAuthority, normalizeComponentEncoding, isIPv4, nonSimpleDomain } = require_utils(); + const { SCHEMES, getSchemeHandler } = require_schemes(); + /** + * @template {import('./types/index').URIComponent|string} T + * @param {T} uri + * @param {import('./types/index').Options} [options] + * @returns {T} + */ + function normalize(uri, options) { + if (typeof uri === "string") uri = serialize(parse(uri, options), options); + else if (typeof uri === "object") uri = parse(serialize(uri, options), options); + return uri; + } + /** + * @param {string} baseURI + * @param {string} relativeURI + * @param {import('./types/index').Options} [options] + * @returns {string} + */ + function resolve(baseURI, relativeURI, options) { + const schemelessOptions = options ? Object.assign({ scheme: "null" }, options) : { scheme: "null" }; + const resolved = resolveComponent(parse(baseURI, schemelessOptions), parse(relativeURI, schemelessOptions), schemelessOptions, true); + schemelessOptions.skipEscape = true; + return serialize(resolved, schemelessOptions); + } + /** + * @param {import ('./types/index').URIComponent} base + * @param {import ('./types/index').URIComponent} relative + * @param {import('./types/index').Options} [options] + * @param {boolean} [skipNormalization=false] + * @returns {import ('./types/index').URIComponent} + */ + function resolveComponent(base, relative, options, skipNormalization) { + /** @type {import('./types/index').URIComponent} */ + const target = {}; + if (!skipNormalization) { + base = parse(serialize(base, options), options); + relative = parse(serialize(relative, options), options); + } + options = options || {}; + if (!options.tolerant && relative.scheme) { + target.scheme = relative.scheme; + target.userinfo = relative.userinfo; + target.host = relative.host; + target.port = relative.port; + target.path = removeDotSegments(relative.path || ""); + target.query = relative.query; + } else { + if (relative.userinfo !== void 0 || relative.host !== void 0 || relative.port !== void 0) { + target.userinfo = relative.userinfo; + target.host = relative.host; + target.port = relative.port; + target.path = removeDotSegments(relative.path || ""); + target.query = relative.query; + } else { + if (!relative.path) { + target.path = base.path; + if (relative.query !== void 0) target.query = relative.query; + else target.query = base.query; + } else { + if (relative.path[0] === "/") target.path = removeDotSegments(relative.path); + else { + if ((base.userinfo !== void 0 || base.host !== void 0 || base.port !== void 0) && !base.path) target.path = "/" + relative.path; + else if (!base.path) target.path = relative.path; + else target.path = base.path.slice(0, base.path.lastIndexOf("/") + 1) + relative.path; + target.path = removeDotSegments(target.path); + } + target.query = relative.query; + } + target.userinfo = base.userinfo; + target.host = base.host; + target.port = base.port; + } + target.scheme = base.scheme; + } + target.fragment = relative.fragment; + return target; + } + /** + * @param {import ('./types/index').URIComponent|string} uriA + * @param {import ('./types/index').URIComponent|string} uriB + * @param {import ('./types/index').Options} options + * @returns {boolean} + */ + function equal(uriA, uriB, options) { + if (typeof uriA === "string") { + uriA = unescape(uriA); + uriA = serialize(normalizeComponentEncoding(parse(uriA, options), true), { + ...options, + skipEscape: true + }); + } else if (typeof uriA === "object") uriA = serialize(normalizeComponentEncoding(uriA, true), { + ...options, + skipEscape: true + }); + if (typeof uriB === "string") { + uriB = unescape(uriB); + uriB = serialize(normalizeComponentEncoding(parse(uriB, options), true), { + ...options, + skipEscape: true + }); + } else if (typeof uriB === "object") uriB = serialize(normalizeComponentEncoding(uriB, true), { + ...options, + skipEscape: true + }); + return uriA.toLowerCase() === uriB.toLowerCase(); + } + /** + * @param {Readonly} cmpts + * @param {import('./types/index').Options} [opts] + * @returns {string} + */ + function serialize(cmpts, opts) { + const component = { + host: cmpts.host, + scheme: cmpts.scheme, + userinfo: cmpts.userinfo, + port: cmpts.port, + path: cmpts.path, + query: cmpts.query, + nid: cmpts.nid, + nss: cmpts.nss, + uuid: cmpts.uuid, + fragment: cmpts.fragment, + reference: cmpts.reference, + resourceName: cmpts.resourceName, + secure: cmpts.secure, + error: "" + }; + const options = Object.assign({}, opts); + const uriTokens = []; + const schemeHandler = getSchemeHandler(options.scheme || component.scheme); + if (schemeHandler && schemeHandler.serialize) schemeHandler.serialize(component, options); + if (component.path !== void 0) if (!options.skipEscape) { + component.path = escape(component.path); + if (component.scheme !== void 0) component.path = component.path.split("%3A").join(":"); + } else component.path = unescape(component.path); + if (options.reference !== "suffix" && component.scheme) uriTokens.push(component.scheme, ":"); + const authority = recomposeAuthority(component); + if (authority !== void 0) { + if (options.reference !== "suffix") uriTokens.push("//"); + uriTokens.push(authority); + if (component.path && component.path[0] !== "/") uriTokens.push("/"); + } + if (component.path !== void 0) { + let s = component.path; + if (!options.absolutePath && (!schemeHandler || !schemeHandler.absolutePath)) s = removeDotSegments(s); + if (authority === void 0 && s[0] === "/" && s[1] === "/") s = "/%2F" + s.slice(2); + uriTokens.push(s); + } + if (component.query !== void 0) uriTokens.push("?", component.query); + if (component.fragment !== void 0) uriTokens.push("#", component.fragment); + return uriTokens.join(""); + } + const URI_PARSE = /^(?:([^#/:?]+):)?(?:\/\/((?:([^#/?@]*)@)?(\[[^#/?\]]+\]|[^#/:?]*)(?::(\d*))?))?([^#?]*)(?:\?([^#]*))?(?:#((?:.|[\n\r])*))?/u; + /** + * @param {string} uri + * @param {import('./types/index').Options} [opts] + * @returns + */ + function parse(uri, opts) { + const options = Object.assign({}, opts); + /** @type {import('./types/index').URIComponent} */ + const parsed = { + scheme: void 0, + userinfo: void 0, + host: "", + port: void 0, + path: "", + query: void 0, + fragment: void 0 + }; + let isIP = false; + if (options.reference === "suffix") if (options.scheme) uri = options.scheme + ":" + uri; + else uri = "//" + uri; + const matches = uri.match(URI_PARSE); + if (matches) { + parsed.scheme = matches[1]; + parsed.userinfo = matches[3]; + parsed.host = matches[4]; + parsed.port = parseInt(matches[5], 10); + parsed.path = matches[6] || ""; + parsed.query = matches[7]; + parsed.fragment = matches[8]; + if (isNaN(parsed.port)) parsed.port = matches[5]; + if (parsed.host) if (isIPv4(parsed.host) === false) { + const ipv6result = normalizeIPv6(parsed.host); + parsed.host = ipv6result.host.toLowerCase(); + isIP = ipv6result.isIPV6; + } else isIP = true; + if (parsed.scheme === void 0 && parsed.userinfo === void 0 && parsed.host === void 0 && parsed.port === void 0 && parsed.query === void 0 && !parsed.path) parsed.reference = "same-document"; + else if (parsed.scheme === void 0) parsed.reference = "relative"; + else if (parsed.fragment === void 0) parsed.reference = "absolute"; + else parsed.reference = "uri"; + if (options.reference && options.reference !== "suffix" && options.reference !== parsed.reference) parsed.error = parsed.error || "URI is not a " + options.reference + " reference."; + const schemeHandler = getSchemeHandler(options.scheme || parsed.scheme); + if (!options.unicodeSupport && (!schemeHandler || !schemeHandler.unicodeSupport)) { + if (parsed.host && (options.domainHost || schemeHandler && schemeHandler.domainHost) && isIP === false && nonSimpleDomain(parsed.host)) try { + parsed.host = URL.domainToASCII(parsed.host.toLowerCase()); + } catch (e) { + parsed.error = parsed.error || "Host's domain name can not be converted to ASCII: " + e; + } + } + if (!schemeHandler || schemeHandler && !schemeHandler.skipNormalize) { + if (uri.indexOf("%") !== -1) { + if (parsed.scheme !== void 0) parsed.scheme = unescape(parsed.scheme); + if (parsed.host !== void 0) parsed.host = unescape(parsed.host); + } + if (parsed.path) parsed.path = escape(unescape(parsed.path)); + if (parsed.fragment) parsed.fragment = encodeURI(decodeURIComponent(parsed.fragment)); + } + if (schemeHandler && schemeHandler.parse) schemeHandler.parse(parsed, options); + } else parsed.error = parsed.error || "URI can not be parsed."; + return parsed; + } + const fastUri = { + SCHEMES, + normalize, + resolve, + resolveComponent, + equal, + serialize, + parse + }; + module.exports = fastUri; + module.exports.default = fastUri; + module.exports.fastUri = fastUri; +})); + +//#endregion +//#region ../../node_modules/.pnpm/ajv@8.18.0/node_modules/ajv/dist/runtime/uri.js +var require_uri = /* @__PURE__ */ __commonJSMin(((exports) => { + Object.defineProperty(exports, "__esModule", { value: true }); + const uri = require_fast_uri(); + uri.code = "require(\"ajv/dist/runtime/uri\").default"; + exports.default = uri; +})); + +//#endregion +//#region ../../node_modules/.pnpm/ajv@8.18.0/node_modules/ajv/dist/core.js +var require_core$3 = /* @__PURE__ */ __commonJSMin(((exports) => { + Object.defineProperty(exports, "__esModule", { value: true }); + exports.CodeGen = exports.Name = exports.nil = exports.stringify = exports.str = exports._ = exports.KeywordCxt = void 0; + var validate_1 = require_validate(); + Object.defineProperty(exports, "KeywordCxt", { + enumerable: true, + get: function() { + return validate_1.KeywordCxt; + } + }); + var codegen_1 = require_codegen(); + Object.defineProperty(exports, "_", { + enumerable: true, + get: function() { + return codegen_1._; + } + }); + Object.defineProperty(exports, "str", { + enumerable: true, + get: function() { + return codegen_1.str; + } + }); + Object.defineProperty(exports, "stringify", { + enumerable: true, + get: function() { + return codegen_1.stringify; + } + }); + Object.defineProperty(exports, "nil", { + enumerable: true, + get: function() { + return codegen_1.nil; + } + }); + Object.defineProperty(exports, "Name", { + enumerable: true, + get: function() { + return codegen_1.Name; + } + }); + Object.defineProperty(exports, "CodeGen", { + enumerable: true, + get: function() { + return codegen_1.CodeGen; + } + }); + const validation_error_1 = require_validation_error(); + const ref_error_1 = require_ref_error(); + const rules_1 = require_rules(); + const compile_1 = require_compile(); + const codegen_2 = require_codegen(); + const resolve_1 = require_resolve(); + const dataType_1 = require_dataType(); + const util_1 = require_util(); + const $dataRefSchema = require_data(); + const uri_1 = require_uri(); + const defaultRegExp = (str, flags) => new RegExp(str, flags); + defaultRegExp.code = "new RegExp"; + const META_IGNORE_OPTIONS = [ + "removeAdditional", + "useDefaults", + "coerceTypes" + ]; + const EXT_SCOPE_NAMES = new Set([ + "validate", + "serialize", + "parse", + "wrapper", + "root", + "schema", + "keyword", + "pattern", + "formats", + "validate$data", + "func", + "obj", + "Error" + ]); + const removedOptions = { + 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." + }; + const deprecatedOptions = { + ignoreKeywordsWithRef: "", + jsPropertySyntax: "", + unicode: "\"minLength\"/\"maxLength\" account for unicode characters by default." + }; + const MAX_EXPRESSION = 200; + function requiredOptions(o) { + var _a, _b, _c, _d, _e, _f, _g, _h, _j, _k, _l, _m, _o, _p, _q, _r, _s, _t, _u, _v, _w, _x, _y, _z, _0; + const s = o.strict; + const _optz = (_a = o.code) === null || _a === void 0 ? void 0 : _a.optimize; + const optimize = _optz === true || _optz === void 0 ? 1 : _optz || 0; + const regExp = (_c = (_b = o.code) === null || _b === void 0 ? void 0 : _b.regExp) !== null && _c !== void 0 ? _c : defaultRegExp; + const uriResolver = (_d = o.uriResolver) !== null && _d !== void 0 ? _d : uri_1.default; + return { + strictSchema: (_f = (_e = o.strictSchema) !== null && _e !== void 0 ? _e : s) !== null && _f !== void 0 ? _f : true, + strictNumbers: (_h = (_g = o.strictNumbers) !== null && _g !== void 0 ? _g : s) !== null && _h !== void 0 ? _h : true, + strictTypes: (_k = (_j = o.strictTypes) !== null && _j !== void 0 ? _j : s) !== null && _k !== void 0 ? _k : "log", + strictTuples: (_m = (_l = o.strictTuples) !== null && _l !== void 0 ? _l : s) !== null && _m !== void 0 ? _m : "log", + strictRequired: (_p = (_o = o.strictRequired) !== null && _o !== void 0 ? _o : s) !== null && _p !== void 0 ? _p : false, + code: o.code ? { + ...o.code, + optimize, + regExp + } : { + optimize, + regExp + }, + loopRequired: (_q = o.loopRequired) !== null && _q !== void 0 ? _q : MAX_EXPRESSION, + loopEnum: (_r = o.loopEnum) !== null && _r !== void 0 ? _r : MAX_EXPRESSION, + meta: (_s = o.meta) !== null && _s !== void 0 ? _s : true, + messages: (_t = o.messages) !== null && _t !== void 0 ? _t : true, + inlineRefs: (_u = o.inlineRefs) !== null && _u !== void 0 ? _u : true, + schemaId: (_v = o.schemaId) !== null && _v !== void 0 ? _v : "$id", + addUsedSchema: (_w = o.addUsedSchema) !== null && _w !== void 0 ? _w : true, + validateSchema: (_x = o.validateSchema) !== null && _x !== void 0 ? _x : true, + validateFormats: (_y = o.validateFormats) !== null && _y !== void 0 ? _y : true, + unicodeRegExp: (_z = o.unicodeRegExp) !== null && _z !== void 0 ? _z : true, + int32range: (_0 = o.int32range) !== null && _0 !== void 0 ? _0 : true, + uriResolver + }; + } + var Ajv = class { + constructor(opts = {}) { + this.schemas = {}; + this.refs = {}; + this.formats = {}; + this._compilations = /* @__PURE__ */ new Set(); + this._loading = {}; + this._cache = /* @__PURE__ */ new Map(); + opts = this.opts = { + ...opts, + ...requiredOptions(opts) + }; + const { es5, lines } = this.opts.code; + this.scope = new codegen_2.ValueScope({ + scope: {}, + prefixes: EXT_SCOPE_NAMES, + es5, + lines + }); + this.logger = getLogger(opts.logger); + const formatOpt = opts.validateFormats; + opts.validateFormats = false; + this.RULES = (0, rules_1.getRules)(); + checkOptions.call(this, removedOptions, opts, "NOT SUPPORTED"); + checkOptions.call(this, deprecatedOptions, opts, "DEPRECATED", "warn"); + this._metaOpts = getMetaSchemaOptions.call(this); + if (opts.formats) addInitialFormats.call(this); + this._addVocabularies(); + this._addDefaultMetaSchema(); + if (opts.keywords) addInitialKeywords.call(this, opts.keywords); + if (typeof opts.meta == "object") this.addMetaSchema(opts.meta); + addInitialSchemas.call(this); + opts.validateFormats = formatOpt; + } + _addVocabularies() { + this.addKeyword("$async"); + } + _addDefaultMetaSchema() { + const { $data, meta, schemaId } = this.opts; + let _dataRefSchema = $dataRefSchema; + if (schemaId === "id") { + _dataRefSchema = { ...$dataRefSchema }; + _dataRefSchema.id = _dataRefSchema.$id; + delete _dataRefSchema.$id; + } + if (meta && $data) this.addMetaSchema(_dataRefSchema, _dataRefSchema[schemaId], false); + } + defaultMeta() { + const { meta, schemaId } = this.opts; + return this.opts.defaultMeta = typeof meta == "object" ? meta[schemaId] || meta : void 0; + } + validate(schemaKeyRef, data) { + let v; + if (typeof schemaKeyRef == "string") { + v = this.getSchema(schemaKeyRef); + if (!v) throw new Error(`no schema with key or ref "${schemaKeyRef}"`); + } else v = this.compile(schemaKeyRef); + const valid = v(data); + if (!("$async" in v)) this.errors = v.errors; + return valid; + } + compile(schema, _meta) { + const sch = this._addSchema(schema, _meta); + return sch.validate || this._compileSchemaEnv(sch); + } + compileAsync(schema, meta) { + if (typeof this.opts.loadSchema != "function") throw new Error("options.loadSchema should be a function"); + const { loadSchema } = this.opts; + return runCompileAsync.call(this, schema, meta); + async function runCompileAsync(_schema, _meta) { + await loadMetaSchema.call(this, _schema.$schema); + const sch = this._addSchema(_schema, _meta); + return sch.validate || _compileAsync.call(this, sch); + } + async function loadMetaSchema($ref) { + if ($ref && !this.getSchema($ref)) await runCompileAsync.call(this, { $ref }, true); + } + async function _compileAsync(sch) { + try { + return this._compileSchemaEnv(sch); + } catch (e) { + if (!(e instanceof ref_error_1.default)) throw e; + checkLoaded.call(this, e); + await loadMissingSchema.call(this, e.missingSchema); + return _compileAsync.call(this, sch); + } + } + function checkLoaded({ missingSchema: ref, missingRef }) { + if (this.refs[ref]) throw new Error(`AnySchema ${ref} is loaded but ${missingRef} cannot be resolved`); + } + async function loadMissingSchema(ref) { + const _schema = await _loadSchema.call(this, ref); + if (!this.refs[ref]) await loadMetaSchema.call(this, _schema.$schema); + if (!this.refs[ref]) this.addSchema(_schema, ref, meta); + } + async function _loadSchema(ref) { + const p = this._loading[ref]; + if (p) return p; + try { + return await (this._loading[ref] = loadSchema(ref)); + } finally { + delete this._loading[ref]; + } + } + } + addSchema(schema, key, _meta, _validateSchema = this.opts.validateSchema) { + if (Array.isArray(schema)) { + for (const sch of schema) this.addSchema(sch, void 0, _meta, _validateSchema); + return this; + } + let id; + if (typeof schema === "object") { + const { schemaId } = this.opts; + id = schema[schemaId]; + if (id !== void 0 && typeof id != "string") throw new Error(`schema ${schemaId} must be string`); + } + key = (0, resolve_1.normalizeId)(key || id); + this._checkUnique(key); + this.schemas[key] = this._addSchema(schema, _meta, key, _validateSchema, true); + return this; + } + addMetaSchema(schema, key, _validateSchema = this.opts.validateSchema) { + this.addSchema(schema, key, true, _validateSchema); + return this; + } + validateSchema(schema, throwOrLogError) { + if (typeof schema == "boolean") return true; + let $schema; + $schema = schema.$schema; + if ($schema !== void 0 && typeof $schema != "string") throw new Error("$schema must be a string"); + $schema = $schema || this.opts.defaultMeta || this.defaultMeta(); + if (!$schema) { + this.logger.warn("meta-schema not available"); + this.errors = null; + return true; + } + const valid = this.validate($schema, schema); + if (!valid && throwOrLogError) { + const message = "schema is invalid: " + this.errorsText(); + if (this.opts.validateSchema === "log") this.logger.error(message); + else throw new Error(message); + } + return valid; + } + getSchema(keyRef) { + let sch; + while (typeof (sch = getSchEnv.call(this, keyRef)) == "string") keyRef = sch; + if (sch === void 0) { + const { schemaId } = this.opts; + const root = new compile_1.SchemaEnv({ + schema: {}, + schemaId + }); + sch = compile_1.resolveSchema.call(this, root, keyRef); + if (!sch) return; + this.refs[keyRef] = sch; + } + return sch.validate || this._compileSchemaEnv(sch); + } + removeSchema(schemaKeyRef) { + if (schemaKeyRef instanceof RegExp) { + this._removeAllSchemas(this.schemas, schemaKeyRef); + this._removeAllSchemas(this.refs, schemaKeyRef); + return this; + } + switch (typeof schemaKeyRef) { + case "undefined": + this._removeAllSchemas(this.schemas); + this._removeAllSchemas(this.refs); + this._cache.clear(); + return this; + case "string": { + const sch = getSchEnv.call(this, schemaKeyRef); + if (typeof sch == "object") this._cache.delete(sch.schema); + delete this.schemas[schemaKeyRef]; + delete this.refs[schemaKeyRef]; + return this; + } + case "object": { + const cacheKey = schemaKeyRef; + this._cache.delete(cacheKey); + let id = schemaKeyRef[this.opts.schemaId]; + if (id) { + id = (0, resolve_1.normalizeId)(id); + delete this.schemas[id]; + delete this.refs[id]; + } + return this; + } + default: throw new Error("ajv.removeSchema: invalid parameter"); + } + } + addVocabulary(definitions) { + for (const def of definitions) this.addKeyword(def); + return this; + } + addKeyword(kwdOrDef, def) { + let keyword; + if (typeof kwdOrDef == "string") { + keyword = kwdOrDef; + if (typeof def == "object") { + this.logger.warn("these parameters are deprecated, see docs for addKeyword"); + def.keyword = keyword; + } + } else if (typeof kwdOrDef == "object" && def === void 0) { + def = kwdOrDef; + keyword = def.keyword; + if (Array.isArray(keyword) && !keyword.length) throw new Error("addKeywords: keyword must be string or non-empty array"); + } else throw new Error("invalid addKeywords parameters"); + checkKeyword.call(this, keyword, def); + if (!def) { + (0, util_1.eachItem)(keyword, (kwd) => addRule.call(this, kwd)); + return this; + } + keywordMetaschema.call(this, def); + const definition = { + ...def, + type: (0, dataType_1.getJSONTypes)(def.type), + schemaType: (0, dataType_1.getJSONTypes)(def.schemaType) + }; + (0, util_1.eachItem)(keyword, definition.type.length === 0 ? (k) => addRule.call(this, k, definition) : (k) => definition.type.forEach((t) => addRule.call(this, k, definition, t))); + return this; + } + getKeyword(keyword) { + const rule = this.RULES.all[keyword]; + return typeof rule == "object" ? rule.definition : !!rule; + } + removeKeyword(keyword) { + const { RULES } = this; + delete RULES.keywords[keyword]; + delete RULES.all[keyword]; + for (const group of RULES.rules) { + const i = group.rules.findIndex((rule) => rule.keyword === keyword); + if (i >= 0) group.rules.splice(i, 1); + } + return this; + } + addFormat(name, format) { + if (typeof format == "string") format = new RegExp(format); + this.formats[name] = format; + return this; + } + errorsText(errors = this.errors, { separator = ", ", dataVar = "data" } = {}) { + if (!errors || errors.length === 0) return "No errors"; + return errors.map((e) => `${dataVar}${e.instancePath} ${e.message}`).reduce((text, msg) => text + separator + msg); + } + $dataMetaSchema(metaSchema, keywordsJsonPointers) { + const rules = this.RULES.all; + metaSchema = JSON.parse(JSON.stringify(metaSchema)); + for (const jsonPointer of keywordsJsonPointers) { + const segments = jsonPointer.split("/").slice(1); + let keywords = metaSchema; + for (const seg of segments) keywords = keywords[seg]; + for (const key in rules) { + const rule = rules[key]; + if (typeof rule != "object") continue; + const { $data } = rule.definition; + const schema = keywords[key]; + if ($data && schema) keywords[key] = schemaOrData(schema); + } + } + return metaSchema; + } + _removeAllSchemas(schemas, regex) { + for (const keyRef in schemas) { + const sch = schemas[keyRef]; + if (!regex || regex.test(keyRef)) { + if (typeof sch == "string") delete schemas[keyRef]; + else if (sch && !sch.meta) { + this._cache.delete(sch.schema); + delete schemas[keyRef]; + } + } + } + } + _addSchema(schema, meta, baseId, validateSchema = this.opts.validateSchema, addSchema = this.opts.addUsedSchema) { + let id; + const { schemaId } = this.opts; + if (typeof schema == "object") id = schema[schemaId]; + else if (this.opts.jtd) throw new Error("schema must be object"); + else if (typeof schema != "boolean") throw new Error("schema must be object or boolean"); + let sch = this._cache.get(schema); + if (sch !== void 0) return sch; + baseId = (0, resolve_1.normalizeId)(id || baseId); + const localRefs = resolve_1.getSchemaRefs.call(this, schema, baseId); + sch = new compile_1.SchemaEnv({ + schema, + schemaId, + meta, + baseId, + localRefs + }); + this._cache.set(sch.schema, sch); + if (addSchema && !baseId.startsWith("#")) { + if (baseId) this._checkUnique(baseId); + this.refs[baseId] = sch; + } + if (validateSchema) this.validateSchema(schema, true); + return sch; + } + _checkUnique(id) { + if (this.schemas[id] || this.refs[id]) throw new Error(`schema with key or id "${id}" already exists`); + } + _compileSchemaEnv(sch) { + if (sch.meta) this._compileMetaSchema(sch); + else compile_1.compileSchema.call(this, sch); + /* istanbul ignore if */ + if (!sch.validate) throw new Error("ajv implementation error"); + return sch.validate; + } + _compileMetaSchema(sch) { + const currentOpts = this.opts; + this.opts = this._metaOpts; + try { + compile_1.compileSchema.call(this, sch); + } finally { + this.opts = currentOpts; + } + } + }; + Ajv.ValidationError = validation_error_1.default; + Ajv.MissingRefError = ref_error_1.default; + exports.default = Ajv; + function checkOptions(checkOpts, options, msg, log = "error") { + for (const key in checkOpts) { + const opt = key; + if (opt in options) this.logger[log](`${msg}: option ${key}. ${checkOpts[opt]}`); + } + } + function getSchEnv(keyRef) { + keyRef = (0, resolve_1.normalizeId)(keyRef); + return this.schemas[keyRef] || this.refs[keyRef]; + } + function addInitialSchemas() { + const optsSchemas = this.opts.schemas; + if (!optsSchemas) return; + if (Array.isArray(optsSchemas)) this.addSchema(optsSchemas); + else for (const key in optsSchemas) this.addSchema(optsSchemas[key], key); + } + function addInitialFormats() { + for (const name in this.opts.formats) { + const format = this.opts.formats[name]; + if (format) this.addFormat(name, format); + } + } + function addInitialKeywords(defs) { + if (Array.isArray(defs)) { + this.addVocabulary(defs); + return; + } + this.logger.warn("keywords option as map is deprecated, pass array"); + for (const keyword in defs) { + const def = defs[keyword]; + if (!def.keyword) def.keyword = keyword; + this.addKeyword(def); + } + } + function getMetaSchemaOptions() { + const metaOpts = { ...this.opts }; + for (const opt of META_IGNORE_OPTIONS) delete metaOpts[opt]; + return metaOpts; + } + const noLogs = { + log() {}, + warn() {}, + error() {} + }; + function getLogger(logger) { + if (logger === false) return noLogs; + if (logger === void 0) return console; + if (logger.log && logger.warn && logger.error) return logger; + throw new Error("logger must implement log, warn and error methods"); + } + const KEYWORD_NAME = /^[a-z_$][a-z0-9_$:-]*$/i; + function checkKeyword(keyword, def) { + const { RULES } = this; + (0, util_1.eachItem)(keyword, (kwd) => { + if (RULES.keywords[kwd]) throw new Error(`Keyword ${kwd} is already defined`); + if (!KEYWORD_NAME.test(kwd)) throw new Error(`Keyword ${kwd} has invalid name`); + }); + if (!def) return; + if (def.$data && !("code" in def || "validate" in def)) throw new Error("$data keyword must have \"code\" or \"validate\" function"); + } + function addRule(keyword, definition, dataType) { + var _a; + const post = definition === null || definition === void 0 ? void 0 : definition.post; + if (dataType && post) throw new Error("keyword with \"post\" flag cannot have \"type\""); + const { RULES } = this; + let ruleGroup = post ? RULES.post : RULES.rules.find(({ type: t }) => t === dataType); + if (!ruleGroup) { + ruleGroup = { + type: dataType, + rules: [] + }; + RULES.rules.push(ruleGroup); + } + RULES.keywords[keyword] = true; + if (!definition) return; + const rule = { + keyword, + definition: { + ...definition, + type: (0, dataType_1.getJSONTypes)(definition.type), + schemaType: (0, dataType_1.getJSONTypes)(definition.schemaType) + } + }; + if (definition.before) addBeforeRule.call(this, ruleGroup, rule, definition.before); + else ruleGroup.rules.push(rule); + RULES.all[keyword] = rule; + (_a = definition.implements) === null || _a === void 0 || _a.forEach((kwd) => this.addKeyword(kwd)); + } + function addBeforeRule(ruleGroup, rule, before) { + const i = ruleGroup.rules.findIndex((_rule) => _rule.keyword === before); + if (i >= 0) ruleGroup.rules.splice(i, 0, rule); + else { + ruleGroup.rules.push(rule); + this.logger.warn(`rule ${before} is not defined`); + } + } + function keywordMetaschema(def) { + let { metaSchema } = def; + if (metaSchema === void 0) return; + if (def.$data && this.opts.$data) metaSchema = schemaOrData(metaSchema); + def.validateSchema = this.compile(metaSchema, true); + } + const $dataRef = { $ref: "https://raw.githubusercontent.com/ajv-validator/ajv/master/lib/refs/data.json#" }; + function schemaOrData(schema) { + return { anyOf: [schema, $dataRef] }; + } +})); + +//#endregion +//#region ../../node_modules/.pnpm/ajv@8.18.0/node_modules/ajv/dist/vocabularies/core/id.js +var require_id = /* @__PURE__ */ __commonJSMin(((exports) => { + Object.defineProperty(exports, "__esModule", { value: true }); + const def = { + keyword: "id", + code() { + throw new Error("NOT SUPPORTED: keyword \"id\", use \"$id\" for schema ID"); + } + }; + exports.default = def; +})); + +//#endregion +//#region ../../node_modules/.pnpm/ajv@8.18.0/node_modules/ajv/dist/vocabularies/core/ref.js +var require_ref = /* @__PURE__ */ __commonJSMin(((exports) => { + Object.defineProperty(exports, "__esModule", { value: true }); + exports.callRef = exports.getValidate = void 0; + const ref_error_1 = require_ref_error(); + const code_1 = require_code(); + const codegen_1 = require_codegen(); + const names_1 = require_names(); + const compile_1 = require_compile(); + const util_1 = require_util(); + const def = { + keyword: "$ref", + schemaType: "string", + code(cxt) { + const { gen, schema: $ref, it } = cxt; + const { baseId, schemaEnv: env, validateName, opts, self } = it; + const { root } = env; + if (($ref === "#" || $ref === "#/") && baseId === root.baseId) return callRootRef(); + const schOrEnv = compile_1.resolveRef.call(self, root, baseId, $ref); + if (schOrEnv === void 0) throw new ref_error_1.default(it.opts.uriResolver, baseId, $ref); + if (schOrEnv instanceof compile_1.SchemaEnv) return callValidate(schOrEnv); + return inlineRefSchema(schOrEnv); + function callRootRef() { + if (env === root) return callRef(cxt, validateName, env, env.$async); + const rootName = gen.scopeValue("root", { ref: root }); + return callRef(cxt, (0, codegen_1._)`${rootName}.validate`, root, root.$async); + } + function callValidate(sch) { + callRef(cxt, getValidate(cxt, sch), sch, sch.$async); + } + function inlineRefSchema(sch) { + const schName = gen.scopeValue("schema", opts.code.source === true ? { + ref: sch, + code: (0, codegen_1.stringify)(sch) + } : { ref: sch }); + const valid = gen.name("valid"); + const schCxt = cxt.subschema({ + schema: sch, + dataTypes: [], + schemaPath: codegen_1.nil, + topSchemaRef: schName, + errSchemaPath: $ref + }, valid); + cxt.mergeEvaluated(schCxt); + cxt.ok(valid); + } + } + }; + function getValidate(cxt, sch) { + const { gen } = cxt; + return sch.validate ? gen.scopeValue("validate", { ref: sch.validate }) : (0, codegen_1._)`${gen.scopeValue("wrapper", { ref: sch })}.validate`; + } + exports.getValidate = getValidate; + function callRef(cxt, v, sch, $async) { + const { gen, it } = cxt; + const { allErrors, schemaEnv: env, opts } = it; + const passCxt = opts.passContext ? names_1.default.this : codegen_1.nil; + if ($async) callAsyncRef(); + else callSyncRef(); + function callAsyncRef() { + if (!env.$async) throw new Error("async schema referenced by sync schema"); + const valid = gen.let("valid"); + gen.try(() => { + gen.code((0, codegen_1._)`await ${(0, code_1.callValidateCode)(cxt, v, passCxt)}`); + addEvaluatedFrom(v); + if (!allErrors) gen.assign(valid, true); + }, (e) => { + gen.if((0, codegen_1._)`!(${e} instanceof ${it.ValidationError})`, () => gen.throw(e)); + addErrorsFrom(e); + if (!allErrors) gen.assign(valid, false); + }); + cxt.ok(valid); + } + function callSyncRef() { + cxt.result((0, code_1.callValidateCode)(cxt, v, passCxt), () => addEvaluatedFrom(v), () => addErrorsFrom(v)); + } + function addErrorsFrom(source) { + const errs = (0, codegen_1._)`${source}.errors`; + gen.assign(names_1.default.vErrors, (0, codegen_1._)`${names_1.default.vErrors} === null ? ${errs} : ${names_1.default.vErrors}.concat(${errs})`); + gen.assign(names_1.default.errors, (0, codegen_1._)`${names_1.default.vErrors}.length`); + } + function addEvaluatedFrom(source) { + var _a; + if (!it.opts.unevaluated) return; + const schEvaluated = (_a = sch === null || sch === void 0 ? void 0 : sch.validate) === null || _a === void 0 ? void 0 : _a.evaluated; + if (it.props !== true) if (schEvaluated && !schEvaluated.dynamicProps) { + if (schEvaluated.props !== void 0) it.props = util_1.mergeEvaluated.props(gen, schEvaluated.props, it.props); + } else { + const props = gen.var("props", (0, codegen_1._)`${source}.evaluated.props`); + it.props = util_1.mergeEvaluated.props(gen, props, it.props, codegen_1.Name); + } + if (it.items !== true) if (schEvaluated && !schEvaluated.dynamicItems) { + if (schEvaluated.items !== void 0) it.items = util_1.mergeEvaluated.items(gen, schEvaluated.items, it.items); + } else { + const items = gen.var("items", (0, codegen_1._)`${source}.evaluated.items`); + it.items = util_1.mergeEvaluated.items(gen, items, it.items, codegen_1.Name); + } + } + } + exports.callRef = callRef; + exports.default = def; +})); + +//#endregion +//#region ../../node_modules/.pnpm/ajv@8.18.0/node_modules/ajv/dist/vocabularies/core/index.js +var require_core$2 = /* @__PURE__ */ __commonJSMin(((exports) => { + Object.defineProperty(exports, "__esModule", { value: true }); + const id_1 = require_id(); + const ref_1 = require_ref(); + const core = [ + "$schema", + "$id", + "$defs", + "$vocabulary", + { keyword: "$comment" }, + "definitions", + id_1.default, + ref_1.default + ]; + exports.default = core; +})); + +//#endregion +//#region ../../node_modules/.pnpm/ajv@8.18.0/node_modules/ajv/dist/vocabularies/validation/limitNumber.js +var require_limitNumber = /* @__PURE__ */ __commonJSMin(((exports) => { + Object.defineProperty(exports, "__esModule", { value: true }); + const codegen_1 = require_codegen(); + const ops = codegen_1.operators; + const KWDs = { + maximum: { + okStr: "<=", + ok: ops.LTE, + fail: ops.GT + }, + minimum: { + okStr: ">=", + ok: ops.GTE, + fail: ops.LT + }, + exclusiveMaximum: { + okStr: "<", + ok: ops.LT, + fail: ops.GTE + }, + exclusiveMinimum: { + okStr: ">", + ok: ops.GT, + fail: ops.LTE + } + }; + const def = { + keyword: Object.keys(KWDs), + type: "number", + schemaType: "number", + $data: true, + error: { + message: ({ keyword, schemaCode }) => (0, codegen_1.str)`must be ${KWDs[keyword].okStr} ${schemaCode}`, + params: ({ keyword, schemaCode }) => (0, codegen_1._)`{comparison: ${KWDs[keyword].okStr}, limit: ${schemaCode}}` + }, + code(cxt) { + const { keyword, data, schemaCode } = cxt; + cxt.fail$data((0, codegen_1._)`${data} ${KWDs[keyword].fail} ${schemaCode} || isNaN(${data})`); + } + }; + exports.default = def; +})); + +//#endregion +//#region ../../node_modules/.pnpm/ajv@8.18.0/node_modules/ajv/dist/vocabularies/validation/multipleOf.js +var require_multipleOf = /* @__PURE__ */ __commonJSMin(((exports) => { + Object.defineProperty(exports, "__esModule", { value: true }); + const codegen_1 = require_codegen(); + const def = { + keyword: "multipleOf", + type: "number", + schemaType: "number", + $data: true, + error: { + message: ({ schemaCode }) => (0, codegen_1.str)`must be multiple of ${schemaCode}`, + params: ({ schemaCode }) => (0, codegen_1._)`{multipleOf: ${schemaCode}}` + }, + code(cxt) { + const { gen, data, schemaCode, it } = cxt; + const prec = it.opts.multipleOfPrecision; + const res = gen.let("res"); + const invalid = prec ? (0, codegen_1._)`Math.abs(Math.round(${res}) - ${res}) > 1e-${prec}` : (0, codegen_1._)`${res} !== parseInt(${res})`; + cxt.fail$data((0, codegen_1._)`(${schemaCode} === 0 || (${res} = ${data}/${schemaCode}, ${invalid}))`); + } + }; + exports.default = def; +})); + +//#endregion +//#region ../../node_modules/.pnpm/ajv@8.18.0/node_modules/ajv/dist/runtime/ucs2length.js +var require_ucs2length = /* @__PURE__ */ __commonJSMin(((exports) => { + Object.defineProperty(exports, "__esModule", { value: true }); + function ucs2length(str) { + const len = str.length; + let length = 0; + let pos = 0; + let value; + while (pos < len) { + length++; + value = str.charCodeAt(pos++); + if (value >= 55296 && value <= 56319 && pos < len) { + value = str.charCodeAt(pos); + if ((value & 64512) === 56320) pos++; + } + } + return length; + } + exports.default = ucs2length; + ucs2length.code = "require(\"ajv/dist/runtime/ucs2length\").default"; +})); + +//#endregion +//#region ../../node_modules/.pnpm/ajv@8.18.0/node_modules/ajv/dist/vocabularies/validation/limitLength.js +var require_limitLength = /* @__PURE__ */ __commonJSMin(((exports) => { + Object.defineProperty(exports, "__esModule", { value: true }); + const codegen_1 = require_codegen(); + const util_1 = require_util(); + const ucs2length_1 = require_ucs2length(); + const def = { + keyword: ["maxLength", "minLength"], + type: "string", + schemaType: "number", + $data: true, + error: { + message({ keyword, schemaCode }) { + const comp = keyword === "maxLength" ? "more" : "fewer"; + return (0, codegen_1.str)`must NOT have ${comp} than ${schemaCode} characters`; + }, + params: ({ schemaCode }) => (0, codegen_1._)`{limit: ${schemaCode}}` + }, + code(cxt) { + const { keyword, data, schemaCode, it } = cxt; + const op = keyword === "maxLength" ? codegen_1.operators.GT : codegen_1.operators.LT; + const len = it.opts.unicode === false ? (0, codegen_1._)`${data}.length` : (0, codegen_1._)`${(0, util_1.useFunc)(cxt.gen, ucs2length_1.default)}(${data})`; + cxt.fail$data((0, codegen_1._)`${len} ${op} ${schemaCode}`); + } + }; + exports.default = def; +})); + +//#endregion +//#region ../../node_modules/.pnpm/ajv@8.18.0/node_modules/ajv/dist/vocabularies/validation/pattern.js +var require_pattern = /* @__PURE__ */ __commonJSMin(((exports) => { + Object.defineProperty(exports, "__esModule", { value: true }); + const code_1 = require_code(); + const util_1 = require_util(); + const codegen_1 = require_codegen(); + const def = { + keyword: "pattern", + type: "string", + schemaType: "string", + $data: true, + error: { + message: ({ schemaCode }) => (0, codegen_1.str)`must match pattern "${schemaCode}"`, + params: ({ schemaCode }) => (0, codegen_1._)`{pattern: ${schemaCode}}` + }, + code(cxt) { + const { gen, data, $data, schema, schemaCode, it } = cxt; + const u = it.opts.unicodeRegExp ? "u" : ""; + if ($data) { + const { regExp } = it.opts.code; + const regExpCode = regExp.code === "new RegExp" ? (0, codegen_1._)`new RegExp` : (0, util_1.useFunc)(gen, regExp); + const valid = gen.let("valid"); + gen.try(() => gen.assign(valid, (0, codegen_1._)`${regExpCode}(${schemaCode}, ${u}).test(${data})`), () => gen.assign(valid, false)); + cxt.fail$data((0, codegen_1._)`!${valid}`); + } else { + const regExp = (0, code_1.usePattern)(cxt, schema); + cxt.fail$data((0, codegen_1._)`!${regExp}.test(${data})`); + } + } + }; + exports.default = def; +})); + +//#endregion +//#region ../../node_modules/.pnpm/ajv@8.18.0/node_modules/ajv/dist/vocabularies/validation/limitProperties.js +var require_limitProperties = /* @__PURE__ */ __commonJSMin(((exports) => { + Object.defineProperty(exports, "__esModule", { value: true }); + const codegen_1 = require_codegen(); + const def = { + keyword: ["maxProperties", "minProperties"], + type: "object", + schemaType: "number", + $data: true, + error: { + message({ keyword, schemaCode }) { + const comp = keyword === "maxProperties" ? "more" : "fewer"; + return (0, codegen_1.str)`must NOT have ${comp} than ${schemaCode} properties`; + }, + params: ({ schemaCode }) => (0, codegen_1._)`{limit: ${schemaCode}}` + }, + code(cxt) { + const { keyword, data, schemaCode } = cxt; + const op = keyword === "maxProperties" ? codegen_1.operators.GT : codegen_1.operators.LT; + cxt.fail$data((0, codegen_1._)`Object.keys(${data}).length ${op} ${schemaCode}`); + } + }; + exports.default = def; +})); + +//#endregion +//#region ../../node_modules/.pnpm/ajv@8.18.0/node_modules/ajv/dist/vocabularies/validation/required.js +var require_required = /* @__PURE__ */ __commonJSMin(((exports) => { + Object.defineProperty(exports, "__esModule", { value: true }); + const code_1 = require_code(); + const codegen_1 = require_codegen(); + const util_1 = require_util(); + const def = { + keyword: "required", + type: "object", + schemaType: "array", + $data: true, + error: { + message: ({ params: { missingProperty } }) => (0, codegen_1.str)`must have required property '${missingProperty}'`, + params: ({ params: { missingProperty } }) => (0, codegen_1._)`{missingProperty: ${missingProperty}}` + }, + code(cxt) { + const { gen, schema, schemaCode, data, $data, it } = cxt; + const { opts } = it; + if (!$data && schema.length === 0) return; + const useLoop = schema.length >= opts.loopRequired; + if (it.allErrors) allErrorsMode(); + else exitOnErrorMode(); + if (opts.strictRequired) { + const props = cxt.parentSchema.properties; + const { definedProperties } = cxt.it; + for (const requiredKey of schema) if ((props === null || props === void 0 ? void 0 : props[requiredKey]) === void 0 && !definedProperties.has(requiredKey)) { + const msg = `required property "${requiredKey}" is not defined at "${it.schemaEnv.baseId + it.errSchemaPath}" (strictRequired)`; + (0, util_1.checkStrictMode)(it, msg, it.opts.strictRequired); + } + } + function allErrorsMode() { + if (useLoop || $data) cxt.block$data(codegen_1.nil, loopAllRequired); + else for (const prop of schema) (0, code_1.checkReportMissingProp)(cxt, prop); + } + function exitOnErrorMode() { + const missing = gen.let("missing"); + if (useLoop || $data) { + const valid = gen.let("valid", true); + cxt.block$data(valid, () => loopUntilMissing(missing, valid)); + cxt.ok(valid); + } else { + gen.if((0, code_1.checkMissingProp)(cxt, schema, missing)); + (0, code_1.reportMissingProp)(cxt, missing); + gen.else(); + } + } + function loopAllRequired() { + gen.forOf("prop", schemaCode, (prop) => { + cxt.setParams({ missingProperty: prop }); + gen.if((0, code_1.noPropertyInData)(gen, data, prop, opts.ownProperties), () => cxt.error()); + }); + } + function loopUntilMissing(missing, valid) { + cxt.setParams({ missingProperty: missing }); + gen.forOf(missing, schemaCode, () => { + gen.assign(valid, (0, code_1.propertyInData)(gen, data, missing, opts.ownProperties)); + gen.if((0, codegen_1.not)(valid), () => { + cxt.error(); + gen.break(); + }); + }, codegen_1.nil); + } + } + }; + exports.default = def; +})); + +//#endregion +//#region ../../node_modules/.pnpm/ajv@8.18.0/node_modules/ajv/dist/vocabularies/validation/limitItems.js +var require_limitItems = /* @__PURE__ */ __commonJSMin(((exports) => { + Object.defineProperty(exports, "__esModule", { value: true }); + const codegen_1 = require_codegen(); + const def = { + keyword: ["maxItems", "minItems"], + type: "array", + schemaType: "number", + $data: true, + error: { + message({ keyword, schemaCode }) { + const comp = keyword === "maxItems" ? "more" : "fewer"; + return (0, codegen_1.str)`must NOT have ${comp} than ${schemaCode} items`; + }, + params: ({ schemaCode }) => (0, codegen_1._)`{limit: ${schemaCode}}` + }, + code(cxt) { + const { keyword, data, schemaCode } = cxt; + const op = keyword === "maxItems" ? codegen_1.operators.GT : codegen_1.operators.LT; + cxt.fail$data((0, codegen_1._)`${data}.length ${op} ${schemaCode}`); + } + }; + exports.default = def; +})); + +//#endregion +//#region ../../node_modules/.pnpm/ajv@8.18.0/node_modules/ajv/dist/runtime/equal.js +var require_equal = /* @__PURE__ */ __commonJSMin(((exports) => { + Object.defineProperty(exports, "__esModule", { value: true }); + const equal = require_fast_deep_equal(); + equal.code = "require(\"ajv/dist/runtime/equal\").default"; + exports.default = equal; +})); + +//#endregion +//#region ../../node_modules/.pnpm/ajv@8.18.0/node_modules/ajv/dist/vocabularies/validation/uniqueItems.js +var require_uniqueItems = /* @__PURE__ */ __commonJSMin(((exports) => { + Object.defineProperty(exports, "__esModule", { value: true }); + const dataType_1 = require_dataType(); + const codegen_1 = require_codegen(); + const util_1 = require_util(); + const equal_1 = require_equal(); + const def = { + keyword: "uniqueItems", + type: "array", + schemaType: "boolean", + $data: true, + error: { + message: ({ params: { i, j } }) => (0, codegen_1.str)`must NOT have duplicate items (items ## ${j} and ${i} are identical)`, + params: ({ params: { i, j } }) => (0, codegen_1._)`{i: ${i}, j: ${j}}` + }, + code(cxt) { + const { gen, data, $data, schema, parentSchema, schemaCode, it } = cxt; + if (!$data && !schema) return; + const valid = gen.let("valid"); + const itemTypes = parentSchema.items ? (0, dataType_1.getSchemaTypes)(parentSchema.items) : []; + cxt.block$data(valid, validateUniqueItems, (0, codegen_1._)`${schemaCode} === false`); + cxt.ok(valid); + function validateUniqueItems() { + const i = gen.let("i", (0, codegen_1._)`${data}.length`); + const j = gen.let("j"); + cxt.setParams({ + i, + j + }); + gen.assign(valid, true); + gen.if((0, codegen_1._)`${i} > 1`, () => (canOptimize() ? loopN : loopN2)(i, j)); + } + function canOptimize() { + return itemTypes.length > 0 && !itemTypes.some((t) => t === "object" || t === "array"); + } + function loopN(i, j) { + const item = gen.name("item"); + const wrongType = (0, dataType_1.checkDataTypes)(itemTypes, item, it.opts.strictNumbers, dataType_1.DataType.Wrong); + const indices = gen.const("indices", (0, codegen_1._)`{}`); + gen.for((0, codegen_1._)`;${i}--;`, () => { + gen.let(item, (0, codegen_1._)`${data}[${i}]`); + gen.if(wrongType, (0, codegen_1._)`continue`); + if (itemTypes.length > 1) gen.if((0, codegen_1._)`typeof ${item} == "string"`, (0, codegen_1._)`${item} += "_"`); + gen.if((0, codegen_1._)`typeof ${indices}[${item}] == "number"`, () => { + gen.assign(j, (0, codegen_1._)`${indices}[${item}]`); + cxt.error(); + gen.assign(valid, false).break(); + }).code((0, codegen_1._)`${indices}[${item}] = ${i}`); + }); + } + function loopN2(i, j) { + const eql = (0, util_1.useFunc)(gen, equal_1.default); + const outer = gen.name("outer"); + gen.label(outer).for((0, codegen_1._)`;${i}--;`, () => gen.for((0, codegen_1._)`${j} = ${i}; ${j}--;`, () => gen.if((0, codegen_1._)`${eql}(${data}[${i}], ${data}[${j}])`, () => { + cxt.error(); + gen.assign(valid, false).break(outer); + }))); + } + } + }; + exports.default = def; +})); + +//#endregion +//#region ../../node_modules/.pnpm/ajv@8.18.0/node_modules/ajv/dist/vocabularies/validation/const.js +var require_const = /* @__PURE__ */ __commonJSMin(((exports) => { + Object.defineProperty(exports, "__esModule", { value: true }); + const codegen_1 = require_codegen(); + const util_1 = require_util(); + const equal_1 = require_equal(); + const def = { + keyword: "const", + $data: true, + error: { + message: "must be equal to constant", + params: ({ schemaCode }) => (0, codegen_1._)`{allowedValue: ${schemaCode}}` + }, + code(cxt) { + const { gen, data, $data, schemaCode, schema } = cxt; + if ($data || schema && typeof schema == "object") cxt.fail$data((0, codegen_1._)`!${(0, util_1.useFunc)(gen, equal_1.default)}(${data}, ${schemaCode})`); + else cxt.fail((0, codegen_1._)`${schema} !== ${data}`); + } + }; + exports.default = def; +})); + +//#endregion +//#region ../../node_modules/.pnpm/ajv@8.18.0/node_modules/ajv/dist/vocabularies/validation/enum.js +var require_enum = /* @__PURE__ */ __commonJSMin(((exports) => { + Object.defineProperty(exports, "__esModule", { value: true }); + const codegen_1 = require_codegen(); + const util_1 = require_util(); + const equal_1 = require_equal(); + const def = { + keyword: "enum", + schemaType: "array", + $data: true, + error: { + message: "must be equal to one of the allowed values", + params: ({ schemaCode }) => (0, codegen_1._)`{allowedValues: ${schemaCode}}` + }, + code(cxt) { + const { gen, data, $data, schema, schemaCode, it } = cxt; + if (!$data && schema.length === 0) throw new Error("enum must have non-empty array"); + const useLoop = schema.length >= it.opts.loopEnum; + let eql; + const getEql = () => eql !== null && eql !== void 0 ? eql : eql = (0, util_1.useFunc)(gen, equal_1.default); + let valid; + if (useLoop || $data) { + valid = gen.let("valid"); + cxt.block$data(valid, loopEnum); + } else { + /* istanbul ignore if */ + if (!Array.isArray(schema)) throw new Error("ajv implementation error"); + const vSchema = gen.const("vSchema", schemaCode); + valid = (0, codegen_1.or)(...schema.map((_x, i) => equalCode(vSchema, i))); + } + cxt.pass(valid); + function loopEnum() { + gen.assign(valid, false); + gen.forOf("v", schemaCode, (v) => gen.if((0, codegen_1._)`${getEql()}(${data}, ${v})`, () => gen.assign(valid, true).break())); + } + function equalCode(vSchema, i) { + const sch = schema[i]; + return typeof sch === "object" && sch !== null ? (0, codegen_1._)`${getEql()}(${data}, ${vSchema}[${i}])` : (0, codegen_1._)`${data} === ${sch}`; + } + } + }; + exports.default = def; +})); + +//#endregion +//#region ../../node_modules/.pnpm/ajv@8.18.0/node_modules/ajv/dist/vocabularies/validation/index.js +var require_validation$2 = /* @__PURE__ */ __commonJSMin(((exports) => { + Object.defineProperty(exports, "__esModule", { value: true }); + const limitNumber_1 = require_limitNumber(); + const multipleOf_1 = require_multipleOf(); + const limitLength_1 = require_limitLength(); + const pattern_1 = require_pattern(); + const limitProperties_1 = require_limitProperties(); + const required_1 = require_required(); + const limitItems_1 = require_limitItems(); + const uniqueItems_1 = require_uniqueItems(); + const const_1 = require_const(); + const enum_1 = require_enum(); + const validation = [ + limitNumber_1.default, + multipleOf_1.default, + limitLength_1.default, + pattern_1.default, + limitProperties_1.default, + required_1.default, + limitItems_1.default, + uniqueItems_1.default, + { + keyword: "type", + schemaType: ["string", "array"] + }, + { + keyword: "nullable", + schemaType: "boolean" + }, + const_1.default, + enum_1.default + ]; + exports.default = validation; +})); + +//#endregion +//#region ../../node_modules/.pnpm/ajv@8.18.0/node_modules/ajv/dist/vocabularies/applicator/additionalItems.js +var require_additionalItems = /* @__PURE__ */ __commonJSMin(((exports) => { + Object.defineProperty(exports, "__esModule", { value: true }); + exports.validateAdditionalItems = void 0; + const codegen_1 = require_codegen(); + const util_1 = require_util(); + const def = { + keyword: "additionalItems", + type: "array", + schemaType: ["boolean", "object"], + before: "uniqueItems", + error: { + message: ({ params: { len } }) => (0, codegen_1.str)`must NOT have more than ${len} items`, + params: ({ params: { len } }) => (0, codegen_1._)`{limit: ${len}}` + }, + code(cxt) { + const { parentSchema, it } = cxt; + const { items } = parentSchema; + if (!Array.isArray(items)) { + (0, util_1.checkStrictMode)(it, "\"additionalItems\" is ignored when \"items\" is not an array of schemas"); + return; + } + validateAdditionalItems(cxt, items); + } + }; + function validateAdditionalItems(cxt, items) { + const { gen, schema, data, keyword, it } = cxt; + it.items = true; + const len = gen.const("len", (0, codegen_1._)`${data}.length`); + if (schema === false) { + cxt.setParams({ len: items.length }); + cxt.pass((0, codegen_1._)`${len} <= ${items.length}`); + } else if (typeof schema == "object" && !(0, util_1.alwaysValidSchema)(it, schema)) { + const valid = gen.var("valid", (0, codegen_1._)`${len} <= ${items.length}`); + gen.if((0, codegen_1.not)(valid), () => validateItems(valid)); + cxt.ok(valid); + } + function validateItems(valid) { + gen.forRange("i", items.length, len, (i) => { + cxt.subschema({ + keyword, + dataProp: i, + dataPropType: util_1.Type.Num + }, valid); + if (!it.allErrors) gen.if((0, codegen_1.not)(valid), () => gen.break()); + }); + } + } + exports.validateAdditionalItems = validateAdditionalItems; + exports.default = def; +})); + +//#endregion +//#region ../../node_modules/.pnpm/ajv@8.18.0/node_modules/ajv/dist/vocabularies/applicator/items.js +var require_items = /* @__PURE__ */ __commonJSMin(((exports) => { + Object.defineProperty(exports, "__esModule", { value: true }); + exports.validateTuple = void 0; + const codegen_1 = require_codegen(); + const util_1 = require_util(); + const code_1 = require_code(); + const def = { + keyword: "items", + type: "array", + schemaType: [ + "object", + "array", + "boolean" + ], + before: "uniqueItems", + code(cxt) { + const { schema, it } = cxt; + if (Array.isArray(schema)) return validateTuple(cxt, "additionalItems", schema); + it.items = true; + if ((0, util_1.alwaysValidSchema)(it, schema)) return; + cxt.ok((0, code_1.validateArray)(cxt)); + } + }; + function validateTuple(cxt, extraItems, schArr = cxt.schema) { + const { gen, parentSchema, data, keyword, it } = cxt; + checkStrictTuple(parentSchema); + if (it.opts.unevaluated && schArr.length && it.items !== true) it.items = util_1.mergeEvaluated.items(gen, schArr.length, it.items); + const valid = gen.name("valid"); + const len = gen.const("len", (0, codegen_1._)`${data}.length`); + schArr.forEach((sch, i) => { + if ((0, util_1.alwaysValidSchema)(it, sch)) return; + gen.if((0, codegen_1._)`${len} > ${i}`, () => cxt.subschema({ + keyword, + schemaProp: i, + dataProp: i + }, valid)); + cxt.ok(valid); + }); + function checkStrictTuple(sch) { + const { opts, errSchemaPath } = it; + const l = schArr.length; + const fullTuple = l === sch.minItems && (l === sch.maxItems || sch[extraItems] === false); + if (opts.strictTuples && !fullTuple) { + const msg = `"${keyword}" is ${l}-tuple, but minItems or maxItems/${extraItems} are not specified or different at path "${errSchemaPath}"`; + (0, util_1.checkStrictMode)(it, msg, opts.strictTuples); + } + } + } + exports.validateTuple = validateTuple; + exports.default = def; +})); + +//#endregion +//#region ../../node_modules/.pnpm/ajv@8.18.0/node_modules/ajv/dist/vocabularies/applicator/prefixItems.js +var require_prefixItems = /* @__PURE__ */ __commonJSMin(((exports) => { + Object.defineProperty(exports, "__esModule", { value: true }); + const items_1 = require_items(); + const def = { + keyword: "prefixItems", + type: "array", + schemaType: ["array"], + before: "uniqueItems", + code: (cxt) => (0, items_1.validateTuple)(cxt, "items") + }; + exports.default = def; +})); + +//#endregion +//#region ../../node_modules/.pnpm/ajv@8.18.0/node_modules/ajv/dist/vocabularies/applicator/items2020.js +var require_items2020 = /* @__PURE__ */ __commonJSMin(((exports) => { + Object.defineProperty(exports, "__esModule", { value: true }); + const codegen_1 = require_codegen(); + const util_1 = require_util(); + const code_1 = require_code(); + const additionalItems_1 = require_additionalItems(); + const def = { + keyword: "items", + type: "array", + schemaType: ["object", "boolean"], + before: "uniqueItems", + error: { + message: ({ params: { len } }) => (0, codegen_1.str)`must NOT have more than ${len} items`, + params: ({ params: { len } }) => (0, codegen_1._)`{limit: ${len}}` + }, + code(cxt) { + const { schema, parentSchema, it } = cxt; + const { prefixItems } = parentSchema; + it.items = true; + if ((0, util_1.alwaysValidSchema)(it, schema)) return; + if (prefixItems) (0, additionalItems_1.validateAdditionalItems)(cxt, prefixItems); + else cxt.ok((0, code_1.validateArray)(cxt)); + } + }; + exports.default = def; +})); + +//#endregion +//#region ../../node_modules/.pnpm/ajv@8.18.0/node_modules/ajv/dist/vocabularies/applicator/contains.js +var require_contains = /* @__PURE__ */ __commonJSMin(((exports) => { + Object.defineProperty(exports, "__esModule", { value: true }); + const codegen_1 = require_codegen(); + const util_1 = require_util(); + const def = { + keyword: "contains", + type: "array", + schemaType: ["object", "boolean"], + before: "uniqueItems", + trackErrors: true, + error: { + message: ({ params: { min, max } }) => max === void 0 ? (0, codegen_1.str)`must contain at least ${min} valid item(s)` : (0, codegen_1.str)`must contain at least ${min} and no more than ${max} valid item(s)`, + params: ({ params: { min, max } }) => max === void 0 ? (0, codegen_1._)`{minContains: ${min}}` : (0, codegen_1._)`{minContains: ${min}, maxContains: ${max}}` + }, + code(cxt) { + const { gen, schema, parentSchema, data, it } = cxt; + let min; + let max; + const { minContains, maxContains } = parentSchema; + if (it.opts.next) { + min = minContains === void 0 ? 1 : minContains; + max = maxContains; + } else min = 1; + const len = gen.const("len", (0, codegen_1._)`${data}.length`); + cxt.setParams({ + min, + max + }); + if (max === void 0 && min === 0) { + (0, util_1.checkStrictMode)(it, `"minContains" == 0 without "maxContains": "contains" keyword ignored`); + return; + } + if (max !== void 0 && min > max) { + (0, util_1.checkStrictMode)(it, `"minContains" > "maxContains" is always invalid`); + cxt.fail(); + return; + } + if ((0, util_1.alwaysValidSchema)(it, schema)) { + let cond = (0, codegen_1._)`${len} >= ${min}`; + if (max !== void 0) cond = (0, codegen_1._)`${cond} && ${len} <= ${max}`; + cxt.pass(cond); + return; + } + it.items = true; + const valid = gen.name("valid"); + if (max === void 0 && min === 1) validateItems(valid, () => gen.if(valid, () => gen.break())); + else if (min === 0) { + gen.let(valid, true); + if (max !== void 0) gen.if((0, codegen_1._)`${data}.length > 0`, validateItemsWithCount); + } else { + gen.let(valid, false); + validateItemsWithCount(); + } + cxt.result(valid, () => cxt.reset()); + function validateItemsWithCount() { + const schValid = gen.name("_valid"); + const count = gen.let("count", 0); + validateItems(schValid, () => gen.if(schValid, () => checkLimits(count))); + } + function validateItems(_valid, block) { + gen.forRange("i", 0, len, (i) => { + cxt.subschema({ + keyword: "contains", + dataProp: i, + dataPropType: util_1.Type.Num, + compositeRule: true + }, _valid); + block(); + }); + } + function checkLimits(count) { + gen.code((0, codegen_1._)`${count}++`); + if (max === void 0) gen.if((0, codegen_1._)`${count} >= ${min}`, () => gen.assign(valid, true).break()); + else { + gen.if((0, codegen_1._)`${count} > ${max}`, () => gen.assign(valid, false).break()); + if (min === 1) gen.assign(valid, true); + else gen.if((0, codegen_1._)`${count} >= ${min}`, () => gen.assign(valid, true)); + } + } + } + }; + exports.default = def; +})); + +//#endregion +//#region ../../node_modules/.pnpm/ajv@8.18.0/node_modules/ajv/dist/vocabularies/applicator/dependencies.js +var require_dependencies = /* @__PURE__ */ __commonJSMin(((exports) => { + Object.defineProperty(exports, "__esModule", { value: true }); + exports.validateSchemaDeps = exports.validatePropertyDeps = exports.error = void 0; + const codegen_1 = require_codegen(); + const util_1 = require_util(); + const code_1 = require_code(); + exports.error = { + message: ({ params: { property, depsCount, deps } }) => { + const property_ies = depsCount === 1 ? "property" : "properties"; + return (0, codegen_1.str)`must have ${property_ies} ${deps} when property ${property} is present`; + }, + params: ({ params: { property, depsCount, deps, missingProperty } }) => (0, codegen_1._)`{property: ${property}, + missingProperty: ${missingProperty}, + depsCount: ${depsCount}, + deps: ${deps}}` + }; + const def = { + keyword: "dependencies", + type: "object", + schemaType: "object", + error: exports.error, + code(cxt) { + const [propDeps, schDeps] = splitDependencies(cxt); + validatePropertyDeps(cxt, propDeps); + validateSchemaDeps(cxt, schDeps); + } + }; + function splitDependencies({ schema }) { + const propertyDeps = {}; + const schemaDeps = {}; + for (const key in schema) { + if (key === "__proto__") continue; + const deps = Array.isArray(schema[key]) ? propertyDeps : schemaDeps; + deps[key] = schema[key]; + } + return [propertyDeps, schemaDeps]; + } + function validatePropertyDeps(cxt, propertyDeps = cxt.schema) { + const { gen, data, it } = cxt; + if (Object.keys(propertyDeps).length === 0) return; + const missing = gen.let("missing"); + for (const prop in propertyDeps) { + const deps = propertyDeps[prop]; + if (deps.length === 0) continue; + const hasProperty = (0, code_1.propertyInData)(gen, data, prop, it.opts.ownProperties); + cxt.setParams({ + property: prop, + depsCount: deps.length, + deps: deps.join(", ") + }); + if (it.allErrors) gen.if(hasProperty, () => { + for (const depProp of deps) (0, code_1.checkReportMissingProp)(cxt, depProp); + }); + else { + gen.if((0, codegen_1._)`${hasProperty} && (${(0, code_1.checkMissingProp)(cxt, deps, missing)})`); + (0, code_1.reportMissingProp)(cxt, missing); + gen.else(); + } + } + } + exports.validatePropertyDeps = validatePropertyDeps; + function validateSchemaDeps(cxt, schemaDeps = cxt.schema) { + const { gen, data, keyword, it } = cxt; + const valid = gen.name("valid"); + for (const prop in schemaDeps) { + if ((0, util_1.alwaysValidSchema)(it, schemaDeps[prop])) continue; + gen.if((0, code_1.propertyInData)(gen, data, prop, it.opts.ownProperties), () => { + const schCxt = cxt.subschema({ + keyword, + schemaProp: prop + }, valid); + cxt.mergeValidEvaluated(schCxt, valid); + }, () => gen.var(valid, true)); + cxt.ok(valid); + } + } + exports.validateSchemaDeps = validateSchemaDeps; + exports.default = def; +})); + +//#endregion +//#region ../../node_modules/.pnpm/ajv@8.18.0/node_modules/ajv/dist/vocabularies/applicator/propertyNames.js +var require_propertyNames = /* @__PURE__ */ __commonJSMin(((exports) => { + Object.defineProperty(exports, "__esModule", { value: true }); + const codegen_1 = require_codegen(); + const util_1 = require_util(); + const def = { + keyword: "propertyNames", + type: "object", + schemaType: ["object", "boolean"], + error: { + message: "property name must be valid", + params: ({ params }) => (0, codegen_1._)`{propertyName: ${params.propertyName}}` + }, + code(cxt) { + const { gen, schema, data, it } = cxt; + if ((0, util_1.alwaysValidSchema)(it, schema)) return; + const valid = gen.name("valid"); + gen.forIn("key", data, (key) => { + cxt.setParams({ propertyName: key }); + cxt.subschema({ + keyword: "propertyNames", + data: key, + dataTypes: ["string"], + propertyName: key, + compositeRule: true + }, valid); + gen.if((0, codegen_1.not)(valid), () => { + cxt.error(true); + if (!it.allErrors) gen.break(); + }); + }); + cxt.ok(valid); + } + }; + exports.default = def; +})); + +//#endregion +//#region ../../node_modules/.pnpm/ajv@8.18.0/node_modules/ajv/dist/vocabularies/applicator/additionalProperties.js +var require_additionalProperties = /* @__PURE__ */ __commonJSMin(((exports) => { + Object.defineProperty(exports, "__esModule", { value: true }); + const code_1 = require_code(); + const codegen_1 = require_codegen(); + const names_1 = require_names(); + const util_1 = require_util(); + const def = { + keyword: "additionalProperties", + type: ["object"], + schemaType: ["boolean", "object"], + allowUndefined: true, + trackErrors: true, + error: { + message: "must NOT have additional properties", + params: ({ params }) => (0, codegen_1._)`{additionalProperty: ${params.additionalProperty}}` + }, + code(cxt) { + const { gen, schema, parentSchema, data, errsCount, it } = cxt; + /* istanbul ignore if */ + if (!errsCount) throw new Error("ajv implementation error"); + const { allErrors, opts } = it; + it.props = true; + if (opts.removeAdditional !== "all" && (0, util_1.alwaysValidSchema)(it, schema)) return; + const props = (0, code_1.allSchemaProperties)(parentSchema.properties); + const patProps = (0, code_1.allSchemaProperties)(parentSchema.patternProperties); + checkAdditionalProperties(); + cxt.ok((0, codegen_1._)`${errsCount} === ${names_1.default.errors}`); + function checkAdditionalProperties() { + gen.forIn("key", data, (key) => { + if (!props.length && !patProps.length) additionalPropertyCode(key); + else gen.if(isAdditional(key), () => additionalPropertyCode(key)); + }); + } + function isAdditional(key) { + let definedProp; + if (props.length > 8) { + const propsSchema = (0, util_1.schemaRefOrVal)(it, parentSchema.properties, "properties"); + definedProp = (0, code_1.isOwnProperty)(gen, propsSchema, key); + } else if (props.length) definedProp = (0, codegen_1.or)(...props.map((p) => (0, codegen_1._)`${key} === ${p}`)); + else definedProp = codegen_1.nil; + if (patProps.length) definedProp = (0, codegen_1.or)(definedProp, ...patProps.map((p) => (0, codegen_1._)`${(0, code_1.usePattern)(cxt, p)}.test(${key})`)); + return (0, codegen_1.not)(definedProp); + } + function deleteAdditional(key) { + gen.code((0, codegen_1._)`delete ${data}[${key}]`); + } + function additionalPropertyCode(key) { + if (opts.removeAdditional === "all" || opts.removeAdditional && schema === false) { + deleteAdditional(key); + return; + } + if (schema === false) { + cxt.setParams({ additionalProperty: key }); + cxt.error(); + if (!allErrors) gen.break(); + return; + } + if (typeof schema == "object" && !(0, util_1.alwaysValidSchema)(it, schema)) { + const valid = gen.name("valid"); + if (opts.removeAdditional === "failing") { + applyAdditionalSchema(key, valid, false); + gen.if((0, codegen_1.not)(valid), () => { + cxt.reset(); + deleteAdditional(key); + }); + } else { + applyAdditionalSchema(key, valid); + if (!allErrors) gen.if((0, codegen_1.not)(valid), () => gen.break()); + } + } + } + function applyAdditionalSchema(key, valid, errors) { + const subschema = { + keyword: "additionalProperties", + dataProp: key, + dataPropType: util_1.Type.Str + }; + if (errors === false) Object.assign(subschema, { + compositeRule: true, + createErrors: false, + allErrors: false + }); + cxt.subschema(subschema, valid); + } + } + }; + exports.default = def; +})); + +//#endregion +//#region ../../node_modules/.pnpm/ajv@8.18.0/node_modules/ajv/dist/vocabularies/applicator/properties.js +var require_properties = /* @__PURE__ */ __commonJSMin(((exports) => { + Object.defineProperty(exports, "__esModule", { value: true }); + const validate_1 = require_validate(); + const code_1 = require_code(); + const util_1 = require_util(); + const additionalProperties_1 = require_additionalProperties(); + const def = { + keyword: "properties", + type: "object", + schemaType: "object", + code(cxt) { + const { gen, schema, parentSchema, data, it } = cxt; + if (it.opts.removeAdditional === "all" && parentSchema.additionalProperties === void 0) additionalProperties_1.default.code(new validate_1.KeywordCxt(it, additionalProperties_1.default, "additionalProperties")); + const allProps = (0, code_1.allSchemaProperties)(schema); + for (const prop of allProps) it.definedProperties.add(prop); + if (it.opts.unevaluated && allProps.length && it.props !== true) it.props = util_1.mergeEvaluated.props(gen, (0, util_1.toHash)(allProps), it.props); + const properties = allProps.filter((p) => !(0, util_1.alwaysValidSchema)(it, schema[p])); + if (properties.length === 0) return; + const valid = gen.name("valid"); + for (const prop of properties) { + if (hasDefault(prop)) applyPropertySchema(prop); + else { + gen.if((0, code_1.propertyInData)(gen, data, prop, it.opts.ownProperties)); + applyPropertySchema(prop); + if (!it.allErrors) gen.else().var(valid, true); + gen.endIf(); + } + cxt.it.definedProperties.add(prop); + cxt.ok(valid); + } + function hasDefault(prop) { + return it.opts.useDefaults && !it.compositeRule && schema[prop].default !== void 0; + } + function applyPropertySchema(prop) { + cxt.subschema({ + keyword: "properties", + schemaProp: prop, + dataProp: prop + }, valid); + } + } + }; + exports.default = def; +})); + +//#endregion +//#region ../../node_modules/.pnpm/ajv@8.18.0/node_modules/ajv/dist/vocabularies/applicator/patternProperties.js +var require_patternProperties = /* @__PURE__ */ __commonJSMin(((exports) => { + Object.defineProperty(exports, "__esModule", { value: true }); + const code_1 = require_code(); + const codegen_1 = require_codegen(); + const util_1 = require_util(); + const util_2 = require_util(); + const def = { + keyword: "patternProperties", + type: "object", + schemaType: "object", + code(cxt) { + const { gen, schema, data, parentSchema, it } = cxt; + const { opts } = it; + const patterns = (0, code_1.allSchemaProperties)(schema); + const alwaysValidPatterns = patterns.filter((p) => (0, util_1.alwaysValidSchema)(it, schema[p])); + if (patterns.length === 0 || alwaysValidPatterns.length === patterns.length && (!it.opts.unevaluated || it.props === true)) return; + const checkProperties = opts.strictSchema && !opts.allowMatchingProperties && parentSchema.properties; + const valid = gen.name("valid"); + if (it.props !== true && !(it.props instanceof codegen_1.Name)) it.props = (0, util_2.evaluatedPropsToName)(gen, it.props); + const { props } = it; + validatePatternProperties(); + function validatePatternProperties() { + for (const pat of patterns) { + if (checkProperties) checkMatchingProperties(pat); + if (it.allErrors) validateProperties(pat); + else { + gen.var(valid, true); + validateProperties(pat); + gen.if(valid); + } + } + } + function checkMatchingProperties(pat) { + for (const prop in checkProperties) if (new RegExp(pat).test(prop)) (0, util_1.checkStrictMode)(it, `property ${prop} matches pattern ${pat} (use allowMatchingProperties)`); + } + function validateProperties(pat) { + gen.forIn("key", data, (key) => { + gen.if((0, codegen_1._)`${(0, code_1.usePattern)(cxt, pat)}.test(${key})`, () => { + const alwaysValid = alwaysValidPatterns.includes(pat); + if (!alwaysValid) cxt.subschema({ + keyword: "patternProperties", + schemaProp: pat, + dataProp: key, + dataPropType: util_2.Type.Str + }, valid); + if (it.opts.unevaluated && props !== true) gen.assign((0, codegen_1._)`${props}[${key}]`, true); + else if (!alwaysValid && !it.allErrors) gen.if((0, codegen_1.not)(valid), () => gen.break()); + }); + }); + } + } + }; + exports.default = def; +})); + +//#endregion +//#region ../../node_modules/.pnpm/ajv@8.18.0/node_modules/ajv/dist/vocabularies/applicator/not.js +var require_not = /* @__PURE__ */ __commonJSMin(((exports) => { + Object.defineProperty(exports, "__esModule", { value: true }); + const util_1 = require_util(); + const def = { + keyword: "not", + schemaType: ["object", "boolean"], + trackErrors: true, + code(cxt) { + const { gen, schema, it } = cxt; + if ((0, util_1.alwaysValidSchema)(it, schema)) { + cxt.fail(); + return; + } + const valid = gen.name("valid"); + cxt.subschema({ + keyword: "not", + compositeRule: true, + createErrors: false, + allErrors: false + }, valid); + cxt.failResult(valid, () => cxt.reset(), () => cxt.error()); + }, + error: { message: "must NOT be valid" } + }; + exports.default = def; +})); + +//#endregion +//#region ../../node_modules/.pnpm/ajv@8.18.0/node_modules/ajv/dist/vocabularies/applicator/anyOf.js +var require_anyOf = /* @__PURE__ */ __commonJSMin(((exports) => { + Object.defineProperty(exports, "__esModule", { value: true }); + const def = { + keyword: "anyOf", + schemaType: "array", + trackErrors: true, + code: require_code().validateUnion, + error: { message: "must match a schema in anyOf" } + }; + exports.default = def; +})); + +//#endregion +//#region ../../node_modules/.pnpm/ajv@8.18.0/node_modules/ajv/dist/vocabularies/applicator/oneOf.js +var require_oneOf = /* @__PURE__ */ __commonJSMin(((exports) => { + Object.defineProperty(exports, "__esModule", { value: true }); + const codegen_1 = require_codegen(); + const util_1 = require_util(); + const def = { + keyword: "oneOf", + schemaType: "array", + trackErrors: true, + error: { + message: "must match exactly one schema in oneOf", + params: ({ params }) => (0, codegen_1._)`{passingSchemas: ${params.passing}}` + }, + code(cxt) { + const { gen, schema, parentSchema, it } = cxt; + /* istanbul ignore if */ + if (!Array.isArray(schema)) throw new Error("ajv implementation error"); + if (it.opts.discriminator && parentSchema.discriminator) return; + const schArr = schema; + const valid = gen.let("valid", false); + const passing = gen.let("passing", null); + const schValid = gen.name("_valid"); + cxt.setParams({ passing }); + gen.block(validateOneOf); + cxt.result(valid, () => cxt.reset(), () => cxt.error(true)); + function validateOneOf() { + schArr.forEach((sch, i) => { + let schCxt; + if ((0, util_1.alwaysValidSchema)(it, sch)) gen.var(schValid, true); + else schCxt = cxt.subschema({ + keyword: "oneOf", + schemaProp: i, + compositeRule: true + }, schValid); + if (i > 0) gen.if((0, codegen_1._)`${schValid} && ${valid}`).assign(valid, false).assign(passing, (0, codegen_1._)`[${passing}, ${i}]`).else(); + gen.if(schValid, () => { + gen.assign(valid, true); + gen.assign(passing, i); + if (schCxt) cxt.mergeEvaluated(schCxt, codegen_1.Name); + }); + }); + } + } + }; + exports.default = def; +})); + +//#endregion +//#region ../../node_modules/.pnpm/ajv@8.18.0/node_modules/ajv/dist/vocabularies/applicator/allOf.js +var require_allOf = /* @__PURE__ */ __commonJSMin(((exports) => { + Object.defineProperty(exports, "__esModule", { value: true }); + const util_1 = require_util(); + const def = { + keyword: "allOf", + schemaType: "array", + code(cxt) { + const { gen, schema, it } = cxt; + /* istanbul ignore if */ + if (!Array.isArray(schema)) throw new Error("ajv implementation error"); + const valid = gen.name("valid"); + schema.forEach((sch, i) => { + if ((0, util_1.alwaysValidSchema)(it, sch)) return; + const schCxt = cxt.subschema({ + keyword: "allOf", + schemaProp: i + }, valid); + cxt.ok(valid); + cxt.mergeEvaluated(schCxt); + }); + } + }; + exports.default = def; +})); + +//#endregion +//#region ../../node_modules/.pnpm/ajv@8.18.0/node_modules/ajv/dist/vocabularies/applicator/if.js +var require_if = /* @__PURE__ */ __commonJSMin(((exports) => { + Object.defineProperty(exports, "__esModule", { value: true }); + const codegen_1 = require_codegen(); + const util_1 = require_util(); + const def = { + keyword: "if", + schemaType: ["object", "boolean"], + trackErrors: true, + error: { + message: ({ params }) => (0, codegen_1.str)`must match "${params.ifClause}" schema`, + params: ({ params }) => (0, codegen_1._)`{failingKeyword: ${params.ifClause}}` + }, + code(cxt) { + const { gen, parentSchema, it } = cxt; + if (parentSchema.then === void 0 && parentSchema.else === void 0) (0, util_1.checkStrictMode)(it, "\"if\" without \"then\" and \"else\" is ignored"); + const hasThen = hasSchema(it, "then"); + const hasElse = hasSchema(it, "else"); + if (!hasThen && !hasElse) return; + const valid = gen.let("valid", true); + const schValid = gen.name("_valid"); + validateIf(); + cxt.reset(); + if (hasThen && hasElse) { + const ifClause = gen.let("ifClause"); + cxt.setParams({ ifClause }); + gen.if(schValid, validateClause("then", ifClause), validateClause("else", ifClause)); + } else if (hasThen) gen.if(schValid, validateClause("then")); + else gen.if((0, codegen_1.not)(schValid), validateClause("else")); + cxt.pass(valid, () => cxt.error(true)); + function validateIf() { + const schCxt = cxt.subschema({ + keyword: "if", + compositeRule: true, + createErrors: false, + allErrors: false + }, schValid); + cxt.mergeEvaluated(schCxt); + } + function validateClause(keyword, ifClause) { + return () => { + const schCxt = cxt.subschema({ keyword }, schValid); + gen.assign(valid, schValid); + cxt.mergeValidEvaluated(schCxt, valid); + if (ifClause) gen.assign(ifClause, (0, codegen_1._)`${keyword}`); + else cxt.setParams({ ifClause: keyword }); + }; + } + } + }; + function hasSchema(it, keyword) { + const schema = it.schema[keyword]; + return schema !== void 0 && !(0, util_1.alwaysValidSchema)(it, schema); + } + exports.default = def; +})); + +//#endregion +//#region ../../node_modules/.pnpm/ajv@8.18.0/node_modules/ajv/dist/vocabularies/applicator/thenElse.js +var require_thenElse = /* @__PURE__ */ __commonJSMin(((exports) => { + Object.defineProperty(exports, "__esModule", { value: true }); + const util_1 = require_util(); + const def = { + keyword: ["then", "else"], + schemaType: ["object", "boolean"], + code({ keyword, parentSchema, it }) { + if (parentSchema.if === void 0) (0, util_1.checkStrictMode)(it, `"${keyword}" without "if" is ignored`); + } + }; + exports.default = def; +})); + +//#endregion +//#region ../../node_modules/.pnpm/ajv@8.18.0/node_modules/ajv/dist/vocabularies/applicator/index.js +var require_applicator$2 = /* @__PURE__ */ __commonJSMin(((exports) => { + Object.defineProperty(exports, "__esModule", { value: true }); + const additionalItems_1 = require_additionalItems(); + const prefixItems_1 = require_prefixItems(); + const items_1 = require_items(); + const items2020_1 = require_items2020(); + const contains_1 = require_contains(); + const dependencies_1 = require_dependencies(); + const propertyNames_1 = require_propertyNames(); + const additionalProperties_1 = require_additionalProperties(); + const properties_1 = require_properties(); + const patternProperties_1 = require_patternProperties(); + const not_1 = require_not(); + const anyOf_1 = require_anyOf(); + const oneOf_1 = require_oneOf(); + const allOf_1 = require_allOf(); + const if_1 = require_if(); + const thenElse_1 = require_thenElse(); + function getApplicator(draft2020 = false) { + const applicator = [ + not_1.default, + anyOf_1.default, + oneOf_1.default, + allOf_1.default, + if_1.default, + thenElse_1.default, + propertyNames_1.default, + additionalProperties_1.default, + dependencies_1.default, + properties_1.default, + patternProperties_1.default + ]; + if (draft2020) applicator.push(prefixItems_1.default, items2020_1.default); + else applicator.push(additionalItems_1.default, items_1.default); + applicator.push(contains_1.default); + return applicator; + } + exports.default = getApplicator; +})); + +//#endregion +//#region ../../node_modules/.pnpm/ajv@8.18.0/node_modules/ajv/dist/vocabularies/format/format.js +var require_format$2 = /* @__PURE__ */ __commonJSMin(((exports) => { + Object.defineProperty(exports, "__esModule", { value: true }); + const codegen_1 = require_codegen(); + const def = { + keyword: "format", + type: ["number", "string"], + schemaType: "string", + $data: true, + error: { + message: ({ schemaCode }) => (0, codegen_1.str)`must match format "${schemaCode}"`, + params: ({ schemaCode }) => (0, codegen_1._)`{format: ${schemaCode}}` + }, + code(cxt, ruleType) { + const { gen, data, $data, schema, schemaCode, it } = cxt; + const { opts, errSchemaPath, schemaEnv, self } = it; + if (!opts.validateFormats) return; + if ($data) validate$DataFormat(); + else validateFormat(); + function validate$DataFormat() { + const fmts = gen.scopeValue("formats", { + ref: self.formats, + code: opts.code.formats + }); + const fDef = gen.const("fDef", (0, codegen_1._)`${fmts}[${schemaCode}]`); + const fType = gen.let("fType"); + const format = gen.let("format"); + gen.if((0, codegen_1._)`typeof ${fDef} == "object" && !(${fDef} instanceof RegExp)`, () => gen.assign(fType, (0, codegen_1._)`${fDef}.type || "string"`).assign(format, (0, codegen_1._)`${fDef}.validate`), () => gen.assign(fType, (0, codegen_1._)`"string"`).assign(format, fDef)); + cxt.fail$data((0, codegen_1.or)(unknownFmt(), invalidFmt())); + function unknownFmt() { + if (opts.strictSchema === false) return codegen_1.nil; + return (0, codegen_1._)`${schemaCode} && !${format}`; + } + function invalidFmt() { + const callFormat = schemaEnv.$async ? (0, codegen_1._)`(${fDef}.async ? await ${format}(${data}) : ${format}(${data}))` : (0, codegen_1._)`${format}(${data})`; + const validData = (0, codegen_1._)`(typeof ${format} == "function" ? ${callFormat} : ${format}.test(${data}))`; + return (0, codegen_1._)`${format} && ${format} !== true && ${fType} === ${ruleType} && !${validData}`; + } + } + function validateFormat() { + const formatDef = self.formats[schema]; + if (!formatDef) { + unknownFormat(); + return; + } + if (formatDef === true) return; + const [fmtType, format, fmtRef] = getFormat(formatDef); + if (fmtType === ruleType) cxt.pass(validCondition()); + function unknownFormat() { + if (opts.strictSchema === false) { + self.logger.warn(unknownMsg()); + return; + } + throw new Error(unknownMsg()); + function unknownMsg() { + return `unknown format "${schema}" ignored in schema at path "${errSchemaPath}"`; + } + } + function getFormat(fmtDef) { + const code = fmtDef instanceof RegExp ? (0, codegen_1.regexpCode)(fmtDef) : opts.code.formats ? (0, codegen_1._)`${opts.code.formats}${(0, codegen_1.getProperty)(schema)}` : void 0; + const fmt = gen.scopeValue("formats", { + key: schema, + ref: fmtDef, + code + }); + if (typeof fmtDef == "object" && !(fmtDef instanceof RegExp)) return [ + fmtDef.type || "string", + fmtDef.validate, + (0, codegen_1._)`${fmt}.validate` + ]; + return [ + "string", + fmtDef, + fmt + ]; + } + function validCondition() { + if (typeof formatDef == "object" && !(formatDef instanceof RegExp) && formatDef.async) { + if (!schemaEnv.$async) throw new Error("async format in sync schema"); + return (0, codegen_1._)`await ${fmtRef}(${data})`; + } + return typeof format == "function" ? (0, codegen_1._)`${fmtRef}(${data})` : (0, codegen_1._)`${fmtRef}.test(${data})`; + } + } + } + }; + exports.default = def; +})); + +//#endregion +//#region ../../node_modules/.pnpm/ajv@8.18.0/node_modules/ajv/dist/vocabularies/format/index.js +var require_format$1 = /* @__PURE__ */ __commonJSMin(((exports) => { + Object.defineProperty(exports, "__esModule", { value: true }); + const format = [require_format$2().default]; + exports.default = format; +})); + +//#endregion +//#region ../../node_modules/.pnpm/ajv@8.18.0/node_modules/ajv/dist/vocabularies/metadata.js +var require_metadata = /* @__PURE__ */ __commonJSMin(((exports) => { + Object.defineProperty(exports, "__esModule", { value: true }); + exports.contentVocabulary = exports.metadataVocabulary = void 0; + exports.metadataVocabulary = [ + "title", + "description", + "default", + "deprecated", + "readOnly", + "writeOnly", + "examples" + ]; + exports.contentVocabulary = [ + "contentMediaType", + "contentEncoding", + "contentSchema" + ]; +})); + +//#endregion +//#region ../../node_modules/.pnpm/ajv@8.18.0/node_modules/ajv/dist/vocabularies/draft7.js +var require_draft7 = /* @__PURE__ */ __commonJSMin(((exports) => { + Object.defineProperty(exports, "__esModule", { value: true }); + const core_1 = require_core$2(); + const validation_1 = require_validation$2(); + const applicator_1 = require_applicator$2(); + const format_1 = require_format$1(); + const metadata_1 = require_metadata(); + const draft7Vocabularies = [ + core_1.default, + validation_1.default, + (0, applicator_1.default)(), + format_1.default, + metadata_1.metadataVocabulary, + metadata_1.contentVocabulary + ]; + exports.default = draft7Vocabularies; +})); + +//#endregion +//#region ../../node_modules/.pnpm/ajv@8.18.0/node_modules/ajv/dist/vocabularies/discriminator/types.js +var require_types = /* @__PURE__ */ __commonJSMin(((exports) => { + Object.defineProperty(exports, "__esModule", { value: true }); + exports.DiscrError = void 0; + var DiscrError; + (function(DiscrError) { + DiscrError["Tag"] = "tag"; + DiscrError["Mapping"] = "mapping"; + })(DiscrError || (exports.DiscrError = DiscrError = {})); +})); + +//#endregion +//#region ../../node_modules/.pnpm/ajv@8.18.0/node_modules/ajv/dist/vocabularies/discriminator/index.js +var require_discriminator = /* @__PURE__ */ __commonJSMin(((exports) => { + Object.defineProperty(exports, "__esModule", { value: true }); + const codegen_1 = require_codegen(); + const types_1 = require_types(); + const compile_1 = require_compile(); + const ref_error_1 = require_ref_error(); + const util_1 = require_util(); + const def = { + keyword: "discriminator", + type: "object", + schemaType: "object", + error: { + message: ({ params: { discrError, tagName } }) => discrError === types_1.DiscrError.Tag ? `tag "${tagName}" must be string` : `value of tag "${tagName}" must be in oneOf`, + params: ({ params: { discrError, tag, tagName } }) => (0, codegen_1._)`{error: ${discrError}, tag: ${tagName}, tagValue: ${tag}}` + }, + code(cxt) { + const { gen, data, schema, parentSchema, it } = cxt; + const { oneOf } = parentSchema; + if (!it.opts.discriminator) throw new Error("discriminator: requires discriminator option"); + const tagName = schema.propertyName; + if (typeof tagName != "string") throw new Error("discriminator: requires propertyName"); + if (schema.mapping) throw new Error("discriminator: mapping is not supported"); + if (!oneOf) throw new Error("discriminator: requires oneOf keyword"); + const valid = gen.let("valid", false); + const tag = gen.const("tag", (0, codegen_1._)`${data}${(0, codegen_1.getProperty)(tagName)}`); + gen.if((0, codegen_1._)`typeof ${tag} == "string"`, () => validateMapping(), () => cxt.error(false, { + discrError: types_1.DiscrError.Tag, + tag, + tagName + })); + cxt.ok(valid); + function validateMapping() { + const mapping = getMapping(); + gen.if(false); + for (const tagValue in mapping) { + gen.elseIf((0, codegen_1._)`${tag} === ${tagValue}`); + gen.assign(valid, applyTagSchema(mapping[tagValue])); + } + gen.else(); + cxt.error(false, { + discrError: types_1.DiscrError.Mapping, + tag, + tagName + }); + gen.endIf(); + } + function applyTagSchema(schemaProp) { + const _valid = gen.name("valid"); + const schCxt = cxt.subschema({ + keyword: "oneOf", + schemaProp + }, _valid); + cxt.mergeEvaluated(schCxt, codegen_1.Name); + return _valid; + } + function getMapping() { + var _a; + const oneOfMapping = {}; + const topRequired = hasRequired(parentSchema); + let tagRequired = true; + for (let i = 0; i < oneOf.length; i++) { + let sch = oneOf[i]; + if ((sch === null || sch === void 0 ? void 0 : sch.$ref) && !(0, util_1.schemaHasRulesButRef)(sch, it.self.RULES)) { + const ref = sch.$ref; + sch = compile_1.resolveRef.call(it.self, it.schemaEnv.root, it.baseId, ref); + if (sch instanceof compile_1.SchemaEnv) sch = sch.schema; + if (sch === void 0) throw new ref_error_1.default(it.opts.uriResolver, it.baseId, ref); + } + const propSch = (_a = sch === null || sch === void 0 ? void 0 : sch.properties) === null || _a === void 0 ? void 0 : _a[tagName]; + if (typeof propSch != "object") throw new Error(`discriminator: oneOf subschemas (or referenced schemas) must have "properties/${tagName}"`); + tagRequired = tagRequired && (topRequired || hasRequired(sch)); + addMappings(propSch, i); + } + if (!tagRequired) throw new Error(`discriminator: "${tagName}" must be required`); + return oneOfMapping; + function hasRequired({ required }) { + return Array.isArray(required) && required.includes(tagName); + } + function addMappings(sch, i) { + if (sch.const) addMapping(sch.const, i); + else if (sch.enum) for (const tagValue of sch.enum) addMapping(tagValue, i); + else throw new Error(`discriminator: "properties/${tagName}" must have "const" or "enum"`); + } + function addMapping(tagValue, i) { + if (typeof tagValue != "string" || tagValue in oneOfMapping) throw new Error(`discriminator: "${tagName}" values must be unique strings`); + oneOfMapping[tagValue] = i; + } + } + } + }; + exports.default = def; +})); + +//#endregion +//#region ../../node_modules/.pnpm/ajv@8.18.0/node_modules/ajv/dist/refs/json-schema-draft-07.json +var require_json_schema_draft_07 = /* @__PURE__ */ __commonJSMin(((exports, module) => { + module.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": true, + "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": true, + "readOnly": { + "type": "boolean", + "default": false + }, + "examples": { + "type": "array", + "items": true + }, + "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": true + }, + "maxItems": { "$ref": "#/definitions/nonNegativeInteger" }, + "minItems": { "$ref": "#/definitions/nonNegativeIntegerDefault0" }, + "uniqueItems": { + "type": "boolean", + "default": false + }, + "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": true, + "enum": { + "type": "array", + "items": true, + "minItems": 1, + "uniqueItems": true + }, + "type": { "anyOf": [{ "$ref": "#/definitions/simpleTypes" }, { + "type": "array", + "items": { "$ref": "#/definitions/simpleTypes" }, + "minItems": 1, + "uniqueItems": true + }] }, + "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": true + }; +})); + +//#endregion +//#region ../../node_modules/.pnpm/ajv@8.18.0/node_modules/ajv/dist/ajv.js +var require_ajv = /* @__PURE__ */ __commonJSMin(((exports, module) => { + Object.defineProperty(exports, "__esModule", { value: true }); + exports.MissingRefError = exports.ValidationError = exports.CodeGen = exports.Name = exports.nil = exports.stringify = exports.str = exports._ = exports.KeywordCxt = exports.Ajv = void 0; + const core_1 = require_core$3(); + const draft7_1 = require_draft7(); + const discriminator_1 = require_discriminator(); + const draft7MetaSchema = require_json_schema_draft_07(); + const META_SUPPORT_DATA = ["/properties"]; + const META_SCHEMA_ID = "http://json-schema.org/draft-07/schema"; + var Ajv = class extends core_1.default { + _addVocabularies() { + super._addVocabularies(); + draft7_1.default.forEach((v) => this.addVocabulary(v)); + if (this.opts.discriminator) this.addKeyword(discriminator_1.default); + } + _addDefaultMetaSchema() { + super._addDefaultMetaSchema(); + if (!this.opts.meta) return; + const metaSchema = this.opts.$data ? this.$dataMetaSchema(draft7MetaSchema, META_SUPPORT_DATA) : draft7MetaSchema; + this.addMetaSchema(metaSchema, META_SCHEMA_ID, false); + this.refs["http://json-schema.org/schema"] = META_SCHEMA_ID; + } + defaultMeta() { + return this.opts.defaultMeta = super.defaultMeta() || (this.getSchema(META_SCHEMA_ID) ? META_SCHEMA_ID : void 0); + } + }; + exports.Ajv = Ajv; + module.exports = exports = Ajv; + module.exports.Ajv = Ajv; + Object.defineProperty(exports, "__esModule", { value: true }); + exports.default = Ajv; + var validate_1 = require_validate(); + Object.defineProperty(exports, "KeywordCxt", { + enumerable: true, + get: function() { + return validate_1.KeywordCxt; + } + }); + var codegen_1 = require_codegen(); + Object.defineProperty(exports, "_", { + enumerable: true, + get: function() { + return codegen_1._; + } + }); + Object.defineProperty(exports, "str", { + enumerable: true, + get: function() { + return codegen_1.str; + } + }); + Object.defineProperty(exports, "stringify", { + enumerable: true, + get: function() { + return codegen_1.stringify; + } + }); + Object.defineProperty(exports, "nil", { + enumerable: true, + get: function() { + return codegen_1.nil; + } + }); + Object.defineProperty(exports, "Name", { + enumerable: true, + get: function() { + return codegen_1.Name; + } + }); + Object.defineProperty(exports, "CodeGen", { + enumerable: true, + get: function() { + return codegen_1.CodeGen; + } + }); + var validation_error_1 = require_validation_error(); + Object.defineProperty(exports, "ValidationError", { + enumerable: true, + get: function() { + return validation_error_1.default; + } + }); + var ref_error_1 = require_ref_error(); + Object.defineProperty(exports, "MissingRefError", { + enumerable: true, + get: function() { + return ref_error_1.default; + } + }); +})); + +//#endregion +//#region ../../node_modules/.pnpm/ajv@8.18.0/node_modules/ajv/dist/vocabularies/dynamic/dynamicAnchor.js +var require_dynamicAnchor = /* @__PURE__ */ __commonJSMin(((exports) => { + Object.defineProperty(exports, "__esModule", { value: true }); + exports.dynamicAnchor = void 0; + const codegen_1 = require_codegen(); + const names_1 = require_names(); + const compile_1 = require_compile(); + const ref_1 = require_ref(); + const def = { + keyword: "$dynamicAnchor", + schemaType: "string", + code: (cxt) => dynamicAnchor(cxt, cxt.schema) + }; + function dynamicAnchor(cxt, anchor) { + const { gen, it } = cxt; + it.schemaEnv.root.dynamicAnchors[anchor] = true; + const v = (0, codegen_1._)`${names_1.default.dynamicAnchors}${(0, codegen_1.getProperty)(anchor)}`; + const validate = it.errSchemaPath === "#" ? it.validateName : _getValidate(cxt); + gen.if((0, codegen_1._)`!${v}`, () => gen.assign(v, validate)); + } + exports.dynamicAnchor = dynamicAnchor; + function _getValidate(cxt) { + const { schemaEnv, schema, self } = cxt.it; + const { root, baseId, localRefs, meta } = schemaEnv.root; + const { schemaId } = self.opts; + const sch = new compile_1.SchemaEnv({ + schema, + schemaId, + root, + baseId, + localRefs, + meta + }); + compile_1.compileSchema.call(self, sch); + return (0, ref_1.getValidate)(cxt, sch); + } + exports.default = def; +})); + +//#endregion +//#region ../../node_modules/.pnpm/ajv@8.18.0/node_modules/ajv/dist/vocabularies/dynamic/dynamicRef.js +var require_dynamicRef = /* @__PURE__ */ __commonJSMin(((exports) => { + Object.defineProperty(exports, "__esModule", { value: true }); + exports.dynamicRef = void 0; + const codegen_1 = require_codegen(); + const names_1 = require_names(); + const ref_1 = require_ref(); + const def = { + keyword: "$dynamicRef", + schemaType: "string", + code: (cxt) => dynamicRef(cxt, cxt.schema) + }; + function dynamicRef(cxt, ref) { + const { gen, keyword, it } = cxt; + if (ref[0] !== "#") throw new Error(`"${keyword}" only supports hash fragment reference`); + const anchor = ref.slice(1); + if (it.allErrors) _dynamicRef(); + else { + const valid = gen.let("valid", false); + _dynamicRef(valid); + cxt.ok(valid); + } + function _dynamicRef(valid) { + if (it.schemaEnv.root.dynamicAnchors[anchor]) { + const v = gen.let("_v", (0, codegen_1._)`${names_1.default.dynamicAnchors}${(0, codegen_1.getProperty)(anchor)}`); + gen.if(v, _callRef(v, valid), _callRef(it.validateName, valid)); + } else _callRef(it.validateName, valid)(); + } + function _callRef(validate, valid) { + return valid ? () => gen.block(() => { + (0, ref_1.callRef)(cxt, validate); + gen.let(valid, true); + }) : () => (0, ref_1.callRef)(cxt, validate); + } + } + exports.dynamicRef = dynamicRef; + exports.default = def; +})); + +//#endregion +//#region ../../node_modules/.pnpm/ajv@8.18.0/node_modules/ajv/dist/vocabularies/dynamic/recursiveAnchor.js +var require_recursiveAnchor = /* @__PURE__ */ __commonJSMin(((exports) => { + Object.defineProperty(exports, "__esModule", { value: true }); + const dynamicAnchor_1 = require_dynamicAnchor(); + const util_1 = require_util(); + const def = { + keyword: "$recursiveAnchor", + schemaType: "boolean", + code(cxt) { + if (cxt.schema) (0, dynamicAnchor_1.dynamicAnchor)(cxt, ""); + else (0, util_1.checkStrictMode)(cxt.it, "$recursiveAnchor: false is ignored"); + } + }; + exports.default = def; +})); + +//#endregion +//#region ../../node_modules/.pnpm/ajv@8.18.0/node_modules/ajv/dist/vocabularies/dynamic/recursiveRef.js +var require_recursiveRef = /* @__PURE__ */ __commonJSMin(((exports) => { + Object.defineProperty(exports, "__esModule", { value: true }); + const dynamicRef_1 = require_dynamicRef(); + const def = { + keyword: "$recursiveRef", + schemaType: "string", + code: (cxt) => (0, dynamicRef_1.dynamicRef)(cxt, cxt.schema) + }; + exports.default = def; +})); + +//#endregion +//#region ../../node_modules/.pnpm/ajv@8.18.0/node_modules/ajv/dist/vocabularies/dynamic/index.js +var require_dynamic = /* @__PURE__ */ __commonJSMin(((exports) => { + Object.defineProperty(exports, "__esModule", { value: true }); + const dynamicAnchor_1 = require_dynamicAnchor(); + const dynamicRef_1 = require_dynamicRef(); + const recursiveAnchor_1 = require_recursiveAnchor(); + const recursiveRef_1 = require_recursiveRef(); + const dynamic = [ + dynamicAnchor_1.default, + dynamicRef_1.default, + recursiveAnchor_1.default, + recursiveRef_1.default + ]; + exports.default = dynamic; +})); + +//#endregion +//#region ../../node_modules/.pnpm/ajv@8.18.0/node_modules/ajv/dist/vocabularies/validation/dependentRequired.js +var require_dependentRequired = /* @__PURE__ */ __commonJSMin(((exports) => { + Object.defineProperty(exports, "__esModule", { value: true }); + const dependencies_1 = require_dependencies(); + const def = { + keyword: "dependentRequired", + type: "object", + schemaType: "object", + error: dependencies_1.error, + code: (cxt) => (0, dependencies_1.validatePropertyDeps)(cxt) + }; + exports.default = def; +})); + +//#endregion +//#region ../../node_modules/.pnpm/ajv@8.18.0/node_modules/ajv/dist/vocabularies/applicator/dependentSchemas.js +var require_dependentSchemas = /* @__PURE__ */ __commonJSMin(((exports) => { + Object.defineProperty(exports, "__esModule", { value: true }); + const dependencies_1 = require_dependencies(); + const def = { + keyword: "dependentSchemas", + type: "object", + schemaType: "object", + code: (cxt) => (0, dependencies_1.validateSchemaDeps)(cxt) + }; + exports.default = def; +})); + +//#endregion +//#region ../../node_modules/.pnpm/ajv@8.18.0/node_modules/ajv/dist/vocabularies/validation/limitContains.js +var require_limitContains = /* @__PURE__ */ __commonJSMin(((exports) => { + Object.defineProperty(exports, "__esModule", { value: true }); + const util_1 = require_util(); + const def = { + keyword: ["maxContains", "minContains"], + type: "array", + schemaType: "number", + code({ keyword, parentSchema, it }) { + if (parentSchema.contains === void 0) (0, util_1.checkStrictMode)(it, `"${keyword}" without "contains" is ignored`); + } + }; + exports.default = def; +})); + +//#endregion +//#region ../../node_modules/.pnpm/ajv@8.18.0/node_modules/ajv/dist/vocabularies/next.js +var require_next = /* @__PURE__ */ __commonJSMin(((exports) => { + Object.defineProperty(exports, "__esModule", { value: true }); + const dependentRequired_1 = require_dependentRequired(); + const dependentSchemas_1 = require_dependentSchemas(); + const limitContains_1 = require_limitContains(); + const next = [ + dependentRequired_1.default, + dependentSchemas_1.default, + limitContains_1.default + ]; + exports.default = next; +})); + +//#endregion +//#region ../../node_modules/.pnpm/ajv@8.18.0/node_modules/ajv/dist/vocabularies/unevaluated/unevaluatedProperties.js +var require_unevaluatedProperties = /* @__PURE__ */ __commonJSMin(((exports) => { + Object.defineProperty(exports, "__esModule", { value: true }); + const codegen_1 = require_codegen(); + const util_1 = require_util(); + const names_1 = require_names(); + const def = { + keyword: "unevaluatedProperties", + type: "object", + schemaType: ["boolean", "object"], + trackErrors: true, + error: { + message: "must NOT have unevaluated properties", + params: ({ params }) => (0, codegen_1._)`{unevaluatedProperty: ${params.unevaluatedProperty}}` + }, + code(cxt) { + const { gen, schema, data, errsCount, it } = cxt; + /* istanbul ignore if */ + if (!errsCount) throw new Error("ajv implementation error"); + const { allErrors, props } = it; + if (props instanceof codegen_1.Name) gen.if((0, codegen_1._)`${props} !== true`, () => gen.forIn("key", data, (key) => gen.if(unevaluatedDynamic(props, key), () => unevaluatedPropCode(key)))); + else if (props !== true) gen.forIn("key", data, (key) => props === void 0 ? unevaluatedPropCode(key) : gen.if(unevaluatedStatic(props, key), () => unevaluatedPropCode(key))); + it.props = true; + cxt.ok((0, codegen_1._)`${errsCount} === ${names_1.default.errors}`); + function unevaluatedPropCode(key) { + if (schema === false) { + cxt.setParams({ unevaluatedProperty: key }); + cxt.error(); + if (!allErrors) gen.break(); + return; + } + if (!(0, util_1.alwaysValidSchema)(it, schema)) { + const valid = gen.name("valid"); + cxt.subschema({ + keyword: "unevaluatedProperties", + dataProp: key, + dataPropType: util_1.Type.Str + }, valid); + if (!allErrors) gen.if((0, codegen_1.not)(valid), () => gen.break()); + } + } + function unevaluatedDynamic(evaluatedProps, key) { + return (0, codegen_1._)`!${evaluatedProps} || !${evaluatedProps}[${key}]`; + } + function unevaluatedStatic(evaluatedProps, key) { + const ps = []; + for (const p in evaluatedProps) if (evaluatedProps[p] === true) ps.push((0, codegen_1._)`${key} !== ${p}`); + return (0, codegen_1.and)(...ps); + } + } + }; + exports.default = def; +})); + +//#endregion +//#region ../../node_modules/.pnpm/ajv@8.18.0/node_modules/ajv/dist/vocabularies/unevaluated/unevaluatedItems.js +var require_unevaluatedItems = /* @__PURE__ */ __commonJSMin(((exports) => { + Object.defineProperty(exports, "__esModule", { value: true }); + const codegen_1 = require_codegen(); + const util_1 = require_util(); + const def = { + keyword: "unevaluatedItems", + type: "array", + schemaType: ["boolean", "object"], + error: { + message: ({ params: { len } }) => (0, codegen_1.str)`must NOT have more than ${len} items`, + params: ({ params: { len } }) => (0, codegen_1._)`{limit: ${len}}` + }, + code(cxt) { + const { gen, schema, data, it } = cxt; + const items = it.items || 0; + if (items === true) return; + const len = gen.const("len", (0, codegen_1._)`${data}.length`); + if (schema === false) { + cxt.setParams({ len: items }); + cxt.fail((0, codegen_1._)`${len} > ${items}`); + } else if (typeof schema == "object" && !(0, util_1.alwaysValidSchema)(it, schema)) { + const valid = gen.var("valid", (0, codegen_1._)`${len} <= ${items}`); + gen.if((0, codegen_1.not)(valid), () => validateItems(valid, items)); + cxt.ok(valid); + } + it.items = true; + function validateItems(valid, from) { + gen.forRange("i", from, len, (i) => { + cxt.subschema({ + keyword: "unevaluatedItems", + dataProp: i, + dataPropType: util_1.Type.Num + }, valid); + if (!it.allErrors) gen.if((0, codegen_1.not)(valid), () => gen.break()); + }); + } + } + }; + exports.default = def; +})); + +//#endregion +//#region ../../node_modules/.pnpm/ajv@8.18.0/node_modules/ajv/dist/vocabularies/unevaluated/index.js +var require_unevaluated$1 = /* @__PURE__ */ __commonJSMin(((exports) => { + Object.defineProperty(exports, "__esModule", { value: true }); + const unevaluatedProperties_1 = require_unevaluatedProperties(); + const unevaluatedItems_1 = require_unevaluatedItems(); + const unevaluated = [unevaluatedProperties_1.default, unevaluatedItems_1.default]; + exports.default = unevaluated; +})); + +//#endregion +//#region ../../node_modules/.pnpm/ajv@8.18.0/node_modules/ajv/dist/refs/json-schema-2019-09/schema.json +var require_schema$1 = /* @__PURE__ */ __commonJSMin(((exports, module) => { + module.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": true, + "https://json-schema.org/draft/2019-09/vocab/applicator": true, + "https://json-schema.org/draft/2019-09/vocab/validation": true, + "https://json-schema.org/draft/2019-09/vocab/meta-data": true, + "https://json-schema.org/draft/2019-09/vocab/format": false, + "https://json-schema.org/draft/2019-09/vocab/content": true + }, + "$recursiveAnchor": true, + "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" }] } + } + } + }; +})); + +//#endregion +//#region ../../node_modules/.pnpm/ajv@8.18.0/node_modules/ajv/dist/refs/json-schema-2019-09/meta/applicator.json +var require_applicator$1 = /* @__PURE__ */ __commonJSMin(((exports, module) => { + module.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": true }, + "$recursiveAnchor": true, + "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": "#" } + } } + }; +})); + +//#endregion +//#region ../../node_modules/.pnpm/ajv@8.18.0/node_modules/ajv/dist/refs/json-schema-2019-09/meta/content.json +var require_content$1 = /* @__PURE__ */ __commonJSMin(((exports, module) => { + module.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": true }, + "$recursiveAnchor": true, + "title": "Content vocabulary meta-schema", + "type": ["object", "boolean"], + "properties": { + "contentMediaType": { "type": "string" }, + "contentEncoding": { "type": "string" }, + "contentSchema": { "$recursiveRef": "#" } + } + }; +})); + +//#endregion +//#region ../../node_modules/.pnpm/ajv@8.18.0/node_modules/ajv/dist/refs/json-schema-2019-09/meta/core.json +var require_core$1 = /* @__PURE__ */ __commonJSMin(((exports, module) => { + module.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": true }, + "$recursiveAnchor": true, + "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": false + }, + "$vocabulary": { + "type": "object", + "propertyNames": { + "type": "string", + "format": "uri" + }, + "additionalProperties": { "type": "boolean" } + }, + "$comment": { "type": "string" }, + "$defs": { + "type": "object", + "additionalProperties": { "$recursiveRef": "#" }, + "default": {} + } + } + }; +})); + +//#endregion +//#region ../../node_modules/.pnpm/ajv@8.18.0/node_modules/ajv/dist/refs/json-schema-2019-09/meta/format.json +var require_format = /* @__PURE__ */ __commonJSMin(((exports, module) => { + module.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": true }, + "$recursiveAnchor": true, + "title": "Format vocabulary meta-schema", + "type": ["object", "boolean"], + "properties": { "format": { "type": "string" } } + }; +})); + +//#endregion +//#region ../../node_modules/.pnpm/ajv@8.18.0/node_modules/ajv/dist/refs/json-schema-2019-09/meta/meta-data.json +var require_meta_data$1 = /* @__PURE__ */ __commonJSMin(((exports, module) => { + module.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": true }, + "$recursiveAnchor": true, + "title": "Meta-data vocabulary meta-schema", + "type": ["object", "boolean"], + "properties": { + "title": { "type": "string" }, + "description": { "type": "string" }, + "default": true, + "deprecated": { + "type": "boolean", + "default": false + }, + "readOnly": { + "type": "boolean", + "default": false + }, + "writeOnly": { + "type": "boolean", + "default": false + }, + "examples": { + "type": "array", + "items": true + } + } + }; +})); + +//#endregion +//#region ../../node_modules/.pnpm/ajv@8.18.0/node_modules/ajv/dist/refs/json-schema-2019-09/meta/validation.json +var require_validation$1 = /* @__PURE__ */ __commonJSMin(((exports, module) => { + module.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": true }, + "$recursiveAnchor": true, + "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": false + }, + "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": true, + "enum": { + "type": "array", + "items": true + }, + "type": { "anyOf": [{ "$ref": "#/$defs/simpleTypes" }, { + "type": "array", + "items": { "$ref": "#/$defs/simpleTypes" }, + "minItems": 1, + "uniqueItems": true + }] } + }, + "$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": true, + "default": [] + } + } + }; +})); + +//#endregion +//#region ../../node_modules/.pnpm/ajv@8.18.0/node_modules/ajv/dist/refs/json-schema-2019-09/index.js +var require_json_schema_2019_09 = /* @__PURE__ */ __commonJSMin(((exports) => { + Object.defineProperty(exports, "__esModule", { value: true }); + const metaSchema = require_schema$1(); + const applicator = require_applicator$1(); + const content = require_content$1(); + const core = require_core$1(); + const format = require_format(); + const metadata = require_meta_data$1(); + const validation = require_validation$1(); + const META_SUPPORT_DATA = ["/properties"]; + function addMetaSchema2019($data) { + [ + metaSchema, + applicator, + content, + core, + with$data(this, format), + metadata, + with$data(this, validation) + ].forEach((sch) => this.addMetaSchema(sch, void 0, false)); + return this; + function with$data(ajv, sch) { + return $data ? ajv.$dataMetaSchema(sch, META_SUPPORT_DATA) : sch; + } + } + exports.default = addMetaSchema2019; +})); + +//#endregion +//#region ../../node_modules/.pnpm/ajv@8.18.0/node_modules/ajv/dist/2019.js +var require__2019 = /* @__PURE__ */ __commonJSMin(((exports, module) => { + Object.defineProperty(exports, "__esModule", { value: true }); + exports.MissingRefError = exports.ValidationError = exports.CodeGen = exports.Name = exports.nil = exports.stringify = exports.str = exports._ = exports.KeywordCxt = exports.Ajv2019 = void 0; + const core_1 = require_core$3(); + const draft7_1 = require_draft7(); + const dynamic_1 = require_dynamic(); + const next_1 = require_next(); + const unevaluated_1 = require_unevaluated$1(); + const discriminator_1 = require_discriminator(); + const json_schema_2019_09_1 = require_json_schema_2019_09(); + const META_SCHEMA_ID = "https://json-schema.org/draft/2019-09/schema"; + var Ajv2019 = class extends core_1.default { + constructor(opts = {}) { + super({ + ...opts, + dynamicRef: true, + next: true, + unevaluated: true + }); + } + _addVocabularies() { + super._addVocabularies(); + this.addVocabulary(dynamic_1.default); + draft7_1.default.forEach((v) => this.addVocabulary(v)); + this.addVocabulary(next_1.default); + this.addVocabulary(unevaluated_1.default); + if (this.opts.discriminator) this.addKeyword(discriminator_1.default); + } + _addDefaultMetaSchema() { + super._addDefaultMetaSchema(); + const { $data, meta } = this.opts; + if (!meta) return; + json_schema_2019_09_1.default.call(this, $data); + this.refs["http://json-schema.org/schema"] = META_SCHEMA_ID; + } + defaultMeta() { + return this.opts.defaultMeta = super.defaultMeta() || (this.getSchema(META_SCHEMA_ID) ? META_SCHEMA_ID : void 0); + } + }; + exports.Ajv2019 = Ajv2019; + module.exports = exports = Ajv2019; + module.exports.Ajv2019 = Ajv2019; + Object.defineProperty(exports, "__esModule", { value: true }); + exports.default = Ajv2019; + var validate_1 = require_validate(); + Object.defineProperty(exports, "KeywordCxt", { + enumerable: true, + get: function() { + return validate_1.KeywordCxt; + } + }); + var codegen_1 = require_codegen(); + Object.defineProperty(exports, "_", { + enumerable: true, + get: function() { + return codegen_1._; + } + }); + Object.defineProperty(exports, "str", { + enumerable: true, + get: function() { + return codegen_1.str; + } + }); + Object.defineProperty(exports, "stringify", { + enumerable: true, + get: function() { + return codegen_1.stringify; + } + }); + Object.defineProperty(exports, "nil", { + enumerable: true, + get: function() { + return codegen_1.nil; + } + }); + Object.defineProperty(exports, "Name", { + enumerable: true, + get: function() { + return codegen_1.Name; + } + }); + Object.defineProperty(exports, "CodeGen", { + enumerable: true, + get: function() { + return codegen_1.CodeGen; + } + }); + var validation_error_1 = require_validation_error(); + Object.defineProperty(exports, "ValidationError", { + enumerable: true, + get: function() { + return validation_error_1.default; + } + }); + var ref_error_1 = require_ref_error(); + Object.defineProperty(exports, "MissingRefError", { + enumerable: true, + get: function() { + return ref_error_1.default; + } + }); +})); + +//#endregion +//#region ../../node_modules/.pnpm/ajv@8.18.0/node_modules/ajv/dist/vocabularies/draft2020.js +var require_draft2020 = /* @__PURE__ */ __commonJSMin(((exports) => { + Object.defineProperty(exports, "__esModule", { value: true }); + const core_1 = require_core$2(); + const validation_1 = require_validation$2(); + const applicator_1 = require_applicator$2(); + const dynamic_1 = require_dynamic(); + const next_1 = require_next(); + const unevaluated_1 = require_unevaluated$1(); + const format_1 = require_format$1(); + const metadata_1 = require_metadata(); + const draft2020Vocabularies = [ + dynamic_1.default, + core_1.default, + validation_1.default, + (0, applicator_1.default)(true), + format_1.default, + metadata_1.metadataVocabulary, + metadata_1.contentVocabulary, + next_1.default, + unevaluated_1.default + ]; + exports.default = draft2020Vocabularies; +})); + +//#endregion +//#region ../../node_modules/.pnpm/ajv@8.18.0/node_modules/ajv/dist/refs/json-schema-2020-12/schema.json +var require_schema = /* @__PURE__ */ __commonJSMin(((exports, module) => { + module.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": true, + "https://json-schema.org/draft/2020-12/vocab/applicator": true, + "https://json-schema.org/draft/2020-12/vocab/unevaluated": true, + "https://json-schema.org/draft/2020-12/vocab/validation": true, + "https://json-schema.org/draft/2020-12/vocab/meta-data": true, + "https://json-schema.org/draft/2020-12/vocab/format-annotation": true, + "https://json-schema.org/draft/2020-12/vocab/content": true + }, + "$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": true, + "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": true, + "default": {} + }, + "$recursiveAnchor": { + "$comment": "\"$recursiveAnchor\" has been replaced by \"$dynamicAnchor\".", + "$ref": "meta/core#/$defs/anchorString", + "deprecated": true + }, + "$recursiveRef": { + "$comment": "\"$recursiveRef\" has been replaced by \"$dynamicRef\".", + "$ref": "meta/core#/$defs/uriReferenceString", + "deprecated": true + } + } + }; +})); + +//#endregion +//#region ../../node_modules/.pnpm/ajv@8.18.0/node_modules/ajv/dist/refs/json-schema-2020-12/meta/applicator.json +var require_applicator = /* @__PURE__ */ __commonJSMin(((exports, module) => { + module.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": true }, + "$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" } + } } + }; +})); + +//#endregion +//#region ../../node_modules/.pnpm/ajv@8.18.0/node_modules/ajv/dist/refs/json-schema-2020-12/meta/unevaluated.json +var require_unevaluated = /* @__PURE__ */ __commonJSMin(((exports, module) => { + module.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": true }, + "$dynamicAnchor": "meta", + "title": "Unevaluated applicator vocabulary meta-schema", + "type": ["object", "boolean"], + "properties": { + "unevaluatedItems": { "$dynamicRef": "#meta" }, + "unevaluatedProperties": { "$dynamicRef": "#meta" } + } + }; +})); + +//#endregion +//#region ../../node_modules/.pnpm/ajv@8.18.0/node_modules/ajv/dist/refs/json-schema-2020-12/meta/content.json +var require_content = /* @__PURE__ */ __commonJSMin(((exports, module) => { + module.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": true }, + "$dynamicAnchor": "meta", + "title": "Content vocabulary meta-schema", + "type": ["object", "boolean"], + "properties": { + "contentEncoding": { "type": "string" }, + "contentMediaType": { "type": "string" }, + "contentSchema": { "$dynamicRef": "#meta" } + } + }; +})); + +//#endregion +//#region ../../node_modules/.pnpm/ajv@8.18.0/node_modules/ajv/dist/refs/json-schema-2020-12/meta/core.json +var require_core = /* @__PURE__ */ __commonJSMin(((exports, module) => { + module.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": true }, + "$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" + } + } + }; +})); + +//#endregion +//#region ../../node_modules/.pnpm/ajv@8.18.0/node_modules/ajv/dist/refs/json-schema-2020-12/meta/format-annotation.json +var require_format_annotation = /* @__PURE__ */ __commonJSMin(((exports, module) => { + module.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": true }, + "$dynamicAnchor": "meta", + "title": "Format vocabulary meta-schema for annotation results", + "type": ["object", "boolean"], + "properties": { "format": { "type": "string" } } + }; +})); + +//#endregion +//#region ../../node_modules/.pnpm/ajv@8.18.0/node_modules/ajv/dist/refs/json-schema-2020-12/meta/meta-data.json +var require_meta_data = /* @__PURE__ */ __commonJSMin(((exports, module) => { + module.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": true }, + "$dynamicAnchor": "meta", + "title": "Meta-data vocabulary meta-schema", + "type": ["object", "boolean"], + "properties": { + "title": { "type": "string" }, + "description": { "type": "string" }, + "default": true, + "deprecated": { + "type": "boolean", + "default": false + }, + "readOnly": { + "type": "boolean", + "default": false + }, + "writeOnly": { + "type": "boolean", + "default": false + }, + "examples": { + "type": "array", + "items": true + } + } + }; +})); + +//#endregion +//#region ../../node_modules/.pnpm/ajv@8.18.0/node_modules/ajv/dist/refs/json-schema-2020-12/meta/validation.json +var require_validation = /* @__PURE__ */ __commonJSMin(((exports, module) => { + module.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": true }, + "$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": true + }] }, + "const": true, + "enum": { + "type": "array", + "items": true + }, + "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": false + }, + "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": true, + "default": [] + } + } + }; +})); + +//#endregion +//#region ../../node_modules/.pnpm/ajv@8.18.0/node_modules/ajv/dist/refs/json-schema-2020-12/index.js +var require_json_schema_2020_12 = /* @__PURE__ */ __commonJSMin(((exports) => { + Object.defineProperty(exports, "__esModule", { value: true }); + const metaSchema = require_schema(); + const applicator = require_applicator(); + const unevaluated = require_unevaluated(); + const content = require_content(); + const core = require_core(); + const format = require_format_annotation(); + const metadata = require_meta_data(); + const validation = require_validation(); + const META_SUPPORT_DATA = ["/properties"]; + function addMetaSchema2020($data) { + [ + metaSchema, + applicator, + unevaluated, + content, + core, + with$data(this, format), + metadata, + with$data(this, validation) + ].forEach((sch) => this.addMetaSchema(sch, void 0, false)); + return this; + function with$data(ajv, sch) { + return $data ? ajv.$dataMetaSchema(sch, META_SUPPORT_DATA) : sch; + } + } + exports.default = addMetaSchema2020; +})); + +//#endregion +//#region ../../node_modules/.pnpm/ajv@8.18.0/node_modules/ajv/dist/2020.js +var require__2020 = /* @__PURE__ */ __commonJSMin(((exports, module) => { + Object.defineProperty(exports, "__esModule", { value: true }); + exports.MissingRefError = exports.ValidationError = exports.CodeGen = exports.Name = exports.nil = exports.stringify = exports.str = exports._ = exports.KeywordCxt = exports.Ajv2020 = void 0; + const core_1 = require_core$3(); + const draft2020_1 = require_draft2020(); + const discriminator_1 = require_discriminator(); + const json_schema_2020_12_1 = require_json_schema_2020_12(); + const META_SCHEMA_ID = "https://json-schema.org/draft/2020-12/schema"; + var Ajv2020 = class extends core_1.default { + constructor(opts = {}) { + super({ + ...opts, + dynamicRef: true, + next: true, + unevaluated: true + }); + } + _addVocabularies() { + super._addVocabularies(); + draft2020_1.default.forEach((v) => this.addVocabulary(v)); + if (this.opts.discriminator) this.addKeyword(discriminator_1.default); + } + _addDefaultMetaSchema() { + super._addDefaultMetaSchema(); + const { $data, meta } = this.opts; + if (!meta) return; + json_schema_2020_12_1.default.call(this, $data); + this.refs["http://json-schema.org/schema"] = META_SCHEMA_ID; + } + defaultMeta() { + return this.opts.defaultMeta = super.defaultMeta() || (this.getSchema(META_SCHEMA_ID) ? META_SCHEMA_ID : void 0); + } + }; + exports.Ajv2020 = Ajv2020; + module.exports = exports = Ajv2020; + module.exports.Ajv2020 = Ajv2020; + Object.defineProperty(exports, "__esModule", { value: true }); + exports.default = Ajv2020; + var validate_1 = require_validate(); + Object.defineProperty(exports, "KeywordCxt", { + enumerable: true, + get: function() { + return validate_1.KeywordCxt; + } + }); + var codegen_1 = require_codegen(); + Object.defineProperty(exports, "_", { + enumerable: true, + get: function() { + return codegen_1._; + } + }); + Object.defineProperty(exports, "str", { + enumerable: true, + get: function() { + return codegen_1.str; + } + }); + Object.defineProperty(exports, "stringify", { + enumerable: true, + get: function() { + return codegen_1.stringify; + } + }); + Object.defineProperty(exports, "nil", { + enumerable: true, + get: function() { + return codegen_1.nil; + } + }); + Object.defineProperty(exports, "Name", { + enumerable: true, + get: function() { + return codegen_1.Name; + } + }); + Object.defineProperty(exports, "CodeGen", { + enumerable: true, + get: function() { + return codegen_1.CodeGen; + } + }); + var validation_error_1 = require_validation_error(); + Object.defineProperty(exports, "ValidationError", { + enumerable: true, + get: function() { + return validation_error_1.default; + } + }); + var ref_error_1 = require_ref_error(); + Object.defineProperty(exports, "MissingRefError", { + enumerable: true, + get: function() { + return ref_error_1.default; + } + }); +})); + +//#endregion +//#region ../../node_modules/.pnpm/ajv-formats@3.0.1_ajv@8.18.0/node_modules/ajv-formats/dist/formats.js +var require_formats = /* @__PURE__ */ __commonJSMin(((exports) => { + Object.defineProperty(exports, "__esModule", { value: true }); + exports.formatNames = exports.fastFormats = exports.fullFormats = void 0; + function fmtDef(validate, compare) { + return { + validate, + compare + }; + } + exports.fullFormats = { + date: fmtDef(date, compareDate), + time: fmtDef(getTime(true), compareTime), + "date-time": fmtDef(getDateTime(true), compareDateTime), + "iso-time": fmtDef(getTime(), compareIsoTime), + "iso-date-time": fmtDef(getDateTime(), compareIsoDateTime), + duration: /^P(?!$)((\d+Y)?(\d+M)?(\d+D)?(T(?=\d)(\d+H)?(\d+M)?(\d+S)?)?|(\d+W)?)$/, + uri, + "uri-reference": /^(?:[a-z][a-z0-9+\-.]*:)?(?:\/?\/(?:(?:[a-z0-9\-._~!$&'()*+,;=:]|%[0-9a-f]{2})*@)?(?:\[(?:(?:(?:(?:[0-9a-f]{1,4}:){6}|::(?:[0-9a-f]{1,4}:){5}|(?:[0-9a-f]{1,4})?::(?:[0-9a-f]{1,4}:){4}|(?:(?:[0-9a-f]{1,4}:){0,1}[0-9a-f]{1,4})?::(?:[0-9a-f]{1,4}:){3}|(?:(?:[0-9a-f]{1,4}:){0,2}[0-9a-f]{1,4})?::(?:[0-9a-f]{1,4}:){2}|(?:(?:[0-9a-f]{1,4}:){0,3}[0-9a-f]{1,4})?::[0-9a-f]{1,4}:|(?:(?:[0-9a-f]{1,4}:){0,4}[0-9a-f]{1,4})?::)(?:[0-9a-f]{1,4}:[0-9a-f]{1,4}|(?:(?:25[0-5]|2[0-4]\d|[01]?\d\d?)\.){3}(?:25[0-5]|2[0-4]\d|[01]?\d\d?))|(?:(?:[0-9a-f]{1,4}:){0,5}[0-9a-f]{1,4})?::[0-9a-f]{1,4}|(?:(?:[0-9a-f]{1,4}:){0,6}[0-9a-f]{1,4})?::)|[Vv][0-9a-f]+\.[a-z0-9\-._~!$&'()*+,;=:]+)\]|(?:(?:25[0-5]|2[0-4]\d|[01]?\d\d?)\.){3}(?:25[0-5]|2[0-4]\d|[01]?\d\d?)|(?:[a-z0-9\-._~!$&'"()*+,;=]|%[0-9a-f]{2})*)(?::\d*)?(?:\/(?:[a-z0-9\-._~!$&'"()*+,;=:@]|%[0-9a-f]{2})*)*|\/(?:(?:[a-z0-9\-._~!$&'"()*+,;=:@]|%[0-9a-f]{2})+(?:\/(?:[a-z0-9\-._~!$&'"()*+,;=:@]|%[0-9a-f]{2})*)*)?|(?:[a-z0-9\-._~!$&'"()*+,;=:@]|%[0-9a-f]{2})+(?:\/(?:[a-z0-9\-._~!$&'"()*+,;=:@]|%[0-9a-f]{2})*)*)?(?:\?(?:[a-z0-9\-._~!$&'"()*+,;=:@/?]|%[0-9a-f]{2})*)?(?:#(?:[a-z0-9\-._~!$&'"()*+,;=:@/?]|%[0-9a-f]{2})*)?$/i, + "uri-template": /^(?:(?:[^\x00-\x20"'<>%\\^`{|}]|%[0-9a-f]{2})|\{[+#./;?&=,!@|]?(?:[a-z0-9_]|%[0-9a-f]{2})+(?::[1-9][0-9]{0,3}|\*)?(?:,(?:[a-z0-9_]|%[0-9a-f]{2})+(?::[1-9][0-9]{0,3}|\*)?)*\})*$/i, + url: /^(?:https?|ftp):\/\/(?:\S+(?::\S*)?@)?(?:(?!(?:10|127)(?:\.\d{1,3}){3})(?!(?:169\.254|192\.168)(?:\.\d{1,3}){2})(?!172\.(?:1[6-9]|2\d|3[0-1])(?:\.\d{1,3}){2})(?:[1-9]\d?|1\d\d|2[01]\d|22[0-3])(?:\.(?:1?\d{1,2}|2[0-4]\d|25[0-5])){2}(?:\.(?:[1-9]\d?|1\d\d|2[0-4]\d|25[0-4]))|(?:(?:[a-z0-9\u{00a1}-\u{ffff}]+-)*[a-z0-9\u{00a1}-\u{ffff}]+)(?:\.(?:[a-z0-9\u{00a1}-\u{ffff}]+-)*[a-z0-9\u{00a1}-\u{ffff}]+)*(?:\.(?:[a-z\u{00a1}-\u{ffff}]{2,})))(?::\d{2,5})?(?:\/[^\s]*)?$/iu, + email: /^[a-z0-9!#$%&'*+/=?^_`{|}~-]+(?:\.[a-z0-9!#$%&'*+/=?^_`{|}~-]+)*@(?:[a-z0-9](?:[a-z0-9-]*[a-z0-9])?\.)+[a-z0-9](?:[a-z0-9-]*[a-z0-9])?$/i, + hostname: /^(?=.{1,253}\.?$)[a-z0-9](?:[a-z0-9-]{0,61}[a-z0-9])?(?:\.[a-z0-9](?:[-0-9a-z]{0,61}[0-9a-z])?)*\.?$/i, + ipv4: /^(?:(?:25[0-5]|2[0-4]\d|1\d\d|[1-9]?\d)\.){3}(?:25[0-5]|2[0-4]\d|1\d\d|[1-9]?\d)$/, + ipv6: /^((([0-9a-f]{1,4}:){7}([0-9a-f]{1,4}|:))|(([0-9a-f]{1,4}:){6}(:[0-9a-f]{1,4}|((25[0-5]|2[0-4]\d|1\d\d|[1-9]?\d)(\.(25[0-5]|2[0-4]\d|1\d\d|[1-9]?\d)){3})|:))|(([0-9a-f]{1,4}:){5}(((:[0-9a-f]{1,4}){1,2})|:((25[0-5]|2[0-4]\d|1\d\d|[1-9]?\d)(\.(25[0-5]|2[0-4]\d|1\d\d|[1-9]?\d)){3})|:))|(([0-9a-f]{1,4}:){4}(((:[0-9a-f]{1,4}){1,3})|((:[0-9a-f]{1,4})?:((25[0-5]|2[0-4]\d|1\d\d|[1-9]?\d)(\.(25[0-5]|2[0-4]\d|1\d\d|[1-9]?\d)){3}))|:))|(([0-9a-f]{1,4}:){3}(((:[0-9a-f]{1,4}){1,4})|((:[0-9a-f]{1,4}){0,2}:((25[0-5]|2[0-4]\d|1\d\d|[1-9]?\d)(\.(25[0-5]|2[0-4]\d|1\d\d|[1-9]?\d)){3}))|:))|(([0-9a-f]{1,4}:){2}(((:[0-9a-f]{1,4}){1,5})|((:[0-9a-f]{1,4}){0,3}:((25[0-5]|2[0-4]\d|1\d\d|[1-9]?\d)(\.(25[0-5]|2[0-4]\d|1\d\d|[1-9]?\d)){3}))|:))|(([0-9a-f]{1,4}:){1}(((:[0-9a-f]{1,4}){1,6})|((:[0-9a-f]{1,4}){0,4}:((25[0-5]|2[0-4]\d|1\d\d|[1-9]?\d)(\.(25[0-5]|2[0-4]\d|1\d\d|[1-9]?\d)){3}))|:))|(:(((:[0-9a-f]{1,4}){1,7})|((:[0-9a-f]{1,4}){0,5}:((25[0-5]|2[0-4]\d|1\d\d|[1-9]?\d)(\.(25[0-5]|2[0-4]\d|1\d\d|[1-9]?\d)){3}))|:)))$/i, + regex, + 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, + int32: { + type: "number", + validate: validateInt32 + }, + int64: { + type: "number", + validate: validateInt64 + }, + float: { + type: "number", + validate: validateNumber + }, + double: { + type: "number", + validate: validateNumber + }, + password: true, + binary: true + }; + exports.fastFormats = { + ...exports.fullFormats, + date: fmtDef(/^\d\d\d\d-[0-1]\d-[0-3]\d$/, compareDate), + time: fmtDef(/^(?:[0-2]\d:[0-5]\d:[0-5]\d|23:59:60)(?:\.\d+)?(?:z|[+-]\d\d(?::?\d\d)?)$/i, compareTime), + "date-time": fmtDef(/^\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, compareDateTime), + "iso-time": fmtDef(/^(?:[0-2]\d:[0-5]\d:[0-5]\d|23:59:60)(?:\.\d+)?(?:z|[+-]\d\d(?::?\d\d)?)?$/i, compareIsoTime), + "iso-date-time": fmtDef(/^\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, compareIsoDateTime), + uri: /^(?:[a-z][a-z0-9+\-.]*:)(?:\/?\/)?[^\s]*$/i, + "uri-reference": /^(?:(?:[a-z][a-z0-9+\-.]*:)?\/?\/)?(?:[^\\\s#][^\s#]*)?(?:#[^\\\s]*)?$/i, + email: /^[a-z0-9.!#$%&'*+/=?^_`{|}~-]+@[a-z0-9](?:[a-z0-9-]{0,61}[a-z0-9])?(?:\.[a-z0-9](?:[a-z0-9-]{0,61}[a-z0-9])?)*$/i + }; + exports.formatNames = Object.keys(exports.fullFormats); + function isLeapYear(year) { + return year % 4 === 0 && (year % 100 !== 0 || year % 400 === 0); + } + const DATE = /^(\d\d\d\d)-(\d\d)-(\d\d)$/; + const DAYS = [ + 0, + 31, + 28, + 31, + 30, + 31, + 30, + 31, + 31, + 30, + 31, + 30, + 31 + ]; + function date(str) { + const matches = DATE.exec(str); + if (!matches) return false; + const year = +matches[1]; + const month = +matches[2]; + const day = +matches[3]; + return month >= 1 && month <= 12 && day >= 1 && day <= (month === 2 && isLeapYear(year) ? 29 : DAYS[month]); + } + function compareDate(d1, d2) { + if (!(d1 && d2)) return void 0; + if (d1 > d2) return 1; + if (d1 < d2) return -1; + return 0; + } + const TIME = /^(\d\d):(\d\d):(\d\d(?:\.\d+)?)(z|([+-])(\d\d)(?::?(\d\d))?)?$/i; + function getTime(strictTimeZone) { + return function time(str) { + const matches = TIME.exec(str); + if (!matches) return false; + const hr = +matches[1]; + const min = +matches[2]; + const sec = +matches[3]; + const tz = matches[4]; + const tzSign = matches[5] === "-" ? -1 : 1; + const tzH = +(matches[6] || 0); + const tzM = +(matches[7] || 0); + if (tzH > 23 || tzM > 59 || strictTimeZone && !tz) return false; + if (hr <= 23 && min <= 59 && sec < 60) return true; + const utcMin = min - tzM * tzSign; + const utcHr = hr - tzH * tzSign - (utcMin < 0 ? 1 : 0); + return (utcHr === 23 || utcHr === -1) && (utcMin === 59 || utcMin === -1) && sec < 61; + }; + } + function compareTime(s1, s2) { + if (!(s1 && s2)) return void 0; + const t1 = (/* @__PURE__ */ new Date("2020-01-01T" + s1)).valueOf(); + const t2 = (/* @__PURE__ */ new Date("2020-01-01T" + s2)).valueOf(); + if (!(t1 && t2)) return void 0; + return t1 - t2; + } + function compareIsoTime(t1, t2) { + if (!(t1 && t2)) return void 0; + const a1 = TIME.exec(t1); + const a2 = TIME.exec(t2); + if (!(a1 && a2)) return void 0; + t1 = a1[1] + a1[2] + a1[3]; + t2 = a2[1] + a2[2] + a2[3]; + if (t1 > t2) return 1; + if (t1 < t2) return -1; + return 0; + } + const DATE_TIME_SEPARATOR = /t|\s/i; + function getDateTime(strictTimeZone) { + const time = getTime(strictTimeZone); + return function date_time(str) { + const dateTime = str.split(DATE_TIME_SEPARATOR); + return dateTime.length === 2 && date(dateTime[0]) && time(dateTime[1]); + }; + } + function compareDateTime(dt1, dt2) { + if (!(dt1 && dt2)) return void 0; + const d1 = new Date(dt1).valueOf(); + const d2 = new Date(dt2).valueOf(); + if (!(d1 && d2)) return void 0; + return d1 - d2; + } + function compareIsoDateTime(dt1, dt2) { + if (!(dt1 && dt2)) return void 0; + const [d1, t1] = dt1.split(DATE_TIME_SEPARATOR); + const [d2, t2] = dt2.split(DATE_TIME_SEPARATOR); + const res = compareDate(d1, d2); + if (res === void 0) return void 0; + return res || compareTime(t1, t2); + } + const NOT_URI_FRAGMENT = /\/|:/; + const URI = /^(?:[a-z][a-z0-9+\-.]*:)(?:\/?\/(?:(?:[a-z0-9\-._~!$&'()*+,;=:]|%[0-9a-f]{2})*@)?(?:\[(?:(?:(?:(?:[0-9a-f]{1,4}:){6}|::(?:[0-9a-f]{1,4}:){5}|(?:[0-9a-f]{1,4})?::(?:[0-9a-f]{1,4}:){4}|(?:(?:[0-9a-f]{1,4}:){0,1}[0-9a-f]{1,4})?::(?:[0-9a-f]{1,4}:){3}|(?:(?:[0-9a-f]{1,4}:){0,2}[0-9a-f]{1,4})?::(?:[0-9a-f]{1,4}:){2}|(?:(?:[0-9a-f]{1,4}:){0,3}[0-9a-f]{1,4})?::[0-9a-f]{1,4}:|(?:(?:[0-9a-f]{1,4}:){0,4}[0-9a-f]{1,4})?::)(?:[0-9a-f]{1,4}:[0-9a-f]{1,4}|(?:(?:25[0-5]|2[0-4]\d|[01]?\d\d?)\.){3}(?:25[0-5]|2[0-4]\d|[01]?\d\d?))|(?:(?:[0-9a-f]{1,4}:){0,5}[0-9a-f]{1,4})?::[0-9a-f]{1,4}|(?:(?:[0-9a-f]{1,4}:){0,6}[0-9a-f]{1,4})?::)|[Vv][0-9a-f]+\.[a-z0-9\-._~!$&'()*+,;=:]+)\]|(?:(?:25[0-5]|2[0-4]\d|[01]?\d\d?)\.){3}(?:25[0-5]|2[0-4]\d|[01]?\d\d?)|(?:[a-z0-9\-._~!$&'()*+,;=]|%[0-9a-f]{2})*)(?::\d*)?(?:\/(?:[a-z0-9\-._~!$&'()*+,;=:@]|%[0-9a-f]{2})*)*|\/(?:(?:[a-z0-9\-._~!$&'()*+,;=:@]|%[0-9a-f]{2})+(?:\/(?:[a-z0-9\-._~!$&'()*+,;=:@]|%[0-9a-f]{2})*)*)?|(?:[a-z0-9\-._~!$&'()*+,;=:@]|%[0-9a-f]{2})+(?:\/(?:[a-z0-9\-._~!$&'()*+,;=:@]|%[0-9a-f]{2})*)*)(?:\?(?:[a-z0-9\-._~!$&'()*+,;=:@/?]|%[0-9a-f]{2})*)?(?:#(?:[a-z0-9\-._~!$&'()*+,;=:@/?]|%[0-9a-f]{2})*)?$/i; + function uri(str) { + return NOT_URI_FRAGMENT.test(str) && URI.test(str); + } + const BYTE = /^(?:[A-Za-z0-9+/]{4})*(?:[A-Za-z0-9+/]{2}==|[A-Za-z0-9+/]{3}=)?$/gm; + function byte(str) { + BYTE.lastIndex = 0; + return BYTE.test(str); + } + const MIN_INT32 = -(2 ** 31); + const MAX_INT32 = 2 ** 31 - 1; + function validateInt32(value) { + return Number.isInteger(value) && value <= MAX_INT32 && value >= MIN_INT32; + } + function validateInt64(value) { + return Number.isInteger(value); + } + function validateNumber() { + return true; + } + const Z_ANCHOR = /[^\\]\\Z/; + function regex(str) { + if (Z_ANCHOR.test(str)) return false; + try { + new RegExp(str); + return true; + } catch (e) { + return false; + } + } +})); + +//#endregion +//#region ../../node_modules/.pnpm/ajv-formats@3.0.1_ajv@8.18.0/node_modules/ajv-formats/dist/limit.js +var require_limit = /* @__PURE__ */ __commonJSMin(((exports) => { + Object.defineProperty(exports, "__esModule", { value: true }); + exports.formatLimitDefinition = void 0; + const ajv_1 = require_ajv(); + const codegen_1 = require_codegen(); + const ops = codegen_1.operators; + const KWDs = { + formatMaximum: { + okStr: "<=", + ok: ops.LTE, + fail: ops.GT + }, + formatMinimum: { + okStr: ">=", + ok: ops.GTE, + fail: ops.LT + }, + formatExclusiveMaximum: { + okStr: "<", + ok: ops.LT, + fail: ops.GTE + }, + formatExclusiveMinimum: { + okStr: ">", + ok: ops.GT, + fail: ops.LTE + } + }; + const error = { + message: ({ keyword, schemaCode }) => (0, codegen_1.str)`should be ${KWDs[keyword].okStr} ${schemaCode}`, + params: ({ keyword, schemaCode }) => (0, codegen_1._)`{comparison: ${KWDs[keyword].okStr}, limit: ${schemaCode}}` + }; + exports.formatLimitDefinition = { + keyword: Object.keys(KWDs), + type: "string", + schemaType: "string", + $data: true, + error, + code(cxt) { + const { gen, data, schemaCode, keyword, it } = cxt; + const { opts, self } = it; + if (!opts.validateFormats) return; + const fCxt = new ajv_1.KeywordCxt(it, self.RULES.all.format.definition, "format"); + if (fCxt.$data) validate$DataFormat(); + else validateFormat(); + function validate$DataFormat() { + const fmts = gen.scopeValue("formats", { + ref: self.formats, + code: opts.code.formats + }); + const fmt = gen.const("fmt", (0, codegen_1._)`${fmts}[${fCxt.schemaCode}]`); + cxt.fail$data((0, codegen_1.or)((0, codegen_1._)`typeof ${fmt} != "object"`, (0, codegen_1._)`${fmt} instanceof RegExp`, (0, codegen_1._)`typeof ${fmt}.compare != "function"`, compareCode(fmt))); + } + function validateFormat() { + const format = fCxt.schema; + const fmtDef = self.formats[format]; + if (!fmtDef || fmtDef === true) return; + if (typeof fmtDef != "object" || fmtDef instanceof RegExp || typeof fmtDef.compare != "function") throw new Error(`"${keyword}": format "${format}" does not define "compare" function`); + const fmt = gen.scopeValue("formats", { + key: format, + ref: fmtDef, + code: opts.code.formats ? (0, codegen_1._)`${opts.code.formats}${(0, codegen_1.getProperty)(format)}` : void 0 + }); + cxt.fail$data(compareCode(fmt)); + } + function compareCode(fmt) { + return (0, codegen_1._)`${fmt}.compare(${data}, ${schemaCode}) ${KWDs[keyword].fail} 0`; + } + }, + dependencies: ["format"] + }; + const formatLimitPlugin = (ajv) => { + ajv.addKeyword(exports.formatLimitDefinition); + return ajv; + }; + exports.default = formatLimitPlugin; +})); + +//#endregion +//#region ../../node_modules/.pnpm/ajv-formats@3.0.1_ajv@8.18.0/node_modules/ajv-formats/dist/index.js +var require_dist = /* @__PURE__ */ __commonJSMin(((exports, module) => { + Object.defineProperty(exports, "__esModule", { value: true }); + const formats_1 = require_formats(); + const limit_1 = require_limit(); + const codegen_1 = require_codegen(); + const fullName = new codegen_1.Name("fullFormats"); + const fastName = new codegen_1.Name("fastFormats"); + const formatsPlugin = (ajv, opts = { keywords: true }) => { + if (Array.isArray(opts)) { + addFormats(ajv, opts, formats_1.fullFormats, fullName); + return ajv; + } + const [formats, exportName] = opts.mode === "fast" ? [formats_1.fastFormats, fastName] : [formats_1.fullFormats, fullName]; + addFormats(ajv, opts.formats || formats_1.formatNames, formats, exportName); + if (opts.keywords) (0, limit_1.default)(ajv); + return ajv; + }; + formatsPlugin.get = (name, mode = "full") => { + const f = (mode === "fast" ? formats_1.fastFormats : formats_1.fullFormats)[name]; + if (!f) throw new Error(`Unknown format "${name}"`); + return f; + }; + function addFormats(ajv, list, fs, exportName) { + var _a; + var _b; + (_a = (_b = ajv.opts.code).formats) !== null && _a !== void 0 || (_b.formats = (0, codegen_1._)`require("ajv-formats/dist/formats").${exportName}`); + for (const f of list) ajv.addFormat(f, fs[f]); + } + module.exports = exports = formatsPlugin; + Object.defineProperty(exports, "__esModule", { value: true }); + exports.default = formatsPlugin; +})); + +//#endregion +//#region ../core-internal/src/validators/ajvProvider.ts +var import_ajv = require_ajv(); +var import__2019 = require__2019(); +var import__2020 = require__2020(); +var import_dist = /* @__PURE__ */ __toESM(require_dist(), 1); +/** `ajv-formats` default export, normalised through the CJS/ESM interop wrapper. */ +const ajvProvider_CEoC_sr_addFormats = import_dist.default; +function createDefaultAjvInstance(engineClass) { + const ajv = new engineClass({ + strict: false, + validateFormats: true, + validateSchema: false, + allErrors: true + }); + ajvProvider_CEoC_sr_addFormats(ajv); + return ajv; +} +/** +* AJV-backed JSON Schema validator. See `@modelcontextprotocol/{client,server}/validators/ajv` +* for the customisation entry point (re-exports `Ajv` and `addFormats` from the bundled copy). +* +* Default dispatches on the schema's declared dialect: no `$schema` or 2020-12 → `Ajv2020` +* (SEP-1613); 2019-09 → `Ajv2019`; draft-07 or draft-06 → the classic draft-07 `Ajv` class +* (draft-07's changes over draft-06 are additive, so one engine covers both). Known draft-07 deviation: classic Ajv +* evaluates keywords adjacent to `$ref` (stricter than draft-07's ignore-siblings rule, matching +* v1's default engine), while the cfworker provider ignores them per spec. +* Schemas declaring any other `$schema` are +* rejected with a plain `Error`; pass a pre-configured Ajv instance to validate +* other dialects. The SDK bundles ajv internally but does not re-export `Ajv2020` (its type +* graph tips downstream declaration bundling — see #2339). To construct a custom 2020-12 +* instance, add `ajv` to your own dependencies (matching the SDK's pinned version) and +* `import { Ajv2020 } from 'ajv/dist/2020.js'` — `new Ajv(...)` is the draft-07 class and would +* silently downgrade dialect. +* +* @example Use with default configuration +* ```ts source="./ajvProvider.examples.ts#AjvJsonSchemaValidator_default" +* const validator = new AjvJsonSchemaValidator(); +* ``` +* +* @example Use with a custom AJV instance +* ```ts source="./ajvProvider.examples.ts#AjvJsonSchemaValidator_customInstance" +* // import { Ajv2020 } from 'ajv/dist/2020.js'; +* const ajv = new Ajv2020({ strict: false, validateSchema: false, allErrors: true }); +* const validator = new AjvJsonSchemaValidator(ajv); +* ``` +* +* @example Register ajv-formats +* ```ts source="./ajvProvider.examples.ts#AjvJsonSchemaValidator_withFormats" +* // import { Ajv2020 } from 'ajv/dist/2020.js'; +* const ajv = new Ajv2020({ strict: false, validateSchema: false, allErrors: true }); +* addFormats(ajv); +* const validator = new AjvJsonSchemaValidator(ajv); +* ``` +*/ +var AjvJsonSchemaValidator = class { + _ajv; + /** Lazy classic (draft-07) engine, built on the first draft-07/draft-06-declared schema. */ + _ajvDraft7; + /** Lazy 2019-09 engine, built on the first 2019-09-declared schema. */ + _ajv2019; + /** True iff the constructor received a caller-supplied engine; the `$schema` dispatch is skipped. */ + _userAjv; + /** + * @param ajv - Optional pre-configured AJV-compatible instance. When supplied, this instance is + * used for **every** schema regardless of its declared `$schema` (the caller owns dialect + * choice). When omitted, the provider constructs per-dialect engines (`Ajv2020`, `Ajv2019`, + * and the classic draft-07 `Ajv` for draft-07/06-declared schemas) with + * `strict: false`, `validateFormats: true`, `validateSchema: false`, `allErrors: true`, and + * `ajv-formats` registered — **lazily, on the first {@linkcode getValidator} call needing each**, so + * constructing the provider (e.g. as the default validator of a `Client`/`Server` that never + * validates a JSON Schema) does not pay the ajv + ajv-formats instantiation cost. The parameter + * is typed structurally so consumers who don't pass an instance need not have `ajv` installed. + */ + constructor(ajv) { + this._userAjv = ajv !== void 0; + this._ajv = ajv; + } + /** The underlying 2020-12 engine — the default instance is created on first use. */ + get ajv() { + return this._ajv ??= createDefaultAjvInstance(import__2020.Ajv2020); + } + /** + * Pick the engine for a schema's declared dialect. A caller-supplied engine is used for + * every schema — do not second-guess by `$schema` (bring-your-own-validator means + * bring-your-own-dialect). Otherwise: no `$schema` or 2020-12 → `Ajv2020`; 2019-09 → + * `Ajv2019`; draft-07 or draft-06 → classic `Ajv`; anything else → `Error`. + */ + _engineFor(schema) { + if (this._userAjv) return this.ajv; + const dialect = declaredDialect(schema, "pass a pre-configured Ajv instance to AjvJsonSchemaValidator(ajv) to validate other dialects."); + if (dialect === "2020-12") return this.ajv; + if (dialect === "2019-09") return this._ajv2019 ??= createDefaultAjvInstance(import__2019.Ajv2019); + return this._ajvDraft7 ??= createDefaultAjvInstance(import_ajv.Ajv); + } + getValidator(schema) { + const engine = this._engineFor(schema); + const ajvValidator = "$id" in schema && typeof schema.$id === "string" ? engine.getSchema(schema.$id) ?? engine.compile(schema) : engine.compile(schema); + return (input) => { + return ajvValidator(input) ? { + valid: true, + data: input, + errorMessage: void 0 + } : { + valid: false, + data: void 0, + errorMessage: engine.errorsText(ajvValidator.errors) + }; + }; + } +}; +/** +* Draft-07 AJV class, re-exported for consumers who need to opt back to the pre-SEP-1613 default. +* The full v1-equivalent construction is: +* +* ```ts +* const ajv = new Ajv({ strict: false, validateFormats: true, validateSchema: false, allErrors: true }); +* addFormats(ajv); +* new AjvJsonSchemaValidator(ajv); +* ``` +* +* (omitting `validateSchema: false` makes a 2020-12-stamped `$schema` fail with an opaque +* "no schema with key or ref …" engine error; omitting `addFormats` silently drops `format` +* validation that the v1 default had). +* +* The SDK bundles ajv internally but does not re-export `Ajv2020` (its type graph tips downstream +* declaration bundling — see #2339). To construct a custom 2020-12 instance, add `ajv` to your own +* dependencies (matching the SDK's pinned version) and `import { Ajv2020 } from 'ajv/dist/2020.js'`. +*/ +const ajvProvider_CEoC_sr_Ajv = import_ajv.Ajv; + +//#endregion + +//# sourceMappingURL=ajvProvider-CEoC__sr.mjs.map + + + + + + + + +//#region src/server/completable.ts +const COMPLETABLE_SYMBOL = Symbol.for("mcp.completable"); +/** +* Wraps a schema to provide autocompletion capabilities. Useful for, e.g., prompt arguments in MCP. +* +* @example +* ```ts source="./completable.examples.ts#completable_basicUsage" +* server.registerPrompt( +* 'review-code', +* { +* title: 'Code Review', +* argsSchema: z.object({ +* language: completable(z.string().describe('Programming language'), value => +* ['typescript', 'javascript', 'python', 'rust', 'go'].filter(lang => lang.startsWith(value)) +* ) +* }) +* }, +* ({ language }) => ({ +* messages: [ +* { +* role: 'user' as const, +* content: { +* type: 'text' as const, +* text: `Review this ${language} code.` +* } +* } +* ] +* }) +* ); +* ``` +* +* @see {@linkcode server/mcp.McpServer.registerPrompt | McpServer.registerPrompt} for using completable schemas in prompt argument definitions +*/ +function completable(schema, complete) { + Object.defineProperty(schema, COMPLETABLE_SYMBOL, { + value: { complete }, + enumerable: false, + writable: false, + configurable: false + }); + return schema; +} +/** +* Checks if a schema is completable (has completion metadata). +*/ +function isCompletable(schema) { + return !!schema && typeof schema === "object" && COMPLETABLE_SYMBOL in schema; +} +/** +* Gets the completer callback from a completable schema, if it exists. +*/ +function getCompleter(schema) { + return schema[COMPLETABLE_SYMBOL]?.complete; +} + +//#endregion +//#region src/server/sseKeepAlive.ts +/** Default interval between SSE keep-alive comment frames. */ +const mcp_DXXb3Vv3_DEFAULT_SSE_KEEP_ALIVE_MS = 15e3; +const MAX_TIMER_DELAY_MS = (/* unused pure expression or super */ null && (2 ** 31 - 1)); +/** Arms an unref'd timer, or disables keep-alive for invalid delays. */ +function mcp_DXXb3Vv3_armSseKeepAlive(intervalMs, onTick) { + if (!Number.isFinite(intervalMs) || intervalMs < 1) return; + const timer = setInterval(onTick, Math.min(intervalMs, MAX_TIMER_DELAY_MS)); + timer.unref?.(); + return timer; +} + +//#endregion +//#region src/server/serverEventBus.ts +/** +* A `ServerEventBus` backed by an in-process listener set. +* +* `publish()` delivers synchronously to the live listener set (a listener +* unsubscribing itself mid-dispatch is safe; the entry's listen-router +* listeners never unsubscribe peers). A throwing listener does not stop +* delivery to the others. +*/ +var mcp_DXXb3Vv3_InMemoryServerEventBus = class { + _listeners = /* @__PURE__ */ new Set(); + /** + * @param onerror - Optional callback for errors thrown by listeners + * during dispatch. + */ + constructor(onerror) { + this.onerror = onerror; + } + publish(event) { + for (const listener of this._listeners) try { + listener(event); + } catch (error) { + this.onerror?.(error instanceof Error ? error : new Error(String(error))); + } + } + subscribe(listener) { + this._listeners.add(listener); + let live = true; + return () => { + if (!live) return; + live = false; + this._listeners.delete(listener); + }; + } + /** The number of currently registered listeners (test/introspection only — the routers track capacity via their own open-subscription set). */ + get listenerCount() { + return this._listeners.size; + } +}; +/** Build a {@linkcode ServerNotifier} over a bus. */ +function mcp_DXXb3Vv3_createServerNotifier(bus) { + return { + toolsChanged: () => bus.publish({ kind: "tools_list_changed" }), + promptsChanged: () => bus.publish({ kind: "prompts_list_changed" }), + resourcesChanged: () => bus.publish({ kind: "resources_list_changed" }), + resourceUpdated: (uri) => bus.publish({ + kind: "resource_updated", + uri + }) + }; +} +/** +* Whether a `subscriptions/listen` filter accepts a given change event. +* +* Pure: no I/O, no mutation. The filter governs ONLY the four +* subscription-gated change types — non-gated notifications never reach the +* bus and are not modeled here. +* +* `resource_updated` matches only when `resourceSubscriptions` is present and +* contains the event's URI exactly (per the spec: "for these resource URIs"). +*/ +function listenFilterAccepts(filter, event) { + switch (event.kind) { + case "tools_list_changed": return filter.toolsListChanged === true; + case "prompts_list_changed": return filter.promptsListChanged === true; + case "resources_list_changed": return filter.resourcesListChanged === true; + case "resource_updated": return filter.resourceSubscriptions !== void 0 && filter.resourceSubscriptions.includes(event.uri); + } +} +/** +* The honored subset of a requested filter: keeps only the fields the client +* explicitly opted in to (drops `false` and absent fields), narrowed against +* the server's declared capabilities when supplied. The serving entry sends +* this back in `notifications/subscriptions/acknowledged` so the ack reflects +* what the server can actually deliver. +* +* - `toolsListChanged` is honored only when `capabilities.tools.listChanged` +* is advertised; likewise `promptsListChanged` / `resourcesListChanged`. +* - `resourceSubscriptions` is honored only when +* `capabilities.resources.subscribe` is advertised. +* +* `capabilities` is optional on this pure helper for test convenience only — +* both wired routers REQUIRE capabilities at the call site (the HTTP router's +* `serve()` takes a required parameter; `StdioListenRouter.serve()` throws +* before `setServerCapabilities()` was called), so the fail-open +* `undefined → honor everything` branch is never reachable on a wired entry. +*/ +function honoredSubset(requested, capabilities) { + const honored = {}; + const allow = (bit) => capabilities === void 0 || bit === true; + if (requested.toolsListChanged === true && allow(capabilities?.tools?.listChanged)) honored.toolsListChanged = true; + if (requested.promptsListChanged === true && allow(capabilities?.prompts?.listChanged)) honored.promptsListChanged = true; + if (requested.resourcesListChanged === true && allow(capabilities?.resources?.listChanged)) honored.resourcesListChanged = true; + if (requested.resourceSubscriptions !== void 0 && requested.resourceSubscriptions.length > 0 && allow(capabilities?.resources?.subscribe)) honored.resourceSubscriptions = [...requested.resourceSubscriptions]; + return honored; +} +/** Map a {@linkcode ServerEvent} onto its wire notification `{method, params}`. */ +function serverEventToNotification(event) { + switch (event.kind) { + case "tools_list_changed": return { method: "notifications/tools/list_changed" }; + case "prompts_list_changed": return { method: "notifications/prompts/list_changed" }; + case "resources_list_changed": return { method: "notifications/resources/list_changed" }; + case "resource_updated": return { + method: "notifications/resources/updated", + params: { uri: event.uri } + }; + } +} + +//#endregion +//#region src/server/listenRouter.ts +/** Default capacity guard: refuse a new subscription when this many are already open. */ +const mcp_DXXb3Vv3_DEFAULT_MAX_SUBSCRIPTIONS = 1024; +function jsonRpcError(id, code, message) { + return Response.json({ + jsonrpc: "2.0", + error: { + code, + message + }, + id + }, { status: 200 }); +} +/** Stamp the subscription id onto a notification's `_meta`. Non-mutating. */ +function stampSubscriptionId(notification, subscriptionId) { + return { + method: notification.method, + params: { + ...notification.params, + _meta: { + ...notification.params?._meta, + [SUBSCRIPTION_ID_META_KEY]: subscriptionId + } + } + }; +} +/** +* Read the requested filter off a `subscriptions/listen` request body. +* Returns the validated filter, or `undefined` when `params.notifications` +* is absent or fails the schema (the caller answers `-32602` — the spec +* marks `notifications` REQUIRED on the listen request). +*/ +function parseListenFilter(message) { + const outcome = codecForVersion(MODERN_WIRE_REVISION).validateRequest("subscriptions/listen", message); + return outcome.ok ? outcome.value.params?.notifications : void 0; +} +function mcp_DXXb3Vv3_createListenRouter(options) { + const { bus, onerror } = options; + const maxSubscriptions = options.maxSubscriptions ?? mcp_DXXb3Vv3_DEFAULT_MAX_SUBSCRIPTIONS; + const keepAliveMs = options.keepAliveMs ?? mcp_DXXb3Vv3_DEFAULT_SSE_KEEP_ALIVE_MS; + const open = /* @__PURE__ */ new Set(); + function serve(message, signal, capabilities, serverInfo) { + if (open.size >= maxSubscriptions) { + onerror?.(/* @__PURE__ */ new Error(`subscriptions/listen refused: subscription limit reached (${maxSubscriptions})`)); + return jsonRpcError(message.id, -32603, "Subscription limit reached"); + } + const filter = parseListenFilter(message); + if (filter === void 0) return jsonRpcError(message.id, -32602, "Invalid params: 'notifications' is required and must be a valid SubscriptionFilter"); + const honored = honoredSubset(filter, capabilities); + const subscriptionId = message.id; + const encoder = new TextEncoder(); + let controller; + let closed = false; + let unsubscribe; + let keepAliveTimer; + let abortCleanup; + const writeFrame = (frame) => { + if (closed) return; + try { + controller.enqueue(encoder.encode(frame)); + } catch (error) { + onerror?.(error instanceof Error ? error : new Error(String(error))); + } + }; + const writeNotification = (method, params) => { + writeFrame(`event: message\ndata: ${JSON.stringify({ + jsonrpc: "2.0", + method, + params + })}\n\n`); + }; + const teardown = (graceful) => { + if (closed) return; + if (graceful) writeFrame(`event: message\ndata: ${JSON.stringify({ + jsonrpc: "2.0", + id: subscriptionId, + result: { + resultType: "complete", + _meta: { + [SUBSCRIPTION_ID_META_KEY]: subscriptionId, + [SERVER_INFO_META_KEY]: serverInfo + } + } + })}\n\n`); + closed = true; + try { + unsubscribe?.(); + } catch (error) { + onerror?.(error instanceof Error ? error : new Error(String(error))); + } + if (keepAliveTimer !== void 0) clearInterval(keepAliveTimer); + abortCleanup?.(); + open.delete(teardown); + try { + controller.close(); + } catch {} + }; + const readable = new ReadableStream({ + start(streamController) { + controller = streamController; + const ack = stampSubscriptionId({ + method: "notifications/subscriptions/acknowledged", + params: { notifications: honored } + }, subscriptionId); + writeNotification(ack.method, ack.params); + unsubscribe = bus.subscribe((event) => { + if (closed || !listenFilterAccepts(honored, event)) return; + const note = stampSubscriptionId(serverEventToNotification(event), subscriptionId); + writeNotification(note.method, note.params); + }); + keepAliveTimer = mcp_DXXb3Vv3_armSseKeepAlive(keepAliveMs, () => writeFrame(": keepalive\n\n")); + open.add(teardown); + }, + cancel() { + teardown(false); + } + }); + if (signal !== void 0) if (signal.aborted) teardown(false); + else { + const onAbort = () => teardown(false); + signal.addEventListener("abort", onAbort, { once: true }); + abortCleanup = () => signal.removeEventListener("abort", onAbort); + } + return new Response(readable, { + status: 200, + headers: { + "Content-Type": "text/event-stream", + "Cache-Control": "no-cache, no-transform", + Connection: "keep-alive", + "X-Accel-Buffering": "no" + } + }); + } + return { + serve, + closeAll() { + for (const teardown of open) teardown(true); + }, + get openCount() { + return open.size; + } + }; +} +const CHANGE_NOTIFICATION_METHODS = new Set([ + "notifications/tools/list_changed", + "notifications/prompts/list_changed", + "notifications/resources/list_changed", + "notifications/resources/updated" +]); +/** +* Per-connection listen state for the stdio entry. One instance is held by +* `serveStdio` for the connection lifetime; it routes inbound +* `subscriptions/listen` / `notifications/cancelled` and rewrites outbound +* change notifications onto the active subscriptions. No bus — the long-lived +* pinned instance's existing `send*ListChanged()` calls feed straight into +* `routeOutbound()`. +*/ +var mcp_DXXb3Vv3_StdioListenRouter = class { + /** Active subscriptions, keyed by the listen request's JSON-RPC id verbatim. */ + _subs = /* @__PURE__ */ new Map(); + /** + * The serving instance's declared capabilities. Filled in by the entry + * once the modern instance is constructed (the router is created before + * the instance exists), so the acknowledged filter is narrowed against + * what the server can actually deliver. + */ + _serverCapabilities; + /** + * The serving instance's identity, stamped onto the graceful-close + * results' `_meta` (the spec's `SubscriptionsListenResultMeta` extends + * `ResultMetaObject`). Handed over together with the capabilities. + */ + _serverInfo; + constructor(_maxSubscriptions = mcp_DXXb3Vv3_DEFAULT_MAX_SUBSCRIPTIONS, serverCapabilities, serverInfo) { + this._maxSubscriptions = _maxSubscriptions; + this._serverCapabilities = serverCapabilities; + this._serverInfo = serverInfo; + } + /** + * Record the serving instance's declared capabilities and identity once + * it has been constructed. Called by `serveStdio`'s connect path; + * subsequent `serve()` calls narrow the honored filter against the + * capabilities, and `teardownAll()` stamps the identity. + */ + setServerCapabilities(capabilities, serverInfo) { + this._serverCapabilities = capabilities; + if (serverInfo !== void 0) this._serverInfo = serverInfo; + } + /** Whether `id` is an active listen subscription on this connection. */ + has(id) { + return this._subs.has(id); + } + /** + * Serve one inbound `subscriptions/listen` request: registers the + * subscription and returns the stamped acknowledged notification (or, on + * capacity / params rejection, the in-band JSON-RPC error response). + * + * @throws when called before {@linkcode setServerCapabilities} (or the + * constructor) has supplied the serving instance's capabilities. Honoring a + * filter without knowing the server's advertised capabilities would fail + * open (deliver unadvertised types); the entry guarantees capabilities are + * set before any listen request is routed here. + */ + serve(message) { + if (this._serverCapabilities === void 0) throw new Error("StdioListenRouter.serve() called before setServerCapabilities(); refusing to honor a filter without capabilities"); + if (this._subs.size >= this._maxSubscriptions) return { + jsonrpc: "2.0", + id: message.id, + error: { + code: -32603, + message: "Subscription limit reached" + } + }; + const filter = parseListenFilter(message); + if (filter === void 0) return { + jsonrpc: "2.0", + id: message.id, + error: { + code: -32602, + message: "Invalid params: 'notifications' is required and must be a valid SubscriptionFilter" + } + }; + const honored = honoredSubset(filter, this._serverCapabilities); + this._subs.set(message.id, honored); + return stampSubscriptionId({ + method: "notifications/subscriptions/acknowledged", + params: { notifications: honored } + }, message.id); + } + /** + * Tear down one subscription (inbound `notifications/cancelled`). Returns + * `true` when a subscription was removed. After this call NOTHING further + * is delivered for that subscription id (the post-cancel hardening). + */ + cancel(id) { + return this._subs.delete(id); + } + /** + * Route an outbound notification through the active subscriptions. + * + * - For a subscription-gated change notification, returns one stamped copy + * per subscription that opted in to it (an empty array means it is + * dropped — the modern era never delivers an un-requested change type). + * - For any other outbound message, returns `'passthrough'` (the entry + * forwards it as-is). + */ + routeOutbound(message) { + if (!CHANGE_NOTIFICATION_METHODS.has(message.method)) return "passthrough"; + const uriParam = message.params?.["uri"]; + const uri = typeof uriParam === "string" ? uriParam : void 0; + const event = notificationToServerEvent(message.method, uri); + const out = []; + for (const [subscriptionId, filter] of this._subs) if (listenFilterAccepts(filter, event)) out.push(stampSubscriptionId({ + method: message.method, + params: message.params ?? {} + }, subscriptionId)); + return out; + } + /** + * Server-side graceful teardown of every active subscription: returns the + * empty `subscriptions/listen` JSON-RPC result for each subscription id — + * the spec's graceful-close signal, `_meta` carrying the subscription id + * and the serving instance's identity — for the entry to emit before + * closing the wire. Clears the set so nothing further is delivered. + */ + teardownAll() { + const out = []; + for (const id of this._subs.keys()) out.push({ + jsonrpc: "2.0", + id, + result: { + resultType: "complete", + _meta: { + [SUBSCRIPTION_ID_META_KEY]: id, + ...this._serverInfo !== void 0 && { [SERVER_INFO_META_KEY]: this._serverInfo } + } + } + }); + this._subs.clear(); + return out; + } +}; +function notificationToServerEvent(method, uri) { + switch (method) { + case "notifications/tools/list_changed": return { kind: "tools_list_changed" }; + case "notifications/prompts/list_changed": return { kind: "prompts_list_changed" }; + case "notifications/resources/list_changed": return { kind: "resources_list_changed" }; + default: return { + kind: "resource_updated", + uri: uri ?? "" + }; + } +} + +//#endregion +//#region src/server/legacyInputRequiredShim.ts +/** +* Default handler re-entries per originating request — tighter than the +* client driver's 10 because the shim holds a live wire request open. +*/ +const DEFAULT_LEGACY_SHIM_MAX_ROUNDS = 8; +/** Default per-leg timeout: legs are human-paced, so the 60s protocol default is wrong. */ +const DEFAULT_LEGACY_SHIM_ROUND_TIMEOUT_MS = 6e5; +/** Resolves and validates `ServerOptions.inputRequired`, failing loudly at construction time. */ +function resolveLegacyShimOptions(options) { + if (options?.maxRounds !== void 0 && (!Number.isInteger(options.maxRounds) || options.maxRounds < 1)) throw new RangeError(`inputRequired.maxRounds must be a positive integer (got ${options.maxRounds})`); + if (options?.roundTimeoutMs !== void 0 && (!Number.isFinite(options.roundTimeoutMs) || options.roundTimeoutMs <= 0)) throw new RangeError(`inputRequired.roundTimeoutMs must be a positive number (got ${options.roundTimeoutMs})`); + return { + maxRounds: options?.maxRounds ?? DEFAULT_LEGACY_SHIM_MAX_ROUNDS, + roundTimeoutMs: options?.roundTimeoutMs ?? DEFAULT_LEGACY_SHIM_ROUND_TIMEOUT_MS, + legacyShim: options?.legacyShim ?? true + }; +} +/** +* Validates one `inputRequests` entry: malformed or unknown kinds are server +* bugs and fail loudly on both eras. Shared by the modern seam's capability +* check and the shim's gate. +*/ +function coerceEmbeddedInputRequest(method, key, entry) { + if (entry === null || typeof entry !== "object" || typeof entry.method !== "string") throw new src_CX2iR2pK_ProtocolError(src_CX2iR2pK_ProtocolErrorCode.InternalError, `Handler for ${method} returned an invalid input request '${key}': each inputRequests entry must be an embedded elicitation/create, sampling/createMessage, or roots/list request`); + const embedded = entry; + const required = requiredClientCapabilitiesForInputRequest(embedded); + if (required === void 0) throw new src_CX2iR2pK_ProtocolError(src_CX2iR2pK_ProtocolErrorCode.InternalError, `Handler for ${method} returned an input request '${key}' of kind '${embedded.method}', which is not an embedded request the 2026-07-28 revision defines`); + return { + embedded, + required + }; +} +/** +* The 2025-11-25 URL-mode wire shape requires an `elicitationId`; the 2026 +* in-band shape has none, so URL legs mint one (CSPRNG-backed, with a +* getRandomValues fallback for runtimes without `randomUUID`). +*/ +function syntheticElicitationId() { + const webCrypto = globalThis.crypto; + if (webCrypto?.randomUUID !== void 0) return webCrypto.randomUUID(); + const bytes = new Uint8Array(16); + webCrypto.getRandomValues(bytes); + bytes[6] = bytes[6] & 15 | 64; + bytes[8] = bytes[8] & 63 | 128; + const hex = [...bytes].map((byte) => byte.toString(16).padStart(2, "0")).join(""); + return `${hex.slice(0, 8)}-${hex.slice(8, 12)}-${hex.slice(12, 16)}-${hex.slice(16, 20)}-${hex.slice(20)}`; +} +/** Per-family surfacing: tools/call → isError result (the 2025 idiom); prompts/resources → JSON-RPC error. */ +function legacyShimFailure(method, message) { + if (method === "tools/call") return { + content: [{ + type: "text", + text: message + }], + isError: true + }; + throw new src_CX2iR2pK_ProtocolError(src_CX2iR2pK_ProtocolErrorCode.InternalError, message); +} +/** The fulfilment loop — see the module doc for the contract. */ +var LegacyInputRequiredShim = class { + constructor(_host) { + this._host = _host; + } + async fulfill(method, handler, request, ctx, firstResult) { + const { maxRounds, roundTimeoutMs } = this._host; + const outerSignal = ctx.mcpReq.signal; + let current = firstResult; + let round = 0; + while (true) { + round += 1; + if (round > maxRounds) return legacyShimFailure(method, inputRequiredRoundsExceededMessage(method, maxRounds)); + const inputRequests = current.inputRequests; + const hasInputRequests = inputRequests != null && Object.keys(inputRequests).length > 0; + const requestState = typeof current.requestState === "string" ? current.requestState : void 0; + if (!hasInputRequests && requestState === void 0) throw new src_CX2iR2pK_ProtocolError(src_CX2iR2pK_ProtocolErrorCode.InternalError, `Handler for ${method} returned an input-required result with neither inputRequests nor requestState (every InputRequiredResult must include at least one of the two)`); + let responses; + if (hasInputRequests) { + const declared = this._host.resolvedClientCapabilities(ctx); + const coerced = []; + for (const [key, entry] of Object.entries(inputRequests)) { + const { embedded, required } = coerceEmbeddedInputRequest(method, key, entry); + if (embedded.method !== "roots/list" && embedded.params === void 0) throw new src_CX2iR2pK_ProtocolError(src_CX2iR2pK_ProtocolErrorCode.InternalError, `Handler for ${method} returned an input request '${key}' of kind '${embedded.method}' without params`); + if (src_CX2iR2pK_missingClientCapabilities(required, declared) !== void 0) return legacyShimFailure(method, `Cannot request input '${key}' (${embedded.method}): the client on this 2025-era connection did not declare the required capability${declared === void 0 ? " (no client capabilities are available on this connection — per-request legacy serving cannot receive server-to-client requests)" : ""}`); + coerced.push([key, embedded]); + } + const roundAbort = linkedRoundAbort(outerSignal); + try { + const legOptions = { + relatedRequestId: ctx.mcpReq.id, + timeout: roundTimeoutMs, + resetTimeoutOnProgress: true, + onprogress: () => {}, + signal: roundAbort.signal + }; + const fulfilled = await Promise.all(coerced.map(async ([key, embedded]) => { + try { + return [key, await this._dispatchLeg(embedded, legOptions)]; + } catch (error) { + roundAbort.abort(error); + throw error; + } + })); + responses = Object.fromEntries(fulfilled); + } catch (error) { + if (outerSignal.aborted) throw error; + return legacyShimFailure(method, `Fulfilling input required by '${method}' failed: ${error instanceof Error ? error.message : String(error)}`); + } finally { + roundAbort.dispose(); + } + } else await sleep((/* inlined export .C */250), outerSignal); + let ctxNext = { + ...ctx, + mcpReq: { + ...ctx.mcpReq, + inputResponses: responses, + droppedInputResponseKeys: void 0, + requestState: requestStateAccessor(requestState) + } + }; + if (requestState !== void 0) { + const decoded = await this._host.verifyRequestState(requestState, ctxNext, method); + if (decoded !== void 0) ctxNext = withRequestStateValue(ctxNext, decoded); + } + const next = await handler(request, ctxNext); + if (!isInputRequiredResult(next)) return next; + current = next; + } + } + /** Routes one embedded request through the host's existing 2025-era senders (gate already ran). */ + async _dispatchLeg(embedded, options) { + switch (embedded.method) { + case "elicitation/create": { + let params = embedded.params; + if (params.mode === "url" && params.elicitationId === void 0) params = { + ...params, + elicitationId: syntheticElicitationId() + }; + return await this._host.sendElicitation(params, options); + } + case "sampling/createMessage": return await this._host.sendSampling(embedded.params, options); + case "roots/list": return await this._host.listRoots(embedded.params, options); + } + } +}; + +//#endregion +//#region src/server/server.ts +/** +* The request methods whose 2026-07-28 result vocabulary includes +* `input_required` (the multi round-trip methods). Returning an +* input-required result from any other handler is a server bug. +*/ +const INPUT_REQUIRED_CAPABLE_METHODS = new Set([ + "tools/call", + "prompts/get", + "resources/read" +]); +let writeClientIdentity; +let installDiscoverHandler; +let readServerIdentity; +/** +* Package-internal: backfills the connection-scoped client-identity fields of a +* per-request server instance from the request's validated `_meta` envelope, so the +* (deprecated) {@linkcode Server.getClientCapabilities} / {@linkcode Server.getClientVersion} +* accessors keep answering on instances that never see an `initialize` handshake. +* Not public API. +*/ +function mcp_DXXb3Vv3_seedClientIdentityFromEnvelope(server, identity) { + writeClientIdentity(server, identity); +} +/** +* Package-internal: installs the modern-only `server/discover` handler on an instance +* the HTTP entry has marked as serving the 2026-07-28 era, and makes sure the modern +* revisions the entry serves appear in the instance's supported-versions list (so the +* discover advertisement and version-mismatch errors name them). Idempotent. +* Hand-constructed instances are unaffected: nothing else calls this, so they keep +* answering `-32601` unless their own supported-versions list opts into a modern +* revision. Not public API. +*/ +function mcp_DXXb3Vv3_installModernOnlyHandlers(server, servedModernVersions) { + installDiscoverHandler(server, servedModernVersions); +} +/** +* Package-internal: the instance's implementation identity, for the serving +* entries to stamp onto entry-built results (the `subscriptions/listen` +* graceful-close result — built outside the encode seam, but the spec's +* `SubscriptionsListenResultMeta` extends `ResultMetaObject`, so it carries +* the serverInfo SHOULD like every other result). Not public API. +*/ +function mcp_DXXb3Vv3_serverIdentityOf(server) { + return readServerIdentity(server); +} +/** +* An MCP server on top of a pluggable transport. +* +* This server will automatically respond to the initialization flow as initiated from the client. +* +* @deprecated Use {@linkcode server/mcp.McpServer | McpServer} instead for the high-level API. Only use `Server` for advanced use cases. +*/ +var Server = class extends Protocol { + _clientCapabilities; + _clientVersion; + static { + writeClientIdentity = (server, identity) => { + if (identity.clientCapabilities !== void 0) server._clientCapabilities = identity.clientCapabilities; + if (identity.clientInfo !== void 0) server._clientVersion = identity.clientInfo; + }; + installDiscoverHandler = (server, servedModernVersions) => { + const missing = servedModernVersions.filter((version) => !server._supportedProtocolVersions.includes(version)); + if (missing.length > 0) server._supportedProtocolVersions = [...server._supportedProtocolVersions, ...missing]; + server.setRequestHandler("server/discover", () => server._ondiscover()); + }; + readServerIdentity = (server) => server._serverInfo; + } + _capabilities; + _instructions; + _jsonSchemaValidator; + _cacheHints; + _requestStateVerify; + _inputRequiredServing; + _legacyShim; + /** Lazily-built legacy shim; the loop lives in legacyInputRequiredShim.ts behind a narrow host contract. */ + _legacyInputRequiredShim() { + return this._legacyShim ??= new LegacyInputRequiredShim({ + maxRounds: this._inputRequiredServing.maxRounds, + roundTimeoutMs: this._inputRequiredServing.roundTimeoutMs, + resolvedClientCapabilities: (ctx) => this._inputRequestCapabilityView(ctx), + verifyRequestState: (state, ctx, method) => this._verifyRequestState(state, ctx, method), + sendElicitation: (params, options) => this._sendElicitationLeg(params, options, { validateAcceptedContent: false }), + sendSampling: (params, options) => this.createMessage(params, options), + listRoots: (params, options) => this.listRoots(params, options) + }); + } + /** + * Callback for when initialization has fully completed (i.e., the client has sent an `notifications/initialized` notification). + */ + oninitialized; + /** + * Initializes this server with the given name and version information. + */ + constructor(_serverInfo, options) { + super(options); + this._serverInfo = _serverInfo; + this._capabilities = options?.capabilities ? { ...options.capabilities } : {}; + this._instructions = options?.instructions; + this._jsonSchemaValidator = options?.jsonSchemaValidator ?? new AjvJsonSchemaValidator(); + this._requestStateVerify = options?.requestState?.verify; + this._inputRequiredServing = resolveLegacyShimOptions(options?.inputRequired); + if (options?.cacheHints !== void 0) { + for (const [operation, hint] of Object.entries(options.cacheHints)) if (hint !== void 0) assertValidCacheHint(hint, `cacheHints['${operation}']`); + this._cacheHints = options.cacheHints; + } + this.setRequestHandler("initialize", (request) => this._oninitialize(request)); + this.setNotificationHandler("notifications/initialized", () => this.oninitialized?.()); + if (modernProtocolVersions(this._supportedProtocolVersions).length > 0) this.setRequestHandler("server/discover", () => this._ondiscover()); + if (this._capabilities.logging) this._registerLoggingHandler(); + } + /** + * Registers the built-in `logging/setLevel` request handler. + * + * @deprecated Deprecated as of protocol version 2026-07-28 (SEP-2577). + * Remains functional during the deprecation window (at least twelve months). + * Migrate to stderr logging (STDIO servers) or OpenTelemetry. + */ + _registerLoggingHandler() { + this.setRequestHandler("logging/setLevel", async (request, ctx) => { + const transportSessionId = ctx.sessionId || ctx.http?.req?.headers.get("mcp-session-id") || void 0; + const { level } = request.params; + const parseResult = parseSchema(LoggingLevelSchema, level); + if (parseResult.success) this._loggingLevels.set(transportSessionId, parseResult.data); + return {}; + }); + } + buildContext(ctx, transportInfo) { + const hasHttpInfo = ctx.http || transportInfo?.request || transportInfo?.closeSSEStream || transportInfo?.closeStandaloneSSEStream; + return { + ...ctx, + mcpReq: { + ...ctx.mcpReq, + log: (level, data, logger) => { + if (!this._capabilities.logging) return Promise.resolve(); + let threshold; + if (this._servedModernEra()) { + threshold = ctx.mcpReq.envelope?.[LOG_LEVEL_META_KEY]; + if (threshold === void 0) return Promise.resolve(); + } else threshold = this._loggingLevels.get(ctx.sessionId) ?? this._loggingLevels.get(void 0); + if (threshold !== void 0 && this.LOG_LEVEL_SEVERITY.get(level) < this.LOG_LEVEL_SEVERITY.get(threshold)) return Promise.resolve(); + return ctx.mcpReq.notify({ + method: "notifications/message", + params: { + level, + data, + logger + } + }); + }, + elicitInput: (params, options) => this.elicitInput(params, options), + requestSampling: (params, options) => this.createMessage(params, options) + }, + http: hasHttpInfo ? { + ...ctx.http, + req: transportInfo?.request, + closeSSE: transportInfo?.closeSSEStream, + closeStandaloneSSE: transportInfo?.closeStandaloneSSEStream + } : void 0 + }; + } + _loggingLevels = /* @__PURE__ */ new Map(); + LOG_LEVEL_SEVERITY = new Map(LoggingLevelSchema.options.map((level, index) => [level, index])); + isMessageIgnored = (level, sessionId) => { + const currentLevel = this._loggingLevels.get(sessionId); + return currentLevel ? this.LOG_LEVEL_SEVERITY.get(level) < this.LOG_LEVEL_SEVERITY.get(currentLevel) : false; + }; + /** + * Registers new capabilities. This can only be called before connecting to a transport. + * + * The new capabilities will be merged with any existing capabilities previously given (e.g., at initialization). + */ + registerCapabilities(capabilities) { + if (this.transport) throw new src_CX2iR2pK_SdkError(src_CX2iR2pK_SdkErrorCode.AlreadyConnected, "Cannot register capabilities after connecting to transport"); + const hadLogging = !!this._capabilities.logging; + this._capabilities = mergeCapabilities(this._capabilities, capabilities); + if (!hadLogging && this._capabilities.logging) this._registerLoggingHandler(); + } + /** + * Enforces server-side validation for `tools/call` results regardless of how the + * handler was registered, attaches the configured per-operation cache hint + * (when one exists) so the 2026-07-28 encode seam can fill `ttlMs`/`cacheScope` + * for results that do not provide their own, and owns the multi-round-trip + * seam: on the methods whose 2026-07-28 result vocabulary includes + * `input_required` (`tools/call`, `prompts/get`, `resources/read`) an + * input-required return skips result-schema validation and is checked + * against the served era, the at-least-one rule, and the request's own + * declared client capabilities; on every other method an input-required + * return is a server bug and fails loudly. The hint rides a symbol-keyed + * property that is never serialized, so 2025-era responses are unaffected. + */ + _wrapHandler(method, handler) { + if (method !== "tools/call") { + const cacheHint = this._cacheHints?.[method]; + const isInputRequiredCapable = INPUT_REQUIRED_CAPABLE_METHODS.has(method); + if (cacheHint === void 0 && !isInputRequiredCapable) return async (request, ctx) => { + const result = await handler(request, ctx); + if (isInputRequiredResult(result)) throw new src_CX2iR2pK_ProtocolError(src_CX2iR2pK_ProtocolErrorCode.InternalError, `Handler for ${method} returned an input-required result, but only tools/call, prompts/get and resources/read support input_required (protocol revision 2026-07-28)`); + return result; + }; + return async (request, ctx) => { + const result = isInputRequiredCapable ? await this._invokeInputRequiredCapableHandler(method, handler, request, ctx) : await handler(request, ctx); + if (isInputRequiredResult(result)) { + if (!isInputRequiredCapable) throw new src_CX2iR2pK_ProtocolError(src_CX2iR2pK_ProtocolErrorCode.InternalError, `Handler for ${method} returned an input-required result, but only tools/call, prompts/get and resources/read support input_required (protocol revision 2026-07-28)`); + return result; + } + return cacheHint === void 0 ? result : attachCacheHintFallback(result, cacheHint); + }; + } + return async (request, ctx) => { + const codec = src_CX2iR2pK_codecForVersion(this._negotiatedProtocolVersion); + const validatedRequest = codec.validateRequest("tools/call", request); + if (!validatedRequest.ok) throw new src_CX2iR2pK_ProtocolError(validatedRequest.reason === "not-in-era" ? src_CX2iR2pK_ProtocolErrorCode.InternalError : src_CX2iR2pK_ProtocolErrorCode.InvalidParams, validatedRequest.reason === "not-in-era" ? "No wire schema for tools/call in the resolved era" : `Invalid tools/call request: ${validatedRequest.message}`); + const result = await this._invokeInputRequiredCapableHandler("tools/call", handler, request, ctx); + if (isInputRequiredResult(result)) return result; + const normalizedResult = normalizeContentlessToolResult(result); + const validationResult = codec.validateResult("tools/call", normalizedResult); + if (!validationResult.ok) throw new src_CX2iR2pK_ProtocolError(validationResult.reason === "not-in-era" ? src_CX2iR2pK_ProtocolErrorCode.InternalError : src_CX2iR2pK_ProtocolErrorCode.InvalidParams, validationResult.reason === "not-in-era" ? "No wire schema for tools/call in the resolved era" : `Invalid tools/call result: ${validationResult.message}`); + return validationResult.value; + }; + } + /** + * Whether this instance is bound to a 2026-07-28-or-later protocol + * revision. Era is instance state — a serving entry (`createMcpHandler`, + * `serveStdio`) marks the instance modern at construction; a 2025-era + * `initialize` handshake binds it legacy. The multi-round-trip seam reads + * this directly: there is no per-request era consult. + */ + _servedModernEra() { + return this._negotiatedProtocolVersion !== void 0 && isModernProtocolVersion(this._negotiatedProtocolVersion); + } + /** + * Invokes a handler for one of the multi-round-trip methods and applies + * the input-required seam: + * + * - a `UrlElicitationRequiredError` (or any 2025-style server→client + * request idiom) escaping the handler on a request served on the + * 2026-07-28 era fails LOUDLY with a clear steer to + * `inputRequired.elicitUrl(...)` — the `-32042` error never reaches the + * 2026-07-28 wire and the throw is not silently converted. Requests + * served on the 2025 era keep today's `-32042` behavior byte-exact (the + * error is rethrown unchanged). + * - an input-required RETURN toward a 2026-07-28 request must satisfy + * the at-least-one rule, and every embedded request must be covered by + * the capabilities declared on the request's envelope (violations + * answer the typed `-32021` error). Toward a 2025-era request the + * return is fulfilled by the default-on legacy shim, whose own gate + * consults the initialize-declared capabilities and surfaces + * violations per family; `inputRequired.legacyShim: false` restores + * the pre-shim loud failure. + */ + async _invokeInputRequiredCapableHandler(method, handler, request, ctx) { + const servedModern = this._servedModernEra(); + const rawRequestState = ctx.mcpReq.requestState(); + if (rawRequestState !== void 0 && typeof rawRequestState !== "string") throw new src_CX2iR2pK_ProtocolError(src_CX2iR2pK_ProtocolErrorCode.InvalidParams, "Invalid or expired requestState", { reason: "invalid_request_state" }); + let ctxForHandler = ctx; + if (typeof rawRequestState === "string") { + const decoded = await this._verifyRequestState(rawRequestState, ctx, method); + if (decoded !== void 0) ctxForHandler = withRequestStateValue(ctx, decoded); + } + let result; + try { + result = await handler(request, ctxForHandler); + } catch (error) { + if (error instanceof src_CX2iR2pK_ProtocolError && error.code === src_CX2iR2pK_ProtocolErrorCode.UrlElicitationRequired) { + if (!servedModern) throw error; + throw new src_CX2iR2pK_ProtocolError(src_CX2iR2pK_ProtocolErrorCode.InternalError, `URL elicitation cannot be signalled by throwing UrlElicitationRequiredError on protocol revision ${this._negotiatedProtocolVersion}: return inputRequired({ inputRequests: { …: inputRequired.elicitUrl(...) } }) from the handler instead. The urlElicitationRequired error (-32042) of earlier revisions is not available on this revision.`); + } + throw error; + } + if (!isInputRequiredResult(result)) return result; + if (!servedModern) { + if (!this._inputRequiredServing.legacyShim) throw new src_CX2iR2pK_ProtocolError(src_CX2iR2pK_ProtocolErrorCode.InternalError, `Handler for ${method} returned an input-required result, but this request is served on protocol revision ${this._negotiatedProtocolVersion ?? LATEST_PROTOCOL_VERSION}, which has no input_required vocabulary`); + return await this._legacyInputRequiredShim().fulfill(method, handler, request, ctxForHandler, result); + } + const inputRequests = result.inputRequests; + const hasInputRequests = inputRequests != null && Object.keys(inputRequests).length > 0; + const hasRequestState = typeof result.requestState === "string"; + if (!hasInputRequests && !hasRequestState) throw new src_CX2iR2pK_ProtocolError(src_CX2iR2pK_ProtocolErrorCode.InternalError, `Handler for ${method} returned an input-required result with neither inputRequests nor requestState (every InputRequiredResult must include at least one of the two)`); + if (hasInputRequests) { + const declared = this._inputRequestCapabilityView(ctx); + for (const [key, entry] of Object.entries(inputRequests)) { + const { embedded, required } = coerceEmbeddedInputRequest(method, key, entry); + const missing = src_CX2iR2pK_missingClientCapabilities(required, declared); + if (missing !== void 0) throw new src_CX2iR2pK_MissingRequiredClientCapabilityError({ requiredCapabilities: missing }, `Cannot request input '${key}' (${embedded.method}): the request's client capabilities do not declare the required capability`); + } + } + return result; + } + /** + * Runs the configured `requestState.verify` hook and returns its + * resolved value (`undefined` when unconfigured or the hook returns + * nothing). Deny-on-error: any hook failure answers the frozen `-32602`; + * the reason goes to `onerror` only. + */ + async _verifyRequestState(state, ctx, method) { + if (this._requestStateVerify === void 0) return; + try { + return await this._requestStateVerify(state, ctx); + } catch (error) { + this.onerror?.(/* @__PURE__ */ new Error(`requestState verification rejected ${method}: ${error instanceof Error ? error.message : String(error)}`)); + throw new src_CX2iR2pK_ProtocolError(src_CX2iR2pK_ProtocolErrorCode.InvalidParams, "Invalid or expired requestState", { reason: "invalid_request_state" }); + } + } + /** + * The per-request resolved client-capabilities view: the request's own + * `_meta` envelope on the 2026 era; the `initialize`-declared state on a + * 2025-era connection. Per-request instances that never saw an + * initialize (stateless legacy) hold nothing, so gates refuse there. + */ + _inputRequestCapabilityView(ctx) { + return this._servedModernEra() ? ctx.mcpReq.envelope?.[auth_CUe6YdwF_CLIENT_CAPABILITIES_META_KEY] : this._clientCapabilities; + } + /** + * Guard for the push-style server→client request APIs ({@linkcode createMessage}, + * {@linkcode elicitInput}, {@linkcode listRoots}, {@linkcode ping}) on a + * modern-era instance: the 2026-07-28 revision has no server→client request + * channel, so the call fails before any wire traffic with a typed error + * whose message steers to `inputRequired(...)`. The base era gate would + * also reject it; this guard runs first to carry the steer. + */ + _assertPushApiInServedEra(method) { + if (this._servedModernEra()) throw new src_CX2iR2pK_SdkError(src_CX2iR2pK_SdkErrorCode.MethodNotSupportedByProtocolVersion, `Server-to-client requests are not available on protocol revision ${this._negotiatedProtocolVersion}: '${method}' cannot be sent while serving a request on that revision. Return inputRequired({ ... }) from the handler instead — the client fulfils the embedded requests and retries the original request (multi round-trip requests).`, { + method, + era: "2026-07-28" + }); + } + assertCapabilityForMethod(method) { + switch (method) { + case "sampling/createMessage": + if (!this._clientCapabilities?.sampling) throw new src_CX2iR2pK_SdkError(src_CX2iR2pK_SdkErrorCode.CapabilityNotSupported, `Client does not support sampling (required for ${method})`); + break; + case "elicitation/create": + if (!this._clientCapabilities?.elicitation) throw new src_CX2iR2pK_SdkError(src_CX2iR2pK_SdkErrorCode.CapabilityNotSupported, `Client does not support elicitation (required for ${method})`); + break; + case "roots/list": + if (!this._clientCapabilities?.roots) throw new src_CX2iR2pK_SdkError(src_CX2iR2pK_SdkErrorCode.CapabilityNotSupported, `Client does not support listing roots (required for ${method})`); + break; + case "ping": break; + } + } + assertNotificationCapability(method) { + switch (method) { + case "notifications/message": + if (!this._capabilities.logging) throw new src_CX2iR2pK_SdkError(src_CX2iR2pK_SdkErrorCode.CapabilityNotSupported, `Server does not support logging (required for ${method})`); + break; + case "notifications/resources/updated": + case "notifications/resources/list_changed": + if (!this._capabilities.resources) throw new src_CX2iR2pK_SdkError(src_CX2iR2pK_SdkErrorCode.CapabilityNotSupported, `Server does not support notifying about resources (required for ${method})`); + break; + case "notifications/tools/list_changed": + if (!this._capabilities.tools) throw new src_CX2iR2pK_SdkError(src_CX2iR2pK_SdkErrorCode.CapabilityNotSupported, `Server does not support notifying of tool list changes (required for ${method})`); + break; + case "notifications/prompts/list_changed": + if (!this._capabilities.prompts) throw new src_CX2iR2pK_SdkError(src_CX2iR2pK_SdkErrorCode.CapabilityNotSupported, `Server does not support notifying of prompt list changes (required for ${method})`); + break; + case "notifications/elicitation/complete": + if (!this._clientCapabilities?.elicitation?.url) throw new src_CX2iR2pK_SdkError(src_CX2iR2pK_SdkErrorCode.CapabilityNotSupported, `Client does not support URL elicitation (required for ${method})`); + break; + case "notifications/cancelled": break; + case "notifications/progress": break; + } + } + assertRequestHandlerCapability(method) { + switch (method) { + case "completion/complete": + if (!this._capabilities.completions) throw new src_CX2iR2pK_SdkError(src_CX2iR2pK_SdkErrorCode.CapabilityNotSupported, `Server does not support completions (required for ${method})`); + break; + case "logging/setLevel": + if (!this._capabilities.logging) throw new src_CX2iR2pK_SdkError(src_CX2iR2pK_SdkErrorCode.CapabilityNotSupported, `Server does not support logging (required for ${method})`); + break; + case "prompts/get": + case "prompts/list": + if (!this._capabilities.prompts) throw new src_CX2iR2pK_SdkError(src_CX2iR2pK_SdkErrorCode.CapabilityNotSupported, `Server does not support prompts (required for ${method})`); + break; + case "resources/list": + case "resources/templates/list": + case "resources/read": + if (!this._capabilities.resources) throw new src_CX2iR2pK_SdkError(src_CX2iR2pK_SdkErrorCode.CapabilityNotSupported, `Server does not support resources (required for ${method})`); + break; + case "tools/call": + case "tools/list": + if (!this._capabilities.tools) throw new src_CX2iR2pK_SdkError(src_CX2iR2pK_SdkErrorCode.CapabilityNotSupported, `Server does not support tools (required for ${method})`); + break; + case "ping": + case "initialize": break; + } + } + async _oninitialize(request) { + const requestedVersion = request.params.protocolVersion; + this._clientCapabilities = request.params.capabilities; + this._clientVersion = request.params.clientInfo; + const legacyVersions = legacyProtocolVersions(this._supportedProtocolVersions); + const protocolVersion = legacyVersions.includes(requestedVersion) ? requestedVersion : legacyVersions[0] ?? LATEST_PROTOCOL_VERSION; + this._negotiatedProtocolVersion = protocolVersion; + this.transport?.setProtocolVersion?.(protocolVersion); + return { + protocolVersion, + capabilities: this.getCapabilities(), + serverInfo: this._serverInfo, + ...this._instructions && { instructions: this._instructions } + }; + } + /** + * Answers `server/discover` (protocol revision 2026-07-28). `supportedVersions` + * lists only modern revisions (2025-era versions are negotiated via `initialize`); + * the capabilities are advertised as-is, listChanged/subscribe bits included + * (see {@linkcode discoverAdvertisedCapabilities}). + */ + _ondiscover() { + return { + supportedVersions: modernProtocolVersions(this._supportedProtocolVersions), + capabilities: discoverAdvertisedCapabilities(this.getCapabilities()), + ...this._instructions && { instructions: this._instructions } + }; + } + /** + * The identity the 2026-era encode seam stamps into every outbound + * result's `_meta` under `io.modelcontextprotocol/serverInfo` (spec PR + * #3002: servers SHOULD identify themselves on every response). + */ + _outboundServerInfo() { + return this._serverInfo; + } + /** + * After initialization has completed, this will be populated with the client's reported capabilities. + * + * @deprecated Read client identity from the per-request handler context instead: on + * 2026-07-28 (per-request envelope) requests `ctx.mcpReq.envelope` carries the client's + * declared capabilities, while on 2025-era connections this accessor keeps returning the + * `initialize`-scoped value. The accessor remains functional — instances serving the + * 2026-07-28 era are backfilled per request from the validated envelope. + */ + getClientCapabilities() { + return this._clientCapabilities; + } + /** + * After initialization has completed, this will be populated with information about the client's name and version. + * + * @deprecated Read client identity from the per-request handler context instead: on + * 2026-07-28 (per-request envelope) requests `ctx.mcpReq.envelope` carries the client's + * name and version, while on 2025-era connections this accessor keeps returning the + * `initialize`-scoped value. The accessor remains functional — instances serving the + * 2026-07-28 era are backfilled per request from the validated envelope. + */ + getClientVersion() { + return this._clientVersion; + } + /** + * After initialization has completed, this will be populated with the protocol version negotiated + * with the client (the version the server responded with during the initialize handshake), or + * `undefined` before initialization. + * + * @deprecated Read the protocol revision from the per-request handler context instead: on + * 2026-07-28 (per-request envelope) requests `ctx.mcpReq.envelope` names the revision the + * request was sent for, while on 2025-era connections this accessor keeps returning the + * `initialize`-negotiated version. The accessor remains functional — instances serving the + * 2026-07-28 era report that revision. + */ + getNegotiatedProtocolVersion() { + return this._negotiatedProtocolVersion; + } + /** + * Project a `tools/call` result through this instance's negotiated wire + * codec — the era-agnostic SEP-2106 §4.3 TextContent auto-append, plus on + * the 2025 era the `{result:…}` wrap when `structuredContent` is a + * non-object value or the advertised `outputSchema` had a non-object root. + * Identity for object-shaped `structuredContent` on the 2026 era. + * + * `McpServer`'s built-in `tools/call` handler routes through this method. + * Low-level `setRequestHandler('tools/call', …)` authors call it + * themselves so the projection lives in one place (the codec) and the + * server-side handler stays era-blind. + * + * This is the only codec function exposed on `Server` — the full + * `WireCodec` is intentionally not part of the public surface. + */ + projectCallToolResult(result, advertisedOutputSchema) { + return this._wireCodec().projectCallToolResult(result, advertisedOutputSchema); + } + /** + * Returns the current server capabilities. + */ + getCapabilities() { + return this._capabilities; + } + /** + * Sends a `ping` request to the connected client. + * + * @deprecated The 2026-07-28 protocol removed ping; it throws on a 2026-07-28-era instance. + * If your factory serves both eras, this only works on the legacy path. + */ + async ping() { + this._assertPushApiInServedEra("ping"); + return this.request({ method: "ping" }); + } + async createMessage(params, options) { + this._assertPushApiInServedEra("sampling/createMessage"); + if ((params.tools || params.toolChoice) && !this._clientCapabilities?.sampling?.tools) throw new src_CX2iR2pK_SdkError(src_CX2iR2pK_SdkErrorCode.CapabilityNotSupported, "Client does not support sampling tools capability."); + if (params.messages.length > 0) { + const lastMessage = params.messages.at(-1); + const lastContent = Array.isArray(lastMessage.content) ? lastMessage.content : [lastMessage.content]; + const hasToolResults = lastContent.some((c) => c.type === "tool_result"); + const previousMessage = params.messages.length > 1 ? params.messages.at(-2) : void 0; + const previousContent = previousMessage ? Array.isArray(previousMessage.content) ? previousMessage.content : [previousMessage.content] : []; + const hasPreviousToolUse = previousContent.some((c) => c.type === "tool_use"); + if (hasToolResults) { + if (lastContent.some((c) => c.type !== "tool_result")) throw new src_CX2iR2pK_ProtocolError(src_CX2iR2pK_ProtocolErrorCode.InvalidParams, "The last message must contain only tool_result content if any is present"); + if (!hasPreviousToolUse) throw new src_CX2iR2pK_ProtocolError(src_CX2iR2pK_ProtocolErrorCode.InvalidParams, "tool_result blocks are not matching any tool_use from the previous message"); + } + if (hasPreviousToolUse) { + const toolUseIds = new Set(previousContent.filter((c) => c.type === "tool_use").map((c) => c.id)); + const toolResultIds = new Set(lastContent.filter((c) => c.type === "tool_result").map((c) => c.toolUseId)); + if (toolUseIds.size !== toolResultIds.size || ![...toolUseIds].every((id) => toolResultIds.has(id))) throw new src_CX2iR2pK_ProtocolError(src_CX2iR2pK_ProtocolErrorCode.InvalidParams, "ids of tool_result blocks and tool_use blocks from previous message do not match"); + } + } + const hasTools = Boolean(params.tools || params.toolChoice); + const wide = await this.request({ + method: "sampling/createMessage", + params + }, options); + const outcome = this._wireCodec().samplingResultVariant(hasTools, wide); + if (!outcome.ok) throw new src_CX2iR2pK_SdkError(src_CX2iR2pK_SdkErrorCode.InvalidResult, `Invalid sampling/createMessage result: ${outcome.reason === "invalid" ? outcome.message : outcome.reason}`); + return outcome.value; + } + /** + * Creates an elicitation request for the given parameters. + * For backwards compatibility, `mode` may be omitted for form requests and will default to `"form"`. + * @param params The parameters for the elicitation request. + * @param options Optional request options. + * @returns The result of the elicitation request. + * + * @deprecated Throws on a 2026-07-28-era request — use {@link index.inputRequired | inputRequired} (multi-round-trip) + * instead. The 2025 push-style server-to-client request model is replaced by input_required + * results in the 2026-07-28 protocol. If your factory serves both eras, this only works on the + * legacy path. + */ + async elicitInput(params, options) { + this._assertPushApiInServedEra("elicitation/create"); + switch (params.mode ?? "form") { + case "url": + if (!this._clientCapabilities?.elicitation?.url) throw new src_CX2iR2pK_SdkError(src_CX2iR2pK_SdkErrorCode.CapabilityNotSupported, "Client does not support url elicitation."); + break; + case "form": + if (!this._clientCapabilities?.elicitation?.form) throw new src_CX2iR2pK_SdkError(src_CX2iR2pK_SdkErrorCode.CapabilityNotSupported, "Client does not support form elicitation."); + break; + } + return this._sendElicitationLeg(params, options); + } + /** + * The capability-check-free core of {@linkcode elicitInput}. The shim + * uses it because its gate differs from the public checks: a bare + * `elicitation: {}` counts as form support (the pre-mode rule), and + * accepted content passes through unvalidated for parity with the + * modern client driver (handlers validate via the schema-aware + * `acceptedContent` overload and can re-ask). + */ + async _sendElicitationLeg(params, options, behavior) { + const mode = params.mode ?? "form"; + const validateAcceptedContent = behavior?.validateAcceptedContent ?? true; + switch (mode) { + case "url": { + const urlParams = params; + return this.request({ + method: "elicitation/create", + params: urlParams + }, options); + } + case "form": { + const formParams = params.mode === "form" ? params : { + ...params, + mode: "form" + }; + const result = await this.request({ + method: "elicitation/create", + params: formParams + }, options); + if (validateAcceptedContent && result.action === "accept" && result.content && formParams.requestedSchema) try { + const validationResult = this._jsonSchemaValidator.getValidator(formParams.requestedSchema)(result.content); + if (!validationResult.valid) throw new src_CX2iR2pK_ProtocolError(src_CX2iR2pK_ProtocolErrorCode.InvalidParams, `Elicitation response content does not match requested schema: ${validationResult.errorMessage}`); + } catch (error) { + if (error instanceof src_CX2iR2pK_ProtocolError) throw error; + throw new src_CX2iR2pK_ProtocolError(src_CX2iR2pK_ProtocolErrorCode.InternalError, `Error validating elicitation response: ${error instanceof Error ? error.message : String(error)}`); + } + return result; + } + } + } + /** + * Creates a reusable callback that, when invoked, will send a `notifications/elicitation/complete` + * notification for the specified elicitation ID. + * + * The notification (and the `elicitationId` it references) exists only on protocol revision + * 2025-11-25 — the 2026-07-28 revision removed both. On a connection negotiated at 2026-07-28 the + * returned callback rejects with a typed local error before anything reaches the transport + * (the method is not part of that revision's wire registry). + * + * @param elicitationId The ID of the elicitation to mark as complete. + * @param options Optional notification options. Useful when the completion notification should be related to a prior request. + * @returns A function that emits the completion notification when awaited. + */ + createElicitationCompletionNotifier(elicitationId, options) { + if (!this._clientCapabilities?.elicitation?.url) throw new src_CX2iR2pK_SdkError(src_CX2iR2pK_SdkErrorCode.CapabilityNotSupported, "Client does not support URL elicitation (required for notifications/elicitation/complete)"); + return () => this.notification({ + method: "notifications/elicitation/complete", + params: { elicitationId } + }, options); + } + /** + * Requests the list of roots from the client. + * + * @deprecated Deprecated as of protocol version 2026-07-28 (SEP-2577). + * Throws on a 2026-07-28-era request — use {@link index.inputRequired | inputRequired} (multi-round-trip) instead, + * or migrate to passing paths via tool parameters, resource URIs, or configuration. The 2025 + * push-style server-to-client request model is replaced by input_required results in the + * 2026-07-28 protocol. If your factory serves both eras, this only works on the legacy path. + */ + async listRoots(params, options) { + this._assertPushApiInServedEra("roots/list"); + return this.request({ + method: "roots/list", + params + }, options); + } + /** + * Sends a logging message to the client, if connected. + * Note: You only need to send the parameters object, not the entire JSON-RPC message. + * @see {@linkcode LoggingMessageNotification} + * @param params + * @param sessionId Optional for stateless transports and backward compatibility. + * + * @deprecated Deprecated as of protocol version 2026-07-28 (SEP-2577). + * Remains functional during the deprecation window (at least twelve months). + * Migrate to stderr logging (STDIO servers) or OpenTelemetry. + */ + async sendLoggingMessage(params, sessionId) { + if (this._capabilities.logging && !this.isMessageIgnored(params.level, sessionId)) return this.notification({ + method: "notifications/message", + params + }); + } + async sendResourceUpdated(params) { + return this.notification({ + method: "notifications/resources/updated", + params + }); + } + 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" }); + } +}; +/** +* The capability set a server advertises on `server/discover`. Pure — never +* mutates the input; the legacy `initialize` advertisement is untouched. +* +* The serving entries serve `subscriptions/listen` themselves, so the +* `listChanged` and `resources.subscribe` capability bits are advertised +* as-is: a modern-era client uses them to decide which notification types to +* request on its listen filter. +*/ +function discoverAdvertisedCapabilities(capabilities) { + return { ...capabilities }; +} + +//#endregion +//#region src/server/mcp.ts +/** +* High-level MCP server that provides a simpler API for working with resources, tools, and prompts. +* For advanced usage (like sending notifications or setting custom request handlers), use the underlying +* {@linkcode Server} instance available via the {@linkcode McpServer.server | server} property. +* +* @example +* ```ts source="./mcp.examples.ts#McpServer_basicUsage" +* const server = new McpServer({ +* name: 'my-server', +* version: '1.0.0' +* }); +* ``` +*/ +var mcp_DXXb3Vv3_McpServer = class { + /** + * The underlying {@linkcode Server} instance, useful for advanced operations like sending notifications. + */ + server; + _registeredResources = {}; + _registeredResourceTemplates = {}; + _registeredTools = {}; + _registeredPrompts = {}; + /** + * Per-tool JSON-converted `inputSchema`, memoized so the SEP-2243 + * registration-time scan and the pre-dispatch validation step share one + * conversion instead of paying it twice per request under the + * per-request-factory `createMcpHandler` model. + */ + _toolInputSchemaJson = {}; + /** + * The JSON-serialized `inputSchema` of a registered tool, or `undefined` + * when no such tool is registered. Used by the HTTP entry's pre-dispatch + * SEP-2243 `Mcp-Param-*` validation step (which needs the same JSON Schema + * `tools/list` would emit, before dispatch reaches the handler). + * + * @internal + */ + toolInputSchemaJson(name) { + const tool = this._registeredTools[name]; + if (tool === void 0 || !tool.enabled) return void 0; + if (Object.hasOwn(this._toolInputSchemaJson, name)) return this._toolInputSchemaJson[name]; + if (tool.inputSchema === void 0) return EMPTY_OBJECT_JSON_SCHEMA; + try { + const json = standardSchemaToJsonSchema(tool.inputSchema, "input"); + this._toolInputSchemaJson[name] = json; + return json; + } catch { + return; + } + } + constructor(serverInfo, options) { + this.server = new Server(serverInfo, options); + if (options?.capabilities?.tools) this.setToolRequestHandlers(); + if (options?.capabilities?.resources) this.setResourceRequestHandlers(); + if (options?.capabilities?.prompts) this.setPromptRequestHandlers(); + } + /** + * Attaches to the given transport, starts it, and starts listening for messages. + * + * The `server` object assumes ownership of the {@linkcode Transport}, replacing any callbacks that have already been set, and expects that it is the only user of the {@linkcode Transport} instance going forward. + * + * @example + * ```ts source="./mcp.examples.ts#McpServer_connect_stdio" + * const server = new McpServer({ name: 'my-server', version: '1.0.0' }); + * const transport = new StdioServerTransport(); + * await server.connect(transport); + * ``` + */ + async connect(transport) { + return await this.server.connect(transport); + } + /** + * Closes the connection. + */ + async close() { + await this.server.close(); + } + _toolHandlersInitialized = false; + setToolRequestHandlers() { + if (this._toolHandlersInitialized) return; + this.server.assertCanSetRequestHandler("tools/list"); + this.server.assertCanSetRequestHandler("tools/call"); + this.server.registerCapabilities({ tools: { listChanged: this.server.getCapabilities().tools?.listChanged ?? true } }); + this.server.setRequestHandler("tools/list", () => ({ tools: Object.entries(this._registeredTools).filter(([, tool]) => tool.enabled).map(([name, tool]) => { + const toolDefinition = { + name, + title: tool.title, + description: tool.description, + inputSchema: tool.inputSchema ? standardSchemaToJsonSchema(tool.inputSchema, "input") : EMPTY_OBJECT_JSON_SCHEMA, + annotations: tool.annotations, + icons: tool.icons, + execution: tool.execution, + _meta: tool._meta + }; + if (tool.outputSchema) toolDefinition.outputSchema = standardSchemaToJsonSchema(tool.outputSchema, "output"); + return toolDefinition; + }) })); + this.server.setRequestHandler("tools/call", async (request, ctx) => { + const tool = this._registeredTools[request.params.name]; + if (!tool) throw new src_CX2iR2pK_ProtocolError(src_CX2iR2pK_ProtocolErrorCode.InvalidParams, `Tool ${request.params.name} not found`); + if (!tool.enabled) throw new src_CX2iR2pK_ProtocolError(src_CX2iR2pK_ProtocolErrorCode.InvalidParams, `Tool ${request.params.name} disabled`); + try { + const args = await this.validateToolInput(tool, request.params.arguments, request.params.name); + const result = await this.executeToolHandler(tool, args, ctx); + await this.validateToolOutput(tool, result, request.params.name); + if (isInputRequiredResult(result)) return result; + return this.server.projectCallToolResult(result, tool.outputSchemaJson); + } catch (error) { + if (error instanceof src_CX2iR2pK_ProtocolError && error.code === src_CX2iR2pK_ProtocolErrorCode.UrlElicitationRequired) throw error; + return this.createToolError(error instanceof Error ? error.message : String(error)); + } + }); + this._toolHandlersInitialized = true; + } + /** + * Creates a tool error result. + * + * @param errorMessage - The error message. + * @returns The tool error result. + */ + createToolError(errorMessage) { + return { + content: [{ + type: "text", + text: errorMessage + }], + isError: true + }; + } + /** + * Validates tool input arguments against the tool's input schema. + */ + async validateToolInput(tool, args, toolName) { + if (!tool.inputSchema) return; + const parseResult = await validateStandardSchema(tool.inputSchema, args ?? {}); + if (!parseResult.success) throw new src_CX2iR2pK_ProtocolError(src_CX2iR2pK_ProtocolErrorCode.InvalidParams, `Input validation error: Invalid arguments for tool ${toolName}: ${parseResult.error}`); + return parseResult.data; + } + /** + * Validates tool output against the tool's output schema. + */ + async validateToolOutput(tool, result, toolName) { + if (!tool.outputSchema) return; + if (isInputRequiredResult(result)) return; + if (result.isError) return; + if (result.structuredContent === void 0) throw new src_CX2iR2pK_ProtocolError(src_CX2iR2pK_ProtocolErrorCode.InvalidParams, `Output validation error: Tool ${toolName} has an output schema but no structured content was provided`); + const parseResult = await validateStandardSchema(tool.outputSchema, result.structuredContent); + if (!parseResult.success) throw new src_CX2iR2pK_ProtocolError(src_CX2iR2pK_ProtocolErrorCode.InvalidParams, `Output validation error: Invalid structured content for tool ${toolName}: ${parseResult.error}`); + } + /** + * Executes a tool handler. + */ + async executeToolHandler(tool, args, ctx) { + return tool.executor(args, ctx); + } + _completionHandlerInitialized = false; + setCompletionRequestHandler() { + if (this._completionHandlerInitialized) return; + this.server.assertCanSetRequestHandler("completion/complete"); + this.server.registerCapabilities({ completions: {} }); + this.server.setRequestHandler("completion/complete", async (request) => { + switch (request.params.ref.type) { + case "ref/prompt": + assertCompleteRequestPrompt(request); + return this.handlePromptCompletion(request, request.params.ref); + case "ref/resource": + assertCompleteRequestResourceTemplate(request); + return this.handleResourceCompletion(request, request.params.ref); + default: throw new src_CX2iR2pK_ProtocolError(src_CX2iR2pK_ProtocolErrorCode.InvalidParams, `Invalid completion reference: ${request.params.ref}`); + } + }); + this._completionHandlerInitialized = true; + } + async handlePromptCompletion(request, ref) { + const prompt = this._registeredPrompts[ref.name]; + if (!prompt) throw new src_CX2iR2pK_ProtocolError(src_CX2iR2pK_ProtocolErrorCode.InvalidParams, `Prompt ${ref.name} not found`); + if (!prompt.enabled) throw new src_CX2iR2pK_ProtocolError(src_CX2iR2pK_ProtocolErrorCode.InvalidParams, `Prompt ${ref.name} disabled`); + if (!prompt.argsSchema) return EMPTY_COMPLETION_RESULT; + const field = unwrapOptionalSchema(getSchemaShape(prompt.argsSchema)?.[request.params.argument.name]); + if (!isCompletable(field)) return EMPTY_COMPLETION_RESULT; + const completer = getCompleter(field); + if (!completer) return EMPTY_COMPLETION_RESULT; + return createCompletionResult(await completer(request.params.argument.value, request.params.context)); + } + async handleResourceCompletion(request, ref) { + const template = Object.values(this._registeredResourceTemplates).find((t) => t.resourceTemplate.uriTemplate.toString() === ref.uri); + if (!template) { + if (this._registeredResources[ref.uri]) return EMPTY_COMPLETION_RESULT; + throw new src_CX2iR2pK_ProtocolError(src_CX2iR2pK_ProtocolErrorCode.InvalidParams, `Resource template ${request.params.ref.uri} not found`); + } + const completer = template.resourceTemplate.completeCallback(request.params.argument.name); + if (!completer) return EMPTY_COMPLETION_RESULT; + return createCompletionResult(await completer(request.params.argument.value, request.params.context)); + } + _resourceHandlersInitialized = false; + setResourceRequestHandlers() { + if (this._resourceHandlersInitialized) return; + this.server.assertCanSetRequestHandler("resources/list"); + this.server.assertCanSetRequestHandler("resources/templates/list"); + this.server.assertCanSetRequestHandler("resources/read"); + this.server.registerCapabilities({ resources: { listChanged: this.server.getCapabilities().resources?.listChanged ?? true } }); + this.server.setRequestHandler("resources/list", async (_request, ctx) => { + const resources = Object.entries(this._registeredResources).filter(([_, resource]) => resource.enabled).map(([uri, resource]) => ({ + uri, + name: resource.name, + ...resource.metadata + })); + const templateResources = []; + for (const template of Object.values(this._registeredResourceTemplates)) { + if (!template.resourceTemplate.listCallback) continue; + const result = await template.resourceTemplate.listCallback(ctx); + for (const resource of result.resources) templateResources.push({ + ...template.metadata, + ...resource + }); + } + return { resources: [...resources, ...templateResources] }; + }); + this.server.setRequestHandler("resources/templates/list", async () => { + return { resourceTemplates: Object.entries(this._registeredResourceTemplates).map(([name, template]) => ({ + name, + uriTemplate: template.resourceTemplate.uriTemplate.toString(), + ...template.metadata + })) }; + }); + this.server.setRequestHandler("resources/read", async (request, ctx) => { + let uri; + try { + uri = new URL(request.params.uri); + } catch { + throw new src_CX2iR2pK_ProtocolError(src_CX2iR2pK_ProtocolErrorCode.InvalidParams, `Resource URI ${request.params.uri} is invalid`, { + uri: request.params.uri, + reason: "invalid_uri" + }); + } + const resource = this._registeredResources[uri.toString()]; + if (resource) { + if (!resource.enabled) throw new src_CX2iR2pK_ProtocolError(src_CX2iR2pK_ProtocolErrorCode.InvalidParams, `Resource ${uri} disabled`); + return attachCacheHintFallback(await resource.readCallback(uri, ctx), resource.cacheHint); + } + for (const template of Object.values(this._registeredResourceTemplates)) { + const variables = template.resourceTemplate.uriTemplate.match(uri.toString()); + if (variables) return attachCacheHintFallback(await template.readCallback(uri, variables, ctx), template.cacheHint); + } + throw new ResourceNotFoundError(request.params.uri); + }); + this._resourceHandlersInitialized = true; + } + _promptHandlersInitialized = false; + setPromptRequestHandlers() { + if (this._promptHandlersInitialized) return; + this.server.assertCanSetRequestHandler("prompts/list"); + this.server.assertCanSetRequestHandler("prompts/get"); + this.server.registerCapabilities({ prompts: { listChanged: this.server.getCapabilities().prompts?.listChanged ?? true } }); + this.server.setRequestHandler("prompts/list", () => ({ prompts: Object.entries(this._registeredPrompts).filter(([, prompt]) => prompt.enabled).map(([name, prompt]) => { + return { + name, + title: prompt.title, + description: prompt.description, + arguments: prompt.argsSchema ? promptArgumentsFromStandardSchema(prompt.argsSchema) : void 0, + icons: prompt.icons, + _meta: prompt._meta + }; + }) })); + this.server.setRequestHandler("prompts/get", async (request, ctx) => { + const prompt = this._registeredPrompts[request.params.name]; + if (!prompt) throw new src_CX2iR2pK_ProtocolError(src_CX2iR2pK_ProtocolErrorCode.InvalidParams, `Prompt ${request.params.name} not found`); + if (!prompt.enabled) throw new src_CX2iR2pK_ProtocolError(src_CX2iR2pK_ProtocolErrorCode.InvalidParams, `Prompt ${request.params.name} disabled`); + return prompt.handler(request.params.arguments, ctx); + }); + this._promptHandlersInitialized = true; + } + registerResource(name, uriOrTemplate, config, readCallback) { + const cacheHint = config.cacheHint; + let metadata = config; + if (cacheHint !== void 0) { + assertValidCacheHint(cacheHint, `resource ${name}`); + const rest = { ...config }; + delete rest.cacheHint; + metadata = rest; + } + if (typeof uriOrTemplate === "string") { + if (this._registeredResources[uriOrTemplate]) throw new Error(`Resource ${uriOrTemplate} is already registered`); + const registeredResource = this._createRegisteredResource(name, config.title, uriOrTemplate, metadata, readCallback); + if (cacheHint !== void 0) registeredResource.cacheHint = cacheHint; + this.setResourceRequestHandlers(); + this.sendResourceListChanged(); + return registeredResource; + } else { + if (this._registeredResourceTemplates[name]) throw new Error(`Resource template ${name} is already registered`); + const registeredResourceTemplate = this._createRegisteredResourceTemplate(name, config.title, uriOrTemplate, metadata, readCallback); + if (cacheHint !== void 0) registeredResourceTemplate.cacheHint = cacheHint; + this.setResourceRequestHandlers(); + this.sendResourceListChanged(); + return registeredResourceTemplate; + } + } + _createRegisteredResource(name, title, uri, metadata, readCallback) { + const registeredResource = { + name, + title, + metadata, + readCallback, + enabled: true, + disable: () => registeredResource.update({ enabled: false }), + enable: () => registeredResource.update({ enabled: true }), + remove: () => registeredResource.update({ uri: null }), + update: (updates) => { + if (updates.uri !== void 0 && updates.uri !== uri) { + delete this._registeredResources[uri]; + if (updates.uri) this._registeredResources[updates.uri] = registeredResource; + } + if (updates.name !== void 0) registeredResource.name = updates.name; + if (updates.title !== void 0) registeredResource.title = updates.title; + if (updates.metadata !== void 0) registeredResource.metadata = updates.metadata; + if (updates.callback !== void 0) registeredResource.readCallback = updates.callback; + if (updates.enabled !== void 0) registeredResource.enabled = updates.enabled; + this.sendResourceListChanged(); + } + }; + this._registeredResources[uri] = registeredResource; + return registeredResource; + } + _createRegisteredResourceTemplate(name, title, template, metadata, readCallback) { + const registeredResourceTemplate = { + resourceTemplate: template, + title, + metadata, + readCallback, + enabled: true, + disable: () => registeredResourceTemplate.update({ enabled: false }), + enable: () => registeredResourceTemplate.update({ enabled: true }), + remove: () => registeredResourceTemplate.update({ name: null }), + update: (updates) => { + if (updates.name !== void 0 && updates.name !== name) { + delete this._registeredResourceTemplates[name]; + if (updates.name) this._registeredResourceTemplates[updates.name] = registeredResourceTemplate; + } + if (updates.title !== void 0) registeredResourceTemplate.title = updates.title; + if (updates.template !== void 0) registeredResourceTemplate.resourceTemplate = updates.template; + if (updates.metadata !== void 0) registeredResourceTemplate.metadata = updates.metadata; + if (updates.callback !== void 0) registeredResourceTemplate.readCallback = updates.callback; + if (updates.enabled !== void 0) registeredResourceTemplate.enabled = updates.enabled; + this.sendResourceListChanged(); + } + }; + this._registeredResourceTemplates[name] = registeredResourceTemplate; + const variableNames = template.uriTemplate.variableNames; + if (Array.isArray(variableNames) && variableNames.some((v) => !!template.completeCallback(v))) this.setCompletionRequestHandler(); + return registeredResourceTemplate; + } + _createRegisteredPrompt(name, title, description, argsSchema, callback, icons, _meta) { + let currentArgsSchema = argsSchema; + let currentCallback = callback; + const registeredPrompt = { + title, + description, + argsSchema, + icons, + _meta, + handler: createPromptHandler(name, argsSchema, callback), + enabled: true, + disable: () => registeredPrompt.update({ enabled: false }), + enable: () => registeredPrompt.update({ enabled: true }), + remove: () => registeredPrompt.update({ name: null }), + update: (updates) => { + if (updates.name !== void 0 && updates.name !== name) { + delete this._registeredPrompts[name]; + if (updates.name) this._registeredPrompts[updates.name] = registeredPrompt; + } + if (updates.title !== void 0) registeredPrompt.title = updates.title; + if (updates.description !== void 0) registeredPrompt.description = updates.description; + if (updates.icons !== void 0) registeredPrompt.icons = updates.icons; + if (updates._meta !== void 0) registeredPrompt._meta = updates._meta; + let needsHandlerRegen = false; + if (updates.argsSchema !== void 0) { + registeredPrompt.argsSchema = updates.argsSchema; + currentArgsSchema = updates.argsSchema; + needsHandlerRegen = true; + } + if (updates.callback !== void 0) { + currentCallback = updates.callback; + needsHandlerRegen = true; + } + if (needsHandlerRegen) registeredPrompt.handler = createPromptHandler(name, currentArgsSchema, currentCallback); + if (updates.enabled !== void 0) registeredPrompt.enabled = updates.enabled; + this.sendPromptListChanged(); + } + }; + this._registeredPrompts[name] = registeredPrompt; + if (argsSchema) { + const shape = getSchemaShape(argsSchema); + if (shape) { + if (Object.values(shape).some((field) => { + return isCompletable(unwrapOptionalSchema(field)); + })) this.setCompletionRequestHandler(); + } + } + return registeredPrompt; + } + _createRegisteredTool(name, title, description, inputSchema, outputSchema, annotations, icons, execution, _meta, handler) { + validateAndWarnToolName(name); + if (inputSchema !== void 0) try { + const json = standardSchemaToJsonSchema(inputSchema, "input"); + this._toolInputSchemaJson[name] = json; + const scan = src_CX2iR2pK_scanXMcpHeaderDeclarations(json); + if (!scan.valid) console.warn(`[mcp-sdk] tool '${name}' carries an invalid x-mcp-header declaration and will be excluded by conforming Streamable HTTP clients: ${scan.reason}`); + } catch {} + let currentHandler = handler; + const registeredTool = { + title, + description, + inputSchema, + outputSchema, + outputSchemaJson: convertOutputSchemaJson(outputSchema), + annotations, + icons, + execution, + _meta, + handler, + executor: createToolExecutor(inputSchema, handler), + enabled: true, + disable: () => registeredTool.update({ enabled: false }), + enable: () => registeredTool.update({ enabled: true }), + remove: () => registeredTool.update({ name: null }), + update: (updates) => { + if (updates.name !== void 0 && updates.name !== name) { + if (typeof updates.name === "string") validateAndWarnToolName(updates.name); + delete this._registeredTools[name]; + delete this._toolInputSchemaJson[name]; + if (updates.name) { + delete this._toolInputSchemaJson[updates.name]; + this._registeredTools[updates.name] = registeredTool; + name = updates.name; + } + } + if (updates.title !== void 0) registeredTool.title = updates.title; + if (updates.description !== void 0) registeredTool.description = updates.description; + let needsExecutorRegen = false; + if (updates.paramsSchema !== void 0) { + registeredTool.inputSchema = updates.paramsSchema; + delete this._toolInputSchemaJson[name]; + needsExecutorRegen = true; + } + if (updates.callback !== void 0) { + registeredTool.handler = updates.callback; + currentHandler = updates.callback; + needsExecutorRegen = true; + } + if (needsExecutorRegen) registeredTool.executor = createToolExecutor(registeredTool.inputSchema, currentHandler); + if (updates.outputSchema !== void 0) { + registeredTool.outputSchema = updates.outputSchema; + registeredTool.outputSchemaJson = convertOutputSchemaJson(updates.outputSchema); + } + if (updates.annotations !== void 0) registeredTool.annotations = updates.annotations; + if (updates.icons !== void 0) registeredTool.icons = updates.icons; + if (updates._meta !== void 0) registeredTool._meta = updates._meta; + if (updates.enabled !== void 0) registeredTool.enabled = updates.enabled; + this.sendToolListChanged(); + } + }; + this._registeredTools[name] = registeredTool; + this.setToolRequestHandlers(); + this.sendToolListChanged(); + return registeredTool; + } + registerTool(name, config, cb) { + if (this._registeredTools[name]) throw new Error(`Tool ${name} is already registered`); + const { title, description, inputSchema, outputSchema, annotations, icons, _meta } = config; + return this._createRegisteredTool(name, title, description, normalizeRawShapeSchema(inputSchema), normalizeRawShapeSchema(outputSchema), annotations, icons, void 0, _meta, cb); + } + registerPrompt(name, config, cb) { + if (this._registeredPrompts[name]) throw new Error(`Prompt ${name} is already registered`); + const { title, description, argsSchema, icons, _meta } = config; + const registeredPrompt = this._createRegisteredPrompt(name, title, description, normalizeRawShapeSchema(argsSchema), cb, icons, _meta); + this.setPromptRequestHandlers(); + this.sendPromptListChanged(); + return registeredPrompt; + } + /** + * Checks if the server is connected to a transport. + * @returns `true` if the server is connected + */ + isConnected() { + return this.server.transport !== void 0; + } + /** + * Sends a logging message to the client, if connected. + * Note: You only need to send the parameters object, not the entire JSON-RPC message. + * @see {@linkcode LoggingMessageNotification} + * @param params + * @param sessionId Optional for stateless transports and backward compatibility. + * + * @example + * ```ts source="./mcp.examples.ts#McpServer_sendLoggingMessage_basic" + * await server.sendLoggingMessage({ + * level: 'info', + * data: 'Processing complete' + * }); + * ``` + * + * @deprecated Deprecated as of protocol version 2026-07-28 (SEP-2577). + * Remains functional during the deprecation window (at least twelve months). + * Migrate to stderr logging (STDIO servers) or OpenTelemetry. + */ + async sendLoggingMessage(params, sessionId) { + return this.server.sendLoggingMessage(params, sessionId); + } + /** + * Sends a resource list changed event to the client, if connected. + */ + sendResourceListChanged() { + if (this.isConnected()) this.server.sendResourceListChanged(); + } + /** + * Sends a tool list changed event to the client, if connected. + */ + sendToolListChanged() { + if (this.isConnected()) this.server.sendToolListChanged(); + } + /** + * Sends a prompt list changed event to the client, if connected. + */ + sendPromptListChanged() { + if (this.isConnected()) this.server.sendPromptListChanged(); + } +}; +/** +* A resource template combines a URI pattern with optional functionality to enumerate +* all resources matching that pattern. +*/ +var ResourceTemplate = class { + _uriTemplate; + constructor(uriTemplate, _callbacks) { + this._callbacks = _callbacks; + this._uriTemplate = typeof uriTemplate === "string" ? new UriTemplate(uriTemplate) : uriTemplate; + } + /** + * Gets the URI template pattern. + */ + get uriTemplate() { + return this._uriTemplate; + } + /** + * Gets the list callback, if one was provided. + */ + get listCallback() { + return this._callbacks.list; + } + /** + * Gets the callback for completing a specific URI template variable, if one was provided. + */ + completeCallback(variable) { + return this._callbacks.complete?.[variable]; + } +}; +/** +* Creates an executor that invokes the handler with the appropriate arguments. +* When `inputSchema` is defined, the handler is called with `(args, ctx)`. +* When `inputSchema` is undefined, the handler is called with just `(ctx)`. +*/ +function createToolExecutor(inputSchema, handler) { + if (inputSchema) { + const callback$1 = handler; + return async (args, ctx) => callback$1(args, ctx); + } + const callback = handler; + return async (_args, ctx) => callback(ctx); +} +const EMPTY_OBJECT_JSON_SCHEMA = { + type: "object", + properties: {} +}; +/** +* Convert a registered `outputSchema` to JSON Schema, memoised on {@link RegisteredTool.outputSchemaJson} +* so `tools/call` passes the SAME advertised schema to the wire codec's `projectCallToolResult` that +* `tools/list` emits (and that the 2025 codec's `encodeResult('tools/list', …)` may wrap). A conversion +* failure yields `undefined` so the failure surfaces where it always has (`tools/list`). +*/ +function convertOutputSchemaJson(outputSchema) { + if (outputSchema === void 0) return void 0; + try { + return standardSchemaToJsonSchema(outputSchema, "output"); + } catch { + return; + } +} +/** +* Creates a type-safe prompt handler that captures the schema and callback in a closure. +* This eliminates the need for type assertions at the call site. +*/ +function createPromptHandler(name, argsSchema, callback) { + if (argsSchema) { + const typedCallback = callback; + return async (args, ctx) => { + const parseResult = await validateStandardSchema(argsSchema, args); + if (!parseResult.success) throw new src_CX2iR2pK_ProtocolError(src_CX2iR2pK_ProtocolErrorCode.InvalidParams, `Invalid arguments for prompt ${name}: ${parseResult.error}`); + return typedCallback(parseResult.data, ctx); + }; + } else { + const typedCallback = callback; + return async (_args, ctx) => { + return typedCallback(ctx); + }; + } +} +function createCompletionResult(suggestions) { + return { completion: { + values: suggestions.map(String).slice(0, 100), + total: suggestions.length, + hasMore: suggestions.length > 100 + } }; +} +const EMPTY_COMPLETION_RESULT = { completion: { + values: [], + hasMore: false +} }; +/** @internal Gets the shape of a Zod object schema */ +function getSchemaShape(schema) { + const candidate = schema; + if (candidate.shape && typeof candidate.shape === "object") return candidate.shape; +} +/** @internal Checks if a Zod schema is optional */ +function isOptionalSchema(schema) { + return schema?.type === "optional"; +} +/** @internal Unwraps an optional Zod schema */ +function unwrapOptionalSchema(schema) { + if (!isOptionalSchema(schema)) return schema; + return schema.def?.innerType ?? schema; +} + +//#endregion + +//# sourceMappingURL=mcp-DXXb3Vv3.mjs.map + + + + +//#region src/server/perRequestTransport.ts +/** +* The per-request micro-transport: a real, connected `Transport` whose whole +* lifetime is one HTTP exchange. See the module documentation for the +* response shapes it produces. +*/ +var PerRequestHTTPServerTransport = class { + onclose; + onerror; + onmessage; + _classification; + _responseMode; + _started = false; + _used = false; + _closed = false; + _terminalDelivered = false; + /** + * `true` only while the inbound message is being delivered synchronously + * to the connected protocol layer. The pre-handler gates (the era + * registry gate, the edge→instance handoff check, the missing-handler + * rejection) answer inside this window; request handlers always run + * after it (the protocol layer defers them to a microtask). An error + * sent inside the window is therefore ladder-originated, and an error + * sent after it is handler-produced. + */ + _dispatchWindowOpen = false; + _requestId; + _deferredResponse; + _sse; + _abortCleanup; + _keepAliveMs; + constructor(options) { + this._classification = options.classification; + this._responseMode = options.responseMode ?? "auto"; + this._keepAliveMs = options.keepAliveMs ?? DEFAULT_SSE_KEEP_ALIVE_MS; + } + async start() { + if (this._started) throw new Error("PerRequestHTTPServerTransport is already started"); + this._started = true; + } + /** + * Serves the single exchange: delivers the classified message to the + * connected server instance and resolves with the HTTP response. + * + * Throws when called a second time (the transport is strictly + * single-use), or before a server has been connected to the transport. + * The returned promise rejects with a connection-closed error when the + * transport is closed before a response was produced (for example because + * the client disconnected). + */ + async handleMessage(message, extra) { + if (this._used) throw new Error("PerRequestHTTPServerTransport serves exactly one exchange; construct a new transport per request"); + if (!this._started || this.onmessage === void 0) throw new Error("PerRequestHTTPServerTransport is not connected: connect a server to this transport before handling a message"); + if (this._closed) throw new Error("PerRequestHTTPServerTransport is closed"); + this._used = true; + const signal = extra?.request?.signal; + if (signal?.aborted) { + await this.close(); + throw new SdkError(SdkErrorCode.ConnectionClosed, "The request was aborted before it could be handled"); + } + const messageExtra = { + classification: this._classification, + ...extra?.request !== void 0 && { request: extra.request }, + ...extra?.authInfo !== void 0 && { authInfo: extra.authInfo } + }; + if (isJSONRPCRequest(message)) { + this._requestId = message.id; + let resolve; + let reject; + const promise = new Promise((promiseResolve, promiseReject) => { + resolve = promiseResolve; + reject = promiseReject; + }); + this._deferredResponse = { + promise, + resolve, + reject, + settled: false + }; + if (signal !== void 0) { + const onAbort = () => void this.close(); + signal.addEventListener("abort", onAbort, { once: true }); + this._abortCleanup = () => signal.removeEventListener("abort", onAbort); + } + this._dispatchWindowOpen = true; + try { + this.onmessage(message, messageExtra); + } finally { + this._dispatchWindowOpen = false; + } + if (this._responseMode === "sse" && !this._closed && !this._deferredResponse.settled) this.upgradeToSse(); + return promise; + } + this.onmessage(message, messageExtra); + return new Response(null, { status: 202 }); + } + async send(message, options) { + if (this._closed) return; + const isResponse = isJSONRPCResultResponse(message) || isJSONRPCErrorResponse(message); + const relatedId = isResponse ? message.id : options?.relatedRequestId; + if (this._requestId === void 0 || relatedId === void 0 || relatedId !== this._requestId) { + if (isResponse) this.onerror?.(/* @__PURE__ */ new Error(`Received a response for an unknown request id: ${String(message.id)}`)); + return; + } + if (isResponse) { + if (this._terminalDelivered) return; + this._terminalDelivered = true; + const errorCode = isJSONRPCErrorResponse(message) ? message.error.code : void 0; + const ladderStatus = errorCode !== void 0 && (this._dispatchWindowOpen || errorCode === ProtocolErrorCode.MissingRequiredClientCapability) ? LADDER_ERROR_HTTP_STATUS[errorCode] : void 0; + if (ladderStatus !== void 0 && this._sse === void 0) { + this.settleResponse(Response.json(message, { + status: ladderStatus, + headers: { "Content-Type": "application/json" } + })); + queueMicrotask(() => void this.close()); + return; + } + if (this._sse !== void 0 || this._responseMode === "sse") { + if (this._sse === void 0) this.upgradeToSse(); + this.writeMessageFrame(message); + this.finalizeStream(); + return; + } + this.settleResponse(Response.json(message, { + status: 200, + headers: { "Content-Type": "application/json" } + })); + queueMicrotask(() => void this.close()); + return; + } + if (this._responseMode === "json") return; + if (this._sse === void 0) this.upgradeToSse(); + this.writeMessageFrame(message); + } + /** + * Writes an SSE comment frame (a keep-alive heartbeat). Dropped when the + * exchange is not currently streaming. + */ + writeCommentFrame(comment) { + if (this._closed || this._sse === void 0 || this._sse.closed) return; + const frame = comment.split("\n").map((line) => `: ${line}`).join("\n"); + this.writeFrame(`${frame}\n\n`); + } + async close() { + if (this._closed) return; + this._closed = true; + this._abortCleanup?.(); + this._abortCleanup = void 0; + if (this._sse?.keepAliveTimer !== void 0) clearInterval(this._sse.keepAliveTimer); + if (this._sse !== void 0 && !this._sse.closed) { + this._sse.closed = true; + try { + this._sse.controller.close(); + } catch {} + } + if (this._deferredResponse !== void 0 && !this._deferredResponse.settled) { + this._deferredResponse.settled = true; + this._deferredResponse.reject(new SdkError(SdkErrorCode.ConnectionClosed, "Connection closed before a response was produced")); + } + this.onclose?.(); + } + settleResponse(response) { + if (this._deferredResponse === void 0 || this._deferredResponse.settled) return; + this._deferredResponse.settled = true; + this._deferredResponse.resolve(response); + } + upgradeToSse() { + let controller; + const readable = new ReadableStream({ + start: (streamController) => { + controller = streamController; + }, + cancel: () => { + this.close(); + } + }); + this._sse = { + controller, + encoder: new TextEncoder(), + closed: false + }; + this._sse.keepAliveTimer = armSseKeepAlive(this._keepAliveMs, () => this.writeCommentFrame("keepalive")); + this.settleResponse(new Response(readable, { + status: 200, + headers: { + "Content-Type": "text/event-stream", + "Cache-Control": "no-cache, no-transform", + Connection: "keep-alive", + "X-Accel-Buffering": "no" + } + })); + } + finalizeStream() { + if (this._sse?.keepAliveTimer !== void 0) clearInterval(this._sse.keepAliveTimer); + if (this._sse !== void 0 && !this._sse.closed) { + this._sse.closed = true; + try { + this._sse.controller.close(); + } catch {} + } + queueMicrotask(() => void this.close()); + } + writeMessageFrame(message) { + this.writeFrame(`event: message\ndata: ${JSON.stringify(message)}\n\n`); + } + writeFrame(frame) { + if (this._sse === void 0 || this._sse.closed) return; + try { + this._sse.controller.enqueue(this._sse.encoder.encode(frame)); + } catch (error) { + this.onerror?.(/* @__PURE__ */ new Error(`Failed to write to the response stream: ${error}`)); + } + } +}; + +//#endregion +//#region src/server/invoke.ts +/** +* Serves one classified inbound message on the given server instance and +* returns the HTTP response for the exchange. +* +* The instance is connected to a fresh single-exchange transport, the message +* is injected through the normal transport message path, and whatever the +* dispatch layer produces (the handler result, a protocol-level rejection, or +* streamed related messages followed by the result) is captured as the +* returned `Response`. For request exchanges, teardown rides the transport's +* close chain once the terminal response has been delivered; notification +* exchanges resolve with the 202 response immediately and do NOT run the +* close chain — the transport stays connected until the caller closes it or +* drops the per-request instance, which is the caller's choice either way. +*/ +async function invoke(server, message, ctx) { + const transport = new PerRequestHTTPServerTransport({ + classification: ctx.classification, + ...ctx.responseMode !== void 0 && { responseMode: ctx.responseMode }, + ...ctx.keepAliveMs !== void 0 && { keepAliveMs: ctx.keepAliveMs } + }); + await server.connect(transport); + return transport.handleMessage(message, { + ...ctx.request !== void 0 && { request: ctx.request }, + ...ctx.authInfo !== void 0 && { authInfo: ctx.authInfo } + }); +} + +//#endregion +//#region src/server/streamableHttp.ts +/** +* Server transport for Web Standards Streamable HTTP: this implements the MCP Streamable HTTP transport specification +* using Web Standard APIs (`Request`, `Response`, `ReadableStream`). +* +* This transport works on any runtime that supports Web Standards: Node.js 18+, Cloudflare Workers, Deno, Bun, etc. +* +* In stateful mode: +* - Session ID is generated and included in response headers +* - Session ID is always included in initialization responses +* - Requests with invalid session IDs are rejected with `404 Not Found` +* - Non-initialization requests without a session ID are rejected with `400 Bad Request` +* - State is maintained in-memory (connections, message history) +* +* In stateless mode: +* - No Session ID is included in any responses +* - No session validation is performed +* +* @example Stateful setup +* ```ts source="./streamableHttp.examples.ts#WebStandardStreamableHTTPServerTransport_stateful" +* const server = new McpServer({ name: 'my-server', version: '1.0.0' }); +* +* const transport = new WebStandardStreamableHTTPServerTransport({ +* sessionIdGenerator: () => crypto.randomUUID() +* }); +* +* await server.connect(transport); +* ``` +* +* @example Stateless setup +* ```ts source="./streamableHttp.examples.ts#WebStandardStreamableHTTPServerTransport_stateless" +* const transport = new WebStandardStreamableHTTPServerTransport({ +* sessionIdGenerator: undefined +* }); +* ``` +* +* @example Hono.js +* ```ts source="./streamableHttp.examples.ts#WebStandardStreamableHTTPServerTransport_hono" +* app.all('/mcp', async c => { +* return transport.handleRequest(c.req.raw); +* }); +* ``` +* +* @example Cloudflare Workers +* ```ts source="./streamableHttp.examples.ts#WebStandardStreamableHTTPServerTransport_workers" +* const worker = { +* async fetch(request: Request): Promise { +* return transport.handleRequest(request); +* } +* }; +* ``` +*/ +var WebStandardStreamableHTTPServerTransport = class { + sessionIdGenerator; + _started = false; + _closed = false; + _streamMapping = /* @__PURE__ */ new Map(); + _requestToStreamMapping = /* @__PURE__ */ new Map(); + _requestResponseMap = /* @__PURE__ */ new Map(); + _initialized = false; + _enableJsonResponse = false; + _standaloneSseStreamId = "_GET_stream"; + _eventStore; + _onsessioninitialized; + _onsessionclosed; + _allowedHosts; + _allowedOrigins; + _enableDnsRebindingProtection; + _retryInterval; + _supportedProtocolVersions; + _keepAliveMs; + sessionId; + onclose; + onerror; + onmessage; + constructor(options = {}) { + this.sessionIdGenerator = options.sessionIdGenerator; + this._enableJsonResponse = options.enableJsonResponse ?? false; + this._eventStore = options.eventStore; + this._onsessioninitialized = options.onsessioninitialized; + this._onsessionclosed = options.onsessionclosed; + this._allowedHosts = options.allowedHosts; + this._allowedOrigins = options.allowedOrigins; + this._enableDnsRebindingProtection = options.enableDnsRebindingProtection ?? false; + this._retryInterval = options.retryInterval; + this._supportedProtocolVersions = options.supportedProtocolVersions ?? SUPPORTED_PROTOCOL_VERSIONS; + this._keepAliveMs = options.keepAliveMs ?? DEFAULT_SSE_KEEP_ALIVE_MS; + } + startKeepAlive(controller, encoder) { + if (this._closed) return void 0; + const timer = armSseKeepAlive(this._keepAliveMs, () => { + try { + controller.enqueue(encoder.encode(": keepalive\n\n")); + } catch { + if (timer !== void 0) clearInterval(timer); + } + }); + return timer; + } + /** + * Starts the transport. This is required by the {@linkcode Transport} interface but is a no-op + * for the Streamable HTTP transport as connections are managed per-request. + */ + async start() { + if (this._started) throw new Error("Transport already started"); + this._started = true; + } + /** + * Sets the supported protocol versions for header validation. + * Called by the server during {@linkcode server/server.Server.connect | connect()} to pass its supported versions. + */ + setSupportedProtocolVersions(versions) { + this._supportedProtocolVersions = versions; + } + /** + * Helper to create a JSON error response + */ + createJsonErrorResponse(status, code, message, options) { + const error = { + code, + message + }; + if (options?.data !== void 0) error.data = options.data; + return Response.json({ + jsonrpc: "2.0", + error, + id: null + }, { + status, + headers: { + "Content-Type": "application/json", + ...options?.headers + } + }); + } + /** + * Validates request headers for DNS rebinding protection. + * @returns Error response if validation fails, `undefined` if validation passes. + */ + validateRequestHeaders(req) { + if (!this._enableDnsRebindingProtection) return; + if (this._allowedHosts && this._allowedHosts.length > 0) { + const hostHeader = req.headers.get("host"); + if (!hostHeader || !this._allowedHosts.includes(hostHeader)) { + const error = `Invalid Host header: ${hostHeader}`; + this.onerror?.(new Error(error)); + return this.createJsonErrorResponse(403, -32e3, error); + } + } + if (this._allowedOrigins && this._allowedOrigins.length > 0) { + const originHeader = req.headers.get("origin"); + if (originHeader && !this._allowedOrigins.includes(originHeader)) { + const error = `Invalid Origin header: ${originHeader}`; + this.onerror?.(new Error(error)); + return this.createJsonErrorResponse(403, -32e3, error); + } + } + } + /** + * Handles an incoming HTTP request, whether `GET`, `POST`, or `DELETE` + * Returns a `Response` object (Web Standard) + */ + async handleRequest(req, options) { + if (this._closed) return this.createJsonErrorResponse(404, -32001, "Session not found"); + const validationError = this.validateRequestHeaders(req); + if (validationError) return validationError; + switch (req.method) { + case "POST": return this.handlePostRequest(req, options); + case "GET": return this.handleGetRequest(req); + case "DELETE": return this.handleDeleteRequest(req); + default: return this.handleUnsupportedRequest(); + } + } + /** + * Returns true if the client's protocol version supports empty SSE data in + * priming events (the fix shipped with protocol version `2025-11-25`). + * + * The version is checked for membership in this transport instance's + * supported protocol versions rather than with an open-ended + * `>= '2025-11-25'` comparison: the value may come from an `initialize` + * request body, which (unlike the `MCP-Protocol-Version` header) is not + * validated against `supportedProtocolVersions` before reaching this + * check. An unknown future version string must not silently enable + * behavior reserved for versions this transport actually supports. + */ + supportsEmptySSEData(protocolVersion) { + return this._supportedProtocolVersions.includes(protocolVersion) && protocolVersion >= "2025-11-25"; + } + /** + * Writes a priming event to establish resumption capability. + * Only sends if `eventStore` is configured (opt-in for resumability) and + * the client's protocol version supports empty SSE data (a supported + * version that is >= `2025-11-25`). + */ + async writePrimingEvent(controller, encoder, streamId, protocolVersion) { + if (!this._eventStore) return; + if (!this.supportsEmptySSEData(protocolVersion)) return; + const primingEventId = await this._eventStore.storeEvent(streamId, {}); + let primingEvent = `id: ${primingEventId}\ndata: \n\n`; + if (this._retryInterval !== void 0) primingEvent = `id: ${primingEventId}\nretry: ${this._retryInterval}\ndata: \n\n`; + controller.enqueue(encoder.encode(primingEvent)); + } + /** + * Handles `GET` requests for SSE stream + */ + async handleGetRequest(req) { + if (!req.headers.get("accept")?.includes("text/event-stream")) { + this.onerror?.(/* @__PURE__ */ new Error("Not Acceptable: Client must accept text/event-stream")); + return this.createJsonErrorResponse(406, -32e3, "Not Acceptable: Client must accept text/event-stream"); + } + const sessionError = this.validateSession(req); + if (sessionError) return sessionError; + const protocolError = this.validateProtocolVersion(req); + if (protocolError) return protocolError; + if (this._eventStore) { + const lastEventId = req.headers.get("last-event-id"); + if (lastEventId) return this.replayEvents(lastEventId); + } + if (this._streamMapping.get(this._standaloneSseStreamId) !== void 0) { + this.onerror?.(/* @__PURE__ */ new Error("Conflict: Only one SSE stream is allowed per session")); + return this.createJsonErrorResponse(409, -32e3, "Conflict: Only one SSE stream is allowed per session"); + } + const encoder = new TextEncoder(); + let streamController; + let keepAliveTimer; + const readable = new ReadableStream({ + start: (controller) => { + streamController = controller; + }, + cancel: () => { + if (keepAliveTimer !== void 0) clearInterval(keepAliveTimer); + if (this._streamMapping.get(this._standaloneSseStreamId)?.controller === streamController) this._streamMapping.delete(this._standaloneSseStreamId); + } + }); + const headers = { + "Content-Type": "text/event-stream", + "Cache-Control": "no-cache, no-transform", + Connection: "keep-alive", + "X-Accel-Buffering": "no" + }; + if (this.sessionId !== void 0) headers["mcp-session-id"] = this.sessionId; + this._streamMapping.set(this._standaloneSseStreamId, { + controller: streamController, + encoder, + cleanup: () => { + if (keepAliveTimer !== void 0) clearInterval(keepAliveTimer); + this._streamMapping.delete(this._standaloneSseStreamId); + try { + streamController.close(); + } catch {} + } + }); + keepAliveTimer = this.startKeepAlive(streamController, encoder); + return new Response(readable, { headers }); + } + /** + * Replays events that would have been sent after the specified event ID + * Only used when resumability is enabled + */ + async replayEvents(lastEventId) { + if (!this._eventStore) { + this.onerror?.(/* @__PURE__ */ new Error("Event store not configured")); + return this.createJsonErrorResponse(400, -32e3, "Event store not configured"); + } + try { + let streamId; + if (this._eventStore.getStreamIdForEventId) { + streamId = await this._eventStore.getStreamIdForEventId(lastEventId); + if (!streamId) { + this.onerror?.(/* @__PURE__ */ new Error("Invalid event ID format")); + return this.createJsonErrorResponse(400, -32e3, "Invalid event ID format"); + } + if (this._streamMapping.get(streamId) !== void 0) { + this.onerror?.(/* @__PURE__ */ new Error("Conflict: Stream already has an active connection")); + return this.createJsonErrorResponse(409, -32e3, "Conflict: Stream already has an active connection"); + } + } + const headers = { + "Content-Type": "text/event-stream", + "Cache-Control": "no-cache, no-transform", + Connection: "keep-alive", + "X-Accel-Buffering": "no" + }; + if (this.sessionId !== void 0) headers["mcp-session-id"] = this.sessionId; + const encoder = new TextEncoder(); + let streamController; + let keepAliveTimer; + let cancelled = false; + let replayedStreamId; + const readable = new ReadableStream({ + start: (controller) => { + streamController = controller; + }, + cancel: () => { + cancelled = true; + if (keepAliveTimer !== void 0) clearInterval(keepAliveTimer); + if (replayedStreamId !== void 0 && this._streamMapping.get(replayedStreamId)?.controller === streamController) this._streamMapping.delete(replayedStreamId); + } + }); + const replayedEventIds = /* @__PURE__ */ new Set(); + replayedStreamId = await this._eventStore.replayEventsAfter(lastEventId, { send: async (eventId, message) => { + replayedEventIds.add(eventId); + if (!this.writeSSEEvent(streamController, encoder, message, eventId)) try { + streamController.close(); + } catch {} + } }); + if (this._closed || cancelled) { + try { + streamController.close(); + } catch {} + return this.createJsonErrorResponse(404, -32001, "Session not found"); + } + this._streamMapping.get(replayedStreamId)?.cleanup(); + this._streamMapping.set(replayedStreamId, { + controller: streamController, + encoder, + replayedEventIds, + cleanup: () => { + if (keepAliveTimer !== void 0) clearInterval(keepAliveTimer); + this._streamMapping.delete(replayedStreamId); + try { + streamController.close(); + } catch {} + } + }); + if (replayedStreamId !== this._standaloneSseStreamId) { + if (![...this._requestToStreamMapping.values()].includes(replayedStreamId)) { + this._streamMapping.delete(replayedStreamId); + try { + streamController.close(); + } catch {} + } + } + if (this._streamMapping.get(replayedStreamId)?.controller === streamController) keepAliveTimer = this.startKeepAlive(streamController, encoder); + return new Response(readable, { headers }); + } catch (error) { + this.onerror?.(error); + return this.createJsonErrorResponse(500, -32e3, "Error replaying events"); + } + } + /** + * Writes an event to an SSE stream via controller with proper formatting + */ + writeSSEEvent(controller, encoder, message, eventId) { + try { + let eventData = `event: message\n`; + if (eventId) eventData += `id: ${eventId}\n`; + eventData += `data: ${JSON.stringify(message)}\n\n`; + controller.enqueue(encoder.encode(eventData)); + return true; + } catch (error) { + this.onerror?.(error); + return false; + } + } + /** + * Handles unsupported requests (`PUT`, `PATCH`, etc.) + */ + handleUnsupportedRequest() { + this.onerror?.(/* @__PURE__ */ new Error("Method not allowed.")); + return Response.json({ + jsonrpc: "2.0", + error: { + code: -32e3, + message: "Method not allowed." + }, + id: null + }, { + status: 405, + headers: { + Allow: "GET, POST, DELETE", + "Content-Type": "application/json" + } + }); + } + /** + * Handles `POST` requests containing JSON-RPC messages + */ + async handlePostRequest(req, options) { + try { + const acceptHeader = req.headers.get("accept"); + if (!acceptHeader?.includes("application/json") || !acceptHeader.includes("text/event-stream")) { + this.onerror?.(/* @__PURE__ */ new Error("Not Acceptable: Client must accept both application/json and text/event-stream")); + return this.createJsonErrorResponse(406, -32e3, "Not Acceptable: Client must accept both application/json and text/event-stream"); + } + if (!isJsonContentType(req.headers.get("content-type"))) { + this.onerror?.(/* @__PURE__ */ new Error("Unsupported Media Type: Content-Type must be application/json")); + return this.createJsonErrorResponse(415, -32e3, "Unsupported Media Type: Content-Type must be application/json"); + } + const request = req; + let rawMessage; + if (options?.parsedBody === void 0) try { + rawMessage = await req.json(); + } catch (error) { + this.onerror?.(error); + return this.createJsonErrorResponse(400, -32700, "Parse error: Invalid JSON"); + } + else rawMessage = options.parsedBody; + let messages; + try { + messages = Array.isArray(rawMessage) ? rawMessage.map((msg) => JSONRPCMessageSchema.parse(msg)) : [JSONRPCMessageSchema.parse(rawMessage)]; + } catch (error) { + this.onerror?.(error); + return this.createJsonErrorResponse(400, -32700, "Parse error: Invalid JSON-RPC message"); + } + if (this._closed) return this.createJsonErrorResponse(404, -32001, "Session not found"); + const isInitializationRequest = messages.some((element) => isInitializeRequest(element)); + if (isInitializationRequest) { + if (this._initialized && this.sessionId !== void 0) { + this.onerror?.(/* @__PURE__ */ new Error("Invalid Request: Server already initialized")); + return this.createJsonErrorResponse(400, -32600, "Invalid Request: Server already initialized"); + } + if (messages.length > 1) { + this.onerror?.(/* @__PURE__ */ new Error("Invalid Request: Only one initialization request is allowed")); + return this.createJsonErrorResponse(400, -32600, "Invalid Request: Only one initialization request is allowed"); + } + this.sessionId = this.sessionIdGenerator?.(); + this._initialized = true; + if (this.sessionId && this._onsessioninitialized) await Promise.resolve(this._onsessioninitialized(this.sessionId)); + } + if (!isInitializationRequest) { + const sessionError = this.validateSession(req); + if (sessionError) return sessionError; + const protocolError = this.validateProtocolVersion(req); + if (protocolError) return protocolError; + } + if (this._closed) return this.createJsonErrorResponse(404, -32001, "Session not found"); + if (!messages.some((element) => isJSONRPCRequest(element))) { + for (const message of messages) this.onmessage?.(message, { + authInfo: options?.authInfo, + request + }); + return new Response(null, { status: 202 }); + } + const streamId = crypto.randomUUID(); + const initRequest = messages.find((m) => isInitializeRequest(m)); + const clientProtocolVersion = initRequest ? initRequest.params.protocolVersion : req.headers.get("mcp-protocol-version") ?? DEFAULT_NEGOTIATED_PROTOCOL_VERSION; + if (this._enableJsonResponse) return new Promise((resolve) => { + this._streamMapping.set(streamId, { + resolveJson: resolve, + cleanup: () => { + this._streamMapping.delete(streamId); + } + }); + for (const message of messages) if (isJSONRPCRequest(message)) this._requestToStreamMapping.set(message.id, streamId); + for (const message of messages) this.onmessage?.(message, { + authInfo: options?.authInfo, + request + }); + }); + const encoder = new TextEncoder(); + let streamController; + let keepAliveTimer; + const readable = new ReadableStream({ + start: (controller) => { + streamController = controller; + }, + cancel: () => { + if (keepAliveTimer !== void 0) clearInterval(keepAliveTimer); + if (this._streamMapping.get(streamId)?.controller === streamController) this._streamMapping.delete(streamId); + } + }); + const headers = { + "Content-Type": "text/event-stream", + "Cache-Control": "no-cache, no-transform", + Connection: "keep-alive", + "X-Accel-Buffering": "no" + }; + if (this.sessionId !== void 0) headers["mcp-session-id"] = this.sessionId; + for (const message of messages) if (isJSONRPCRequest(message)) { + this._streamMapping.set(streamId, { + controller: streamController, + encoder, + cleanup: () => { + if (keepAliveTimer !== void 0) clearInterval(keepAliveTimer); + this._streamMapping.delete(streamId); + try { + streamController.close(); + } catch {} + } + }); + this._requestToStreamMapping.set(message.id, streamId); + } + await this.writePrimingEvent(streamController, encoder, streamId, clientProtocolVersion); + for (const message of messages) { + let closeSSEStream; + let closeStandaloneSSEStream; + if (isJSONRPCRequest(message) && this._eventStore && this.supportsEmptySSEData(clientProtocolVersion)) { + closeSSEStream = () => { + this.closeSSEStream(message.id); + }; + closeStandaloneSSEStream = () => { + this.closeStandaloneSSEStream(); + }; + } + this.onmessage?.(message, { + authInfo: options?.authInfo, + request, + closeSSEStream, + closeStandaloneSSEStream + }); + } + if (this._streamMapping.get(streamId)?.controller === streamController) keepAliveTimer = this.startKeepAlive(streamController, encoder); + return new Response(readable, { + status: 200, + headers + }); + } catch (error) { + this.onerror?.(error); + return this.createJsonErrorResponse(400, -32700, "Parse error", { data: String(error) }); + } + } + /** + * Handles `DELETE` requests to terminate sessions + */ + async handleDeleteRequest(req) { + const sessionError = this.validateSession(req); + if (sessionError) return sessionError; + const protocolError = this.validateProtocolVersion(req); + if (protocolError) return protocolError; + try { + await Promise.resolve(this._onsessionclosed?.(this.sessionId)); + return new Response(null, { status: 200 }); + } finally { + await this.close(); + } + } + /** + * Validates session ID for non-initialization requests. + * Returns `Response` error if invalid, `undefined` otherwise + */ + validateSession(req) { + if (this.sessionIdGenerator === void 0) return; + if (!this._initialized) { + this.onerror?.(/* @__PURE__ */ new Error("Bad Request: Server not initialized")); + return this.createJsonErrorResponse(400, -32e3, "Bad Request: Server not initialized"); + } + const sessionId = req.headers.get("mcp-session-id"); + if (!sessionId) { + this.onerror?.(/* @__PURE__ */ new Error("Bad Request: Mcp-Session-Id header is required")); + return this.createJsonErrorResponse(400, -32e3, "Bad Request: Mcp-Session-Id header is required"); + } + if (sessionId !== this.sessionId) { + this.onerror?.(/* @__PURE__ */ new Error("Session not found")); + return this.createJsonErrorResponse(404, -32001, "Session not found"); + } + } + /** + * Validates the `MCP-Protocol-Version` header on incoming requests. + * + * For initialization: Version negotiation handles unknown versions gracefully + * (server responds with its supported version). + * + * For subsequent requests with `MCP-Protocol-Version` header: + * - Accept if in supported list + * - 400 if unsupported + * + * For HTTP requests without the `MCP-Protocol-Version` header: + * - Accept and default to the version negotiated at initialization + */ + validateProtocolVersion(req) { + const protocolVersion = req.headers.get("mcp-protocol-version"); + if (protocolVersion !== null && !this._supportedProtocolVersions.includes(protocolVersion)) { + const error = `Bad Request: Unsupported protocol version: ${protocolVersion} (supported versions: ${this._supportedProtocolVersions.join(", ")})`; + this.onerror?.(new Error(error)); + return this.createJsonErrorResponse(400, -32e3, error); + } + } + async close() { + if (this._closed) return; + this._closed = true; + for (const { cleanup } of this._streamMapping.values()) cleanup(); + this._streamMapping.clear(); + this._requestResponseMap.clear(); + this.onclose?.(); + } + /** + * Close an SSE stream for a specific request, triggering client reconnection. + * Use this to implement polling behavior during long-running operations - + * client will reconnect after the retry interval specified in the priming event. + */ + closeSSEStream(requestId) { + const streamId = this._requestToStreamMapping.get(requestId); + if (!streamId) return; + const stream = this._streamMapping.get(streamId); + if (stream) stream.cleanup(); + } + /** + * Close the standalone `GET` SSE stream, triggering client reconnection. + * Use this to implement polling behavior for server-initiated notifications. + */ + closeStandaloneSSEStream() { + const stream = this._streamMapping.get(this._standaloneSseStreamId); + if (stream) stream.cleanup(); + } + async send(message, options) { + let requestId = options?.relatedRequestId; + if (isJSONRPCResultResponse(message) || isJSONRPCErrorResponse(message)) requestId = message.id; + if (requestId === void 0) { + if (isJSONRPCResultResponse(message) || isJSONRPCErrorResponse(message)) throw new Error("Cannot send a response on a standalone SSE stream unless resuming a previous client request"); + let eventId; + if (this._eventStore) eventId = await this._eventStore.storeEvent(this._standaloneSseStreamId, message); + const standaloneSse = this._streamMapping.get(this._standaloneSseStreamId); + if (standaloneSse === void 0) return; + if (standaloneSse.controller && standaloneSse.encoder && (eventId === void 0 || !standaloneSse.replayedEventIds?.has(eventId))) this.writeSSEEvent(standaloneSse.controller, standaloneSse.encoder, message, eventId); + return; + } + const streamId = this._requestToStreamMapping.get(requestId); + if (!streamId) throw new Error(`No connection established for request ID: ${String(requestId)}`); + let stream = this._streamMapping.get(streamId); + if (!this._enableJsonResponse) { + let eventId; + if (this._eventStore) { + eventId = await this._eventStore.storeEvent(streamId, message); + stream = this._streamMapping.get(streamId); + } + if (stream?.controller && stream?.encoder && (eventId === void 0 || !stream.replayedEventIds?.has(eventId))) this.writeSSEEvent(stream.controller, stream.encoder, message, eventId); + } + if (isJSONRPCResultResponse(message) || isJSONRPCErrorResponse(message)) { + this._requestResponseMap.set(requestId, message); + const relatedIds = [...this._requestToStreamMapping.entries()].filter(([_, sid]) => sid === streamId).map(([id]) => id); + if (relatedIds.every((id) => this._requestResponseMap.has(id))) { + if (!stream) { + if (this._enableJsonResponse) throw new Error(`No connection established for request ID: ${String(requestId)}`); + if (!this._eventStore) { + this.onerror?.(/* @__PURE__ */ new Error(`Response for request ID ${String(requestId)} is undeliverable: per-request stream is disconnected and no eventStore is configured`)); + for (const id of relatedIds) { + this._requestResponseMap.delete(id); + this._requestToStreamMapping.delete(id); + } + return; + } + for (const id of relatedIds) { + this._requestResponseMap.delete(id); + this._requestToStreamMapping.delete(id); + } + return; + } + if (this._enableJsonResponse && stream.resolveJson) { + const headers = { "Content-Type": "application/json" }; + if (this.sessionId !== void 0) headers["mcp-session-id"] = this.sessionId; + const responses = relatedIds.map((id) => this._requestResponseMap.get(id)); + if (responses.length === 1) stream.resolveJson(Response.json(responses[0], { + status: 200, + headers + })); + else stream.resolveJson(Response.json(responses, { + status: 200, + headers + })); + stream.cleanup(); + } else stream.cleanup(); + for (const id of relatedIds) { + this._requestResponseMap.delete(id); + this._requestToStreamMapping.delete(id); + } + } + } + } +}; + +//#endregion +//#region src/server/createMcpHandler.ts +/** +* The JSON-RPC id to echo on an entry-built error response: the body's `id` +* when the body is a single JSON-RPC request whose id is a string or number, +* `null` otherwise. Error responses must carry the id of the request they +* correspond to whenever it could be read; `null` is reserved for the cases +* where no single request id is determinable — unparseable bodies, body-less +* methods, notifications, posted responses and batch arrays. +*/ +function echoableRequestId(body) { + if (body === null || typeof body !== "object" || Array.isArray(body)) return null; + const { method, id } = body; + if (typeof method !== "string") return null; + return typeof id === "string" || typeof id === "number" ? id : null; +} +function jsonRpcErrorResponse(httpStatus, code, message, data, id = null) { + return Response.json({ + jsonrpc: "2.0", + error: { + code, + message, + ...data !== void 0 && { data } + }, + id + }, { status: httpStatus }); +} +function rejectionResponse(rejection, id = null) { + return jsonRpcErrorResponse(rejection.httpStatus, rejection.code, rejection.message, rejection.data, id); +} +function toError(value) { + return value instanceof Error ? value : new Error(String(value)); +} +function internalServerErrorResponse(id = null) { + return jsonRpcErrorResponse(500, -32603, "Internal server error", void 0, id); +} +/** +* The entry's default legacy serving (`legacy: 'stateless'`): per-request +* stateless serving of 2025-era traffic using the same factory as the modern +* path. Exported as a standalone building block for hand-wired compositions +* (for example mounting legacy stateless serving on its own route next to a +* strict modern endpoint). +* +* Each POST is served by a fresh instance from the factory connected to a +* fresh streamable HTTP transport constructed with only +* `sessionIdGenerator: undefined` — the established stateless idiom, unchanged. +* Because serving is per-request and stateless, GET and DELETE (2025 session +* operations) are answered with `405` / `Method not allowed.`, exactly like the +* canonical stateless example. +* +* The optional `onerror` callback receives factory and serving failures on +* this leg (reporting only — the response stays the 500 internal-error body). +* The entry passes its own `onerror` here when expanding the default, so +* legacy-leg failures are never silently swallowed. +*/ +function createLegacyStatelessFallback(factory, onerror, keepAliveMs) { + return async (request, options) => { + if (request.method.toUpperCase() !== "POST") return jsonRpcErrorResponse(405, -32e3, "Method not allowed."); + try { + const product = await factory({ + era: "legacy", + ...options?.authInfo !== void 0 && { authInfo: options.authInfo }, + requestInfo: request + }); + const transport = new WebStandardStreamableHTTPServerTransport({ + sessionIdGenerator: void 0, + ...keepAliveMs !== void 0 && { keepAliveMs } + }); + await product.connect(transport); + const teardown = () => { + transport.close().catch(() => {}); + product.close().catch(() => {}); + }; + request.signal?.addEventListener("abort", teardown, { once: true }); + const response = await transport.handleRequest(request, { + ...options?.authInfo !== void 0 && { authInfo: options.authInfo }, + ...options?.parsedBody !== void 0 && { parsedBody: options.parsedBody } + }); + if (response.body === null || mediaTypeEssence(response.headers.get("content-type")) !== "text/event-stream") { + teardown(); + return response; + } + const reader = response.body.getReader(); + let toreDown = false; + const completeExchange = () => { + if (!toreDown) { + toreDown = true; + teardown(); + } + }; + const monitoredBody = new ReadableStream({ + pull: async (controller) => { + try { + const { done, value } = await reader.read(); + if (done) { + completeExchange(); + controller.close(); + return; + } + if (value !== void 0) controller.enqueue(value); + } catch (error) { + completeExchange(); + controller.error(error); + } + }, + cancel: (reason) => { + completeExchange(); + return reader.cancel(reason).catch(() => {}); + } + }); + return new Response(monitoredBody, { + status: response.status, + statusText: response.statusText, + headers: response.headers + }); + } catch (error) { + try { + onerror?.(toError(error)); + } catch {} + return internalServerErrorResponse(echoableRequestId(options?.parsedBody)); + } + }; +} +function legacyStatelessFallback(factory, onerror) { + return createLegacyStatelessFallback(factory, onerror); +} +/** +* The entry's classification step: read the request body exactly once (unless +* a pre-parsed body is supplied) and classify the request with +* {@linkcode classifyInboundRequest}. This is the single code path behind both +* {@linkcode createMcpHandler}'s routing and the exported +* {@linkcode isLegacyRequest} predicate, so the two can never disagree. +* +* Pass `needsForward: false` when the caller never reads `forwardRequest` — +* the body-preserving clone is then skipped and `forwardRequest` is the +* (consumed) input request. +*/ +async function classifyEntryRequest(request, providedParsedBody, needsForward = true) { + const httpMethod = request.method.toUpperCase(); + let body; + let parsedBody = providedParsedBody; + let forwardRequest = request; + let unparseable = false; + if (httpMethod === "POST") { + if (parsedBody === void 0) { + if (needsForward) forwardRequest = request.clone(); + let bodyText; + try { + bodyText = await request.text(); + } catch { + return { step: "unreadable-body" }; + } + try { + body = bodyText.length === 0 ? void 0 : JSON.parse(bodyText); + } catch { + unparseable = true; + } + if (!unparseable && body !== void 0) parsedBody = body; + } else body = parsedBody; + if (unparseable || body === void 0) return { + step: "no-json-body", + forwardRequest + }; + } + return { + step: "classified", + outcome: classifyInboundRequest({ + httpMethod, + protocolVersionHeader: request.headers.get("mcp-protocol-version") ?? void 0, + mcpMethodHeader: request.headers.get("mcp-method") ?? void 0, + mcpNameHeader: request.headers.get("mcp-name") ?? void 0, + ...body !== void 0 && { body } + }), + body, + parsedBody, + forwardRequest + }; +} +/** +* Whether {@linkcode createMcpHandler} would route this request to its legacy +* (2025-era) serving rather than the modern (2026-07-28) path. +* +* Call it with just the request: `await isLegacyRequest(request)`. For a +* `POST` the body is read from an internal clone, so the request you pass +* stays fully readable for whichever handler you route it to — no second +* argument is needed. (In a Node `(req, res)` handler, build that `Request` +* with `toWebRequest(req)` from `@modelcontextprotocol/node`; behind a body +* parser, which has already drained the Node stream, build it as +* `toWebRequest(req, req.body)` so the bytes come from the parsed body — +* either way the predicate still takes just the request.) The optional +* `parsedBody` is a perf escape hatch for a body you already hold parsed: +* pass it and the predicate classifies from the value directly, reading and +* cloning nothing. It is needed, not just faster, when the request's own +* body was already read — the internal clone is then impossible (cloning a +* used body throws a `TypeError`), so such a single-argument call rejects +* instead of guessing. +* +* This is the entry's own classification step exported as a predicate — it +* runs exactly the code `createMcpHandler` runs to make the routing decision, +* not a re-implementation — so a hand-wired composition that branches on it +* can never disagree with the entry. It is classification only: hand-wired +* compositions must validate Content-Type themselves (415 for POSTs whose +* media type is not `application/json`, via {@linkcode isJsonContentType}) +* before dispatching either leg — routing the legacy leg into the SDK +* transports gets their built-in check, but a custom modern leg has none. Use it to keep an existing legacy +* deployment (for example a sessionful streamable HTTP wiring) serving 2025 +* traffic next to a strict modern endpoint, now that the entry has no +* handler-valued `legacy` option: +* +* ```ts +* import { createMcpHandler, isLegacyRequest } from '@modelcontextprotocol/server'; +* +* const modern = createMcpHandler(factory, { legacy: 'reject' }); +* +* export default { +* async fetch(request: Request): Promise { +* if (await isLegacyRequest(request)) { +* // e.g. an existing sessionful WebStandardStreamableHTTPServerTransport wiring +* return myExistingLegacyHandler(request); +* } +* return modern.fetch(request); +* } +* }; +* ``` +* +* Semantics (identical to the entry's routing): +* +* - Returns `true` only for requests with no per-request `_meta` envelope +* claim: claim-less POSTs (including the `initialize` handshake and 2025-era +* notification POSTs without a modern protocol-version header), body-less +* GET/DELETE session operations, all-legacy JSON-RPC batch arrays, posted +* JSON-RPC responses, and POSTs whose body is empty or not valid JSON. +* - Returns `false` for everything the modern path answers, including its +* validation-ladder rejections: a request carrying the envelope claim (even +* one naming a revision the endpoint does not serve — the modern path +* answers it with the unsupported-protocol-version error), a malformed +* envelope behind a present claim (answered `-32602`), a request whose +* `MCP-Protocol-Version` header names a modern revision but that lacks the +* envelope (`-32602`), and header/body mismatches (`-32020`). Consumers +* routing on the predicate must send `false` traffic to the modern handler, +* never to a legacy handler — the modern path owns those error answers. +* - `server/discover` probes sent by negotiating clients always carry the +* envelope claim, so they are never legacy; a hand-built claim-less POST to +* a method named `server/discover` has no claim and classifies legacy, +* exactly as the entry itself routes it. +*/ +async function isLegacyRequest(request, parsedBody) { + const classified = await classifyEntryRequest(parsedBody === void 0 && request.method.toUpperCase() === "POST" ? request.clone() : request, parsedBody, false); + return classified.step === "no-json-body" || classified.step === "classified" && classified.outcome.kind === "legacy"; +} +/** +* Creates an HTTP handler that serves the 2026-07-28 protocol revision from a +* per-request server factory and, by default, falls back to old-school +* stateless serving for 2025-era traffic. Pass `legacy: 'reject'` for a +* modern-only strict endpoint. +* +* Mounting: `handler.fetch` is the web-standard face (Cloudflare Workers, +* Deno, Bun, Hono's `c.req.raw`); for Express/Fastify/plain `node:http`, wrap +* the handler once with `toNodeHandler(handler)` from +* `@modelcontextprotocol/node`. When mounting bare on a fetch-native runtime, +* put Origin/Host validation in front of the handler — the entry itself is +* deliberately validation-free: +* +* ```ts +* import { hostHeaderValidationResponse, originValidationResponse, localhostAllowedHostnames, localhostAllowedOrigins } from '@modelcontextprotocol/server'; +* +* export default { +* async fetch(request: Request): Promise { +* const rejected = +* hostHeaderValidationResponse(request, localhostAllowedHostnames()) ?? +* originValidationResponse(request, localhostAllowedOrigins()); +* return rejected ?? handler.fetch(request); +* } +* }; +* ``` +* +* Use ONE factory for both legs: the same tools/resources/prompts definition +* backs the modern path and the stateless legacy fallback, so the two eras can +* never drift apart. To keep an existing legacy deployment (for example a +* sessionful streamable HTTP wiring) serving 2025 traffic instead of the +* stateless fallback, route in user land with {@linkcode isLegacyRequest} in +* front of a strict handler — see that predicate's documentation for the +* pattern. Power users composing transport-neutral routing can also use the +* exported building blocks directly: {@linkcode classifyInboundRequest} for +* the era decision and `PerRequestHTTPServerTransport` for single-exchange +* serving — such compositions must reject POSTs whose Content-Type media type +* is not `application/json` (415) before parsing the body, using +* {@linkcode isJsonContentType}; neither building block performs this +* validation itself. +* +* The entry performs no token verification: `authInfo` given to `fetch` is +* passed through to handlers and the factory as-is and is never derived from +* request headers. +*/ +function createMcpHandler(factory, options = {}) { + const { legacy, onerror, responseMode } = options; + if (typeof legacy === "function") throw new TypeError("The 'legacy' option only accepts 'stateless' or 'reject', not a handler function. To serve 2025-era traffic with your own handler, route in user land with the exported isLegacyRequest(request) predicate in front of a strict (legacy: 'reject') handler."); + /** Modern per-request instances with an exchange still in flight (close() tears these down). */ + const inflight = /* @__PURE__ */ new Set(); + let closed = false; + const reportError = (error) => { + try { + onerror?.(error); + } catch {} + }; + const bus = options.bus ?? new InMemoryServerEventBus(reportError); + const notify = createServerNotifier(bus); + const listenRouter = createListenRouter({ + bus, + maxSubscriptions: options.maxSubscriptions ?? DEFAULT_MAX_SUBSCRIPTIONS, + keepAliveMs: options.keepAliveMs ?? DEFAULT_SSE_KEEP_ALIVE_MS, + onerror: reportError + }); + if (responseMode === "json") console.warn("responseMode: 'json' drops mid-call notifications. subscriptions/listen streams are always served over SSE regardless; other notifications emitted before a result are dropped."); + const legacyHandler = legacy === "reject" ? void 0 : createLegacyStatelessFallback(factory, reportError, options.keepAliveMs); + async function serveModern(route, request, authInfo) { + const claimedRevision = route.classification.revision; + if (claimedRevision === void 0 || !SUPPORTED_MODERN_PROTOCOL_VERSIONS.includes(claimedRevision)) { + const error = new UnsupportedProtocolVersionError({ + supported: [...SUPPORTED_MODERN_PROTOCOL_VERSIONS], + requested: claimedRevision ?? "unknown" + }); + reportError(error); + return jsonRpcErrorResponse(400, error.code, error.message, error.data, echoableRequestId(route.message)); + } + const stdHeaderRejection = validateStandardRequestHeaders({ + httpMethod: request.method, + mcpMethodHeader: request.headers.get("mcp-method") ?? void 0, + mcpNameHeader: request.headers.get("mcp-name") ?? void 0 + }, route); + if (stdHeaderRejection !== void 0) { + reportError(/* @__PURE__ */ new Error(`Rejected inbound request (${stdHeaderRejection.cell}): ${stdHeaderRejection.message}`)); + return rejectionResponse(stdHeaderRejection, echoableRequestId(route.message)); + } + const meta = route.messageKind === "request" ? requestMetaOf(route.message.params) : void 0; + const declaredClientCapabilities = meta?.[CLIENT_CAPABILITIES_META_KEY]; + if (route.messageKind === "request") { + const required = requiredClientCapabilitiesForRequest(route.message.method); + if (required !== void 0) { + const missing = missingClientCapabilities(required, declaredClientCapabilities); + if (missing !== void 0) { + const error = new MissingRequiredClientCapabilityError({ requiredCapabilities: missing }); + reportError(error); + return jsonRpcErrorResponse(httpStatusForErrorCode(error.code, "ladder"), error.code, error.message, error.data, route.message.id); + } + } + } + const product = await factory({ + era: "modern", + ...authInfo !== void 0 && { authInfo }, + requestInfo: request + }); + const server = product instanceof McpServer ? product.server : product; + if (route.messageKind === "request" && route.message.method === "subscriptions/listen") { + const capabilities = server.getCapabilities(); + const serverInfo = serverIdentityOf(server); + product.close().catch(reportError); + return listenRouter.serve(route.message, request.signal, capabilities, serverInfo); + } + if (route.messageKind === "request" && route.message.method === "tools/call" && product instanceof McpServer) { + const callParams = route.message.params; + const toolName = typeof callParams?.name === "string" ? callParams.name : void 0; + const inputSchema = toolName === void 0 ? void 0 : product.toolInputSchemaJson(toolName); + if (inputSchema !== void 0) { + const scan = scanXMcpHeaderDeclarations(inputSchema); + if (scan.valid && scan.declarations.length > 0) { + const rejection = validateMcpParamHeaders(scan.declarations, callParams?.arguments, request.headers); + if (rejection !== void 0) { + product.close().catch(reportError); + reportError(/* @__PURE__ */ new Error(`Rejected inbound request (${rejection.cell}): ${rejection.message}`)); + return rejectionResponse(rejection, route.message.id); + } + } + } + } + setNegotiatedProtocolVersion(server, claimedRevision); + installModernOnlyHandlers(server, SUPPORTED_MODERN_PROTOCOL_VERSIONS); + if (meta !== void 0) seedClientIdentityFromEnvelope(server, { + clientInfo: meta[CLIENT_INFO_META_KEY], + clientCapabilities: declaredClientCapabilities + }); + const previousOnClose = server.onclose; + inflight.add(server); + server.onclose = () => { + inflight.delete(server); + previousOnClose?.(); + }; + try { + const response = await invoke(product, route.message, { + classification: route.classification, + request, + ...authInfo !== void 0 && { authInfo }, + ...responseMode !== void 0 && { responseMode }, + ...options.keepAliveMs !== void 0 && { keepAliveMs: options.keepAliveMs } + }); + if (route.messageKind === "notification") queueMicrotask(() => void server.close().catch(() => {})); + return response; + } catch (error) { + if (error instanceof SdkError && error.code === SdkErrorCode.ConnectionClosed) return new Response(null, { status: 499 }); + await server.close().catch(() => {}); + inflight.delete(server); + reportError(toError(error)); + return internalServerErrorResponse(echoableRequestId(route.message)); + } + } + async function serveLegacyRoute(route, forwardRequest, authInfo, parsedBody) { + if (legacyHandler !== void 0) return legacyHandler(forwardRequest, { + ...authInfo !== void 0 && { authInfo }, + ...parsedBody !== void 0 && { parsedBody } + }); + const strict = modernOnlyStrictRejection(route, SUPPORTED_MODERN_PROTOCOL_VERSIONS); + if (strict === void 0) return new Response(null, { status: 202 }); + reportError(/* @__PURE__ */ new Error(`Rejected 2025-era request on a modern-only endpoint (${strict.cell}): ${strict.message}`)); + return rejectionResponse(strict, echoableRequestId(parsedBody)); + } + async function handle(request, requestOptions) { + const authInfo = requestOptions?.authInfo; + if (request.method.toUpperCase() === "POST" && !isJsonContentType(request.headers.get("content-type"))) { + reportError(/* @__PURE__ */ new Error("Unsupported Media Type: Content-Type must be application/json")); + return jsonRpcErrorResponse(415, -32e3, "Unsupported Media Type: Content-Type must be application/json"); + } + const classified = await classifyEntryRequest(request, requestOptions?.parsedBody); + if (classified.step === "unreadable-body") return jsonRpcErrorResponse(400, -32700, "Parse error: the request body could not be read"); + if (classified.step === "no-json-body") { + if (legacyHandler !== void 0) return legacyHandler(classified.forwardRequest, { ...authInfo !== void 0 && { authInfo } }); + return jsonRpcErrorResponse(400, -32700, "Parse error: the request body is not valid JSON"); + } + const { outcome, body, parsedBody, forwardRequest } = classified; + try { + switch (outcome.kind) { + case "reject": + reportError(/* @__PURE__ */ new Error(`Rejected inbound request (${outcome.cell}): ${outcome.message}`)); + return rejectionResponse(outcome, echoableRequestId(body)); + case "modern": return await serveModern(outcome, request, authInfo); + case "legacy": return await serveLegacyRoute(outcome, forwardRequest, authInfo, parsedBody); + } + } catch (error) { + reportError(toError(error)); + return internalServerErrorResponse(echoableRequestId(body)); + } + } + const fetchFace = async (request, requestOptions) => { + if (closed) throw new Error("This MCP handler has been closed"); + try { + return await handle(request, requestOptions); + } catch (error) { + reportError(toError(error)); + return internalServerErrorResponse(echoableRequestId(requestOptions?.parsedBody)); + } + }; + return { + fetch: fetchFace, + notify, + bus, + close: async () => { + closed = true; + listenRouter.closeAll(); + const closing = [...inflight].map((server) => server.close().catch(() => {})); + inflight.clear(); + await Promise.all(closing); + } + }; +} + +//#endregion +//#region src/server/middleware/bearerAuth.ts +function headerQuotedValue(value) { + return value.replaceAll(/[\\"]/g, String.raw`\$&`).replaceAll(/[^\u0020-\u007E]/g, " "); +} +function buildWwwAuthenticateHeader(errorCode, description, requiredScopes, resourceMetadataUrl) { + let header = `Bearer error="${headerQuotedValue(errorCode)}", error_description="${headerQuotedValue(description)}"`; + if (requiredScopes.length > 0) header += `, scope="${requiredScopes.join(" ")}"`; + if (resourceMetadataUrl) header += `, resource_metadata="${resourceMetadataUrl}"`; + return header; +} +/** +* Validate a raw `Authorization` header value as a Bearer token and return +* the verified {@link AuthInfo}. +* +* The runtime-neutral core of Bearer authentication: it parses the header, +* runs the verifier, enforces `requiredScopes`, and rejects tokens without an +* expiration or past it. On any failure it throws an {@link OAuthError} — +* pass that to {@link bearerAuthChallengeResponse} for the matching HTTP +* answer, or use {@link requireBearerAuth} to get both steps as one call. +* +* Framework adapters build on this: `requireBearerAuth` from +* `@modelcontextprotocol/express` feeds it `req.headers.authorization`. +*/ +async function verifyBearerToken(authorizationHeader, options) { + const { verifier, requiredScopes = [] } = options; + if (!authorizationHeader) throw new OAuthError(OAuthErrorCode.InvalidToken, "Missing Authorization header"); + const [type, token] = authorizationHeader.split(" "); + if (type?.toLowerCase() !== "bearer" || !token) throw new OAuthError(OAuthErrorCode.InvalidToken, "Invalid Authorization header format, expected 'Bearer TOKEN'"); + const authInfo = await verifier.verifyAccessToken(token); + if (requiredScopes.length > 0) { + if (!requiredScopes.every((scope) => authInfo.scopes.includes(scope))) throw new OAuthError(OAuthErrorCode.InsufficientScope, "Insufficient scope"); + } + if (typeof authInfo.expiresAt !== "number" || Number.isNaN(authInfo.expiresAt)) throw new OAuthError(OAuthErrorCode.InvalidToken, "Token has no expiration time"); + else if (authInfo.expiresAt < Date.now() / 1e3) throw new OAuthError(OAuthErrorCode.InvalidToken, "Token has expired"); + return authInfo; +} +/** +* Build the HTTP answer for a Bearer authentication failure. +* +* Maps an {@link OAuthError} to its status — `401` for `invalid_token` and +* `403` for `insufficient_scope` (both carrying the `WWW-Authenticate: Bearer …` +* challenge, with `resource_metadata` when configured so clients can discover +* the Authorization Server), `500` for `server_error`, `400` for anything +* else. A non-`OAuthError` value answers `500 server_error`. The body is the +* OAuth error JSON. +*/ +function bearerAuthChallengeResponse(error, options) { + const { requiredScopes = [], resourceMetadataUrl } = options ?? {}; + if (!(error instanceof OAuthError)) { + const serverError = new OAuthError(OAuthErrorCode.ServerError, "Internal Server Error"); + return Response.json(serverError.toResponseObject(), { status: 500 }); + } + switch (error.code) { + case OAuthErrorCode.InvalidToken: { + const challenge = buildWwwAuthenticateHeader(error.code, error.message, requiredScopes, resourceMetadataUrl); + return Response.json(error.toResponseObject(), { + status: 401, + headers: { "WWW-Authenticate": challenge } + }); + } + case OAuthErrorCode.InsufficientScope: { + const challenge = buildWwwAuthenticateHeader(error.code, error.message, requiredScopes, resourceMetadataUrl); + return Response.json(error.toResponseObject(), { + status: 403, + headers: { "WWW-Authenticate": challenge } + }); + } + case OAuthErrorCode.ServerError: return Response.json(error.toResponseObject(), { status: 500 }); + default: return Response.json(error.toResponseObject(), { status: 400 }); + } +} +/** +* Require a valid Bearer token on web-standard requests. +* +* The framework-free counterpart of `requireBearerAuth` from +* `@modelcontextprotocol/express`, for hosts whose HTTP surface is a +* `fetch(request)` handler — Cloudflare Workers, Deno, Bun, Hono. The +* returned gate resolves to the verified {@link AuthInfo}, or to the +* ready-to-return challenge `Response` when the request must be refused. +* +* @example +* ```ts source="./bearerAuth.examples.ts#requireBearerAuth_fetchGate" +* const gate = requireBearerAuth({ verifier, requiredScopes: ['mcp'] }); +* +* async function fetchHandler(request: Request): Promise { +* const auth: AuthInfo | Response = await gate(request); +* if (auth instanceof Response) return auth; +* return handler.fetch(request, { authInfo: auth }); +* } +* ``` +*/ +function requireBearerAuth(options) { + const { verifier, requiredScopes = [], resourceMetadataUrl } = options; + const resolved = { + verifier, + requiredScopes, + resourceMetadataUrl + }; + return async (request) => { + const [authorizationHeader] = (request.headers.get("authorization") ?? "").split(","); + try { + return await verifyBearerToken(authorizationHeader || void 0, resolved); + } catch (error) { + return bearerAuthChallengeResponse(error, resolved); + } + }; +} + +//#endregion +//#region src/server/middleware/hostHeaderValidation.ts +/** +* Parse and validate a `Host` header against an allowlist of hostnames (port-agnostic). +* +* - Input host header may include a port (e.g. `localhost:3000`) or IPv6 brackets (e.g. `[::1]:3000`). +* - Allowlist items should be hostnames only (no ports). For IPv6, include brackets (e.g. `[::1]`). +*/ +function validateHostHeader(hostHeader, allowedHostnames) { + if (!hostHeader) return { + ok: false, + errorCode: "missing_host", + message: "Missing Host header" + }; + let hostname; + try { + hostname = new URL(`http://${hostHeader}`).hostname; + } catch { + return { + ok: false, + errorCode: "invalid_host_header", + message: `Invalid Host header: ${hostHeader}`, + hostHeader + }; + } + if (!allowedHostnames.includes(hostname)) return { + ok: false, + errorCode: "invalid_host", + message: `Invalid Host: ${hostname}`, + hostHeader, + hostname + }; + return { + ok: true, + hostname + }; +} +/** +* Convenience allowlist for `localhost` DNS rebinding protection. +*/ +function localhostAllowedHostnames() { + return [ + "localhost", + "127.0.0.1", + "[::1]" + ]; +} +/** +* Web-standard `Request` helper for DNS rebinding protection. +* @example +* ```ts source="./hostHeaderValidation.examples.ts#hostHeaderValidationResponse_basicUsage" +* const result = validateHostHeader(req.headers.get('host'), ['localhost']); +* ``` +*/ +function hostHeaderValidationResponse(req, allowedHostnames) { + const result = validateHostHeader(req.headers.get("host"), allowedHostnames); + if (result.ok) return void 0; + return Response.json({ + jsonrpc: "2.0", + error: { + code: -32e3, + message: result.message + }, + id: null + }, { + status: 403, + headers: { "Content-Type": "application/json" } + }); +} + +//#endregion +//#region src/server/middleware/oauthMetadata.ts +function checkIssuerUrl(issuer, allowInsecure) { + if (issuer.protocol !== "https:" && issuer.hostname !== "localhost" && issuer.hostname !== "127.0.0.1" && !allowInsecure) throw new Error("Issuer URL must be HTTPS"); + if (issuer.hash) throw new Error(`Issuer URL must not have a fragment: ${issuer}`); + if (issuer.search) throw new Error(`Issuer URL must not have a query string: ${issuer}`); +} +/** +* Derive the RFC 9728 Protected Resource Metadata document from +* {@link AuthMetadataOptions}, validating the Authorization Server issuer URL +* (HTTPS required outside localhost) in the process. +* +* `oauthMetadataResponse` and the Express `mcpAuthMetadataRouter` both build +* on this; use it directly when serving the document through your own +* routing — or call it once at startup to fail fast on a misconfigured +* issuer before any request arrives. +*/ +function buildOAuthProtectedResourceMetadata(options) { + checkIssuerUrl(new URL(options.oauthMetadata.issuer), options.dangerouslyAllowInsecureIssuerUrl); + return { + resource: options.resourceServerUrl.href, + authorization_servers: [options.oauthMetadata.issuer], + scopes_supported: options.scopesSupported, + resource_name: options.resourceName, + resource_documentation: options.serviceDocumentationUrl?.href + }; +} +/** +* Builds the RFC 9728 Protected Resource Metadata URL for a given MCP server +* URL by inserting `/.well-known/oauth-protected-resource` ahead of the path. +* +* @example +* ```ts +* getOAuthProtectedResourceMetadataUrl(new URL('https://api.example.com/mcp')) +* // → 'https://api.example.com/.well-known/oauth-protected-resource/mcp' +* ``` +*/ +function getOAuthProtectedResourceMetadataUrl(serverUrl) { + return new URL(protectedResourceMetadataPath(serverUrl), serverUrl).href; +} +/** The RFC 9728 path-aware well-known path for a resource URL. */ +function protectedResourceMetadataPath(resourceServerUrl) { + const rsPath = stripTrailingSlash(resourceServerUrl.pathname); + return `/.well-known/oauth-protected-resource${rsPath === "/" ? "" : rsPath}`; +} +function stripTrailingSlash(path) { + return path.length > 1 && path.endsWith("/") ? path.slice(0, -1) : path; +} +const ALLOWED_METHODS = "GET, HEAD, OPTIONS"; +function metadataDocumentResponse(request, metadata) { + if (request.method === "OPTIONS") { + const requestedHeaders = request.headers.get("access-control-request-headers"); + return new Response(null, { + status: 204, + headers: { + "Access-Control-Allow-Origin": "*", + "Access-Control-Allow-Methods": ALLOWED_METHODS, + ...requestedHeaders === null ? {} : { + "Access-Control-Allow-Headers": requestedHeaders, + Vary: "Access-Control-Request-Headers" + } + } + }); + } + if (request.method !== "GET" && request.method !== "HEAD") { + const error = new OAuthError(OAuthErrorCode.MethodNotAllowed, `The method ${request.method} is not allowed for this endpoint`); + return Response.json(error.toResponseObject(), { + status: 405, + headers: { + Allow: ALLOWED_METHODS, + "Access-Control-Allow-Origin": "*" + } + }); + } + const response = Response.json(metadata, { headers: { "Access-Control-Allow-Origin": "*" } }); + return request.method === "HEAD" ? new Response(null, { + status: response.status, + headers: response.headers + }) : response; +} +/** +* Serve the two OAuth discovery documents an MCP server acting as a Resource +* Server exposes, from a web-standard `fetch(request)` handler: +* +* - `/.well-known/oauth-protected-resource[/]` — RFC 9728 Protected +* Resource Metadata, derived from the supplied options (path-aware: the +* resource URL's path is reflected in the route). +* - `/.well-known/oauth-authorization-server` — RFC 8414 Authorization +* Server Metadata, passed through verbatim. +* +* Returns the matched document `Response` (JSON with permissive CORS, `405` +* with an `Allow` header for non-GET methods, `204` for CORS preflight), or +* `undefined` when the request path is neither well-known route — fall +* through to your own routing. The framework-free counterpart of +* `mcpAuthMetadataRouter` from `@modelcontextprotocol/express`; pair it with +* `requireBearerAuth` and `getOAuthProtectedResourceMetadataUrl` so +* unauthenticated clients can discover the AS from the `401` challenge. +* +* @example +* ```ts source="./oauthMetadata.examples.ts#oauthMetadataResponse_fetchHandler" +* async function fetchHandler(request: Request): Promise { +* return oauthMetadataResponse(request, options) ?? serveMcp(request); +* } +* ``` +*/ +function oauthMetadataResponse(request, options) { + const requestPath = stripTrailingSlash(new URL(request.url).pathname); + if (requestPath === protectedResourceMetadataPath(options.resourceServerUrl)) return metadataDocumentResponse(request, buildOAuthProtectedResourceMetadata(options)); + if (requestPath === "/.well-known/oauth-authorization-server") { + buildOAuthProtectedResourceMetadata(options); + return metadataDocumentResponse(request, options.oauthMetadata); + } +} + +//#endregion +//#region src/server/middleware/originValidation.ts +/** +* Validate an `Origin` header against an allowlist of hostnames (port-agnostic). +* +* - A missing/empty `Origin` header passes: non-browser clients do not send one, +* and only browser-originated requests carry the header this check defends against. +* - Allowlist items are hostnames only (no scheme, no port), the same convention as +* `validateHostHeader`. For IPv6, include brackets (e.g. `[::1]`). +* - Any present value that cannot be parsed as an origin URL — including the literal +* `null` origin browsers send for opaque contexts — is rejected (deny on failure). +*/ +function validateOriginHeader(originHeader, allowedOriginHostnames) { + if (originHeader === null || originHeader === void 0 || originHeader === "") return { ok: true }; + let hostname; + try { + hostname = new URL(originHeader).hostname; + } catch { + return { + ok: false, + errorCode: "invalid_origin_header", + message: `Invalid Origin header: ${originHeader}`, + originHeader + }; + } + if (hostname === "") return { + ok: false, + errorCode: "invalid_origin_header", + message: `Invalid Origin header: ${originHeader}`, + originHeader + }; + if (!allowedOriginHostnames.includes(hostname)) return { + ok: false, + errorCode: "invalid_origin", + message: `Invalid Origin: ${hostname}`, + originHeader, + hostname + }; + return { + ok: true, + origin: originHeader, + hostname + }; +} +/** +* Convenience allowlist of localhost-class origin hostnames, mirroring +* `localhostAllowedHostnames`. +*/ +function localhostAllowedOrigins() { + return [ + "localhost", + "127.0.0.1", + "[::1]" + ]; +} +/** +* Web-standard `Request` helper for Origin validation: returns a `403` JSON-RPC +* error response when the request's `Origin` header is not allowed, and +* `undefined` when the request may proceed. +* +* ```ts +* const rejected = originValidationResponse(request, localhostAllowedOrigins()); +* if (rejected) return rejected; +* ``` +*/ +function originValidationResponse(req, allowedOriginHostnames) { + const result = validateOriginHeader(req.headers.get("origin"), allowedOriginHostnames); + if (result.ok) return void 0; + return Response.json({ + jsonrpc: "2.0", + error: { + code: -32e3, + message: result.message + }, + id: null + }, { + status: 403, + headers: { "Content-Type": "application/json" } + }); +} + +//#endregion +//#region src/server/requestStateCodec.ts +const PREFIX = "v1."; +function bytesToBase64Url(bytes) { + let bin = ""; + for (const b of bytes) bin += String.fromCodePoint(b); + return btoa(bin).replaceAll("+", "-").replaceAll("/", "_").replace(/=+$/, ""); +} +function constantTimeTagEqual(a, b) { + if (a.length !== b.length) return false; + let r = 0; + for (let i = 0; i < a.length; i++) r |= a.codePointAt(i) ^ b.codePointAt(i); + return r === 0; +} +function base64UrlToBytes(s) { + const b64 = s.replaceAll("-", "+").replaceAll("_", "/"); + const bin = atob(b64); + const bytes = new Uint8Array(bin.length); + for (let i = 0; i < bin.length; i++) bytes[i] = bin.codePointAt(i); + return bytes; +} +/** +* Create an opt-in HMAC-SHA256 codec for the multi-round-trip `requestState` +* (protocol revision 2026-07-28). +* +* `requestState` round-trips through the client and is attacker-controlled +* input on re-entry. The SDK applies no protection of its own; this helper is +* the convenience implementation of the spec's integrity MUST so authors don't +* hand-roll HMAC. Wire shape: +* +* "v1." b64url({"p":,"exp":,"b":?}) "." b64url(mac) +* +* where `bindTag` is `b64url(HMAC(key, "mcp.requestState.bind:" + bind(ctx))[:16])` +* — the binding value is never embedded raw. +* +* The codec is **signed, not encrypted**: the body is integrity-protected but +* the client can base64url-decode it and read the payload (`p`) in clear. Do +* not put secrets in the payload; use an AEAD construction if confidentiality +* is required. The handler reads its payload back via the typed +* `ctx.mcpReq.requestState()` accessor — the seam has already run `verify` +* (integrity proven, payload decoded) by the time the handler is entered. +* +* Verification is fail-closed and constant-time (WebCrypto `subtle.verify` for +* the body MAC; a fixed-length XOR-accumulator compare for the bind tag). +* See `examples/mrtr/server.ts` for a worked end-to-end example. +* +* Design comparison (mcp.d `secureRequestState`, the peer SDK's reference +* implementation): mcp.d additionally offers an AES-256-GCM encrypted mode and +* derives independent cipher / bind-HMAC sub-keys from the operator secret via +* HKDF-SHA256, with an auto-generated per-process ephemeral key when none is +* supplied. This codec deliberately ships only the signed mode and a single +* keyed HMAC (domain-separated by input prefix) — HKDF sub-key derivation and +* an encrypted mode are intentionally out of scope for the initial release. +*/ +function createRequestStateCodec(options) { + const subtle = globalThis.crypto?.subtle; + if (subtle === void 0) throw new TypeError("createRequestStateCodec requires the Web Crypto API (globalThis.crypto.subtle); see https://ts.sdk.modelcontextprotocol.io/v2/troubleshooting for the Node.js polyfill instructions"); + const keyBytes = typeof options.key === "string" ? new TextEncoder().encode(options.key) : Uint8Array.from(options.key); + if (keyBytes.byteLength < 32) throw new RangeError(`createRequestStateCodec: key must be at least 32 bytes (got ${keyBytes.byteLength})`); + const ttlSeconds = options.ttlSeconds ?? 600; + if (!Number.isFinite(ttlSeconds)) throw new RangeError("createRequestStateCodec: ttlSeconds must be a finite number"); + const bind = options.bind; + let cryptoKey; + const importedKey = () => cryptoKey ??= subtle.importKey("raw", keyBytes, { + name: "HMAC", + hash: "SHA-256" + }, false, ["sign", "verify"]); + const utf8 = new TextEncoder(); + const BIND_LABEL = "mcp.requestState.bind:"; + const bindTag = async (value) => { + return bytesToBase64Url(new Uint8Array(await subtle.sign("HMAC", await importedKey(), utf8.encode(BIND_LABEL + value))).slice(0, 16)); + }; + return { + async mint(payload, ctx) { + const envelope = { + p: payload, + exp: Math.floor(Date.now() / 1e3) + ttlSeconds + }; + if (bind !== void 0) { + if (ctx === void 0) throw new TypeError("createRequestStateCodec: mint() requires ctx when a bind callback is configured"); + envelope.b = await bindTag(bind(ctx)); + } + const body = bytesToBase64Url(utf8.encode(JSON.stringify(envelope))); + return `${PREFIX}${body}.${bytesToBase64Url(new Uint8Array(await subtle.sign("HMAC", await importedKey(), utf8.encode(PREFIX + body))))}`; + }, + async verify(state, ctx) { + const dot = state.lastIndexOf("."); + if (!state.startsWith(PREFIX) || dot <= 3) throw new Error("malformed"); + const body = state.slice(3, dot); + let macBytes; + try { + macBytes = base64UrlToBytes(state.slice(dot + 1)); + } catch { + throw new Error("malformed"); + } + if (!await subtle.verify("HMAC", await importedKey(), macBytes, utf8.encode(PREFIX + body))) throw new Error("mac"); + let envelope; + try { + envelope = JSON.parse(new TextDecoder("utf-8", { fatal: true }).decode(base64UrlToBytes(body))); + } catch { + throw new Error("malformed"); + } + if (typeof envelope.exp !== "number" || envelope.exp < Math.floor(Date.now() / 1e3)) throw new Error("expired"); + if (bind !== void 0) { + const expected = await bindTag(bind(ctx)); + if (envelope.b === void 0 || !constantTimeTagEqual(envelope.b, expected)) throw new Error("bind"); + } else if (envelope.b !== void 0) throw new Error("bind"); + return envelope.p; + } + }; +} + +//#endregion +//#region src/fromJsonSchema.ts +let _defaultValidator; +function dist_fromJsonSchema(schema, validator) { + return fromJsonSchema$1(schema, validator ?? (_defaultValidator ??= new DefaultJsonSchemaValidator())); +} + +//#endregion + +//# sourceMappingURL=index.mjs.map +const mcpApps = Object.freeze([]); + +/* export default */ const mcp_status_073c1634_0 = (mcpApps); + +// Generated by agent-bundle. Do not edit. +const meta_name = "mcp-app-example"; +const packageName = "@agent-bundle-example/mcp-app"; +const packageVersion = undefined; +const meta_version = "1.0.0"; +const meta_meta = Object.freeze({ + name: meta_name, + packageName: packageName, + packageVersion: packageVersion, + version: meta_version +}); +/* export default */ const _agent_bundle_virtual_meta = ((/* unused pure expression or super */ null && (meta_meta))); + +const healthyCompilerStatus = Object.freeze({ + checks: Object.freeze([ + Object.freeze({ + label: 'Availability', + status: 'passing' + }), + Object.freeze({ + label: 'Build queue', + status: 'passing' + }) + ]), + service: 'compiler', + status: 'healthy', + summary: 'Compiler service is ready for release.' +}); +const isRecord = (value)=>value !== null && typeof value === 'object' && !Array.isArray(value); +const isHealthyCompilerFixture = (value)=>{ + if (!isRecord(value) || value.service !== healthyCompilerStatus.service || value.status !== healthyCompilerStatus.status || value.summary !== healthyCompilerStatus.summary || !Array.isArray(value.checks) || value.checks.length !== healthyCompilerStatus.checks.length) { + return false; + } + return healthyCompilerStatus.checks.every((expected, index)=>{ + const received = value.checks[index]; + return isRecord(received) && received.label === expected.label && received.status === expected.status; + }); +}; + + + + + + +const app = mcp_status_073c1634_0["0"]; +if (app === undefined) throw new Error('Expected the status MCP App.'); +const serviceCatalog = Object.freeze({ + compiler: healthyCompilerStatus, + 'payments-api': Object.freeze({ + checks: Object.freeze([ + Object.freeze({ + label: 'Availability', + status: 'passing' + }), + Object.freeze({ + label: 'P95 latency', + status: 'failing' + }) + ]), + service: 'payments-api', + status: 'degraded', + summary: 'Payment latency is above the release threshold.' + }) +}); +const createStatusServer = ()=>{ + // The compiler stamps this project's identity into `agent-bundle/meta`, so + // the wire identity cannot drift from the config or package.json. + const server = new mcp_DXXb3Vv3_McpServer({ + name: meta_name, + version: (/* inlined export .version */"1.0.0") + }); + server.registerResource(app.name, app.resourceUri, { + _meta: { + ui: { + resourceUri: app.resourceUri + } + }, + mimeType: app.mimeType + }, async (uri)=>({ + contents: [ + { + mimeType: app.mimeType, + text: app.html, + uri: uri.href + } + ] + })); + server.registerTool('show-status', { + _meta: { + ui: { + resourceUri: app.resourceUri + } + }, + description: 'Show the health of one example service.', + inputSchema: schemas_object({ + service: schemas_enum([ + 'compiler', + 'payments-api' + ]) + }) + }, async ({ service })=>{ + const result = serviceCatalog[service]; + return { + _meta: { + ui: { + resourceUri: app.resourceUri + } + }, + content: [ + { + text: result.summary, + type: 'text' + } + ], + structuredContent: result + }; + }); + return server; +}; +/** + * Default-exported server factory: `agent-bundle build` detects it and wraps + * this entry in the framework stdio lifecycle shell (console-to-stderr guard, + * SIGINT/SIGTERM handling, stdin-EOF exit, bounded shutdown, heartbeat). + */ /* export default */ const mcp_status = (createStatusServer); + + + + + +//#region src/server/stdio.ts +/** +* Server transport for stdio: this communicates with an MCP client by reading from the current process' `stdin` and writing to `stdout`. +* +* This transport is only available in Node.js environments. +* +* @example +* ```ts source="./stdio.examples.ts#StdioServerTransport_basicUsage" +* const server = new McpServer({ name: 'my-server', version: '1.0.0' }); +* const transport = new StdioServerTransport(); +* await server.connect(transport); +* ``` +*/ +var stdio_StdioServerTransport = class { + _readBuffer; + _started = false; + _closed = false; + constructor(_stdin = node_process.stdin, _stdout = node_process.stdout, options) { + this._stdin = _stdin; + this._stdout = _stdout; + this._readBuffer = new ReadBuffer({ maxBufferSize: options?.maxBufferSize }); + } + onclose; + onerror; + onmessage; + _ondata = (chunk) => { + try { + this._readBuffer.append(chunk); + this.processReadBuffer(); + } catch (error) { + this.onerror?.(error); + this.close().catch(() => {}); + } + }; + _onerror = (error) => { + this.onerror?.(error); + }; + _onstdouterror = (error) => { + this.onerror?.(error); + this.close().catch(() => {}); + }; + /** + * Starts listening for messages on `stdin`. + */ + async start() { + if (this._started) throw new Error("StdioServerTransport already started! If using Server class, note that connect() calls start() automatically."); + this._started = true; + this._stdin.on("data", this._ondata); + this._stdin.on("error", this._onerror); + this._stdout.on("error", this._onstdouterror); + } + processReadBuffer() { + while (true) try { + const message = this._readBuffer.readMessage(); + if (message === null) break; + this.onmessage?.(message); + } catch (error) { + this.onerror?.(error); + } + } + async close() { + if (this._closed) return; + this._closed = true; + this._stdin.off("data", this._ondata); + this._stdin.off("error", this._onerror); + this._stdout.off("error", this._onstdouterror); + if (this._stdin.listenerCount("data") === 0) this._stdin.pause(); + this._readBuffer.clear(); + this.onclose?.(); + } + send(message) { + if (this._closed) return Promise.reject(/* @__PURE__ */ new Error("StdioServerTransport is closed")); + return new Promise((resolve, reject) => { + const json = serializeMessage(message); + let settled = false; + const onError = (error) => { + if (settled) return; + settled = true; + this._stdout.off("error", onError); + this._stdout.off("drain", onDrain); + reject(error); + }; + const onDrain = () => { + if (settled) return; + settled = true; + this._stdout.off("error", onError); + this._stdout.off("drain", onDrain); + resolve(); + }; + this._stdout.once("error", onError); + if (this._stdout.write(json)) { + if (settled) return; + settled = true; + this._stdout.off("error", onError); + resolve(); + } else if (!settled) this._stdout.once("drain", onDrain); + }); + } +}; + +//#endregion +//#region src/server/serveStdio.ts +/** +* How long the probe-discard path waits for the probe instance to answer the +* requests it was delivered before closing it. The wait normally settles as +* soon as the DiscoverResult is handed to the wire (or immediately, when a +* delivered cancellation already settled the probe); the bound is a backstop +* so no edge can ever hold the connection's inbound pump indefinitely behind +* the discard. +*/ +const DISCARD_ANSWER_TIMEOUT_MS = 3e3; +/** +* The transport a pinned instance is connected to: a thin channel that writes +* through to the entry-owned wire transport and receives the messages the +* entry forwards. The wire transport itself is never handed to an instance — +* that is what lets the entry discard an optimistic probe instance (close the +* channel) without tearing down the connection. +*/ +var StdioConnectionChannel = class { + onclose; + onerror; + onmessage; + _closed = false; + /** Request ids the entry delivered to the instance that the instance has not yet answered. */ + _pendingRequests = /* @__PURE__ */ new Set(); + _drainWaiters = []; + constructor(_wire, _onInstanceClose, _outboundIntercept) { + this._wire = _wire; + this._onInstanceClose = _onInstanceClose; + this._outboundIntercept = _outboundIntercept; + } + async start() {} + async send(message, options) { + if (isJSONRPCResultResponse(message) || isJSONRPCErrorResponse(message)) { + const { id } = message; + if (id !== void 0) this._settle(id); + } + if (this._closed) return; + if (this._outboundIntercept?.(message) === "handled") return; + return this._wire.send(message, options); + } + setProtocolVersion = (version) => { + this._wire.setProtocolVersion?.(version); + }; + /** Forwards one inbound message to the connected instance. */ + deliver(message, extra) { + if (this._closed) return; + if (isJSONRPCRequest(message)) this._pendingRequests.add(message.id); + else if (isJSONRPCNotification(message) && message.method === "notifications/cancelled") { + const cancelledId = message.params?.requestId; + if (cancelledId !== void 0) this._settle(cancelledId); + } + this.onmessage?.(message, extra); + } + /** + * Resolves once every request delivered to the instance has been answered + * through {@linkcode send}, settled by a delivered cancellation, or the + * channel has been closed and nothing further can be answered. The wait is + * bounded by `timeoutMs` as a backstop so no edge can hold the caller + * indefinitely; resolves `false` only when the bound elapsed with requests + * still unanswered. Used by the probe-discard path so a probe request the + * entry accepted is never silently dropped. + */ + async whenRequestsAnswered(timeoutMs) { + if (this._closed || this._pendingRequests.size === 0) return true; + return await new Promise((resolve) => { + const waiter = () => { + clearTimeout(timer); + resolve(true); + }; + const timer = setTimeout(() => { + this._drainWaiters = this._drainWaiters.filter((pending) => pending !== waiter); + resolve(false); + }, timeoutMs); + this._drainWaiters.push(waiter); + }); + } + async close() { + if (this._closed) return; + this._closed = true; + this._pendingRequests.clear(); + this._releaseDrainWaiters(); + try { + this._onInstanceClose(); + } finally { + this.onclose?.(); + } + } + _settle(id) { + this._pendingRequests.delete(id); + if (this._pendingRequests.size === 0) this._releaseDrainWaiters(); + } + _releaseDrainWaiters() { + const waiters = this._drainWaiters; + this._drainWaiters = []; + for (const waiter of waiters) waiter(); + } +}; +/** +* Classifies one message of the opening exchange with the same body-primary +* rules the HTTP entry applies per request: `initialize` is the legacy +* handshake unless it carries a valid modern envelope claim; a present claim +* is validated (never silently ignored); a claim-less message is 2025-era +* traffic. There is no header layer on stdio, so the body is the only signal. +*/ +function classifyOpeningMessage(message) { + const params = message.params; + if (message.method === "initialize" && !carriesValidModernEnvelopeClaim(params)) { + const requestedVersion = params !== null && typeof params === "object" && typeof params.protocolVersion === "string" ? params.protocolVersion : void 0; + return { + kind: "legacy", + reason: "initialize", + ...requestedVersion !== void 0 && { requestedVersion } + }; + } + if (!hasEnvelopeClaim(params)) return { + kind: "legacy", + reason: "no-claim" + }; + const meta = requestMetaOf(params); + const firstIssue = (meta === void 0 ? [] : validateEnvelopeMeta(meta))[0]; + if (firstIssue !== void 0) return { + kind: "invalid-envelope", + issue: firstIssue + }; + const claimedVersion = envelopeClaimVersion(params); + if (claimedVersion === void 0 || !SUPPORTED_MODERN_PROTOCOL_VERSIONS.includes(claimedVersion)) return { + kind: "unsupported-revision", + requested: claimedVersion ?? "unknown" + }; + return { + kind: "modern", + revision: claimedVersion, + classification: { + era: "modern", + revision: claimedVersion + } + }; +} +/** +* Serves MCP over stdio from a server factory, owning the era decision for +* the connection: the opening exchange selects the era, ONE instance from the +* factory is pinned for the connection lifetime, and everything after passes +* straight through to it. See the module documentation for the opening rules. +* +* ```ts +* import { serveStdio } from '@modelcontextprotocol/server/stdio'; +* +* serveStdio(() => { +* const server = new McpServer({ name: 'my-server', version: '1.0.0' }, { capabilities: { tools: {} } }); +* // register tools/resources/prompts once — the same factory serves both eras +* return server; +* }); +* ``` +*/ +function serveStdio(factory, options = {}) { + const legacyMode = options.legacy ?? "serve"; + const wire = options.transport ?? new stdio_StdioServerTransport(); + let state = { phase: "opening" }; + /** Channel currently being discarded (its close must not tear the connection down). */ + let discarding; + let closing = false; + /** + * Whether the connection has been torn down (`handle.close()` or the wire + * closing). The opening arms re-check this after every await: a close can + * race factory construction, and the continuation must neither resurrect + * the connection state nor keep a late-resolved instance around. + */ + const isTornDown = () => closing || state.phase === "closed"; + const reportError = (error) => { + try { + options.onerror?.(error); + } catch {} + }; + const writeErrorResponse = (id, code, message, data) => wire.send({ + jsonrpc: "2.0", + id, + error: { + code, + message, + ...data !== void 0 && { data } + } + }).catch((error) => reportError(stdio_toError(error))); + /** + * Entry-handled `subscriptions/listen` for this connection: holds the + * active subscriptions, serves inbound listen / cancelled-of-listen + * before the pinned instance is consulted, and rewrites the instance's + * outbound change notifications onto the active subscriptions. Only + * consulted on a modern-pinned connection — on a legacy connection + * change notifications pass straight through (the 2025 unsolicited + * delivery model is unchanged). + */ + const listenRouter = new StdioListenRouter(options.maxSubscriptions ?? DEFAULT_MAX_SUBSCRIPTIONS); + /** Outbound intercept installed on a modern instance's channel. */ + const modernOutboundIntercept = (message) => { + if (!isJSONRPCNotification(message)) return void 0; + const routed = listenRouter.routeOutbound(message); + if (routed === "passthrough") return void 0; + for (const stamped of routed) wire.send({ + jsonrpc: "2.0", + ...stamped + }).catch((error) => reportError(stdio_toError(error))); + return "handled"; + }; + /** + * Entry-handled inbound listen routing for a modern-pinned connection. + * Returns `true` when the message was served at the entry and must NOT + * be delivered to the pinned instance. + */ + const tryServeListen = async (message) => { + if (isJSONRPCRequest(message) && message.method === "subscriptions/listen") { + const meta = requestMetaOf(message.params); + const issue = hasEnvelopeClaim(message.params) ? (meta === void 0 ? [] : validateEnvelopeMeta(meta))[0] : { + key: "_meta", + problem: "the per-request envelope is required on protocol revision 2026-07-28" + }; + const claimedVersion = envelopeClaimVersion(message.params); + let reply; + if (issue !== void 0) reply = { + jsonrpc: "2.0", + id: message.id, + error: { + code: -32602, + message: `Invalid _meta envelope: ${issue.key}: ${issue.problem}` + } + }; + else if (claimedVersion === void 0 || !SUPPORTED_MODERN_PROTOCOL_VERSIONS.includes(claimedVersion)) { + const error = new UnsupportedProtocolVersionError({ + supported: [...SUPPORTED_MODERN_PROTOCOL_VERSIONS], + requested: claimedVersion ?? "unknown" + }); + reply = { + jsonrpc: "2.0", + id: message.id, + error: { + code: error.code, + message: error.message, + data: error.data + } + }; + } else reply = listenRouter.serve(message); + await wire.send("error" in reply ? reply : { + jsonrpc: "2.0", + method: reply.method, + params: reply.params + }).catch((error) => reportError(stdio_toError(error))); + return true; + } + if (isJSONRPCNotification(message) && message.method === "notifications/cancelled") { + const cancelledId = message.params?.requestId; + if (cancelledId !== void 0 && listenRouter.cancel(cancelledId)) return true; + } + return false; + }; + /** Answers a 2025-era request the entry will not serve (the modern-only rejection cells). */ + const answerLegacyRejection = (request, reason, requestedVersion) => { + const rejection = modernOnlyStrictRejection({ + kind: "legacy", + reason, + ...requestedVersion !== void 0 && { requestedVersion } + }, SUPPORTED_MODERN_PROTOCOL_VERSIONS); + if (rejection === void 0) return Promise.resolve(); + reportError(/* @__PURE__ */ new Error(`Rejected 2025-era request on a modern-only stdio connection (${rejection.cell}): ${rejection.message}`)); + return writeErrorResponse(request.id, rejection.code, rejection.message, rejection.data); + }; + const onInstanceClosed = (channel) => { + if (closing || channel === discarding) return; + closeAll(); + }; + const connectInstance = async (era, revision) => { + const product = await factory({ era }); + const server = product instanceof McpServer ? product.server : product; + if (era === "modern") { + setNegotiatedProtocolVersion(server, revision); + installModernOnlyHandlers(server, SUPPORTED_MODERN_PROTOCOL_VERSIONS); + listenRouter.setServerCapabilities(server.getCapabilities(), serverIdentityOf(server)); + } + const channel = new StdioConnectionChannel(wire, () => onInstanceClosed(channel), era === "modern" ? modernOutboundIntercept : void 0); + await product.connect(channel); + return { + product, + channel + }; + }; + /** Closes an instance whose factory resolved only after the connection was torn down. */ + const disposeLateInstance = (instance) => instance.product.close().catch((error) => reportError(stdio_toError(error))); + const discardProbeInstance = async (instance) => { + discarding = instance.channel; + try { + if (!await instance.channel.whenRequestsAnswered(DISCARD_ANSWER_TIMEOUT_MS)) reportError(/* @__PURE__ */ new Error(`Discarded the probe instance with requests still unanswered after ${DISCARD_ANSWER_TIMEOUT_MS}ms; continuing with the fallback`)); + await instance.product.close(); + } catch (error) { + reportError(stdio_toError(error)); + } finally { + discarding = void 0; + } + }; + const processMessage = async (message) => { + if (state.phase === "closed") return; + if (state.phase === "pinned") { + if (state.era === "modern" && isJSONRPCRequest(message) && message.method === "initialize" && !carriesValidModernEnvelopeClaim(message.params)) { + await answerLegacyRejection(message, "initialize", message.params !== null && typeof message.params === "object" && typeof message.params.protocolVersion === "string" ? message.params.protocolVersion : void 0); + return; + } + if (state.era === "modern" && await tryServeListen(message)) return; + state.instance.channel.deliver(message); + return; + } + if (!isJSONRPCRequest(message) && !isJSONRPCNotification(message)) { + reportError(/* @__PURE__ */ new Error("Discarded a JSON-RPC response received before the connection negotiated an era")); + return; + } + const opening = classifyOpeningMessage(message); + switch (opening.kind) { + case "invalid-envelope": { + const detail = `Invalid _meta envelope for protocol revision 2026-07-28: ${opening.issue.key}: ${opening.issue.problem}`; + if (isJSONRPCRequest(message)) await writeErrorResponse(message.id, ProtocolErrorCode.InvalidParams, detail, { envelope: opening.issue }); + else reportError(/* @__PURE__ */ new Error(`Discarded a notification with a malformed envelope: ${detail}`)); + return; + } + case "unsupported-revision": + if (isJSONRPCRequest(message)) { + const error = new UnsupportedProtocolVersionError({ + supported: [...SUPPORTED_MODERN_PROTOCOL_VERSIONS], + requested: opening.requested + }); + reportError(error); + await writeErrorResponse(message.id, error.code, error.message, error.data); + } else reportError(/* @__PURE__ */ new Error(`Discarded a notification claiming unsupported protocol revision ${opening.requested}`)); + return; + case "modern": + if (isJSONRPCRequest(message) && message.method === "server/discover") { + if (state.phase === "probe") { + state.instance.channel.deliver(message, { classification: opening.classification }); + return; + } + const instance = await connectInstance("modern", opening.revision); + if (isTornDown()) { + await disposeLateInstance(instance); + return; + } + state = { + phase: "probe", + instance + }; + instance.channel.deliver(message, { classification: opening.classification }); + return; + } + if (state.phase === "probe") { + if (isJSONRPCNotification(message)) { + state.instance.channel.deliver(message, { classification: opening.classification }); + return; + } + state = { + phase: "pinned", + era: "modern", + instance: state.instance + }; + } else { + const instance = await connectInstance("modern", opening.revision); + if (isTornDown()) { + await disposeLateInstance(instance); + return; + } + state = { + phase: "pinned", + era: "modern", + instance + }; + } + if (await tryServeListen(message)) return; + state.instance.channel.deliver(message, { classification: opening.classification }); + return; + case "legacy": { + if (legacyMode === "reject") { + if (isJSONRPCRequest(message)) await answerLegacyRejection(message, opening.reason, opening.requestedVersion); + return; + } + if (state.phase === "probe") { + await discardProbeInstance(state.instance); + if (isTornDown()) return; + state = { phase: "opening" }; + } + const instance = await connectInstance("legacy"); + if (isTornDown()) { + await disposeLateInstance(instance); + return; + } + state = { + phase: "pinned", + era: "legacy", + instance + }; + state.instance.channel.deliver(message); + return; + } + } + }; + const queue = []; + let pumping = false; + const pump = async () => { + if (pumping) return; + pumping = true; + try { + while (queue.length > 0) { + const message = queue.shift(); + try { + await processMessage(message); + } catch (error) { + if (isJSONRPCRequest(message)) await writeErrorResponse(message.id, ProtocolErrorCode.InternalError, "Internal server error"); + reportError(stdio_toError(error)); + } + } + } finally { + pumping = false; + } + }; + const closeAll = async () => { + if (closing || state.phase === "closed") return; + closing = true; + const current = state; + state = { phase: "closed" }; + for (const result of listenRouter.teardownAll()) await wire.send(result).catch((error) => reportError(stdio_toError(error))); + if (current.phase === "probe" || current.phase === "pinned") await current.instance.product.close().catch((error) => reportError(stdio_toError(error))); + await wire.close().catch((error) => reportError(stdio_toError(error))); + }; + wire.onmessage = (message) => { + queue.push(message); + pump(); + }; + wire.onerror = (error) => { + reportError(error); + if (state.phase === "probe" || state.phase === "pinned") state.instance.channel.onerror?.(error); + }; + wire.onclose = () => { + if (closing || state.phase === "closed") return; + closing = true; + const current = state; + state = { phase: "closed" }; + if (current.phase === "probe" || current.phase === "pinned") current.instance.product.close().catch((error) => reportError(stdio_toError(error))); + }; + const started = wire.start().catch((error) => { + reportError(stdio_toError(error)); + throw error; + }); + started.catch(() => {}); + return { close: async () => { + await started.catch(() => {}); + await closeAll(); + } }; +} +function stdio_toError(value) { + return value instanceof Error ? value : new Error(String(value)); +} + +//#endregion + +//# sourceMappingURL=stdio.mjs.map +const defaultHeartbeatIntervalMs = 300000; +const defaultActivityThrottleMs = 60000; +const defaultShutdownTimeoutMs = 5000; +const defaultHeartbeatName = 'agent-bundle'; +const redirectConsoleToStderr = ()=>{ + const originalStdoutWrite = process.stdout.write.bind(process.stdout); + const stderrConsole = new console.Console({ + stderr: process.stderr, + stdout: process.stderr + }); + const methods = [ + 'debug', + 'dir', + 'error', + 'info', + 'log', + 'trace', + 'warn' + ]; + for (const method of methods)console[method] = stderrConsole[method].bind(stderrConsole); + process.stdout.write = (chunk, encoding, callback)=>process.stderr.write(chunk, encoding, callback); + return Object.freeze({ + restoreProtocolStdout: ()=>{ + process.stdout.write = originalStdoutWrite; + } + }); +}; +const createHeartbeat = ({ activityThrottleMs = defaultActivityThrottleMs, intervalMs = defaultHeartbeatIntervalMs, name = defaultHeartbeatName, writeLine })=>{ + const startedAt = Date.now(); + let lastActivityAt = startedAt; + let lastActivityLogAt = 0; + const log = (reason)=>{ + const uptimeSeconds = Math.round((Date.now() - startedAt) / 1000); + const idleSeconds = Math.round((Date.now() - lastActivityAt) / 1000); + writeLine(`[${name}] stdio heartbeat (${reason}) pid=${process.pid} uptime=${uptimeSeconds}s idle=${idleSeconds}s`); + }; + const timer = setInterval(()=>log('interval'), intervalMs); + timer.unref?.(); + return Object.freeze({ + log, + noteActivity: ()=>{ + lastActivityAt = Date.now(); + if (lastActivityAt - lastActivityLogAt >= activityThrottleMs) { + lastActivityLogAt = lastActivityAt; + log('activity'); + } + }, + stop: ()=>clearInterval(timer) + }); +}; +const runStdioServer = async ({ activityThrottleMs, exit = (code)=>process.exit(code), heartbeat: heartbeatEnabled = true, heartbeatIntervalMs, server, serverName, shutdownTimeoutMs = defaultShutdownTimeoutMs, signals = process, stdin = process.stdin, transport, writeLine = (line)=>void process.stderr.write(`${line}\n`) })=>{ + const heartbeat = createHeartbeat({ + ...void 0 === activityThrottleMs ? {} : { + activityThrottleMs + }, + ...void 0 === heartbeatIntervalMs ? {} : { + intervalMs: heartbeatIntervalMs + }, + ...void 0 === serverName ? {} : { + name: serverName + }, + writeLine: heartbeatEnabled ? writeLine : ()=>void 0 + }); + const keepalive = setInterval(()=>void 0, 60000); + keepalive.unref?.(); + let shuttingDown = false; + const shutdown = async (exitCode = 0)=>{ + if (shuttingDown) return; + shuttingDown = true; + signals.off('SIGINT', handleSigint); + signals.off('SIGTERM', handleSigterm); + stdin.off?.('end', handleStdinEnd); + clearInterval(keepalive); + heartbeat.stop(); + await Promise.race([ + Promise.allSettled([ + Promise.resolve().then(()=>transport.close()), + Promise.resolve().then(()=>server.close()) + ]), + new Promise((resolve)=>setTimeout(resolve, shutdownTimeoutMs)) + ]); + exit(exitCode); + }; + const handleSigint = ()=>{ + shutdown(130); + }; + const handleSigterm = ()=>{ + shutdown(143); + }; + const handleStdinEnd = ()=>{ + shutdown(0); + }; + signals.on('SIGINT', handleSigint); + signals.on('SIGTERM', handleSigterm); + stdin.once?.('end', handleStdinEnd); + transport.onclose = ()=>{ + shutdown(0); + }; + await server.connect(transport); + const originalOnMessage = transport.onmessage; + transport.onmessage = (message, extra)=>{ + heartbeat.noteActivity(); + originalOnMessage?.(message, extra); + }; + return Object.freeze({ + heartbeat, + shutdown + }); +}; +const runGeneratedStdioMcpEntry = async (options)=>{ + const guard = redirectConsoleToStderr(); + const entry = await options.loadEntry(); + const factory = entry.default; + if ('function' != typeof factory) throw new TypeError(`Generated stdio entry for MCP server ${JSON.stringify(options.serverName)} must default-export a server factory.`); + const server = await factory(); + const { StdioServerTransport } = await Promise.resolve(stdio_namespaceObject); + guard.restoreProtocolStdout(); + const transport = new StdioServerTransport(); + return runStdioServer({ + ...options.lifecycle, + server, + serverName: options.serverName, + transport: transport + }); +}; + + + +await runGeneratedStdioMcpEntry({ + loadEntry: ()=>Promise.resolve(status_namespaceObject), + serverName: "status" +}); + +export {}; diff --git a/examples/mcp-app/artifact/codex/scripts/check-service-fixture.mjs b/examples/mcp-app/artifact/codex/scripts/check-service-fixture.mjs new file mode 100644 index 000000000..a059060bb --- /dev/null +++ b/examples/mcp-app/artifact/codex/scripts/check-service-fixture.mjs @@ -0,0 +1,60 @@ +import { readFile } from "node:fs/promises"; + + + + +const healthyCompilerStatus = Object.freeze({ + checks: Object.freeze([ + Object.freeze({ + label: 'Availability', + status: 'passing' + }), + Object.freeze({ + label: 'Build queue', + status: 'passing' + }) + ]), + service: 'compiler', + status: 'healthy', + summary: 'Compiler service is ready for release.' +}); +const isRecord = (value)=>value !== null && typeof value === 'object' && !Array.isArray(value); +const isHealthyCompilerFixture = (value)=>{ + if (!isRecord(value) || value.service !== healthyCompilerStatus.service || value.status !== healthyCompilerStatus.status || value.summary !== healthyCompilerStatus.summary || !Array.isArray(value.checks) || value.checks.length !== healthyCompilerStatus.checks.length) { + return false; + } + return healthyCompilerStatus.checks.every((expected, index)=>{ + const received = value.checks[index]; + return isRecord(received) && received.label === expected.label && received.status === expected.status; + }); +}; + + + +const fixturePath = new URL('../assets/evals/fixtures/status/result.json', import.meta.url); +/** + * `agent-bundle build` detects the `main` export and generates the process + * envelope (argv, awaiting, numeric-return exit-code adoption) around it. + */ const main = async ()=>{ + try { + const fixture = JSON.parse(await readFile(fixturePath, 'utf8')); + if (!isHealthyCompilerFixture(fixture)) { + throw new Error('compiler fixture must contain the exact healthy compiler status'); + } + process.stdout.write('Compiler fixture is healthy.\n'); + return 0; + } catch (error) { + process.stderr.write(`Unable to verify service fixture: ${error instanceof Error ? error.message : String(error)}\n`); + return 1; + } +}; + + +const check_service_fixture_entry_main = main; +if (typeof check_service_fixture_entry_main !== 'function') { + throw new TypeError('Executable entry must export a main function: ' + "/fast/projects/agent-bundle-worktrees/host-test/examples/mcp-app/src/scripts/check-service-fixture.ts"); +} +const code = await check_service_fixture_entry_main(process.argv.slice(2)); +if (typeof code === 'number') process.exitCode = code; + +export {}; diff --git a/examples/mcp-app/artifact/codex/skills/service-readiness/SKILL.md b/examples/mcp-app/artifact/codex/skills/service-readiness/SKILL.md new file mode 100644 index 000000000..8f91a79d7 --- /dev/null +++ b/examples/mcp-app/artifact/codex/skills/service-readiness/SKILL.md @@ -0,0 +1,33 @@ +--- +name: service-readiness +description: Reviews service health evidence and records an auditable readiness decision. +--- +# Service readiness + +## When to use + +Use this Skill when a release, incident decision, or service handoff needs a +clear health verdict backed by named checks and current evidence. + +## Required resources + +- Apply [the service status policy](references/status-policy.md) before + classifying a healthy, degraded, or blocked result. +- Deliver the decision with [the readiness report](assets/readiness-report.md). + +## Workflow + +1. Identify the service and collect its current summary and every labelled + check. Record the command, time, result, and evidence source. +2. Classify any failing check with the status policy. A degraded service is not + release-ready until its failing check has an approved mitigation. +3. State the readiness verdict only after confirming availability and the + service-specific release threshold. +4. Complete the report with the status, checks, evidence, owner, and next + action. Do not omit a failing check from the final decision. + +## Final report requirements + +State `ready`, `degraded`, `blocked`, or `needs evidence`; reproduce the +service summary; list each labelled check and its status; identify the owner +and due date for every non-passing check; and name the next required action. diff --git a/examples/mcp-app/artifact/codex/skills/service-readiness/assets/readiness-report.md b/examples/mcp-app/artifact/codex/skills/service-readiness/assets/readiness-report.md new file mode 100644 index 000000000..3da5d52ea --- /dev/null +++ b/examples/mcp-app/artifact/codex/skills/service-readiness/assets/readiness-report.md @@ -0,0 +1,22 @@ +# Service readiness report + +## Verdict + +State `ready`, `degraded`, `blocked`, or `needs evidence` and name the service. + +## Evidence + +Record the collection time, command or artifact, service summary, and source. + +## Checks + +List every labelled check with its observed status and release threshold. + +## Findings and mitigation + +For each non-passing check, record the impact, owner, mitigation, due date, +and the evidence required to clear it. + +## Next action + +Name the decision owner and the next verification or release action. diff --git a/examples/mcp-app/artifact/codex/skills/service-readiness/references/status-policy.md b/examples/mcp-app/artifact/codex/skills/service-readiness/references/status-policy.md new file mode 100644 index 000000000..7e5766172 --- /dev/null +++ b/examples/mcp-app/artifact/codex/skills/service-readiness/references/status-policy.md @@ -0,0 +1,22 @@ +# Service status policy + +## Evidence standard + +Readiness evidence must identify the service, collection time, check label, +observed status, and source command or artifact. Missing or stale evidence is +not a passing check. + +## Status classification + +- **Healthy**: every required release check is passing. +- **Degraded**: availability remains sufficient, but a release threshold such + as P95 latency is failing. Record an owner and mitigation before release. +- **Blocked**: availability or a critical safety check is failing. Do not + release until new passing evidence is collected. +- **Needs evidence**: the service or any required check cannot be verified. + +## Release decision + +Issue `ready` only for a healthy service with current evidence. A degraded +service needs an explicit mitigation decision; a blocked service cannot pass; +and missing evidence requires a new check rather than an assumption. diff --git a/examples/mcp-app/artifact/portable/INSTALL.md b/examples/mcp-app/artifact/portable/INSTALL.md new file mode 100644 index 000000000..5ba00d88e --- /dev/null +++ b/examples/mcp-app/artifact/portable/INSTALL.md @@ -0,0 +1,19 @@ +# Install mcp-app-example + +A unified service-readiness assistant with MCP, Skills, Hooks, scripts, and evaluation. + +Version: `1.0.0` + +Run these commands from this bundle directory. + +## Portable Agent Plugin + +Portable is a distribution profile, not a host runtime with one universal install location. +This bundle follows the Agent Plugins open standard (Agent Plugins 1.0.0, https://agent-plugins.org). +Cursor loads this format natively from `~/.cursor/plugins/local/`; restart Cursor or run +`Developer: Reload Window` after copying it. Codex, VS Code, GitHub Copilot, Kiro, and ChatGPT +are also native clients. The bundled installer provides the Cursor local copy: + +```sh +node ./install.mjs +``` diff --git a/examples/mcp-app/artifact/portable/assets/evals/fixtures/status/result.json b/examples/mcp-app/artifact/portable/assets/evals/fixtures/status/result.json new file mode 100644 index 000000000..a765aa4b5 --- /dev/null +++ b/examples/mcp-app/artifact/portable/assets/evals/fixtures/status/result.json @@ -0,0 +1,9 @@ +{ + "service": "compiler", + "status": "healthy", + "summary": "Compiler service is ready for release.", + "checks": [ + { "label": "Availability", "status": "passing" }, + { "label": "Build queue", "status": "passing" } + ] +} diff --git a/examples/mcp-app/artifact/portable/install.mjs b/examples/mcp-app/artifact/portable/install.mjs new file mode 100644 index 000000000..1d942a81a --- /dev/null +++ b/examples/mcp-app/artifact/portable/install.mjs @@ -0,0 +1,80 @@ +#!/usr/bin/env node +import { createHash } from 'node:crypto'; +import { cp, lstat, mkdir, mkdtemp, readFile, readdir, rename, rm } from 'node:fs/promises'; +import { homedir } from 'node:os'; +import { basename, join, resolve } from 'node:path'; +import { fileURLToPath } from 'node:url'; + +const pluginName = "mcp-app-example"; +const pluginVersion = "1.0.0"; +const source = resolve(fileURLToPath(new URL('.', import.meta.url))); +const cursorRoot = join(homedir(), '.cursor'); +const installRoot = join(cursorRoot, 'plugins', 'local'); +const destination = join(installRoot, pluginName); + +const exists = async (path) => { + try { await lstat(path); return true; } + catch (error) { if (error?.code === 'ENOENT') return false; throw error; } +}; + +const treeHash = async (root, prefix = '') => { + const rootMetadata = await lstat(root); + if (rootMetadata.isSymbolicLink() || !rootMetadata.isDirectory()) { + throw new Error('Refusing unsupported filesystem entry ".".'); + } + const hash = createHash('sha256'); + const visit = async (relative) => { + const absolute = join(root, relative); + const metadata = await lstat(absolute); + if (metadata.isSymbolicLink() || (!metadata.isDirectory() && !metadata.isFile())) { + throw new Error(`Refusing unsupported filesystem entry ${JSON.stringify(relative || '.')}.`); + } + if (metadata.isDirectory()) { + for (const name of (await readdir(absolute)).sort()) await visit(join(relative, name)); + return; + } + hash.update(relative.replaceAll('\\', '/')); + hash.update('\0'); + hash.update(await readFile(absolute)); + hash.update('\0'); + }; + for (const name of (await readdir(root)).sort()) await visit(join(prefix, name)); + return hash.digest('hex'); +}; + +const installedVersion = async () => { + for (const manifest of ['.cursor-plugin/plugin.json', 'plugin.json']) { + try { + const value = JSON.parse(await readFile(join(destination, manifest), 'utf8')); + if (typeof value.version === 'string') return value.version; + } catch (error) { if (error?.code !== 'ENOENT') throw error; } + } + return undefined; +}; + +if (!(await exists(cursorRoot)) || !(await lstat(cursorRoot)).isDirectory()) { + throw new Error(`Cursor is not installed in ${cursorRoot}.`); +} +await mkdir(installRoot, { recursive: true }); +if (await exists(destination)) { + const currentVersion = await installedVersion(); + if (currentVersion !== undefined && currentVersion !== pluginVersion) { + throw new Error(`Refusing version collision at ${destination}: found ${currentVersion}, requested ${pluginVersion}.`); + } + if (source === destination || await treeHash(source) === await treeHash(destination)) { + console.log(`Already installed ${pluginName}@${pluginVersion} at ${destination}`); + process.exit(0); + } + throw new Error(`Refusing content collision at ${destination}.`); +} + +const stageParent = await mkdtemp(join(installRoot, `.${basename(destination)}.stage-`)); +const stage = join(stageParent, 'bundle'); +try { + await cp(source, stage, { errorOnExist: true, force: false, recursive: true, verbatimSymlinks: true }); + await treeHash(stage); + await rename(stage, destination); + console.log(`Installed ${pluginName}@${pluginVersion} at ${destination}`); +} finally { + await rm(stageParent, { force: true, recursive: true }); +} diff --git a/examples/mcp-app/artifact/portable/mcp-apps/status.html b/examples/mcp-app/artifact/portable/mcp-apps/status.html new file mode 100644 index 000000000..4d949f09e --- /dev/null +++ b/examples/mcp-app/artifact/portable/mcp-apps/status.html @@ -0,0 +1,154 @@ + + + + + + Service status + + + +
+
MCP App example
+

No service selected

+
unknown
+

Invoke the readiness tool to inspect a service.

+
    + + + + +

    +
    + + diff --git a/examples/mcp-app/artifact/portable/mcp.json b/examples/mcp-app/artifact/portable/mcp.json new file mode 100644 index 000000000..ac9282f22 --- /dev/null +++ b/examples/mcp-app/artifact/portable/mcp.json @@ -0,0 +1 @@ +{"$schema":"https://agent-plugins.org/schemas/1.0.0/mcp.schema.json","mcpServers":{"status":{"args":["mcp/mcp-status-073c1634.mjs"],"command":"node","cwd":"${PLUGIN_ROOT}","env":{"AGENT_BUNDLE_PLUGIN_ROOT":"${PLUGIN_ROOT}"},"type":"stdio"}}} diff --git a/examples/mcp-app/artifact/portable/mcp/mcp-status-073c1634.mjs b/examples/mcp-app/artifact/portable/mcp/mcp-status-073c1634.mjs new file mode 100644 index 000000000..8a8e6ecb4 --- /dev/null +++ b/examples/mcp-app/artifact/portable/mcp/mcp-status-073c1634.mjs @@ -0,0 +1,30768 @@ +import node_process from "node:process"; + +// The require scope +var __webpack_require__ = {}; + +// webpack/runtime/define_property_getters +(() => { +__webpack_require__.d = (exports, getters, values) => { + var define = (defs, kind) => { + for(var key in defs) { + if(__webpack_require__.o(defs, key) && !__webpack_require__.o(exports, key)) { + Object.defineProperty(exports, key, { enumerable: true, [kind]: defs[key] }); + } + } + }; + define(getters, "get"); + define(values, "value"); +}; +})(); +// webpack/runtime/has_own_property +(() => { +__webpack_require__.o = (obj, prop) => (Object.prototype.hasOwnProperty.call(obj, prop)) +})(); +// webpack/runtime/make_namespace_object +(() => { +// define __esModule on exports +__webpack_require__.r = (exports) => { + if(typeof Symbol !== 'undefined' && Symbol.toStringTag) { + Object.defineProperty(exports, Symbol.toStringTag, { value: 'Module' }); + } + Object.defineProperty(exports, '__esModule', { value: true }); +}; +})(); + +// NAMESPACE OBJECT: ./src/mcp/status.ts +var status_namespaceObject = {}; +__webpack_require__.r(status_namespaceObject); +__webpack_require__.d(status_namespaceObject, { + createStatusServer: () => (createStatusServer), + "default": () => (mcp_status) }); + + +// NAMESPACE OBJECT: ../../node_modules/.pnpm/@modelcontextprotocol+server@2.0.0/node_modules/@modelcontextprotocol/server/dist/stdio.mjs +var stdio_namespaceObject = {}; +__webpack_require__.r(stdio_namespaceObject); +__webpack_require__.d(stdio_namespaceObject, { + StdioServerTransport: () => (stdio_StdioServerTransport) }); + + +//#region rolldown:runtime +var __create = Object.create; +var __defProp = Object.defineProperty; +var __getOwnPropDesc = Object.getOwnPropertyDescriptor; +var __getOwnPropNames = Object.getOwnPropertyNames; +var __getProtoOf = Object.getPrototypeOf; +var __hasOwnProp = Object.prototype.hasOwnProperty; +var __commonJSMin = (cb, mod) => () => (mod || cb((mod = { exports: {} }).exports, mod), mod.exports); +var __exportAll = (all, symbols) => { + let target = {}; + for (var name in all) { + __defProp(target, name, { + get: all[name], + enumerable: true + }); + } + if (symbols) { + __defProp(target, Symbol.toStringTag, { value: "Module" }); + } + return target; +}; +var __copyProps = (to, from, except, desc) => { + if (from && typeof from === "object" || typeof from === "function") { + for (var keys = __getOwnPropNames(from), i = 0, n = keys.length, key; i < n; i++) { + key = keys[i]; + if (!__hasOwnProp.call(to, key) && key !== except) { + __defProp(to, key, { + get: ((k) => from[k]).bind(null, key), + enumerable: !(desc = __getOwnPropDesc(from, key)) || desc.enumerable + }); + } + } + } + return to; +}; +var __toESM = (mod, isNodeMode, target) => (target = mod != null ? __create(__getProtoOf(mod)) : {}, __copyProps(isNodeMode || !mod || !mod.__esModule ? __defProp(target, "default", { + value: mod, + enumerable: true +}) : target, mod)); + +//#endregion + +//#region ../core-internal/src/validators/dialects.ts +/** +* Canonical `$schema` URIs per supported dialect (http + https variants, trailing-`#` stripped). +*/ +const DRAFT_2020_12_URIS = new Set(["https://json-schema.org/draft/2020-12/schema", "http://json-schema.org/draft/2020-12/schema"]); +const DRAFT_2019_09_URIS = new Set(["https://json-schema.org/draft/2019-09/schema", "http://json-schema.org/draft/2019-09/schema"]); +const DRAFT_07_URIS = new Set(["https://json-schema.org/draft-07/schema", "http://json-schema.org/draft-07/schema"]); +const DRAFT_06_URIS = new Set(["https://json-schema.org/draft-06/schema", "http://json-schema.org/draft-06/schema"]); +/** +* Whether a `$schema` value declares the 2019-09 dialect — the only supported dialect with +* `$recursiveRef`/`$recursiveAnchor`. Non-throwing (unlike {@linkcode declaredDialect}) so +* wire-layer callers can consult it for documents whose dialect may be unsupported. +*/ +function declares2019Dialect($schema) { + return typeof $schema === "string" && DRAFT_2019_09_URIS.has($schema.replace(/#$/, "")); +} +/** +* Classify a schema's declared `$schema` dialect. No `$schema` (or a non-string one) means +* 2020-12. Any other dialect throws a plain `Error` with a clear message rather than letting the +* engine crash on an opaque internal error or silently mis-validate; `remedy` names the calling +* provider's escape hatch in that message. +*/ +function declaredDialect(schema, remedy) { + if (!("$schema" in schema) || typeof schema.$schema !== "string") return "2020-12"; + const declared = schema.$schema.replace(/#$/, ""); + if (DRAFT_2020_12_URIS.has(declared)) return "2020-12"; + if (DRAFT_2019_09_URIS.has(declared)) return "2019-09"; + if (DRAFT_07_URIS.has(declared) || DRAFT_06_URIS.has(declared)) return "draft-7"; + throw new Error(`JSON Schema declares an unsupported dialect ("$schema": "${schema.$schema.slice(0, 200)}"). The default validator supports JSON Schema 2020-12, 2019-09, draft-07, and draft-06; ${remedy}`); +} + +//#endregion + +//# sourceMappingURL=dialects-DoSzNhcb.mjs.map + +// functions +function assertEqual(val) { + return val; +} +function assertNotEqual(val) { + return val; +} +function toZod() { + return (schema) => schema; +} +function assertIs(_arg) { } +function assertNever(_x) { + throw new Error("Unexpected value in exhaustive check"); +} +function assert(_) { } +function getEnumValues(entries) { + const numericValues = Object.values(entries).filter((v) => typeof v === "number"); + const values = Object.entries(entries) + .filter(([k, _]) => numericValues.indexOf(+k) === -1) + .map(([_, v]) => v); + return values; +} +function joinValues(array, separator = "|") { + return array.map((val) => stringifyPrimitive(val)).join(separator); +} +function jsonStringifyReplacer(_, value) { + if (typeof value === "bigint") + return value.toString(); + return value; +} +function util_cached(getter) { + const set = false; + return { + get value() { + if (!set) { + const value = getter(); + Object.defineProperty(this, "value", { value }); + return value; + } + throw new Error("cached value already set"); + }, + }; +} +function nullish(input) { + return input === null || input === undefined; +} +function cleanRegex(source) { + const start = source.startsWith("^") ? 1 : 0; + const end = source.endsWith("$") ? source.length - 1 : source.length; + return source.slice(start, end); +} +function floatSafeRemainder(val, step) { + const ratio = val / step; + const roundedRatio = Math.round(ratio); + // `val` and `step` each round to a double before the division rounds again, so a true decimal multiple's quotient can sit up to 1.5 of these scaled epsilons from the integer. A 1x tolerance therefore rejected 2.03 as a multiple of 0.07; 4x covers the worst case with margin. + const tolerance = 4 * Number.EPSILON * Math.max(Math.abs(ratio), 1); + if (Math.abs(ratio - roundedRatio) < tolerance) + return 0; + return ratio - roundedRatio; +} +const EVALUATING = /* @__PURE__*/ Symbol("evaluating"); +function defineLazy(object, key, getter) { + let value = undefined; + Object.defineProperty(object, key, { + get() { + if (value === EVALUATING) { + // Circular reference detected, return undefined to break the cycle + return undefined; + } + if (value === undefined) { + value = EVALUATING; + value = getter(); + } + return value; + }, + set(v) { + Object.defineProperty(object, key, { + value: v, + // configurable: true, + }); + // object[key] = v; + }, + configurable: true, + }); +} +function objectClone(obj) { + return Object.create(Object.getPrototypeOf(obj), Object.getOwnPropertyDescriptors(obj)); +} +function assignProp(target, prop, value) { + Object.defineProperty(target, prop, { + value, + writable: true, + enumerable: true, + configurable: true, + }); +} +function mergeDefs(...defs) { + const mergedDescriptors = {}; + for (const def of defs) { + const descriptors = Object.getOwnPropertyDescriptors(def); + Object.assign(mergedDescriptors, descriptors); + } + return Object.defineProperties({}, mergedDescriptors); +} +function cloneDef(schema) { + return mergeDefs(schema._zod.def); +} +function getElementAtPath(obj, path) { + if (!path) + return obj; + return path.reduce((acc, key) => acc?.[key], obj); +} +function promiseAllObject(promisesObj) { + const keys = Object.keys(promisesObj); + const promises = keys.map((key) => promisesObj[key]); + return Promise.all(promises).then((results) => { + const resolvedObj = {}; + for (let i = 0; i < keys.length; i++) { + resolvedObj[keys[i]] = results[i]; + } + return resolvedObj; + }); +} +function randomString(length = 10) { + const chars = "abcdefghijklmnopqrstuvwxyz"; + let str = ""; + for (let i = 0; i < length; i++) { + str += chars[Math.floor(Math.random() * chars.length)]; + } + return str; +} +function util_esc(str) { + return JSON.stringify(str); +} +function slugify(input) { + return input + .toLowerCase() + .trim() + .replace(/[^\w\s-]/g, "") + .replace(/[\s_-]+/g, "-") + .replace(/^-+|-+$/g, ""); +} +const captureStackTrace = ("captureStackTrace" in Error ? Error.captureStackTrace : (..._args) => { }); +function util_isObject(data) { + return typeof data === "object" && data !== null && !Array.isArray(data); +} +const util_allowsEval = /* @__PURE__*/ util_cached(() => { + // Skip the probe under `jitless`: strict CSPs report the caught `new Function` as a `securitypolicyviolation` even though the throw is swallowed. + if (globalConfig.jitless) { + return false; + } + // @ts-ignore + if (typeof navigator !== "undefined" && navigator?.userAgent?.includes("Cloudflare")) { + return false; + } + try { + const F = Function; + new F(""); + return true; + } + catch (_) { + return false; + } +}); +function isPlainObject(o) { + if (util_isObject(o) === false) + return false; + // modified constructor + const ctor = o.constructor; + if (ctor === undefined) + return true; + if (typeof ctor !== "function") + return true; + // modified prototype + const prot = ctor.prototype; + if (util_isObject(prot) === false) + return false; + // ctor doesn't have static `isPrototypeOf` + if (Object.prototype.hasOwnProperty.call(prot, "isPrototypeOf") === false) { + return false; + } + return true; +} +function shallowClone(o) { + if (isPlainObject(o)) + return { ...o }; + if (Array.isArray(o)) + return [...o]; + if (o instanceof Map) + return new Map(o); + if (o instanceof Set) + return new Set(o); + return o; +} +function numKeys(data) { + let keyCount = 0; + for (const key in data) { + if (Object.prototype.hasOwnProperty.call(data, key)) { + keyCount++; + } + } + return keyCount; +} +const getParsedType = (data) => { + const t = typeof data; + switch (t) { + case "undefined": + return "undefined"; + case "string": + return "string"; + case "number": + return Number.isNaN(data) ? "nan" : "number"; + case "boolean": + return "boolean"; + case "function": + return "function"; + case "bigint": + return "bigint"; + case "symbol": + return "symbol"; + case "object": + if (Array.isArray(data)) { + return "array"; + } + if (data === null) { + return "null"; + } + if (data.then && typeof data.then === "function" && data.catch && typeof data.catch === "function") { + return "promise"; + } + if (typeof Map !== "undefined" && data instanceof Map) { + return "map"; + } + if (typeof Set !== "undefined" && data instanceof Set) { + return "set"; + } + if (typeof Date !== "undefined" && data instanceof Date) { + return "date"; + } + // @ts-ignore + if (typeof File !== "undefined" && data instanceof File) { + return "file"; + } + return "object"; + default: + throw new Error(`Unknown data type: ${t}`); + } +}; +const propertyKeyTypes = /* @__PURE__*/ new Set(["string", "number", "symbol"]); +const primitiveTypes = /* @__PURE__*/ (/* unused pure expression or super */ null && (new Set([ + "string", + "number", + "bigint", + "boolean", + "symbol", + "undefined", +]))); +function escapeRegex(str) { + return str.replace(/[.*+?^${}()|[\]\\]/g, "\\$&"); +} +// zod-specific utils +function clone(inst, def, params) { + const cl = new inst._zod.constr(def ?? inst._zod.def); + if (!def || params?.parent) + cl._zod.parent = inst; + return cl; +} +function normalizeParams(_params) { + const params = _params; + if (!params) + return {}; + if (typeof params === "string") + return { error: () => params }; + if (params?.message !== undefined) { + if (params?.error !== undefined) + throw new Error("Cannot specify both `message` and `error` params"); + params.error = params.message; + } + delete params.message; + if (typeof params.error === "string") + return { ...params, error: () => params.error }; + return params; +} +function createTransparentProxy(getter) { + let target; + return new Proxy({}, { + get(_, prop, receiver) { + target ?? (target = getter()); + return Reflect.get(target, prop, receiver); + }, + set(_, prop, value, receiver) { + target ?? (target = getter()); + return Reflect.set(target, prop, value, receiver); + }, + has(_, prop) { + target ?? (target = getter()); + return Reflect.has(target, prop); + }, + deleteProperty(_, prop) { + target ?? (target = getter()); + return Reflect.deleteProperty(target, prop); + }, + ownKeys(_) { + target ?? (target = getter()); + return Reflect.ownKeys(target); + }, + getOwnPropertyDescriptor(_, prop) { + target ?? (target = getter()); + return Reflect.getOwnPropertyDescriptor(target, prop); + }, + defineProperty(_, prop, descriptor) { + target ?? (target = getter()); + return Reflect.defineProperty(target, prop, descriptor); + }, + }); +} +function stringifyPrimitive(value) { + if (typeof value === "bigint") + return value.toString() + "n"; + if (typeof value === "string") + return `"${value}"`; + return `${value}`; +} +function optionalKeys(shape) { + return Object.keys(shape).filter((k) => { + return shape[k]._zod.optin !== undefined && shape[k]._zod.optout === "optional"; + }); +} +// Wrapped in a `@__PURE__` IIFE: esbuild never tree-shakes a top-level initializer that contains a member access on `Number`, so the bare object literal survived into every bundle. +const NUMBER_FORMAT_RANGES = /*@__PURE__*/ (() => ({ + safeint: [Number.MIN_SAFE_INTEGER, Number.MAX_SAFE_INTEGER], + int32: [-2147483648, 2147483647], + uint32: [0, 4294967295], + float32: [-3.4028234663852886e38, 3.4028234663852886e38], + float64: [-Number.MAX_VALUE, Number.MAX_VALUE], +}))(); +const BIGINT_FORMAT_RANGES = { + int64: [/* @__PURE__*/ BigInt("-9223372036854775808"), /* @__PURE__*/ BigInt("9223372036854775807")], + uint64: [/* @__PURE__*/ BigInt(0), /* @__PURE__*/ BigInt("18446744073709551615")], +}; +function pick(schema, mask) { + const currDef = schema._zod.def; + const checks = currDef.checks; + const hasChecks = checks && checks.length > 0; + if (hasChecks) { + throw new Error(".pick() cannot be used on object schemas containing refinements"); + } + const def = mergeDefs(schema._zod.def, { + get shape() { + const newShape = {}; + // `for...in` skips symbols, so a symbol in the mask would select nothing + for (const key of Reflect.ownKeys(mask)) { + if (!Object.prototype.hasOwnProperty.call(currDef.shape, key)) { + throw new Error(`Unrecognized key: "${String(key)}"`); + } + if (!mask[key]) + continue; + assignProp(newShape, key, currDef.shape[key]); + } + assignProp(this, "shape", newShape); // self-caching + return newShape; + }, + checks: [], + }); + return clone(schema, def); +} +function omit(schema, mask) { + const currDef = schema._zod.def; + const checks = currDef.checks; + const hasChecks = checks && checks.length > 0; + if (hasChecks) { + throw new Error(".omit() cannot be used on object schemas containing refinements"); + } + const def = mergeDefs(schema._zod.def, { + get shape() { + const newShape = { ...schema._zod.def.shape }; + for (const key of Reflect.ownKeys(mask)) { + if (!Object.prototype.hasOwnProperty.call(currDef.shape, key)) { + throw new Error(`Unrecognized key: "${String(key)}"`); + } + if (!mask[key]) + continue; + delete newShape[key]; + } + assignProp(this, "shape", newShape); // self-caching + return newShape; + }, + checks: [], + }); + return clone(schema, def); +} +function extend(schema, shape) { + if (!isPlainObject(shape)) { + throw new Error("Invalid input to extend: expected a plain object"); + } + const checks = schema._zod.def.checks; + const hasChecks = checks && checks.length > 0; + if (hasChecks) { + // Only throw if new shape overlaps with existing shape. Use getOwnPropertyDescriptor to check key existence without accessing values + const existingShape = schema._zod.def.shape; + for (const key of Reflect.ownKeys(shape)) { + if (Object.getOwnPropertyDescriptor(existingShape, key) !== undefined) { + throw new Error("Cannot overwrite keys on object schemas containing refinements. Use `.safeExtend()` instead."); + } + } + } + const def = mergeDefs(schema._zod.def, { + get shape() { + const _shape = { ...schema._zod.def.shape, ...shape }; + assignProp(this, "shape", _shape); // self-caching + return _shape; + }, + }); + return clone(schema, def); +} +function safeExtend(schema, shape) { + if (!isPlainObject(shape)) { + throw new Error("Invalid input to safeExtend: expected a plain object"); + } + const def = mergeDefs(schema._zod.def, { + get shape() { + const _shape = { ...schema._zod.def.shape, ...shape }; + assignProp(this, "shape", _shape); // self-caching + return _shape; + }, + }); + return clone(schema, def); +} +function merge(a, b) { + if (!b?._zod?.def) { + throw new Error("Invalid input to merge: expected an object schema. To merge a plain shape, use `.extend()`."); + } + if (a._zod.def.checks?.length) { + throw new Error(".merge() cannot be used on object schemas containing refinements. Use .safeExtend() instead."); + } + const def = mergeDefs(a._zod.def, { + get shape() { + const _shape = { ...a._zod.def.shape, ...b._zod.def.shape }; + assignProp(this, "shape", _shape); // self-caching + return _shape; + }, + get catchall() { + return b._zod.def.catchall; + }, + checks: b._zod.def.checks ?? [], + }); + return clone(a, def); +} +function partial(Class, schema, mask, name = "partial") { + const currDef = schema._zod.def; + const checks = currDef.checks; + const hasChecks = checks && checks.length > 0; + if (hasChecks) { + throw new Error(`.${name}() cannot be used on object schemas containing refinements`); + } + const def = mergeDefs(schema._zod.def, { + get shape() { + const oldShape = schema._zod.def.shape; + const shape = { ...oldShape }; + if (mask) { + for (const key of Reflect.ownKeys(mask)) { + if (!Object.prototype.hasOwnProperty.call(oldShape, key)) { + throw new Error(`Unrecognized key: "${String(key)}"`); + } + if (!mask[key]) + continue; + // if (oldShape[key]!._zod.optin === "optional") continue; + shape[key] = Class + ? new Class({ + type: "optional", + innerType: oldShape[key], + }) + : oldShape[key]; + } + } + else { + // the spread copies symbol keys; `for...in` would not reach them + for (const key of Reflect.ownKeys(oldShape)) { + // if (oldShape[key]!._zod.optin === "optional") continue; + shape[key] = Class + ? new Class({ + type: "optional", + innerType: oldShape[key], + }) + : oldShape[key]; + } + } + assignProp(this, "shape", shape); // self-caching + return shape; + }, + checks: [], + }); + return clone(schema, def); +} +function util_required(Class, schema, mask) { + const def = mergeDefs(schema._zod.def, { + get shape() { + const oldShape = schema._zod.def.shape; + const shape = { ...oldShape }; + if (mask) { + for (const key of Reflect.ownKeys(mask)) { + if (!Object.prototype.hasOwnProperty.call(shape, key)) { + throw new Error(`Unrecognized key: "${String(key)}"`); + } + if (!mask[key]) + continue; + // overwrite with non-optional + shape[key] = new Class({ + type: "nonoptional", + innerType: oldShape[key], + }); + } + } + else { + for (const key of Reflect.ownKeys(oldShape)) { + // overwrite with non-optional + shape[key] = new Class({ + type: "nonoptional", + innerType: oldShape[key], + }); + } + } + assignProp(this, "shape", shape); // self-caching + return shape; + }, + }); + return clone(schema, def); +} +// invalid_type | too_big | too_small | invalid_format | not_multiple_of | unrecognized_keys | invalid_union | invalid_key | invalid_element | invalid_value | custom +function aborted(x, startIndex = 0) { + if (x.aborted === true) + return true; + for (let i = startIndex; i < x.issues.length; i++) { + if (x.issues[i]?.continue !== true) { + return true; + } + } + return false; +} +// Checks for explicit abort (continue === false), as opposed to implicit abort (continue === undefined). Used to respect `abort: true` in .refine() even for checks that have a `when` function. +function explicitlyAborted(x, startIndex = 0) { + if (x.aborted === true) + return true; + for (let i = startIndex; i < x.issues.length; i++) { + if (x.issues[i]?.continue === false) { + return true; + } + } + return false; +} +function prefixIssues(path, issues) { + return issues.map((iss) => { + var _a; + (_a = iss).path ?? (_a.path = []); + iss.path.unshift(path); + return iss; + }); +} +function unwrapMessage(message) { + return typeof message === "string" ? message : message?.message; +} +/* A check holds no link back to the schema it is attached to — the same check instance is shared by every clone of that schema — so the owner is stamped onto the issues a check just raised, at the only point where both are in scope. Runs on the failure path only; `start` is the issue count from before the check ran. */ +function attachSchema(issues, start, inst) { + var _a; + for (let i = start; i < issues.length; i++) { + (_a = issues[i]).schema ?? (_a.schema = inst); + } +} +function finalizeIssue(iss, ctx, config) { + var _a; + // A schema that raised an issue itself owns it outright, and outranks any stamp an enclosing check left in `attachSchema`. String formats and z.custom() are schema and check at once, so when they act as a check they defer to that stamp instead. + const traits = iss.inst?._zod?.traits; + if (traits?.has("$ZodType")) { + if (traits.has("$ZodCheck")) + (_a = iss).schema ?? (_a.schema = iss.inst); + else + iss.schema = iss.inst; + } + // Decreasing specificity, first map to return a message wins. `inst` is whatever raised the issue, so a check's own map outranks the owning schema's. + const schemaError = iss.schema !== iss.inst ? iss.schema?._zod.def?.error : undefined; + const message = iss.message + ? iss.message + : (unwrapMessage(iss.inst?._zod.def?.error?.(iss)) ?? + unwrapMessage(schemaError?.(iss)) ?? + unwrapMessage(ctx?.error?.(iss)) ?? + unwrapMessage(config.customError?.(iss)) ?? + unwrapMessage(config.localeError?.(iss)) ?? + "Invalid input"); + const { inst: _inst, schema: _schema, continue: _continue, input: _input, ...rest } = iss; + rest.path ?? (rest.path = []); + rest.message = message; + if (ctx?.reportInput) { + rest.input = _input; + } + return rest; +} +function getSizableOrigin(input) { + if (input instanceof Set) + return "set"; + if (input instanceof Map) + return "map"; + // @ts-ignore + if (input instanceof File) + return "file"; + return "unknown"; +} +const highSurrogate = /[\uD800-\uDBFF]/; +// Code points in `str`: a surrogate pair counts once, a lone surrogate as itself. Hand-rolled because the string iterator allocates and runs ~250x slower on this path; the regex probe exits ~50x quicker for a string with no astral characters. +function codePointLength(str) { + const units = str.length; + if (!highSurrogate.test(str)) + return units; + let count = units; + for (let i = 0; i < units - 1; i++) { + if ((str.charCodeAt(i) & 0xfc00) === 0xd800 && (str.charCodeAt(i + 1) & 0xfc00) === 0xdc00) { + count--; + i++; + } + } + return count; +} +function getLengthableOrigin(input) { + if (Array.isArray(input)) + return "array"; + if (typeof input === "string") + return "string"; + return "unknown"; +} +function parsedType(data) { + const t = typeof data; + switch (t) { + case "number": { + return Number.isNaN(data) ? "nan" : "number"; + } + case "object": { + if (data === null) { + return "null"; + } + if (Array.isArray(data)) { + return "array"; + } + const obj = data; + if (obj && Object.getPrototypeOf(obj) !== Object.prototype && "constructor" in obj && obj.constructor) { + return obj.constructor.name; + } + } + } + return t; +} +function util_issue(...args) { + const [iss, input, inst] = args; + if (typeof iss === "string") { + return { + message: iss, + code: "custom", + input, + inst, + }; + } + return { ...iss }; +} +function cleanEnum(obj) { + return Object.entries(obj) + .filter(([k, _]) => { + // return true if NaN, meaning it's not a number, thus a string key + return Number.isNaN(Number.parseInt(k, 10)); + }) + .map((el) => el[1]); +} +// Codec utility functions +function base64ToUint8Array(base64) { + const binaryString = atob(base64); + const bytes = new Uint8Array(binaryString.length); + for (let i = 0; i < binaryString.length; i++) { + bytes[i] = binaryString.charCodeAt(i); + } + return bytes; +} +function uint8ArrayToBase64(bytes) { + let binaryString = ""; + for (let i = 0; i < bytes.length; i++) { + binaryString += String.fromCharCode(bytes[i]); + } + return btoa(binaryString); +} +function base64urlToUint8Array(base64url) { + const base64 = base64url.replace(/-/g, "+").replace(/_/g, "/"); + const padding = "=".repeat((4 - (base64.length % 4)) % 4); + return base64ToUint8Array(base64 + padding); +} +function uint8ArrayToBase64url(bytes) { + return uint8ArrayToBase64(bytes).replace(/\+/g, "-").replace(/\//g, "_").replace(/=/g, ""); +} +function hexToUint8Array(hex) { + const cleanHex = hex.replace(/^0x/, ""); + if (cleanHex.length % 2 !== 0) { + throw new Error("Invalid hex string length"); + } + const bytes = new Uint8Array(cleanHex.length / 2); + for (let i = 0; i < cleanHex.length; i += 2) { + bytes[i / 2] = Number.parseInt(cleanHex.slice(i, i + 2), 16); + } + return bytes; +} +function uint8ArrayToHex(bytes) { + return Array.from(bytes) + .map((b) => b.toString(16).padStart(2, "0")) + .join(""); +} +// instanceof +class util_Class { + constructor(..._args) { } +} +////////// PROTOTYPE INSTALLERS ////////// +// +// Members live on the prototype and materialize per instance on first read, which keeps own-property count under the step where V8 stops using inline slots. Changing anything here means re-measuring runtime, memory and bundle size together — see "The three axes" in AGENTS.md. +/** + * Installs a trait's members on its prototype. Each value builds that member for the instance on first read; the built value shadows the accessor as an own property, so a detached `const { parse } = schema` keeps working. + * + * Call this from a `proto` initializer, which runs once per prototype — never per instance. + */ +function util_members(proto, table) { + for (const key in table) { + const desc = Object.getOwnPropertyDescriptor(table, key); + // a getter installs as written, so it stays live: `description` reads through to the registry on every access. not enumerable: an object literal's is, and a prototype member never was + if (desc.get) + Object.defineProperty(proto, key, { ...desc, enumerable: false }); + // a method materializes bound on first read, which is what keeps a detached member working: `const opt = schema.optional; opt()` + else + defineBound(proto, key, desc.value); + } +} +/** Shadows a prototype member with an own value, so a getter that builds from the instance runs once. */ +function util_own(inst, key, value, enumerable = true) { + Object.defineProperty(inst, key, { configurable: true, writable: true, enumerable, value }); + return value; +} +/** Like {@link own}, for a member that was never an own data property and has to stay out of `Object.keys`. */ +function hide(inst, key, value) { + return util_own(inst, key, value, false); +} +function defineBound(proto, key, fn) { + Object.defineProperty(proto, key, { + configurable: true, + get() { + // vitest's spyOn calls a prototype getter bare to find the function it wraps, so a nullish receiver answers the raw method + return this == null ? fn : util_own(this, key, fn.bind(this)); + }, + set(value) { + util_own(this, key, value); + }, + }); +} +/** Returns the prototype to install on, or `undefined` if this group is already installed on it. */ +function claim(inst, sentinel) { + const proto = Object.getPrototypeOf(inst); + // Runs on every construction, so `in` rather than the costlier `hasOwnProperty.call`. Sentinels are keys the group itself defines. + return sentinel in proto ? undefined : proto; +} +// The internals whose init chain is installing. A second call for the same one is a derived constructor overriding its base, so it must not construct another schema in between or the override is dropped. +let installing; +// Set while a getter is running, so a value that resolved through a recursion break is not memoized. One shared descriptor shadows the key for the duration, which costs no per-key allocation. +let broke = false; +const breaker = { + configurable: true, + get() { + broke = true; + return undefined; + }, +}; +/** + * Installs a lazily-derived internal on the `_zod` prototype of `inst`'s + * constructor, computed from the internals object itself and cached there on + * first read. One accessor per constructor rather than one per instance. + */ +function defineLazyInternal(inst, key, compute) { + const proto = Object.getPrototypeOf(inst._zod); + if (key in proto && installing !== inst._zod) { + // A repeat construction: everything is installed already. Cleared here so the reference is not held past the first construction of every type. + installing = undefined; + return; + } + installing = inst._zod; + Object.defineProperty(proto, key, { + configurable: true, + get() { + // Shadowed before computing so a re-entrant read from a recursive schema resolves to undefined instead of running the getter again. + Object.defineProperty(this, key, breaker); + const outer = broke; + broke = false; + try { + const value = compute(this); + // A result that resolved through a recursion break is recomputed once the graph is complete; everything else memoizes, undefined included. + if (broke) + delete this[key]; + else + Object.defineProperty(this, key, { configurable: true, writable: true, value }); + broke = broke || outer; + return value; + } + catch (err) { + // A compute that threw memoizes nothing, so a later read runs it again and fails the same way. The shadow goes with it, since leaving it installed would answer undefined for every later read. + delete this[key]; + broke = broke || outer; + throw err; + } + }, + set(value) { + Object.defineProperty(this, key, { configurable: true, writable: true, value }); + }, + }); +} +/** + * Installs `key` on `inst`'s prototype, computed by `make` on first read and cached there as an own + * data property. One accessor per constructor rather than one per instance, because an own accessor + * puts every instance after the first into v8 dictionary mode. The key doubles as the sentinel. + */ +function installLazyProp(inst, key, make, enumerable) { + const proto = claim(inst, key); + if (!proto) + return; + Object.defineProperty(proto, key, { + configurable: true, + get() { + // Shadowed before computing, so a re-entrant read from a self-referential shape resolves to undefined instead of running the getter again. A data property rather than an accessor: an own accessor is the dictionary-mode transition this exists to avoid. + const desc = { configurable: true, writable: true, enumerable, value: undefined }; + Object.defineProperty(this, key, desc); + // a compute that throws leaves the shadow behind, so later reads answer undefined instead of re-throwing; `defineLazy` did the same, and `defineLazyInternal`'s delete-on-catch would cost bytes in every bundle for a case only a throwing user getter reaches + desc.value = make(this); + Object.defineProperty(this, key, desc); + return desc.value; + }, + set(value) { + Object.defineProperty(this, key, { configurable: true, writable: true, enumerable, value }); + }, + }); +} +/** Marks the thunk `_catch` synthesises for a constant catch value. `Function.length` cannot tell that thunk from a user callback — rest and defaulted parameters both report arity 0 — and a user callback reads `ctx.error`, whose issues only finalize correctly against the caller's per-parse error map. Provenance can say what arity cannot. A plain string key rather than `Symbol.for`, whose call at module scope no bundler can prove pure — the same shape that anchored `urlCanParse` into every build. */ +const CONSTANT_CATCH = "~constantCatch"; +/** Wraps a constant catch value in a thunk tagged with {@link CONSTANT_CATCH}. */ +function constantCatch(value) { + const fn = () => value; + fn[CONSTANT_CATCH] = true; + return fn; +} + +var core_a; + +/** A special constant with type `never` */ +const NEVER = /*@__PURE__*/ Object.freeze({ + status: "aborted", +}); +/* Shared descriptor for installing `_zod`; defineProperty reads it + * synchronously, so reusing one object avoids a per-instance allocation. */ +const _zodDesc = { value: undefined, enumerable: false }; +// null where suppressing the capture would be unrecoverable: `parse()` puts the frames back with `captureStackTrace`, so without it the throw would lose its stack. also latched to null once `stackTraceLimit` proves unassignable, which a realm can do at any point by hardening Error +let _E = "captureStackTrace" in Error ? Error : null; +// v8 captures a stack trace inside the Error constructor, which dominates a failed parse; costs only the frames, and parse() restores those. the constructor must RUN: Object.create is cheaper and passes instanceof, but Error.isError and util.types.isNativeError check an internal slot +function newError(Definition) { + const E = _E; + if (E) { + const saved = E.stackTraceLimit; + if (typeof saved === "number") { + try { + E.stackTraceLimit = 0; + } + catch { + _E = null; + return new Definition(); + } + try { + return new Definition(); + } + finally { + E.stackTraceLimit = saved; + } + } + } + return new Definition(); +} +function $constructor(name, initializer, +/** This trait's members, installed once on every prototype that composes it. They cannot be declared in the initializer above: that runs per instance, and the prototype is shared. */ +proto, params) { + // Prototype for this constructor's `_zod` internals. Lazily-derived fields (`values`, `pattern`, `optin`, …) install here once rather than as an accessor on every instance. + const zodProto = {}; + // Assigning the fields in the constructor body is what gives instances in-object slots; building the object literally and reparenting it costs a second allocation and a generic property copy. + function Internals(def) { + this.def = def; + this.constr = _; + this.traits = new Set(); + } + Internals.prototype = zodProto; + const protoMembers = proto; + // One trait's members land on every prototype whose chain composes it, so the answer is per prototype rather than per trait. + const initialized = protoMembers && new WeakSet(); + function init(inst, def) { + if (!inst._zod) { + _zodDesc.value = new Internals(def); + try { + Object.defineProperty(inst, "_zod", _zodDesc); + } + finally { + // Cleared even on throw, so the shared descriptor never leaks one instance's internals into the next. + _zodDesc.value = undefined; + } + } + if (inst._zod.traits.has(name)) { + return; + } + inst._zod.traits.add(name); + initializer(inst, def); + if (initialized) { + // `super(def)` from a user subclass gives `this` a prototype the subclass owns, and installing there would overwrite whatever the subclass declared. `constr` built the instance, so its prototype is the one below the subclass's that should carry the members. A receiver whose chain never reaches that prototype installs on its own, which for a plain object handed straight to `init` means `Object.prototype` — unchanged from before. + const own = Object.getPrototypeOf(inst); + const ctorProto = inst._zod.constr.prototype; + let up = own; + while (up && up !== ctorProto) + up = Object.getPrototypeOf(up); + const target = up ?? own; + if (!initialized.has(target)) { + initialized.add(target); + util_members(target, protoMembers); + } + } + // support prototype modifications; for-in avoids the array allocation of Object.keys on the (usually empty) prototype + const proto = _.prototype; + for (const k in proto) { + if (!Object.prototype.hasOwnProperty.call(proto, k)) + continue; + if (!(k in inst)) { + inst[k] = proto[k].bind(inst); + } + } + } + // doesn't work if Parent has a constructor with arguments + const Parent = params?.Parent ?? Object; + class Definition extends Parent { + } + Object.defineProperty(Definition, "name", { value: name }); + function _(def) { + const inst = params?.Parent ? newError(Definition) : this; + init(inst, def); + const deferred = inst._zod.deferred; + if (deferred) { + for (const fn of deferred) { + fn(); + } + // Released: initializers run once, and the list would otherwise be retained for the schema's lifetime. + inst._zod.deferred = undefined; + } + // Global post-processor hook. Internal: installed by `import "zod/compile"` to enable AOT compilation for every constructed schema. Runs last, once the instance is fully built, because it hands the instance to compile(). The post-processor is expected to be reentrancy-guarded by its own implementation. + const pp = globalThis.__zod_globalConfig?.postProcessor; + if (pp) + pp(inst); + return inst; + } + Object.defineProperty(_, "init", { value: init }); + Object.defineProperty(_, Symbol.hasInstance, { + value: (inst) => { + if (params?.Parent && inst instanceof params.Parent) + return true; + return inst?._zod?.traits?.has(name); + }, + }); + Object.defineProperty(_, "name", { value: name }); + return _; +} +////////////////////////////// UTILITIES /////////////////////////////////////// +const $brand = /*@__PURE__*/ (/* unused pure expression or super */ null && (Symbol("zod_brand"))); +class $ZodAsyncError extends Error { + constructor() { + super(`Encountered Promise during synchronous parse. Use .parseAsync() instead.`); + } +} +class $ZodEncodeError extends Error { + constructor(name) { + super(`Encountered unidirectional transform during encode: ${name}`); + this.name = "ZodEncodeError"; + } +} +(core_a = globalThis).__zod_globalConfig ?? (core_a.__zod_globalConfig = {}); +const globalConfig = globalThis.__zod_globalConfig; +function core_config(newConfig) { + if (newConfig) + Object.assign(globalConfig, newConfig); + return globalConfig; +} + +class $ZodCyclicError extends Error { + constructor() { + super(`Cannot parse a reference cycle that closes through a transform`); + this.name = "ZodCyclicError"; + } +} +/** Keyed off the context object every schema in one parse call already shares. */ +const STATE = "~memo"; +const NO_ISSUES = []; +// Receivers prefix paths in place, so the cache and every hand-out need their own copies. +function cloneIssues(issues) { + return issues.map((iss) => (iss.path ? { ...iss, path: iss.path.slice() } : { ...iss })); +} +const recursive = /*@__PURE__*/ new WeakMap(); +/** Whether this schema's subtree contains a cycle, so one parse can re-enter it. */ +function isRecursive(inst, stack) { + const cached = recursive.get(inst); + if (cached !== undefined) + return cached; + // Relative to the walk in progress, so not cached. + if (stack.has(inst)) + return true; + stack.add(inst); + let result = false; + const check = (child) => { + if (!result && child?._zod && isRecursive(child, stack)) + result = true; + }; + const def = inst._zod.def; + const kind = def.type; + switch (kind) { + case "object": { + // `Reflect.ownKeys` rather than `Object.keys`, so a cycle through a declared symbol key is still seen + for (const key of Reflect.ownKeys(def.shape)) + check(def.shape[key]); + check(def.catchall); + break; + } + case "array": + check(def.element); + break; + case "tuple": + for (const el of def.items) + check(el); + check(def.rest); + break; + case "record": + case "map": + check(def.keyType); + check(def.valueType); + break; + case "set": + check(def.valueType); + break; + case "union": + for (const el of def.options) + check(el); + break; + case "intersection": + check(def.left); + check(def.right); + break; + case "optional": + case "nullable": + case "default": + case "prefault": + case "catch": + case "readonly": + case "nonoptional": + case "promise": + case "success": + check(def.innerType); + break; + case "pipe": + check(def.in); + check(def.out); + break; + case "function": + check(def.input); + check(def.output); + break; + // reading `_zod.innerType` resolves the getter once and caches it + case "lazy": + check(inst._zod.innerType); + break; + // a leaf by choice: `parts` are regex fragments, not data positions + case "template_literal": + // leaves + case "string": + case "number": + case "int": + case "boolean": + case "bigint": + case "symbol": + case "undefined": + case "null": + case "void": + case "never": + case "any": + case "unknown": + case "date": + case "nan": + case "enum": + case "literal": + case "file": + case "transform": + case "custom": + break; + default: { + // a new built-in kind becomes a compile error here + kind; + // a user-defined kind can still hold children, and only its author knows where, so fall back to scanning the def — skipping accessors, since reading one can run user code + for (const key in def) { + const desc = Object.getOwnPropertyDescriptor(def, key); + if (!desc || desc.get) + continue; + const value = desc.value; + if (!value || typeof value !== "object") + continue; + if (value._zod) + check(value); + else if (Array.isArray(value)) + for (const el of value) + check(el); + } + } + } + stack.delete(inst); + recursive.set(inst, result); + return result; +} +/** + * Whether one parse can re-enter this schema, i.e. its subtree contains a cycle. + * Exported for `z.compile`, which refuses to compile such a schema: cycle + * breaking is driven from here off state keyed on the parse context, and a + * generated fast path has no context to key on. + */ +function isRecursiveSchema(inst) { + return isRecursive(inst, new Set()); +} +function bucketFor(state, inst) { + let bucket = state.buckets.get(inst); + if (!bucket) { + bucket = new Map(); + state.buckets.set(inst, bucket); + } + return bucket; +} +// Set immediately before delegating to core and cleared immediately after, so `alloc` registers only for a visit this module is driving. +let handoff; +// Allocated but unfinished entries. `alloc` and the matching pop both happen in the synchronous part of a parse, so they nest even when children are async, and one stack serves every schema. +const memoizer_open = []; +const memoizer_memo = { + alloc(_inst, payload, empty) { + const bucket = handoff; + if (!bucket) + return empty; + handoff = undefined; + const entry = { value: empty, issues: null }; + bucket.set(payload.value, entry); + memoizer_open.push(entry); + return empty; + }, + guard(inst) { + var _a; + (_a = inst._zod).deferred ?? (_a.deferred = []); + inst._zod.deferred.push(() => { + const base = inst._zod.parse; + const wrapped = (payload, ctx) => { + // The value is a placeholder a back-edge is still waiting on, so the cycle closes through this transform. Its output can't exist in time to bind. + if (ctx.direction !== "backward" && isBackEdge(ctx, payload.value)) + throw new $ZodCyclicError(); + return base(payload, ctx); + }; + inst._zod.parse = wrapped; + if (inst._zod.run === base) + inst._zod.run = wrapped; + }); + }, + attach(inst) { + var _a; + let isRecursiveInst; + // `bucket` memoized for one parse; a recursive schema is re-entered many times and its bucket never changes + let lastCtx; + let lastBucket; + // Wraps `parse` in a deferred so it sees the container's final parse. Core's own deferred copies `parse` into `run` when there are no checks, and it ran first, so `run` is patched to match; with checks, `run` reads `parse` dynamically. + (_a = inst._zod).deferred ?? (_a.deferred = []); + inst._zod.deferred.push(() => { + const base = inst._zod.parse; + const wrapped = (payload, ctx) => { + if (isRecursiveInst === undefined) { + isRecursiveInst = isRecursive(inst, new Set()); + if (!isRecursiveInst) { + // Nothing here can ever fire, so take it back out. + inst._zod.parse = base; + if (inst._zod.run === wrapped) + inst._zod.run = base; + return base(payload, ctx); + } + } + const input = payload.value; + if (input === null || typeof input !== "object") + return base(payload, ctx); + let state = ctx[STATE]; + if (!state) { + state = { buckets: new Map(), backEdges: undefined }; + ctx[STATE] = state; + } + let bucket; + if (lastCtx === ctx) { + bucket = lastBucket; + } + else { + bucket = bucketFor(state, inst); + lastCtx = ctx; + lastBucket = bucket; + } + const hit = bucket.get(input); + if (hit) { + payload.value = hit.value; + if (hit.issues) { + if (hit.issues.length) + payload.issues.push(...cloneIssues(hit.issues)); + } + else { + // Still being parsed: its own checks cover it, so skip them here. + payload.memo = true; + state.backEdges ?? (state.backEdges = new Set()); + state.backEdges.add(hit.value); + } + return payload; + } + handoff = bucket; + const depth = memoizer_open.length; + const result = base(payload, ctx); + handoff = undefined; + // A container that rejected its input outright allocated nothing. + const entry = memoizer_open.length > depth ? memoizer_open.pop() : undefined; + // Both paths written out so the sync one allocates no closure. It runs once per node, and capturing here cost more than everything else combined. + if (result instanceof Promise) { + return result.then((r) => { + if (entry) + entry.issues = r.issues.length ? cloneIssues(r.issues) : NO_ISSUES; + return r; + }); + } + if (entry) + entry.issues = result.issues.length ? cloneIssues(result.issues) : NO_ISSUES; + return result; + }; + inst._zod.parse = wrapped; + if (inst._zod.run === base) + inst._zod.run = wrapped; + }); + }, +}; +/** The memoizer that gives containers cycle support. `zod` installs it by default; `zod/mini` opts in with `config({ memoizer: memoizer() })`. */ +function memoizer() { + return memoizer_memo; +} +/** Whether this value is a node a back-edge resolved to before it finished. */ +function isBackEdge(ctx, value) { + const backEdges = ctx[STATE]?.backEdges; + return backEdges !== undefined && value !== null && typeof value === "object" && backEdges.has(value); +} + + +/** + * @deprecated CUID v1 is deprecated by its authors due to information leakage + * (timestamps embedded in the id). Use {@link cuid2} instead. + * See https://github.com/paralleldrive/cuid. + */ +const cuid = /^[cC][0-9a-z]{6,}$/; +const cuid2 = /^[0-9a-z]+$/; +const ulid = /^[0-7][0-9A-HJKMNP-TV-Za-hjkmnp-tv-z]{25}$/; +const xid = /^[0-9a-vA-V]{20}$/; +const ksuid = /^[A-Za-z0-9]{27}$/; +const nanoid = /^[a-zA-Z0-9_-]{21}$/; +function nanoidOfLength(length) { + return new RegExp(`^[a-zA-Z0-9_-]{${length}}$`); +} +/** ISO 8601-1 duration regex. Does not support the 8601-2 extensions like negative durations or fractional/negative components. */ +const duration = /^P(?:(\d+W)|(?!.*W)(?=\d|T\d)(\d+Y)?(\d+M)?(\d+D)?(T(?=\d)(\d+H)?(\d+M)?(\d+([.,]\d+)?S)?)?)$/; +/** Implements ISO 8601-2 extensions like explicit +- prefixes, mixing weeks with other units, and fractional/negative components. */ +const extendedDuration = /^[-+]?P(?!$)(?:(?:[-+]?\d+Y)|(?:[-+]?\d+[.,]\d+Y$))?(?:(?:[-+]?\d+M)|(?:[-+]?\d+[.,]\d+M$))?(?:(?:[-+]?\d+W)|(?:[-+]?\d+[.,]\d+W$))?(?:(?:[-+]?\d+D)|(?:[-+]?\d+[.,]\d+D$))?(?:T(?=[\d+-])(?:(?:[-+]?\d+H)|(?:[-+]?\d+[.,]\d+H$))?(?:(?:[-+]?\d+M)|(?:[-+]?\d+[.,]\d+M$))?(?:[-+]?\d+(?:[.,]\d+)?S)?)??$/; +/** A regex for any UUID-like identifier: 8-4-4-4-12 hex pattern */ +const guid = /^([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})$/; +/** Returns a regex for validating an RFC 9562/4122 UUID. + * + * @param version Optionally specify a version 1-8. If no version is specified, all versions are supported. */ +const uuid = (version) => { + if (!version) + return /^([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)$/; + return new RegExp(`^([0-9a-fA-F]{8}-[0-9a-fA-F]{4}-${version}[0-9a-fA-F]{3}-[89abAB][0-9a-fA-F]{3}-[0-9a-fA-F]{12})$`); +}; +const uuid4 = /*@__PURE__*/ (/* unused pure expression or super */ null && (uuid(4))); +const uuid6 = /*@__PURE__*/ (/* unused pure expression or super */ null && (uuid(6))); +const uuid7 = /*@__PURE__*/ (/* unused pure expression or super */ null && (uuid(7))); +/** Practical email validation */ +const email = /^(?!\.)(?!.*\.\.)([A-Za-z0-9_'+\-\.]*)[A-Za-z0-9_+-]@([A-Za-z0-9][A-Za-z0-9\-]*\.)+[A-Za-z]{2,}$/; +/** Equivalent to the HTML5 input[type=email] validation implemented by browsers. Source: https://developer.mozilla.org/en-US/docs/Web/HTML/Element/input/email */ +const html5Email = /^[a-zA-Z0-9.!#$%&'*+/=?^_`{|}~-]+@[a-zA-Z0-9](?:[a-zA-Z0-9-]{0,61}[a-zA-Z0-9])?(?:\.[a-zA-Z0-9](?:[a-zA-Z0-9-]{0,61}[a-zA-Z0-9])?)*$/; +/** The classic emailregex.com regex for RFC 5322-compliant emails */ +const rfc5322Email = /^(([^<>()\[\]\\.,;:\s@"]+(\.[^<>()\[\]\\.,;:\s@"]+)*)|(".+"))@((\[[0-9]{1,3}\.[0-9]{1,3}\.[0-9]{1,3}\.[0-9]{1,3}])|(([a-zA-Z\-0-9]+\.)+[a-zA-Z]{2,}))$/; +/** A loose regex that allows Unicode characters, enforces length limits, and that's about it. */ +const unicodeEmail = /^[^\s@"]{1,64}@[^\s@]{1,255}$/u; +const idnEmail = (/* unused pure expression or super */ null && (unicodeEmail)); +const browserEmail = /^[a-zA-Z0-9.!#$%&'*+/=?^_`{|}~-]+@[a-zA-Z0-9](?:[a-zA-Z0-9-]{0,61}[a-zA-Z0-9])?(?:\.[a-zA-Z0-9](?:[a-zA-Z0-9-]{0,61}[a-zA-Z0-9])?)*$/; +// from https://thekevinscott.com/emojis-in-javascript/#writing-a-regular-expression +// Single character class, not an alternation: the two properties overlap (U+1F9B0-U+1F9B3), so `(A|B)+` backtracks exponentially on a failed match. +const _emoji = `^[\\p{Extended_Pictographic}\\p{Emoji_Component}]+$`; +function emoji() { + return new RegExp(_emoji, "u"); +} +const ipv4 = /^(?:(?: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])$/; +const regexes_ipv6 = /^(([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}|:))$/; +const mac = (delimiter) => { + const escapedDelim = util.escapeRegex(delimiter ?? ":"); + return new RegExp(`^(?:[0-9A-F]{2}${escapedDelim}){5}[0-9A-F]{2}$|^(?:[0-9a-f]{2}${escapedDelim}){5}[0-9a-f]{2}$`); +}; +const cidrv4 = /^((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])$/; +const cidrv6 = /^(([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}|:))\/(12[0-8]|1[01][0-9]|[1-9]?[0-9])$/; +// https://stackoverflow.com/questions/7860392/determine-if-string-is-in-base64-using-javascript +const regexes_base64 = /^$|^(?:[0-9a-zA-Z+/]{4})*(?:(?:[0-9a-zA-Z+/]{2}==)|(?:[0-9a-zA-Z+/]{3}=))?$/; +const regexes_base64url = /^[A-Za-z0-9_-]*$/; +// based on https://stackoverflow.com/questions/106179/regular-expression-to-match-dns-hostname-or-ip-address +// export const hostname: RegExp = /^([a-zA-Z0-9-]+\.)*[a-zA-Z0-9-]+$/; +const regexes_hostname = /^(?=.{1,253}\.?$)[a-zA-Z0-9](?:[a-zA-Z0-9-]{0,61}[a-zA-Z0-9])?(?:\.[a-zA-Z0-9](?:[-0-9a-zA-Z]{0,61}[0-9a-zA-Z])?)*\.?$/; +const domain = /^(?=.{1,253}$)([a-zA-Z0-9](?:[a-zA-Z0-9-]{0,61}[a-zA-Z0-9])?\.)+[a-zA-Z]{2,63}$/; +const httpProtocol = /^https?$/; +// https://blog.stevenlevithan.com/archives/validate-phone-number#r4-3 (regex sans spaces) E.164: leading digit must be 1-9; total digits (excluding '+') between 7-15 +const e164 = /^\+[1-9]\d{6,14}$/; +// Credit card shape: 12–19 digits, optionally separated by single spaces or single hyphens. ISO/IEC 7812 caps the PAN at 19 digits; 12 is the shortest issued length (Maestro). +const creditCard = /^\d(?:[ -]?\d){11,18}$/; +const dateSource = `(?:(?:\\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])))`; +/** Anchors a pattern source. The interpolation lives here rather than at the call site because + * esbuild will not drop a `@__PURE__` call whose own argument interpolates a variable, but it + * will drop `anchor(dateSource)`. Keeping it inline pinned `date` into every bundle. */ +function regexes_anchor(source) { + return new RegExp(`^${source}$`); +} +const regexes_date = /*@__PURE__*/ regexes_anchor(dateSource); +function timeSource(args) { + const hhmm = `(?:[01]\\d|2[0-3]):[0-5]\\d`; + const regex = typeof args.precision === "number" + ? args.precision === -1 + ? `${hhmm}` + : args.precision === 0 + ? `${hhmm}:[0-5]\\d` + : `${hhmm}:[0-5]\\d\\.\\d{${args.precision}}` + : args.seconds + ? `${hhmm}:[0-5]\\d(?:\\.\\d+)?` + : `${hhmm}(?::[0-5]\\d(?:\\.\\d+)?)?`; + return regex; +} +function regexes_time(args) { + return new RegExp(`^${timeSource(args)}$`); +} +// Adapted from https://stackoverflow.com/a/3143231 +function datetime(args) { + const opts = ["Z"]; + // if (args.offset) opts.push(`([+-]\\d{2}:\\d{2})`); + if (args.offset) + opts.push(`([+-](?:[01]\\d|2[0-3]):[0-5]\\d)`); + // RFC 3339 mandates seconds wherever the time carries a `Z` or an offset, so only the unqualified form `local` adds may omit them + const qualified = `${timeSource({ precision: args.precision, seconds: true })}(?:${opts.join("|")})`; + const timeRegex = args.local ? `${qualified}|${timeSource({ precision: args.precision })}` : qualified; + return new RegExp(`^${dateSource}T(?:${timeRegex})$`); +} +const regexes_string = (params) => { + const regex = params ? `[\\s\\S]{${params?.minimum ?? 0},${params?.maximum ?? ""}}` : `[\\s\\S]*`; + return new RegExp(`^${regex}$`); +}; +const bigint = /^-?\d+n?$/; +const integer = /^-?\d+$/; +const number = /^-?\d+(?:\.\d+)?$/; +const regexes_boolean = /^(?:true|false)$/i; +const _null = /^null$/i; + +const _undefined = /^undefined$/i; + +// regex for string with no uppercase letters +const lowercase = /^[^A-Z]*$/; +// regex for string with no lowercase letters +const uppercase = /^[^a-z]*$/; +// regex for hexadecimal strings (any length) +const regexes_hex = /^[0-9a-fA-F]*$/; +// Hash regexes for different algorithms and encodings +// Helper function to create base64 regex with exact length and padding +function fixedBase64(bodyLength, padding) { + return new RegExp(`^[A-Za-z0-9+/]{${bodyLength}}${padding}$`); +} +// Helper function to create base64url regex with exact length (no padding) +function fixedBase64url(length) { + return new RegExp(`^[A-Za-z0-9_-]{${length}}$`); +} +// MD5 (16 bytes): base64 = 24 chars total (22 + "==") +const md5_hex = /^[0-9a-fA-F]{32}$/; +const md5_base64 = /*@__PURE__*/ (/* unused pure expression or super */ null && (fixedBase64(22, "=="))); +const md5_base64url = /*@__PURE__*/ (/* unused pure expression or super */ null && (fixedBase64url(22))); +// SHA1 (20 bytes): base64 = 28 chars total (27 + "=") +const sha1_hex = /^[0-9a-fA-F]{40}$/; +const sha1_base64 = /*@__PURE__*/ (/* unused pure expression or super */ null && (fixedBase64(27, "="))); +const sha1_base64url = /*@__PURE__*/ (/* unused pure expression or super */ null && (fixedBase64url(27))); +// SHA256 (32 bytes): base64 = 44 chars total (43 + "=") +const sha256_hex = /^[0-9a-fA-F]{64}$/; +const sha256_base64 = /*@__PURE__*/ (/* unused pure expression or super */ null && (fixedBase64(43, "="))); +const sha256_base64url = /*@__PURE__*/ (/* unused pure expression or super */ null && (fixedBase64url(43))); +// SHA384 (48 bytes): base64 = 64 chars total (no padding) +const sha384_hex = /^[0-9a-fA-F]{96}$/; +const sha384_base64 = /*@__PURE__*/ (/* unused pure expression or super */ null && (fixedBase64(64, ""))); +const sha384_base64url = /*@__PURE__*/ (/* unused pure expression or super */ null && (fixedBase64url(64))); +// SHA512 (64 bytes): base64 = 88 chars total (86 + "==") +const sha512_hex = /^[0-9a-fA-F]{128}$/; +const sha512_base64 = /*@__PURE__*/ (/* unused pure expression or super */ null && (fixedBase64(86, "=="))); +const sha512_base64url = /*@__PURE__*/ (/* unused pure expression or super */ null && (fixedBase64url(86))); + +// import { $ZodType } from "./schemas.js"; + + + +const $ZodCheck = /*@__PURE__*/ $constructor("$ZodCheck", (inst, def) => { + var _a; + inst._zod ?? (inst._zod = {}); + inst._zod.def = def; + (_a = inst._zod).onattach ?? (_a.onattach = []); +}); +/** Default `when` for size-based checks: run only on non-nullish values with a `size`. */ +const _whenHasSize = (payload) => { + const val = payload.value; + return !util.nullish(val) && val.size !== undefined; +}; +/** Default `when` for length-based checks: run only on non-nullish values with a `length`. */ +const _whenHasLength = (payload) => { + const val = payload.value; + return !nullish(val) && val.length !== undefined; +}; +const numericOriginMap = { + number: "number", + bigint: "bigint", + object: "date", +}; +const $ZodCheckLessThan = /*@__PURE__*/ $constructor("$ZodCheckLessThan", (inst, def) => { + $ZodCheck.init(inst, def); + const origin = numericOriginMap[typeof def.value]; + inst._zod.onattach.push((inst) => { + const bag = inst._zod.bag; + const curr = (def.inclusive ? bag.maximum : bag.exclusiveMaximum) ?? Number.POSITIVE_INFINITY; + if (def.value < curr) { + if (def.inclusive) + bag.maximum = def.value; + else + bag.exclusiveMaximum = def.value; + } + }); + inst._zod.check = (payload) => { + if (def.inclusive ? payload.value <= def.value : payload.value < def.value) { + return; + } + payload.issues.push({ + origin: numericOriginMap[typeof payload.value] ?? origin, + code: "too_big", + maximum: typeof def.value === "object" ? def.value.getTime() : def.value, + input: payload.value, + inclusive: def.inclusive, + inst, + continue: !def.abort, + }); + }; +}); +const $ZodCheckGreaterThan = /*@__PURE__*/ $constructor("$ZodCheckGreaterThan", (inst, def) => { + $ZodCheck.init(inst, def); + const origin = numericOriginMap[typeof def.value]; + inst._zod.onattach.push((inst) => { + const bag = inst._zod.bag; + const curr = (def.inclusive ? bag.minimum : bag.exclusiveMinimum) ?? Number.NEGATIVE_INFINITY; + if (def.value > curr) { + if (def.inclusive) + bag.minimum = def.value; + else + bag.exclusiveMinimum = def.value; + } + }); + inst._zod.check = (payload) => { + if (def.inclusive ? payload.value >= def.value : payload.value > def.value) { + return; + } + payload.issues.push({ + origin: numericOriginMap[typeof payload.value] ?? origin, + code: "too_small", + minimum: typeof def.value === "object" ? def.value.getTime() : def.value, + input: payload.value, + inclusive: def.inclusive, + inst, + continue: !def.abort, + }); + }; +}); +const $ZodCheckMultipleOf = +/*@__PURE__*/ $constructor("$ZodCheckMultipleOf", (inst, def) => { + $ZodCheck.init(inst, def); + inst._zod.onattach.push((inst) => { + var _a; + (_a = inst._zod.bag).multipleOf ?? (_a.multipleOf = def.value); + }); + inst._zod.check = (payload) => { + if (typeof payload.value !== typeof def.value) + throw new Error("Cannot mix number and bigint in multiple_of check."); + const isMultiple = typeof payload.value === "bigint" + ? // `value % 0n` throws, and nothing is a multiple of zero — the number branch already fails this way via NaN + def.value !== BigInt(0) && payload.value % def.value === BigInt(0) + : floatSafeRemainder(payload.value, def.value) === 0; + if (isMultiple) + return; + payload.issues.push({ + origin: typeof payload.value, + code: "not_multiple_of", + divisor: def.value, + input: payload.value, + inst, + continue: !def.abort, + }); + }; +}); +const $ZodCheckNumberFormat = /*@__PURE__*/ $constructor("$ZodCheckNumberFormat", (inst, def) => { + $ZodCheck.init(inst, def); // no format checks + def.format = def.format || "float64"; + const isInt = def.format?.includes("int"); + const origin = isInt ? "int" : "number"; + const [minimum, maximum] = NUMBER_FORMAT_RANGES[def.format]; + inst._zod.onattach.push((inst) => { + const bag = inst._zod.bag; + bag.format = def.format; + bag.minimum = minimum; + bag.maximum = maximum; + if (isInt) + bag.pattern = integer; + }); + inst._zod.check = (payload) => { + const input = payload.value; + if (isInt) { + if (!Number.isInteger(input)) { + // invalid_format issue + // payload.issues.push({ + // expected: def.format, + // format: def.format, + // code: "invalid_format", + // input, + // inst, + // }); + // invalid_type issue + payload.issues.push({ + expected: origin, + format: def.format, + code: "invalid_type", + continue: false, + input, + inst, + }); + return; + // not_multiple_of issue + // payload.issues.push({ + // code: "not_multiple_of", + // origin: "number", + // input, + // inst, + // divisor: 1, + // }); + } + if (!Number.isSafeInteger(input)) { + if (input > 0) { + // too_big + payload.issues.push({ + input, + code: "too_big", + maximum: Number.MAX_SAFE_INTEGER, + note: "Integers must be within the safe integer range.", + inst, + origin, + inclusive: true, + continue: !def.abort, + }); + } + else { + // too_small + payload.issues.push({ + input, + code: "too_small", + minimum: Number.MIN_SAFE_INTEGER, + note: "Integers must be within the safe integer range.", + inst, + origin, + inclusive: true, + continue: !def.abort, + }); + } + return; + } + } + if (input < minimum) { + payload.issues.push({ + origin: "number", + input, + code: "too_small", + minimum, + inclusive: true, + inst, + continue: !def.abort, + }); + } + if (input > maximum) { + payload.issues.push({ + origin: "number", + input, + code: "too_big", + maximum, + inclusive: true, + inst, + continue: !def.abort, + }); + } + }; +}); +const $ZodCheckBigIntFormat = /*@__PURE__*/ (/* unused pure expression or super */ null && (core.$constructor("$ZodCheckBigIntFormat", (inst, def) => { + $ZodCheck.init(inst, def); // no format checks + const [minimum, maximum] = util.BIGINT_FORMAT_RANGES[def.format]; + inst._zod.onattach.push((inst) => { + const bag = inst._zod.bag; + bag.format = def.format; + bag.minimum = minimum; + bag.maximum = maximum; + }); + inst._zod.check = (payload) => { + const input = payload.value; + if (input < minimum) { + payload.issues.push({ + origin: "bigint", + input, + code: "too_small", + minimum: minimum, + inclusive: true, + inst, + continue: !def.abort, + }); + } + if (input > maximum) { + payload.issues.push({ + origin: "bigint", + input, + code: "too_big", + maximum, + inclusive: true, + inst, + continue: !def.abort, + }); + } + }; +}))); +const $ZodCheckMaxSize = /*@__PURE__*/ (/* unused pure expression or super */ null && (core.$constructor("$ZodCheckMaxSize", (inst, def) => { + var _a; + $ZodCheck.init(inst, def); + (_a = inst._zod.def).when ?? (_a.when = _whenHasSize); + inst._zod.onattach.push((inst) => { + const curr = (inst._zod.bag.maximum ?? Number.POSITIVE_INFINITY); + if (def.maximum < curr) + inst._zod.bag.maximum = def.maximum; + }); + inst._zod.check = (payload) => { + const input = payload.value; + const size = input.size; + if (size <= def.maximum) + return; + payload.issues.push({ + origin: util.getSizableOrigin(input), + code: "too_big", + maximum: def.maximum, + inclusive: true, + input, + inst, + continue: !def.abort, + }); + }; +}))); +const $ZodCheckMinSize = /*@__PURE__*/ (/* unused pure expression or super */ null && (core.$constructor("$ZodCheckMinSize", (inst, def) => { + var _a; + $ZodCheck.init(inst, def); + (_a = inst._zod.def).when ?? (_a.when = _whenHasSize); + inst._zod.onattach.push((inst) => { + const curr = (inst._zod.bag.minimum ?? Number.NEGATIVE_INFINITY); + if (def.minimum > curr) + inst._zod.bag.minimum = def.minimum; + }); + inst._zod.check = (payload) => { + const input = payload.value; + const size = input.size; + if (size >= def.minimum) + return; + payload.issues.push({ + origin: util.getSizableOrigin(input), + code: "too_small", + minimum: def.minimum, + inclusive: true, + input, + inst, + continue: !def.abort, + }); + }; +}))); +const $ZodCheckSizeEquals = /*@__PURE__*/ (/* unused pure expression or super */ null && (core.$constructor("$ZodCheckSizeEquals", (inst, def) => { + var _a; + $ZodCheck.init(inst, def); + (_a = inst._zod.def).when ?? (_a.when = _whenHasSize); + inst._zod.onattach.push((inst) => { + const bag = inst._zod.bag; + bag.minimum = def.size; + bag.maximum = def.size; + bag.size = def.size; + }); + inst._zod.check = (payload) => { + const input = payload.value; + const size = input.size; + if (size === def.size) + return; + const tooBig = size > def.size; + payload.issues.push({ + origin: util.getSizableOrigin(input), + ...(tooBig ? { code: "too_big", maximum: def.size } : { code: "too_small", minimum: def.size }), + inclusive: true, + exact: true, + input: payload.value, + inst, + continue: !def.abort, + }); + }; +}))); +const $ZodCheckMaxLength = /*@__PURE__*/ $constructor("$ZodCheckMaxLength", (inst, def) => { + var _a; + $ZodCheck.init(inst, def); + (_a = inst._zod.def).when ?? (_a.when = _whenHasLength); + inst._zod.onattach.push((inst) => { + const curr = (inst._zod.bag.maximum ?? Number.POSITIVE_INFINITY); + if (def.maximum < curr) + inst._zod.bag.maximum = def.maximum; + }); + inst._zod.check = (payload) => { + const input = payload.value; + const units = input.length; + // Strings are measured in Unicode code points, not UTF-16 units. A code point is at most two units, so a string that already fits in units fits in code points; only an overflow has to be counted. + const length = typeof input === "string" && units > def.maximum ? codePointLength(input) : units; + if (length <= def.maximum) + return; + const origin = getLengthableOrigin(input); + payload.issues.push({ + origin, + code: "too_big", + maximum: def.maximum, + inclusive: true, + input, + inst, + continue: !def.abort, + }); + }; +}); +const $ZodCheckMinLength = /*@__PURE__*/ $constructor("$ZodCheckMinLength", (inst, def) => { + var _a; + $ZodCheck.init(inst, def); + (_a = inst._zod.def).when ?? (_a.when = _whenHasLength); + inst._zod.onattach.push((inst) => { + const curr = (inst._zod.bag.minimum ?? Number.NEGATIVE_INFINITY); + if (def.minimum > curr) + inst._zod.bag.minimum = def.minimum; + }); + inst._zod.check = (payload) => { + const input = payload.value; + const units = input.length; + // A code point is one or two UTF-16 units, so fewer units than the floor can never reach it and twice the floor always clears it. Only in between is the exact count in doubt. + const length = typeof input === "string" && units >= def.minimum && units < def.minimum * 2 + ? codePointLength(input) + : units; + if (length >= def.minimum) + return; + const origin = getLengthableOrigin(input); + payload.issues.push({ + origin, + code: "too_small", + minimum: def.minimum, + inclusive: true, + input, + inst, + continue: !def.abort, + }); + }; +}); +const $ZodCheckLengthEquals = /*@__PURE__*/ $constructor("$ZodCheckLengthEquals", (inst, def) => { + var _a; + $ZodCheck.init(inst, def); + (_a = inst._zod.def).when ?? (_a.when = _whenHasLength); + inst._zod.onattach.push((inst) => { + const bag = inst._zod.bag; + bag.minimum = def.length; + bag.maximum = def.length; + bag.length = def.length; + }); + inst._zod.check = (payload) => { + const input = payload.value; + const units = input.length; + // A code point is one or two UTF-16 units, so outside `[length, length * 2]` units the target is missed either way — and missed in the same direction in both measures. + const length = typeof input === "string" && units >= def.length && units <= def.length * 2 + ? codePointLength(input) + : units; + if (length === def.length) + return; + const origin = getLengthableOrigin(input); + const tooBig = length > def.length; + payload.issues.push({ + origin, + ...(tooBig ? { code: "too_big", maximum: def.length } : { code: "too_small", minimum: def.length }), + inclusive: true, + exact: true, + input: payload.value, + inst, + continue: !def.abort, + }); + }; +}); +const $ZodCheckStringFormat = /*@__PURE__*/ $constructor("$ZodCheckStringFormat", (inst, def) => { + var _a, _b; + $ZodCheck.init(inst, def); + inst._zod.onattach.push((inst) => { + const bag = inst._zod.bag; + bag.format = def.format; + if (def.pattern) { + bag.patterns ?? (bag.patterns = new Set()); + bag.patterns.add(def.pattern); + } + }); + if (def.pattern) + (_a = inst._zod).check ?? (_a.check = (payload) => { + def.pattern.lastIndex = 0; + if (def.pattern.test(payload.value)) + return; + payload.issues.push({ + origin: "string", + code: "invalid_format", + format: def.format, + input: payload.value, + ...(def.pattern ? { pattern: def.pattern.toString() } : {}), + inst, + continue: !def.abort, + }); + }); + else + (_b = inst._zod).check ?? (_b.check = () => { }); +}); +const $ZodCheckRegex = /*@__PURE__*/ $constructor("$ZodCheckRegex", (inst, def) => { + $ZodCheckStringFormat.init(inst, def); + inst._zod.check = (payload) => { + def.pattern.lastIndex = 0; + if (def.pattern.test(payload.value)) + return; + payload.issues.push({ + origin: "string", + code: "invalid_format", + format: "regex", + input: payload.value, + pattern: def.pattern.toString(), + inst, + continue: !def.abort, + }); + }; +}); +const $ZodCheckLowerCase = /*@__PURE__*/ $constructor("$ZodCheckLowerCase", (inst, def) => { + def.pattern ?? (def.pattern = lowercase); + $ZodCheckStringFormat.init(inst, def); +}); +const $ZodCheckUpperCase = /*@__PURE__*/ $constructor("$ZodCheckUpperCase", (inst, def) => { + def.pattern ?? (def.pattern = uppercase); + $ZodCheckStringFormat.init(inst, def); +}); +const $ZodCheckIncludes = /*@__PURE__*/ $constructor("$ZodCheckIncludes", (inst, def) => { + $ZodCheck.init(inst, def); + const escapedRegex = escapeRegex(def.includes); + // `String.prototype.includes(sub, position)` matches `sub` at `position` + // OR LATER, so the pattern must allow at least `position` leading chars + // (`{N,}`), not exactly `position` chars (`{N}`). + const pattern = new RegExp(typeof def.position === "number" ? `^.{${def.position},}${escapedRegex}` : escapedRegex); + def.pattern = pattern; + inst._zod.onattach.push((inst) => { + const bag = inst._zod.bag; + bag.patterns ?? (bag.patterns = new Set()); + bag.patterns.add(pattern); + }); + inst._zod.check = (payload) => { + if (payload.value.includes(def.includes, def.position)) + return; + payload.issues.push({ + origin: "string", + code: "invalid_format", + format: "includes", + includes: def.includes, + input: payload.value, + inst, + continue: !def.abort, + }); + }; +}); +const $ZodCheckStartsWith = /*@__PURE__*/ $constructor("$ZodCheckStartsWith", (inst, def) => { + $ZodCheck.init(inst, def); + const pattern = new RegExp(`^${escapeRegex(def.prefix)}.*`); + def.pattern ?? (def.pattern = pattern); + inst._zod.onattach.push((inst) => { + const bag = inst._zod.bag; + bag.patterns ?? (bag.patterns = new Set()); + bag.patterns.add(pattern); + }); + inst._zod.check = (payload) => { + if (payload.value.startsWith(def.prefix)) + return; + payload.issues.push({ + origin: "string", + code: "invalid_format", + format: "starts_with", + prefix: def.prefix, + input: payload.value, + inst, + continue: !def.abort, + }); + }; +}); +const $ZodCheckEndsWith = /*@__PURE__*/ $constructor("$ZodCheckEndsWith", (inst, def) => { + $ZodCheck.init(inst, def); + const pattern = new RegExp(`.*${escapeRegex(def.suffix)}$`); + def.pattern ?? (def.pattern = pattern); + inst._zod.onattach.push((inst) => { + const bag = inst._zod.bag; + bag.patterns ?? (bag.patterns = new Set()); + bag.patterns.add(pattern); + }); + inst._zod.check = (payload) => { + if (payload.value.endsWith(def.suffix)) + return; + payload.issues.push({ + origin: "string", + code: "invalid_format", + format: "ends_with", + suffix: def.suffix, + input: payload.value, + inst, + continue: !def.abort, + }); + }; +}); +/////////////////////////////////// +///// $ZodCheckProperty ///// +/////////////////////////////////// +function handleCheckPropertyResult(result, payload, property) { + if (result.issues.length) { + payload.issues.push(...util.prefixIssues(property, result.issues)); + } +} +const $ZodCheckProperty = /*@__PURE__*/ (/* unused pure expression or super */ null && (core.$constructor("$ZodCheckProperty", (inst, def) => { + $ZodCheck.init(inst, def); + inst._zod.check = (payload) => { + const result = def.schema._zod.run({ + value: payload.value[def.property], + issues: [], + }, {}); + if (result instanceof Promise) { + return result.then((result) => handleCheckPropertyResult(result, payload, def.property)); + } + handleCheckPropertyResult(result, payload, def.property); + return; + }; +}))); +const $ZodCheckMimeType = /*@__PURE__*/ (/* unused pure expression or super */ null && (core.$constructor("$ZodCheckMimeType", (inst, def) => { + $ZodCheck.init(inst, def); + const mimeSet = new Set(def.mime); + inst._zod.onattach.push((inst) => { + inst._zod.bag.mime = def.mime; + }); + inst._zod.check = (payload) => { + if (mimeSet.has(payload.value.type)) + return; + payload.issues.push({ + code: "invalid_value", + values: def.mime, + input: payload.value.type, + inst, + continue: !def.abort, + }); + }; +}))); +const $ZodCheckOverwrite = /*@__PURE__*/ $constructor("$ZodCheckOverwrite", (inst, def) => { + $ZodCheck.init(inst, def); + inst._zod.check = (payload) => { + payload.value = def.tx(payload.value); + }; +}); + +class Doc { + constructor(args = [], closed = {}) { + this.content = []; + this.indent = 0; + this.args = args; + this.closed = closed; + } + indented(fn) { + this.indent += 1; + fn(this); + this.indent -= 1; + } + write(arg) { + if (typeof arg === "function") { + arg(this, { execution: "sync" }); + arg(this, { execution: "async" }); + return; + } + const content = arg; + const lines = content.split("\n").filter((x) => x); + const minIndent = Math.min(...lines.map((x) => x.length - x.trimStart().length)); + const dedented = lines.map((x) => x.slice(minIndent)).map((x) => " ".repeat(this.indent * 2) + x); + for (const line of dedented) { + this.content.push(line); + } + } + compile() { + const F = Function; + const content = this?.content ?? [``]; + const factory = new F(...Object.keys(this.closed), `return function (${this.args.join(", ")}) {\n${content.join("\n")}\n};`); + return factory(...Object.values(this.closed)); + } +} + + + +/* Computing the message eagerly is expensive (pretty-printed JSON of all + * issues), so defer it until first read. The accessor functions and + * descriptors are shared across instances to keep error construction + * cheap; the computed message is cached on the internals object. The + * setter preserves plain assignment semantics for consumers that + * overwrite `message`. */ +function _getMessage() { + const internals = this._zod; + internals.message ?? (internals.message = JSON.stringify(internals.def, jsonStringifyReplacer, 2)); + return internals.message; +} +function _setMessage(value) { + this._zod.message = value; +} +const _messageDesc = { + get: _getMessage, + set: _setMessage, + enumerable: true, + configurable: true, +}; +const errors_zodDesc = { value: undefined, enumerable: false }; +const _issuesDesc = { value: undefined, enumerable: false }; +/* Prototypes that already carry the lazy `toString`. Seeded with the + * intrinsics so that `init` on a foreign object — it accepts any object — + * can never install an accessor onto a prototype we do not own. */ +const _installedToString = /* @__PURE__ */ new WeakSet([Object.prototype, Error.prototype]); +const errors_initializer = (inst, def) => { + inst.name = "$ZodError"; + errors_zodDesc.value = inst._zod; + Object.defineProperty(inst, "_zod", errors_zodDesc); + _issuesDesc.value = def; + Object.defineProperty(inst, "issues", _issuesDesc); + // Clear the shared slots; a retained `value` pins the last error's issues. + errors_zodDesc.value = undefined; + _issuesDesc.value = undefined; + Object.defineProperty(inst, "message", _messageDesc); + /* `toString` lives as a non-enumerable lazy getter on the shared + * prototype; on first access it caches a per-instance closure so + * detached usage still works. */ + const proto = Object.getPrototypeOf(inst); + if (!_installedToString.has(proto)) { + _installedToString.add(proto); + Object.defineProperty(proto, "toString", { + configurable: true, + enumerable: false, + get() { + const value = () => this.message; + Object.defineProperty(this, "toString", { value, configurable: true, writable: true }); + return value; + }, + set(value) { + Object.defineProperty(this, "toString", { value, configurable: true, writable: true }); + }, + }); + } +}; +const $ZodError = $constructor("$ZodError", errors_initializer); +const $ZodRealError = $constructor("$ZodError", errors_initializer, undefined, { + Parent: Error, +}); +/** Get-or-create `obj[key]` as an own data property. A path segment naming an inherited member + * ("toString", "constructor") would otherwise read through to the prototype, and assigning + * "__proto__" would hit the setter instead of creating a key. */ +function errors_node(obj, key, make) { + if (!Object.prototype.hasOwnProperty.call(obj, key)) { + if (key === "__proto__") { + Object.defineProperty(obj, key, { value: make(), writable: true, enumerable: true, configurable: true }); + } + else { + obj[key] = make(); + } + } + return obj[key]; +} +function flattenError(error, mapper = (issue) => issue.message) { + const fieldErrors = {}; + const formErrors = []; + for (const sub of error.issues) { + if (sub.path.length > 0) { + errors_node(fieldErrors, sub.path[0], () => []).push(mapper(sub)); + } + else { + formErrors.push(mapper(sub)); + } + } + return { formErrors, fieldErrors }; +} +function formatError(error, mapper = (issue) => issue.message) { + const fieldErrors = { _errors: [] }; + const processError = (error, path = []) => { + for (const issue of error.issues) { + if (issue.code === "invalid_union" && issue.errors.length) { + issue.errors.map((issues) => processError({ issues }, [...path, ...issue.path])); + } + else if (issue.code === "invalid_key") { + processError({ issues: issue.issues }, [...path, ...issue.path]); + } + else if (issue.code === "invalid_element") { + processError({ issues: issue.issues }, [...path, ...issue.path]); + } + else { + const fullpath = [...path, ...issue.path]; + if (fullpath.length === 0) { + fieldErrors._errors.push(mapper(issue)); + } + else { + let curr = fieldErrors; + let i = 0; + while (i < fullpath.length) { + const el = fullpath[i]; + const terminal = i === fullpath.length - 1; + // `_errors` is reserved by this legacy format, so merge a matching path segment into the current node instead of treating its array as a child. + if (el === "_errors") { + if (terminal) + curr._errors.push(mapper(issue)); + i++; + continue; + } + // A path element may collide with an inherited property name such as + // "__proto__" or "constructor". Truthiness checks read the prototype + // (so no node is created, then ._errors.push throws), and bracket + // assignment of "__proto__" hits the setter instead of creating an + // own key. Guard the read with hasOwnProperty and create the node + // with defineProperty so any path element becomes a real own key. + if (!Object.prototype.hasOwnProperty.call(curr, el)) { + Object.defineProperty(curr, el, { + value: { _errors: [] }, + enumerable: true, + writable: true, + configurable: true, + }); + } + const node = curr[el]; + if (terminal) { + node._errors.push(mapper(issue)); + } + curr = node; + i++; + } + } + } + } + }; + processError(error); + return fieldErrors; +} +function treeifyError(error, mapper = (issue) => issue.message) { + const result = { errors: [] }; + const processError = (error, path = []) => { + var _a; + for (const issue of error.issues) { + if (issue.code === "invalid_union" && issue.errors.length) { + // regular union error + issue.errors.map((issues) => processError({ issues }, [...path, ...issue.path])); + } + else if (issue.code === "invalid_key") { + processError({ issues: issue.issues }, [...path, ...issue.path]); + } + else if (issue.code === "invalid_element") { + processError({ issues: issue.issues }, [...path, ...issue.path]); + } + else { + const fullpath = [...path, ...issue.path]; + if (fullpath.length === 0) { + result.errors.push(mapper(issue)); + continue; + } + let curr = result; + let i = 0; + while (i < fullpath.length) { + const el = fullpath[i]; + const terminal = i === fullpath.length - 1; + if (typeof el === "string") { + curr.properties ?? (curr.properties = {}); + // el may collide with an inherited property name ("__proto__", + // "constructor", ...); ??= reads the prototype so the node is never + // created and curr.errors.push throws. Guard with hasOwnProperty and + // create the node with defineProperty so "__proto__" becomes a real + // own key rather than invoking the prototype setter. + if (!Object.prototype.hasOwnProperty.call(curr.properties, el)) { + Object.defineProperty(curr.properties, el, { + value: { errors: [] }, + enumerable: true, + writable: true, + configurable: true, + }); + } + curr = curr.properties[el]; + } + else { + curr.items ?? (curr.items = []); + (_a = curr.items)[el] ?? (_a[el] = { errors: [] }); + curr = curr.items[el]; + } + if (terminal) { + curr.errors.push(mapper(issue)); + } + i++; + } + } + } + }; + processError(error); + return result; +} +/** Format a ZodError as a human-readable string in the following form. + * + * From + * + * ```ts + * ZodError { + * issues: [ + * { + * expected: 'string', + * code: 'invalid_type', + * path: [ 'username' ], + * message: 'Invalid input: expected string' + * }, + * { + * expected: 'number', + * code: 'invalid_type', + * path: [ 'favoriteNumbers', 1 ], + * message: 'Invalid input: expected number' + * } + * ]; + * } + * ``` + * + * to + * + * ``` + * username + * ✖ Expected number, received string at "username + * favoriteNumbers[0] + * ✖ Invalid input: expected number + * ``` + */ +function toDotPath(_path) { + const segs = []; + const path = _path.map((seg) => (typeof seg === "object" ? seg.key : seg)); + for (const seg of path) { + if (typeof seg === "number") + segs.push(`[${seg}]`); + else if (typeof seg === "symbol") + segs.push(`[${JSON.stringify(String(seg))}]`); + else if (/[^\w$]/.test(seg)) + segs.push(`[${JSON.stringify(seg)}]`); + else { + if (segs.length) + segs.push("."); + segs.push(seg); + } + } + return segs.join(""); +} +function prettifyError(error) { + const lines = []; + // sort by path length + const issues = [...error.issues].sort((a, b) => (a.path ?? []).length - (b.path ?? []).length); + // Process each issue + for (const issue of issues) { + lines.push(`✖ ${issue.message}`); + if (issue.path?.length) + lines.push(` → at ${toDotPath(issue.path)}`); + } + // Convert Map to formatted string + return lines.join("\n"); +} + + + + +// Always both keys, so the `_params` read site in `_parse` sees one object shape rather than two. +function finalizeParams(callee, params) { + return { callee: params?.callee ?? callee, Err: params?.Err }; +} +const parse_parse = (_Err) => { + const fn = (schema, value, _ctx, _params) => { + const ctx = _ctx ? { ..._ctx, async: false } : { async: false }; + const result = schema._zod.run({ value, issues: [] }, ctx); + if (result instanceof Promise) { + throw new $ZodAsyncError(); + } + if (result.issues.length) { + const e = new (_params?.Err ?? _Err)(result.issues.map((iss) => finalizeIssue(iss, ctx, core_config()))); + captureStackTrace(e, _params?.callee ?? fn); + throw e; + } + return result.value; + }; + return fn; +}; +const core_parse_parse = /* @__PURE__*/ parse_parse($ZodRealError); +const parse_parseAsync = (_Err) => { + const fn = async (schema, value, _ctx, params) => { + const ctx = _ctx ? { ..._ctx, async: true } : { async: true }; + let result = schema._zod.run({ value, issues: [] }, ctx); + if (result instanceof Promise) + result = await result; + if (result.issues.length) { + const e = new (params?.Err ?? _Err)(result.issues.map((iss) => finalizeIssue(iss, ctx, core_config()))); + captureStackTrace(e, params?.callee ?? fn); + throw e; + } + return result.value; + }; + return fn; +}; +const core_parse_parseAsync = /* @__PURE__*/ parse_parseAsync($ZodRealError); +const _safeParse = (_Err) => (schema, value, _ctx) => { + const ctx = _ctx ? { ..._ctx, async: false } : { async: false }; + const result = schema._zod.run({ value, issues: [] }, ctx); + if (result instanceof Promise) { + throw new $ZodAsyncError(); + } + return result.issues.length + ? { + success: false, + error: new (_Err ?? $ZodError)(result.issues.map((iss) => finalizeIssue(iss, ctx, core_config()))), + } + : { success: true, data: result.value }; +}; +const safeParse = /* @__PURE__*/ _safeParse($ZodRealError); +const _safeParseAsync = (_Err) => async (schema, value, _ctx) => { + const ctx = _ctx ? { ..._ctx, async: true } : { async: true }; + let result = schema._zod.run({ value, issues: [] }, ctx); + if (result instanceof Promise) + result = await result; + return result.issues.length + ? { + success: false, + error: new _Err(result.issues.map((iss) => finalizeIssue(iss, ctx, core_config()))), + } + : { success: true, data: result.value }; +}; +const safeParseAsync = /* @__PURE__*/ _safeParseAsync($ZodRealError); +// registry mirrors of the compiler's sentinels, so this module never imports the compiler +const COMPILE_INVALID = /* @__PURE__ */ (/* unused pure expression or super */ null && (Symbol.for("zod.compile.invalid"))); +const COMPILE_FALLBACK = /* @__PURE__ */ (/* unused pure expression or super */ null && (Symbol.for("zod.compile.fallback"))); +// Deliberately tiny, because v8 will not inline a body carrying the fallback's object literals and throw. Everything that is not the compiled happy path lives in validateFallback, and that split is worth ~35% on a compiled schema. +const parse_validate = ((schema, value, _ctx) => { + const validator = schema._zod.bag.validator; + if (validator !== undefined && validator(value) !== COMPILE_INVALID) + return true; + return validateFallback(schema, value, _ctx); +}); +function validateFallback(schema, value, _ctx) { + const ctx = _ctx ? { ..._ctx, async: false } : { async: false }; + const fallbackRun = schema._zod.bag.fallbackRun; + let result; + if (fallbackRun) { + // skip nested fast paths on the fallback, so user callbacks keep the at-most-twice bound + ctx[COMPILE_FALLBACK] = true; + result = fallbackRun({ value, issues: [] }, ctx); + } + else { + result = schema._zod.run({ value, issues: [] }, ctx); + } + if (result instanceof Promise) { + throw new core.$ZodAsyncError(); + } + return result.issues.length === 0; +} +// no fast path: the compiler keeps async parses on the runtime, because a promise-returning callback that is not declared async compiles to a throw +const parse_validateAsync = async (schema, value, _ctx) => { + const ctx = _ctx ? { ..._ctx, async: true } : { async: true }; + let result = schema._zod.run({ value, issues: [] }, ctx); + if (result instanceof Promise) + result = await result; + return result.issues.length === 0; +}; +const parse_encode = (_Err) => { + const parse = parse_parse(_Err); + const fn = (schema, value, _ctx, _params) => { + const ctx = _ctx ? { ..._ctx, direction: "backward" } : { direction: "backward" }; + return parse(schema, value, ctx, finalizeParams(fn, _params)); + }; + return fn; +}; +const encode = /* @__PURE__*/ parse_encode($ZodRealError); +const parse_decode = (_Err) => { + const parse = parse_parse(_Err); + const fn = (schema, value, _ctx, _params) => { + return parse(schema, value, _ctx, finalizeParams(fn, _params)); + }; + return fn; +}; +const decode = /* @__PURE__*/ parse_decode($ZodRealError); +const parse_encodeAsync = (_Err) => { + const parseAsync = parse_parseAsync(_Err); + const fn = async (schema, value, _ctx, _params) => { + const ctx = _ctx ? { ..._ctx, direction: "backward" } : { direction: "backward" }; + return (await parseAsync(schema, value, ctx, finalizeParams(fn, _params))); + }; + return fn; +}; +const encodeAsync = /* @__PURE__*/ parse_encodeAsync($ZodRealError); +const parse_decodeAsync = (_Err) => { + const parseAsync = parse_parseAsync(_Err); + const fn = async (schema, value, _ctx, _params) => { + return await parseAsync(schema, value, _ctx, finalizeParams(fn, _params)); + }; + return fn; +}; +const decodeAsync = /* @__PURE__*/ parse_decodeAsync($ZodRealError); +const _safeEncode = (_Err) => (schema, value, _ctx) => { + const ctx = _ctx ? { ..._ctx, direction: "backward" } : { direction: "backward" }; + return _safeParse(_Err)(schema, value, ctx); +}; +const safeEncode = /* @__PURE__*/ _safeEncode($ZodRealError); +const _safeDecode = (_Err) => (schema, value, _ctx) => { + return _safeParse(_Err)(schema, value, _ctx); +}; +const safeDecode = /* @__PURE__*/ _safeDecode($ZodRealError); +const _safeEncodeAsync = (_Err) => async (schema, value, _ctx) => { + const ctx = _ctx ? { ..._ctx, direction: "backward" } : { direction: "backward" }; + return _safeParseAsync(_Err)(schema, value, ctx); +}; +const safeEncodeAsync = /* @__PURE__*/ _safeEncodeAsync($ZodRealError); +const _safeDecodeAsync = (_Err) => async (schema, value, _ctx) => { + return _safeParseAsync(_Err)(schema, value, _ctx); +}; +const safeDecodeAsync = /* @__PURE__*/ _safeDecodeAsync($ZodRealError); + +const versions_version = { + major: 4, + minor: 5, + patch: 4, +}; + + + + + + + + +const $ZodType = /*@__PURE__*/ $constructor("$ZodType", (inst, def) => { + var _a; + inst ?? (inst = {}); + inst._zod.def = def; // set _def property + inst._zod.bag = inst._zod.bag || {}; // initialize _bag object + inst._zod.version = versions_version; + const defChecks = inst._zod.def.checks; + // if inst is itself a checks.$ZodCheck, run it as a check + const checks = inst._zod.traits.has("$ZodCheck") + ? [inst, ...(defChecks ?? [])] + : defChecks?.length + ? [...defChecks] + : []; + for (const ch of checks) { + for (const fn of ch._zod.onattach) { + fn(inst); + } + } + if (checks.length === 0) { + // deferred initializer inst._zod.parse is not yet defined + (_a = inst._zod).deferred ?? (_a.deferred = []); + inst._zod.deferred?.push(() => { + inst._zod.run = inst._zod.parse; + }); + } + else { + const runChecks = (payload, checks, ctx) => { + if (payload.memo) + return payload; + let isAborted = aborted(payload); + let asyncResult; + for (const ch of checks) { + if (ch._zod.def.when) { + if (explicitlyAborted(payload)) + continue; + const shouldRun = ch._zod.def.when(payload); + if (!shouldRun) + continue; + } + else if (isAborted) { + continue; + } + const currLen = payload.issues.length; + const _ = ch._zod.check(payload); + if (_ instanceof Promise && ctx?.async === false) { + throw new $ZodAsyncError(); + } + if (asyncResult || _ instanceof Promise) { + asyncResult = (asyncResult ?? Promise.resolve()).then(async () => { + await _; + const nextLen = payload.issues.length; + if (nextLen === currLen) + return; + attachSchema(payload.issues, currLen, inst); + if (!isAborted) + isAborted = aborted(payload, currLen); + }); + } + else { + const nextLen = payload.issues.length; + if (nextLen === currLen) + continue; + attachSchema(payload.issues, currLen, inst); + if (!isAborted) + isAborted = aborted(payload, currLen); + } + } + if (asyncResult) { + return asyncResult.then(() => { + return payload; + }); + } + return payload; + }; + const handleCanaryResult = (canary, payload, ctx) => { + // abort if the canary is aborted + if (aborted(canary)) { + canary.aborted = true; + return canary; + } + // run checks first, then + const checkResult = runChecks(payload, checks, ctx); + if (checkResult instanceof Promise) { + if (ctx.async === false) + throw new $ZodAsyncError(); + return checkResult.then((checkResult) => inst._zod.parse(checkResult, ctx)); + } + return inst._zod.parse(checkResult, ctx); + }; + inst._zod.run = (payload, ctx) => { + if (ctx.skipChecks) { + return inst._zod.parse(payload, ctx); + } + if (ctx.direction === "backward") { + // run canary initial pass (no checks) + const canary = inst._zod.parse({ value: payload.value, issues: [] }, { ...ctx, skipChecks: true }); + if (canary instanceof Promise) { + return canary.then((canary) => { + return handleCanaryResult(canary, payload, ctx); + }); + } + return handleCanaryResult(canary, payload, ctx); + } + // forward + const result = inst._zod.parse(payload, ctx); + if (result instanceof Promise) { + if (ctx.async === false) + throw new $ZodAsyncError(); + return result.then((result) => runChecks(result, checks, ctx)); + } + return runChecks(result, checks, ctx); + }; + } +}, { + // Wrappers extend this by installing a richer factory over it; reading it eagerly would defeat the laziness. + get "~standard"() { + return hide(this, "~standard", standardProps(this)); + }, + set "~standard"(value) { + util_own(this, "~standard", value); + }, +}); +/** The Standard Schema surface for `inst`. Shared so wrappers can extend it without forcing it. */ +const toStandardResult = (r) => r.success ? { value: r.data } : { issues: r.error?.issues }; +function standardProps(inst) { + return { + validate: (value) => { + try { + return toStandardResult(safeParse(inst, value)); + } + catch (_) { + return safeParseAsync(inst, value).then(toStandardResult); + } + }, + vendor: "zod", + version: 1, + }; +} + +const $ZodString = /*@__PURE__*/ $constructor("$ZodString", (inst, def) => { + $ZodType.init(inst, def); + inst._zod.pattern = [...(inst?._zod.bag?.patterns ?? [])].pop() ?? regexes_string(inst._zod.bag); + inst._zod.parse = (payload, _) => { + if (def.coerce) + try { + payload.value = String(payload.value); + } + catch (_) { } + if (typeof payload.value === "string") + return payload; + payload.issues.push({ + expected: "string", + code: "invalid_type", + input: payload.value, + inst, + }); + return payload; + }; +}); +const $ZodStringFormat = /*@__PURE__*/ $constructor("$ZodStringFormat", (inst, def) => { + // check initialization must come first + $ZodCheckStringFormat.init(inst, def); + $ZodString.init(inst, def); +}); +const $ZodGUID = /*@__PURE__*/ $constructor("$ZodGUID", (inst, def) => { + def.pattern ?? (def.pattern = guid); + $ZodStringFormat.init(inst, def); +}); +const $ZodUUID = /*@__PURE__*/ $constructor("$ZodUUID", (inst, def) => { + if (def.version) { + const versionMap = { + v1: 1, + v2: 2, + v3: 3, + v4: 4, + v5: 5, + v6: 6, + v7: 7, + v8: 8, + }; + const v = versionMap[def.version]; + if (v === undefined) + throw new Error(`Invalid UUID version: "${def.version}"`); + def.pattern ?? (def.pattern = uuid(v)); + } + else + def.pattern ?? (def.pattern = uuid()); + $ZodStringFormat.init(inst, def); +}); +const $ZodEmail = /*@__PURE__*/ $constructor("$ZodEmail", (inst, def) => { + def.pattern ?? (def.pattern = email); + $ZodStringFormat.init(inst, def); +}); +/** The `://` guard rejected the input before the URL constructor saw it. */ +const URL_BAD_FORMAT = 1; +/** The URL constructor rejected the input. */ +const URL_UNPARSEABLE = 2; +/** Parses a URL for `$ZodURL`, applying the one guard the URL constructor cannot express. Returns the parsed URL, or a code naming the stage that rejected it — the runtime needs that distinction to pick an issue note, and compiled code only needs to know it is not a URL. */ +function parseURLObject(trimmed, def) { + // When normalize is off, require :// for http/https URLs. This prevents strings like "http:example.com" or "https:/path" from being silently accepted + if (!def.normalize && def.protocol?.source === httpProtocol.source && !/^https?:\/\//i.test(trimmed)) { + return URL_BAD_FORMAT; + } + try { + // @ts-ignore + return new URL(trimmed); + } + catch { + return URL_UNPARSEABLE; + } +} +const asciiTabOrNewline = /[\t\n\r]/g; +/** The URL parser deletes every ASCII tab, LF and CR from its input before it parses, so `new URL("https://exa\nmple.com")` reports on `example.com`. Applying the same deletion to the returned value closes the half of that divergence which can move the host; the parser's other rewrite, stripping C0 controls at the edges, cannot. */ +function stripTabAndNewline(value) { + return value.replace(asciiTabOrNewline, ""); +} +function urlHostnameOk(url, hostname) { + hostname.lastIndex = 0; + return hostname.test(url.hostname); +} +function urlProtocolOk(url, protocol) { + protocol.lastIndex = 0; + return protocol.test(url.protocol.endsWith(":") ? url.protocol.slice(0, -1) : url.protocol); +} +const $ZodURL = /*@__PURE__*/ $constructor("$ZodURL", (inst, def) => { + $ZodStringFormat.init(inst, def); + inst._zod.check = (payload) => { + try { + // Trim whitespace from input + const trimmed = payload.value.trim(); + const url = parseURLObject(trimmed, def); + if (url === URL_BAD_FORMAT) { + payload.issues.push({ + code: "invalid_format", + format: "url", + note: "Invalid URL format", + input: payload.value, + inst, + continue: !def.abort, + }); + return; + } + if (url === URL_UNPARSEABLE) { + payload.issues.push({ + code: "invalid_format", + format: "url", + input: payload.value, + inst, + continue: !def.abort, + }); + return; + } + if (def.hostname && !urlHostnameOk(url, def.hostname)) { + payload.issues.push({ + code: "invalid_format", + format: "url", + note: "Invalid hostname", + pattern: def.hostname.source, + input: payload.value, + inst, + continue: !def.abort, + }); + } + if (def.protocol && !urlProtocolOk(url, def.protocol)) { + payload.issues.push({ + code: "invalid_format", + format: "url", + note: "Invalid protocol", + pattern: def.protocol.source, + input: payload.value, + inst, + continue: !def.abort, + }); + } + // Set the output value based on normalize flag + payload.value = def.normalize ? url.href : stripTabAndNewline(trimmed); + return; + } + catch (_) { + payload.issues.push({ + code: "invalid_format", + format: "url", + input: payload.value, + inst, + continue: !def.abort, + }); + } + }; +}); +const $ZodEmoji = /*@__PURE__*/ $constructor("$ZodEmoji", (inst, def) => { + def.pattern ?? (def.pattern = emoji()); + $ZodStringFormat.init(inst, def); +}); +const $ZodNanoID = /*@__PURE__*/ $constructor("$ZodNanoID", (inst, def) => { + if (def.length !== undefined && (!Number.isInteger(def.length) || def.length < 1)) + throw new Error(`Invalid nanoid length: ${def.length}`); + def.pattern ?? (def.pattern = def.length === undefined ? nanoid : nanoidOfLength(def.length)); + $ZodStringFormat.init(inst, def); +}); +/** + * @deprecated CUID v1 is deprecated by its authors due to information leakage + * (timestamps embedded in the id). Use {@link $ZodCUID2} instead. + * See https://github.com/paralleldrive/cuid. + */ +const $ZodCUID = /*@__PURE__*/ $constructor("$ZodCUID", (inst, def) => { + def.pattern ?? (def.pattern = cuid); + $ZodStringFormat.init(inst, def); +}); +const $ZodCUID2 = /*@__PURE__*/ $constructor("$ZodCUID2", (inst, def) => { + def.pattern ?? (def.pattern = cuid2); + $ZodStringFormat.init(inst, def); +}); +const $ZodULID = /*@__PURE__*/ $constructor("$ZodULID", (inst, def) => { + def.pattern ?? (def.pattern = ulid); + $ZodStringFormat.init(inst, def); +}); +const $ZodXID = /*@__PURE__*/ $constructor("$ZodXID", (inst, def) => { + def.pattern ?? (def.pattern = xid); + $ZodStringFormat.init(inst, def); +}); +const $ZodKSUID = /*@__PURE__*/ $constructor("$ZodKSUID", (inst, def) => { + def.pattern ?? (def.pattern = ksuid); + $ZodStringFormat.init(inst, def); +}); +const $ZodISODateTime = /*@__PURE__*/ $constructor("$ZodISODateTime", (inst, def) => { + def.pattern ?? (def.pattern = datetime(def)); + $ZodStringFormat.init(inst, def); + // these two drop the offset or seconds `date-time` requires — on the bag not the def, since `z.string().check(...)` lands the format on a different schema + if (def.local || def.precision === -1) { + inst._zod.bag.laxFormat = true; + inst._zod.onattach.push((s) => { + s._zod.bag.laxFormat = true; + }); + } +}); +const $ZodISODate = /*@__PURE__*/ $constructor("$ZodISODate", (inst, def) => { + def.pattern ?? (def.pattern = regexes_date); + $ZodStringFormat.init(inst, def); +}); +const $ZodISOTime = /*@__PURE__*/ $constructor("$ZodISOTime", (inst, def) => { + def.pattern ?? (def.pattern = regexes_time(def)); + $ZodStringFormat.init(inst, def); +}); +const $ZodISODuration = /*@__PURE__*/ $constructor("$ZodISODuration", (inst, def) => { + def.pattern ?? (def.pattern = duration); + $ZodStringFormat.init(inst, def); +}); +const $ZodIPv4 = /*@__PURE__*/ $constructor("$ZodIPv4", (inst, def) => { + def.pattern ?? (def.pattern = ipv4); + $ZodStringFormat.init(inst, def); + inst._zod.bag.format = `ipv4`; +}); +/** An IPv6 address is written with hex digits, colons and dots, and nothing else. The guard is what makes the check below an IPv6 check: `new URL("http://[...]")` parses an authority, not an address, so `@` and `\` re-delimit it and `"::@1\\"` validates against the host `0.0.0.1`. The URL parser also deletes ASCII tab, LF and CR rather than failing, which is how `"::1\n"` validated as `::1`. */ +const ipv6Alphabet = /^[0-9a-fA-F:.]+$/; +function isValidIPv6(value) { + if (!ipv6Alphabet.test(value)) + return false; + try { + // @ts-ignore + new URL(`http://[${value}]`); + return true; + } + catch { + return false; + } +} +const $ZodIPv6 = /*@__PURE__*/ $constructor("$ZodIPv6", (inst, def) => { + def.pattern ?? (def.pattern = regexes_ipv6); + $ZodStringFormat.init(inst, def); + inst._zod.bag.format = `ipv6`; + inst._zod.check = (payload) => { + if (!isValidIPv6(payload.value)) { + payload.issues.push({ + code: "invalid_format", + format: "ipv6", + input: payload.value, + inst, + continue: !def.abort, + }); + } + }; +}); +const $ZodMAC = /*@__PURE__*/ (/* unused pure expression or super */ null && (core.$constructor("$ZodMAC", (inst, def) => { + def.pattern ?? (def.pattern = regexes.mac(def.delimiter)); + $ZodStringFormat.init(inst, def); + inst._zod.bag.format = `mac`; +}))); +const $ZodCIDRv4 = /*@__PURE__*/ $constructor("$ZodCIDRv4", (inst, def) => { + def.pattern ?? (def.pattern = cidrv4); + $ZodStringFormat.init(inst, def); +}); +function isValidCIDRv6(value) { + const parts = value.split("/"); + if (parts.length !== 2) + return false; + const [address, prefix] = parts; + if (!prefix) + return false; + const prefixNum = Number(prefix); + if (`${prefixNum}` !== prefix) + return false; + if (prefixNum < 0 || prefixNum > 128) + return false; + return isValidIPv6(address); +} +const $ZodCIDRv6 = /*@__PURE__*/ $constructor("$ZodCIDRv6", (inst, def) => { + def.pattern ?? (def.pattern = cidrv6); // not used for validation + $ZodStringFormat.init(inst, def); + inst._zod.check = (payload) => { + if (!isValidCIDRv6(payload.value)) { + payload.issues.push({ + code: "invalid_format", + format: "cidrv6", + input: payload.value, + inst, + continue: !def.abort, + }); + } + }; +}); +////////////////////////////// ZodBase64 ////////////////////////////// +function isValidBase64(data) { + if (data === "") + return true; + // atob ignores whitespace, so reject it up front. + if (/\s/.test(data)) + return false; + if (data.length % 4 !== 0) + return false; + try { + // @ts-ignore + atob(data); + return true; + } + catch { + return false; + } +} +const $ZodBase64 = /*@__PURE__*/ $constructor("$ZodBase64", (inst, def) => { + def.pattern ?? (def.pattern = regexes_base64); + $ZodStringFormat.init(inst, def); + inst._zod.bag.contentEncoding = "base64"; + inst._zod.check = (payload) => { + if (isValidBase64(payload.value)) + return; + payload.issues.push({ + code: "invalid_format", + format: "base64", + input: payload.value, + inst, + continue: !def.abort, + }); + }; +}); +////////////////////////////// ZodBase64 ////////////////////////////// +function isValidBase64URL(data) { + if (!regexes_base64url.test(data)) + return false; + const base64 = data.replace(/[-_]/g, (c) => (c === "-" ? "+" : "/")); + const padded = base64.padEnd(Math.ceil(base64.length / 4) * 4, "="); + return isValidBase64(padded); +} +const $ZodBase64URL = /*@__PURE__*/ $constructor("$ZodBase64URL", (inst, def) => { + def.pattern ?? (def.pattern = regexes_base64url); + $ZodStringFormat.init(inst, def); + inst._zod.bag.contentEncoding = "base64url"; + inst._zod.check = (payload) => { + if (isValidBase64URL(payload.value)) + return; + payload.issues.push({ + code: "invalid_format", + format: "base64url", + input: payload.value, + inst, + continue: !def.abort, + }); + }; +}); +const $ZodE164 = /*@__PURE__*/ $constructor("$ZodE164", (inst, def) => { + def.pattern ?? (def.pattern = e164); + $ZodStringFormat.init(inst, def); +}); +////////////////////////////// ZodCreditCard ////////////////////////////// +const CC_SANITIZE = /[- ]/g; +/** Luhn checksum on a digit-only string. Adapted from valibot (MIT). */ +function isLuhnAlgo(digits) { + let length = digits.length; + let bit = 1; + let sum = 0; + while (length) { + const value = +digits[--length]; + bit ^= 1; + sum += bit ? [0, 2, 4, 6, 8, 1, 3, 5, 7, 9][value] : value; + } + return sum % 10 === 0; +} +function isValidCreditCard(input) { + if (!regexes.creditCard.test(input)) + return false; + return isLuhnAlgo(input.replace(CC_SANITIZE, "")); +} +const $ZodCreditCard = /*@__PURE__*/ (/* unused pure expression or super */ null && (core.$constructor("$ZodCreditCard", (inst, def) => { + // Shape only — the Luhn check below is not expressible as a pattern, so consumers of `pattern` (JSON Schema, template literals) get the length and separator rules alone. + def.pattern ?? (def.pattern = regexes.creditCard); + $ZodStringFormat.init(inst, def); + inst._zod.check = (payload) => { + if (isValidCreditCard(payload.value)) + return; + payload.issues.push({ + code: "invalid_format", + format: "credit_card", + input: payload.value, + inst, + continue: !def.abort, + }); + }; +}))); +////////////////////////////// ZodJWT ////////////////////////////// +function isValidJWT(token, algorithm = null) { + try { + const tokensParts = token.split("."); + if (tokensParts.length !== 3) + return false; + const [header] = tokensParts; + if (!header) + return false; + // @ts-ignore + const parsedHeader = JSON.parse(atob(header)); + if ("typ" in parsedHeader && parsedHeader?.typ !== "JWT") + return false; + if (!parsedHeader.alg) + return false; + if (algorithm && (!("alg" in parsedHeader) || parsedHeader.alg !== algorithm)) + return false; + return true; + } + catch { + return false; + } +} +const $ZodJWT = /*@__PURE__*/ $constructor("$ZodJWT", (inst, def) => { + $ZodStringFormat.init(inst, def); + inst._zod.check = (payload) => { + if (isValidJWT(payload.value, def.alg)) + return; + payload.issues.push({ + code: "invalid_format", + format: "jwt", + input: payload.value, + inst, + continue: !def.abort, + }); + }; +}); +const $ZodCustomStringFormat = /*@__PURE__*/ (/* unused pure expression or super */ null && (core.$constructor("$ZodCustomStringFormat", (inst, def) => { + $ZodStringFormat.init(inst, def); + inst._zod.check = (payload) => { + if (def.fn(payload.value)) + return; + payload.issues.push({ + code: "invalid_format", + format: def.format, + input: payload.value, + inst, + continue: !def.abort, + }); + }; +}))); +const $ZodNumber = /*@__PURE__*/ $constructor("$ZodNumber", (inst, def) => { + $ZodType.init(inst, def); + inst._zod.pattern = inst._zod.bag.pattern ?? number; + inst._zod.parse = (payload, _ctx) => { + if (def.coerce) + try { + payload.value = Number(payload.value); + } + catch (_) { } + const input = payload.value; + if (typeof input === "number" && !Number.isNaN(input) && Number.isFinite(input)) { + return payload; + } + const received = typeof input === "number" + ? Number.isNaN(input) + ? "NaN" + : !Number.isFinite(input) + ? String(input) + : undefined + : undefined; + payload.issues.push({ + expected: "number", + code: "invalid_type", + input, + inst, + ...(received ? { received } : {}), + }); + return payload; + }; +}); +const $ZodNumberFormat = /*@__PURE__*/ $constructor("$ZodNumberFormat", (inst, def) => { + $ZodCheckNumberFormat.init(inst, def); + $ZodNumber.init(inst, def); // no format checks +}); +const $ZodBoolean = /*@__PURE__*/ $constructor("$ZodBoolean", (inst, def) => { + $ZodType.init(inst, def); + inst._zod.pattern = regexes_boolean; + inst._zod.parse = (payload, _ctx) => { + if (def.coerce) + try { + payload.value = Boolean(payload.value); + } + catch (_) { } + const input = payload.value; + if (typeof input === "boolean") + return payload; + payload.issues.push({ + expected: "boolean", + code: "invalid_type", + input, + inst, + }); + return payload; + }; +}); +const $ZodBigInt = /*@__PURE__*/ (/* unused pure expression or super */ null && (core.$constructor("$ZodBigInt", (inst, def) => { + $ZodType.init(inst, def); + inst._zod.pattern = regexes.bigint; + inst._zod.parse = (payload, _ctx) => { + if (def.coerce) + try { + payload.value = BigInt(payload.value); + } + catch (_) { } + if (typeof payload.value === "bigint") + return payload; + payload.issues.push({ + expected: "bigint", + code: "invalid_type", + input: payload.value, + inst, + }); + return payload; + }; +}))); +const $ZodBigIntFormat = /*@__PURE__*/ (/* unused pure expression or super */ null && (core.$constructor("$ZodBigIntFormat", (inst, def) => { + checks.$ZodCheckBigIntFormat.init(inst, def); + $ZodBigInt.init(inst, def); // no format checks +}))); +const $ZodSymbol = /*@__PURE__*/ (/* unused pure expression or super */ null && (core.$constructor("$ZodSymbol", (inst, def) => { + $ZodType.init(inst, def); + inst._zod.parse = (payload, _ctx) => { + const input = payload.value; + if (typeof input === "symbol") + return payload; + payload.issues.push({ + expected: "symbol", + code: "invalid_type", + input, + inst, + }); + return payload; + }; +}))); +const $ZodUndefined = /*@__PURE__*/ (/* unused pure expression or super */ null && (core.$constructor("$ZodUndefined", (inst, def) => { + $ZodType.init(inst, def); + inst._zod.pattern = regexes.undefined; + inst._zod.values = new Set([undefined]); + inst._zod.parse = (payload, _ctx) => { + const input = payload.value; + if (typeof input === "undefined") + return payload; + payload.issues.push({ + expected: "undefined", + code: "invalid_type", + input, + inst, + }); + return payload; + }; +}))); +const $ZodNull = /*@__PURE__*/ $constructor("$ZodNull", (inst, def) => { + $ZodType.init(inst, def); + inst._zod.pattern = _null; + inst._zod.values = new Set([null]); + inst._zod.parse = (payload, _ctx) => { + const input = payload.value; + if (input === null) + return payload; + payload.issues.push({ + expected: "null", + code: "invalid_type", + input, + inst, + }); + return payload; + }; +}); +const $ZodAny = /*@__PURE__*/ $constructor("$ZodAny", (inst, def) => { + $ZodType.init(inst, def); + inst._zod.parse = (payload) => payload; +}); +const $ZodUnknown = /*@__PURE__*/ $constructor("$ZodUnknown", (inst, def) => { + $ZodType.init(inst, def); + inst._zod.parse = (payload) => payload; +}); +const $ZodNever = /*@__PURE__*/ $constructor("$ZodNever", (inst, def) => { + $ZodType.init(inst, def); + inst._zod.parse = (payload, _ctx) => { + payload.issues.push({ + expected: "never", + code: "invalid_type", + input: payload.value, + inst, + }); + return payload; + }; +}); +const $ZodVoid = /*@__PURE__*/ (/* unused pure expression or super */ null && (core.$constructor("$ZodVoid", (inst, def) => { + $ZodType.init(inst, def); + inst._zod.parse = (payload, _ctx) => { + const input = payload.value; + if (typeof input === "undefined") + return payload; + payload.issues.push({ + expected: "void", + code: "invalid_type", + input, + inst, + }); + return payload; + }; +}))); +const $ZodDate = /*@__PURE__*/ (/* unused pure expression or super */ null && (core.$constructor("$ZodDate", (inst, def) => { + $ZodType.init(inst, def); + inst._zod.parse = (payload, _ctx) => { + if (def.coerce) { + try { + payload.value = new Date(payload.value); + } + catch (_err) { } + } + const input = payload.value; + const isDate = input instanceof Date; + const isValidDate = isDate && !Number.isNaN(input.getTime()); + if (isValidDate) + return payload; + payload.issues.push({ + expected: "date", + code: "invalid_type", + input, + ...(isDate ? { received: "Invalid Date" } : {}), + inst, + }); + return payload; + }; +}))); +function handleArrayResult(result, final, index) { + if (result.issues.length) { + final.issues.push(...prefixIssues(index, result.issues)); + } + final.value[index] = result.value; +} +const $ZodArray = /*@__PURE__*/ $constructor("$ZodArray", (inst, def) => { + $ZodType.init(inst, def); + const memo = globalConfig.memoizer; + memo?.attach(inst); + inst._zod.parse = (payload, ctx) => { + const input = payload.value; + if (!Array.isArray(input)) { + payload.issues.push({ + expected: "array", + code: "invalid_type", + input, + inst, + }); + return payload; + } + payload.value = memo ? memo.alloc(inst, payload, Array(input.length), ctx) : Array(input.length); + const proms = []; + for (let i = 0; i < input.length; i++) { + const item = input[i]; + const result = def.element._zod.run({ + value: item, + issues: [], + }, ctx); + if (result instanceof Promise) { + proms.push(result.then((result) => handleArrayResult(result, payload, i))); + } + else { + handleArrayResult(result, payload, i); + } + } + if (proms.length) { + return Promise.all(proms).then(() => payload); + } + return payload; //handleArrayResultsAsync(parseResults, final); + }; +}); +function handlePropertyResult(result, final, key, input, optin, optout) { + const isPresent = key in input; + const isOptionalOut = optout === "optional"; + // The middle rung means "absence permitted, nothing supplied in its place", so an absent key contributes nothing — whatever the schema made of `undefined` is invented, not substituted. Only `optional` reaches this with a value: `defaulted` substitutes, and a schema that isn't optional-out has to keep the key. + if (!isPresent && isOptionalOut && optin === "optional") { + return; + } + if (result.issues.length) { + // For optional-in/out schemas, ignore errors on absent keys. + if (optin !== undefined && isOptionalOut && !isPresent) { + return; + } + final.issues.push(...prefixIssues(key, result.issues)); + } + if (!isPresent && optin === undefined) { + if (!result.issues.length) { + final.issues.push({ + code: "invalid_type", + expected: "nonoptional", + input: undefined, + path: [key], + }); + } + return; + } + if (result.value === undefined) { + if (isPresent) { + final.value[key] = undefined; + } + } + else { + final.value[key] = result.value; + } +} +// one shared instance; a fresh [] per schema cost 56 bytes retained +const NO_SYMBOL_KEYS = []; +function normalizeDef(def) { + const keys = Object.keys(def.shape); + const ownSymbols = Object.getOwnPropertySymbols(def.shape); + const symbolKeys = ownSymbols.length ? ownSymbols : NO_SYMBOL_KEYS; + // aliases `keys` when there are no symbols, so a string-only shape keeps one array + const allKeys = symbolKeys.length ? [...keys, ...symbolKeys] : keys; + for (const k of allKeys) { + if (!def.shape?.[k]?._zod?.traits?.has("$ZodType")) { + throw new Error(`Invalid element at key "${String(k)}": expected a Zod schema`); + } + } + const okeys = optionalKeys(def.shape); + return { + ...def, + allKeys, + symbolKeys, + // string-only: handleCatchall matches it against `for...in`, which never yields a symbol + keySet: new Set(keys), + numKeys: keys.length, + optionalKeys: new Set(okeys), + }; +} +function handleCatchall(proms, input, payload, ctx, def, inst) { + const unrecognized = []; + const keySet = def.keySet; + const _catchall = def.catchall._zod; + const t = _catchall.def.type; + const optin = _catchall.optin; + const optout = _catchall.optout; + for (const key in input) { + // Must precede the __proto__ branch: a declared key is not unrecognized, even though the shape loop deliberately strips __proto__ from the parsed output. + if (keySet.has(key)) + continue; + // Don't copy an undeclared __proto__ into the result; assignment to a plain {} would replace the result prototype. But in strict mode it is still an unknown key, so report it before skipping. + if (key === "__proto__") { + if (t === "never") + unrecognized.push(key); + continue; + } + if (t === "never") { + unrecognized.push(key); + continue; + } + const r = _catchall.run({ value: input[key], issues: [] }, ctx); + if (r instanceof Promise) { + proms.push(r.then((r) => handlePropertyResult(r, payload, key, input, optin, optout))); + } + else { + handlePropertyResult(r, payload, key, input, optin, optout); + } + } + if (unrecognized.length) { + payload.issues.push({ + code: "unrecognized_keys", + keys: unrecognized, + input, + inst, + // Describes the shape of the input, not the validity of the parsed value, so it never aborts. The parse still fails; the schema's own checks just get to run first, and an enclosing intersection can reconcile the key against a sibling operand. + continue: true, + }); + } + if (!proms.length) + return payload; + return Promise.all(proms).then(() => { + return payload; + }); +} +// Whichever object a def's `shape` currently answers from: the one the caller passed until the first read, the frozen copy after it. Keyed by def, so a def rebuilt by a builder is simply absent rather than inheriting the source's. Read its keys with `Object.keys`, which does not invoke them — that is what lets a discriminated union check its discriminator without resolving an option whose getters reference the union being constructed. +const propShapes = new WeakMap(); +const $ZodObject = /*@__PURE__*/ $constructor("$ZodObject", (inst, def) => { + // requires cast because technically $ZodObject doesn't extend + $ZodType.init(inst, def); + // const sh = def.shape; + const desc = Object.getOwnPropertyDescriptor(def, "shape"); + if (!desc?.get) { + const sh = def.shape; + propShapes.set(def, sh); + Object.defineProperty(def, "shape", { + get: () => { + const newSh = { ...sh }; + Object.defineProperty(def, "shape", { + value: newSh, + }); + propShapes.set(def, newSh); + return newSh; + }, + }); + } + const _normalized = util_cached(() => normalizeDef(def)); + defineLazyInternal(inst, "propValues", (zod) => { + const shape = zod.def.shape; + const propValues = {}; + for (const key in shape) { + const field = shape[key]._zod; + if (field.values) { + if (!Object.prototype.hasOwnProperty.call(propValues, key)) { + assignProp(propValues, key, new Set()); + } + for (const v of field.values) + propValues[key].add(v); + // An omittable slot reads back as undefined at a discriminator lookup, so it has to claim undefined: two options that can both omit the key are not discriminable on it. + if (field.optin !== undefined) + propValues[key].add(undefined); + } + } + return propValues; + }); + const isObject = util_isObject; + const catchall = def.catchall; + let value; + const memo = globalConfig.memoizer; + memo?.attach(inst); + inst._zod.parse = (payload, ctx) => { + value ?? (value = _normalized.value); + const input = payload.value; + if (!isObject(input)) { + payload.issues.push({ + expected: "object", + code: "invalid_type", + input, + inst, + }); + return payload; + } + payload.value = memo ? memo.alloc(inst, payload, {}, ctx) : {}; + const proms = []; + const shape = value.shape; + for (const key of value.allKeys) { + if (key === "__proto__") + continue; + const el = shape[key]; + const optin = el._zod.optin; + const optout = el._zod.optout; + const r = el._zod.run({ value: input[key], issues: [] }, ctx); + if (r instanceof Promise) { + proms.push(r.then((r) => handlePropertyResult(r, payload, key, input, optin, optout))); + } + else { + handlePropertyResult(r, payload, key, input, optin, optout); + } + } + if (!catchall) { + return proms.length ? Promise.all(proms).then(() => payload) : payload; + } + return handleCatchall(proms, input, payload, ctx, _normalized.value, inst); + }; +}); +const $ZodObjectJIT = /*@__PURE__*/ $constructor("$ZodObjectJIT", (inst, def) => { + // requires cast because technically $ZodObject doesn't extend + $ZodObject.init(inst, def); + const superParse = inst._zod.parse; + const _normalized = util_cached(() => normalizeDef(def)); + const memo = globalConfig.memoizer; + const generateFastpass = (shape) => { + const normalized = _normalized.value; + const syms = normalized.symbolKeys; + // a symbol has no source literal, so it is read as `syms[i]` off the closed-over scope + const doc = new Doc(["payload", "ctx"], { shape, inst, memo, syms }); + const parseStr = (k) => `shape[${k}]._zod.run({ value: input[${k}], issues: [] }, ctx)`; + // Prefixes in place, like util.prefixIssues does for every interpreted path. + const prefixStr = (id, k) => ` + for (let i = 0; i < ${id}.issues.length; i++) { + const iss = ${id}.issues[i]; + iss.path = iss.path ? [${k}, ...iss.path] : [${k}]; + payload.issues.push(iss); + }`; + doc.write(`const input = payload.value;`); + const ids = Object.create(null); + let counter = 0; + for (const key of normalized.allKeys) { + ids[key] = `key_${counter++}`; + } + // A: preserve key order { + doc.write(memo ? `const newResult = memo.alloc(inst, payload, {}, ctx);` : `const newResult = {};`); + for (const key of normalized.allKeys) { + if (key === "__proto__") + continue; + const id = ids[key]; + const k = typeof key === "symbol" ? `syms[${syms.indexOf(key)}]` : util_esc(key); + const isPresent = `${k} in input`; + const schema = shape[key]; + const optin = schema?._zod?.optin; + const isOptionalIn = optin !== undefined; + const isOptionalOut = schema?._zod?.optout === "optional"; + doc.write(`const ${id} = ${parseStr(k)};`); + if (isOptionalIn && isOptionalOut) { + // For optional-in/out schemas, ignore errors on absent keys — and, like the interpreted path, drop the value produced alongside them. The middle rung goes further: it permits absence without supplying anything in its place, so an absent key contributes nothing at all. + const assign = optin === "optional" ? `${id}_present` : `${id}.value !== undefined || ${id}_present`; + doc.write(` + const ${id}_present = ${isPresent}; + if (!${id}.issues.length || ${id}_present) { + if (${id}.issues.length) {${prefixStr(id, k)} + } + + if (${assign}) { + newResult[${k}] = ${id}.value; + } + } + + `); + } + else if (!isOptionalIn) { + doc.write(` + const ${id}_present = ${isPresent}; + if (${id}.issues.length) {${prefixStr(id, k)} + } + if (!${id}_present && !${id}.issues.length) { + payload.issues.push({ + code: "invalid_type", + expected: "nonoptional", + input: undefined, + path: [${k}] + }); + } + + if (${id}_present) { + newResult[${k}] = ${id}.value; + } + + `); + } + else { + doc.write(` + if (${id}.issues.length) {${prefixStr(id, k)} + } + + if (${id}.value === undefined) { + if (${isPresent}) { + newResult[${k}] = undefined; + } + } else { + newResult[${k}] = ${id}.value; + } + + `); + } + } + doc.write(`payload.value = newResult;`); + doc.write(`return payload;`); + // closing `shape` in is what pays: turbofan specializes the parser against that one shape object, so every `shape[k]._zod.run` folds to a known callee. as a parameter it stays a generic load and measures 13% slower even with the forwarding frame gone + return doc.compile(); + }; + let fastpass; + const isObject = util_isObject; + const jit = !globalConfig.jitless; + const allowsEval = util_allowsEval; + const fastEnabled = jit && allowsEval.value; // && !def.catchall; + const catchall = def.catchall; + let value; + inst._zod.parse = (payload, ctx) => { + value ?? (value = _normalized.value); + const input = payload.value; + if (!isObject(input)) { + payload.issues.push({ + expected: "object", + code: "invalid_type", + input, + inst, + }); + return payload; + } + if (jit && fastEnabled && ctx?.async === false && ctx.jitless !== true) { + // always synchronous + if (!fastpass) + fastpass = generateFastpass(def.shape); + payload = fastpass(payload, ctx); + if (!catchall) + return payload; + return handleCatchall([], input, payload, ctx, value, inst); + } + return superParse(payload, ctx); + }; +}); +function handleUnionResults(results, final, inst, ctx) { + for (const result of results) { + if (result.issues.length === 0) { + final.value = result.value; + return final; + } + } + const nonaborted = results.filter((r) => !aborted(r)); + if (nonaborted.length === 1) { + final.value = nonaborted[0].value; + return nonaborted[0]; + } + final.issues.push({ + code: "invalid_union", + input: final.value, + inst, + errors: results.map((result) => result.issues.map((iss) => finalizeIssue(iss, ctx, core_config()))), + }); + return final; +} +const $ZodUnion = /*@__PURE__*/ $constructor("$ZodUnion", (inst, def) => { + $ZodType.init(inst, def); + defineLazyInternal(inst, "optin", (zod) => zod.def.options.some((o) => o._zod.optin === "defaulted") + ? "defaulted" + : zod.def.options.some((o) => o._zod.optin !== undefined) + ? "optional" + : undefined); + defineLazyInternal(inst, "optout", (zod) => zod.def.options.some((o) => o._zod.optout === "optional") ? "optional" : undefined); + defineLazyInternal(inst, "values", (zod) => { + if (zod.def.options.every((o) => o._zod.values)) { + return new Set(zod.def.options.flatMap((option) => Array.from(option._zod.values))); + } + return undefined; + }); + defineLazyInternal(inst, "pattern", (zod) => { + if (zod.def.options.every((o) => o._zod.pattern)) { + const patterns = zod.def.options.map((o) => o._zod.pattern); + return new RegExp(`^(${patterns.map((p) => cleanRegex(p.source)).join("|")})$`); + } + return undefined; + }); + const first = def.options.length === 1 ? def.options[0]._zod.run : null; + inst._zod.parse = (payload, ctx) => { + if (first) { + return first(payload, ctx); + } + let async = false; + const results = []; + for (const option of def.options) { + const result = option._zod.run({ + value: payload.value, + issues: [], + }, ctx); + if (result instanceof Promise) { + results.push(result); + async = true; + } + else { + if (result.issues.length === 0) + return result; + results.push(result); + } + } + if (!async) + return handleUnionResults(results, payload, inst, ctx); + return Promise.all(results).then((results) => { + return handleUnionResults(results, payload, inst, ctx); + }); + }; +}); +function handleExclusiveUnionResults(results, final, inst, ctx) { + const matches = []; + for (let i = 0; i < results.length; i++) { + if (results[i].issues.length === 0) + matches.push(i); + } + if (matches.length === 1) { + final.value = results[matches[0]].value; + return final; + } + if (matches.length === 0) { + // No matches - same as regular union + final.issues.push({ + code: "invalid_union", + input: final.value, + inst, + errors: results.map((result) => result.issues.map((iss) => util.finalizeIssue(iss, ctx, core.config()))), + }); + } + else { + // Multiple matches - exclusive union failure + final.issues.push({ + code: "invalid_union", + input: final.value, + inst, + errors: [], + inclusive: false, + matches, + }); + } + return final; +} +const $ZodXor = /*@__PURE__*/ (/* unused pure expression or super */ null && (core.$constructor("$ZodXor", (inst, def) => { + $ZodUnion.init(inst, def); + def.inclusive = false; + const first = def.options.length === 1 ? def.options[0]._zod.run : null; + inst._zod.parse = (payload, ctx) => { + if (first) { + return first(payload, ctx); + } + let async = false; + const results = []; + for (const option of def.options) { + const result = option._zod.run({ + value: payload.value, + issues: [], + }, ctx); + if (result instanceof Promise) { + results.push(result); + async = true; + } + else { + results.push(result); + } + } + if (!async) + return handleExclusiveUnionResults(results, payload, inst, ctx); + return Promise.all(results).then((results) => { + return handleExclusiveUnionResults(results, payload, inst, ctx); + }); + }; +}))); +/** Returns the option of `union` whose discriminator claims `value`. */ +function getDiscriminatedOption(union, value) { + const internals = union._zod; + let map = internals.bag.optionsMap; + if (!map) { + map = new Map(); + const { options, discriminator } = internals.def; + for (const option of options) { + // First declaration wins, matching the order the parse path resolves a duplicate in. + for (const v of option._zod.propValues?.[discriminator] ?? []) + if (!map.has(v)) + map.set(v, option); + } + internals.bag.optionsMap = map; + } + return map.get(value); +} +const $ZodDiscriminatedUnion = +/*@__PURE__*/ +$constructor("$ZodDiscriminatedUnion", (inst, def) => { + def.inclusive = false; + $ZodUnion.init(inst, def); + const _super = inst._zod.parse; + defineLazyInternal(inst, "propValues", (zod) => { + const propValues = {}; + for (const option of zod.def.options) { + const pv = option._zod.propValues; + if (!pv || Object.keys(pv).length === 0) + throw new Error(`Invalid discriminated union option at index "${zod.def.options.indexOf(option)}"`); + for (const [k, v] of Object.entries(pv)) { + if (!Object.prototype.hasOwnProperty.call(propValues, k)) { + assignProp(propValues, k, new Set()); + } + for (const val of v) { + propValues[k].add(val); + } + } + } + return propValues; + }); + // Checked now rather than in the lookup map below, so an option that lacks the discriminator fails at the `discriminatedUnion` call instead of on the first object parsed. Options whose shape cannot be enumerated without resolving it — pipes, lazies, and objects rebuilt by a builder such as `.extend()` — are left to the map. + def.options.forEach((option, i) => { + const propShape = propShapes.get(option._zod.def); + if (propShape && !Object.prototype.hasOwnProperty.call(propShape, def.discriminator)) { + throw new Error(`Invalid discriminated union option at index "${i}"`); + } + }); + const disc = util_cached(() => { + const opts = def.options; + const map = new Map(); + for (const o of opts) { + const values = o._zod.propValues?.[def.discriminator]; + if (!values || values.size === 0) + throw new Error(`Invalid discriminated union option at index "${def.options.indexOf(o)}"`); + for (const v of values) { + if (map.has(v)) { + throw new Error(`Duplicate discriminator value "${String(v)}"`); + } + map.set(v, o); + } + } + return map; + }); + inst._zod.parse = (payload, ctx) => { + const input = payload.value; + if (!util_isObject(input)) { + payload.issues.push({ + code: "invalid_type", + expected: "object", + input, + inst, + }); + return payload; + } + const opt = disc.value.get(input?.[def.discriminator]); + if (opt) { + return opt._zod.run(payload, ctx); + } + // Fall back to union matching when the fast discriminator path fails: + // - explicitly enabled via unionFallback, or + // - during backward direction (encode), since codec-based discriminators have different values in forward vs backward directions + if (def.unionFallback || ctx.direction === "backward") { + return _super(payload, ctx); + } + // no matching discriminator + payload.issues.push({ + code: "invalid_union", + errors: [], + note: "No matching discriminator", + discriminator: def.discriminator, + options: Array.from(disc.value.keys()), + input, + path: [def.discriminator], + inst, + }); + return payload; + }; +}); +const $ZodIntersection = /*@__PURE__*/ $constructor("$ZodIntersection", (inst, def) => { + $ZodType.init(inst, def); + inst._zod.parse = (payload, ctx) => { + const input = payload.value; + const left = def.left._zod.run({ value: input, issues: [] }, ctx); + const right = def.right._zod.run({ value: input, issues: [] }, ctx); + const async = left instanceof Promise || right instanceof Promise; + if (async) { + return Promise.all([left, right]).then(([left, right]) => { + return handleIntersectionResults(payload, left, right); + }); + } + return handleIntersectionResults(payload, left, right); + }; +}); +function schemas_mergeValues(a, b) { + // const aType = parse.t(a); + // const bType = parse.t(b); + if (a === b) { + return { valid: true, data: a }; + } + if (a instanceof Date && b instanceof Date && +a === +b) { + return { valid: true, data: a }; + } + if (isPlainObject(a) && isPlainObject(b)) { + const bKeys = Object.keys(b); + const sharedKeys = Object.keys(a).filter((key) => bKeys.indexOf(key) !== -1); + const newObj = { ...a, ...b }; + if (Object.prototype.hasOwnProperty.call(newObj, "__proto__")) + delete newObj.__proto__; + for (const key of sharedKeys) { + if (key === "__proto__") + continue; + const sharedValue = schemas_mergeValues(a[key], b[key]); + if (!sharedValue.valid) { + return { + valid: false, + mergeErrorPath: [key, ...sharedValue.mergeErrorPath], + }; + } + newObj[key] = sharedValue.data; + } + return { valid: true, data: newObj }; + } + if (Array.isArray(a) && Array.isArray(b)) { + if (a.length !== b.length) { + return { valid: false, mergeErrorPath: [] }; + } + const newArray = []; + for (let index = 0; index < a.length; index++) { + const itemA = a[index]; + const itemB = b[index]; + const sharedValue = schemas_mergeValues(itemA, itemB); + if (!sharedValue.valid) { + return { + valid: false, + mergeErrorPath: [index, ...sharedValue.mergeErrorPath], + }; + } + newArray.push(sharedValue.data); + } + return { valid: true, data: newArray }; + } + return { valid: false, mergeErrorPath: [] }; +} +function handleIntersectionResults(result, left, right) { + // Track which side(s) reject each key. A key rejection is reported only when BOTH sides reject it, so a key owned by one branch survives the other's key schema. strictObject reports these as unrecognized_keys; a record with an open key schema reports one invalid_key per key. + const unrecKeys = new Map(); + let unrecIssue; + const keyIssues = new Map(); + const collect = (iss, side) => { + let keys; + if (iss.code === "unrecognized_keys" && !iss.path?.length) { + unrecIssue ?? (unrecIssue = iss); + keys = iss.keys; + } + else if (iss.code === "invalid_key" && iss.origin === "record" && iss.path?.length === 1) { + const k = String(iss.path[0]); + if (!keyIssues.has(k)) + keyIssues.set(k, iss); + keys = [k]; + } + else { + return false; + } + for (const k of keys) { + if (!unrecKeys.has(k)) + unrecKeys.set(k, {}); + unrecKeys.get(k)[side] = true; + } + return true; + }; + for (const iss of left.issues) { + if (!collect(iss, "l")) + result.issues.push(iss); + } + for (const iss of right.issues) { + if (!collect(iss, "r")) + result.issues.push(iss); + } + // Report only keys rejected by BOTH sides + const bothKeys = [...unrecKeys].filter(([, f]) => f.l && f.r).map(([k]) => k); + if (bothKeys.length) { + const aggregated = unrecIssue ? bothKeys.filter((k) => unrecIssue.keys.includes(k)) : []; + if (aggregated.length) + result.issues.push({ ...unrecIssue, keys: aggregated }); + for (const k of bothKeys) { + if (!aggregated.includes(k) && keyIssues.has(k)) + result.issues.push(keyIssues.get(k)); + } + } + const merged = schemas_mergeValues(left.value, right.value); + if (!merged.valid) { + if (aborted(result)) + return result; + throw new Error(`Unmergable intersection. Error path: ` + `${JSON.stringify(merged.mergeErrorPath)}`); + } + result.value = merged.data; + return result; +} +const $ZodTuple = /*@__PURE__*/ (/* unused pure expression or super */ null && (core.$constructor("$ZodTuple", (inst, def) => { + $ZodType.init(inst, def); + const items = def.items; + const memo = core.globalConfig.memoizer; + memo?.attach(inst); + inst._zod.parse = (payload, ctx) => { + const input = payload.value; + if (!Array.isArray(input)) { + payload.issues.push({ + input, + inst, + expected: "tuple", + code: "invalid_type", + }); + return payload; + } + payload.value = memo ? memo.alloc(inst, payload, [], ctx) : []; + const proms = []; + const optinStart = getTupleOptStart(items, "optin"); + const optoutStart = getTupleOptStart(items, "optout"); + if (!def.rest) { + if (input.length < optinStart) { + payload.issues.push({ + code: "too_small", + minimum: optinStart, + inclusive: true, + input, + inst, + origin: "array", + }); + return payload; + } + if (input.length > items.length) { + payload.issues.push({ + code: "too_big", + maximum: items.length, + inclusive: true, + input, + inst, + origin: "array", + }); + } + } + // Run every item in parallel, collecting results into an indexed array. The post-processing in `handleTupleResults` walks them in order so it can decide whether an absent optional-output error can truncate the tail or must be reported to preserve required output. + const itemResults = new Array(items.length); + for (let i = 0; i < items.length; i++) { + const r = items[i]._zod.run({ value: input[i], issues: [] }, ctx); + if (r instanceof Promise) { + proms.push(r.then((rr) => { + itemResults[i] = rr; + })); + } + else { + itemResults[i] = r; + } + } + if (def.rest) { + let i = items.length - 1; + const rest = input.slice(items.length); + for (const el of rest) { + i++; + const result = def.rest._zod.run({ value: el, issues: [] }, ctx); + if (result instanceof Promise) { + proms.push(result.then((r) => handleTupleResult(r, payload, i))); + } + else { + handleTupleResult(result, payload, i); + } + } + } + if (proms.length) { + return Promise.all(proms).then(() => handleTupleResults(itemResults, payload, items, input, optoutStart)); + } + return handleTupleResults(itemResults, payload, items, input, optoutStart); + }; +}))); +function getTupleOptStart(items, key) { + for (let i = items.length - 1; i >= 0; i--) { + // optin is a three-rung ladder so any rung above `undefined` permits an absent slot; optout stays two-valued. + const omittable = key === "optin" ? items[i]._zod.optin !== undefined : items[i]._zod.optout === "optional"; + if (!omittable) + return i + 1; + } + return 0; +} +function handleTupleResult(result, final, index) { + if (result.issues.length) { + final.issues.push(...util.prefixIssues(index, result.issues)); + } + final.value[index] = result.value; +} +function handleTupleResults(itemResults, final, items, input, optoutStart) { + // Walk results in order. Mirror $ZodObject's swallow-on-absent-optional rule, but only after `optoutStart`: the first index where the output tuple tail can be absent. + for (let i = 0; i < items.length; i++) { + const r = itemResults[i]; + const isPresent = i < input.length; + // The array analog of `handlePropertyResult`'s absent-key early return: the middle rung permits absence without supplying anything in its place, so the tail truncates here instead of materializing whatever the item made of `undefined`. + if (!isPresent && i >= optoutStart && items[i]._zod.optin === "optional") { + final.value.length = i; + break; + } + if (r.issues.length) { + if (!isPresent && i >= optoutStart) { + final.value.length = i; + break; + } + final.issues.push(...util.prefixIssues(i, r.issues)); + } + final.value[i] = r.value; + } + // Drop trailing slots that produced `undefined` for absent input + // (the array analog of an absent optional key on an object). The + // `i >= input.length` floor is critical: an explicit `undefined` + // *inside* the input must be preserved even when the schema is + // optional-out (e.g. `z.string().or(z.undefined())` accepting an + // explicit undefined value). + for (let i = final.value.length - 1; i >= input.length; i--) { + if (items[i]._zod.optout === "optional" && final.value[i] === undefined) { + final.value.length = i; + } + else { + break; + } + } + return final; +} +const $ZodRecord = /*@__PURE__*/ $constructor("$ZodRecord", (inst, def) => { + $ZodType.init(inst, def); + const memo = globalConfig.memoizer; + memo?.attach(inst); + inst._zod.parse = (payload, ctx) => { + const input = payload.value; + if (!isPlainObject(input)) { + payload.issues.push({ + expected: "record", + code: "invalid_type", + input, + inst, + }); + return payload; + } + const proms = []; + const values = def.keyType._zod.values; + if (values && !def.partial) { + payload.value = memo ? memo.alloc(inst, payload, {}, ctx) : {}; + const recordKeys = new Set(); + for (const key of values) { + if (typeof key === "string" || typeof key === "number" || typeof key === "symbol") { + recordKeys.add(typeof key === "number" ? key.toString() : key); + // A declared __proto__ is stripped but is not an unrecognized key. + if (key === "__proto__") + continue; + const keyResult = def.keyType._zod.run({ value: key, issues: [] }, ctx); + if (keyResult instanceof Promise) { + throw new Error("Async schemas not supported in object keys currently"); + } + if (keyResult.issues.length) { + payload.issues.push({ + code: "invalid_key", + origin: "record", + issues: keyResult.issues.map((iss) => finalizeIssue(iss, ctx, core_config())), + input: key, + path: [key], + inst, + }); + continue; + } + const outKey = keyResult.value; + if (outKey === "__proto__") + continue; + const result = def.valueType._zod.run({ value: input[key], issues: [] }, ctx); + if (result instanceof Promise) { + proms.push(result.then((result) => { + if (result.issues.length) { + payload.issues.push(...prefixIssues(key, result.issues)); + } + payload.value[outKey] = result.value; + })); + } + else { + if (result.issues.length) { + payload.issues.push(...prefixIssues(key, result.issues)); + } + payload.value[outKey] = result.value; + } + } + } + let unrecognized; + for (const key in input) { + if (!recordKeys.has(key)) { + if (def.mode === "loose") { + // skip __proto__ so it can't replace the result prototype via the assignment setter on the plain {} we build into + if (key === "__proto__") + continue; + payload.value[key] = input[key]; + } + else { + unrecognized = unrecognized ?? []; + unrecognized.push(key); + } + } + } + if (unrecognized && unrecognized.length > 0) { + payload.issues.push({ + code: "unrecognized_keys", + input, + inst, + keys: unrecognized, + continue: true, + }); + } + } + else { + payload.value = memo ? memo.alloc(inst, payload, {}, ctx) : {}; + // An enumerable key schema declares which keys the record owns, so a key outside the set is unrecognized. A non-enumerable one (regex, refine) is a constraint every key must satisfy, so a failing key is invalid. Only the former is reconcilable against the other side of an intersection. + let unrecognized; + // Reflect.ownKeys for Symbol-key support; filter non-enumerable to match z.object() + for (const key of Reflect.ownKeys(input)) { + if (key === "__proto__") + continue; + if (!Object.prototype.propertyIsEnumerable.call(input, key)) + continue; + let keyResult = def.keyType._zod.run({ value: key, issues: [] }, ctx); + if (keyResult instanceof Promise) { + throw new Error("Async schemas not supported in object keys currently"); + } + // Numeric string fallback: if key is a numeric string and failed, retry with Number(key). This handles z.number(), z.literal([1, 2, 3]), and unions containing numeric literals + const checkNumericKey = typeof key === "string" && number.test(key) && keyResult.issues.length; + if (checkNumericKey) { + const retryResult = def.keyType._zod.run({ value: Number(key), issues: [] }, ctx); + if (retryResult instanceof Promise) { + throw new Error("Async schemas not supported in object keys currently"); + } + if (retryResult.issues.length === 0) { + keyResult = retryResult; + } + } + if (keyResult.issues.length) { + if (def.mode === "loose") { + // Pass through unchanged + payload.value[key] = input[key]; + } + else if (values) { + unrecognized = unrecognized ?? []; + unrecognized.push(key); + } + else { + // Default "strict" behavior: error on invalid key + payload.issues.push({ + code: "invalid_key", + origin: "record", + issues: keyResult.issues.map((iss) => finalizeIssue(iss, ctx, core_config())), + input: key, + path: [key], + inst, + }); + } + continue; + } + // the guard above tests the raw input key, but the key schema can normalize an ordinary key into __proto__; re-check the key we actually write under + const outKey = keyResult.value; + if (outKey === "__proto__") + continue; + const result = def.valueType._zod.run({ value: input[key], issues: [] }, ctx); + if (result instanceof Promise) { + proms.push(result.then((result) => { + if (result.issues.length) { + payload.issues.push(...prefixIssues(key, result.issues)); + } + payload.value[outKey] = result.value; + })); + } + else { + if (result.issues.length) { + payload.issues.push(...prefixIssues(key, result.issues)); + } + payload.value[outKey] = result.value; + } + } + if (unrecognized && unrecognized.length > 0) { + payload.issues.push({ + code: "unrecognized_keys", + input, + inst, + keys: unrecognized, + continue: true, + }); + } + } + if (proms.length) { + return Promise.all(proms).then(() => payload); + } + return payload; + }; +}); +const $ZodMap = /*@__PURE__*/ (/* unused pure expression or super */ null && (core.$constructor("$ZodMap", (inst, def) => { + $ZodType.init(inst, def); + const memo = core.globalConfig.memoizer; + memo?.attach(inst); + inst._zod.parse = (payload, ctx) => { + const input = payload.value; + if (!(input instanceof Map)) { + payload.issues.push({ + expected: "map", + code: "invalid_type", + input, + inst, + }); + return payload; + } + const proms = []; + payload.value = memo ? memo.alloc(inst, payload, new Map(), ctx) : new Map(); + for (const [key, value] of input) { + const keyResult = def.keyType._zod.run({ value: key, issues: [] }, ctx); + const valueResult = def.valueType._zod.run({ value: value, issues: [] }, ctx); + if (keyResult instanceof Promise || valueResult instanceof Promise) { + proms.push(Promise.all([keyResult, valueResult]).then(([keyResult, valueResult]) => { + handleMapResult(keyResult, valueResult, payload, key, input, inst, ctx); + })); + } + else { + handleMapResult(keyResult, valueResult, payload, key, input, inst, ctx); + } + } + if (proms.length) + return Promise.all(proms).then(() => payload); + return payload; + }; +}))); +function handleMapResult(keyResult, valueResult, final, key, input, inst, ctx) { + if (keyResult.issues.length) { + if (util.propertyKeyTypes.has(typeof key)) { + final.issues.push(...util.prefixIssues(key, keyResult.issues)); + } + else { + final.issues.push({ + code: "invalid_key", + origin: "map", + input, + inst, + issues: keyResult.issues.map((iss) => util.finalizeIssue(iss, ctx, core.config())), + }); + } + } + if (valueResult.issues.length) { + if (util.propertyKeyTypes.has(typeof key)) { + final.issues.push(...util.prefixIssues(key, valueResult.issues)); + } + else { + final.issues.push({ + origin: "map", + code: "invalid_element", + input, + inst, + key: key, + issues: valueResult.issues.map((iss) => util.finalizeIssue(iss, ctx, core.config())), + }); + } + } + final.value.set(keyResult.value, valueResult.value); +} +const $ZodSet = /*@__PURE__*/ (/* unused pure expression or super */ null && (core.$constructor("$ZodSet", (inst, def) => { + $ZodType.init(inst, def); + const memo = core.globalConfig.memoizer; + memo?.attach(inst); + inst._zod.parse = (payload, ctx) => { + const input = payload.value; + if (!(input instanceof Set)) { + payload.issues.push({ + input, + inst, + expected: "set", + code: "invalid_type", + }); + return payload; + } + const proms = []; + payload.value = memo ? memo.alloc(inst, payload, new Set(), ctx) : new Set(); + for (const item of input) { + const result = def.valueType._zod.run({ value: item, issues: [] }, ctx); + if (result instanceof Promise) { + proms.push(result.then((result) => handleSetResult(result, payload))); + } + else + handleSetResult(result, payload); + } + if (proms.length) + return Promise.all(proms).then(() => payload); + return payload; + }; +}))); +function handleSetResult(result, final) { + if (result.issues.length) { + final.issues.push(...result.issues); + } + final.value.add(result.value); +} +const $ZodEnum = /*@__PURE__*/ $constructor("$ZodEnum", (inst, def) => { + $ZodType.init(inst, def); + const values = getEnumValues(def.entries); + const valuesSet = new Set(values); + inst._zod.values = valuesSet; + const patternValues = values.filter((k) => propertyKeyTypes.has(typeof k)); + // unmatchable fallback, RE2-safe: an empty alternation would compile to /^()$/, which matches "" + inst._zod.pattern = new RegExp(patternValues.length ? `^(${patternValues.map((o) => escapeRegex(o.toString())).join("|")})$` : "^[^\\s\\S]$"); + inst._zod.parse = (payload, _ctx) => { + const input = payload.value; + if (valuesSet.has(input)) { + return payload; + } + payload.issues.push({ + code: "invalid_value", + values, + input, + inst, + }); + return payload; + }; +}); +const $ZodLiteral = /*@__PURE__*/ $constructor("$ZodLiteral", (inst, def) => { + $ZodType.init(inst, def); + const values = new Set(def.values); + inst._zod.values = values; + // unmatchable fallback, RE2-safe: an empty alternation would compile to /^()$/, which matches "" + inst._zod.pattern = new RegExp(def.values.length + ? `^(${def.values + .map((o) => (typeof o === "string" ? escapeRegex(o) : o ? escapeRegex(o.toString()) : String(o))) + .join("|")})$` + : "^[^\\s\\S]$"); + inst._zod.parse = (payload, _ctx) => { + const input = payload.value; + if (values.has(input)) { + return payload; + } + payload.issues.push({ + code: "invalid_value", + values: def.values, + input, + inst, + }); + return payload; + }; +}); +const $ZodFile = /*@__PURE__*/ (/* unused pure expression or super */ null && (core.$constructor("$ZodFile", (inst, def) => { + $ZodType.init(inst, def); + inst._zod.parse = (payload, _ctx) => { + const input = payload.value; + // @ts-ignore + if (input instanceof File) + return payload; + payload.issues.push({ + expected: "file", + code: "invalid_type", + input, + inst, + }); + return payload; + }; +}))); +const $ZodTransform = /*@__PURE__*/ $constructor("$ZodTransform", (inst, def) => { + $ZodType.init(inst, def); + inst._zod.optin = "optional"; + globalConfig.memoizer?.guard(inst); + inst._zod.parse = (payload, ctx) => { + if (ctx.direction === "backward") { + throw new $ZodEncodeError(inst.constructor.name); + } + const _out = def.transform(payload.value, payload); + if (ctx.async) { + const output = _out instanceof Promise ? _out : Promise.resolve(_out); + return output.then((output) => { + payload.value = output; + return payload; + }); + } + if (_out instanceof Promise) { + throw new $ZodAsyncError(); + } + payload.value = _out; + return payload; + }; +}); +function handleOptionalResult(payload, result) { + // A substituting schema that still failed has no usable answer; yield undefined. Its issues are simply dropped: it ran on a payload of its own, so there is no shared array to truncate and nothing of the caller's to lose with it. + payload.value = result.issues.length ? undefined : result.value; + return payload; +} +const $ZodOptional = /*@__PURE__*/ $constructor("$ZodOptional", (inst, def) => { + $ZodType.init(inst, def); + // .optional() propagates absence rather than substituting for it, so a defaulted inner keeps its rung. + defineLazyInternal(inst, "optin", (zod) => zod.def.innerType._zod.optin === "defaulted" ? "defaulted" : "optional"); + inst._zod.optout = "optional"; + defineLazyInternal(inst, "values", (zod) => { + const values = zod.def.innerType._zod.values; + return values ? new Set([...values, undefined]) : undefined; + }); + defineLazyInternal(inst, "pattern", (zod) => { + const pattern = zod.def.innerType._zod.pattern; + return pattern ? new RegExp(`^(${cleanRegex(pattern.source)})?$`) : undefined; + }); + inst._zod.parse = (payload, ctx) => { + if (payload.value === undefined) { + // Only the top rung substitutes a value for absence; everything else leaves it intact, which is what .optional() means. + if (def.innerType._zod.optin !== "defaulted") + return payload; + // Its own payload, for the same reason $ZodCatch gets one: a pipe forwards an unrecognized key through the caller's issues array, and this must not read that as the substituting schema failing and drop it. + const result = def.innerType._zod.run({ value: payload.value, issues: [] }, ctx); + if (result instanceof Promise) + return result.then((result) => handleOptionalResult(payload, result)); + return handleOptionalResult(payload, result); + } + return def.innerType._zod.run(payload, ctx); + }; +}); +const $ZodExactOptional = /*@__PURE__*/ $constructor("$ZodExactOptional", (inst, def) => { + // Call parent init - inherits optin/optout = "optional" + $ZodOptional.init(inst, def); + // Override values/pattern to NOT add undefined + defineLazyInternal(inst, "values", (zod) => zod.def.innerType._zod.values); + defineLazyInternal(inst, "pattern", (zod) => zod.def.innerType._zod.pattern); + // Override parse to just delegate (no undefined handling) + inst._zod.parse = (payload, ctx) => { + return def.innerType._zod.run(payload, ctx); + }; +}); +const $ZodNullable = /*@__PURE__*/ $constructor("$ZodNullable", (inst, def) => { + $ZodType.init(inst, def); + defineLazyInternal(inst, "optin", (zod) => zod.def.innerType._zod.optin); + defineLazyInternal(inst, "optout", (zod) => zod.def.innerType._zod.optout); + defineLazyInternal(inst, "pattern", (zod) => { + const pattern = zod.def.innerType._zod.pattern; + return pattern ? new RegExp(`^(${cleanRegex(pattern.source)}|null)$`) : undefined; + }); + defineLazyInternal(inst, "values", (zod) => { + return zod.def.innerType._zod.values ? new Set([...zod.def.innerType._zod.values, null]) : undefined; + }); + inst._zod.parse = (payload, ctx) => { + // Forward direction (decode): allow null to pass through + if (payload.value === null) + return payload; + return def.innerType._zod.run(payload, ctx); + }; +}); +const $ZodDefault = /*@__PURE__*/ $constructor("$ZodDefault", (inst, def) => { + $ZodType.init(inst, def); + // inst._zod.qin = "true"; + inst._zod.optin = "defaulted"; + defineLazyInternal(inst, "values", (zod) => zod.def.innerType._zod.values); + inst._zod.parse = (payload, ctx) => { + if (ctx.direction === "backward") { + return def.innerType._zod.run(payload, ctx); + } + // Forward direction (decode): apply defaults for undefined input + if (payload.value === undefined) { + payload.value = def.defaultValue; + /** + * $ZodDefault returns the default value immediately in forward direction. + * It doesn't pass the default value into the validator ("prefault"). There's no reason to pass the default value through validation. The validity of the default is enforced by TypeScript statically. Otherwise, it's the responsibility of the user to ensure the default is valid. In the case of pipes with divergent in/out types, you can specify the default on the `in` schema of your ZodPipe to set a "prefault" for the pipe. */ + return payload; + } + // Forward direction: continue with default handling + const result = def.innerType._zod.run(payload, ctx); + if (result instanceof Promise) { + return result.then((result) => handleDefaultResult(result, def)); + } + return handleDefaultResult(result, def); + }; +}); +function handleDefaultResult(payload, def) { + if (payload.value === undefined) { + payload.value = def.defaultValue; + } + return payload; +} +const $ZodPrefault = /*@__PURE__*/ $constructor("$ZodPrefault", (inst, def) => { + $ZodType.init(inst, def); + inst._zod.optin = "defaulted"; + defineLazyInternal(inst, "values", (zod) => zod.def.innerType._zod.values); + inst._zod.parse = (payload, ctx) => { + if (ctx.direction === "backward") { + return def.innerType._zod.run(payload, ctx); + } + // Forward direction (decode): apply prefault for undefined input + if (payload.value === undefined) { + payload.value = def.defaultValue; + } + return def.innerType._zod.run(payload, ctx); + }; +}); +const $ZodNonOptional = /*@__PURE__*/ $constructor("$ZodNonOptional", (inst, def) => { + $ZodType.init(inst, def); + defineLazyInternal(inst, "values", (zod) => { + const v = zod.def.innerType._zod.values; + return v ? new Set([...v].filter((x) => x !== undefined)) : undefined; + }); + inst._zod.parse = (payload, ctx) => { + const result = def.innerType._zod.run(payload, ctx); + if (result instanceof Promise) { + return result.then((result) => handleNonOptionalResult(result, inst)); + } + return handleNonOptionalResult(result, inst); + }; +}); +function handleNonOptionalResult(payload, inst) { + if (!payload.issues.length && payload.value === undefined) { + payload.issues.push({ + code: "invalid_type", + expected: "nonoptional", + input: payload.value, + inst, + }); + } + return payload; +} +const $ZodSuccess = /*@__PURE__*/ (/* unused pure expression or super */ null && (core.$constructor("$ZodSuccess", (inst, def) => { + $ZodType.init(inst, def); + inst._zod.parse = (payload, ctx) => { + if (ctx.direction === "backward") { + throw new core.$ZodEncodeError("ZodSuccess"); + } + const result = def.innerType._zod.run(payload, ctx); + if (result instanceof Promise) { + return result.then((result) => { + payload.value = result.issues.length === 0; + return payload; + }); + } + payload.value = result.issues.length === 0; + return payload; + }; +}))); +function handleCatchResult(payload, result, def, ctx) { + if (!result.issues.length) { + payload.value = result.value; + // The value carries up, so the flag describing it has to carry with it: a back-edge into a node still being parsed must not be frozen by an enclosing readonly, and its checks belong to the node itself. Guarded so the ordinary case adds no own property. + if (result.memo) + payload.memo = true; + return payload; + } + // Spread the inner's own payload, not ours: `value` has to stay the input the catch was handed, and the inner ran on a payload of its own so its issues are already private to this call. + payload.value = def.catchValue({ + ...result, + value: payload.value, + error: { + issues: result.issues.map((iss) => finalizeIssue(iss, ctx, core_config())), + }, + input: payload.value, + }); + return payload; +} +const $ZodCatch = /*@__PURE__*/ $constructor("$ZodCatch", (inst, def) => { + $ZodType.init(inst, def); + defineLazyInternal(inst, "optin", (zod) => zod.def.innerType._zod.optin === "defaulted" ? "defaulted" : "optional"); + defineLazyInternal(inst, "optout", (zod) => zod.def.innerType._zod.optout); + defineLazyInternal(inst, "values", (zod) => zod.def.innerType._zod.values); + inst._zod.parse = (payload, ctx) => { + if (ctx.direction === "backward") { + return def.innerType._zod.run(payload, ctx); + } + // Forward direction (decode): apply catch logic + const result = def.innerType._zod.run({ value: payload.value, issues: [] }, ctx); + if (result instanceof Promise) { + return result.then((result) => handleCatchResult(payload, result, def, ctx)); + } + return handleCatchResult(payload, result, def, ctx); + }; +}); +const $ZodNaN = /*@__PURE__*/ (/* unused pure expression or super */ null && (core.$constructor("$ZodNaN", (inst, def) => { + $ZodType.init(inst, def); + inst._zod.parse = (payload, _ctx) => { + if (typeof payload.value !== "number" || !Number.isNaN(payload.value)) { + payload.issues.push({ + input: payload.value, + inst, + expected: "nan", + code: "invalid_type", + }); + return payload; + } + return payload; + }; +}))); +const $ZodPipe = /*@__PURE__*/ $constructor("$ZodPipe", (inst, def) => { + $ZodType.init(inst, def); + defineLazyInternal(inst, "values", (zod) => zod.def.in._zod.values); + defineLazyInternal(inst, "optin", (zod) => zod.def.in._zod.optin); + defineLazyInternal(inst, "optout", (zod) => zod.def.out._zod.optout); + defineLazyInternal(inst, "propValues", (zod) => zod.def.in._zod.propValues); + inst._zod.parse = (payload, ctx) => { + if (ctx.direction === "backward") { + const right = def.out._zod.run(payload, ctx); + if (right instanceof Promise) { + return right.then((right) => handlePipeResult(right, def.in, ctx)); + } + return handlePipeResult(right, def.in, ctx); + } + const left = def.in._zod.run(payload, ctx); + if (left instanceof Promise) { + return left.then((left) => handlePipeResult(left, def.out, ctx)); + } + return handlePipeResult(left, def.out, ctx); + }; +}); +function handlePipeResult(left, next, ctx) { + // Any issue stops the pipe, so a failing refinement never feeds its transform. An unrecognized key is the exception: it describes the input's extra properties, not the value being piped, and an enclosing intersection may yet reconcile it. + if (left.issues.some((iss) => iss.code !== "unrecognized_keys")) { + // prevent further checks + left.aborted = true; + return left; + } + return next._zod.run({ value: left.value, issues: left.issues }, ctx); +} +const $ZodCodec = /*@__PURE__*/ (/* unused pure expression or super */ null && (core.$constructor("$ZodCodec", (inst, def) => { + $ZodType.init(inst, def); + util.defineLazyInternal(inst, "values", (zod) => zod.def.in._zod.values); + util.defineLazyInternal(inst, "optin", (zod) => zod.def.in._zod.optin); + util.defineLazyInternal(inst, "optout", (zod) => zod.def.out._zod.optout); + util.defineLazyInternal(inst, "propValues", (zod) => zod.def.in._zod.propValues); + inst._zod.parse = (payload, ctx) => { + const direction = ctx.direction || "forward"; + if (direction === "forward") { + const left = def.in._zod.run(payload, ctx); + if (left instanceof Promise) { + return left.then((left) => handleCodecAResult(left, def, ctx)); + } + return handleCodecAResult(left, def, ctx); + } + else { + const right = def.out._zod.run(payload, ctx); + if (right instanceof Promise) { + return right.then((right) => handleCodecAResult(right, def, ctx)); + } + return handleCodecAResult(right, def, ctx); + } + }; +}))); +function handleCodecAResult(result, def, ctx) { + if (result.issues.length) { + // prevent further checks + result.aborted = true; + return result; + } + const direction = ctx.direction || "forward"; + if (direction === "forward") { + const transformed = def.transform(result.value, result); + if (transformed instanceof Promise) { + return transformed.then((value) => handleCodecTxResult(result, value, def.out, ctx)); + } + return handleCodecTxResult(result, transformed, def.out, ctx); + } + else { + const transformed = def.reverseTransform(result.value, result); + if (transformed instanceof Promise) { + return transformed.then((value) => handleCodecTxResult(result, value, def.in, ctx)); + } + return handleCodecTxResult(result, transformed, def.in, ctx); + } +} +function handleCodecTxResult(left, value, nextSchema, ctx) { + // Check if transform added any issues + if (left.issues.length) { + left.aborted = true; + return left; + } + return nextSchema._zod.run({ value, issues: left.issues }, ctx); +} +const $ZodPreprocess = /*@__PURE__*/ $constructor("$ZodPreprocess", (inst, def) => { + $ZodPipe.init(inst, def); +}); +const $ZodReadonly = /*@__PURE__*/ $constructor("$ZodReadonly", (inst, def) => { + $ZodType.init(inst, def); + defineLazyInternal(inst, "propValues", (zod) => zod.def.innerType._zod.propValues); + defineLazyInternal(inst, "values", (zod) => zod.def.innerType._zod.values); + defineLazyInternal(inst, "optin", (zod) => zod.def.innerType?._zod?.optin); + defineLazyInternal(inst, "optout", (zod) => zod.def.innerType?._zod?.optout); + inst._zod.parse = (payload, ctx) => { + if (ctx.direction === "backward") { + return def.innerType._zod.run(payload, ctx); + } + const result = def.innerType._zod.run(payload, ctx); + if (result instanceof Promise) { + return result.then(handleReadonlyResult); + } + return handleReadonlyResult(result); + }; +}); +function handleReadonlyResult(payload) { + // A repeat visit hands back a node that is still being built; freezing it here would make the rest of its keys fail to assign. + if (!payload.memo) + payload.value = Object.freeze(payload.value); + return payload; +} +const $ZodTemplateLiteral = /*@__PURE__*/ (/* unused pure expression or super */ null && (core.$constructor("$ZodTemplateLiteral", (inst, def) => { + $ZodType.init(inst, def); + const regexParts = []; + for (const part of def.parts) { + if (typeof part === "object" && part !== null) { + // is Zod schema + if (!part._zod.pattern) { + // if (!source) + throw new Error(`Invalid template literal part, no pattern found: ${[...part._zod.traits].shift()}`); + } + const source = part._zod.pattern instanceof RegExp ? part._zod.pattern.source : part._zod.pattern; + if (!source) + throw new Error(`Invalid template literal part: ${part._zod.traits}`); + const start = source.startsWith("^") ? 1 : 0; + const end = source.endsWith("$") ? source.length - 1 : source.length; + regexParts.push(source.slice(start, end)); + } + else if (part === null || util.primitiveTypes.has(typeof part)) { + regexParts.push(util.escapeRegex(`${part}`)); + } + else { + throw new Error(`Invalid template literal part: ${part}`); + } + } + inst._zod.pattern = new RegExp(`^${regexParts.join("")}$`); + inst._zod.parse = (payload, _ctx) => { + if (typeof payload.value !== "string") { + payload.issues.push({ + input: payload.value, + inst, + expected: "string", + code: "invalid_type", + }); + return payload; + } + inst._zod.pattern.lastIndex = 0; + if (!inst._zod.pattern.test(payload.value)) { + payload.issues.push({ + input: payload.value, + inst, + code: "invalid_format", + format: def.format ?? "template_literal", + pattern: inst._zod.pattern.source, + }); + return payload; + } + return payload; + }; +}))); +const $ZodFunction = /*@__PURE__*/ (/* unused pure expression or super */ null && (core.$constructor("$ZodFunction", (inst, def) => { + $ZodType.init(inst, def); + // Defined, not assigned: the classic prototype exposes `_def` as a getter with no setter. + Object.defineProperty(inst, "_def", { value: def }); + inst._zod.def = def; + inst.implement = (func) => { + if (typeof func !== "function") { + throw new Error("implement() must be called with a function"); + } + // Defined inline so the closure stays anonymous: binding it to a `const` first names it, which costs 256 bytes per implemented function. + return Object.defineProperty(function (...args) { + const parsedArgs = inst._def.input ? parse(inst._def.input, args) : args; + const result = Reflect.apply(func, this, parsedArgs); + if (inst._def.output) { + return parse(inst._def.output, result); + } + return result; + }, "_zod", { value: inst._zod, enumerable: false }); + }; + inst.implementAsync = (func) => { + if (typeof func !== "function") { + throw new Error("implementAsync() must be called with a function"); + } + return Object.defineProperty(async function (...args) { + const parsedArgs = inst._def.input ? await parseAsync(inst._def.input, args) : args; + const result = await Reflect.apply(func, this, parsedArgs); + if (inst._def.output) { + return await parseAsync(inst._def.output, result); + } + return result; + }, "_zod", { value: inst._zod, enumerable: false }); + }; + inst._zod.parse = (payload, _ctx) => { + if (typeof payload.value !== "function") { + payload.issues.push({ + code: "invalid_type", + expected: "function", + input: payload.value, + inst, + }); + return payload; + } + // Check if output is a promise type to determine if we should use async implementation + const hasPromiseOutput = inst._def.output && inst._def.output._zod.def.type === "promise"; + if (hasPromiseOutput) { + payload.value = inst.implementAsync(payload.value); + } + else { + payload.value = inst.implement(payload.value); + } + return payload; + }; + inst.input = (...args) => { + const F = inst.constructor; + if (Array.isArray(args[0])) { + return new F({ + type: "function", + input: new $ZodTuple({ + type: "tuple", + items: args[0], + rest: args[1], + }), + output: inst._def.output, + }); + } + return new F({ + type: "function", + input: args[0], + output: inst._def.output, + }); + }; + inst.output = (output) => { + const F = inst.constructor; + return new F({ + type: "function", + input: inst._def.input, + output, + }); + }; + return inst; +}))); +const $ZodPromise = /*@__PURE__*/ (/* unused pure expression or super */ null && (core.$constructor("$ZodPromise", (inst, def) => { + $ZodType.init(inst, def); + inst._zod.parse = (payload, ctx) => { + return Promise.resolve(payload.value).then((inner) => def.innerType._zod.run({ value: inner, issues: [] }, ctx)); + }; +}))); +const $ZodLazy = /*@__PURE__*/ $constructor("$ZodLazy", (inst, def) => { + $ZodType.init(inst, def); + // Cache the resolved inner type on the shared `def` so all clones of this lazy (e.g. via `.describe()`/`.meta()`) share the same inner instance, preserving identity for cycle detection on recursive schemas. + defineLazy(inst._zod, "innerType", () => { + const d = def; + if (!d._cachedInner) + d._cachedInner = def.getter(); + return d._cachedInner; + }); + defineLazyInternal(inst, "pattern", (zod) => zod.innerType?._zod?.pattern); + defineLazyInternal(inst, "propValues", (zod) => zod.innerType?._zod?.propValues); + defineLazyInternal(inst, "optin", (zod) => zod.innerType?._zod?.optin ?? undefined); + defineLazyInternal(inst, "optout", (zod) => zod.innerType?._zod?.optout ?? undefined); + inst._zod.parse = (payload, ctx) => { + const inner = inst._zod.innerType; + return inner._zod.run(payload, ctx); + }; +}); +const $ZodCustom = /*@__PURE__*/ $constructor("$ZodCustom", (inst, def) => { + $ZodCheck.init(inst, def); + $ZodType.init(inst, def); + inst._zod.parse = (payload, _) => { + return payload; + }; + inst._zod.check = (payload) => { + const input = payload.value; + const r = def.fn(input); + if (r instanceof Promise) { + return r.then((r) => handleRefineResult(r, payload, input, inst)); + } + handleRefineResult(r, payload, input, inst); + return; + }; +}); +function handleRefineResult(result, payload, input, inst) { + if (!result) { + const _iss = { + code: "custom", + input, + inst, // incorporates params.error into issue reporting + path: [...(inst._zod.def.path ?? [])], // incorporates params.error into issue reporting + continue: !inst._zod.def.abort, + // params: inst._zod.def.params, + }; + if (inst._zod.def.params) + _iss.params = inst._zod.def.params; + payload.issues.push(util_issue(_iss)); + } +} + +var registries_a; +const $output = /*@__PURE__*/ (/* unused pure expression or super */ null && (Symbol("ZodOutput"))); +const $input = /*@__PURE__*/ (/* unused pure expression or super */ null && (Symbol("ZodInput"))); +class $ZodRegistry { + constructor() { + this._map = new WeakMap(); + this._idmap = new Map(); + } + add(schema, ..._meta) { + const meta = _meta[0]; + this._map.set(schema, meta); + if (meta && typeof meta === "object" && "id" in meta) { + this._idmap.set(meta.id, schema); + } + return this; + } + clear() { + this._map = new WeakMap(); + this._idmap = new Map(); + return this; + } + remove(schema) { + const meta = this._map.get(schema); + if (meta && typeof meta === "object" && "id" in meta) { + this._idmap.delete(meta.id); + } + this._map.delete(schema); + return this; + } + get(schema) { + // return this._map.get(schema) as any; + // inherit metadata + const p = schema._zod.parent; + if (p) { + const pm = { ...(this.get(p) ?? {}) }; + delete pm.id; // do not inherit id + const f = { ...pm, ...this._map.get(schema) }; + return Object.keys(f).length ? f : undefined; + } + return this._map.get(schema); + } + has(schema) { + return this._map.has(schema); + } +} +// registries +function registries_registry() { + return new $ZodRegistry(); +} +(registries_a = globalThis).__zod_globalRegistry ?? (registries_a.__zod_globalRegistry = registries_registry()); +const globalRegistry = globalThis.__zod_globalRegistry; + + + + + +// @__NO_SIDE_EFFECTS__ +function _string(Class, params) { + return new Class({ + type: "string", + ...normalizeParams(params), + }); +} +// @__NO_SIDE_EFFECTS__ +function _coercedString(Class, params) { + return new Class({ + type: "string", + coerce: true, + ...util.normalizeParams(params), + }); +} +// @__NO_SIDE_EFFECTS__ +function _email(Class, params) { + return new Class({ + type: "string", + format: "email", + check: "string_format", + abort: false, + ...normalizeParams(params), + }); +} +// @__NO_SIDE_EFFECTS__ +function _guid(Class, params) { + return new Class({ + type: "string", + format: "guid", + check: "string_format", + abort: false, + ...normalizeParams(params), + }); +} +// @__NO_SIDE_EFFECTS__ +function _uuid(Class, params) { + return new Class({ + type: "string", + format: "uuid", + check: "string_format", + abort: false, + ...normalizeParams(params), + }); +} +// @__NO_SIDE_EFFECTS__ +function _uuidv4(Class, params) { + return new Class({ + type: "string", + format: "uuid", + check: "string_format", + abort: false, + version: "v4", + ...normalizeParams(params), + }); +} +// @__NO_SIDE_EFFECTS__ +function _uuidv6(Class, params) { + return new Class({ + type: "string", + format: "uuid", + check: "string_format", + abort: false, + version: "v6", + ...normalizeParams(params), + }); +} +// @__NO_SIDE_EFFECTS__ +function _uuidv7(Class, params) { + return new Class({ + type: "string", + format: "uuid", + check: "string_format", + abort: false, + version: "v7", + ...normalizeParams(params), + }); +} +// @__NO_SIDE_EFFECTS__ +function _url(Class, params) { + return new Class({ + type: "string", + format: "url", + check: "string_format", + abort: false, + ...normalizeParams(params), + }); +} +// @__NO_SIDE_EFFECTS__ +function api_emoji(Class, params) { + return new Class({ + type: "string", + format: "emoji", + check: "string_format", + abort: false, + ...normalizeParams(params), + }); +} +// @__NO_SIDE_EFFECTS__ +function _nanoid(Class, params) { + return new Class({ + type: "string", + format: "nanoid", + check: "string_format", + abort: false, + ...normalizeParams(params), + }); +} +/** + * @deprecated CUID v1 is deprecated by its authors due to information leakage + * (timestamps embedded in the id). Use {@link _cuid2} instead. + * See https://github.com/paralleldrive/cuid. + */ +// @__NO_SIDE_EFFECTS__ +function _cuid(Class, params) { + return new Class({ + type: "string", + format: "cuid", + check: "string_format", + abort: false, + ...normalizeParams(params), + }); +} +// @__NO_SIDE_EFFECTS__ +function _cuid2(Class, params) { + return new Class({ + type: "string", + format: "cuid2", + check: "string_format", + abort: false, + ...normalizeParams(params), + }); +} +// @__NO_SIDE_EFFECTS__ +function _ulid(Class, params) { + return new Class({ + type: "string", + format: "ulid", + check: "string_format", + abort: false, + ...normalizeParams(params), + }); +} +// @__NO_SIDE_EFFECTS__ +function _xid(Class, params) { + return new Class({ + type: "string", + format: "xid", + check: "string_format", + abort: false, + ...normalizeParams(params), + }); +} +// @__NO_SIDE_EFFECTS__ +function _ksuid(Class, params) { + return new Class({ + type: "string", + format: "ksuid", + check: "string_format", + abort: false, + ...normalizeParams(params), + }); +} +// @__NO_SIDE_EFFECTS__ +function _ipv4(Class, params) { + return new Class({ + type: "string", + format: "ipv4", + check: "string_format", + abort: false, + ...normalizeParams(params), + }); +} +// @__NO_SIDE_EFFECTS__ +function _ipv6(Class, params) { + return new Class({ + type: "string", + format: "ipv6", + check: "string_format", + abort: false, + ...normalizeParams(params), + }); +} +// @__NO_SIDE_EFFECTS__ +function _mac(Class, params) { + return new Class({ + type: "string", + format: "mac", + check: "string_format", + abort: false, + ...util.normalizeParams(params), + }); +} +// @__NO_SIDE_EFFECTS__ +function _cidrv4(Class, params) { + return new Class({ + type: "string", + format: "cidrv4", + check: "string_format", + abort: false, + ...normalizeParams(params), + }); +} +// @__NO_SIDE_EFFECTS__ +function _cidrv6(Class, params) { + return new Class({ + type: "string", + format: "cidrv6", + check: "string_format", + abort: false, + ...normalizeParams(params), + }); +} +// @__NO_SIDE_EFFECTS__ +function _base64(Class, params) { + return new Class({ + type: "string", + format: "base64", + check: "string_format", + abort: false, + ...normalizeParams(params), + }); +} +// @__NO_SIDE_EFFECTS__ +function _base64url(Class, params) { + return new Class({ + type: "string", + format: "base64url", + check: "string_format", + abort: false, + ...normalizeParams(params), + }); +} +// @__NO_SIDE_EFFECTS__ +function _e164(Class, params) { + return new Class({ + type: "string", + format: "e164", + check: "string_format", + abort: false, + ...normalizeParams(params), + }); +} +// @__NO_SIDE_EFFECTS__ +function _creditCard(Class, params) { + return new Class({ + type: "string", + format: "credit_card", + check: "string_format", + abort: false, + ...util.normalizeParams(params), + }); +} +// @__NO_SIDE_EFFECTS__ +function _jwt(Class, params) { + return new Class({ + type: "string", + format: "jwt", + check: "string_format", + abort: false, + ...normalizeParams(params), + }); +} +const TimePrecision = (/* unused pure expression or super */ null && ({ + Any: null, + Minute: -1, + Second: 0, + Millisecond: 3, + Microsecond: 6, +})); +// @__NO_SIDE_EFFECTS__ +function _isoDateTime(Class, params) { + return new Class({ + type: "string", + format: "datetime", + check: "string_format", + offset: false, + local: false, + precision: null, + ...normalizeParams(params), + }); +} +// @__NO_SIDE_EFFECTS__ +function _isoDate(Class, params) { + return new Class({ + type: "string", + format: "date", + check: "string_format", + ...normalizeParams(params), + }); +} +// @__NO_SIDE_EFFECTS__ +function _isoTime(Class, params) { + return new Class({ + type: "string", + format: "time", + check: "string_format", + precision: null, + ...normalizeParams(params), + }); +} +// @__NO_SIDE_EFFECTS__ +function _isoDuration(Class, params) { + return new Class({ + type: "string", + format: "duration", + check: "string_format", + ...normalizeParams(params), + }); +} +// @__NO_SIDE_EFFECTS__ +function _number(Class, params) { + return new Class({ + type: "number", + checks: [], + ...normalizeParams(params), + }); +} +// @__NO_SIDE_EFFECTS__ +function _coercedNumber(Class, params) { + return new Class({ + type: "number", + coerce: true, + checks: [], + ...normalizeParams(params), + }); +} +// @__NO_SIDE_EFFECTS__ +function _int(Class, params) { + return new Class({ + type: "number", + check: "number_format", + abort: false, + format: "safeint", + ...normalizeParams(params), + }); +} +// @__NO_SIDE_EFFECTS__ +function _float32(Class, params) { + return new Class({ + type: "number", + check: "number_format", + abort: false, + format: "float32", + ...util.normalizeParams(params), + }); +} +// @__NO_SIDE_EFFECTS__ +function _float64(Class, params) { + return new Class({ + type: "number", + check: "number_format", + abort: false, + format: "float64", + ...util.normalizeParams(params), + }); +} +// @__NO_SIDE_EFFECTS__ +function _int32(Class, params) { + return new Class({ + type: "number", + check: "number_format", + abort: false, + format: "int32", + ...util.normalizeParams(params), + }); +} +// @__NO_SIDE_EFFECTS__ +function _uint32(Class, params) { + return new Class({ + type: "number", + check: "number_format", + abort: false, + format: "uint32", + ...util.normalizeParams(params), + }); +} +// @__NO_SIDE_EFFECTS__ +function _boolean(Class, params) { + return new Class({ + type: "boolean", + ...normalizeParams(params), + }); +} +// @__NO_SIDE_EFFECTS__ +function _coercedBoolean(Class, params) { + return new Class({ + type: "boolean", + coerce: true, + ...util.normalizeParams(params), + }); +} +// @__NO_SIDE_EFFECTS__ +function _bigint(Class, params) { + return new Class({ + type: "bigint", + ...util.normalizeParams(params), + }); +} +// @__NO_SIDE_EFFECTS__ +function _coercedBigint(Class, params) { + return new Class({ + type: "bigint", + coerce: true, + ...util.normalizeParams(params), + }); +} +// @__NO_SIDE_EFFECTS__ +function _int64(Class, params) { + return new Class({ + type: "bigint", + check: "bigint_format", + abort: false, + format: "int64", + ...util.normalizeParams(params), + }); +} +// @__NO_SIDE_EFFECTS__ +function _uint64(Class, params) { + return new Class({ + type: "bigint", + check: "bigint_format", + abort: false, + format: "uint64", + ...util.normalizeParams(params), + }); +} +// @__NO_SIDE_EFFECTS__ +function _symbol(Class, params) { + return new Class({ + type: "symbol", + ...util.normalizeParams(params), + }); +} +// @__NO_SIDE_EFFECTS__ +function api_undefined(Class, params) { + return new Class({ + type: "undefined", + ...util.normalizeParams(params), + }); +} +// @__NO_SIDE_EFFECTS__ +function api_null(Class, params) { + return new Class({ + type: "null", + ...normalizeParams(params), + }); +} +// @__NO_SIDE_EFFECTS__ +function _any(Class) { + return new Class({ + type: "any", + }); +} +// @__NO_SIDE_EFFECTS__ +function _unknown(Class) { + return new Class({ + type: "unknown", + }); +} +// @__NO_SIDE_EFFECTS__ +function _never(Class, params) { + return new Class({ + type: "never", + ...normalizeParams(params), + }); +} +// @__NO_SIDE_EFFECTS__ +function _void(Class, params) { + return new Class({ + type: "void", + ...util.normalizeParams(params), + }); +} +// @__NO_SIDE_EFFECTS__ +function _date(Class, params) { + return new Class({ + type: "date", + ...util.normalizeParams(params), + }); +} +// @__NO_SIDE_EFFECTS__ +function _coercedDate(Class, params) { + return new Class({ + type: "date", + coerce: true, + ...util.normalizeParams(params), + }); +} +// @__NO_SIDE_EFFECTS__ +function _nan(Class, params) { + return new Class({ + type: "nan", + ...util.normalizeParams(params), + }); +} +// @__NO_SIDE_EFFECTS__ +function _lt(value, params) { + return new $ZodCheckLessThan({ + check: "less_than", + ...normalizeParams(params), + value, + inclusive: false, + }); +} +// @__NO_SIDE_EFFECTS__ +function _lte(value, params) { + return new $ZodCheckLessThan({ + check: "less_than", + ...normalizeParams(params), + value, + inclusive: true, + }); +} + +// @__NO_SIDE_EFFECTS__ +function _gt(value, params) { + return new $ZodCheckGreaterThan({ + check: "greater_than", + ...normalizeParams(params), + value, + inclusive: false, + }); +} +// @__NO_SIDE_EFFECTS__ +function _gte(value, params) { + return new $ZodCheckGreaterThan({ + check: "greater_than", + ...normalizeParams(params), + value, + inclusive: true, + }); +} + +// @__NO_SIDE_EFFECTS__ +function _positive(params) { + return _gt(0, params); +} +// negative +// @__NO_SIDE_EFFECTS__ +function _negative(params) { + return _lt(0, params); +} +// nonpositive +// @__NO_SIDE_EFFECTS__ +function _nonpositive(params) { + return _lte(0, params); +} +// nonnegative +// @__NO_SIDE_EFFECTS__ +function _nonnegative(params) { + return _gte(0, params); +} +// @__NO_SIDE_EFFECTS__ +function _multipleOf(value, params) { + return new $ZodCheckMultipleOf({ + check: "multiple_of", + ...normalizeParams(params), + value, + }); +} +// @__NO_SIDE_EFFECTS__ +function _maxSize(maximum, params) { + return new checks.$ZodCheckMaxSize({ + check: "max_size", + ...util.normalizeParams(params), + maximum, + }); +} +// @__NO_SIDE_EFFECTS__ +function _minSize(minimum, params) { + return new checks.$ZodCheckMinSize({ + check: "min_size", + ...util.normalizeParams(params), + minimum, + }); +} +// @__NO_SIDE_EFFECTS__ +function _size(size, params) { + return new checks.$ZodCheckSizeEquals({ + check: "size_equals", + ...util.normalizeParams(params), + size, + }); +} +// @__NO_SIDE_EFFECTS__ +function _maxLength(maximum, params) { + const ch = new $ZodCheckMaxLength({ + check: "max_length", + ...normalizeParams(params), + maximum, + }); + return ch; +} +// @__NO_SIDE_EFFECTS__ +function _minLength(minimum, params) { + return new $ZodCheckMinLength({ + check: "min_length", + ...normalizeParams(params), + minimum, + }); +} +// @__NO_SIDE_EFFECTS__ +function _length(length, params) { + return new $ZodCheckLengthEquals({ + check: "length_equals", + ...normalizeParams(params), + length, + }); +} +// @__NO_SIDE_EFFECTS__ +function _regex(pattern, params) { + return new $ZodCheckRegex({ + check: "string_format", + format: "regex", + ...normalizeParams(params), + pattern, + }); +} +// @__NO_SIDE_EFFECTS__ +function _lowercase(params) { + return new $ZodCheckLowerCase({ + check: "string_format", + format: "lowercase", + ...normalizeParams(params), + }); +} +// @__NO_SIDE_EFFECTS__ +function _uppercase(params) { + return new $ZodCheckUpperCase({ + check: "string_format", + format: "uppercase", + ...normalizeParams(params), + }); +} +// @__NO_SIDE_EFFECTS__ +function _includes(includes, params) { + return new $ZodCheckIncludes({ + check: "string_format", + format: "includes", + ...normalizeParams(params), + includes, + }); +} +// @__NO_SIDE_EFFECTS__ +function _startsWith(prefix, params) { + return new $ZodCheckStartsWith({ + check: "string_format", + format: "starts_with", + ...normalizeParams(params), + prefix, + }); +} +// @__NO_SIDE_EFFECTS__ +function _endsWith(suffix, params) { + return new $ZodCheckEndsWith({ + check: "string_format", + format: "ends_with", + ...normalizeParams(params), + suffix, + }); +} +// @__NO_SIDE_EFFECTS__ +function _property(property, schema, params) { + return new checks.$ZodCheckProperty({ + check: "property", + property, + schema, + ...util.normalizeParams(params), + }); +} +// @__NO_SIDE_EFFECTS__ +function _properties(shape) { + return Object.entries(shape).map(([property, schema]) => new checks.$ZodCheckProperty({ check: "property", property, schema })); +} +// @__NO_SIDE_EFFECTS__ +function _mime(types, params) { + return new checks.$ZodCheckMimeType({ + check: "mime_type", + mime: types, + ...util.normalizeParams(params), + }); +} +// @__NO_SIDE_EFFECTS__ +function _overwrite(tx) { + return new $ZodCheckOverwrite({ + check: "overwrite", + tx, + }); +} +// normalize +// @__NO_SIDE_EFFECTS__ +function _normalize(form) { + return _overwrite((input) => input.normalize(form)); +} +// trim +// @__NO_SIDE_EFFECTS__ +function _trim() { + return _overwrite((input) => input.trim()); +} +// toLowerCase +// @__NO_SIDE_EFFECTS__ +function _toLowerCase() { + return _overwrite((input) => input.toLowerCase()); +} +// toUpperCase +// @__NO_SIDE_EFFECTS__ +function _toUpperCase() { + return _overwrite((input) => input.toUpperCase()); +} +// slugify +// @__NO_SIDE_EFFECTS__ +function _slugify() { + return _overwrite((input) => slugify(input)); +} +// @__NO_SIDE_EFFECTS__ +function _array(Class, element, params) { + return new Class({ + type: "array", + element, + // get element() { + // return element; + // }, + ...normalizeParams(params), + }); +} +// @__NO_SIDE_EFFECTS__ +function _union(Class, options, params) { + return new Class({ + type: "union", + options, + ...util.normalizeParams(params), + }); +} +function _xor(Class, options, params) { + return new Class({ + type: "union", + options, + inclusive: false, + ...util.normalizeParams(params), + }); +} +// @__NO_SIDE_EFFECTS__ +function _discriminatedUnion(Class, discriminator, options, params) { + return new Class({ + type: "union", + options: options, + discriminator, + ...util.normalizeParams(params), + }); +} +// @__NO_SIDE_EFFECTS__ +function _intersection(Class, left, right) { + return new Class({ + type: "intersection", + left, + right, + }); +} +// export function _tuple( +// Class: util.SchemaClass, +// items: [], +// params?: string | $ZodTupleParams +// ): schemas.$ZodTuple<[], null>; +// @__NO_SIDE_EFFECTS__ +function _tuple(Class, items, _paramsOrRest, _params) { + const hasRest = _paramsOrRest instanceof schemas.$ZodType; + const params = hasRest ? _params : _paramsOrRest; + const rest = hasRest ? _paramsOrRest : null; + return new Class({ + type: "tuple", + items, + rest, + ...util.normalizeParams(params), + }); +} +// @__NO_SIDE_EFFECTS__ +function _record(Class, keyType, valueType, params) { + return new Class({ + type: "record", + keyType, + valueType, + ...util.normalizeParams(params), + }); +} +// @__NO_SIDE_EFFECTS__ +function _map(Class, keyType, valueType, params) { + return new Class({ + type: "map", + keyType, + valueType, + ...util.normalizeParams(params), + }); +} +// @__NO_SIDE_EFFECTS__ +function _set(Class, valueType, params) { + return new Class({ + type: "set", + valueType, + ...util.normalizeParams(params), + }); +} +// @__NO_SIDE_EFFECTS__ +function _enum(Class, values, params) { + const entries = Array.isArray(values) ? Object.fromEntries(values.map((v) => [v, v])) : values; + // if (Array.isArray(values)) { + // for (const value of values) { + // entries[value] = value; + // } + // } else { + // Object.assign(entries, values); + // } + // const entries: util.EnumLike = {}; + // for (const val of values) { + // entries[val] = val; + // } + return new Class({ + type: "enum", + entries, + ...util.normalizeParams(params), + }); +} +// @__NO_SIDE_EFFECTS__ +/** @deprecated This API has been merged into `z.enum()`. Use `z.enum()` instead. + * + * ```ts + * enum Colors { red, green, blue } + * z.enum(Colors); + * ``` + */ +function _nativeEnum(Class, entries, params) { + return new Class({ + type: "enum", + entries, + ...util.normalizeParams(params), + }); +} +// @__NO_SIDE_EFFECTS__ +function _literal(Class, value, params) { + return new Class({ + type: "literal", + values: Array.isArray(value) ? value : [value], + ...util.normalizeParams(params), + }); +} +// @__NO_SIDE_EFFECTS__ +function _file(Class, params) { + return new Class({ + type: "file", + ...util.normalizeParams(params), + }); +} +// @__NO_SIDE_EFFECTS__ +function _transform(Class, fn) { + return new Class({ + type: "transform", + transform: fn, + }); +} +// @__NO_SIDE_EFFECTS__ +function _optional(Class, innerType) { + return new Class({ + type: "optional", + innerType, + }); +} +// @__NO_SIDE_EFFECTS__ +function _nullable(Class, innerType) { + return new Class({ + type: "nullable", + innerType, + }); +} +// @__NO_SIDE_EFFECTS__ +function _default(Class, innerType, defaultValue) { + return new Class({ + type: "default", + innerType, + get defaultValue() { + return typeof defaultValue === "function" ? defaultValue() : util.shallowClone(defaultValue); + }, + }); +} +// @__NO_SIDE_EFFECTS__ +function _nonoptional(Class, innerType, params) { + return new Class({ + type: "nonoptional", + innerType, + ...util.normalizeParams(params), + }); +} +// @__NO_SIDE_EFFECTS__ +function _success(Class, innerType) { + return new Class({ + type: "success", + innerType, + }); +} +// @__NO_SIDE_EFFECTS__ +function _catch(Class, innerType, catchValue) { + return new Class({ + type: "catch", + innerType, + catchValue: (typeof catchValue === "function" ? catchValue : util.constantCatch(catchValue)), + }); +} +// @__NO_SIDE_EFFECTS__ +function _pipe(Class, in_, out) { + return new Class({ + type: "pipe", + in: in_, + out, + }); +} +// @__NO_SIDE_EFFECTS__ +function _readonly(Class, innerType) { + return new Class({ + type: "readonly", + innerType, + }); +} +// @__NO_SIDE_EFFECTS__ +function _templateLiteral(Class, parts, params) { + return new Class({ + type: "template_literal", + parts, + ...util.normalizeParams(params), + }); +} +// @__NO_SIDE_EFFECTS__ +function _lazy(Class, getter) { + return new Class({ + type: "lazy", + getter, + }); +} +// @__NO_SIDE_EFFECTS__ +function _promise(Class, innerType) { + return new Class({ + type: "promise", + innerType, + }); +} +// @__NO_SIDE_EFFECTS__ +function _custom(Class, fn, _params) { + const norm = util.normalizeParams(_params); + norm.abort ?? (norm.abort = true); // default to abort:false + const schema = new Class({ + type: "custom", + check: "custom", + fn: fn, + ...norm, + }); + return schema; +} +// same as _custom but defaults to abort:false +// @__NO_SIDE_EFFECTS__ +function _refine(Class, fn, _params) { + const schema = new Class({ + type: "custom", + check: "custom", + fn: fn, + ...normalizeParams(_params), + }); + return schema; +} +// @__NO_SIDE_EFFECTS__ +function _superRefine(fn, params) { + const ch = _check((payload) => { + payload.addIssue = (issue) => { + if (typeof issue === "string") { + payload.issues.push(util_issue(issue, payload.value, ch._zod.def)); + } + else { + // for Zod 3 backwards compatibility + const _issue = issue; + if (_issue.fatal) + _issue.continue = false; + _issue.code ?? (_issue.code = "custom"); + if (!("input" in _issue)) + _issue.input = payload.value; + _issue.inst ?? (_issue.inst = ch); + _issue.continue ?? (_issue.continue = !ch._zod.def.abort); // abort is always undefined, so this is always true... + payload.issues.push(util_issue(_issue)); + } + }; + return fn(payload.value, payload); + }, params); + return ch; +} +// @__NO_SIDE_EFFECTS__ +function _check(fn, params) { + const ch = new $ZodCheck({ + check: "custom", + ...normalizeParams(params), + }); + ch._zod.check = fn; + return ch; +} +// @__NO_SIDE_EFFECTS__ +function describe(description) { + const ch = new $ZodCheck({ check: "describe" }); + ch._zod.onattach = [ + (inst) => { + const existing = globalRegistry.get(inst) ?? {}; + globalRegistry.add(inst, { ...existing, description }); + }, + ]; + ch._zod.check = () => { }; // no-op check + return ch; +} +// @__NO_SIDE_EFFECTS__ +function api_meta(metadata) { + const ch = new $ZodCheck({ check: "meta" }); + ch._zod.onattach = [ + (inst) => { + const existing = globalRegistry.get(inst) ?? {}; + globalRegistry.add(inst, { ...existing, ...metadata }); + }, + ]; + ch._zod.check = () => { }; // no-op check + return ch; +} +// @__NO_SIDE_EFFECTS__ +function _stringbool(Classes, _params) { + const params = util.normalizeParams(_params); + let truthyArray = params.truthy ?? ["true", "1", "yes", "on", "y", "enabled"]; + let falsyArray = params.falsy ?? ["false", "0", "no", "off", "n", "disabled"]; + if (params.case !== "sensitive") { + truthyArray = truthyArray.map((v) => (typeof v === "string" ? v.toLowerCase() : v)); + falsyArray = falsyArray.map((v) => (typeof v === "string" ? v.toLowerCase() : v)); + } + const truthySet = new Set(truthyArray); + const falsySet = new Set(falsyArray); + const _Codec = Classes.Codec ?? schemas.$ZodCodec; + const _Boolean = Classes.Boolean ?? schemas.$ZodBoolean; + const _String = Classes.String ?? schemas.$ZodString; + const stringSchema = new _String({ type: "string", error: params.error }); + const booleanSchema = new _Boolean({ type: "boolean", error: params.error }); + const codec = new _Codec({ + type: "pipe", + in: stringSchema, + out: booleanSchema, + transform: ((input, payload) => { + let data = input; + if (params.case !== "sensitive") + data = data.toLowerCase(); + if (truthySet.has(data)) { + return true; + } + else if (falsySet.has(data)) { + return false; + } + else { + payload.issues.push({ + code: "invalid_value", + expected: "stringbool", + values: [...truthySet, ...falsySet], + input: payload.value, + inst: codec, + continue: false, + }); + return {}; + } + }), + reverseTransform: ((input, _payload) => { + if (input === true) { + return truthyArray[0] || "true"; + } + else { + return falsyArray[0] || "false"; + } + }), + error: params.error, + }); + codec._zod.bag.truthy = truthyArray; + codec._zod.bag.falsy = falsyArray; + codec._zod.bag.case = params.case ?? "insensitive"; + return codec; +} +// @__NO_SIDE_EFFECTS__ +function _stringFormat(Class, format, fnOrRegex, _params = {}) { + const params = util.normalizeParams(_params); + const def = { + check: "string_format", + type: "string", + format, + fn: typeof fnOrRegex === "function" ? fnOrRegex : (val) => fnOrRegex.test(val), + ...params, + }; + if (fnOrRegex instanceof RegExp) { + def.pattern = fnOrRegex; + } + const inst = new Class(def); + return inst; +} + + + +function assignProps(target, ...sources) { + for (const source of sources) { + for (const key of Reflect.ownKeys(source)) { + if (Object.prototype.propertyIsEnumerable.call(source, key)) { + assignProp(target, key, source[key]); + } + } + } + return target; +} +// function initializeContext(inputs: JSONSchemaGeneratorParams): ToJSONSchemaContext { +// return { +// processor: inputs.processor, +// metadataRegistry: inputs.metadata ?? globalRegistry, +// target: inputs.target ?? "draft-2020-12", +// unrepresentable: inputs.unrepresentable ?? "throw", +// }; +// } +function initializeContext(params) { + // Normalize target: convert old non-hyphenated versions to hyphenated versions + let target = params?.target ?? "draft-2020-12"; + if (target === "draft-4") + target = "draft-04"; + if (target === "draft-7") + target = "draft-07"; + return { + processors: params.processors ?? {}, + metadataRegistry: params?.metadata ?? globalRegistry, + target, + unrepresentable: params?.unrepresentable ?? "throw", + override: params?.override ?? (() => { }), + io: params?.io ?? "output", + counter: 0, + seen: new Map(), + sharedDefsExtractedFor: undefined, + sharedEmitDoneFor: undefined, + cycles: params?.cycles ?? "ref", + reused: params?.reused ?? "inline", + intersections: [], + deferred: [], + external: params?.external ?? undefined, + }; +} +/** + * Applies the `unrepresentable` setting at a site that has no JSON Schema equivalent. Throws + * `message` unless the setting (or the handler's return value) says otherwise. Returns `true` if a + * custom JSON Schema was written into `json`, in which case the caller must not write its own. + */ +function handleUnrepresentable(schema, ctx, json, params, message) { + const result = typeof ctx.unrepresentable === "function" + ? ctx.unrepresentable({ zodSchema: schema, path: params.path, message }) + : ctx.unrepresentable; + if (result === "any") + return false; + if (result === undefined || result === "throw") + throw new Error(message); + Object.assign(json, result); + return true; +} +function to_json_schema_process(schema, ctx, _params = { path: [], schemaPath: [] }) { + var _a; + const def = schema._zod.def; + // check for schema in seens + const seen = ctx.seen.get(schema); + if (seen) { + seen.count++; + // check if cycle + const isCycle = _params.schemaPath.includes(schema); + if (isCycle) { + seen.cycle = _params.path; + } + return seen.schema; + } + // initialize + const result = { schema: {}, count: 1, cycle: undefined, path: _params.path }; + ctx.seen.set(schema, result); + ctx.sharedDefsExtractedFor = undefined; + ctx.sharedEmitDoneFor = undefined; + // custom method overrides default behavior + const overrideSchema = schema._zod.toJSONSchema?.(); + if (overrideSchema) { + result.schema = overrideSchema; + } + else { + const params = { + ..._params, + schemaPath: [..._params.schemaPath, schema], + path: _params.path, + }; + if (schema._zod.processJSONSchema) { + schema._zod.processJSONSchema(ctx, result.schema, params); + } + else { + const _json = result.schema; + const processor = ctx.processors[def.type]; + if (!processor) { + throw new Error(`[toJSONSchema]: Non-representable type encountered: ${def.type}`); + } + processor(schema, ctx, _json, params); + } + const parent = schema._zod.parent; + if (parent) { + // Also set ref if processor didn't (for inheritance) + if (!result.ref) + result.ref = parent; + to_json_schema_process(parent, ctx, params); + ctx.seen.get(parent).isParent = true; + } + } + // metadata + const meta = ctx.metadataRegistry.get(schema); + if (meta) + assignProps(result.schema, meta); + if (ctx.io === "input" && isTransforming(schema)) { + // examples/defaults only apply to output type of pipe + delete result.schema.examples; + delete result.schema.default; + } + // set prefault as default + if (ctx.io === "input" && "_prefault" in result.schema) + (_a = result.schema).default ?? (_a.default = result.schema._prefault); + delete result.schema._prefault; + // pulling fresh from ctx.seen in case it was overwritten + const _result = ctx.seen.get(schema); + return _result.schema; +} +// Escape a reference token for use in a JSON Pointer fragment (RFC 6901): `~` becomes `~0` and `/` becomes `~1`. The `~` replacement must run first. +function encodeJSONPointerSegment(segment) { + return segment.replace(/~/g, "~0").replace(/\//g, "~1"); +} +function extractDefs(ctx, schema +// params: EmitParams +) { + // iterate over seen map; + const root = ctx.seen.get(schema); + if (!root) + throw new Error("Unprocessed schema. This is a bug in Zod."); + // With `external` set, every registered schema resolves through the external branch of `makeURI`, so the root branch below produces the same ref the external branch would — this pass is identical whichever schema it is called with, and only needs to run once. + if (ctx.external && ctx.sharedDefsExtractedFor === ctx.external) + return; + // Track ids to detect duplicates across different schemas + const idToSchema = new Map(); + for (const entry of ctx.seen.entries()) { + const id = ctx.metadataRegistry.get(entry[0])?.id; + if (id) { + const existing = idToSchema.get(id); + if (existing && existing !== entry[0]) { + throw new Error(`Duplicate schema id "${id}" detected during JSON Schema conversion. Two different schemas cannot share the same id when converted together.`); + } + idToSchema.set(id, entry[0]); + } + } + // returns a ref to the schema defId will be empty if the ref points to an external schema (or #) + const makeURI = (entry) => { + // comparing the seen objects because sometimes multiple schemas map to the same seen object. e.g. lazy + // external is configured + const defsSegment = ctx.target === "draft-2020-12" ? "$defs" : "definitions"; + if (ctx.external) { + const externalId = ctx.external.registry.get(entry[0])?.id; // ?? "__shared";// `__schema${ctx.counter++}`; + // check if schema is in the external registry + const uriGenerator = ctx.external.uri ?? ((id) => id); + if (externalId) { + return { ref: uriGenerator(externalId) }; + } + // otherwise, add to __shared + const id = entry[1].defId ?? entry[1].schema.id ?? `schema${ctx.counter++}`; + entry[1].defId = id; // set defId so it will be reused if needed + return { defId: id, ref: `${uriGenerator("__shared")}#/${defsSegment}/${encodeJSONPointerSegment(id)}` }; + } + const uriPrefix = `#`; + const defUriPrefix = `${uriPrefix}/${defsSegment}/`; + // an id-less root has nowhere to be extracted to, so it stays inline and self-references as `#` + if (entry[1] === root && !entry[1].schema.id) { + return { ref: uriPrefix }; + } + // self-contained schema + const defId = entry[1].schema.id ?? `__schema${ctx.counter++}`; + return { defId, ref: defUriPrefix + encodeJSONPointerSegment(defId) }; + }; + // stored cached version in `def` property remove all properties, set $ref + const extractToDef = (entry) => { + // if the schema is already a reference, do not extract it + if (entry[1].schema.$ref) { + return; + } + const seen = entry[1]; + const { ref, defId } = makeURI(entry); + seen.def = { ...seen.schema }; + // defId won't be set if the schema is a reference to an external schema or if the schema is the root schema + if (defId) + seen.defId = defId; + // wipe away all properties except $ref + const schema = seen.schema; + for (const key in schema) { + delete schema[key]; + } + schema.$ref = ref; + }; + // throw on cycles + // break cycles + if (ctx.cycles === "throw") { + for (const entry of ctx.seen.entries()) { + const seen = entry[1]; + if (seen.cycle) { + throw new Error("Cycle detected: " + + `#/${seen.cycle?.join("/")}/` + + '\n\nSet the `cycles` parameter to `"ref"` to resolve cyclical schemas with defs.'); + } + } + } + // extract schemas into $defs + for (const entry of ctx.seen.entries()) { + const seen = entry[1]; + // convert root schema to # $ref + if (schema === entry[0]) { + extractToDef(entry); // this has special handling for the root schema + continue; + } + // extract schemas that are in the external registry + if (ctx.external) { + const ext = ctx.external.registry.get(entry[0])?.id; + if (schema !== entry[0] && ext) { + extractToDef(entry); + continue; + } + } + // extract schemas with `id` meta + const id = ctx.metadataRegistry.get(entry[0])?.id; + if (id) { + extractToDef(entry); + continue; + } + // break cycles + if (seen.cycle) { + // any + extractToDef(entry); + continue; + } + // extract reused schemas + if (seen.count > 1) { + if (ctx.reused === "ref") { + extractToDef(entry); + // biome-ignore lint: + continue; + } + } + } + if (ctx.external) + ctx.sharedDefsExtractedFor = ctx.external; +} +/** Rewrites `anyOf: [{type: "a"}, {type: "b"}]` to `type: ["a", "b"]`, which every JSON Schema draft treats as equivalent and most consumers render far better for the nullable case. Only branches that are a bare type assertion qualify — anything carrying a constraint, `$ref`, `const` or metadata is left alone. Runs after `flattenRef`, so a branch an override decorated or `$defs` extraction turned into a `$ref` is no longer bare and correctly stays in `anyOf`. `oneOf` is excluded: `integer` and `number` overlap, so "exactly one" and "at least one" are not the same there. OpenAPI 3.0 is excluded: its `type` must be a single string. */ +function compactTypeUnion(schema) { + const options = schema.anyOf; + if (!Array.isArray(options) || options.length === 0 || schema.type !== undefined) + return; + const types = []; + for (const option of options) { + if (!option || typeof option !== "object") + return; + // A branch that is itself a compactible union folds into this one — nested `anyOf` and a flat `type` array say the same thing. Compacting it first also makes the result independent of the order this pass walks the seen map in. + compactTypeUnion(option); + const keys = Object.keys(option); + if (keys.length !== 1 || keys[0] !== "type") + return; + const type = option.type; + for (const member of Array.isArray(type) ? type : [type]) { + if (typeof member !== "string") + return; + if (!types.includes(member)) + types.push(member); + } + } + delete schema.anyOf; + // A `type` array must be non-empty and unique (metaschema); a single member is spelled as a bare string. + schema.type = types.length === 1 ? types[0] : types; +} +/** Keywords `foldIntersection` knows how to combine. Anything else — `$ref`, `patternProperties`, + * an annotation like `description` — makes a member unfoldable, so a constraint this does not + * understand leaves the `allOf` alone instead of being silently dropped or misattributed. */ +const FOLDABLE_KEYS = new Set(["type", "properties", "required", "additionalProperties"]); +const UNION_KEYS = ["oneOf", "anyOf"]; +/** A member's constraint on a key it does not declare itself. A `catchall` states one; `false`, an absent `additionalProperties`, and the empty schema a loose object emits state nothing. */ +function undeclaredConstraint(member) { + const extra = member.additionalProperties; + if (extra === undefined || extra === false || typeof extra !== "object" || extra === null) + return null; + return Object.keys(extra).length ? extra : null; +} +/** Combines object members into the single object they describe together, or returns `null` if any of them carries a keyword outside {@link FOLDABLE_KEYS}. */ +function foldObjects(members) { + const objects = []; + for (const member of members) { + // A boolean subschema is legal JSON Schema and carries no keywords to fold. + if (typeof member !== "object" || member.type !== "object") + return null; + for (const key in member) { + if (!FOLDABLE_KEYS.has(key)) + return null; + } + objects.push(member); + } + const properties = {}; + const required = new Set(); + for (const object of objects) { + for (const key in object.properties) { + // `in` would report a `__proto__` key as already present via the prototype chain and skip it. + if (Object.prototype.hasOwnProperty.call(properties, key)) + continue; + // Every member constrains this key: the ones that declare it say how, and a `catchall` member constrains it too even though it does not name it. The key has to satisfy all of them, which is the same intersection one level down. + const parts = []; + for (const other of objects) { + const part = other.properties?.[key] ?? undeclaredConstraint(other); + if (part === null || part === undefined) + continue; + if (!parts.some((seen) => JSON.stringify(seen) === JSON.stringify(part))) + parts.push(part); + } + const merged = parts.length === 1 + ? parts[0] + : (foldObjects(parts) ?? { allOf: parts }); + assignProp(properties, key, merged); + } + for (const key of object.required ?? []) + required.add(key); + } + const folded = { type: "object", properties }; + if (required.size) + folded.required = [...required]; + // A key no member declares is rejected only when every member rejects it, so the fold is closed only when every member is. Otherwise it carries whatever the `catchall` members demand of such a key. + if (objects.every((object) => object.additionalProperties === false)) { + folded.additionalProperties = false; + } + else { + const constraints = []; + for (const object of objects) { + const constraint = undeclaredConstraint(object); + if (constraint && !constraints.some((seen) => JSON.stringify(seen) === JSON.stringify(constraint))) + constraints.push(constraint); + } + if (constraints.length === 1) + folded.additionalProperties = constraints[0]; + else if (constraints.length > 1) + folded.additionalProperties = { allOf: constraints }; + } + return folded; +} +/** `additionalProperties` in an `allOf` member sees only that member's own `properties`, so two + * closed object members reject each other's keys and the schema validates nothing. Zod's parser + * pools the key sets instead — `handleIntersectionResults` reports a key as unrecognized only when + * *every* side rejects it — so the emitted schema has to pool them too, and folding the members + * into one object is the encoding that says so on every target. + * + * This runs from `finalize`, after `extractDefs`, which is what keeps it clear of the `$ref` + * machinery: a member extracted into `$defs` is already a `$ref` by now and declines to fold, so it + * keeps its reference and its own closedness rather than being inlined as a stale copy. */ +function foldIntersection(json) { + const allOf = json.allOf; + if (!Array.isArray(allOf) || allOf.length < 2) + return; + // An `override` runs before this pass and may have written object keywords onto the intersection itself. Those are deliberate, so decline rather than overwrite them. + for (const key of FOLDABLE_KEYS) + if (key in json) + return; + // An intersection distributes over a union: `A & (X | Y)` is `(A & X) | (A & Y)`. Only the first union is distributed over; a second one stays among the members every branch folds against, where it fails the object check and declines the whole intersection rather than multiplying out. + const unions = allOf.filter((m) => UNION_KEYS.some((k) => Array.isArray(m[k]))); + let folded = null; + if (!unions.length) { + folded = foldObjects(allOf); + } + else { + const union = unions[0]; + const keyword = UNION_KEYS.find((k) => Array.isArray(union[k])); + if (Object.keys(union).length !== 1) + return; + const rest = allOf.filter((m) => m !== union); + const branches = union[keyword].map((branch) => foldObjects([...rest, branch])); + if (branches.some((b) => !b)) + return; + folded = { [keyword]: branches }; + } + if (!folded) + return; + delete json.allOf; + assignProps(json, folded); +} +function finalize(ctx, schema) { + const root = ctx.seen.get(schema); + if (!root) + throw new Error("Unprocessed schema. This is a bug in Zod."); + // flatten refs - inherit properties from parent schemas + const flattenRef = (zodSchema) => { + const seen = ctx.seen.get(zodSchema); + // already processed + if (seen.ref === null) + return; + const schema = seen.def ?? seen.schema; + const _cached = { ...schema }; + const ref = seen.ref; + seen.ref = null; // prevent infinite recursion + if (ref) { + flattenRef(ref); + const refSeen = ctx.seen.get(ref); + const refSchema = refSeen.schema; + // merge referenced schema into current + if (refSchema.$ref && (ctx.target === "draft-07" || ctx.target === "draft-04" || ctx.target === "openapi-3.0")) { + // older drafts can't combine $ref with other properties + schema.allOf = schema.allOf ?? []; + schema.allOf.push(refSchema); + } + else { + assignProps(schema, refSchema); + } + // restore child's own properties (child wins) + assignProps(schema, _cached); + const isParentRef = zodSchema._zod.parent === ref; + // For parent chain, child is a refinement - remove parent-only properties + if (isParentRef) { + for (const key in schema) { + if (key === "$ref" || key === "allOf") + continue; + if (!(key in _cached)) { + delete schema[key]; + } + } + } + // When ref was extracted to $defs, remove properties that match the definition + if (refSchema.$ref && refSeen.def) { + for (const key in schema) { + if (key === "$ref" || key === "allOf") + continue; + if (key in refSeen.def && JSON.stringify(schema[key]) === JSON.stringify(refSeen.def[key])) { + delete schema[key]; + } + } + } + } + // If parent was extracted (has $ref), propagate $ref to this schema. This handles cases like: readonly().meta({id}).describe() where processor sets ref to innerType but parent should be referenced + const parent = zodSchema._zod.parent; + if (parent && parent !== ref) { + // Ensure parent is processed first so its def has inherited properties + flattenRef(parent); + const parentSeen = ctx.seen.get(parent); + if (parentSeen?.schema.$ref) { + schema.$ref = parentSeen.schema.$ref; + // De-duplicate with parent's definition + if (parentSeen.def) { + for (const key in schema) { + if (key === "$ref" || key === "allOf") + continue; + if (key in parentSeen.def && JSON.stringify(schema[key]) === JSON.stringify(parentSeen.def[key])) { + delete schema[key]; + } + } + } + } + } + // execute overrides + ctx.override({ + zodSchema: zodSchema, + jsonSchema: schema, + path: seen.path ?? [], + }); + }; + // Flattening walks the whole map and clears each `ref` as it goes, so a second call over the same map is a no-op scan. Skip it outright once it has run for a registry conversion. + if (!ctx.external || ctx.sharedEmitDoneFor !== ctx.external) { + for (const entry of [...ctx.seen.entries()].reverse()) { + flattenRef(entry[0]); + } + if (ctx.target !== "openapi-3.0") { + for (const entry of ctx.seen.entries()) { + compactTypeUnion(entry[1].def ?? entry[1].schema); + } + } + for (const rewrite of ctx.deferred) + rewrite(); + // After flattening, every member that was extracted is a `$ref`, so the fold sees the final shape. A schema that inherits an intersection — through `z.lazy`, or any `ref` chain — holds the same `allOf` array, so fold by array identity to catch every copy. + if (ctx.intersections.length) { + const carriers = new Map(); + for (const seen of ctx.seen.values()) { + for (const json of [seen.schema, seen.def]) { + const allOf = json?.allOf; + if (!Array.isArray(allOf)) + continue; + const existing = carriers.get(allOf); + if (existing) + existing.push(json); + else + carriers.set(allOf, [json]); + } + } + for (const allOf of ctx.intersections) { + for (const json of carriers.get(allOf) ?? []) + foldIntersection(json); + } + } + } + const result = {}; + if (ctx.target === "draft-2020-12") { + result.$schema = "https://json-schema.org/draft/2020-12/schema"; + } + else if (ctx.target === "draft-07") { + result.$schema = "http://json-schema.org/draft-07/schema#"; + } + else if (ctx.target === "draft-04") { + result.$schema = "http://json-schema.org/draft-04/schema#"; + } + else if (ctx.target === "openapi-3.0") { + // OpenAPI 3.0 schema objects should not include a $schema property + } + else { + // Arbitrary string values are allowed but won't have a $schema property set + } + if (ctx.external?.uri) { + const id = ctx.external.registry.get(schema)?.id; + if (!id) + throw new Error("Schema is missing an `id` property"); + result.$id = ctx.external.uri(id); + } + // when the root was extracted into $defs, `root.schema` is the `$ref` wrapper and `root.def` is the body that now lives under $defs + assignProps(result, root.defId ? root.schema : (root.def ?? root.schema)); + // The `id` in `.meta()` is a Zod-specific registration tag used to extract schemas into $defs — it is not user-facing JSON Schema metadata. Strip it from the output body where it would otherwise leak. The id is preserved implicitly via the $defs key (and via $ref paths). + const rootMetaId = ctx.metadataRegistry.get(schema)?.id; + if (rootMetaId !== undefined && result.id === rootMetaId) + delete result.id; + // build defs object. With `external`, `defs` is the shared object every schema writes into, so the same entries are reassigned on every call. Without it, `defs` is fresh per call and must be rebuilt. + const defs = ctx.external?.defs ?? {}; + if (!ctx.external || ctx.sharedEmitDoneFor !== ctx.external) { + for (const entry of ctx.seen.entries()) { + const seen = entry[1]; + if (seen.def && seen.defId) { + if (seen.def.id === seen.defId) + delete seen.def.id; + assignProp(defs, seen.defId, seen.def); + } + } + } + if (ctx.external) + ctx.sharedEmitDoneFor = ctx.external; + // set definitions in result + if (ctx.external) { + } + else { + if (Object.keys(defs).length > 0) { + if (ctx.target === "draft-2020-12") { + result.$defs = defs; + } + else { + result.definitions = defs; + } + } + } + try { + // this "finalizes" this schema and ensures all cycles are removed each call to finalize() is functionally independent though the seen map is shared + const finalized = JSON.parse(JSON.stringify(result)); + Object.defineProperty(finalized, "~standard", { + value: { + ...schema["~standard"], + jsonSchema: { + input: createStandardJSONSchemaMethod(schema, "input", ctx.processors), + output: createStandardJSONSchemaMethod(schema, "output", ctx.processors), + }, + }, + enumerable: false, + writable: false, + }); + return finalized; + } + catch (_err) { + throw new Error("Error converting schema to JSON."); + } +} +function isTransforming(_schema, _ctx) { + const ctx = _ctx ?? { seen: new Set() }; + if (ctx.seen.has(_schema)) + return false; + ctx.seen.add(_schema); + const def = _schema._zod.def; + if (def.type === "transform") + return true; + if (def.type === "array") + return isTransforming(def.element, ctx); + if (def.type === "set") + return isTransforming(def.valueType, ctx); + if (def.type === "lazy") + return isTransforming(def.getter(), ctx); + if (def.type === "promise" || + def.type === "optional" || + def.type === "nonoptional" || + def.type === "nullable" || + def.type === "readonly" || + def.type === "default" || + def.type === "prefault" || + def.type === "catch") { + return isTransforming(def.innerType, ctx); + } + if (def.type === "intersection") { + return isTransforming(def.left, ctx) || isTransforming(def.right, ctx); + } + if (def.type === "record" || def.type === "map") { + return isTransforming(def.keyType, ctx) || isTransforming(def.valueType, ctx); + } + if (def.type === "pipe") { + if (_schema._zod.traits.has("$ZodCodec")) + return true; + return isTransforming(def.in, ctx) || isTransforming(def.out, ctx); + } + if (def.type === "object") { + for (const key in def.shape) { + if (isTransforming(def.shape[key], ctx)) + return true; + } + return false; + } + if (def.type === "union") { + for (const option of def.options) { + if (isTransforming(option, ctx)) + return true; + } + return false; + } + if (def.type === "tuple") { + for (const item of def.items) { + if (isTransforming(item, ctx)) + return true; + } + if (def.rest && isTransforming(def.rest, ctx)) + return true; + return false; + } + return false; +} +/** + * Creates a toJSONSchema method for a schema instance. + * This encapsulates the logic of initializing context, processing, extracting defs, and finalizing. + */ +const createToJSONSchemaMethod = (schema, processors = {}) => (params) => { + const ctx = initializeContext({ ...params, processors }); + to_json_schema_process(schema, ctx); + extractDefs(ctx, schema); + return finalize(ctx, schema); +}; +const createStandardJSONSchemaMethod = (schema, io, processors = {}) => (params) => { + const { libraryOptions, target } = params ?? {}; + const ctx = initializeContext({ ...(libraryOptions ?? {}), target, io, processors }); + to_json_schema_process(schema, ctx); + extractDefs(ctx, schema); + return finalize(ctx, schema); +}; + + + + +const formatMap = { + guid: "uuid", + url: "uri", + datetime: "date-time", + json_string: "json-string", + regex: "", // do not set +}; +// ==================== SIMPLE TYPE PROCESSORS ==================== +const stringProcessor = (schema, ctx, _json, _params) => { + const json = _json; + json.type = "string"; + const { minimum, maximum, format, patterns, contentEncoding, laxFormat } = schema._zod + .bag; + if (typeof minimum === "number") + json.minLength = minimum; + if (typeof maximum === "number") + json.maxLength = maximum; + // custom pattern overrides format + if (format) { + json.format = formatMap[format] ?? format; + if (json.format === "") + delete json.format; // empty format is not valid + // `z.iso.time()` is never full-time, and `laxFormat` carries the datetime shapes that also accept what their keyword forbids + if (format === "time" || laxFormat) { + delete json.format; + } + } + if (contentEncoding) + json.contentEncoding = contentEncoding; + if (patterns && patterns.size > 0) { + const patternList = [...patterns]; + if (patternList.length === 1) + json.pattern = patternList[0].source; + else if (patternList.length > 1) { + json.allOf = [ + ...patternList.map((regex) => ({ + ...(ctx.target === "draft-07" || ctx.target === "draft-04" || ctx.target === "openapi-3.0" + ? { type: "string" } + : {}), + pattern: regex.source, + })), + ]; + } + } +}; +const numberProcessor = (schema, ctx, _json, params) => { + const json = _json; + const { minimum, maximum, format, multipleOf, exclusiveMaximum, exclusiveMinimum } = schema._zod.bag; + if (typeof format === "string" && format.includes("int")) + json.type = "integer"; + else + json.type = "number"; + // when both minimum and exclusiveMinimum exist, pick the more restrictive one + const exMin = typeof exclusiveMinimum === "number" && exclusiveMinimum >= (minimum ?? Number.NEGATIVE_INFINITY); + const exMax = typeof exclusiveMaximum === "number" && exclusiveMaximum <= (maximum ?? Number.POSITIVE_INFINITY); + const legacy = ctx.target === "draft-04" || ctx.target === "openapi-3.0"; + if (exMin) { + if (legacy) { + json.minimum = exclusiveMinimum; + json.exclusiveMinimum = true; + } + else { + json.exclusiveMinimum = exclusiveMinimum; + } + } + else if (typeof minimum === "number") { + json.minimum = minimum; + } + if (exMax) { + if (legacy) { + json.maximum = exclusiveMaximum; + json.exclusiveMaximum = true; + } + else { + json.exclusiveMaximum = exclusiveMaximum; + } + } + else if (typeof maximum === "number") { + json.maximum = maximum; + } + if (typeof multipleOf === "number") { + // JSON Schema requires a divisor strictly greater than zero, and a non-finite one does not survive JSON at all. A negative divisor accepts exactly what its absolute value accepts, so it still maps; zero, NaN and Infinity have no keyword form. + if (Number.isFinite(multipleOf) && multipleOf !== 0) + json.multipleOf = Math.abs(multipleOf); + else + handleUnrepresentable(schema, ctx, json, params, `A multipleOf divisor of ${multipleOf} cannot be represented in JSON Schema`); + } +}; +const booleanProcessor = (_schema, _ctx, json, _params) => { + json.type = "boolean"; +}; +const bigintProcessor = (schema, ctx, json, params) => { + handleUnrepresentable(schema, ctx, json, params, "BigInt cannot be represented in JSON Schema"); +}; +const symbolProcessor = (schema, ctx, json, params) => { + handleUnrepresentable(schema, ctx, json, params, "Symbols cannot be represented in JSON Schema"); +}; +const nullProcessor = (_schema, ctx, json, _params) => { + if (ctx.target === "openapi-3.0") { + json.type = "string"; + json.nullable = true; + json.enum = [null]; + } + else { + json.type = "null"; + } +}; +const undefinedProcessor = (schema, ctx, json, params) => { + handleUnrepresentable(schema, ctx, json, params, "Undefined cannot be represented in JSON Schema"); +}; +const voidProcessor = (schema, ctx, json, params) => { + handleUnrepresentable(schema, ctx, json, params, "Void cannot be represented in JSON Schema"); +}; +const neverProcessor = (_schema, _ctx, json, _params) => { + json.not = {}; +}; +const anyProcessor = (_schema, _ctx, _json, _params) => { + // empty schema accepts anything +}; +const unknownProcessor = (_schema, _ctx, _json, _params) => { + // empty schema accepts anything +}; +const dateProcessor = (schema, ctx, json, params) => { + handleUnrepresentable(schema, ctx, json, params, "Date cannot be represented in JSON Schema"); +}; +const enumProcessor = (schema, _ctx, json, _params) => { + const def = schema._zod.def; + const values = getEnumValues(def.entries); + // an empty enum accepts nothing, same as z.never() + if (values.length === 0) { + json.not = {}; + return; + } + // Number enums can have both string and number values + if (values.every((v) => typeof v === "number")) + json.type = "number"; + if (values.every((v) => typeof v === "string")) + json.type = "string"; + json.enum = values; +}; +const literalProcessor = (schema, ctx, json, params) => { + const def = schema._zod.def; + // a literal with no values accepts nothing, same as z.never() + if (def.values.length === 0) { + json.not = {}; + return; + } + const vals = []; + for (const val of def.values) { + if (val === undefined) { + // a custom schema replaces the whole literal, so there is nothing left to accumulate + if (handleUnrepresentable(schema, ctx, json, params, "Literal `undefined` cannot be represented in JSON Schema")) + return; + // otherwise do not add to vals + } + else if (typeof val === "bigint") { + if (handleUnrepresentable(schema, ctx, json, params, "BigInt literals cannot be represented in JSON Schema")) + return; + vals.push(Number(val)); + } + else { + vals.push(val); + } + } + if (vals.length === 0) { + // do nothing (an undefined literal was stripped) + } + else if (vals.length === 1) { + const val = vals[0]; + json.type = val === null ? "null" : typeof val; + if (ctx.target === "draft-04" || ctx.target === "openapi-3.0") { + json.enum = [val]; + } + else { + json.const = val; + } + } + else { + if (vals.every((v) => typeof v === "number")) + json.type = "number"; + if (vals.every((v) => typeof v === "string")) + json.type = "string"; + if (vals.every((v) => typeof v === "boolean")) + json.type = "boolean"; + if (vals.every((v) => v === null)) + json.type = "null"; + json.enum = vals; + } +}; +const nanProcessor = (schema, ctx, json, params) => { + handleUnrepresentable(schema, ctx, json, params, "NaN cannot be represented in JSON Schema"); +}; +const templateLiteralProcessor = (schema, _ctx, json, _params) => { + const _json = json; + const pattern = schema._zod.pattern; + if (!pattern) + throw new Error("Pattern not found in template literal"); + _json.type = "string"; + _json.pattern = pattern.source; +}; +const fileProcessor = (schema, _ctx, json, _params) => { + const _json = json; + const file = { + type: "string", + format: "binary", + contentEncoding: "binary", + }; + const { minimum, maximum, mime } = schema._zod.bag; + if (minimum !== undefined) + file.minLength = minimum; + if (maximum !== undefined) + file.maxLength = maximum; + if (mime) { + if (mime.length === 1) { + file.contentMediaType = mime[0]; + Object.assign(_json, file); + } + else { + Object.assign(_json, file); // shared props at root + _json.anyOf = mime.map((m) => ({ contentMediaType: m })); // only contentMediaType differs + } + } + else { + Object.assign(_json, file); + } +}; +const successProcessor = (_schema, _ctx, json, _params) => { + json.type = "boolean"; +}; +const customProcessor = (schema, ctx, json, params) => { + handleUnrepresentable(schema, ctx, json, params, "Custom types cannot be represented in JSON Schema"); +}; +const functionProcessor = (schema, ctx, json, params) => { + handleUnrepresentable(schema, ctx, json, params, "Function types cannot be represented in JSON Schema"); +}; +const transformProcessor = (schema, ctx, json, params) => { + handleUnrepresentable(schema, ctx, json, params, "Transforms cannot be represented in JSON Schema"); +}; +const mapProcessor = (schema, ctx, json, params) => { + handleUnrepresentable(schema, ctx, json, params, "Map cannot be represented in JSON Schema"); +}; +const setProcessor = (schema, ctx, json, params) => { + handleUnrepresentable(schema, ctx, json, params, "Set cannot be represented in JSON Schema"); +}; +// ==================== COMPOSITE TYPE PROCESSORS ==================== +const arrayProcessor = (schema, ctx, _json, params) => { + const json = _json; + const def = schema._zod.def; + const { minimum, maximum } = schema._zod.bag; + if (typeof minimum === "number") + json.minItems = minimum; + if (typeof maximum === "number") + json.maxItems = maximum; + json.type = "array"; + json.items = to_json_schema_process(def.element, ctx, { + ...params, + path: [...params.path, "items"], + }); +}; +// Transform and catch set `optin = "optional"` at runtime so the parser lets them observe an +// absent key, but their declared input type stays required. An input JSON Schema describes the +// declared type, so resolve past them to the schema that actually carries the optionality. +// Used by both `objectProcessor` (for `required`) and `tupleProcessor` (for `minItems`); see +// wiki/optionality.md, "The JSON Schema emitter reads the *static* value". +function inputOptin(schema) { + const def = schema._zod.def; + if (def.type === "pipe" && def.in._zod.traits.has("$ZodTransform")) { + return inputOptin(def.out); + } + if (def.type === "catch") { + return inputOptin(def.innerType); + } + return schema._zod.optin; +} +const objectProcessor = (schema, ctx, _json, params) => { + const json = _json; + const def = schema._zod.def; + const shape = def.shape; + // dropping it while still emitting `additionalProperties: false` would emit a schema that rejects data this one requires + const symbolKeys = Object.getOwnPropertySymbols(shape); + if (symbolKeys.length && + handleUnrepresentable(schema, ctx, json, params, "Symbol keys cannot be represented in JSON Schema")) { + return; + } + json.type = "object"; + json.properties = {}; + for (const key in shape) { + // assignProp so a __proto__ key becomes an own property instead of hitting the inherited setter on the plain {} we build into + assignProp(json.properties, key, to_json_schema_process(shape[key], ctx, { + ...params, + path: [...params.path, "properties", key], + })); + } + // required keys + const allKeys = new Set(Object.keys(shape)); + const requiredKeys = new Set([...allKeys].filter((key) => { + const field = def.shape[key]; + if (ctx.io === "input") { + return inputOptin(field) === undefined; + } + else { + return field._zod.optout === undefined; + } + })); + if (requiredKeys.size > 0) { + json.required = Array.from(requiredKeys); + } + // catchall + if (def.catchall?._zod.def.type === "never") { + // strict + json.additionalProperties = false; + } + else if (!def.catchall) { + // regular + if (ctx.io === "output") + json.additionalProperties = false; + } + else if (def.catchall) { + json.additionalProperties = to_json_schema_process(def.catchall, ctx, { + ...params, + path: [...params.path, "additionalProperties"], + }); + } +}; +const unionProcessor = (schema, ctx, json, params) => { + const def = schema._zod.def; + // Exclusive unions (inclusive === false) use oneOf (exactly one match) instead of anyOf (one or more matches). This includes both z.xor() and discriminated unions + const isExclusive = def.inclusive === false; + const options = def.options.map((x, i) => to_json_schema_process(x, ctx, { + ...params, + path: [...params.path, isExclusive ? "oneOf" : "anyOf", i], + })); + if (isExclusive) { + json.oneOf = options; + } + else { + json.anyOf = options; + } +}; +const intersectionProcessor = (schema, ctx, json, params) => { + const def = schema._zod.def; + const a = to_json_schema_process(def.left, ctx, { + ...params, + path: [...params.path, "allOf", 0], + }); + const b = to_json_schema_process(def.right, ctx, { + ...params, + path: [...params.path, "allOf", 1], + }); + const isSimpleIntersection = (val) => "allOf" in val && Object.keys(val).length === 1; + const allOf = [ + ...(isSimpleIntersection(a) ? a.allOf : [a]), + ...(isSimpleIntersection(b) ? b.allOf : [b]), + ]; + json.allOf = allOf; + // Recorded innermost first, so a nested intersection has already folded by the time this one is considered. The array is the handle rather than the schema, because a wrapper that inherits this schema shares the same array; `finalize` folds every object holding it. See `foldIntersection`. + ctx.intersections.push(allOf); +}; +const tupleProcessor = (schema, ctx, _json, params) => { + const json = _json; + const def = schema._zod.def; + json.type = "array"; + const prefixPath = ctx.target === "draft-2020-12" ? "prefixItems" : "items"; + const restPath = ctx.target === "draft-2020-12" ? "items" : ctx.target === "openapi-3.0" ? "items" : "additionalItems"; + const prefixItems = def.items.map((x, i) => to_json_schema_process(x, ctx, { + ...params, + path: [...params.path, prefixPath, i], + })); + const rest = def.rest + ? to_json_schema_process(def.rest, ctx, { + ...params, + path: [...params.path, restPath, ...(ctx.target === "openapi-3.0" ? [def.items.length] : [])], + }) + : null; + let minItems = def.items.length; + while (minItems > 0) { + const item = def.items[minItems - 1]; + const optional = ctx.io === "input" ? inputOptin(item) !== undefined : item._zod.optout === "optional"; + if (!optional) + break; + minItems--; + } + const maxItems = def.items.length; + const isClosed = !def.rest; + if (ctx.target === "draft-2020-12") { + json.prefixItems = prefixItems; + if (isClosed) { + json.items = false; + } + else if (rest) { + json.items = rest; + } + if (minItems > 0) + json.minItems = minItems; + if (isClosed) + json.maxItems = maxItems; + } + else if (ctx.target === "openapi-3.0") { + json.items = { + anyOf: prefixItems, + }; + if (rest) { + json.items.anyOf.push(rest); + } + if (minItems > 0) + json.minItems = minItems; + if (isClosed) + json.maxItems = maxItems; + } + else { + json.items = prefixItems; + if (isClosed) { + json.additionalItems = false; + } + else if (rest) { + json.additionalItems = rest; + } + if (minItems > 0) + json.minItems = minItems; + if (isClosed) + json.maxItems = maxItems; + } + // explicit user-defined length checks take precedence + const { minimum, maximum } = schema._zod.bag; + if (typeof minimum === "number") + json.minItems = minimum; + if (typeof maximum === "number") + json.maxItems = maximum; +}; +/** JSON object keys are always strings, so a numeric record key schema is re-expressed over the + * numeric-string form the record parser matches. Deferred to `finalize`, after the flatten: a key + * behind a wrapper only carries its own `type` before then, and a union key only has its branches. + * + * A numeric bound cannot apply to a property name, so `minimum` and its siblings are dropped rather + * than carried over: keeping them beside `type: "string"` reproduces the match-nothing schema this + * exists to fix. A key that carries one therefore emits wider than the record parses — `z.record(z.number().min(5), V)` + * accepts `"3"` — which is the deliberate trade, since throwing on it would reject an ordinary schema + * outright. */ +function stringifyKeyNames(bySchema, json, visited) { + // an extracted key that rewrites cannot go on sharing its definition — the string form a key position needs is not the number form every other reference wants — so it inlines. One that does not rewrite keeps the `$ref`. + if (json.$ref) { + // a recursive key holds its own reference inside its definition, so a node already on the path is left alone rather than resolved again + if (visited.has(json)) + return json; + visited.add(json); + const def = bySchema.get(json)?.def; + if (!def) + return json; + const inlined = stringifyKeyNames(bySchema, def, visited); + return inlined === def ? json : inlined; + } + for (const keyword of ["anyOf", "oneOf"]) { + const branches = json[keyword]; + if (!Array.isArray(branches)) + continue; + const mapped = branches.map((branch) => stringifyKeyNames(bySchema, branch, visited)); + // rebuilding regardless would detach a key that had nothing to re-express, dropping its `$ref` and leaking the internal `id` + if (mapped.some((branch, i) => branch !== branches[i])) + json = { ...json, [keyword]: mapped }; + } + // a member that already admits a string leaves the key unconstrained, so the node's own type re-expresses only when every member is numeric + const types = Array.isArray(json.type) ? json.type : [json.type]; + const numericType = !types.includes("string") && types.some((t) => t === "number" || t === "integer"); + // a heterogeneous key carries no type at all, so its numeric members are caught here instead + const values = json.enum ?? (json.const !== undefined ? [json.const] : undefined); + if (!numericType && !values?.some((v) => typeof v === "number")) + return json; + const { minimum, maximum, exclusiveMinimum, exclusiveMaximum, multipleOf, format, id, ...rest } = json; + if (rest.enum) + rest.enum = rest.enum.map((v) => (typeof v === "number" ? String(v) : v)); + else if (typeof rest.const === "number") + rest.const = String(rest.const); + // a heterogeneous key keeps its absent type: the stringified members already say what a key may be + if (!numericType) + return rest; + rest.type = "string"; + if (!values) + rest.pattern = (types.includes("number") ? number : integer).source; + return rest; +} +/** Every record of one conversion, so the carriers are found in a single pass rather than once per record. */ +const pendingRecords = new WeakMap(); +function rewriteKeyNames(ctx) { + // an extracted key is resolved by the object `extractToDef` left in its place, so the map is built once rather than searched per reference. `_zod.toJSONSchema` can hand the same object to two schemas, so the first entry carrying a body wins, as a search would have found it. + const bySchema = new Map(); + for (const entry of ctx.seen.values()) { + if (entry.def && !bySchema.has(entry.schema)) + bySchema.set(entry.schema, entry); + } + const rewrites = new Map(); + for (const record of pendingRecords.get(ctx) ?? []) { + const seen = ctx.seen.get(record); + const names = (seen?.def ?? seen?.schema)?.propertyNames; + if (!names || names === true || rewrites.has(names)) + continue; + const rewritten = stringifyKeyNames(bySchema, names, new Set()); + if (rewritten !== names) + rewrites.set(names, rewritten); + } + if (!rewrites.size) + return; + // the flatten has already copied each record's own properties onto every wrapper by reference, and an extracted body is another such copy, so every carrier holding a rewritten key is updated together + for (const entry of ctx.seen.values()) { + for (const carrier of [entry.schema, entry.def]) { + const rewritten = carrier && rewrites.get(carrier.propertyNames); + if (rewritten) + carrier.propertyNames = rewritten; + } + } +} +const recordProcessor = (schema, ctx, _json, params) => { + const json = _json; + const def = schema._zod.def; + json.type = "object"; + // For looseRecord with regex patterns, use patternProperties. This correctly represents "only validate keys matching the pattern" semantics and composes well with allOf (intersections) + const keyType = def.keyType; + const keyBag = keyType._zod.bag; + const patterns = keyBag?.patterns; + if (def.mode === "loose" && patterns && patterns.size > 0) { + // Use patternProperties for looseRecord with regex patterns + const valueSchema = to_json_schema_process(def.valueType, ctx, { + ...params, + path: [...params.path, "patternProperties", "*"], + }); + json.patternProperties = {}; + for (const pattern of patterns) { + assignProp(json.patternProperties, pattern.source, valueSchema); + } + } + else { + // Default behavior: use propertyNames + additionalProperties + if (ctx.target === "draft-07" || ctx.target === "draft-2020-12") { + json.propertyNames = to_json_schema_process(def.keyType, ctx, { + ...params, + path: [...params.path, "propertyNames"], + }); + let pending = pendingRecords.get(ctx); + if (!pending) { + pending = []; + pendingRecords.set(ctx, pending); + ctx.deferred.push(() => rewriteKeyNames(ctx)); + } + pending.push(schema); + } + json.additionalProperties = to_json_schema_process(def.valueType, ctx, { + ...params, + path: [...params.path, "additionalProperties"], + }); + } + // Add required for keys with discrete values (enum, literal, etc.) + const keyValues = keyType._zod.values; + // Every key shares one value schema, so an optional-in value makes the whole key set omittable on input. Output keeps them: the exhaustive branch assigns every key, even one whose value came back undefined. + const omittableOnInput = ctx.io === "input" && inputOptin(def.valueType) !== undefined; + if (keyValues && !def.partial && !omittableOnInput) { + const validKeyValues = [...keyValues].filter((v) => typeof v === "string" || typeof v === "number"); + if (validKeyValues.length > 0) { + json.required = validKeyValues.map(String); + } + } +}; +const nullableProcessor = (schema, ctx, json, params) => { + const def = schema._zod.def; + const inner = to_json_schema_process(def.innerType, ctx, params); + const seen = ctx.seen.get(schema); + if (ctx.target === "openapi-3.0") { + seen.ref = def.innerType; + json.nullable = true; + } + else { + json.anyOf = [inner, { type: "null" }]; + } +}; +const nonoptionalProcessor = (schema, ctx, _json, params) => { + const def = schema._zod.def; + to_json_schema_process(def.innerType, ctx, params); + const seen = ctx.seen.get(schema); + seen.ref = def.innerType; +}; +/** Round-trips a default value through JSON so the emitted schema is guaranteed to be valid JSON. + * A BigInt has no reliable encoding, so it goes through `unrepresentable` like any other + * unrepresentable value. Returns a sentinel when the caller must not write a default of its own. */ +const UNREPRESENTABLE_DEFAULT = Symbol(); +function serializeDefaultValue(value, schema, ctx, json, params) { + let unrepresentable = false; + const serialized = JSON.stringify(value, (_, val) => { + if (typeof val !== "bigint") + return val; + unrepresentable = true; + return null; + }); + if (!unrepresentable) + return JSON.parse(serialized); + handleUnrepresentable(schema, ctx, json, params, "BigInt defaults cannot be represented in JSON Schema"); + return UNREPRESENTABLE_DEFAULT; +} +const defaultProcessor = (schema, ctx, json, params) => { + const def = schema._zod.def; + to_json_schema_process(def.innerType, ctx, params); + const seen = ctx.seen.get(schema); + seen.ref = def.innerType; + const value = serializeDefaultValue(def.defaultValue, schema, ctx, json, params); + if (value !== UNREPRESENTABLE_DEFAULT) + json.default = value; +}; +const prefaultProcessor = (schema, ctx, json, params) => { + const def = schema._zod.def; + to_json_schema_process(def.innerType, ctx, params); + const seen = ctx.seen.get(schema); + seen.ref = def.innerType; + if (ctx.io !== "input") + return; + const value = serializeDefaultValue(def.defaultValue, schema, ctx, json, params); + if (value !== UNREPRESENTABLE_DEFAULT) + json._prefault = value; +}; +const catchProcessor = (schema, ctx, json, params) => { + const def = schema._zod.def; + to_json_schema_process(def.innerType, ctx, params); + const seen = ctx.seen.get(schema); + seen.ref = def.innerType; + let catchValue; + try { + catchValue = def.catchValue(undefined); + } + catch { + handleUnrepresentable(schema, ctx, json, params, "Dynamic catch values are not supported in JSON Schema"); + return; + } + json.default = catchValue; +}; +const pipeProcessor = (schema, ctx, _json, params) => { + const def = schema._zod.def; + const inIsTransform = def.in._zod.traits.has("$ZodTransform"); + const innerType = ctx.io === "input" ? (inIsTransform ? def.out : def.in) : def.out; + to_json_schema_process(innerType, ctx, params); + const seen = ctx.seen.get(schema); + seen.ref = innerType; +}; +const readonlyProcessor = (schema, ctx, json, params) => { + const def = schema._zod.def; + to_json_schema_process(def.innerType, ctx, params); + const seen = ctx.seen.get(schema); + seen.ref = def.innerType; + json.readOnly = true; +}; +const promiseProcessor = (schema, ctx, _json, params) => { + const def = schema._zod.def; + to_json_schema_process(def.innerType, ctx, params); + const seen = ctx.seen.get(schema); + seen.ref = def.innerType; +}; +const optionalProcessor = (schema, ctx, _json, params) => { + const def = schema._zod.def; + to_json_schema_process(def.innerType, ctx, params); + const seen = ctx.seen.get(schema); + seen.ref = def.innerType; +}; +const lazyProcessor = (schema, ctx, _json, params) => { + const innerType = schema._zod.innerType; + to_json_schema_process(innerType, ctx, params); + const seen = ctx.seen.get(schema); + seen.ref = innerType; +}; +// ==================== ALL PROCESSORS ==================== +const allProcessors = { + string: stringProcessor, + number: numberProcessor, + boolean: booleanProcessor, + bigint: bigintProcessor, + symbol: symbolProcessor, + null: nullProcessor, + undefined: undefinedProcessor, + void: voidProcessor, + never: neverProcessor, + any: anyProcessor, + unknown: unknownProcessor, + date: dateProcessor, + enum: enumProcessor, + literal: literalProcessor, + nan: nanProcessor, + template_literal: templateLiteralProcessor, + file: fileProcessor, + success: successProcessor, + custom: customProcessor, + function: functionProcessor, + transform: transformProcessor, + map: mapProcessor, + set: setProcessor, + array: arrayProcessor, + object: objectProcessor, + union: unionProcessor, + intersection: intersectionProcessor, + tuple: tupleProcessor, + record: recordProcessor, + nullable: nullableProcessor, + nonoptional: nonoptionalProcessor, + default: defaultProcessor, + prefault: prefaultProcessor, + catch: catchProcessor, + pipe: pipeProcessor, + readonly: readonlyProcessor, + promise: promiseProcessor, + optional: optionalProcessor, + lazy: lazyProcessor, +}; +function toJSONSchema(input, params) { + if ("_idmap" in input) { + // Registry case + const registry = input; + const ctx = initializeContext({ ...params, processors: allProcessors }); + const defs = {}; + // First pass: process all schemas to build the seen map + for (const entry of registry._idmap.entries()) { + const [_, schema] = entry; + to_json_schema_process(schema, ctx); + } + const schemas = {}; + const external = { + registry, + uri: params?.uri, + defs, + }; + // Update the context with external configuration + ctx.external = external; + // Second pass: emit each schema + for (const entry of registry._idmap.entries()) { + const [key, schema] = entry; + extractDefs(ctx, schema); + assignProp(schemas, key, finalize(ctx, schema)); + } + if (Object.keys(defs).length > 0) { + const defsSegment = ctx.target === "draft-2020-12" ? "$defs" : "definitions"; + schemas.__shared = { + [defsSegment]: defs, + }; + } + return { schemas }; + } + // Single schema case + const ctx = initializeContext({ ...params, processors: allProcessors }); + to_json_schema_process(input, ctx); + extractDefs(ctx, input); + return finalize(ctx, input); +} + + +const en_error = () => { + const Sizable = { + string: { unit: "characters", verb: "to have" }, + file: { unit: "bytes", verb: "to have" }, + array: { unit: "items", verb: "to have" }, + set: { unit: "items", verb: "to have" }, + map: { unit: "entries", verb: "to have" }, + }; + function getSizing(origin) { + return Sizable[origin] ?? null; + } + const FormatDictionary = { + 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", + credit_card: "credit card number", + jwt: "JWT", + template_literal: "input", + }; + // type names: missing keys = do not translate (use raw value via ?? fallback) + const TypeDictionary = { + // Compatibility: "nan" -> "NaN" for display + nan: "NaN", + // All other type names omitted - they fall back to raw values via ?? operator + }; + function getTypeName(type, input) { + if (type === "number" && typeof input === "number" && !Number.isFinite(input)) { + return String(input); + } + return TypeDictionary[type] ?? type; + } + return (issue) => { + switch (issue.code) { + case "invalid_type": { + const expected = getTypeName(issue.expected); + const receivedType = parsedType(issue.input); + const received = getTypeName(receivedType, issue.input); + return `Invalid input: expected ${expected}, received ${received}`; + } + case "invalid_value": + if (issue.values.length === 1) + return `Invalid input: expected ${stringifyPrimitive(issue.values[0])}`; + return `Invalid option: expected one of ${joinValues(issue.values, "|")}`; + case "too_big": { + const adj = issue.exact ? "exactly " : issue.inclusive ? "<=" : "<"; + const sizing = getSizing(issue.origin); + if (sizing) + return `Too big: expected ${issue.origin ?? "value"} to have ${adj}${issue.maximum.toString()} ${sizing.unit ?? "elements"}`; + return `Too big: expected ${issue.origin ?? "value"} to be ${adj}${issue.maximum.toString()}`; + } + case "too_small": { + const adj = issue.exact ? "exactly " : issue.inclusive ? ">=" : ">"; + const sizing = getSizing(issue.origin); + if (sizing) { + return `Too small: expected ${issue.origin} to have ${adj}${issue.minimum.toString()} ${sizing.unit}`; + } + return `Too small: expected ${issue.origin} to be ${adj}${issue.minimum.toString()}`; + } + case "invalid_format": { + const _issue = issue; + if (_issue.format === "starts_with") { + return `Invalid string: must start with "${_issue.prefix}"`; + } + if (_issue.format === "ends_with") + return `Invalid string: must end with "${_issue.suffix}"`; + if (_issue.format === "includes") + return `Invalid string: must include "${_issue.includes}"`; + if (_issue.format === "regex") + return `Invalid string: must match pattern ${_issue.pattern}`; + return `Invalid ${FormatDictionary[_issue.format] ?? issue.format}`; + } + case "not_multiple_of": + return `Invalid number: must be a multiple of ${issue.divisor}`; + case "unrecognized_keys": + return `Unrecognized key${issue.keys.length > 1 ? "s" : ""}: ${joinValues(issue.keys, ", ")}`; + case "invalid_key": + return `Invalid key in ${issue.origin}`; + case "invalid_union": + if (issue.options && Array.isArray(issue.options) && issue.options.length > 0) { + const opts = issue.options.map((o) => `'${o}'`).join(" | "); + return `Invalid discriminator value. Expected ${opts}`; + } + if (issue.inclusive === false) { + return "Invalid input: more than one option matched"; + } + return "Invalid input"; + case "invalid_element": + return `Invalid value in ${issue.origin}`; + default: + return `Invalid input`; + } + }; +}; +/* export default */ function en() { + return { + localeError: en_error(), + }; +} + + + + +/* Prototypes that already carry the lazy helper methods. Seeded with the + * intrinsics so that `init` on a foreign object — it accepts any object — + * can never install an accessor onto a prototype we do not own. */ +const _installedErrorProtos = /* @__PURE__ */ new WeakSet([Object.prototype, Error.prototype]); +/* Helper methods live as non-enumerable lazy getters on the shared + * prototype instead of own properties on every instance. On first + * access the getter allocates the per-instance closure and caches it + * as a non-enumerable own property, so detached usage still works and + * the allocation only happens for methods actually touched. */ +function _lazyMethod(proto, key, make) { + Object.defineProperty(proto, key, { + configurable: true, + enumerable: false, + get() { + const value = make(this); + Object.defineProperty(this, key, { value, configurable: true, writable: true }); + return value; + }, + set(value) { + Object.defineProperty(this, key, { value, configurable: true, writable: true }); + }, + }); +} +const classic_errors_initializer = (inst, issues) => { + $ZodError.init(inst, issues); + inst.name = "ZodError"; + const proto = Object.getPrototypeOf(inst); + if (_installedErrorProtos.has(proto)) + return; + _installedErrorProtos.add(proto); + _lazyMethod(proto, "format", (self) => (mapper) => formatError(self, mapper)); + _lazyMethod(proto, "flatten", (self) => (mapper) => flattenError(self, mapper)); + _lazyMethod(proto, "addIssue", (self) => (issue) => { + self.issues.push(issue); + self.message = JSON.stringify(self.issues, jsonStringifyReplacer, 2); + }); + _lazyMethod(proto, "addIssues", (self) => (issues) => { + self.issues.push(...issues); + self.message = JSON.stringify(self.issues, jsonStringifyReplacer, 2); + }); + Object.defineProperty(proto, "isEmpty", { + configurable: true, + enumerable: false, + get() { + return this.issues.length === 0; + }, + }); +}; +const ZodError = /*@__PURE__*/ (/* unused pure expression or super */ null && (core.$constructor("ZodError", classic_errors_initializer))); +const ZodRealError = /*@__PURE__*/ $constructor("ZodError", classic_errors_initializer, undefined, { + Parent: Error, +}); +// /** @deprecated Use `z.core.$ZodErrorMapCtx` instead. */ +// export type ErrorMapCtx = core.$ZodErrorMapCtx; + + + +const classic_parse_parse = /* @__PURE__ */ parse_parse(ZodRealError); +const classic_parse_parseAsync = /* @__PURE__ */ parse_parseAsync(ZodRealError); +const parse_safeParse = /* @__PURE__ */ _safeParse(ZodRealError); +const parse_safeParseAsync = /* @__PURE__ */ _safeParseAsync(ZodRealError); + +// Codec functions +const classic_parse_encode = /* @__PURE__ */ parse_encode(ZodRealError); +const classic_parse_decode = /* @__PURE__ */ parse_decode(ZodRealError); +const classic_parse_encodeAsync = /* @__PURE__ */ parse_encodeAsync(ZodRealError); +const classic_parse_decodeAsync = /* @__PURE__ */ parse_decodeAsync(ZodRealError); +const parse_safeEncode = /* @__PURE__ */ _safeEncode(ZodRealError); +const parse_safeDecode = /* @__PURE__ */ _safeDecode(ZodRealError); +const parse_safeEncodeAsync = /* @__PURE__ */ _safeEncodeAsync(ZodRealError); +const parse_safeDecodeAsync = /* @__PURE__ */ _safeDecodeAsync(ZodRealError); + + + + + + + + +// Register English as the default locale on first ZodType construction. Hooked into the `ZodType` `$constructor` (rather than a top-level `config(en())` in `external.ts`) so bundlers honoring `sideEffects: false` can't tree-shake it out — see #5953, #5725. An explicit `z.config(z.locales.xx())` call wins regardless of order, since this only sets the default when none is present. +function _ensureDefaultLocale() { + if (!globalConfig.localeError) + core_config(en()); +} +// the default memoizer is read by the core container init, which runs before `ZodType.init`, so each container calls this first +function _ensureDefaultMemoizer() { + if (!globalConfig.memoizer) + core_config({ memoizer: memoizer() }); +} +const ZodType = /*@__PURE__*/ $constructor("ZodType", (inst, def) => { + _ensureDefaultLocale(); + $ZodType.init(inst, def); + inst.def = def; + inst.type = def.type; + return inst; +}, { + check(...chks) { + const def = this.def; + return this.clone(mergeDefs(def, { + checks: [ + ...(def.checks ?? []), + ...chks.map((ch) => typeof ch === "function" ? { _zod: { check: ch, def: { check: "custom" }, onattach: [] } } : ch), + ], + }), { parent: true }); + }, + with(...chks) { + return this.check(...chks); + }, + clone(def, params) { + return clone(this, def, params); + }, + brand() { + return this; + }, + register(reg, meta) { + reg.add(this, meta); + return this; + }, + refine(check, params) { + return this.check(refine(check, params)); + }, + superRefine(refinement, params) { + return this.check(superRefine(refinement, params)); + }, + overwrite(fn) { + return this.check(_overwrite(fn)); + }, + optional() { + return schemas_optional(this); + }, + exactOptional() { + return exactOptional(this); + }, + nullable() { + return nullable(this); + }, + nullish() { + return schemas_optional(nullable(this)); + }, + nonoptional(params) { + return nonoptional(this, params); + }, + array() { + return schemas_array(this); + }, + or(arg) { + return schemas_union([this, arg]); + }, + and(arg) { + return intersection(this, arg); + }, + transform(tx) { + return pipe(this, transform(tx)); + }, + default(d) { + return schemas_default(this, d); + }, + prefault(d) { + return prefault(this, d); + }, + catch(params) { + return schemas_catch(this, params); + }, + pipe(target) { + return pipe(this, target); + }, + readonly() { + return readonly(this); + }, + describe(description) { + const cl = this.clone(); + globalRegistry.add(cl, { description }); + return cl; + }, + meta(...args) { + // overloaded: meta() returns the registered metadata, meta(data) returns a clone with `data` registered. The mapped type picks up the second overload, so we accept variadic any-args and return `any` to satisfy both at runtime. + if (args.length === 0) + return globalRegistry.get(this); + const cl = this.clone(); + globalRegistry.add(cl, args[0]); + return cl; + }, + isOptional() { + return this.safeParse(undefined).success; + }, + isNullable() { + return this.safeParse(null).success; + }, + apply(fn, ...args) { + return args.length === 0 ? fn(this) : fn(this, ...args); + }, + // Overrides core's `~standard` to add `jsonSchema`. Must stay a prototype entry: redefining it per instance demotes instances to dictionary mode. + get "~standard"() { + return hide(this, "~standard", { + ...standardProps(this), + jsonSchema: { + input: createStandardJSONSchemaMethod(this, "input"), + output: createStandardJSONSchemaMethod(this, "output"), + }, + }); + }, + set "~standard"(value) { + util_own(this, "~standard", value); + }, + parse: function _parse(data, params) { + return classic_parse_parse(this, data, params, { callee: _parse }); + }, + parseAsync: async function _parseAsync(data, params) { + return await classic_parse_parseAsync(this, data, params, { callee: _parseAsync }); + }, + safeParse(data, params) { + return parse_safeParse(this, data, params); + }, + async safeParseAsync(data, params) { + return parse_safeParseAsync(this, data, params); + }, + // `spa` is an alias: same function object as `safeParseAsync`, as before. + get spa() { + return this?.safeParseAsync; + }, + set spa(value) { + util_own(this, "spa", value); + }, + encode: function _encode(data, params) { + return classic_parse_encode(this, data, params, { callee: _encode }); + }, + decode: function _decode(data, params) { + return classic_parse_decode(this, data, params, { callee: _decode }); + }, + encodeAsync: async function _encodeAsync(data, params) { + return await classic_parse_encodeAsync(this, data, params, { callee: _encodeAsync }); + }, + decodeAsync: async function _decodeAsync(data, params) { + return await classic_parse_decodeAsync(this, data, params, { callee: _decodeAsync }); + }, + safeEncode(data, params) { + return parse_safeEncode(this, data, params); + }, + safeDecode(data, params) { + return parse_safeDecode(this, data, params); + }, + async safeEncodeAsync(data, params) { + return parse_safeEncodeAsync(this, data, params); + }, + async safeDecodeAsync(data, params) { + return parse_safeDecodeAsync(this, data, params); + }, + toJSONSchema(params) { + return createToJSONSchemaMethod(this, {})(params); + }, + // Reads through to the registry on every access, so it must not cache. + get description() { + return globalRegistry.get(this)?.description; + }, + // No setter: `schema._def = x` throws, as it did when `_def` was a non-writable own property. + get _def() { + return this._zod.def; + }, +}); +/** @internal */ +const _ZodString = /*@__PURE__*/ $constructor("_ZodString", (inst, def) => { + $ZodString.init(inst, def); + ZodType.init(inst, def); + inst._zod.processJSONSchema = (ctx, json, params) => stringProcessor(inst, ctx, json, params); + const bag = inst._zod.bag; + inst.format = bag.format ?? null; + inst.minLength = bag.minimum ?? null; + inst.maxLength = bag.maximum ?? null; +}, { + regex(...args) { + return this.check(_regex(...args)); + }, + includes(...args) { + return this.check(_includes(...args)); + }, + startsWith(...args) { + return this.check(_startsWith(...args)); + }, + endsWith(...args) { + return this.check(_endsWith(...args)); + }, + min(...args) { + return this.check(_minLength(...args)); + }, + max(...args) { + return this.check(_maxLength(...args)); + }, + length(...args) { + return this.check(_length(...args)); + }, + nonempty(...args) { + return this.check(_minLength(1, ...args)); + }, + lowercase(params) { + return this.check(_lowercase(params)); + }, + uppercase(params) { + return this.check(_uppercase(params)); + }, + trim() { + return this.check(_trim()); + }, + normalize(...args) { + return this.check(_normalize(...args)); + }, + toLowerCase() { + return this.check(_toLowerCase()); + }, + toUpperCase() { + return this.check(_toUpperCase()); + }, + slugify() { + return this.check(_slugify()); + }, +}); +const ZodString = /*@__PURE__*/ $constructor("ZodString", (inst, def) => { + $ZodString.init(inst, def); + _ZodString.init(inst, def); +}, { + email(params) { + return this.check(_email(ZodEmail, params)); + }, + url(params) { + return this.check(_url(ZodURL, params)); + }, + jwt(params) { + return this.check(_jwt(ZodJWT, params)); + }, + emoji(params) { + return this.check(api_emoji(ZodEmoji, params)); + }, + guid(params) { + return this.check(_guid(ZodGUID, params)); + }, + uuid(params) { + return this.check(_uuid(ZodUUID, params)); + }, + uuidv4(params) { + return this.check(_uuidv4(ZodUUID, params)); + }, + uuidv6(params) { + return this.check(_uuidv6(ZodUUID, params)); + }, + uuidv7(params) { + return this.check(_uuidv7(ZodUUID, params)); + }, + nanoid(params) { + return this.check(_nanoid(ZodNanoID, params)); + }, + cuid(params) { + return this.check(_cuid(ZodCUID, params)); + }, + cuid2(params) { + return this.check(_cuid2(ZodCUID2, params)); + }, + ulid(params) { + return this.check(_ulid(ZodULID, params)); + }, + base64(params) { + return this.check(_base64(ZodBase64, params)); + }, + base64url(params) { + return this.check(_base64url(ZodBase64URL, params)); + }, + xid(params) { + return this.check(_xid(ZodXID, params)); + }, + ksuid(params) { + return this.check(_ksuid(ZodKSUID, params)); + }, + ipv4(params) { + return this.check(_ipv4(ZodIPv4, params)); + }, + ipv6(params) { + return this.check(_ipv6(ZodIPv6, params)); + }, + cidrv4(params) { + return this.check(_cidrv4(ZodCIDRv4, params)); + }, + cidrv6(params) { + return this.check(_cidrv6(ZodCIDRv6, params)); + }, + e164(params) { + return this.check(_e164(ZodE164, params)); + }, + datetime(params) { + return this.check(_isoDateTime(ZodISODateTime, params)); + }, + date(params) { + return this.check(_isoDate(ZodISODate, params)); + }, + time(params) { + return this.check(_isoTime(schemas_ZodISOTime, params)); + }, + duration(params) { + return this.check(_isoDuration(schemas_ZodISODuration, params)); + }, +}); +function schemas_string(params) { + return _string(ZodString, params); +} +const ZodStringFormat = /*@__PURE__*/ $constructor("ZodStringFormat", (inst, def) => { + $ZodStringFormat.init(inst, def); + _ZodString.init(inst, def); +}); +const ZodISODateTime = /*@__PURE__*/ $constructor("ZodISODateTime", (inst, def) => { + $ZodISODateTime.init(inst, def); + ZodStringFormat.init(inst, def); +}); +const ZodISODate = /*@__PURE__*/ $constructor("ZodISODate", (inst, def) => { + $ZodISODate.init(inst, def); + ZodStringFormat.init(inst, def); +}); +const schemas_ZodISOTime = /*@__PURE__*/ $constructor("ZodISOTime", (inst, def) => { + $ZodISOTime.init(inst, def); + ZodStringFormat.init(inst, def); +}); +const schemas_ZodISODuration = /*@__PURE__*/ $constructor("ZodISODuration", (inst, def) => { + $ZodISODuration.init(inst, def); + ZodStringFormat.init(inst, def); +}); +const ZodEmail = /*@__PURE__*/ $constructor("ZodEmail", (inst, def) => { + // ZodStringFormat.init(inst, def); + $ZodEmail.init(inst, def); + ZodStringFormat.init(inst, def); +}); +function schemas_email(params) { + return _email(ZodEmail, params); +} +const ZodGUID = /*@__PURE__*/ $constructor("ZodGUID", (inst, def) => { + // ZodStringFormat.init(inst, def); + $ZodGUID.init(inst, def); + ZodStringFormat.init(inst, def); +}); +function schemas_guid(params) { + return core._guid(ZodGUID, params); +} +const ZodUUID = /*@__PURE__*/ $constructor("ZodUUID", (inst, def) => { + // ZodStringFormat.init(inst, def); + $ZodUUID.init(inst, def); + ZodStringFormat.init(inst, def); +}); +function schemas_uuid(params) { + return core._uuid(ZodUUID, params); +} +function uuidv4(params) { + return core._uuidv4(ZodUUID, params); +} +// ZodUUIDv6 +function uuidv6(params) { + return core._uuidv6(ZodUUID, params); +} +// ZodUUIDv7 +function uuidv7(params) { + return core._uuidv7(ZodUUID, params); +} +const ZodURL = /*@__PURE__*/ $constructor("ZodURL", (inst, def) => { + // ZodStringFormat.init(inst, def); + $ZodURL.init(inst, def); + ZodStringFormat.init(inst, def); +}); +function schemas_url(params) { + return _url(ZodURL, params); +} +function httpUrl(params) { + return core._url(ZodURL, { + protocol: core.regexes.httpProtocol, + hostname: core.regexes.domain, + ...util.normalizeParams(params), + }); +} +const ZodEmoji = /*@__PURE__*/ $constructor("ZodEmoji", (inst, def) => { + // ZodStringFormat.init(inst, def); + $ZodEmoji.init(inst, def); + ZodStringFormat.init(inst, def); +}); +function schemas_emoji(params) { + return core._emoji(ZodEmoji, params); +} +const ZodNanoID = /*@__PURE__*/ $constructor("ZodNanoID", (inst, def) => { + // ZodStringFormat.init(inst, def); + $ZodNanoID.init(inst, def); + ZodStringFormat.init(inst, def); +}); +function schemas_nanoid(params) { + return core._nanoid(ZodNanoID, params); +} +/** + * @deprecated CUID v1 is deprecated by its authors due to information leakage + * (timestamps embedded in the id). Use {@link ZodCUID2} instead. + * See https://github.com/paralleldrive/cuid. + */ +const ZodCUID = /*@__PURE__*/ $constructor("ZodCUID", (inst, def) => { + // ZodStringFormat.init(inst, def); + $ZodCUID.init(inst, def); + ZodStringFormat.init(inst, def); +}); +/** + * Validates a CUID v1 string. + * + * @deprecated CUID v1 is deprecated by its authors due to information leakage + * (timestamps embedded in the id). Use {@link cuid2 | `z.cuid2()`} instead. + * See https://github.com/paralleldrive/cuid. + */ +function schemas_cuid(params) { + return core._cuid(ZodCUID, params); +} +const ZodCUID2 = /*@__PURE__*/ $constructor("ZodCUID2", (inst, def) => { + // ZodStringFormat.init(inst, def); + $ZodCUID2.init(inst, def); + ZodStringFormat.init(inst, def); +}); +function schemas_cuid2(params) { + return core._cuid2(ZodCUID2, params); +} +const ZodULID = /*@__PURE__*/ $constructor("ZodULID", (inst, def) => { + // ZodStringFormat.init(inst, def); + $ZodULID.init(inst, def); + ZodStringFormat.init(inst, def); +}); +function schemas_ulid(params) { + return core._ulid(ZodULID, params); +} +const ZodXID = /*@__PURE__*/ $constructor("ZodXID", (inst, def) => { + // ZodStringFormat.init(inst, def); + $ZodXID.init(inst, def); + ZodStringFormat.init(inst, def); +}); +function schemas_xid(params) { + return core._xid(ZodXID, params); +} +const ZodKSUID = /*@__PURE__*/ $constructor("ZodKSUID", (inst, def) => { + // ZodStringFormat.init(inst, def); + $ZodKSUID.init(inst, def); + ZodStringFormat.init(inst, def); +}); +function schemas_ksuid(params) { + return core._ksuid(ZodKSUID, params); +} +const ZodIPv4 = /*@__PURE__*/ $constructor("ZodIPv4", (inst, def) => { + // ZodStringFormat.init(inst, def); + $ZodIPv4.init(inst, def); + ZodStringFormat.init(inst, def); +}); +function schemas_ipv4(params) { + return core._ipv4(ZodIPv4, params); +} +const ZodMAC = /*@__PURE__*/ (/* unused pure expression or super */ null && (core.$constructor("ZodMAC", (inst, def) => { + // ZodStringFormat.init(inst, def); + core.$ZodMAC.init(inst, def); + ZodStringFormat.init(inst, def); +}))); +function schemas_mac(params) { + return core._mac(ZodMAC, params); +} +const ZodIPv6 = /*@__PURE__*/ $constructor("ZodIPv6", (inst, def) => { + // ZodStringFormat.init(inst, def); + $ZodIPv6.init(inst, def); + ZodStringFormat.init(inst, def); +}); +function schemas_ipv6(params) { + return core._ipv6(ZodIPv6, params); +} +const ZodCIDRv4 = /*@__PURE__*/ $constructor("ZodCIDRv4", (inst, def) => { + $ZodCIDRv4.init(inst, def); + ZodStringFormat.init(inst, def); +}); +function schemas_cidrv4(params) { + return core._cidrv4(ZodCIDRv4, params); +} +const ZodCIDRv6 = /*@__PURE__*/ $constructor("ZodCIDRv6", (inst, def) => { + $ZodCIDRv6.init(inst, def); + ZodStringFormat.init(inst, def); +}); +function schemas_cidrv6(params) { + return core._cidrv6(ZodCIDRv6, params); +} +const ZodBase64 = /*@__PURE__*/ $constructor("ZodBase64", (inst, def) => { + // ZodStringFormat.init(inst, def); + $ZodBase64.init(inst, def); + ZodStringFormat.init(inst, def); +}); +function schemas_base64(params) { + return core._base64(ZodBase64, params); +} +const ZodBase64URL = /*@__PURE__*/ $constructor("ZodBase64URL", (inst, def) => { + // ZodStringFormat.init(inst, def); + $ZodBase64URL.init(inst, def); + ZodStringFormat.init(inst, def); +}); +function schemas_base64url(params) { + return core._base64url(ZodBase64URL, params); +} +const ZodE164 = /*@__PURE__*/ $constructor("ZodE164", (inst, def) => { + // ZodStringFormat.init(inst, def); + $ZodE164.init(inst, def); + ZodStringFormat.init(inst, def); +}); +function schemas_e164(params) { + return core._e164(ZodE164, params); +} +const ZodCreditCard = /*@__PURE__*/ (/* unused pure expression or super */ null && (core.$constructor("ZodCreditCard", (inst, def) => { + core.$ZodCreditCard.init(inst, def); + ZodStringFormat.init(inst, def); +}))); +function schemas_creditCard(params) { + return core._creditCard(ZodCreditCard, params); +} +const ZodJWT = /*@__PURE__*/ $constructor("ZodJWT", (inst, def) => { + // ZodStringFormat.init(inst, def); + $ZodJWT.init(inst, def); + ZodStringFormat.init(inst, def); +}); +function jwt(params) { + return core._jwt(ZodJWT, params); +} +const ZodCustomStringFormat = /*@__PURE__*/ (/* unused pure expression or super */ null && (core.$constructor("ZodCustomStringFormat", (inst, def) => { + // ZodStringFormat.init(inst, def); + core.$ZodCustomStringFormat.init(inst, def); + ZodStringFormat.init(inst, def); +}))); +function stringFormat(format, fnOrRegex, _params = {}) { + return core._stringFormat(ZodCustomStringFormat, format, fnOrRegex, _params); +} +function schemas_hostname(_params) { + return core._stringFormat(ZodCustomStringFormat, "hostname", core.regexes.hostname, _params); +} +function schemas_hex(_params) { + return core._stringFormat(ZodCustomStringFormat, "hex", core.regexes.hex, _params); +} +function schemas_hash(alg, params) { + const enc = params?.enc ?? "hex"; + const format = `${alg}_${enc}`; + const regex = core.regexes[format]; + if (!regex) + throw new Error(`Unrecognized hash format: ${format}`); + return core._stringFormat(ZodCustomStringFormat, format, regex, params); +} +const ZodNumber = /*@__PURE__*/ $constructor("ZodNumber", (inst, def) => { + $ZodNumber.init(inst, def); + ZodType.init(inst, def); + inst._zod.processJSONSchema = (ctx, json, params) => numberProcessor(inst, ctx, json, params); + const bag = inst._zod.bag; + inst.minValue = + Math.max(bag.minimum ?? Number.NEGATIVE_INFINITY, bag.exclusiveMinimum ?? Number.NEGATIVE_INFINITY) ?? null; + inst.maxValue = + Math.min(bag.maximum ?? Number.POSITIVE_INFINITY, bag.exclusiveMaximum ?? Number.POSITIVE_INFINITY) ?? null; + inst.isInt = (bag.format ?? "").includes("int") || Number.isSafeInteger(bag.multipleOf ?? 0.5); + inst.isFinite = true; + inst.format = bag.format ?? null; +}, { + gt(value, params) { + return this.check(_gt(value, params)); + }, + gte(value, params) { + return this.check(_gte(value, params)); + }, + min(value, params) { + return this.check(_gte(value, params)); + }, + lt(value, params) { + return this.check(_lt(value, params)); + }, + lte(value, params) { + return this.check(_lte(value, params)); + }, + max(value, params) { + return this.check(_lte(value, params)); + }, + int(params) { + return this.check(schemas_int(params)); + }, + safe(params) { + return this.check(schemas_int(params)); + }, + positive(params) { + return this.check(_gt(0, params)); + }, + nonnegative(params) { + return this.check(_gte(0, params)); + }, + negative(params) { + return this.check(_lt(0, params)); + }, + nonpositive(params) { + return this.check(_lte(0, params)); + }, + multipleOf(value, params) { + return this.check(_multipleOf(value, params)); + }, + step(value, params) { + return this.check(_multipleOf(value, params)); + }, + finite() { + return this; + }, +}); +function schemas_number(params) { + return _number(ZodNumber, params); +} +const ZodNumberFormat = /*@__PURE__*/ $constructor("ZodNumberFormat", (inst, def) => { + $ZodNumberFormat.init(inst, def); + ZodNumber.init(inst, def); +}); +function schemas_int(params) { + return _int(ZodNumberFormat, params); +} +function float32(params) { + return core._float32(ZodNumberFormat, params); +} +function float64(params) { + return core._float64(ZodNumberFormat, params); +} +function int32(params) { + return core._int32(ZodNumberFormat, params); +} +function uint32(params) { + return core._uint32(ZodNumberFormat, params); +} +const ZodBoolean = /*@__PURE__*/ $constructor("ZodBoolean", (inst, def) => { + $ZodBoolean.init(inst, def); + ZodType.init(inst, def); + inst._zod.processJSONSchema = (ctx, json, params) => booleanProcessor(inst, ctx, json, params); +}); +function schemas_boolean(params) { + return _boolean(ZodBoolean, params); +} +const ZodBigInt = /*@__PURE__*/ (/* unused pure expression or super */ null && (core.$constructor("ZodBigInt", (inst, def) => { + core.$ZodBigInt.init(inst, def); + ZodType.init(inst, def); + inst._zod.processJSONSchema = (ctx, json, params) => processors.bigintProcessor(inst, ctx, json, params); + const bag = inst._zod.bag; + inst.minValue = bag.minimum ?? null; + inst.maxValue = bag.maximum ?? null; + inst.format = bag.format ?? null; +}, { + gte(value, params) { + return this.check(checks.gte(value, params)); + }, + min(value, params) { + return this.check(checks.gte(value, params)); + }, + gt(value, params) { + return this.check(checks.gt(value, params)); + }, + lt(value, params) { + return this.check(checks.lt(value, params)); + }, + lte(value, params) { + return this.check(checks.lte(value, params)); + }, + max(value, params) { + return this.check(checks.lte(value, params)); + }, + positive(params) { + return this.check(checks.gt(BigInt(0), params)); + }, + negative(params) { + return this.check(checks.lt(BigInt(0), params)); + }, + nonpositive(params) { + return this.check(checks.lte(BigInt(0), params)); + }, + nonnegative(params) { + return this.check(checks.gte(BigInt(0), params)); + }, + multipleOf(value, params) { + return this.check(checks.multipleOf(value, params)); + }, +}))); +function schemas_bigint(params) { + return core._bigint(ZodBigInt, params); +} +const ZodBigIntFormat = /*@__PURE__*/ (/* unused pure expression or super */ null && (core.$constructor("ZodBigIntFormat", (inst, def) => { + core.$ZodBigIntFormat.init(inst, def); + ZodBigInt.init(inst, def); +}))); +function int64(params) { + return core._int64(ZodBigIntFormat, params); +} +function uint64(params) { + return core._uint64(ZodBigIntFormat, params); +} +const ZodSymbol = /*@__PURE__*/ (/* unused pure expression or super */ null && (core.$constructor("ZodSymbol", (inst, def) => { + core.$ZodSymbol.init(inst, def); + ZodType.init(inst, def); + inst._zod.processJSONSchema = (ctx, json, params) => processors.symbolProcessor(inst, ctx, json, params); +}))); +function symbol(params) { + return core._symbol(ZodSymbol, params); +} +const ZodUndefined = /*@__PURE__*/ (/* unused pure expression or super */ null && (core.$constructor("ZodUndefined", (inst, def) => { + core.$ZodUndefined.init(inst, def); + ZodType.init(inst, def); + inst._zod.processJSONSchema = (ctx, json, params) => processors.undefinedProcessor(inst, ctx, json, params); +}))); +function schemas_undefined(params) { + return core._undefined(ZodUndefined, params); +} + +const ZodNull = /*@__PURE__*/ $constructor("ZodNull", (inst, def) => { + $ZodNull.init(inst, def); + ZodType.init(inst, def); + inst._zod.processJSONSchema = (ctx, json, params) => nullProcessor(inst, ctx, json, params); +}); +function schemas_null(params) { + return api_null(ZodNull, params); +} + +const ZodAny = /*@__PURE__*/ $constructor("ZodAny", (inst, def) => { + $ZodAny.init(inst, def); + ZodType.init(inst, def); + inst._zod.processJSONSchema = (ctx, json, params) => anyProcessor(inst, ctx, json, params); +}); +function any() { + return _any(ZodAny); +} +const ZodUnknown = /*@__PURE__*/ $constructor("ZodUnknown", (inst, def) => { + $ZodUnknown.init(inst, def); + ZodType.init(inst, def); + inst._zod.processJSONSchema = (ctx, json, params) => unknownProcessor(inst, ctx, json, params); +}); +function unknown() { + return _unknown(ZodUnknown); +} +const ZodNever = /*@__PURE__*/ $constructor("ZodNever", (inst, def) => { + $ZodNever.init(inst, def); + ZodType.init(inst, def); + inst._zod.processJSONSchema = (ctx, json, params) => neverProcessor(inst, ctx, json, params); +}); +function never(params) { + return _never(ZodNever, params); +} +const ZodVoid = /*@__PURE__*/ (/* unused pure expression or super */ null && (core.$constructor("ZodVoid", (inst, def) => { + core.$ZodVoid.init(inst, def); + ZodType.init(inst, def); + inst._zod.processJSONSchema = (ctx, json, params) => processors.voidProcessor(inst, ctx, json, params); +}))); +function schemas_void(params) { + return core._void(ZodVoid, params); +} + +const ZodDate = /*@__PURE__*/ (/* unused pure expression or super */ null && (core.$constructor("ZodDate", (inst, def) => { + core.$ZodDate.init(inst, def); + ZodType.init(inst, def); + inst._zod.processJSONSchema = (ctx, json, params) => processors.dateProcessor(inst, ctx, json, params); + inst.min = (value, params) => inst.check(checks.gte(value, params)); + inst.max = (value, params) => inst.check(checks.lte(value, params)); + const c = inst._zod.bag; + inst.minDate = c.minimum ? new Date(c.minimum) : null; + inst.maxDate = c.maximum ? new Date(c.maximum) : null; +}))); +function schemas_date(params) { + return core._date(ZodDate, params); +} +const ZodArray = /*@__PURE__*/ $constructor("ZodArray", (inst, def) => { + _ensureDefaultMemoizer(); + $ZodArray.init(inst, def); + ZodType.init(inst, def); + inst._zod.processJSONSchema = (ctx, json, params) => arrayProcessor(inst, ctx, json, params); + inst.element = def.element; +}, { + min(n, params) { + return this.check(_minLength(n, params)); + }, + nonempty(params) { + return this.check(_minLength(1, params)); + }, + max(n, params) { + return this.check(_maxLength(n, params)); + }, + length(n, params) { + return this.check(_length(n, params)); + }, + unwrap() { + return this.element; + }, +}); +function schemas_array(element, params) { + return _array(ZodArray, element, params); +} +// .keyof +function keyof(schema) { + const shape = schema._zod.def.shape; + return schemas_enum(Object.keys(shape)); +} +const ZodObject = /*@__PURE__*/ $constructor("ZodObject", (inst, def) => { + _ensureDefaultMemoizer(); + $ZodObjectJIT.init(inst, def); + ZodType.init(inst, def); + inst._zod.processJSONSchema = (ctx, json, params) => objectProcessor(inst, ctx, json, params); + installLazyProp(inst, "shape", (self) => self._zod.def.shape, false); +}, { + keyof() { + return schemas_enum(Object.keys(this._zod.def.shape)); + }, + catchall(catchall) { + return this.clone({ ...this._zod.def, catchall: catchall }); + }, + passthrough() { + return this.clone({ ...this._zod.def, catchall: unknown() }); + }, + loose() { + return this.clone({ ...this._zod.def, catchall: unknown() }); + }, + strict() { + return this.clone({ ...this._zod.def, catchall: never() }); + }, + strip() { + return this.clone({ ...this._zod.def, catchall: undefined }); + }, + extend(incoming) { + return extend(this, incoming); + }, + safeExtend(incoming) { + return safeExtend(this, incoming); + }, + merge(other) { + return merge(this, other); + }, + pick(mask) { + return pick(this, mask); + }, + omit(mask) { + return omit(this, mask); + }, + partial(...args) { + return partial(ZodOptional, this, args[0]); + }, + exactPartial(...args) { + return partial(ZodExactOptional, this, args[0], "exactPartial"); + }, + required(...args) { + return util_required(ZodNonOptional, this, args[0]); + }, +}); +function schemas_object(shape, params) { + const def = { + type: "object", + shape: shape ?? {}, + ...normalizeParams(params), + }; + return new ZodObject(def); +} +// strictObject +function strictObject(shape, params) { + return new ZodObject({ + type: "object", + shape, + catchall: never(), + ...util.normalizeParams(params), + }); +} +// looseObject +function looseObject(shape, params) { + return new ZodObject({ + type: "object", + shape, + catchall: unknown(), + ...normalizeParams(params), + }); +} +const ZodUnion = /*@__PURE__*/ $constructor("ZodUnion", (inst, def) => { + $ZodUnion.init(inst, def); + ZodType.init(inst, def); + inst._zod.processJSONSchema = (ctx, json, params) => unionProcessor(inst, ctx, json, params); + inst.options = def.options; +}); +function schemas_union(options, params) { + return new ZodUnion({ + type: "union", + options: options, + ...normalizeParams(params), + }); +} +const ZodXor = /*@__PURE__*/ (/* unused pure expression or super */ null && (core.$constructor("ZodXor", (inst, def) => { + ZodUnion.init(inst, def); + core.$ZodXor.init(inst, def); + inst._zod.processJSONSchema = (ctx, json, params) => processors.unionProcessor(inst, ctx, json, params); + inst.options = def.options; +}))); +/** Creates an exclusive union (XOR) where exactly one option must match. + * Unlike regular unions that succeed when any option matches, xor fails if + * zero or more than one option matches the input. */ +function xor(options, params) { + return new ZodXor({ + type: "union", + options: options, + inclusive: false, + ...util.normalizeParams(params), + }); +} +const ZodDiscriminatedUnion = /*@__PURE__*/ $constructor("ZodDiscriminatedUnion", (inst, def) => { + ZodUnion.init(inst, def); + $ZodDiscriminatedUnion.init(inst, def); +}); +function discriminatedUnion(discriminator, options, params) { + // const [options, params] = args; + return new ZodDiscriminatedUnion({ + type: "union", + options: options, + discriminator, + ...normalizeParams(params), + }); +} +const ZodIntersection = /*@__PURE__*/ $constructor("ZodIntersection", (inst, def) => { + $ZodIntersection.init(inst, def); + ZodType.init(inst, def); + inst._zod.processJSONSchema = (ctx, json, params) => intersectionProcessor(inst, ctx, json, params); +}); +function intersection(left, right) { + return new ZodIntersection({ + type: "intersection", + left: left, + right: right, + }); +} +const ZodTuple = /*@__PURE__*/ (/* unused pure expression or super */ null && (core.$constructor("ZodTuple", (inst, def) => { + _ensureDefaultMemoizer(); + core.$ZodTuple.init(inst, def); + ZodType.init(inst, def); + inst._zod.processJSONSchema = (ctx, json, params) => processors.tupleProcessor(inst, ctx, json, params); +}, { + rest(rest) { + return this.clone({ + ...this._zod.def, + rest: rest, + }); + }, + partial() { + const def = this._zod.def; + // a refinement was authored against the full arity; partialing would run it on a shorter array + if (def.checks?.length) + throw new Error(".partial() cannot be used on tuple schemas containing refinements"); + return this.clone({ + ...def, + items: def.items.map((item) => new ZodOptional({ type: "optional", innerType: item })), + }); + }, +}))); +function tuple(items, _paramsOrRest, _params) { + const hasRest = _paramsOrRest instanceof core.$ZodType; + const params = hasRest ? _params : _paramsOrRest; + const rest = hasRest ? _paramsOrRest : null; + return new ZodTuple({ + type: "tuple", + items: items, + rest, + ...util.normalizeParams(params), + }); +} +const ZodRecord = /*@__PURE__*/ $constructor("ZodRecord", (inst, def) => { + _ensureDefaultMemoizer(); + $ZodRecord.init(inst, def); + ZodType.init(inst, def); + inst._zod.processJSONSchema = (ctx, json, params) => recordProcessor(inst, ctx, json, params); + inst.keyType = def.keyType; + inst.valueType = def.valueType; +}); +function schemas_record(keyType, valueType, params) { + // v3-compat: z.record(valueType, params?) — defaults keyType to z.string() + if (!valueType || !valueType._zod) { + return new ZodRecord({ + type: "record", + keyType: schemas_string(), + valueType: keyType, + ...normalizeParams(valueType), + }); + } + return new ZodRecord({ + type: "record", + keyType, + valueType: valueType, + ...normalizeParams(params), + }); +} +// type alksjf = core.output; +function partialRecord(keyType, valueType, params) { + return new ZodRecord({ + type: "record", + keyType, + valueType: valueType, + ...util.normalizeParams(params), + partial: true, + }); +} +function looseRecord(keyType, valueType, params) { + return new ZodRecord({ + type: "record", + keyType, + valueType: valueType, + mode: "loose", + ...util.normalizeParams(params), + }); +} +const ZodMap = /*@__PURE__*/ (/* unused pure expression or super */ null && (core.$constructor("ZodMap", (inst, def) => { + _ensureDefaultMemoizer(); + core.$ZodMap.init(inst, def); + ZodType.init(inst, def); + inst._zod.processJSONSchema = (ctx, json, params) => processors.mapProcessor(inst, ctx, json, params); + inst.keyType = def.keyType; + inst.valueType = def.valueType; + inst.min = (...args) => inst.check(core._minSize(...args)); + inst.nonempty = (params) => inst.check(core._minSize(1, params)); + inst.max = (...args) => inst.check(core._maxSize(...args)); + inst.size = (...args) => inst.check(core._size(...args)); +}))); +function schemas_map(keyType, valueType, params) { + return new ZodMap({ + type: "map", + keyType: keyType, + valueType: valueType, + ...util.normalizeParams(params), + }); +} +const ZodSet = /*@__PURE__*/ (/* unused pure expression or super */ null && (core.$constructor("ZodSet", (inst, def) => { + _ensureDefaultMemoizer(); + core.$ZodSet.init(inst, def); + ZodType.init(inst, def); + inst._zod.processJSONSchema = (ctx, json, params) => processors.setProcessor(inst, ctx, json, params); + inst.min = (...args) => inst.check(core._minSize(...args)); + inst.nonempty = (params) => inst.check(core._minSize(1, params)); + inst.max = (...args) => inst.check(core._maxSize(...args)); + inst.size = (...args) => inst.check(core._size(...args)); +}))); +function schemas_set(valueType, params) { + return new ZodSet({ + type: "set", + valueType: valueType, + ...util.normalizeParams(params), + }); +} +const ZodEnum = /*@__PURE__*/ $constructor("ZodEnum", (inst, def) => { + $ZodEnum.init(inst, def); + ZodType.init(inst, def); + inst._zod.processJSONSchema = (ctx, json, params) => enumProcessor(inst, ctx, json, params); + inst.enum = def.entries; + inst.options = Object.values(def.entries); + const keys = new Set(Object.keys(def.entries)); + inst.extract = (values, params) => { + const newEntries = {}; + for (const value of values) { + if (keys.has(value)) { + newEntries[value] = def.entries[value]; + } + else + throw new Error(`Key ${value} not found in enum`); + } + return new ZodEnum({ + ...def, + checks: [], + ...normalizeParams(params), + entries: newEntries, + }); + }; + inst.exclude = (values, params) => { + const newEntries = { ...def.entries }; + for (const value of values) { + if (keys.has(value)) { + delete newEntries[value]; + } + else + throw new Error(`Key ${value} not found in enum`); + } + return new ZodEnum({ + ...def, + checks: [], + ...normalizeParams(params), + entries: newEntries, + }); + }; +}); +function schemas_enum(values, params) { + const entries = Array.isArray(values) ? Object.fromEntries(values.map((v) => [v, v])) : values; + return new ZodEnum({ + type: "enum", + entries, + ...normalizeParams(params), + }); +} + +/** @deprecated This API has been merged into `z.enum()`. Use `z.enum()` instead. + * + * ```ts + * enum Colors { red, green, blue } + * z.enum(Colors); + * ``` + */ +function nativeEnum(entries, params) { + return new ZodEnum({ + type: "enum", + entries, + ...util.normalizeParams(params), + }); +} +const ZodLiteral = /*@__PURE__*/ $constructor("ZodLiteral", (inst, def) => { + $ZodLiteral.init(inst, def); + ZodType.init(inst, def); + inst._zod.processJSONSchema = (ctx, json, params) => literalProcessor(inst, ctx, json, params); + inst.values = new Set(def.values); + Object.defineProperty(inst, "value", { + get() { + if (def.values.length > 1) { + throw new Error("This schema contains multiple valid literal values. Use `.values` instead."); + } + return def.values[0]; + }, + }); +}); +function literal(value, params) { + return new ZodLiteral({ + type: "literal", + values: Array.isArray(value) ? value : [value], + ...normalizeParams(params), + }); +} +const ZodFile = /*@__PURE__*/ (/* unused pure expression or super */ null && (core.$constructor("ZodFile", (inst, def) => { + core.$ZodFile.init(inst, def); + ZodType.init(inst, def); + inst._zod.processJSONSchema = (ctx, json, params) => processors.fileProcessor(inst, ctx, json, params); + inst.min = (size, params) => inst.check(core._minSize(size, params)); + inst.max = (size, params) => inst.check(core._maxSize(size, params)); + inst.mime = (types, params) => inst.check(core._mime(Array.isArray(types) ? types : [types], params)); +}))); +function schemas_file(params) { + return core._file(ZodFile, params); +} +const ZodTransform = /*@__PURE__*/ $constructor("ZodTransform", (inst, def) => { + _ensureDefaultMemoizer(); + $ZodTransform.init(inst, def); + ZodType.init(inst, def); + inst._zod.processJSONSchema = (ctx, json, params) => transformProcessor(inst, ctx, json, params); + inst._zod.parse = (payload, _ctx) => { + if (_ctx.direction === "backward") { + throw new $ZodEncodeError(inst.constructor.name); + } + payload.addIssue = (issue) => { + if (typeof issue === "string") { + payload.issues.push(util_issue(issue, payload.value, def)); + } + else { + // for Zod 3 backwards compatibility + const _issue = issue; + if (_issue.fatal) + _issue.continue = false; + _issue.code ?? (_issue.code = "custom"); + if (!("input" in _issue)) + _issue.input = payload.value; + _issue.inst ?? (_issue.inst = inst); + // _issue.continue ??= true; + payload.issues.push(util_issue(_issue)); + } + }; + const output = def.transform(payload.value, payload); + if (output instanceof Promise) { + return output.then((output) => { + payload.value = output; + return payload; + }); + } + payload.value = output; + return payload; + }; +}); +function transform(fn) { + return new ZodTransform({ + type: "transform", + transform: fn, + }); +} +const ZodOptional = /*@__PURE__*/ $constructor("ZodOptional", (inst, def) => { + $ZodOptional.init(inst, def); + ZodType.init(inst, def); + inst._zod.processJSONSchema = (ctx, json, params) => optionalProcessor(inst, ctx, json, params); + inst.unwrap = () => inst._zod.def.innerType; +}); +function schemas_optional(innerType) { + return new ZodOptional({ + type: "optional", + innerType: innerType, + }); +} +const ZodExactOptional = /*@__PURE__*/ $constructor("ZodExactOptional", (inst, def) => { + $ZodExactOptional.init(inst, def); + ZodType.init(inst, def); + inst._zod.processJSONSchema = (ctx, json, params) => optionalProcessor(inst, ctx, json, params); + inst.unwrap = () => inst._zod.def.innerType; +}); +function exactOptional(innerType) { + return new ZodExactOptional({ + type: "optional", + innerType: innerType, + }); +} +const ZodNullable = /*@__PURE__*/ $constructor("ZodNullable", (inst, def) => { + $ZodNullable.init(inst, def); + ZodType.init(inst, def); + inst._zod.processJSONSchema = (ctx, json, params) => nullableProcessor(inst, ctx, json, params); + inst.unwrap = () => inst._zod.def.innerType; +}); +function nullable(innerType) { + return new ZodNullable({ + type: "nullable", + innerType: innerType, + }); +} +// nullish +function schemas_nullish(innerType) { + return schemas_optional(nullable(innerType)); +} +const ZodDefault = /*@__PURE__*/ $constructor("ZodDefault", (inst, def) => { + $ZodDefault.init(inst, def); + ZodType.init(inst, def); + inst._zod.processJSONSchema = (ctx, json, params) => defaultProcessor(inst, ctx, json, params); + inst.unwrap = () => inst._zod.def.innerType; + inst.removeDefault = inst.unwrap; +}); +function schemas_default(innerType, defaultValue) { + return new ZodDefault({ + type: "default", + innerType: innerType, + get defaultValue() { + return typeof defaultValue === "function" ? defaultValue() : shallowClone(defaultValue); + }, + }); +} +const ZodPrefault = /*@__PURE__*/ $constructor("ZodPrefault", (inst, def) => { + $ZodPrefault.init(inst, def); + ZodType.init(inst, def); + inst._zod.processJSONSchema = (ctx, json, params) => prefaultProcessor(inst, ctx, json, params); + inst.unwrap = () => inst._zod.def.innerType; +}); +function prefault(innerType, defaultValue) { + return new ZodPrefault({ + type: "prefault", + innerType: innerType, + get defaultValue() { + return typeof defaultValue === "function" ? defaultValue() : shallowClone(defaultValue); + }, + }); +} +const ZodNonOptional = /*@__PURE__*/ $constructor("ZodNonOptional", (inst, def) => { + $ZodNonOptional.init(inst, def); + ZodType.init(inst, def); + inst._zod.processJSONSchema = (ctx, json, params) => nonoptionalProcessor(inst, ctx, json, params); + inst.unwrap = () => inst._zod.def.innerType; +}); +function nonoptional(innerType, params) { + return new ZodNonOptional({ + type: "nonoptional", + innerType: innerType, + ...normalizeParams(params), + }); +} +const ZodSuccess = /*@__PURE__*/ (/* unused pure expression or super */ null && (core.$constructor("ZodSuccess", (inst, def) => { + core.$ZodSuccess.init(inst, def); + ZodType.init(inst, def); + inst._zod.processJSONSchema = (ctx, json, params) => processors.successProcessor(inst, ctx, json, params); + inst.unwrap = () => inst._zod.def.innerType; +}))); +function success(innerType) { + return new ZodSuccess({ + type: "success", + innerType: innerType, + }); +} +const ZodCatch = /*@__PURE__*/ $constructor("ZodCatch", (inst, def) => { + $ZodCatch.init(inst, def); + ZodType.init(inst, def); + inst._zod.processJSONSchema = (ctx, json, params) => catchProcessor(inst, ctx, json, params); + inst.unwrap = () => inst._zod.def.innerType; + inst.removeCatch = inst.unwrap; +}); +function schemas_catch(innerType, catchValue) { + return new ZodCatch({ + type: "catch", + innerType: innerType, + catchValue: (typeof catchValue === "function" ? catchValue : constantCatch(catchValue)), + }); +} + +const ZodNaN = /*@__PURE__*/ (/* unused pure expression or super */ null && (core.$constructor("ZodNaN", (inst, def) => { + core.$ZodNaN.init(inst, def); + ZodType.init(inst, def); + inst._zod.processJSONSchema = (ctx, json, params) => processors.nanProcessor(inst, ctx, json, params); +}))); +function nan(params) { + return core._nan(ZodNaN, params); +} +const ZodPipe = /*@__PURE__*/ $constructor("ZodPipe", (inst, def) => { + $ZodPipe.init(inst, def); + ZodType.init(inst, def); + inst._zod.processJSONSchema = (ctx, json, params) => pipeProcessor(inst, ctx, json, params); + inst.in = def.in; + inst.out = def.out; +}); +function pipe(in_, out) { + return new ZodPipe({ + type: "pipe", + in: in_, + out: out, + // ...util.normalizeParams(params), + }); +} +const ZodCodec = /*@__PURE__*/ (/* unused pure expression or super */ null && (core.$constructor("ZodCodec", (inst, def) => { + ZodPipe.init(inst, def); + core.$ZodCodec.init(inst, def); +}))); +function schemas_codec(in_, out, params) { + return new ZodCodec({ + type: "pipe", + in: in_, + out: out, + transform: params.decode, + reverseTransform: params.encode, + }); +} +function invertCodec(codec) { + const def = codec._zod.def; + return new ZodCodec({ + type: "pipe", + in: def.out, + out: def.in, + transform: def.reverseTransform, + reverseTransform: def.transform, + }); +} +const ZodPreprocess = /*@__PURE__*/ $constructor("ZodPreprocess", (inst, def) => { + ZodPipe.init(inst, def); + $ZodPreprocess.init(inst, def); +}); +const ZodReadonly = /*@__PURE__*/ $constructor("ZodReadonly", (inst, def) => { + $ZodReadonly.init(inst, def); + ZodType.init(inst, def); + inst._zod.processJSONSchema = (ctx, json, params) => readonlyProcessor(inst, ctx, json, params); + inst.unwrap = () => inst._zod.def.innerType; +}); +function readonly(innerType) { + return new ZodReadonly({ + type: "readonly", + innerType: innerType, + }); +} +const ZodTemplateLiteral = /*@__PURE__*/ (/* unused pure expression or super */ null && (core.$constructor("ZodTemplateLiteral", (inst, def) => { + core.$ZodTemplateLiteral.init(inst, def); + ZodType.init(inst, def); + inst._zod.processJSONSchema = (ctx, json, params) => processors.templateLiteralProcessor(inst, ctx, json, params); +}))); +function templateLiteral(parts, params) { + return new ZodTemplateLiteral({ + type: "template_literal", + parts, + ...util.normalizeParams(params), + }); +} +const ZodLazy = /*@__PURE__*/ $constructor("ZodLazy", (inst, def) => { + $ZodLazy.init(inst, def); + ZodType.init(inst, def); + inst._zod.processJSONSchema = (ctx, json, params) => lazyProcessor(inst, ctx, json, params); + inst.unwrap = () => inst._zod.def.getter(); +}); +function lazy(getter) { + return new ZodLazy({ + type: "lazy", + getter: getter, + }); +} +const ZodPromise = /*@__PURE__*/ (/* unused pure expression or super */ null && (core.$constructor("ZodPromise", (inst, def) => { + core.$ZodPromise.init(inst, def); + ZodType.init(inst, def); + inst._zod.processJSONSchema = (ctx, json, params) => processors.promiseProcessor(inst, ctx, json, params); + inst.unwrap = () => inst._zod.def.innerType; +}))); +function schemas_promise(innerType) { + return new ZodPromise({ + type: "promise", + innerType: innerType, + }); +} +const ZodFunction = /*@__PURE__*/ (/* unused pure expression or super */ null && (core.$constructor("ZodFunction", (inst, def) => { + core.$ZodFunction.init(inst, def); + ZodType.init(inst, def); + inst._zod.processJSONSchema = (ctx, json, params) => processors.functionProcessor(inst, ctx, json, params); +}))); +function _function(params) { + return new ZodFunction({ + type: "function", + input: Array.isArray(params?.input) ? tuple(params?.input) : (params?.input ?? schemas_array(unknown())), + output: params?.output ?? unknown(), + }); +} + +const ZodCustom = /*@__PURE__*/ $constructor("ZodCustom", (inst, def) => { + $ZodCustom.init(inst, def); + ZodType.init(inst, def); + inst._zod.processJSONSchema = (ctx, json, params) => customProcessor(inst, ctx, json, params); +}); +// custom checks +function schemas_check(fn) { + const ch = new core.$ZodCheck({ + check: "custom", + // ...util.normalizeParams(params), + }); + ch._zod.check = fn; + return ch; +} +function custom(fn, _params) { + return core._custom(ZodCustom, fn ?? (() => true), _params); +} +function refine(fn, _params = {}) { + return _refine(ZodCustom, fn, _params); +} +// superRefine +function superRefine(fn, params) { + return _superRefine(fn, params); +} +// Re-export describe and meta from core +const schemas_describe = describe; +const schemas_meta = api_meta; +function _instanceof(cls, params = {}) { + const inst = new ZodCustom({ + type: "custom", + check: "custom", + fn: (data) => data instanceof cls, + abort: true, + ...util.normalizeParams(params), + }); + inst._zod.bag.Class = cls; + // Override check to emit invalid_type instead of custom + inst._zod.check = (payload) => { + if (!(payload.value instanceof cls)) { + payload.issues.push({ + code: "invalid_type", + expected: cls.name, + input: payload.value, + inst, + path: [...(inst._zod.def.path ?? [])], + }); + } + }; + return inst; +} + +// stringbool +const stringbool = (...args) => core._stringbool({ + Codec: ZodCodec, + Boolean: ZodBoolean, + String: ZodString, +}, ...args); +function schemas_json(params) { + const jsonSchema = lazy(() => { + return schemas_union([schemas_string(params), schemas_number(), schemas_boolean(), schemas_null(), schemas_array(jsonSchema), schemas_record(schemas_string(), jsonSchema)]); + }); + return jsonSchema; +} +// preprocess +function preprocess(fn, schema) { + return new ZodPreprocess({ + type: "pipe", + in: transform(fn), + out: schema, + }); +} + + + + +function iso_datetime(params) { + return _isoDateTime(ZodISODateTime, params); +} +function iso_date(params) { + return _isoDate(ZodISODate, params); +} +function iso_time(params) { + return core._isoTime(ZodISOTime, params); +} +function iso_duration(params) { + return core._isoDuration(ZodISODuration, params); +} + +// Zod 3 compat layer + +/** @deprecated Use the raw string literal codes instead, e.g. "invalid_type". */ +const ZodIssueCode = { + 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", +}; + +/** @deprecated Use `z.config(params)` instead. */ +function setErrorMap(map) { + core.config({ + customError: map, + }); +} +/** @deprecated Use `z.config()` instead. */ +function getErrorMap() { + return core.config().customError; +} +/** @deprecated Do not use. Stub definition, only included for zod-to-json-schema compatibility. */ +var compat_ZodFirstPartyTypeKind; +(function (ZodFirstPartyTypeKind) { +})(compat_ZodFirstPartyTypeKind || (compat_ZodFirstPartyTypeKind = {})); + + + +function coerce_string(params) { + return core._coercedString(schemas.ZodString, params); +} +function coerce_number(params) { + return _coercedNumber(ZodNumber, params); +} +function coerce_boolean(params) { + return core._coercedBoolean(schemas.ZodBoolean, params); +} +function coerce_bigint(params) { + return core._coercedBigint(schemas.ZodBigInt, params); +} +function coerce_date(params) { + return core._coercedDate(schemas.ZodDate, params); +} + + + +//#region src/constants.ts +const LATEST_PROTOCOL_VERSION = "2025-11-25"; +const auth_CUe6YdwF_DEFAULT_NEGOTIATED_PROTOCOL_VERSION = "2025-03-26"; +const auth_CUe6YdwF_SUPPORTED_PROTOCOL_VERSIONS = [ + LATEST_PROTOCOL_VERSION, + "2025-06-18", + "2025-03-26", + "2024-11-05", + "2024-10-07" +]; +/** +* `_meta` key associating a message with a 2025-11-25 task. +* +* @deprecated 2025-11-25 wire vocabulary with no SDK runtime; kept importable for interoperability only. +*/ +const RELATED_TASK_META_KEY = "io.modelcontextprotocol/related-task"; +/** +* `_meta` key carrying the MCP protocol version governing a request. +* +* For the HTTP transport, the value must match the `MCP-Protocol-Version` header. +*/ +const auth_CUe6YdwF_PROTOCOL_VERSION_META_KEY = "io.modelcontextprotocol/protocolVersion"; +/** +* `_meta` key identifying the client software making a request. +* +* Clients SHOULD include it on every request; the value is self-reported and +* intended for display, logging, and debugging — servers should not rely on +* it for behavior or security decisions. +*/ +const auth_CUe6YdwF_CLIENT_INFO_META_KEY = "io.modelcontextprotocol/clientInfo"; +/** +* `_meta` key identifying the server software producing a response. +* +* Servers SHOULD include it on every response; the value is self-reported and +* intended for display, logging, and debugging — clients should not rely on +* it for behavior or security decisions. +*/ +const auth_CUe6YdwF_SERVER_INFO_META_KEY = "io.modelcontextprotocol/serverInfo"; +/** +* `_meta` key carrying the client's capabilities for a request. +* +* Capabilities are declared per request rather than once at initialization; +* servers must not infer capabilities from prior requests. +*/ +const auth_CUe6YdwF_CLIENT_CAPABILITIES_META_KEY = "io.modelcontextprotocol/clientCapabilities"; +/** +* `_meta` key carrying the JSON-RPC ID of the `subscriptions/listen` request +* that opened the stream a notification was delivered on. +* +* Stamped by the server on every notification delivered via a +* `subscriptions/listen` stream (including the leading +* `notifications/subscriptions/acknowledged`); on stdio, where all messages +* share one channel, clients use it to correlate notifications with their +* originating subscription. The value is the listen request's JSON-RPC ID +* verbatim. +*/ +const auth_CUe6YdwF_SUBSCRIPTION_ID_META_KEY = "io.modelcontextprotocol/subscriptionId"; +/** +* `_meta` key carrying the desired log level for a request. +* +* When absent, the server must not send `notifications/message` notifications +* for the request. +* +* @deprecated Deprecated as of protocol version 2026-07-28 (SEP-2577); remains +* in the specification for at least twelve months. +*/ +const LOG_LEVEL_META_KEY = "io.modelcontextprotocol/logLevel"; +/** +* `_meta` key carrying W3C Trace Context for distributed tracing (SEP-414). +* +* When present, the value MUST follow the W3C `traceparent` header format, +* e.g. `00-4bf92f3577b34da6a3ce929d0e0e4736-00f067aa0ba902b7-01`. +* +* @see https://www.w3.org/TR/trace-context/#traceparent-header +*/ +const TRACEPARENT_META_KEY = "traceparent"; +/** +* `_meta` key carrying vendor-specific trace state for distributed tracing (SEP-414). +* +* When present, the value MUST follow the W3C `tracestate` header format, +* e.g. `vendor1=value1,vendor2=value2`. +* +* @see https://www.w3.org/TR/trace-context/#tracestate-header +*/ +const TRACESTATE_META_KEY = "tracestate"; +/** +* `_meta` key carrying cross-cutting propagation values for distributed tracing (SEP-414). +* +* When present, the value MUST follow the W3C Baggage header format, +* e.g. `userId=alice,serverRegion=us-east-1`. +* +* @see https://www.w3.org/TR/baggage/ +*/ +const BAGGAGE_META_KEY = "baggage"; +const JSONRPC_VERSION = "2.0"; +const PARSE_ERROR = (/* unused pure expression or super */ null && (-32700)); +const INVALID_REQUEST = (/* unused pure expression or super */ null && (-32600)); +const METHOD_NOT_FOUND = (/* unused pure expression or super */ null && (-32601)); +const INVALID_PARAMS = (/* unused pure expression or super */ null && (-32602)); +const INTERNAL_ERROR = (/* unused pure expression or super */ null && (-32603)); + +//#endregion +//#region src/schemas.ts +const JSONValueSchema = lazy(() => schemas_union([ + schemas_string(), + schemas_number(), + schemas_boolean(), + schemas_null(), + schemas_record(schemas_string(), JSONValueSchema), + schemas_array(JSONValueSchema) +])); +const JSONObjectSchema = schemas_record(schemas_string(), JSONValueSchema); +const JSONArraySchema = schemas_array(JSONValueSchema); +/** +* A progress token, used to associate progress notifications with the original request. +*/ +const ProgressTokenSchema = schemas_union([schemas_string(), schemas_number().int()]); +/** +* An opaque token used to represent a cursor for pagination. +*/ +const CursorSchema = schemas_string(); +/** @deprecated 2025-11-25 wire vocabulary with no SDK runtime; kept importable for interoperability only. */ +const TaskMetadataSchema = schemas_object({ ttl: schemas_number().optional() }); +/** +* Metadata for associating messages with a task. +* Include this in the `_meta` field under the key `io.modelcontextprotocol/related-task`. +* +* @deprecated 2025-11-25 wire vocabulary with no SDK runtime; kept importable for interoperability only. +*/ +const RelatedTaskMetadataSchema = schemas_object({ taskId: schemas_string() }); +const RequestMetaSchema = looseObject({ + progressToken: ProgressTokenSchema.optional(), + [RELATED_TASK_META_KEY]: RelatedTaskMetadataSchema.optional() +}); +/** +* Common params for any request. +*/ +const BaseRequestParamsSchema = schemas_object({ _meta: RequestMetaSchema.optional() }); +/** +* Common params for any task-augmented request. +* +* @deprecated 2025-11-25 wire vocabulary with no SDK runtime; kept importable for interoperability only. +*/ +const auth_CUe6YdwF_TaskAugmentedRequestParamsSchema = BaseRequestParamsSchema.extend({ task: TaskMetadataSchema.optional() }); +const RequestSchema = schemas_object({ + method: schemas_string(), + params: BaseRequestParamsSchema.loose().optional() +}); +const NotificationsParamsSchema = schemas_object({ _meta: RequestMetaSchema.optional() }); +const NotificationSchema = schemas_object({ + method: schemas_string(), + params: NotificationsParamsSchema.loose().optional() +}); +/** +* The contents of a result's `_meta` field (the 2026-07-28 `ResultMetaObject`). +* Loose — implementation-specific keys pass through. +* +* The serverInfo key identifies the server software producing the response +* (servers SHOULD include it on every response; the value is self-reported +* and intended for display, logging, and debugging). The getter defers the +* `ImplementationSchema` reference, which is declared later in this file. +*/ +const ResultMetaObjectSchema = looseObject({ get [auth_CUe6YdwF_SERVER_INFO_META_KEY]() { + return ImplementationSchema.optional().catch(void 0); +} }); +const ResultSchema = looseObject({ _meta: ResultMetaObjectSchema.optional() }); +/** +* A uniquely identifying ID for a request in JSON-RPC. +*/ +const RequestIdSchema = schemas_union([schemas_string(), schemas_number().int()]); +/** +* A request that expects a response. +*/ +const JSONRPCRequestSchema = schemas_object({ + jsonrpc: literal(JSONRPC_VERSION), + id: RequestIdSchema, + ...RequestSchema.shape +}).strict(); +/** +* A notification which does not expect a response. +*/ +const JSONRPCNotificationSchema = schemas_object({ + jsonrpc: literal(JSONRPC_VERSION), + ...NotificationSchema.shape +}).strict(); +/** +* A successful (non-error) response to a request. +*/ +const JSONRPCResultResponseSchema = schemas_object({ + jsonrpc: literal(JSONRPC_VERSION), + id: RequestIdSchema, + result: ResultSchema +}).strict(); +/** +* A response to a request that indicates an error occurred. +*/ +const JSONRPCErrorResponseSchema = schemas_object({ + jsonrpc: literal(JSONRPC_VERSION), + id: RequestIdSchema.optional(), + error: schemas_object({ + code: schemas_number().int(), + message: schemas_string(), + data: unknown().optional() + }) +}).strict(); +const auth_CUe6YdwF_JSONRPCMessageSchema = schemas_union([ + JSONRPCRequestSchema, + JSONRPCNotificationSchema, + JSONRPCResultResponseSchema, + JSONRPCErrorResponseSchema +]); +const auth_CUe6YdwF_JSONRPCResponseSchema = schemas_union([JSONRPCResultResponseSchema, JSONRPCErrorResponseSchema]); +/** +* A response that indicates success but carries no data. +*/ +const EmptyResultSchema = ResultSchema.strict(); +const CancelledNotificationParamsSchema = NotificationsParamsSchema.extend({ + requestId: RequestIdSchema.optional(), + reason: schemas_string().optional() +}); +/** +* This notification can be sent by either side to indicate that it is cancelling a previously-issued request. +* +* The request SHOULD still be in-flight, but due to communication latency, it is always possible that this notification MAY arrive after the request has already finished. +* +* This notification indicates that the result will be unused, so any associated processing SHOULD cease. +* +* A client MUST NOT attempt to cancel its {@linkcode InitializeRequest | initialize} request. +*/ +const CancelledNotificationSchema = NotificationSchema.extend({ + method: literal("notifications/cancelled"), + params: CancelledNotificationParamsSchema +}); +/** +* Icon schema for use in {@link Tool | tools}, {@link Prompt | prompts}, {@link Resource | resources}, and {@link Implementation | implementations}. +*/ +const IconSchema = schemas_object({ + src: schemas_string(), + mimeType: schemas_string().optional(), + sizes: schemas_array(schemas_string()).optional(), + theme: schemas_enum(["light", "dark"]).optional() +}); +/** +* Base schema to add `icons` property. +* +*/ +const IconsSchema = schemas_object({ icons: schemas_array(IconSchema).optional() }); +/** +* Base metadata interface for common properties across {@link Resource | resources}, {@link Tool | tools}, {@link Prompt | prompts}, and {@link Implementation | implementations}. +*/ +const BaseMetadataSchema = schemas_object({ + name: schemas_string(), + title: schemas_string().optional() +}); +/** +* Describes the name and version of an MCP implementation. +*/ +const ImplementationSchema = BaseMetadataSchema.extend({ + ...BaseMetadataSchema.shape, + ...IconsSchema.shape, + version: schemas_string(), + websiteUrl: schemas_string().optional(), + description: schemas_string().optional() +}); +const auth_CUe6YdwF_FormElicitationCapabilitySchema = intersection(schemas_object({ applyDefaults: schemas_boolean().optional() }), JSONObjectSchema); +const auth_CUe6YdwF_ElicitationCapabilitySchema = preprocess((value) => { + if (value && typeof value === "object" && !Array.isArray(value) && Object.keys(value).length === 0) return { form: {} }; + return value; +}, intersection(schemas_object({ + form: auth_CUe6YdwF_FormElicitationCapabilitySchema.optional(), + url: JSONObjectSchema.optional() +}), JSONObjectSchema.optional())); +/** +* Task capabilities for clients, indicating which request types support task creation. +* +* @deprecated 2025-11-25 wire vocabulary with no SDK runtime; kept importable for interoperability only. +*/ +const ClientTasksCapabilitySchema = looseObject({ + list: JSONObjectSchema.optional(), + cancel: JSONObjectSchema.optional(), + requests: looseObject({ + sampling: looseObject({ createMessage: JSONObjectSchema.optional() }).optional(), + elicitation: looseObject({ create: JSONObjectSchema.optional() }).optional() + }).optional() +}); +/** +* Task capabilities for servers, indicating which request types support task creation. +* +* @deprecated 2025-11-25 wire vocabulary with no SDK runtime; kept importable for interoperability only. +*/ +const ServerTasksCapabilitySchema = looseObject({ + list: JSONObjectSchema.optional(), + cancel: JSONObjectSchema.optional(), + requests: looseObject({ tools: looseObject({ call: JSONObjectSchema.optional() }).optional() }).optional() +}); +/** +* Capabilities a client may support. Known capabilities are defined here, in this schema, but this is not a closed set: any client can define its own, additional capabilities. +*/ +const ClientCapabilitiesSchema = schemas_object({ + experimental: schemas_record(schemas_string(), JSONObjectSchema).optional(), + sampling: schemas_object({ + context: JSONObjectSchema.optional(), + tools: JSONObjectSchema.optional() + }).optional(), + elicitation: auth_CUe6YdwF_ElicitationCapabilitySchema.optional(), + roots: schemas_object({ listChanged: schemas_boolean().optional() }).optional(), + tasks: ClientTasksCapabilitySchema.optional(), + extensions: schemas_record(schemas_string(), JSONObjectSchema).optional() +}); +const InitializeRequestParamsSchema = BaseRequestParamsSchema.extend({ + protocolVersion: schemas_string(), + capabilities: ClientCapabilitiesSchema, + clientInfo: ImplementationSchema +}); +/** +* This request is sent from the client to the server when it first connects, asking it to begin initialization. +*/ +const auth_CUe6YdwF_InitializeRequestSchema = RequestSchema.extend({ + method: literal("initialize"), + params: InitializeRequestParamsSchema +}); +/** +* Capabilities that a server may support. Known capabilities are defined here, in this schema, but this is not a closed set: any server can define its own, additional capabilities. +*/ +const ServerCapabilitiesSchema = schemas_object({ + experimental: schemas_record(schemas_string(), JSONObjectSchema).optional(), + logging: JSONObjectSchema.optional(), + completions: JSONObjectSchema.optional(), + prompts: schemas_object({ listChanged: schemas_boolean().optional() }).optional(), + resources: schemas_object({ + subscribe: schemas_boolean().optional(), + listChanged: schemas_boolean().optional() + }).optional(), + tools: schemas_object({ listChanged: schemas_boolean().optional() }).optional(), + tasks: ServerTasksCapabilitySchema.optional(), + extensions: schemas_record(schemas_string(), JSONObjectSchema).optional() +}); +/** +* After receiving an initialize request from the client, the server sends this response. +*/ +const InitializeResultSchema = ResultSchema.extend({ + protocolVersion: schemas_string(), + capabilities: ServerCapabilitiesSchema, + serverInfo: ImplementationSchema, + instructions: schemas_string().optional() +}); +/** +* This notification is sent from the client to the server after initialization has finished. +*/ +const auth_CUe6YdwF_InitializedNotificationSchema = NotificationSchema.extend({ + method: literal("notifications/initialized"), + params: NotificationsParamsSchema.optional() +}); +/** +* A request from the client asking the server to advertise its supported protocol +* versions, capabilities, and other metadata (protocol revision 2026-07-28). Servers +* MUST implement `server/discover`. Clients MAY call it but are not required to — +* version negotiation can also happen inline via the per-request `_meta` envelope. +*/ +const DiscoverRequestSchema = RequestSchema.extend({ + method: literal("server/discover"), + params: BaseRequestParamsSchema.optional() +}); +/** +* The result returned by the server for a `server/discover` request. +*/ +const DiscoverResultSchema = ResultSchema.extend({ + supportedVersions: schemas_array(schemas_string()), + capabilities: ServerCapabilitiesSchema, + instructions: schemas_string().optional() +}); +/** +* A ping, issued by either the server or the client, to check that the other party is still alive. The receiver must promptly respond, or else may be disconnected. +*/ +const PingRequestSchema = RequestSchema.extend({ + method: literal("ping"), + params: BaseRequestParamsSchema.optional() +}); +const ProgressSchema = schemas_object({ + progress: schemas_number(), + total: schemas_optional(schemas_number()), + message: schemas_optional(schemas_string()) +}); +const ProgressNotificationParamsSchema = schemas_object({ + ...NotificationsParamsSchema.shape, + ...ProgressSchema.shape, + progressToken: ProgressTokenSchema +}); +/** +* An out-of-band notification used to inform the receiver of a progress update for a long-running request. +* +* @category notifications/progress +*/ +const ProgressNotificationSchema = NotificationSchema.extend({ + method: literal("notifications/progress"), + params: ProgressNotificationParamsSchema +}); +const PaginatedRequestParamsSchema = BaseRequestParamsSchema.extend({ cursor: CursorSchema.optional() }); +const PaginatedRequestSchema = RequestSchema.extend({ params: PaginatedRequestParamsSchema.optional() }); +const PaginatedResultSchema = ResultSchema.extend({ nextCursor: CursorSchema.optional() }); +/** +* The contents of a specific resource or sub-resource. +*/ +const ResourceContentsSchema = schemas_object({ + uri: schemas_string(), + mimeType: schemas_optional(schemas_string()), + _meta: schemas_record(schemas_string(), unknown()).optional() +}); +const TextResourceContentsSchema = ResourceContentsSchema.extend({ text: schemas_string() }); +/** +* A Zod schema for validating Base64 strings that is more performant and +* robust for very large inputs than the default regex-based check. It avoids +* stack overflows by using the native `atob` function for validation. +*/ +const auth_CUe6YdwF_Base64Schema = schemas_string().refine((val) => { + try { + atob(val); + return true; + } catch { + return false; + } +}, { message: "Invalid Base64 string" }); +const BlobResourceContentsSchema = ResourceContentsSchema.extend({ blob: auth_CUe6YdwF_Base64Schema }); +/** +* The sender or recipient of messages and data in a conversation. +*/ +const RoleSchema = schemas_enum(["user", "assistant"]); +/** +* Optional annotations providing clients additional context about a resource. +*/ +const AnnotationsSchema = schemas_object({ + audience: schemas_array(RoleSchema).optional(), + priority: schemas_number().min(0).max(1).optional(), + lastModified: iso_datetime({ offset: true }).optional() +}); +/** +* A known resource that the server is capable of reading. +*/ +const ResourceSchema = schemas_object({ + ...BaseMetadataSchema.shape, + ...IconsSchema.shape, + uri: schemas_string(), + description: schemas_optional(schemas_string()), + mimeType: schemas_optional(schemas_string()), + size: schemas_optional(schemas_number()), + annotations: AnnotationsSchema.optional(), + _meta: schemas_optional(looseObject({})) +}); +/** +* A template description for resources available on the server. +*/ +const ResourceTemplateSchema = schemas_object({ + ...BaseMetadataSchema.shape, + ...IconsSchema.shape, + uriTemplate: schemas_string(), + description: schemas_optional(schemas_string()), + mimeType: schemas_optional(schemas_string()), + annotations: AnnotationsSchema.optional(), + _meta: schemas_optional(looseObject({})) +}); +/** +* Sent from the client to request a list of resources the server has. +*/ +const ListResourcesRequestSchema = PaginatedRequestSchema.extend({ method: literal("resources/list") }); +/** +* The server's response to a {@linkcode ListResourcesRequest | resources/list} request from the client. +*/ +const ListResourcesResultSchema = PaginatedResultSchema.extend({ resources: schemas_array(ResourceSchema) }); +/** +* Sent from the client to request a list of resource templates the server has. +*/ +const ListResourceTemplatesRequestSchema = PaginatedRequestSchema.extend({ method: literal("resources/templates/list") }); +/** +* The server's response to a {@linkcode ListResourceTemplatesRequest | resources/templates/list} request from the client. +*/ +const ListResourceTemplatesResultSchema = PaginatedResultSchema.extend({ resourceTemplates: schemas_array(ResourceTemplateSchema) }); +const ResourceRequestParamsSchema = BaseRequestParamsSchema.extend({ uri: schemas_string() }); +/** +* Parameters for a {@linkcode ReadResourceRequest | resources/read} request. +*/ +const ReadResourceRequestParamsSchema = ResourceRequestParamsSchema; +/** +* Sent from the client to the server, to read a specific resource URI. +*/ +const ReadResourceRequestSchema = RequestSchema.extend({ + method: literal("resources/read"), + params: ReadResourceRequestParamsSchema +}); +/** +* The server's response to a {@linkcode ReadResourceRequest | resources/read} request from the client. +*/ +const ReadResourceResultSchema = ResultSchema.extend({ contents: schemas_array(schemas_union([TextResourceContentsSchema, BlobResourceContentsSchema])) }); +/** +* An optional notification from the server to the client, informing it that the list of resources it can read from has changed. This may be issued by servers without any previous subscription from the client. +*/ +const ResourceListChangedNotificationSchema = NotificationSchema.extend({ + method: literal("notifications/resources/list_changed"), + params: NotificationsParamsSchema.optional() +}); +const SubscribeRequestParamsSchema = ResourceRequestParamsSchema; +/** +* Sent from the client to request `resources/updated` notifications from the server whenever a particular resource changes. +*/ +const SubscribeRequestSchema = RequestSchema.extend({ + method: literal("resources/subscribe"), + params: SubscribeRequestParamsSchema +}); +const UnsubscribeRequestParamsSchema = ResourceRequestParamsSchema; +/** +* Sent from the client to request cancellation of {@linkcode ResourceUpdatedNotification | resources/updated} notifications from the server. This should follow a previous {@linkcode SubscribeRequest | resources/subscribe} request. +*/ +const UnsubscribeRequestSchema = RequestSchema.extend({ + method: literal("resources/unsubscribe"), + params: UnsubscribeRequestParamsSchema +}); +/** +* The set of notification types a client opts in to on a `subscriptions/listen` +* request. Each type is opt-in; the server MUST NOT send a notification type +* the client has not explicitly requested here. +*/ +const SubscriptionFilterSchema = schemas_object({ + toolsListChanged: schemas_boolean().optional(), + promptsListChanged: schemas_boolean().optional(), + resourcesListChanged: schemas_boolean().optional(), + resourceSubscriptions: schemas_array(schemas_string()).optional() +}); +const SubscriptionsListenRequestParamsSchema = BaseRequestParamsSchema.extend({ notifications: SubscriptionFilterSchema }); +/** +* Sent from the client to open a long-lived channel for receiving notifications +* outside the context of a specific request (protocol revision 2026-07-28). +* Replaces the previous HTTP GET endpoint and `resources/subscribe`. +*/ +const SubscriptionsListenRequestSchema = RequestSchema.extend({ + method: literal("subscriptions/listen"), + params: SubscriptionsListenRequestParamsSchema +}); +const SubscriptionsAcknowledgedNotificationParamsSchema = NotificationsParamsSchema.extend({ notifications: SubscriptionFilterSchema }); +/** +* Sent by the server as the first message on a `subscriptions/listen` stream +* to acknowledge that the subscription has been established and report which +* notification types it agreed to honor (protocol revision 2026-07-28). +*/ +const SubscriptionsAcknowledgedNotificationSchema = NotificationSchema.extend({ + method: literal("notifications/subscriptions/acknowledged"), + params: SubscriptionsAcknowledgedNotificationParamsSchema +}); +/** +* `_meta` for a {@linkcode SubscriptionsListenResult}: the listen request's +* JSON-RPC ID under the canonical subscription-id key (mirroring the same key +* on every notification delivered on the stream). Extends +* {@linkcode ResultMetaObjectSchema}, so the optional serverInfo key is typed +* here too. +*/ +const SubscriptionsListenResultMetaSchema = ResultMetaObjectSchema.extend({ [auth_CUe6YdwF_SUBSCRIPTION_ID_META_KEY]: RequestIdSchema }); +/** +* The response to a `subscriptions/listen` request, signalling that the +* subscription has ended gracefully (for example, during server shutdown). +* Because the listen stream is long-lived, this result is sent only when the +* server tears the subscription down; an abrupt transport close carries no +* response. The result body is otherwise empty. +*/ +const SubscriptionsListenResultSchema = ResultSchema.extend({ _meta: SubscriptionsListenResultMetaSchema }); +/** +* Parameters for a {@linkcode ResourceUpdatedNotification | notifications/resources/updated} notification. +*/ +const ResourceUpdatedNotificationParamsSchema = NotificationsParamsSchema.extend({ uri: schemas_string() }); +/** +* A notification from the server to the client, informing it that a resource has changed and may need to be read again. This should only be sent if the client previously sent a {@linkcode SubscribeRequest | resources/subscribe} request. +*/ +const ResourceUpdatedNotificationSchema = NotificationSchema.extend({ + method: literal("notifications/resources/updated"), + params: ResourceUpdatedNotificationParamsSchema +}); +/** +* Describes an argument that a prompt can accept. +*/ +const PromptArgumentSchema = schemas_object({ + name: schemas_string(), + description: schemas_optional(schemas_string()), + required: schemas_optional(schemas_boolean()) +}); +/** +* A prompt or prompt template that the server offers. +*/ +const PromptSchema = schemas_object({ + ...BaseMetadataSchema.shape, + ...IconsSchema.shape, + description: schemas_optional(schemas_string()), + arguments: schemas_optional(schemas_array(PromptArgumentSchema)), + _meta: schemas_optional(looseObject({})) +}); +/** +* Sent from the client to request a list of prompts and prompt templates the server has. +*/ +const ListPromptsRequestSchema = PaginatedRequestSchema.extend({ method: literal("prompts/list") }); +/** +* The server's response to a {@linkcode ListPromptsRequest | prompts/list} request from the client. +*/ +const ListPromptsResultSchema = PaginatedResultSchema.extend({ prompts: schemas_array(PromptSchema) }); +/** +* Parameters for a {@linkcode GetPromptRequest | prompts/get} request. +*/ +const GetPromptRequestParamsSchema = BaseRequestParamsSchema.extend({ + name: schemas_string(), + arguments: schemas_record(schemas_string(), schemas_string()).optional() +}); +/** +* Used by the client to get a prompt provided by the server. +*/ +const GetPromptRequestSchema = RequestSchema.extend({ + method: literal("prompts/get"), + params: GetPromptRequestParamsSchema +}); +/** +* Text provided to or from an LLM. +*/ +const TextContentSchema = schemas_object({ + type: literal("text"), + text: schemas_string(), + annotations: AnnotationsSchema.optional(), + _meta: schemas_record(schemas_string(), unknown()).optional() +}); +/** +* An image provided to or from an LLM. +*/ +const ImageContentSchema = schemas_object({ + type: literal("image"), + data: auth_CUe6YdwF_Base64Schema, + mimeType: schemas_string(), + annotations: AnnotationsSchema.optional(), + _meta: schemas_record(schemas_string(), unknown()).optional() +}); +/** +* Audio content provided to or from an LLM. +*/ +const AudioContentSchema = schemas_object({ + type: literal("audio"), + data: auth_CUe6YdwF_Base64Schema, + mimeType: schemas_string(), + annotations: AnnotationsSchema.optional(), + _meta: schemas_record(schemas_string(), unknown()).optional() +}); +/** +* A tool call request from an assistant (LLM). +* Represents the assistant's request to use a tool. +* +* @deprecated Deprecated as of protocol version 2026-07-28 (SEP-2577); remains +* in the specification for at least twelve months. Migrate to calling LLM +* provider APIs directly. +*/ +const ToolUseContentSchema = schemas_object({ + type: literal("tool_use"), + name: schemas_string(), + id: schemas_string(), + input: schemas_record(schemas_string(), unknown()), + _meta: schemas_record(schemas_string(), unknown()).optional() +}); +/** +* The contents of a resource, embedded into a prompt or tool call result. +*/ +const EmbeddedResourceSchema = schemas_object({ + type: literal("resource"), + resource: schemas_union([TextResourceContentsSchema, BlobResourceContentsSchema]), + annotations: AnnotationsSchema.optional(), + _meta: schemas_record(schemas_string(), unknown()).optional() +}); +/** +* A resource that the server is capable of reading, included in a prompt or tool call result. +* +* Note: resource links returned by tools are not guaranteed to appear in the results of {@linkcode ListResourcesRequest | resources/list} requests. +*/ +const ResourceLinkSchema = ResourceSchema.extend({ type: literal("resource_link") }); +/** +* A content block that can be used in prompts and tool results. +*/ +const ContentBlockSchema = schemas_union([ + TextContentSchema, + ImageContentSchema, + AudioContentSchema, + ResourceLinkSchema, + EmbeddedResourceSchema +]); +/** +* Describes a message returned as part of a prompt. +*/ +const PromptMessageSchema = schemas_object({ + role: RoleSchema, + content: ContentBlockSchema +}); +/** +* The server's response to a {@linkcode GetPromptRequest | prompts/get} request from the client. +*/ +const GetPromptResultSchema = ResultSchema.extend({ + description: schemas_string().optional(), + messages: schemas_array(PromptMessageSchema) +}); +/** +* An optional notification from the server to the client, informing it that the list of prompts it offers has changed. This may be issued by servers without any previous subscription from the client. +*/ +const PromptListChangedNotificationSchema = NotificationSchema.extend({ + method: literal("notifications/prompts/list_changed"), + params: NotificationsParamsSchema.optional() +}); +/** +* Additional properties describing a `Tool` to clients. +* +* NOTE: all properties in {@linkcode ToolAnnotations} are **hints**. +* They are not guaranteed to provide a faithful description of +* tool behavior (including descriptive properties like `title`). +* +* Clients should never make tool use decisions based on `ToolAnnotations` +* received from untrusted servers. +*/ +const ToolAnnotationsSchema = schemas_object({ + title: schemas_string().optional(), + readOnlyHint: schemas_boolean().optional(), + destructiveHint: schemas_boolean().optional(), + idempotentHint: schemas_boolean().optional(), + openWorldHint: schemas_boolean().optional() +}); +/** +* Execution-related properties for a tool. +*/ +const ToolExecutionSchema = schemas_object({ taskSupport: schemas_enum([ + "required", + "optional", + "forbidden" +]).optional() }); +/** +* Definition for a tool the client can call. +*/ +const ToolSchema = schemas_object({ + ...BaseMetadataSchema.shape, + ...IconsSchema.shape, + description: schemas_string().optional(), + inputSchema: schemas_object({ + type: literal("object"), + properties: schemas_record(schemas_string(), JSONValueSchema).optional(), + required: schemas_array(schemas_string()).optional() + }).catchall(unknown()), + outputSchema: looseObject({ $schema: schemas_string().optional() }).optional(), + annotations: ToolAnnotationsSchema.optional(), + execution: ToolExecutionSchema.optional(), + _meta: schemas_record(schemas_string(), unknown()).optional() +}); +/** +* Sent from the client to request a list of tools the server has. +*/ +const ListToolsRequestSchema = PaginatedRequestSchema.extend({ method: literal("tools/list") }); +/** +* The server's response to a {@linkcode ListToolsRequest | tools/list} request from the client. +*/ +const ListToolsResultSchema = PaginatedResultSchema.extend({ tools: schemas_array(ToolSchema) }); +/** +* The server's response to a tool call. +*/ +const auth_CUe6YdwF_CallToolResultSchema = ResultSchema.extend({ + content: schemas_array(ContentBlockSchema).default([]), + structuredContent: unknown().optional(), + isError: schemas_boolean().optional() +}); +/** +* {@linkcode CallToolResultSchema} extended with backwards compatibility to protocol version 2024-10-07. +*/ +const CompatibilityCallToolResultSchema = auth_CUe6YdwF_CallToolResultSchema.or(ResultSchema.extend({ toolResult: unknown() })); +/** +* Parameters for a `tools/call` request. +*/ +const CallToolRequestParamsSchema = auth_CUe6YdwF_TaskAugmentedRequestParamsSchema.extend({ + name: schemas_string(), + arguments: schemas_record(schemas_string(), unknown()).optional() +}); +/** +* Used by the client to invoke a tool provided by the server. +*/ +const CallToolRequestSchema = RequestSchema.extend({ + method: literal("tools/call"), + params: CallToolRequestParamsSchema +}); +/** +* An optional notification from the server to the client, informing it that the list of tools it offers has changed. This may be issued by servers without any previous subscription from the client. +*/ +const ToolListChangedNotificationSchema = NotificationSchema.extend({ + method: literal("notifications/tools/list_changed"), + params: NotificationsParamsSchema.optional() +}); +/** +* Base schema for list changed subscription options (without callback). +* Used internally for Zod validation of `autoRefresh` and `debounceMs`. +*/ +const ListChangedOptionsBaseSchema = schemas_object({ + autoRefresh: schemas_boolean().default(true), + debounceMs: schemas_number().int().nonnegative().default(300) +}); +/** +* The severity of a log message. +* +* @deprecated Deprecated as of protocol version 2026-07-28 (SEP-2577); remains +* in the specification for at least twelve months. Migrate to stderr logging +* (STDIO servers) or OpenTelemetry. +*/ +const LoggingLevelSchema = schemas_enum([ + "debug", + "info", + "notice", + "warning", + "error", + "critical", + "alert", + "emergency" +]); +/** +* Parameters for a `logging/setLevel` request. +* +* @deprecated Deprecated as of protocol version 2026-07-28 (SEP-2577); remains +* in the specification for at least twelve months. Migrate to stderr logging +* (STDIO servers) or OpenTelemetry. +*/ +const SetLevelRequestParamsSchema = BaseRequestParamsSchema.extend({ level: LoggingLevelSchema }); +/** +* A request from the client to the server, to enable or adjust logging. +* +* @deprecated Deprecated as of protocol version 2026-07-28 (SEP-2577); remains +* in the specification for at least twelve months. Migrate to stderr logging +* (STDIO servers) or OpenTelemetry. +*/ +const SetLevelRequestSchema = RequestSchema.extend({ + method: literal("logging/setLevel"), + params: SetLevelRequestParamsSchema +}); +/** +* Parameters for a `notifications/message` notification. +* +* @deprecated Deprecated as of protocol version 2026-07-28 (SEP-2577); remains +* in the specification for at least twelve months. Migrate to stderr logging +* (STDIO servers) or OpenTelemetry. +*/ +const LoggingMessageNotificationParamsSchema = NotificationsParamsSchema.extend({ + level: LoggingLevelSchema, + logger: schemas_string().optional(), + data: unknown() +}); +/** +* Notification of a log message passed from server to client. If no `logging/setLevel` request has been sent from the client, the server MAY decide which messages to send automatically. +* +* @deprecated Deprecated as of protocol version 2026-07-28 (SEP-2577); remains +* in the specification for at least twelve months. Migrate to stderr logging +* (STDIO servers) or OpenTelemetry. +*/ +const LoggingMessageNotificationSchema = NotificationSchema.extend({ + method: literal("notifications/message"), + params: LoggingMessageNotificationParamsSchema +}); +/** +* Hints to use for model selection. +* +* @deprecated Deprecated as of protocol version 2026-07-28 (SEP-2577); remains +* in the specification for at least twelve months. Migrate to calling LLM +* provider APIs directly. +*/ +const ModelHintSchema = schemas_object({ name: schemas_string().optional() }); +/** +* The server's preferences for model selection, requested of the client during sampling. +* +* @deprecated Deprecated as of protocol version 2026-07-28 (SEP-2577); remains +* in the specification for at least twelve months. Migrate to calling LLM +* provider APIs directly. +*/ +const ModelPreferencesSchema = schemas_object({ + hints: schemas_array(ModelHintSchema).optional(), + costPriority: schemas_number().min(0).max(1).optional(), + speedPriority: schemas_number().min(0).max(1).optional(), + intelligencePriority: schemas_number().min(0).max(1).optional() +}); +/** +* Controls tool usage behavior in sampling requests. +* +* @deprecated Deprecated as of protocol version 2026-07-28 (SEP-2577); remains +* in the specification for at least twelve months. Migrate to calling LLM +* provider APIs directly. +*/ +const ToolChoiceSchema = schemas_object({ mode: schemas_enum([ + "auto", + "required", + "none" +]).optional() }); +/** +* The result of a tool execution, provided by the user (server). +* Represents the outcome of invoking a tool requested via `ToolUseContent`. +* +* @deprecated Deprecated as of protocol version 2026-07-28 (SEP-2577); remains +* in the specification for at least twelve months. Migrate to calling LLM +* provider APIs directly. +*/ +const ToolResultContentSchema = schemas_object({ + type: literal("tool_result"), + toolUseId: schemas_string().describe("The unique identifier for the corresponding tool call."), + content: schemas_array(ContentBlockSchema), + structuredContent: unknown().optional(), + isError: schemas_boolean().optional(), + _meta: schemas_record(schemas_string(), unknown()).optional() +}); +/** +* Basic content types for sampling responses (without tool use). +* Used for backwards-compatible {@linkcode CreateMessageResult} when tools are not used. +* +* @deprecated Deprecated as of protocol version 2026-07-28 (SEP-2577); remains +* in the specification for at least twelve months. Migrate to calling LLM +* provider APIs directly. +*/ +const SamplingContentSchema = discriminatedUnion("type", [ + TextContentSchema, + ImageContentSchema, + AudioContentSchema +]); +/** +* Content block types allowed in sampling messages. +* This includes text, image, audio, tool use requests, and tool results. +* +* @deprecated Deprecated as of protocol version 2026-07-28 (SEP-2577); remains +* in the specification for at least twelve months. Migrate to calling LLM +* provider APIs directly. +*/ +const SamplingMessageContentBlockSchema = discriminatedUnion("type", [ + TextContentSchema, + ImageContentSchema, + AudioContentSchema, + ToolUseContentSchema, + ToolResultContentSchema +]); +/** +* Describes a message issued to or received from an LLM API. +* +* @deprecated Deprecated as of protocol version 2026-07-28 (SEP-2577); remains +* in the specification for at least twelve months. Migrate to calling LLM +* provider APIs directly. +*/ +const SamplingMessageSchema = schemas_object({ + role: RoleSchema, + content: schemas_union([SamplingMessageContentBlockSchema, schemas_array(SamplingMessageContentBlockSchema)]), + _meta: schemas_record(schemas_string(), unknown()).optional() +}); +/** +* Parameters for a `sampling/createMessage` request. +* +* @deprecated Deprecated as of protocol version 2026-07-28 (SEP-2577); remains +* in the specification for at least twelve months. Migrate to calling LLM +* provider APIs directly. +*/ +const CreateMessageRequestParamsSchema = auth_CUe6YdwF_TaskAugmentedRequestParamsSchema.extend({ + messages: schemas_array(SamplingMessageSchema), + modelPreferences: ModelPreferencesSchema.optional(), + systemPrompt: schemas_string().optional(), + includeContext: schemas_enum([ + "none", + "thisServer", + "allServers" + ]).optional(), + temperature: schemas_number().optional(), + maxTokens: schemas_number().int(), + stopSequences: schemas_array(schemas_string()).optional(), + metadata: JSONObjectSchema.optional(), + tools: schemas_array(ToolSchema).optional(), + toolChoice: ToolChoiceSchema.optional() +}); +/** +* A request from the server to sample an LLM via the client. The client has full discretion over which model to select. The client should also inform the user before beginning sampling, to allow them to inspect the request (human in the loop) and decide whether to approve it. +* +* @deprecated Deprecated as of protocol version 2026-07-28 (SEP-2577); remains +* in the specification for at least twelve months. Migrate to calling LLM +* provider APIs directly. +*/ +const CreateMessageRequestSchema = RequestSchema.extend({ + method: literal("sampling/createMessage"), + params: CreateMessageRequestParamsSchema +}); +/** +* The client's response to a `sampling/create_message` request from the server. +* This is the backwards-compatible version that returns single content (no arrays). +* Used when the request does not include tools. +* +* @deprecated Deprecated as of protocol version 2026-07-28 (SEP-2577); remains +* in the specification for at least twelve months. Migrate to calling LLM +* provider APIs directly. +*/ +const CreateMessageResultSchema = ResultSchema.extend({ + model: schemas_string(), + stopReason: schemas_optional(schemas_enum([ + "endTurn", + "stopSequence", + "maxTokens" + ]).or(schemas_string())), + role: RoleSchema, + content: SamplingContentSchema +}); +/** +* The client's response to a `sampling/create_message` request when tools were provided. +* This version supports array content for tool use flows. +* +* @deprecated Deprecated as of protocol version 2026-07-28 (SEP-2577); remains +* in the specification for at least twelve months. Migrate to calling LLM +* provider APIs directly. +*/ +const CreateMessageResultWithToolsSchema = ResultSchema.extend({ + model: schemas_string(), + stopReason: schemas_optional(schemas_enum([ + "endTurn", + "stopSequence", + "maxTokens", + "toolUse" + ]).or(schemas_string())), + role: RoleSchema, + content: schemas_union([SamplingMessageContentBlockSchema, schemas_array(SamplingMessageContentBlockSchema)]) +}); +/** +* Primitive schema definition for boolean fields. +*/ +const BooleanSchemaSchema = schemas_object({ + type: literal("boolean"), + title: schemas_string().optional(), + description: schemas_string().optional(), + default: schemas_boolean().optional() +}); +/** +* Primitive schema definition for string fields. +*/ +const StringSchemaSchema = schemas_object({ + type: literal("string"), + title: schemas_string().optional(), + description: schemas_string().optional(), + minLength: schemas_number().optional(), + maxLength: schemas_number().optional(), + format: schemas_enum([ + "email", + "uri", + "date", + "date-time" + ]).optional(), + default: schemas_string().optional() +}); +/** +* Primitive schema definition for number fields. +*/ +const NumberSchemaSchema = schemas_object({ + type: schemas_enum(["number", "integer"]), + title: schemas_string().optional(), + description: schemas_string().optional(), + minimum: schemas_number().optional(), + maximum: schemas_number().optional(), + default: schemas_number().optional() +}); +/** +* Schema for single-selection enumeration without display titles for options. +*/ +const UntitledSingleSelectEnumSchemaSchema = schemas_object({ + type: literal("string"), + title: schemas_string().optional(), + description: schemas_string().optional(), + enum: schemas_array(schemas_string()), + default: schemas_string().optional() +}); +/** +* Schema for single-selection enumeration with display titles for each option. +*/ +const TitledSingleSelectEnumSchemaSchema = schemas_object({ + type: literal("string"), + title: schemas_string().optional(), + description: schemas_string().optional(), + oneOf: schemas_array(schemas_object({ + const: schemas_string(), + title: schemas_string() + })), + default: schemas_string().optional() +}); +/** +* Use {@linkcode TitledSingleSelectEnumSchema} instead. +* This interface will be removed in a future version. +*/ +const LegacyTitledEnumSchemaSchema = schemas_object({ + type: literal("string"), + title: schemas_string().optional(), + description: schemas_string().optional(), + enum: schemas_array(schemas_string()), + enumNames: schemas_array(schemas_string()).optional(), + default: schemas_string().optional() +}); +const SingleSelectEnumSchemaSchema = schemas_union([UntitledSingleSelectEnumSchemaSchema, TitledSingleSelectEnumSchemaSchema]); +/** +* Schema for multiple-selection enumeration without display titles for options. +*/ +const UntitledMultiSelectEnumSchemaSchema = schemas_object({ + type: literal("array"), + title: schemas_string().optional(), + description: schemas_string().optional(), + minItems: schemas_number().optional(), + maxItems: schemas_number().optional(), + items: schemas_object({ + type: literal("string"), + enum: schemas_array(schemas_string()) + }), + default: schemas_array(schemas_string()).optional() +}); +/** +* Schema for multiple-selection enumeration with display titles for each option. +*/ +const TitledMultiSelectEnumSchemaSchema = schemas_object({ + type: literal("array"), + title: schemas_string().optional(), + description: schemas_string().optional(), + minItems: schemas_number().optional(), + maxItems: schemas_number().optional(), + items: schemas_object({ anyOf: schemas_array(schemas_object({ + const: schemas_string(), + title: schemas_string() + })) }), + default: schemas_array(schemas_string()).optional() +}); +/** +* Combined schema for multiple-selection enumeration +*/ +const MultiSelectEnumSchemaSchema = schemas_union([UntitledMultiSelectEnumSchemaSchema, TitledMultiSelectEnumSchemaSchema]); +/** +* Primitive schema definition for enum fields. +*/ +const EnumSchemaSchema = schemas_union([ + LegacyTitledEnumSchemaSchema, + SingleSelectEnumSchemaSchema, + MultiSelectEnumSchemaSchema +]); +/** +* Union of all primitive schema definitions. +*/ +const PrimitiveSchemaDefinitionSchema = schemas_union([ + EnumSchemaSchema, + BooleanSchemaSchema, + StringSchemaSchema, + NumberSchemaSchema +]); +/** +* Parameters for an `elicitation/create` request for form-based elicitation. +*/ +const ElicitRequestFormParamsSchema = auth_CUe6YdwF_TaskAugmentedRequestParamsSchema.extend({ + mode: literal("form").optional(), + message: schemas_string(), + requestedSchema: schemas_object({ + type: literal("object"), + properties: schemas_record(schemas_string(), PrimitiveSchemaDefinitionSchema), + required: schemas_array(schemas_string()).optional() + }).catchall(unknown()) +}); +/** +* Parameters for an {@linkcode ElicitRequest | elicitation/create} request for URL-based elicitation. +*/ +const ElicitRequestURLParamsSchema = auth_CUe6YdwF_TaskAugmentedRequestParamsSchema.extend({ + mode: literal("url"), + message: schemas_string(), + elicitationId: schemas_string(), + url: schemas_string().url() +}); +/** +* The parameters for a request to elicit additional information from the user via the client. +*/ +const ElicitRequestParamsSchema = schemas_union([ElicitRequestFormParamsSchema, ElicitRequestURLParamsSchema]); +/** +* A request from the server to elicit user input via the client. +* The client should present the message and form fields to the user (form mode) +* or navigate to a URL (URL mode). +*/ +const ElicitRequestSchema = RequestSchema.extend({ + method: literal("elicitation/create"), + params: ElicitRequestParamsSchema +}); +/** +* Parameters for a {@linkcode ElicitationCompleteNotification | notifications/elicitation/complete} notification. +* +* @deprecated Removed from the spec by #2891 (2026-07-28). The client learns the outcome +* of an out-of-band interaction by retrying the original request; no server-initiated +* completion signal exists in the 2026-07-28 revision. Kept here for the 2025-era flow +* only. The 2026-07-28 wire codec excludes this notification. +* @category notifications/elicitation/complete +*/ +const ElicitationCompleteNotificationParamsSchema = NotificationsParamsSchema.extend({ elicitationId: schemas_string() }); +/** +* A notification from the server to the client, informing it of a completion of an out-of-band elicitation request. +* +* @deprecated Removed from the spec by #2891 (2026-07-28). The client learns the outcome +* of an out-of-band interaction by retrying the original request; no server-initiated +* completion signal exists in the 2026-07-28 revision. Kept here for the 2025-era flow +* only. The 2026-07-28 wire codec excludes this notification. +* @category notifications/elicitation/complete +*/ +const ElicitationCompleteNotificationSchema = NotificationSchema.extend({ + method: literal("notifications/elicitation/complete"), + params: ElicitationCompleteNotificationParamsSchema +}); +/** +* The client's response to an {@linkcode ElicitRequest | elicitation/create} request from the server. +*/ +const ElicitResultSchema = ResultSchema.extend({ + action: schemas_enum([ + "accept", + "decline", + "cancel" + ]), + content: preprocess((val) => val === null ? void 0 : val, schemas_record(schemas_string(), schemas_union([ + schemas_string(), + schemas_number(), + schemas_boolean(), + schemas_array(schemas_string()) + ])).optional()) +}); +/** +* A reference to a resource or resource template definition. +*/ +const ResourceTemplateReferenceSchema = schemas_object({ + type: literal("ref/resource"), + uri: schemas_string() +}); +/** +* Identifies a prompt. +*/ +const PromptReferenceSchema = schemas_object({ + type: literal("ref/prompt"), + name: schemas_string() +}); +/** +* Parameters for a {@linkcode CompleteRequest | completion/complete} request. +*/ +const CompleteRequestParamsSchema = BaseRequestParamsSchema.extend({ + ref: schemas_union([PromptReferenceSchema, ResourceTemplateReferenceSchema]), + argument: schemas_object({ + name: schemas_string(), + value: schemas_string() + }), + context: schemas_object({ arguments: schemas_record(schemas_string(), schemas_string()).optional() }).optional() +}); +/** +* A request from the client to the server, to ask for completion options. +*/ +const CompleteRequestSchema = RequestSchema.extend({ + method: literal("completion/complete"), + params: CompleteRequestParamsSchema +}); +/** +* The server's response to a {@linkcode CompleteRequest | completion/complete} request +*/ +const CompleteResultSchema = ResultSchema.extend({ completion: looseObject({ + values: schemas_array(schemas_string()).max(100), + total: schemas_optional(schemas_number().int()), + hasMore: schemas_optional(schemas_boolean()) +}) }); +/** +* Represents a root directory or file that the server can operate on. +* +* @deprecated Deprecated as of protocol version 2026-07-28 (SEP-2577); remains +* in the specification for at least twelve months. Migrate to passing paths via +* tool parameters, resource URIs, or configuration. +*/ +const RootSchema = schemas_object({ + uri: schemas_string().startsWith("file://"), + name: schemas_string().optional(), + _meta: schemas_record(schemas_string(), unknown()).optional() +}); +/** +* Sent from the server to request a list of root URIs from the client. +* +* @deprecated Deprecated as of protocol version 2026-07-28 (SEP-2577); remains +* in the specification for at least twelve months. Migrate to passing paths via +* tool parameters, resource URIs, or configuration. +*/ +const ListRootsRequestSchema = RequestSchema.extend({ + method: literal("roots/list"), + params: BaseRequestParamsSchema.optional() +}); +/** +* The client's response to a `roots/list` request from the server. +* +* @deprecated Deprecated as of protocol version 2026-07-28 (SEP-2577); remains +* in the specification for at least twelve months. Migrate to passing paths via +* tool parameters, resource URIs, or configuration. +*/ +const ListRootsResultSchema = ResultSchema.extend({ roots: schemas_array(RootSchema) }); +/** +* A notification from the client to the server, informing it that the list of roots has changed. +* +* @deprecated Deprecated as of protocol version 2026-07-28 (SEP-2577); remains +* in the specification for at least twelve months. Migrate to passing paths via +* tool parameters, resource URIs, or configuration. +*/ +const RootsListChangedNotificationSchema = NotificationSchema.extend({ + method: literal("notifications/roots/list_changed"), + params: NotificationsParamsSchema.optional() +}); +/** +* Task creation parameters, used to ask that the server create a task to represent a request. +* +* @deprecated 2025-11-25 wire vocabulary with no SDK runtime; kept importable for interoperability only. +*/ +const TaskCreationParamsSchema = looseObject({ + ttl: schemas_number().optional(), + pollInterval: schemas_number().optional() +}); +/** +* The status of a task. +* +* @deprecated 2025-11-25 wire vocabulary with no SDK runtime; kept importable for interoperability only. +*/ +const TaskStatusSchema = schemas_enum([ + "working", + "input_required", + "completed", + "failed", + "cancelled" +]); +/** +* A pollable state object associated with a request. +* +* @deprecated 2025-11-25 wire vocabulary with no SDK runtime; kept importable for interoperability only. +*/ +const TaskSchema = schemas_object({ + taskId: schemas_string(), + status: TaskStatusSchema, + ttl: schemas_union([schemas_number(), schemas_null()]), + createdAt: schemas_string(), + lastUpdatedAt: schemas_string(), + pollInterval: schemas_optional(schemas_number()), + statusMessage: schemas_optional(schemas_string()) +}); +/** +* Result returned when a task is created, containing the task data wrapped in a `task` field. +* +* @deprecated 2025-11-25 wire vocabulary with no SDK runtime; kept importable for interoperability only. +*/ +const CreateTaskResultSchema = ResultSchema.extend({ task: TaskSchema }); +/** +* Parameters for task status notification. +* +* @deprecated 2025-11-25 wire vocabulary with no SDK runtime; kept importable for interoperability only. +*/ +const TaskStatusNotificationParamsSchema = NotificationsParamsSchema.merge(TaskSchema); +/** +* A notification sent when a task's status changes. +* +* @deprecated 2025-11-25 wire vocabulary with no SDK runtime; kept importable for interoperability only. +*/ +const TaskStatusNotificationSchema = NotificationSchema.extend({ + method: literal("notifications/tasks/status"), + params: TaskStatusNotificationParamsSchema +}); +/** +* A request to get the state of a specific task. +* +* @deprecated 2025-11-25 wire vocabulary with no SDK runtime; kept importable for interoperability only. +*/ +const GetTaskRequestSchema = RequestSchema.extend({ + method: literal("tasks/get"), + params: BaseRequestParamsSchema.extend({ taskId: schemas_string() }) +}); +/** +* The response to a {@linkcode GetTaskRequest | tasks/get} request. +* +* @deprecated 2025-11-25 wire vocabulary with no SDK runtime; kept importable for interoperability only. +*/ +const GetTaskResultSchema = ResultSchema.merge(TaskSchema); +/** +* A request to get the result of a specific task. +* +* @deprecated 2025-11-25 wire vocabulary with no SDK runtime; kept importable for interoperability only. +*/ +const GetTaskPayloadRequestSchema = RequestSchema.extend({ + method: literal("tasks/result"), + params: BaseRequestParamsSchema.extend({ taskId: schemas_string() }) +}); +/** +* The response to a `tasks/result` request. +* The structure matches the result type of the original request. +* For example, a {@linkcode CallToolRequest | tools/call} task would return the `CallToolResult` structure. +* +* +* @deprecated 2025-11-25 wire vocabulary with no SDK runtime; kept importable for interoperability only. +*/ +const GetTaskPayloadResultSchema = ResultSchema.loose(); +/** +* A request to list tasks. +* +* @deprecated 2025-11-25 wire vocabulary with no SDK runtime; kept importable for interoperability only. +*/ +const ListTasksRequestSchema = PaginatedRequestSchema.extend({ method: literal("tasks/list") }); +/** +* The response to a {@linkcode ListTasksRequest | tasks/list} request. +* +* @deprecated 2025-11-25 wire vocabulary with no SDK runtime; kept importable for interoperability only. +*/ +const ListTasksResultSchema = PaginatedResultSchema.extend({ tasks: schemas_array(TaskSchema) }); +/** +* A request to cancel a specific task. +* +* @deprecated 2025-11-25 wire vocabulary with no SDK runtime; kept importable for interoperability only. +*/ +const CancelTaskRequestSchema = RequestSchema.extend({ + method: literal("tasks/cancel"), + params: BaseRequestParamsSchema.extend({ taskId: schemas_string() }) +}); +/** +* The response to a {@linkcode CancelTaskRequest | tasks/cancel} request. +* +* @deprecated 2025-11-25 wire vocabulary with no SDK runtime; kept importable for interoperability only. +*/ +const CancelTaskResultSchema = ResultSchema.merge(TaskSchema); +const ClientRequestSchema = schemas_union([ + PingRequestSchema, + auth_CUe6YdwF_InitializeRequestSchema, + DiscoverRequestSchema, + CompleteRequestSchema, + SetLevelRequestSchema, + GetPromptRequestSchema, + ListPromptsRequestSchema, + ListResourcesRequestSchema, + ListResourceTemplatesRequestSchema, + ReadResourceRequestSchema, + SubscribeRequestSchema, + UnsubscribeRequestSchema, + SubscriptionsListenRequestSchema, + CallToolRequestSchema, + ListToolsRequestSchema +]); +const ClientNotificationSchema = schemas_union([ + CancelledNotificationSchema, + ProgressNotificationSchema, + auth_CUe6YdwF_InitializedNotificationSchema, + RootsListChangedNotificationSchema +]); +const ClientResultSchema = schemas_union([ + EmptyResultSchema, + CreateMessageResultSchema, + CreateMessageResultWithToolsSchema, + ElicitResultSchema, + ListRootsResultSchema +]); +const ServerRequestSchema = schemas_union([ + PingRequestSchema, + CreateMessageRequestSchema, + ElicitRequestSchema, + ListRootsRequestSchema +]); +const ServerNotificationSchema = schemas_union([ + CancelledNotificationSchema, + ProgressNotificationSchema, + LoggingMessageNotificationSchema, + ResourceUpdatedNotificationSchema, + ResourceListChangedNotificationSchema, + ToolListChangedNotificationSchema, + PromptListChangedNotificationSchema, + SubscriptionsAcknowledgedNotificationSchema, + ElicitationCompleteNotificationSchema +]); +const ServerResultSchema = schemas_union([ + EmptyResultSchema, + InitializeResultSchema, + DiscoverResultSchema, + CompleteResultSchema, + GetPromptResultSchema, + ListPromptsResultSchema, + ListResourcesResultSchema, + ListResourceTemplatesResultSchema, + ReadResourceResultSchema, + auth_CUe6YdwF_CallToolResultSchema, + ListToolsResultSchema, + SubscriptionsListenResultSchema +]); + +//#endregion +//#region src/auth.ts +/** +* Reusable URL validation that disallows `javascript:` scheme +*/ +const SafeUrlSchema = schemas_url().superRefine((val, ctx) => { + if (!URL.canParse(val)) { + ctx.addIssue({ + code: ZodIssueCode.custom, + message: "URL must be parseable", + fatal: true + }); + return NEVER; + } +}).refine((url) => { + const u = new URL(url); + return u.protocol !== "javascript:" && u.protocol !== "data:" && u.protocol !== "vbscript:"; +}, { message: "URL cannot use javascript:, data:, or vbscript: scheme" }); +/** +* RFC 9728 OAuth Protected Resource Metadata +*/ +const OAuthProtectedResourceMetadataSchema = looseObject({ + resource: schemas_string().url(), + authorization_servers: schemas_array(SafeUrlSchema).optional(), + jwks_uri: schemas_string().url().optional(), + scopes_supported: schemas_array(schemas_string()).optional(), + bearer_methods_supported: schemas_array(schemas_string()).optional(), + resource_signing_alg_values_supported: schemas_array(schemas_string()).optional(), + resource_name: schemas_string().optional(), + resource_documentation: schemas_string().optional(), + resource_policy_uri: schemas_string().url().optional(), + resource_tos_uri: schemas_string().url().optional(), + tls_client_certificate_bound_access_tokens: schemas_boolean().optional(), + authorization_details_types_supported: schemas_array(schemas_string()).optional(), + dpop_signing_alg_values_supported: schemas_array(schemas_string()).optional(), + dpop_bound_access_tokens_required: schemas_boolean().optional() +}); +/** +* RFC 8414 OAuth 2.0 Authorization Server Metadata +*/ +const OAuthMetadataSchema = looseObject({ + issuer: schemas_string(), + authorization_endpoint: SafeUrlSchema, + token_endpoint: SafeUrlSchema, + registration_endpoint: SafeUrlSchema.optional(), + scopes_supported: schemas_array(schemas_string()).optional(), + response_types_supported: schemas_array(schemas_string()), + response_modes_supported: schemas_array(schemas_string()).optional(), + grant_types_supported: schemas_array(schemas_string()).optional(), + token_endpoint_auth_methods_supported: schemas_array(schemas_string()).optional(), + token_endpoint_auth_signing_alg_values_supported: schemas_array(schemas_string()).optional(), + service_documentation: SafeUrlSchema.optional(), + revocation_endpoint: SafeUrlSchema.optional(), + revocation_endpoint_auth_methods_supported: schemas_array(schemas_string()).optional(), + revocation_endpoint_auth_signing_alg_values_supported: schemas_array(schemas_string()).optional(), + introspection_endpoint: schemas_string().optional(), + introspection_endpoint_auth_methods_supported: schemas_array(schemas_string()).optional(), + introspection_endpoint_auth_signing_alg_values_supported: schemas_array(schemas_string()).optional(), + code_challenge_methods_supported: schemas_array(schemas_string()).optional(), + client_id_metadata_document_supported: schemas_boolean().optional(), + authorization_response_iss_parameter_supported: schemas_boolean().optional().catch(void 0) +}); +/** +* OpenID Connect Discovery 1.0 Provider Metadata +* +* @see https://openid.net/specs/openid-connect-discovery-1_0.html#ProviderMetadata +*/ +const OpenIdProviderMetadataSchema = looseObject({ + issuer: schemas_string(), + authorization_endpoint: SafeUrlSchema, + token_endpoint: SafeUrlSchema, + userinfo_endpoint: SafeUrlSchema.optional(), + jwks_uri: SafeUrlSchema, + registration_endpoint: SafeUrlSchema.optional(), + scopes_supported: schemas_array(schemas_string()).optional(), + response_types_supported: schemas_array(schemas_string()), + response_modes_supported: schemas_array(schemas_string()).optional(), + grant_types_supported: schemas_array(schemas_string()).optional(), + acr_values_supported: schemas_array(schemas_string()).optional(), + subject_types_supported: schemas_array(schemas_string()), + id_token_signing_alg_values_supported: schemas_array(schemas_string()), + id_token_encryption_alg_values_supported: schemas_array(schemas_string()).optional(), + id_token_encryption_enc_values_supported: schemas_array(schemas_string()).optional(), + userinfo_signing_alg_values_supported: schemas_array(schemas_string()).optional(), + userinfo_encryption_alg_values_supported: schemas_array(schemas_string()).optional(), + userinfo_encryption_enc_values_supported: schemas_array(schemas_string()).optional(), + request_object_signing_alg_values_supported: schemas_array(schemas_string()).optional(), + request_object_encryption_alg_values_supported: schemas_array(schemas_string()).optional(), + request_object_encryption_enc_values_supported: schemas_array(schemas_string()).optional(), + token_endpoint_auth_methods_supported: schemas_array(schemas_string()).optional(), + token_endpoint_auth_signing_alg_values_supported: schemas_array(schemas_string()).optional(), + display_values_supported: schemas_array(schemas_string()).optional(), + claim_types_supported: schemas_array(schemas_string()).optional(), + claims_supported: schemas_array(schemas_string()).optional(), + service_documentation: schemas_string().optional(), + claims_locales_supported: schemas_array(schemas_string()).optional(), + ui_locales_supported: schemas_array(schemas_string()).optional(), + claims_parameter_supported: schemas_boolean().optional(), + request_parameter_supported: schemas_boolean().optional(), + request_uri_parameter_supported: schemas_boolean().optional(), + require_request_uri_registration: schemas_boolean().optional(), + op_policy_uri: SafeUrlSchema.optional(), + op_tos_uri: SafeUrlSchema.optional(), + client_id_metadata_document_supported: schemas_boolean().optional(), + authorization_response_iss_parameter_supported: schemas_boolean().optional().catch(void 0) +}); +/** +* OpenID Connect Discovery metadata that may include OAuth 2.0 fields +* This schema represents the real-world scenario where OIDC providers +* return a mix of OpenID Connect and OAuth 2.0 metadata fields +*/ +const OpenIdProviderDiscoveryMetadataSchema = schemas_object({ + ...OpenIdProviderMetadataSchema.shape, + ...OAuthMetadataSchema.pick({ code_challenge_methods_supported: true }).shape +}); +/** +* OAuth 2.1 token response +*/ +const OAuthTokensSchema = schemas_object({ + access_token: schemas_string(), + id_token: schemas_string().optional(), + token_type: schemas_string(), + expires_in: coerce_number().optional(), + scope: schemas_string().optional(), + refresh_token: schemas_string().optional() +}).strip(); +/** +* RFC 8693 §2.2.1 Token Exchange response for ID-JAG tokens. +* +* `token_type` is intentionally optional: per RFC 8693 §2.2.1 it is informational when +* the issued token is not an access token, and per RFC 6749 §5.1 it is case-insensitive, +* so strict checking rejects conformant IdPs. +*/ +const IdJagTokenExchangeResponseSchema = schemas_object({ + issued_token_type: literal("urn:ietf:params:oauth:token-type:id-jag"), + access_token: schemas_string(), + token_type: schemas_string().optional(), + expires_in: schemas_number().optional(), + scope: schemas_string().optional() +}).strip(); +/** +* OAuth 2.1 error response +*/ +const OAuthErrorResponseSchema = schemas_object({ + error: schemas_string(), + error_description: schemas_string().optional(), + error_uri: schemas_string().optional() +}); +/** +* Optional version of {@linkcode SafeUrlSchema} that allows empty string for backward compatibility on `tos_uri` and `logo_uri` +*/ +const OptionalSafeUrlSchema = SafeUrlSchema.optional().or(literal("").transform(() => void 0)); +/** +* RFC 7591 OAuth 2.0 Dynamic Client Registration metadata +*/ +const OAuthClientMetadataSchema = schemas_object({ + redirect_uris: schemas_array(SafeUrlSchema), + token_endpoint_auth_method: schemas_string().optional(), + grant_types: schemas_array(schemas_string()).optional(), + response_types: schemas_array(schemas_string()).optional(), + application_type: schemas_string().optional(), + client_name: schemas_string().optional(), + client_uri: SafeUrlSchema.optional(), + logo_uri: OptionalSafeUrlSchema, + scope: schemas_string().optional(), + contacts: schemas_array(schemas_string()).optional(), + tos_uri: OptionalSafeUrlSchema, + policy_uri: schemas_string().optional(), + jwks_uri: SafeUrlSchema.optional(), + jwks: any().optional(), + software_id: schemas_string().optional(), + software_version: schemas_string().optional(), + software_statement: schemas_string().optional() +}).strip(); +/** +* RFC 7591 OAuth 2.0 Dynamic Client Registration client information +*/ +const OAuthClientInformationSchema = schemas_object({ + client_id: schemas_string(), + client_secret: schemas_string().optional(), + client_id_issued_at: schemas_number().optional(), + client_secret_expires_at: schemas_number().optional() +}).strip(); +/** +* RFC 7591 OAuth 2.0 Dynamic Client Registration full response (client information plus metadata) +*/ +const OAuthClientInformationFullSchema = OAuthClientMetadataSchema.merge(OAuthClientInformationSchema); +/** +* RFC 7591 OAuth 2.0 Dynamic Client Registration error response +*/ +const OAuthClientRegistrationErrorSchema = schemas_object({ + error: schemas_string(), + error_description: schemas_string().optional() +}).strip(); +/** +* RFC 7009 OAuth 2.0 Token Revocation request +*/ +const OAuthTokenRevocationRequestSchema = schemas_object({ + token: schemas_string(), + token_type_hint: schemas_string().optional() +}).strip(); + +//#endregion + +//# sourceMappingURL=auth-CUe6YdwF.mjs.map + + + + + + + + +//#region ../core-internal/src/errors/crossBundleBrand.ts +/** +* Cross-bundle `instanceof` support for the SDK error classes. +* +* `@modelcontextprotocol/client` and `@modelcontextprotocol/server` each bundle their +* own copy of `core-internal`, so an error constructed by one package fails a +* prototype-identity `instanceof` against the same class re-exported by the other — +* exactly the check a dual-role process (gateway, host, in-process test) writes. +* +* Instead of prototype identity, branded classes stamp every instance with the brand +* strings of its class chain under a registry symbol (`Symbol.for`, shared across +* bundles and realms), and resolve `instanceof` via `Symbol.hasInstance` against the +* brand set. Ordinary prototype-based `instanceof` is kept as a fallback so behavior +* is unchanged for anything unbranded. +* +* A class participates by defining an **own** `mcpBrand` static (via a `static {}` +* block, so nothing reaches the declaration files — a declared `protected static` +* field would make the constructor types nominally incompatible across the bundled +* copies) and (for hierarchy roots) installing {@linkcode brandedHasInstance} as +* `Symbol.hasInstance`. User-defined subclasses that do not declare their own brand +* keep plain prototype semantics — a foreign base-class instance never satisfies +* `instanceof UserSubclass`. +* +* Prior art — the same stamp-and-hook shape ships at scale elsewhere: Node core +* (stream.Writable since 2017, Console via a marker symbol, diagnostics_channel), +* undici's whole error hierarchy (vendored into Node as fetch), googleapis/gaxios +* (GaxiosError, Symbol.for marker), AWS SDK v3's ServiceException (which pairs a +* Symbol.hasInstance override with a static isInstance guard, as we do), and zod v4 +* (Symbol.hasInstance on every schema class for cross-version interop). +* +* Contract notes: +* - Participation criterion: **every error class exported from a public package that +* callers are documented to `instanceof` must be branded.** The per-package +* errorBrandConformance tests walk the export surfaces and fail naming any +* exported Error subclass that has not opted in. +* - Brands assert **identity, not shape**: brand strings are version-less, so an +* instance from one SDK version matches the class of another. Members added to a +* branded class in a later version may be absent on a matched instance — read +* fields defensively, and treat branded classes as additive-only. The escape +* hatch when a release must break a branded class's read contract: change that +* class's brand string in the same release, which cleanly severs cross-version +* matching for that class. The per-package brand pins make the rename +* deliberate: errorSurfacePins.test.ts owns the core-internal brands, and each +* package's errorBrandConformance test pins its package-local ones. +* - Cross-bundle matching requires **both** copies to be at or after the release +* that introduced branding; against an older copy, behavior degrades to plain +* prototype `instanceof` in both directions. +* - A consumer re-bundling the SDK with property mangling (`mangle.props`) would +* break the brand statics; default esbuild/webpack/terser settings do not. +*/ +/** Registry symbol — identical across bundled copies and realms. */ +const BRANDS = Symbol.for("mcp.sdk.errorBrands"); +/** +* Stamp `instance` with the brand of every class in `ctor`'s chain that declares an +* own `mcpBrand`. Call once from the hierarchy root's constructor with `new.target` — +* subclasses inherit the stamping without touching their constructors. +* +* Constructor-time only: never stamp arbitrary objects. A stamped non-instance would +* satisfy `instanceof` while lacking the prototype members (getters like `.status`) +* that callers reach for after the check. +*/ +function stampErrorBrands(instance, ctor) { + const brands = /* @__PURE__ */ new Set(); + let current = ctor; + while (typeof current === "function") { + const brand = current.mcpBrand; + if (Object.prototype.hasOwnProperty.call(current, "mcpBrand") && typeof brand === "string") brands.add(brand); + current = Object.getPrototypeOf(current); + } + if (brands.size === 0) return; + Object.defineProperty(instance, BRANDS, { + value: brands, + enumerable: false, + configurable: true + }); +} +/** +* `Symbol.hasInstance` implementation for branded hierarchy roots. Matches when the +* value carries the **own** brand of the class being tested against (cross-bundle +* path), falling back to ordinary prototype-based `instanceof` otherwise. +*/ +function brandedHasInstance(cls, value) { + try { + if (typeof value === "object" && value !== null && Object.prototype.hasOwnProperty.call(cls, "mcpBrand") && typeof cls.mcpBrand === "string" && Object.prototype.hasOwnProperty.call(value, BRANDS)) { + const carried = value[BRANDS]; + if (carried && typeof carried.has === "function" && carried.has(cls.mcpBrand)) return true; + } + } catch {} + return Function.prototype[Symbol.hasInstance].call(cls, value); +} + +//#endregion +//#region ../core-internal/src/auth/errors.ts +/** +* OAuth error codes as defined by {@link https://datatracker.ietf.org/doc/html/rfc6749#section-5.2 | RFC 6749} +* and extensions. +*/ +let src_CX2iR2pK_OAuthErrorCode = /* @__PURE__ */ (/* unused pure expression or super */ null && (function(OAuthErrorCode$1) { + /** + * The request is missing a required parameter, includes an invalid parameter value, + * includes a parameter more than once, or is otherwise malformed. + */ + OAuthErrorCode$1["InvalidRequest"] = "invalid_request"; + /** + * Client authentication failed (e.g., unknown client, no client authentication included, + * or unsupported authentication method). + */ + OAuthErrorCode$1["InvalidClient"] = "invalid_client"; + /** + * The provided authorization grant or refresh token is invalid, expired, revoked, + * does not match the redirection URI used in the authorization request, or was issued to another client. + */ + OAuthErrorCode$1["InvalidGrant"] = "invalid_grant"; + /** + * The authenticated client is not authorized to use this authorization grant type. + */ + OAuthErrorCode$1["UnauthorizedClient"] = "unauthorized_client"; + /** + * The authorization grant type is not supported by the authorization server. + */ + OAuthErrorCode$1["UnsupportedGrantType"] = "unsupported_grant_type"; + /** + * The requested scope is invalid, unknown, malformed, or exceeds the scope granted by the resource owner. + */ + OAuthErrorCode$1["InvalidScope"] = "invalid_scope"; + /** + * The resource owner or authorization server denied the request. + */ + OAuthErrorCode$1["AccessDenied"] = "access_denied"; + /** + * The authorization server encountered an unexpected condition that prevented it from fulfilling the request. + */ + OAuthErrorCode$1["ServerError"] = "server_error"; + /** + * The authorization server is currently unable to handle the request due to temporary overloading or maintenance. + */ + OAuthErrorCode$1["TemporarilyUnavailable"] = "temporarily_unavailable"; + /** + * The authorization server does not support obtaining an authorization code using this method. + */ + OAuthErrorCode$1["UnsupportedResponseType"] = "unsupported_response_type"; + /** + * The authorization server does not support the requested token type. + */ + OAuthErrorCode$1["UnsupportedTokenType"] = "unsupported_token_type"; + /** + * The access token provided is expired, revoked, malformed, or invalid for other reasons. + */ + OAuthErrorCode$1["InvalidToken"] = "invalid_token"; + /** + * The HTTP method used is not allowed for this endpoint. (Custom, non-standard error) + */ + OAuthErrorCode$1["MethodNotAllowed"] = "method_not_allowed"; + /** + * Rate limit exceeded. (Custom, non-standard error based on RFC 6585) + */ + OAuthErrorCode$1["TooManyRequests"] = "too_many_requests"; + /** + * The client metadata is invalid. (Custom error for dynamic client registration - RFC 7591) + */ + OAuthErrorCode$1["InvalidClientMetadata"] = "invalid_client_metadata"; + /** + * The value of one or more redirection URIs is invalid. (Dynamic client registration - RFC 7591 §3.2.2) + */ + OAuthErrorCode$1["InvalidRedirectUri"] = "invalid_redirect_uri"; + /** + * The request requires higher privileges than provided by the access token. + */ + OAuthErrorCode$1["InsufficientScope"] = "insufficient_scope"; + /** + * The requested resource is invalid, missing, unknown, or malformed. (Custom error for resource indicators - RFC 8707) + */ + OAuthErrorCode$1["InvalidTarget"] = "invalid_target"; + return OAuthErrorCode$1; +}({}))); +/** +* OAuth error class for all OAuth-related errors. +*/ +var src_CX2iR2pK_OAuthError = class OAuthError extends Error { + static { + Object.defineProperty(this, "mcpBrand", { value: "mcp.OAuthError" }); + } + static [Symbol.hasInstance](value) { + return brandedHasInstance(this, value); + } + /** + * Brand-based type guard: equivalent to `value instanceof this`, as an + * explicit static predicate (the axios/AWS-SDK `isInstance` style). Reads + * the caller's own brand via `this`, so every branded subclass gets a + * correctly-scoped guard by inheritance. Must be invoked on the class — + * in callback position write `v => SdkError.isInstance(v)`, not + * `.filter(SdkError.isInstance)` (detached calls throw rather than + * silently matching nothing). + */ + static isInstance(value) { + 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 brandedHasInstance(this, value); + } + constructor(code, message, errorUri) { + super(message); + this.code = code; + this.errorUri = errorUri; + this.name = "OAuthError"; + stampErrorBrands(this, new.target); + } + /** + * Converts the error to a standard OAuth error response object. + */ + toResponseObject() { + const response = { + error: this.code, + error_description: this.message + }; + if (this.errorUri) response.error_uri = this.errorUri; + return response; + } + /** + * Creates an {@linkcode OAuthError} from an OAuth error response. + */ + static fromResponse(response) { + return new OAuthError(response.error, response.error_description ?? response.error, response.error_uri); + } +}; + +//#endregion +//#region ../core-internal/src/errors/sdkErrors.ts +/** +* Error codes for SDK errors (local errors that never cross the wire). +* Unlike {@linkcode ProtocolErrorCode} which uses numeric JSON-RPC codes, `SdkErrorCode` uses +* descriptive string values for better developer experience. +* +* These errors are thrown locally by the SDK and are never serialized as +* JSON-RPC error responses. +*/ +let src_CX2iR2pK_SdkErrorCode = /* @__PURE__ */ function(SdkErrorCode$1) { + /** Transport is not connected */ + SdkErrorCode$1["NotConnected"] = "NOT_CONNECTED"; + /** Transport is already connected */ + SdkErrorCode$1["AlreadyConnected"] = "ALREADY_CONNECTED"; + /** Protocol is not initialized */ + SdkErrorCode$1["NotInitialized"] = "NOT_INITIALIZED"; + /** Required capability is not supported by the remote side */ + SdkErrorCode$1["CapabilityNotSupported"] = "CAPABILITY_NOT_SUPPORTED"; + /** Request timed out waiting for response */ + SdkErrorCode$1["RequestTimeout"] = "REQUEST_TIMEOUT"; + /** Connection was closed */ + SdkErrorCode$1["ConnectionClosed"] = "CONNECTION_CLOSED"; + /** Failed to send message */ + SdkErrorCode$1["SendFailed"] = "SEND_FAILED"; + /** Response result failed local schema validation */ + SdkErrorCode$1["InvalidResult"] = "INVALID_RESULT"; + /** + * The response carried a `resultType` discriminator (protocol revision + * 2026-07-28) naming a result kind this client cannot consume yet, e.g. + * `input_required`. The kind is carried in `data.resultType`. + */ + SdkErrorCode$1["UnsupportedResultType"] = "UNSUPPORTED_RESULT_TYPE"; + /** + * The multi-round-trip auto-fulfilment driver exhausted its round cap + * (`inputRequired.maxRounds`) without the server returning a complete + * result. `data.rounds` carries the cap that was hit and + * `data.lastResult` carries the last `input_required` payload received + * (`{ inputRequests, requestState? }`), so callers can inspect or resume + * the flow manually. + */ + SdkErrorCode$1["InputRequiredRoundsExceeded"] = "INPUT_REQUIRED_ROUNDS_EXCEEDED"; + /** + * The auto-aggregating no-`cursor` `listTools()` / `listPrompts()` / + * `listResources()` / `listResourceTemplates()` walk hit the + * `ClientOptions.listMaxPages` cap without the server's pagination + * converging. `data.method` carries the list verb and + * `data.listMaxPages` the cap that was hit; raise the cap or fall back to + * explicit per-page `{ cursor }` calls. + */ + SdkErrorCode$1["ListPaginationExceeded"] = "LIST_PAGINATION_EXCEEDED"; + /** + * The spec method being sent does not exist on the negotiated protocol + * version's wire era (e.g. `tasks/get` toward a 2026-07-28 peer, or + * `server/discover` toward a 2025-era peer). Raised locally, before + * anything reaches the transport. The method and era are carried in + * `data.method` / `data.era`. + */ + SdkErrorCode$1["MethodNotSupportedByProtocolVersion"] = "METHOD_NOT_SUPPORTED_BY_PROTOCOL_VERSION"; + /** + * Protocol-era negotiation at connect time failed without producing either a + * usable modern (2026-07-28+) era or a definitive legacy fallback signal — + * e.g. the negotiation mode forbids falling back (`pin`), the probe hit a + * network failure, or the server answered the probe with a 5xx (a typed + * connect error, never an era verdict). + * + * Negotiation-phase only: this code is never used once an era is + * established. Auth walls never carry it: a 401/403 rejecting the probe + * uses {@linkcode ClientHttpAuthentication} / {@linkcode ClientHttpForbidden} + * instead, so era-recovery flows keyed on this code (e.g. cached-verdict + * gateways) can never persist a verdict for an unauthorized exchange. + */ + SdkErrorCode$1["EraNegotiationFailed"] = "ERA_NEGOTIATION_FAILED"; + SdkErrorCode$1["ClientHttpNotImplemented"] = "CLIENT_HTTP_NOT_IMPLEMENTED"; + /** + * HTTP 401 authentication failure: the transport's re-auth retry still got + * 401 (`Server returned 401 after re-authentication`), or the version + * negotiation probe was rejected 401 with no `authProvider` configured + * (`Version negotiation failed: the server requires authorization (HTTP 401)`). + * Carried on an {@linkcode SdkHttpError} with `status: 401`. + */ + SdkErrorCode$1["ClientHttpAuthentication"] = "CLIENT_HTTP_AUTHENTICATION"; + /** + * HTTP 403 denial: the step-up re-authorization retry limit was reached, + * or the version negotiation probe was rejected 403 + * (`Version negotiation failed: the server denied access (HTTP 403)`). + * Carried on an {@linkcode SdkHttpError} with `status: 403`. + */ + SdkErrorCode$1["ClientHttpForbidden"] = "CLIENT_HTTP_FORBIDDEN"; + SdkErrorCode$1["ClientHttpUnexpectedContent"] = "CLIENT_HTTP_UNEXPECTED_CONTENT"; + SdkErrorCode$1["ClientHttpFailedToOpenStream"] = "CLIENT_HTTP_FAILED_TO_OPEN_STREAM"; + SdkErrorCode$1["ClientHttpFailedToTerminateSession"] = "CLIENT_HTTP_FAILED_TO_TERMINATE_SESSION"; + return SdkErrorCode$1; +}({}); +/** +* SDK errors are local errors that never cross the wire. +* They are distinct from {@linkcode ProtocolError} which represents JSON-RPC protocol errors +* that are serialized and sent as error responses. +* +* @example +* ```ts source="./sdkErrors.examples.ts#SdkError_basicUsage" +* try { +* // Throwing an SDK error +* throw new SdkError(SdkErrorCode.NotConnected, 'Transport is not connected'); +* } catch (error) { +* // Checking error type by code +* if (error instanceof SdkError && error.code === SdkErrorCode.RequestTimeout) { +* // Handle timeout +* } +* } +* ``` +*/ +var src_CX2iR2pK_SdkError = class extends Error { + static { + Object.defineProperty(this, "mcpBrand", { value: "mcp.SdkError" }); + } + static [Symbol.hasInstance](value) { + return brandedHasInstance(this, value); + } + /** + * Brand-based type guard: equivalent to `value instanceof this`, as an + * explicit static predicate (the axios/AWS-SDK `isInstance` style). Reads + * the caller's own brand via `this`, so every branded subclass gets a + * correctly-scoped guard by inheritance. Must be invoked on the class — + * in callback position write `v => SdkError.isInstance(v)`, not + * `.filter(SdkError.isInstance)` (detached calls throw rather than + * silently matching nothing). + */ + static isInstance(value) { + 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 brandedHasInstance(this, value); + } + constructor(code, message, data) { + super(message); + this.code = code; + this.data = data; + this.name = "SdkError"; + stampErrorBrands(this, new.target); + } +}; +/** +* An {@linkcode SdkError} subclass for HTTP transport failures. +* +* Thrown by the streamable HTTP transport when the server responds with a +* non-OK status code. Narrows {@linkcode SdkError.data | data} to +* {@linkcode SdkHttpErrorData} so consumers can inspect the HTTP status +* without unsafe casting. +* +* @example +* ```ts source="./sdkErrors.examples.ts#SdkHttpError_basicUsage" +* if (error instanceof SdkHttpError) { +* console.log(error.status); // number +* console.log(error.statusText); // string | undefined +* } +* ``` +*/ +var SdkHttpError = class extends src_CX2iR2pK_SdkError { + static { + Object.defineProperty(this, "mcpBrand", { value: "mcp.SdkHttpError" }); + } + constructor(code, message, data) { + super(code, message, data); + this.name = "SdkHttpError"; + } + get status() { + return this.data.status; + } + get statusText() { + return this.data.statusText; + } +}; + +//#endregion +//#region ../core-internal/src/shared/authUtils.ts +/** +* Utilities for handling OAuth resource URIs. +*/ +/** +* Converts a server URL to a resource URL by removing the fragment. +* {@link https://datatracker.ietf.org/doc/html/rfc8707#section-2 | RFC 8707 section 2} +* states that resource URIs "MUST NOT include a fragment component". +* Keeps everything else unchanged (scheme, domain, port, path, query). +*/ +function resourceUrlFromServerUrl(url) { + const resourceURL = typeof url === "string" ? new URL(url) : new URL(url.href); + resourceURL.hash = ""; + return resourceURL; +} +/** +* Checks if a requested resource URL matches a configured resource URL. +* A requested resource matches if it has the same scheme, domain, port, +* and its path starts with the configured resource's path. +* +* @param options - The options object +* @param options.requestedResource - The resource URL being requested +* @param options.configuredResource - The resource URL that has been configured +* @returns true if the requested resource matches the configured resource, false otherwise +*/ +function checkResourceAllowed({ requestedResource, configuredResource }) { + const requested = typeof requestedResource === "string" ? new URL(requestedResource) : new URL(requestedResource.href); + const configured = typeof configuredResource === "string" ? new URL(configuredResource) : new URL(configuredResource.href); + if (requested.origin !== configured.origin) return false; + if (requested.pathname.length < configured.pathname.length) return false; + const requestedPath = requested.pathname.endsWith("/") ? requested.pathname : requested.pathname + "/"; + const configuredPath = configured.pathname.endsWith("/") ? configured.pathname : configured.pathname + "/"; + return requestedPath.startsWith(configuredPath); +} + +//#endregion +//#region ../core-internal/src/shared/clientCapabilityRequirements.ts +/** +* Inbound request methods whose processing structurally requires a client +* capability, keyed by method, valued by the capabilities required. +* +* Currently empty: none of the request methods served on the 2026-07-28 +* registry unconditionally requires a client capability. Entries appear here +* when such methods exist — for example requests whose handling embeds +* elicitation or sampling input requests (the input-request engine), or +* opt-in subscription delivery. Handler-conditional requirements (a specific +* tool that needs sampling) are not expressible as a static method table and +* are enforced at the point the requirement arises instead. +*/ +const REQUIRED_CLIENT_CAPABILITIES_BY_METHOD = (/* unused pure expression or super */ null && ({})); +/** +* The client capabilities a request method structurally requires, or +* `undefined` when the method has no static requirement. +*/ +function src_CX2iR2pK_requiredClientCapabilitiesForRequest(method) { + return Object.hasOwn(REQUIRED_CLIENT_CAPABILITIES_BY_METHOD, method) ? REQUIRED_CLIENT_CAPABILITIES_BY_METHOD[method] : void 0; +} +function isPlainObject$7(value) { + return value !== null && typeof value === "object" && !Array.isArray(value); +} +/** +* Whether a required nested member counts as declared even though it is not +* spelled out: a bare `elicitation: {}` declaration (no mode sub-capability at +* all) is read as form support — the pre-mode (2025) meaning of a bare +* declaration — so an `elicitation.form` requirement treats it as satisfied. +* Declaring any mode explicitly (for example `elicitation: { url: {} }`) +* removes the implication. +*/ +function isImpliedCapabilityMember(capability, member, declaredValue) { + return capability === "elicitation" && member === "form" && declaredValue["form"] === void 0 && declaredValue["url"] === void 0; +} +/** +* The client capabilities an embedded multi-round-trip input request requires +* (call site 2 — the outbound input-request leg): a server MUST NOT send an +* `inputRequests` kind the request's declared client capabilities do not +* cover. Returns `undefined` for entries whose method is not one of the +* embedded input-request kinds (those are a server bug handled separately, +* not a capability question). +* +* The requirement is mode-aware where the capability is: URL-mode elicitation +* requires `elicitation.url`; form-mode (or mode-omitted) elicitation requires +* `elicitation.form` (modes are sub-capabilities, and a server MUST NOT send a +* mode the client did not declare); sampling with `tools`/`toolChoice` +* requires `sampling.tools`. A bare `elicitation: {}` declaration satisfies +* the form requirement — see {@linkcode missingClientCapabilities}. +*/ +function requiredClientCapabilitiesForInputRequest(entry) { + switch (entry.method) { + case "elicitation/create": + if (entry.params?.["mode"] === "url") return { elicitation: { url: {} } }; + return { elicitation: { form: {} } }; + case "sampling/createMessage": { + const params = entry.params; + if (params !== void 0 && (params["tools"] !== void 0 || params["toolChoice"] !== void 0)) return { sampling: { tools: {} } }; + return { sampling: {} }; + } + case "roots/list": return { roots: {} }; + default: return; + } +} +/** +* Computes the subset of `required` client capabilities the client did not +* declare. Returns `undefined` when every required capability is declared; +* otherwise returns an object in the `ClientCapabilities` shape containing +* exactly the missing capabilities (suitable for +* `data.requiredCapabilities` on the `-32021` error). +* +* A capability counts as declared when its top-level key is present on the +* declared capabilities; when the requirement names nested members (for +* example `elicitation: { url: {} }`), each named member must also be present +* under the declared capability. One lenient reading applies: a bare +* `elicitation: {}` declaration (no mode sub-capability at all) counts as +* declaring `elicitation.form` — the pre-mode (2025) meaning of a bare +* declaration. An absent or empty `declared` value means +* nothing is declared — every required capability is missing (the structural +* clean-refusal posture for sessions with no per-request capability view). +*/ +function src_CX2iR2pK_missingClientCapabilities(required, declared) { + const missing = {}; + for (const [capability, requirement] of Object.entries(required)) { + if (requirement === void 0) continue; + const declaredValue = declared === void 0 ? void 0 : declared[capability]; + if (declaredValue === void 0) { + missing[capability] = requirement; + continue; + } + if (isPlainObject$7(requirement) && isPlainObject$7(declaredValue)) { + const missingMembers = {}; + for (const [member, memberRequirement] of Object.entries(requirement)) if (memberRequirement !== void 0 && declaredValue[member] === void 0 && !isImpliedCapabilityMember(capability, member, declaredValue)) missingMembers[member] = memberRequirement; + if (Object.keys(missingMembers).length > 0) missing[capability] = missingMembers; + } + } + return Object.keys(missing).length > 0 ? missing : void 0; +} + +//#endregion +//#region ../core-internal/src/shared/protocolEras.ts +/** +* The first protocol revision of the modern (2026-07-28) era. Revision identifiers +* are ISO dates, so lexicographic comparison orders them chronologically. +*/ +const FIRST_MODERN_PROTOCOL_VERSION = "2026-07-28"; +/** +* Modern-era protocol revisions this SDK can negotiate via `server/discover`. +* Deliberately separate from {@linkcode SUPPORTED_PROTOCOL_VERSIONS} (the legacy +* `initialize` list), so adding a revision here can never leak a modern version +* string into a 2025-era handshake. Internal — not part of the public API surface. +*/ +const src_CX2iR2pK_SUPPORTED_MODERN_PROTOCOL_VERSIONS = (/* unused pure expression or super */ null && ([FIRST_MODERN_PROTOCOL_VERSION])); +/** Whether the given protocol revision belongs to the modern (2026-07-28+) era. */ +function isModernProtocolVersion(version) { + return version >= FIRST_MODERN_PROTOCOL_VERSION; +} +/** The legacy-era (pre-2026-07-28) subset of a supported-versions list, in the list's own preference order. */ +function legacyProtocolVersions(versions) { + return versions.filter((version) => !isModernProtocolVersion(version)); +} +/** The modern-era (2026-07-28+) subset of a supported-versions list, in the list's own preference order. */ +function modernProtocolVersions(versions) { + return versions.filter((version) => isModernProtocolVersion(version)); +} + +//#endregion +//#region ../core-internal/src/wire/textFallback.ts +/** +* SEP-2106 §4.3 TextContent auto-append, era-agnostic, called from BOTH +* codecs' {@link WireCodec.projectCallToolResult}: when `structuredContent` +* is a non-object value (array/primitive/`null`) and the handler authored no +* `type:'text'` block, append `{type:'text', text: JSON.stringify(value)}`. +* Object-shaped (or absent) `structuredContent` returns the same reference. +* +* Leaf module: imported by both era codec modules, so it must NOT import from +* `./codec.js` (which value-imports the rev codecs at top level — that would +* make a runtime cycle and a TDZ hazard for entries that evaluate a rev codec +* module first). +*/ +function appendTextFallbackForNonObject(result) { + const sc = result.structuredContent; + if (sc === void 0) return result; + if (!(typeof sc !== "object" || sc === null || Array.isArray(sc))) return result; + if (result.content?.some((c) => c.type === "text") ?? false) return result; + return { + ...result, + content: [...result.content ?? [], { + type: "text", + text: JSON.stringify(sc) + }] + }; +} + +//#endregion +//#region ../core-internal/src/wire/resultFamilies.ts +/** +* Result-family keys that must never default into a `{content: []}` tools/call +* success. Shared by the 2025 wire-seam schema and server normalization. +* Leaf module (like `textFallback.ts`): imported by registry/server paths, so +* it must NOT import from `./codec.js` — that would close a runtime cycle. +*/ +const TOOL_RESULT_FOREIGN_FAMILY_KEYS = [ + "task", + "inputRequests", + "requestState" +]; +/** +* Single owner of the v1-parity ruling: a plain-object tool result without `content` (and +* without foreign-family keys) gains `content: []`. Shared by the 2025 wire seam and server-side handler normalization. +*/ +function normalizeContentlessToolResult(value) { + if (value === null || typeof value !== "object" || Array.isArray(value) || value.content !== void 0 || TOOL_RESULT_FOREIGN_FAMILY_KEYS.some((key) => key in value)) return value; + return { + ...value, + content: [] + }; +} + +//#endregion +//#region ../core-internal/src/wire/rev2025-11-25/buildSchemas.ts +/** +* Complete frozen 2025-11-25 wire schemas. Self-contained — no imports from +* the public/neutral types/schemas.ts. The neutral layer is the public-API +* superset and is free to evolve (e.g., SEP-2106 widening); this file is the +* 2025 wire-parse contract (Q10-L2 byte-identity) and is BEHAVIOR-FROZEN. +* +* This is the era's complete frozen wire-parse contract — both the 2025-only +* delta (the deprecated task family, the era role unions) AND frozen copies of +* every era-shared shape (Tool, CallToolResult, Initialize*, ContentBlock, +* prompts/resources/completion/elicitation, …). The 2026-era codec +* (`wire/rev2026-07-28/`) is symmetrically self-contained in the same way. +* +* The 2025-only delta (the task message surface, restored types-only by #2248 +* for interop with task-capable 2025 peers) is parsed ONLY through this era's +* registry; the deprecated Task* schemas also live (marked `@deprecated`) in +* the neutral schema layer so the public types stay nameable without a +* cross-layer import — nameability is constant, runtime availability is +* version-keyed — but appear in no API signature. Q1 increment 2 — deletions +* are physical: the +* 2026-era REGISTRY has no Task* methods (its frozen building-block copies do +* carry the deprecated Task* sub-schemas by composition — soft contamination, +* tracked for anchor-exactness adjudication). +* +* The only cross-layer dependency is `import type { JSONObject, JSONValue }` +* from the neutral types barrel — pure structural type aliases with no parse +* behavior. No runtime schema is shared with the neutral layer. +*/ +function build$1() { + const JSONValueSchema$1 = lazy(() => schemas_union([ + schemas_string(), + schemas_number(), + schemas_boolean(), + schemas_null(), + schemas_record(schemas_string(), JSONValueSchema$1), + schemas_array(JSONValueSchema$1) + ])); + const JSONObjectSchema$1 = schemas_record(schemas_string(), JSONValueSchema$1); + /** + * A progress token, used to associate progress notifications with the original request. + */ + const ProgressTokenSchema$1 = schemas_union([schemas_string(), schemas_number().int()]); + /** + * An opaque token used to represent a cursor for pagination. + */ + const CursorSchema$1 = schemas_string(); + /** @deprecated 2025-11-25 wire vocabulary with no SDK runtime; kept importable for interoperability only. */ + const TaskMetadataSchema$1 = schemas_object({ ttl: schemas_number().optional() }); + /** + * Metadata for associating messages with a task. + * Include this in the `_meta` field under the key `io.modelcontextprotocol/related-task`. + * + * @deprecated 2025-11-25 wire vocabulary with no SDK runtime; kept importable for interoperability only. + */ + const RelatedTaskMetadataSchema$1 = schemas_object({ taskId: schemas_string() }); + const RequestMetaSchema$1 = looseObject({ + progressToken: ProgressTokenSchema$1.optional(), + "io.modelcontextprotocol/related-task": RelatedTaskMetadataSchema$1.optional() + }); + /** + * Common params for any request. + */ + const BaseRequestParamsSchema$1 = schemas_object({ _meta: RequestMetaSchema$1.optional() }); + /** + * Common params for any task-augmented request. + * + * @deprecated 2025-11-25 wire vocabulary with no SDK runtime; kept importable for interoperability only. + */ + const TaskAugmentedRequestParamsSchema$1 = BaseRequestParamsSchema$1.extend({ task: TaskMetadataSchema$1.optional() }); + const RequestSchema$1 = schemas_object({ + method: schemas_string(), + params: BaseRequestParamsSchema$1.loose().optional() + }); + const NotificationsParamsSchema$1 = schemas_object({ _meta: RequestMetaSchema$1.optional() }); + const NotificationSchema$1 = schemas_object({ + method: schemas_string(), + params: NotificationsParamsSchema$1.loose().optional() + }); + const ResultSchema$1 = looseObject({ _meta: RequestMetaSchema$1.optional() }); + /** + * A uniquely identifying ID for a request in JSON-RPC. + */ + const RequestIdSchema$1 = schemas_union([schemas_string(), schemas_number().int()]); + /** + * A response that indicates success but carries no data. + */ + const EmptyResultSchema$1 = ResultSchema$1.strict(); + const CancelledNotificationParamsSchema$1 = NotificationsParamsSchema$1.extend({ + requestId: RequestIdSchema$1.optional(), + reason: schemas_string().optional() + }); + /** + * This notification can be sent by either side to indicate that it is cancelling a previously-issued request. + * + * The request SHOULD still be in-flight, but due to communication latency, it is always possible that this notification MAY arrive after the request has already finished. + * + * This notification indicates that the result will be unused, so any associated processing SHOULD cease. + * + * A client MUST NOT attempt to cancel its {@linkcode InitializeRequest | initialize} request. + */ + const CancelledNotificationSchema$1 = NotificationSchema$1.extend({ + method: literal("notifications/cancelled"), + params: CancelledNotificationParamsSchema$1 + }); + /** + * Icon schema for use in {@link Tool | tools}, {@link Prompt | prompts}, {@link Resource | resources}, and {@link Implementation | implementations}. + */ + const IconSchema$1 = schemas_object({ + src: schemas_string(), + mimeType: schemas_string().optional(), + sizes: schemas_array(schemas_string()).optional(), + theme: schemas_enum(["light", "dark"]).optional() + }); + /** + * Base schema to add `icons` property. + * + */ + const IconsSchema$1 = schemas_object({ icons: schemas_array(IconSchema$1).optional() }); + /** + * Base metadata interface for common properties across {@link Resource | resources}, {@link Tool | tools}, {@link Prompt | prompts}, and {@link Implementation | implementations}. + */ + const BaseMetadataSchema$1 = schemas_object({ + name: schemas_string(), + title: schemas_string().optional() + }); + /** + * Describes the name and version of an MCP implementation. + */ + const ImplementationSchema$1 = BaseMetadataSchema$1.extend({ + ...BaseMetadataSchema$1.shape, + ...IconsSchema$1.shape, + version: schemas_string(), + websiteUrl: schemas_string().optional(), + description: schemas_string().optional() + }); + const FormElicitationCapabilitySchema = intersection(schemas_object({ applyDefaults: schemas_boolean().optional() }), JSONObjectSchema$1); + const ElicitationCapabilitySchema = preprocess((value) => { + if (value && typeof value === "object" && !Array.isArray(value) && Object.keys(value).length === 0) return { form: {} }; + return value; + }, intersection(schemas_object({ + form: FormElicitationCapabilitySchema.optional(), + url: JSONObjectSchema$1.optional() + }), JSONObjectSchema$1.optional())); + /** + * Task capabilities for clients, indicating which request types support task creation. + * + * @deprecated 2025-11-25 wire vocabulary with no SDK runtime; kept importable for interoperability only. + */ + const ClientTasksCapabilitySchema$1 = looseObject({ + list: JSONObjectSchema$1.optional(), + cancel: JSONObjectSchema$1.optional(), + requests: looseObject({ + sampling: looseObject({ createMessage: JSONObjectSchema$1.optional() }).optional(), + elicitation: looseObject({ create: JSONObjectSchema$1.optional() }).optional() + }).optional() + }); + /** + * Task capabilities for servers, indicating which request types support task creation. + * + * @deprecated 2025-11-25 wire vocabulary with no SDK runtime; kept importable for interoperability only. + */ + const ServerTasksCapabilitySchema$1 = looseObject({ + list: JSONObjectSchema$1.optional(), + cancel: JSONObjectSchema$1.optional(), + requests: looseObject({ tools: looseObject({ call: JSONObjectSchema$1.optional() }).optional() }).optional() + }); + /** + * Capabilities a client may support. Known capabilities are defined here, in this schema, but this is not a closed set: any client can define its own, additional capabilities. + */ + const ClientCapabilitiesSchema$1 = schemas_object({ + experimental: schemas_record(schemas_string(), JSONObjectSchema$1).optional(), + sampling: schemas_object({ + context: JSONObjectSchema$1.optional(), + tools: JSONObjectSchema$1.optional() + }).optional(), + elicitation: ElicitationCapabilitySchema.optional(), + roots: schemas_object({ listChanged: schemas_boolean().optional() }).optional(), + tasks: ClientTasksCapabilitySchema$1.optional(), + extensions: schemas_record(schemas_string(), JSONObjectSchema$1).optional() + }); + const InitializeRequestParamsSchema$1 = BaseRequestParamsSchema$1.extend({ + protocolVersion: schemas_string(), + capabilities: ClientCapabilitiesSchema$1, + clientInfo: ImplementationSchema$1 + }); + /** + * This request is sent from the client to the server when it first connects, asking it to begin initialization. + */ + const InitializeRequestSchema$1 = RequestSchema$1.extend({ + method: literal("initialize"), + params: InitializeRequestParamsSchema$1 + }); + /** + * Capabilities that a server may support. Known capabilities are defined here, in this schema, but this is not a closed set: any server can define its own, additional capabilities. + */ + const ServerCapabilitiesSchema$1 = schemas_object({ + experimental: schemas_record(schemas_string(), JSONObjectSchema$1).optional(), + logging: JSONObjectSchema$1.optional(), + completions: JSONObjectSchema$1.optional(), + prompts: schemas_object({ listChanged: schemas_boolean().optional() }).optional(), + resources: schemas_object({ + subscribe: schemas_boolean().optional(), + listChanged: schemas_boolean().optional() + }).optional(), + tools: schemas_object({ listChanged: schemas_boolean().optional() }).optional(), + tasks: ServerTasksCapabilitySchema$1.optional(), + extensions: schemas_record(schemas_string(), JSONObjectSchema$1).optional() + }); + /** + * After receiving an initialize request from the client, the server sends this response. + */ + const InitializeResultSchema$1 = ResultSchema$1.extend({ + protocolVersion: schemas_string(), + capabilities: ServerCapabilitiesSchema$1, + serverInfo: ImplementationSchema$1, + instructions: schemas_string().optional() + }); + /** + * This notification is sent from the client to the server after initialization has finished. + */ + const InitializedNotificationSchema$1 = NotificationSchema$1.extend({ + method: literal("notifications/initialized"), + params: NotificationsParamsSchema$1.optional() + }); + /** + * A ping, issued by either the server or the client, to check that the other party is still alive. The receiver must promptly respond, or else may be disconnected. + */ + const PingRequestSchema$1 = RequestSchema$1.extend({ + method: literal("ping"), + params: BaseRequestParamsSchema$1.optional() + }); + const ProgressSchema$1 = schemas_object({ + progress: schemas_number(), + total: schemas_optional(schemas_number()), + message: schemas_optional(schemas_string()) + }); + const ProgressNotificationParamsSchema$1 = schemas_object({ + ...NotificationsParamsSchema$1.shape, + ...ProgressSchema$1.shape, + progressToken: ProgressTokenSchema$1 + }); + /** + * An out-of-band notification used to inform the receiver of a progress update for a long-running request. + * + * @category notifications/progress + */ + const ProgressNotificationSchema$1 = NotificationSchema$1.extend({ + method: literal("notifications/progress"), + params: ProgressNotificationParamsSchema$1 + }); + const PaginatedRequestParamsSchema$1 = BaseRequestParamsSchema$1.extend({ cursor: CursorSchema$1.optional() }); + const PaginatedRequestSchema$1 = RequestSchema$1.extend({ params: PaginatedRequestParamsSchema$1.optional() }); + const PaginatedResultSchema$1 = ResultSchema$1.extend({ nextCursor: CursorSchema$1.optional() }); + /** + * The contents of a specific resource or sub-resource. + */ + const ResourceContentsSchema$1 = schemas_object({ + uri: schemas_string(), + mimeType: schemas_optional(schemas_string()), + _meta: schemas_record(schemas_string(), unknown()).optional() + }); + const TextResourceContentsSchema$1 = ResourceContentsSchema$1.extend({ text: schemas_string() }); + /** + * A Zod schema for validating Base64 strings that is more performant and + * robust for very large inputs than the default regex-based check. It avoids + * stack overflows by using the native `atob` function for validation. + */ + const Base64Schema = schemas_string().refine((val) => { + try { + atob(val); + return true; + } catch { + return false; + } + }, { message: "Invalid Base64 string" }); + const BlobResourceContentsSchema$1 = ResourceContentsSchema$1.extend({ blob: Base64Schema }); + /** + * The sender or recipient of messages and data in a conversation. + */ + const RoleSchema$1 = schemas_enum(["user", "assistant"]); + /** + * Optional annotations providing clients additional context about a resource. + */ + const AnnotationsSchema$1 = schemas_object({ + audience: schemas_array(RoleSchema$1).optional(), + priority: schemas_number().min(0).max(1).optional(), + lastModified: iso_datetime({ offset: true }).optional() + }); + /** + * A known resource that the server is capable of reading. + */ + const ResourceSchema$1 = schemas_object({ + ...BaseMetadataSchema$1.shape, + ...IconsSchema$1.shape, + uri: schemas_string(), + description: schemas_optional(schemas_string()), + mimeType: schemas_optional(schemas_string()), + size: schemas_optional(schemas_number()), + annotations: AnnotationsSchema$1.optional(), + _meta: schemas_optional(looseObject({})) + }); + /** + * A template description for resources available on the server. + */ + const ResourceTemplateSchema$1 = schemas_object({ + ...BaseMetadataSchema$1.shape, + ...IconsSchema$1.shape, + uriTemplate: schemas_string(), + description: schemas_optional(schemas_string()), + mimeType: schemas_optional(schemas_string()), + annotations: AnnotationsSchema$1.optional(), + _meta: schemas_optional(looseObject({})) + }); + /** + * Sent from the client to request a list of resources the server has. + */ + const ListResourcesRequestSchema$1 = PaginatedRequestSchema$1.extend({ method: literal("resources/list") }); + /** + * The server's response to a {@linkcode ListResourcesRequest | resources/list} request from the client. + */ + const ListResourcesResultSchema$1 = PaginatedResultSchema$1.extend({ resources: schemas_array(ResourceSchema$1) }); + /** + * Sent from the client to request a list of resource templates the server has. + */ + const ListResourceTemplatesRequestSchema$1 = PaginatedRequestSchema$1.extend({ method: literal("resources/templates/list") }); + /** + * The server's response to a {@linkcode ListResourceTemplatesRequest | resources/templates/list} request from the client. + */ + const ListResourceTemplatesResultSchema$1 = PaginatedResultSchema$1.extend({ resourceTemplates: schemas_array(ResourceTemplateSchema$1) }); + const ResourceRequestParamsSchema$1 = BaseRequestParamsSchema$1.extend({ uri: schemas_string() }); + /** + * Parameters for a {@linkcode ReadResourceRequest | resources/read} request. + */ + const ReadResourceRequestParamsSchema$1 = ResourceRequestParamsSchema$1; + /** + * Sent from the client to the server, to read a specific resource URI. + */ + const ReadResourceRequestSchema$1 = RequestSchema$1.extend({ + method: literal("resources/read"), + params: ReadResourceRequestParamsSchema$1 + }); + /** + * The server's response to a {@linkcode ReadResourceRequest | resources/read} request from the client. + */ + const ReadResourceResultSchema$1 = ResultSchema$1.extend({ contents: schemas_array(schemas_union([TextResourceContentsSchema$1, BlobResourceContentsSchema$1])) }); + /** + * An optional notification from the server to the client, informing it that the list of resources it can read from has changed. This may be issued by servers without any previous subscription from the client. + */ + const ResourceListChangedNotificationSchema$1 = NotificationSchema$1.extend({ + method: literal("notifications/resources/list_changed"), + params: NotificationsParamsSchema$1.optional() + }); + const SubscribeRequestParamsSchema$1 = ResourceRequestParamsSchema$1; + /** + * Sent from the client to request `resources/updated` notifications from the server whenever a particular resource changes. + */ + const SubscribeRequestSchema$1 = RequestSchema$1.extend({ + method: literal("resources/subscribe"), + params: SubscribeRequestParamsSchema$1 + }); + const UnsubscribeRequestParamsSchema$1 = ResourceRequestParamsSchema$1; + /** + * Sent from the client to request cancellation of {@linkcode ResourceUpdatedNotification | resources/updated} notifications from the server. This should follow a previous {@linkcode SubscribeRequest | resources/subscribe} request. + */ + const UnsubscribeRequestSchema$1 = RequestSchema$1.extend({ + method: literal("resources/unsubscribe"), + params: UnsubscribeRequestParamsSchema$1 + }); + /** + * Parameters for a {@linkcode ResourceUpdatedNotification | notifications/resources/updated} notification. + */ + const ResourceUpdatedNotificationParamsSchema$1 = NotificationsParamsSchema$1.extend({ uri: schemas_string() }); + /** + * A notification from the server to the client, informing it that a resource has changed and may need to be read again. This should only be sent if the client previously sent a {@linkcode SubscribeRequest | resources/subscribe} request. + */ + const ResourceUpdatedNotificationSchema$1 = NotificationSchema$1.extend({ + method: literal("notifications/resources/updated"), + params: ResourceUpdatedNotificationParamsSchema$1 + }); + /** + * Describes an argument that a prompt can accept. + */ + const PromptArgumentSchema$1 = schemas_object({ + name: schemas_string(), + description: schemas_optional(schemas_string()), + required: schemas_optional(schemas_boolean()) + }); + /** + * A prompt or prompt template that the server offers. + */ + const PromptSchema$1 = schemas_object({ + ...BaseMetadataSchema$1.shape, + ...IconsSchema$1.shape, + description: schemas_optional(schemas_string()), + arguments: schemas_optional(schemas_array(PromptArgumentSchema$1)), + _meta: schemas_optional(looseObject({})) + }); + /** + * Sent from the client to request a list of prompts and prompt templates the server has. + */ + const ListPromptsRequestSchema$1 = PaginatedRequestSchema$1.extend({ method: literal("prompts/list") }); + /** + * The server's response to a {@linkcode ListPromptsRequest | prompts/list} request from the client. + */ + const ListPromptsResultSchema$1 = PaginatedResultSchema$1.extend({ prompts: schemas_array(PromptSchema$1) }); + /** + * Parameters for a {@linkcode GetPromptRequest | prompts/get} request. + */ + const GetPromptRequestParamsSchema$1 = BaseRequestParamsSchema$1.extend({ + name: schemas_string(), + arguments: schemas_record(schemas_string(), schemas_string()).optional() + }); + /** + * Used by the client to get a prompt provided by the server. + */ + const GetPromptRequestSchema$1 = RequestSchema$1.extend({ + method: literal("prompts/get"), + params: GetPromptRequestParamsSchema$1 + }); + /** + * Text provided to or from an LLM. + */ + const TextContentSchema$1 = schemas_object({ + type: literal("text"), + text: schemas_string(), + annotations: AnnotationsSchema$1.optional(), + _meta: schemas_record(schemas_string(), unknown()).optional() + }); + /** + * An image provided to or from an LLM. + */ + const ImageContentSchema$1 = schemas_object({ + type: literal("image"), + data: Base64Schema, + mimeType: schemas_string(), + annotations: AnnotationsSchema$1.optional(), + _meta: schemas_record(schemas_string(), unknown()).optional() + }); + /** + * Audio content provided to or from an LLM. + */ + const AudioContentSchema$1 = schemas_object({ + type: literal("audio"), + data: Base64Schema, + mimeType: schemas_string(), + annotations: AnnotationsSchema$1.optional(), + _meta: schemas_record(schemas_string(), unknown()).optional() + }); + /** + * A tool call request from an assistant (LLM). + * Represents the assistant's request to use a tool. + * + * @deprecated Deprecated as of protocol version 2026-07-28 (SEP-2577); remains + * in the specification for at least twelve months. Migrate to calling LLM + * provider APIs directly. + */ + const ToolUseContentSchema$1 = schemas_object({ + type: literal("tool_use"), + name: schemas_string(), + id: schemas_string(), + input: schemas_record(schemas_string(), unknown()), + _meta: schemas_record(schemas_string(), unknown()).optional() + }); + /** + * The contents of a resource, embedded into a prompt or tool call result. + */ + const EmbeddedResourceSchema$1 = schemas_object({ + type: literal("resource"), + resource: schemas_union([TextResourceContentsSchema$1, BlobResourceContentsSchema$1]), + annotations: AnnotationsSchema$1.optional(), + _meta: schemas_record(schemas_string(), unknown()).optional() + }); + /** + * A resource that the server is capable of reading, included in a prompt or tool call result. + * + * Note: resource links returned by tools are not guaranteed to appear in the results of {@linkcode ListResourcesRequest | resources/list} requests. + */ + const ResourceLinkSchema$1 = ResourceSchema$1.extend({ type: literal("resource_link") }); + /** + * A content block that can be used in prompts and tool results. + */ + const ContentBlockSchema$1 = schemas_union([ + TextContentSchema$1, + ImageContentSchema$1, + AudioContentSchema$1, + ResourceLinkSchema$1, + EmbeddedResourceSchema$1 + ]); + /** + * Describes a message returned as part of a prompt. + */ + const PromptMessageSchema$1 = schemas_object({ + role: RoleSchema$1, + content: ContentBlockSchema$1 + }); + /** + * The server's response to a {@linkcode GetPromptRequest | prompts/get} request from the client. + */ + const GetPromptResultSchema$1 = ResultSchema$1.extend({ + description: schemas_string().optional(), + messages: schemas_array(PromptMessageSchema$1) + }); + /** + * An optional notification from the server to the client, informing it that the list of prompts it offers has changed. This may be issued by servers without any previous subscription from the client. + */ + const PromptListChangedNotificationSchema$1 = NotificationSchema$1.extend({ + method: literal("notifications/prompts/list_changed"), + params: NotificationsParamsSchema$1.optional() + }); + /** + * Additional properties describing a `Tool` to clients. + * + * NOTE: all properties in {@linkcode ToolAnnotations} are **hints**. + * They are not guaranteed to provide a faithful description of + * tool behavior (including descriptive properties like `title`). + * + * Clients should never make tool use decisions based on `ToolAnnotations` + * received from untrusted servers. + */ + const ToolAnnotationsSchema$1 = schemas_object({ + title: schemas_string().optional(), + readOnlyHint: schemas_boolean().optional(), + destructiveHint: schemas_boolean().optional(), + idempotentHint: schemas_boolean().optional(), + openWorldHint: schemas_boolean().optional() + }); + /** + * Execution-related properties for a tool. + */ + const ToolExecutionSchema$1 = schemas_object({ taskSupport: schemas_enum([ + "required", + "optional", + "forbidden" + ]).optional() }); + /** + * Definition for a tool the client can call. + */ + const ToolSchema$1 = schemas_object({ + ...BaseMetadataSchema$1.shape, + ...IconsSchema$1.shape, + description: schemas_string().optional(), + inputSchema: schemas_object({ + type: literal("object"), + properties: schemas_record(schemas_string(), JSONValueSchema$1).optional(), + required: schemas_array(schemas_string()).optional() + }).catchall(unknown()), + outputSchema: schemas_object({ + type: literal("object"), + properties: schemas_record(schemas_string(), JSONValueSchema$1).optional(), + required: schemas_array(schemas_string()).optional() + }).catchall(unknown()).optional(), + annotations: ToolAnnotationsSchema$1.optional(), + execution: ToolExecutionSchema$1.optional(), + _meta: schemas_record(schemas_string(), unknown()).optional() + }); + /** + * Sent from the client to request a list of tools the server has. + */ + const ListToolsRequestSchema$1 = PaginatedRequestSchema$1.extend({ method: literal("tools/list") }); + /** + * The server's response to a {@linkcode ListToolsRequest | tools/list} request from the client. + */ + const ListToolsResultSchema$1 = PaginatedResultSchema$1.extend({ tools: schemas_array(ToolSchema$1) }); + /** + * The server's response to a tool call. + */ + const CallToolResultSchema$1 = ResultSchema$1.extend({ + content: schemas_array(ContentBlockSchema$1), + structuredContent: schemas_record(schemas_string(), unknown()).optional(), + isError: schemas_boolean().optional() + }); + /** + * Parameters for a `tools/call` request. + */ + const CallToolRequestParamsSchema$1 = TaskAugmentedRequestParamsSchema$1.extend({ + name: schemas_string(), + arguments: schemas_record(schemas_string(), unknown()).optional() + }); + /** + * Used by the client to invoke a tool provided by the server. + */ + const CallToolRequestSchema$1 = RequestSchema$1.extend({ + method: literal("tools/call"), + params: CallToolRequestParamsSchema$1 + }); + /** + * An optional notification from the server to the client, informing it that the list of tools it offers has changed. This may be issued by servers without any previous subscription from the client. + */ + const ToolListChangedNotificationSchema$1 = NotificationSchema$1.extend({ + method: literal("notifications/tools/list_changed"), + params: NotificationsParamsSchema$1.optional() + }); + /** + * The severity of a log message. + * + * @deprecated Deprecated as of protocol version 2026-07-28 (SEP-2577); remains + * in the specification for at least twelve months. Migrate to stderr logging + * (STDIO servers) or OpenTelemetry. + */ + const LoggingLevelSchema$1 = schemas_enum([ + "debug", + "info", + "notice", + "warning", + "error", + "critical", + "alert", + "emergency" + ]); + /** + * Parameters for a `logging/setLevel` request. + * + * @deprecated Deprecated as of protocol version 2026-07-28 (SEP-2577); remains + * in the specification for at least twelve months. Migrate to stderr logging + * (STDIO servers) or OpenTelemetry. + */ + const SetLevelRequestParamsSchema$1 = BaseRequestParamsSchema$1.extend({ level: LoggingLevelSchema$1 }); + /** + * A request from the client to the server, to enable or adjust logging. + * + * @deprecated Deprecated as of protocol version 2026-07-28 (SEP-2577); remains + * in the specification for at least twelve months. Migrate to stderr logging + * (STDIO servers) or OpenTelemetry. + */ + const SetLevelRequestSchema$1 = RequestSchema$1.extend({ + method: literal("logging/setLevel"), + params: SetLevelRequestParamsSchema$1 + }); + /** + * Parameters for a `notifications/message` notification. + * + * @deprecated Deprecated as of protocol version 2026-07-28 (SEP-2577); remains + * in the specification for at least twelve months. Migrate to stderr logging + * (STDIO servers) or OpenTelemetry. + */ + const LoggingMessageNotificationParamsSchema$1 = NotificationsParamsSchema$1.extend({ + level: LoggingLevelSchema$1, + logger: schemas_string().optional(), + data: unknown() + }); + /** + * Notification of a log message passed from server to client. If no `logging/setLevel` request has been sent from the client, the server MAY decide which messages to send automatically. + * + * @deprecated Deprecated as of protocol version 2026-07-28 (SEP-2577); remains + * in the specification for at least twelve months. Migrate to stderr logging + * (STDIO servers) or OpenTelemetry. + */ + const LoggingMessageNotificationSchema$1 = NotificationSchema$1.extend({ + method: literal("notifications/message"), + params: LoggingMessageNotificationParamsSchema$1 + }); + /** + * Hints to use for model selection. + * + * @deprecated Deprecated as of protocol version 2026-07-28 (SEP-2577); remains + * in the specification for at least twelve months. Migrate to calling LLM + * provider APIs directly. + */ + const ModelHintSchema$1 = schemas_object({ name: schemas_string().optional() }); + /** + * The server's preferences for model selection, requested of the client during sampling. + * + * @deprecated Deprecated as of protocol version 2026-07-28 (SEP-2577); remains + * in the specification for at least twelve months. Migrate to calling LLM + * provider APIs directly. + */ + const ModelPreferencesSchema$1 = schemas_object({ + hints: schemas_array(ModelHintSchema$1).optional(), + costPriority: schemas_number().min(0).max(1).optional(), + speedPriority: schemas_number().min(0).max(1).optional(), + intelligencePriority: schemas_number().min(0).max(1).optional() + }); + /** + * Controls tool usage behavior in sampling requests. + * + * @deprecated Deprecated as of protocol version 2026-07-28 (SEP-2577); remains + * in the specification for at least twelve months. Migrate to calling LLM + * provider APIs directly. + */ + const ToolChoiceSchema$1 = schemas_object({ mode: schemas_enum([ + "auto", + "required", + "none" + ]).optional() }); + /** + * The result of a tool execution, provided by the user (server). + * Represents the outcome of invoking a tool requested via `ToolUseContent`. + * + * @deprecated Deprecated as of protocol version 2026-07-28 (SEP-2577); remains + * in the specification for at least twelve months. Migrate to calling LLM + * provider APIs directly. + */ + const ToolResultContentSchema$1 = schemas_object({ + type: literal("tool_result"), + toolUseId: schemas_string().describe("The unique identifier for the corresponding tool call."), + content: schemas_array(ContentBlockSchema$1), + structuredContent: schemas_object({}).loose().optional(), + isError: schemas_boolean().optional(), + _meta: schemas_record(schemas_string(), unknown()).optional() + }); + /** + * Basic content types for sampling responses (without tool use). + * Used for backwards-compatible {@linkcode CreateMessageResult} when tools are not used. + * + * @deprecated Deprecated as of protocol version 2026-07-28 (SEP-2577); remains + * in the specification for at least twelve months. Migrate to calling LLM + * provider APIs directly. + */ + const SamplingContentSchema$1 = discriminatedUnion("type", [ + TextContentSchema$1, + ImageContentSchema$1, + AudioContentSchema$1 + ]); + /** + * Content block types allowed in sampling messages. + * This includes text, image, audio, tool use requests, and tool results. + * + * @deprecated Deprecated as of protocol version 2026-07-28 (SEP-2577); remains + * in the specification for at least twelve months. Migrate to calling LLM + * provider APIs directly. + */ + const SamplingMessageContentBlockSchema$1 = discriminatedUnion("type", [ + TextContentSchema$1, + ImageContentSchema$1, + AudioContentSchema$1, + ToolUseContentSchema$1, + ToolResultContentSchema$1 + ]); + /** + * Describes a message issued to or received from an LLM API. + * + * @deprecated Deprecated as of protocol version 2026-07-28 (SEP-2577); remains + * in the specification for at least twelve months. Migrate to calling LLM + * provider APIs directly. + */ + const SamplingMessageSchema$1 = schemas_object({ + role: RoleSchema$1, + content: schemas_union([SamplingMessageContentBlockSchema$1, schemas_array(SamplingMessageContentBlockSchema$1)]), + _meta: schemas_record(schemas_string(), unknown()).optional() + }); + /** + * Parameters for a `sampling/createMessage` request. + * + * @deprecated Deprecated as of protocol version 2026-07-28 (SEP-2577); remains + * in the specification for at least twelve months. Migrate to calling LLM + * provider APIs directly. + */ + const CreateMessageRequestParamsSchema$1 = TaskAugmentedRequestParamsSchema$1.extend({ + messages: schemas_array(SamplingMessageSchema$1), + modelPreferences: ModelPreferencesSchema$1.optional(), + systemPrompt: schemas_string().optional(), + includeContext: schemas_enum([ + "none", + "thisServer", + "allServers" + ]).optional(), + temperature: schemas_number().optional(), + maxTokens: schemas_number().int(), + stopSequences: schemas_array(schemas_string()).optional(), + metadata: JSONObjectSchema$1.optional(), + tools: schemas_array(ToolSchema$1).optional(), + toolChoice: ToolChoiceSchema$1.optional() + }); + /** + * A request from the server to sample an LLM via the client. The client has full discretion over which model to select. The client should also inform the user before beginning sampling, to allow them to inspect the request (human in the loop) and decide whether to approve it. + * + * @deprecated Deprecated as of protocol version 2026-07-28 (SEP-2577); remains + * in the specification for at least twelve months. Migrate to calling LLM + * provider APIs directly. + */ + const CreateMessageRequestSchema$1 = RequestSchema$1.extend({ + method: literal("sampling/createMessage"), + params: CreateMessageRequestParamsSchema$1 + }); + /** + * The client's response to a `sampling/create_message` request from the server. + * This is the backwards-compatible version that returns single content (no arrays). + * Used when the request does not include tools. + * + * @deprecated Deprecated as of protocol version 2026-07-28 (SEP-2577); remains + * in the specification for at least twelve months. Migrate to calling LLM + * provider APIs directly. + */ + const CreateMessageResultSchema$1 = ResultSchema$1.extend({ + model: schemas_string(), + stopReason: schemas_optional(schemas_enum([ + "endTurn", + "stopSequence", + "maxTokens" + ]).or(schemas_string())), + role: RoleSchema$1, + content: SamplingContentSchema$1 + }); + /** + * The client's response to a `sampling/create_message` request when tools were provided. + * This version supports array content for tool use flows. + * + * @deprecated Deprecated as of protocol version 2026-07-28 (SEP-2577); remains + * in the specification for at least twelve months. Migrate to calling LLM + * provider APIs directly. + */ + const CreateMessageResultWithToolsSchema$1 = ResultSchema$1.extend({ + model: schemas_string(), + stopReason: schemas_optional(schemas_enum([ + "endTurn", + "stopSequence", + "maxTokens", + "toolUse" + ]).or(schemas_string())), + role: RoleSchema$1, + content: schemas_union([SamplingMessageContentBlockSchema$1, schemas_array(SamplingMessageContentBlockSchema$1)]) + }); + /** + * Primitive schema definition for boolean fields. + */ + const BooleanSchemaSchema$1 = schemas_object({ + type: literal("boolean"), + title: schemas_string().optional(), + description: schemas_string().optional(), + default: schemas_boolean().optional() + }); + /** + * Primitive schema definition for string fields. + */ + const StringSchemaSchema$1 = schemas_object({ + type: literal("string"), + title: schemas_string().optional(), + description: schemas_string().optional(), + minLength: schemas_number().optional(), + maxLength: schemas_number().optional(), + format: schemas_enum([ + "email", + "uri", + "date", + "date-time" + ]).optional(), + default: schemas_string().optional() + }); + /** + * Primitive schema definition for number fields. + */ + const NumberSchemaSchema$1 = schemas_object({ + type: schemas_enum(["number", "integer"]), + title: schemas_string().optional(), + description: schemas_string().optional(), + minimum: schemas_number().optional(), + maximum: schemas_number().optional(), + default: schemas_number().optional() + }); + /** + * Schema for single-selection enumeration without display titles for options. + */ + const UntitledSingleSelectEnumSchemaSchema$1 = schemas_object({ + type: literal("string"), + title: schemas_string().optional(), + description: schemas_string().optional(), + enum: schemas_array(schemas_string()), + default: schemas_string().optional() + }); + /** + * Schema for single-selection enumeration with display titles for each option. + */ + const TitledSingleSelectEnumSchemaSchema$1 = schemas_object({ + type: literal("string"), + title: schemas_string().optional(), + description: schemas_string().optional(), + oneOf: schemas_array(schemas_object({ + const: schemas_string(), + title: schemas_string() + })), + default: schemas_string().optional() + }); + /** + * Use {@linkcode TitledSingleSelectEnumSchema} instead. + * This interface will be removed in a future version. + */ + const LegacyTitledEnumSchemaSchema$1 = schemas_object({ + type: literal("string"), + title: schemas_string().optional(), + description: schemas_string().optional(), + enum: schemas_array(schemas_string()), + enumNames: schemas_array(schemas_string()).optional(), + default: schemas_string().optional() + }); + const SingleSelectEnumSchemaSchema$1 = schemas_union([UntitledSingleSelectEnumSchemaSchema$1, TitledSingleSelectEnumSchemaSchema$1]); + /** + * Schema for multiple-selection enumeration without display titles for options. + */ + const UntitledMultiSelectEnumSchemaSchema$1 = schemas_object({ + type: literal("array"), + title: schemas_string().optional(), + description: schemas_string().optional(), + minItems: schemas_number().optional(), + maxItems: schemas_number().optional(), + items: schemas_object({ + type: literal("string"), + enum: schemas_array(schemas_string()) + }), + default: schemas_array(schemas_string()).optional() + }); + /** + * Schema for multiple-selection enumeration with display titles for each option. + */ + const TitledMultiSelectEnumSchemaSchema$1 = schemas_object({ + type: literal("array"), + title: schemas_string().optional(), + description: schemas_string().optional(), + minItems: schemas_number().optional(), + maxItems: schemas_number().optional(), + items: schemas_object({ anyOf: schemas_array(schemas_object({ + const: schemas_string(), + title: schemas_string() + })) }), + default: schemas_array(schemas_string()).optional() + }); + /** + * Combined schema for multiple-selection enumeration + */ + const MultiSelectEnumSchemaSchema$1 = schemas_union([UntitledMultiSelectEnumSchemaSchema$1, TitledMultiSelectEnumSchemaSchema$1]); + /** + * Primitive schema definition for enum fields. + */ + const EnumSchemaSchema$1 = schemas_union([ + LegacyTitledEnumSchemaSchema$1, + SingleSelectEnumSchemaSchema$1, + MultiSelectEnumSchemaSchema$1 + ]); + /** + * Union of all primitive schema definitions. + */ + const PrimitiveSchemaDefinitionSchema$1 = schemas_union([ + EnumSchemaSchema$1, + BooleanSchemaSchema$1, + StringSchemaSchema$1, + NumberSchemaSchema$1 + ]); + /** + * Parameters for an `elicitation/create` request for form-based elicitation. + */ + const ElicitRequestFormParamsSchema$1 = TaskAugmentedRequestParamsSchema$1.extend({ + mode: literal("form").optional(), + message: schemas_string(), + requestedSchema: schemas_object({ + type: literal("object"), + properties: schemas_record(schemas_string(), PrimitiveSchemaDefinitionSchema$1), + required: schemas_array(schemas_string()).optional() + }).catchall(unknown()) + }); + /** + * Parameters for an {@linkcode ElicitRequest | elicitation/create} request for URL-based elicitation. + */ + const ElicitRequestURLParamsSchema$1 = TaskAugmentedRequestParamsSchema$1.extend({ + mode: literal("url"), + message: schemas_string(), + elicitationId: schemas_string(), + url: schemas_string().url() + }); + /** + * The parameters for a request to elicit additional information from the user via the client. + */ + const ElicitRequestParamsSchema$1 = schemas_union([ElicitRequestFormParamsSchema$1, ElicitRequestURLParamsSchema$1]); + /** + * A request from the server to elicit user input via the client. + * The client should present the message and form fields to the user (form mode) + * or navigate to a URL (URL mode). + */ + const ElicitRequestSchema$1 = RequestSchema$1.extend({ + method: literal("elicitation/create"), + params: ElicitRequestParamsSchema$1 + }); + /** + * Parameters for a {@linkcode ElicitationCompleteNotification | notifications/elicitation/complete} notification. + * + * @category notifications/elicitation/complete + */ + const ElicitationCompleteNotificationParamsSchema$1 = NotificationsParamsSchema$1.extend({ elicitationId: schemas_string() }); + /** + * A notification from the server to the client, informing it of a completion of an out-of-band elicitation request. + * + * @category notifications/elicitation/complete + */ + const ElicitationCompleteNotificationSchema$1 = NotificationSchema$1.extend({ + method: literal("notifications/elicitation/complete"), + params: ElicitationCompleteNotificationParamsSchema$1 + }); + /** + * The client's response to an {@linkcode ElicitRequest | elicitation/create} request from the server. + */ + const ElicitResultSchema$1 = ResultSchema$1.extend({ + action: schemas_enum([ + "accept", + "decline", + "cancel" + ]), + content: preprocess((val) => val === null ? void 0 : val, schemas_record(schemas_string(), schemas_union([ + schemas_string(), + schemas_number(), + schemas_boolean(), + schemas_array(schemas_string()) + ])).optional()) + }); + /** + * A reference to a resource or resource template definition. + */ + const ResourceTemplateReferenceSchema$1 = schemas_object({ + type: literal("ref/resource"), + uri: schemas_string() + }); + /** + * Identifies a prompt. + */ + const PromptReferenceSchema$1 = schemas_object({ + type: literal("ref/prompt"), + name: schemas_string() + }); + /** + * Parameters for a {@linkcode CompleteRequest | completion/complete} request. + */ + const CompleteRequestParamsSchema$1 = BaseRequestParamsSchema$1.extend({ + ref: schemas_union([PromptReferenceSchema$1, ResourceTemplateReferenceSchema$1]), + argument: schemas_object({ + name: schemas_string(), + value: schemas_string() + }), + context: schemas_object({ arguments: schemas_record(schemas_string(), schemas_string()).optional() }).optional() + }); + /** + * A request from the client to the server, to ask for completion options. + */ + const CompleteRequestSchema$1 = RequestSchema$1.extend({ + method: literal("completion/complete"), + params: CompleteRequestParamsSchema$1 + }); + /** + * The server's response to a {@linkcode CompleteRequest | completion/complete} request + */ + const CompleteResultSchema$1 = ResultSchema$1.extend({ completion: looseObject({ + values: schemas_array(schemas_string()).max(100), + total: schemas_optional(schemas_number().int()), + hasMore: schemas_optional(schemas_boolean()) + }) }); + /** + * Represents a root directory or file that the server can operate on. + * + * @deprecated Deprecated as of protocol version 2026-07-28 (SEP-2577); remains + * in the specification for at least twelve months. Migrate to passing paths via + * tool parameters, resource URIs, or configuration. + */ + const RootSchema$1 = schemas_object({ + uri: schemas_string().startsWith("file://"), + name: schemas_string().optional(), + _meta: schemas_record(schemas_string(), unknown()).optional() + }); + /** + * Sent from the server to request a list of root URIs from the client. + * + * @deprecated Deprecated as of protocol version 2026-07-28 (SEP-2577); remains + * in the specification for at least twelve months. Migrate to passing paths via + * tool parameters, resource URIs, or configuration. + */ + const ListRootsRequestSchema$1 = RequestSchema$1.extend({ + method: literal("roots/list"), + params: BaseRequestParamsSchema$1.optional() + }); + /** + * The client's response to a `roots/list` request from the server. + * + * @deprecated Deprecated as of protocol version 2026-07-28 (SEP-2577); remains + * in the specification for at least twelve months. Migrate to passing paths via + * tool parameters, resource URIs, or configuration. + */ + const ListRootsResultSchema$1 = ResultSchema$1.extend({ roots: schemas_array(RootSchema$1) }); + /** + * A notification from the client to the server, informing it that the list of roots has changed. + * + * @deprecated Deprecated as of protocol version 2026-07-28 (SEP-2577); remains + * in the specification for at least twelve months. Migrate to passing paths via + * tool parameters, resource URIs, or configuration. + */ + const RootsListChangedNotificationSchema$1 = NotificationSchema$1.extend({ + method: literal("notifications/roots/list_changed"), + params: NotificationsParamsSchema$1.optional() + }); + /** + * Task creation parameters, used to ask that the server create a task to represent a request. + * + * @deprecated 2025-11-25 wire vocabulary with no SDK runtime; kept importable for interoperability only. + */ + const TaskCreationParamsSchema$1 = looseObject({ + ttl: schemas_number().optional(), + pollInterval: schemas_number().optional() + }); + /** + * The status of a task. + * + * @deprecated 2025-11-25 wire vocabulary with no SDK runtime; kept importable for interoperability only. + */ + const TaskStatusSchema$1 = schemas_enum([ + "working", + "input_required", + "completed", + "failed", + "cancelled" + ]); + /** + * A pollable state object associated with a request. + * + * @deprecated 2025-11-25 wire vocabulary with no SDK runtime; kept importable for interoperability only. + */ + const TaskSchema$1 = schemas_object({ + taskId: schemas_string(), + status: TaskStatusSchema$1, + ttl: schemas_union([schemas_number(), schemas_null()]), + createdAt: schemas_string(), + lastUpdatedAt: schemas_string(), + pollInterval: schemas_optional(schemas_number()), + statusMessage: schemas_optional(schemas_string()) + }); + /** + * Result returned when a task is created, containing the task data wrapped in a `task` field. + * + * @deprecated 2025-11-25 wire vocabulary with no SDK runtime; kept importable for interoperability only. + */ + const CreateTaskResultSchema$1 = ResultSchema$1.extend({ task: TaskSchema$1 }); + /** + * Parameters for task status notification. + * + * @deprecated 2025-11-25 wire vocabulary with no SDK runtime; kept importable for interoperability only. + */ + const TaskStatusNotificationParamsSchema$1 = NotificationsParamsSchema$1.merge(TaskSchema$1); + /** + * A notification sent when a task's status changes. + * + * @deprecated 2025-11-25 wire vocabulary with no SDK runtime; kept importable for interoperability only. + */ + const TaskStatusNotificationSchema$1 = NotificationSchema$1.extend({ + method: literal("notifications/tasks/status"), + params: TaskStatusNotificationParamsSchema$1 + }); + /** + * A request to get the state of a specific task. + * + * @deprecated 2025-11-25 wire vocabulary with no SDK runtime; kept importable for interoperability only. + */ + const GetTaskRequestSchema$1 = RequestSchema$1.extend({ + method: literal("tasks/get"), + params: BaseRequestParamsSchema$1.extend({ taskId: schemas_string() }) + }); + /** + * The response to a {@linkcode GetTaskRequest | tasks/get} request. + * + * @deprecated 2025-11-25 wire vocabulary with no SDK runtime; kept importable for interoperability only. + */ + const GetTaskResultSchema$1 = ResultSchema$1.merge(TaskSchema$1); + /** + * A request to get the result of a specific task. + * + * @deprecated 2025-11-25 wire vocabulary with no SDK runtime; kept importable for interoperability only. + */ + const GetTaskPayloadRequestSchema$1 = RequestSchema$1.extend({ + method: literal("tasks/result"), + params: BaseRequestParamsSchema$1.extend({ taskId: schemas_string() }) + }); + /** + * The response to a `tasks/result` request. + * The structure matches the result type of the original request. + * For example, a {@linkcode CallToolRequest | tools/call} task would return the `CallToolResult` structure. + * + * + * @deprecated 2025-11-25 wire vocabulary with no SDK runtime; kept importable for interoperability only. + */ + const GetTaskPayloadResultSchema$1 = ResultSchema$1.loose(); + /** + * A request to list tasks. + * + * @deprecated 2025-11-25 wire vocabulary with no SDK runtime; kept importable for interoperability only. + */ + const ListTasksRequestSchema$1 = PaginatedRequestSchema$1.extend({ method: literal("tasks/list") }); + /** + * The response to a {@linkcode ListTasksRequest | tasks/list} request. + * + * @deprecated 2025-11-25 wire vocabulary with no SDK runtime; kept importable for interoperability only. + */ + const ListTasksResultSchema$1 = PaginatedResultSchema$1.extend({ tasks: schemas_array(TaskSchema$1) }); + /** + * A request to cancel a specific task. + * + * @deprecated 2025-11-25 wire vocabulary with no SDK runtime; kept importable for interoperability only. + */ + const CancelTaskRequestSchema$1 = RequestSchema$1.extend({ + method: literal("tasks/cancel"), + params: BaseRequestParamsSchema$1.extend({ taskId: schemas_string() }) + }); + return { + JSONValueSchema: JSONValueSchema$1, + JSONObjectSchema: JSONObjectSchema$1, + ProgressTokenSchema: ProgressTokenSchema$1, + CursorSchema: CursorSchema$1, + TaskMetadataSchema: TaskMetadataSchema$1, + RelatedTaskMetadataSchema: RelatedTaskMetadataSchema$1, + RequestMetaSchema: RequestMetaSchema$1, + BaseRequestParamsSchema: BaseRequestParamsSchema$1, + TaskAugmentedRequestParamsSchema: TaskAugmentedRequestParamsSchema$1, + RequestSchema: RequestSchema$1, + NotificationsParamsSchema: NotificationsParamsSchema$1, + NotificationSchema: NotificationSchema$1, + ResultSchema: ResultSchema$1, + RequestIdSchema: RequestIdSchema$1, + EmptyResultSchema: EmptyResultSchema$1, + CancelledNotificationParamsSchema: CancelledNotificationParamsSchema$1, + CancelledNotificationSchema: CancelledNotificationSchema$1, + IconSchema: IconSchema$1, + IconsSchema: IconsSchema$1, + BaseMetadataSchema: BaseMetadataSchema$1, + ImplementationSchema: ImplementationSchema$1, + ClientTasksCapabilitySchema: ClientTasksCapabilitySchema$1, + ServerTasksCapabilitySchema: ServerTasksCapabilitySchema$1, + ClientCapabilitiesSchema: ClientCapabilitiesSchema$1, + InitializeRequestParamsSchema: InitializeRequestParamsSchema$1, + InitializeRequestSchema: InitializeRequestSchema$1, + ServerCapabilitiesSchema: ServerCapabilitiesSchema$1, + InitializeResultSchema: InitializeResultSchema$1, + InitializedNotificationSchema: InitializedNotificationSchema$1, + PingRequestSchema: PingRequestSchema$1, + ProgressSchema: ProgressSchema$1, + ProgressNotificationParamsSchema: ProgressNotificationParamsSchema$1, + ProgressNotificationSchema: ProgressNotificationSchema$1, + PaginatedRequestParamsSchema: PaginatedRequestParamsSchema$1, + PaginatedRequestSchema: PaginatedRequestSchema$1, + PaginatedResultSchema: PaginatedResultSchema$1, + ResourceContentsSchema: ResourceContentsSchema$1, + TextResourceContentsSchema: TextResourceContentsSchema$1, + BlobResourceContentsSchema: BlobResourceContentsSchema$1, + RoleSchema: RoleSchema$1, + AnnotationsSchema: AnnotationsSchema$1, + ResourceSchema: ResourceSchema$1, + ResourceTemplateSchema: ResourceTemplateSchema$1, + ListResourcesRequestSchema: ListResourcesRequestSchema$1, + ListResourcesResultSchema: ListResourcesResultSchema$1, + ListResourceTemplatesRequestSchema: ListResourceTemplatesRequestSchema$1, + ListResourceTemplatesResultSchema: ListResourceTemplatesResultSchema$1, + ResourceRequestParamsSchema: ResourceRequestParamsSchema$1, + ReadResourceRequestParamsSchema: ReadResourceRequestParamsSchema$1, + ReadResourceRequestSchema: ReadResourceRequestSchema$1, + ReadResourceResultSchema: ReadResourceResultSchema$1, + ResourceListChangedNotificationSchema: ResourceListChangedNotificationSchema$1, + SubscribeRequestParamsSchema: SubscribeRequestParamsSchema$1, + SubscribeRequestSchema: SubscribeRequestSchema$1, + UnsubscribeRequestParamsSchema: UnsubscribeRequestParamsSchema$1, + UnsubscribeRequestSchema: UnsubscribeRequestSchema$1, + ResourceUpdatedNotificationParamsSchema: ResourceUpdatedNotificationParamsSchema$1, + ResourceUpdatedNotificationSchema: ResourceUpdatedNotificationSchema$1, + PromptArgumentSchema: PromptArgumentSchema$1, + PromptSchema: PromptSchema$1, + ListPromptsRequestSchema: ListPromptsRequestSchema$1, + ListPromptsResultSchema: ListPromptsResultSchema$1, + GetPromptRequestParamsSchema: GetPromptRequestParamsSchema$1, + GetPromptRequestSchema: GetPromptRequestSchema$1, + TextContentSchema: TextContentSchema$1, + ImageContentSchema: ImageContentSchema$1, + AudioContentSchema: AudioContentSchema$1, + ToolUseContentSchema: ToolUseContentSchema$1, + EmbeddedResourceSchema: EmbeddedResourceSchema$1, + ResourceLinkSchema: ResourceLinkSchema$1, + ContentBlockSchema: ContentBlockSchema$1, + PromptMessageSchema: PromptMessageSchema$1, + GetPromptResultSchema: GetPromptResultSchema$1, + PromptListChangedNotificationSchema: PromptListChangedNotificationSchema$1, + ToolAnnotationsSchema: ToolAnnotationsSchema$1, + ToolExecutionSchema: ToolExecutionSchema$1, + ToolSchema: ToolSchema$1, + ListToolsRequestSchema: ListToolsRequestSchema$1, + ListToolsResultSchema: ListToolsResultSchema$1, + CallToolResultSchema: CallToolResultSchema$1, + CallToolRequestParamsSchema: CallToolRequestParamsSchema$1, + CallToolRequestSchema: CallToolRequestSchema$1, + ToolListChangedNotificationSchema: ToolListChangedNotificationSchema$1, + LoggingLevelSchema: LoggingLevelSchema$1, + SetLevelRequestParamsSchema: SetLevelRequestParamsSchema$1, + SetLevelRequestSchema: SetLevelRequestSchema$1, + LoggingMessageNotificationParamsSchema: LoggingMessageNotificationParamsSchema$1, + LoggingMessageNotificationSchema: LoggingMessageNotificationSchema$1, + ModelHintSchema: ModelHintSchema$1, + ModelPreferencesSchema: ModelPreferencesSchema$1, + ToolChoiceSchema: ToolChoiceSchema$1, + ToolResultContentSchema: ToolResultContentSchema$1, + SamplingContentSchema: SamplingContentSchema$1, + SamplingMessageContentBlockSchema: SamplingMessageContentBlockSchema$1, + SamplingMessageSchema: SamplingMessageSchema$1, + CreateMessageRequestParamsSchema: CreateMessageRequestParamsSchema$1, + CreateMessageRequestSchema: CreateMessageRequestSchema$1, + CreateMessageResultSchema: CreateMessageResultSchema$1, + CreateMessageResultWithToolsSchema: CreateMessageResultWithToolsSchema$1, + BooleanSchemaSchema: BooleanSchemaSchema$1, + StringSchemaSchema: StringSchemaSchema$1, + NumberSchemaSchema: NumberSchemaSchema$1, + UntitledSingleSelectEnumSchemaSchema: UntitledSingleSelectEnumSchemaSchema$1, + TitledSingleSelectEnumSchemaSchema: TitledSingleSelectEnumSchemaSchema$1, + LegacyTitledEnumSchemaSchema: LegacyTitledEnumSchemaSchema$1, + SingleSelectEnumSchemaSchema: SingleSelectEnumSchemaSchema$1, + UntitledMultiSelectEnumSchemaSchema: UntitledMultiSelectEnumSchemaSchema$1, + TitledMultiSelectEnumSchemaSchema: TitledMultiSelectEnumSchemaSchema$1, + MultiSelectEnumSchemaSchema: MultiSelectEnumSchemaSchema$1, + EnumSchemaSchema: EnumSchemaSchema$1, + PrimitiveSchemaDefinitionSchema: PrimitiveSchemaDefinitionSchema$1, + ElicitRequestFormParamsSchema: ElicitRequestFormParamsSchema$1, + ElicitRequestURLParamsSchema: ElicitRequestURLParamsSchema$1, + ElicitRequestParamsSchema: ElicitRequestParamsSchema$1, + ElicitRequestSchema: ElicitRequestSchema$1, + ElicitationCompleteNotificationParamsSchema: ElicitationCompleteNotificationParamsSchema$1, + ElicitationCompleteNotificationSchema: ElicitationCompleteNotificationSchema$1, + ElicitResultSchema: ElicitResultSchema$1, + ResourceTemplateReferenceSchema: ResourceTemplateReferenceSchema$1, + PromptReferenceSchema: PromptReferenceSchema$1, + CompleteRequestParamsSchema: CompleteRequestParamsSchema$1, + CompleteRequestSchema: CompleteRequestSchema$1, + CompleteResultSchema: CompleteResultSchema$1, + RootSchema: RootSchema$1, + ListRootsRequestSchema: ListRootsRequestSchema$1, + ListRootsResultSchema: ListRootsResultSchema$1, + RootsListChangedNotificationSchema: RootsListChangedNotificationSchema$1, + TaskCreationParamsSchema: TaskCreationParamsSchema$1, + TaskStatusSchema: TaskStatusSchema$1, + TaskSchema: TaskSchema$1, + CreateTaskResultSchema: CreateTaskResultSchema$1, + TaskStatusNotificationParamsSchema: TaskStatusNotificationParamsSchema$1, + TaskStatusNotificationSchema: TaskStatusNotificationSchema$1, + GetTaskRequestSchema: GetTaskRequestSchema$1, + GetTaskResultSchema: GetTaskResultSchema$1, + GetTaskPayloadRequestSchema: GetTaskPayloadRequestSchema$1, + GetTaskPayloadResultSchema: GetTaskPayloadResultSchema$1, + ListTasksRequestSchema: ListTasksRequestSchema$1, + ListTasksResultSchema: ListTasksResultSchema$1, + CancelTaskRequestSchema: CancelTaskRequestSchema$1, + CancelTaskResultSchema: ResultSchema$1.merge(TaskSchema$1), + ClientRequestSchema: schemas_union([ + PingRequestSchema$1, + InitializeRequestSchema$1, + CompleteRequestSchema$1, + SetLevelRequestSchema$1, + GetPromptRequestSchema$1, + ListPromptsRequestSchema$1, + ListResourcesRequestSchema$1, + ListResourceTemplatesRequestSchema$1, + ReadResourceRequestSchema$1, + SubscribeRequestSchema$1, + UnsubscribeRequestSchema$1, + CallToolRequestSchema$1, + ListToolsRequestSchema$1, + GetTaskRequestSchema$1, + GetTaskPayloadRequestSchema$1, + ListTasksRequestSchema$1, + CancelTaskRequestSchema$1 + ]), + ClientNotificationSchema: schemas_union([ + CancelledNotificationSchema$1, + ProgressNotificationSchema$1, + InitializedNotificationSchema$1, + RootsListChangedNotificationSchema$1, + TaskStatusNotificationSchema$1 + ]), + ClientResultSchema: schemas_union([ + EmptyResultSchema$1, + CreateMessageResultSchema$1, + CreateMessageResultWithToolsSchema$1, + ElicitResultSchema$1, + ListRootsResultSchema$1, + GetTaskResultSchema$1, + ListTasksResultSchema$1, + CreateTaskResultSchema$1 + ]), + ServerRequestSchema: schemas_union([ + PingRequestSchema$1, + CreateMessageRequestSchema$1, + ElicitRequestSchema$1, + ListRootsRequestSchema$1, + GetTaskRequestSchema$1, + GetTaskPayloadRequestSchema$1, + ListTasksRequestSchema$1, + CancelTaskRequestSchema$1 + ]), + ServerNotificationSchema: schemas_union([ + CancelledNotificationSchema$1, + ProgressNotificationSchema$1, + LoggingMessageNotificationSchema$1, + ResourceUpdatedNotificationSchema$1, + ResourceListChangedNotificationSchema$1, + ToolListChangedNotificationSchema$1, + PromptListChangedNotificationSchema$1, + TaskStatusNotificationSchema$1, + ElicitationCompleteNotificationSchema$1 + ]), + ServerResultSchema: schemas_union([ + EmptyResultSchema$1, + InitializeResultSchema$1, + CompleteResultSchema$1, + GetPromptResultSchema$1, + ListPromptsResultSchema$1, + ListResourcesResultSchema$1, + ListResourceTemplatesResultSchema$1, + ReadResourceResultSchema$1, + CallToolResultSchema$1, + ListToolsResultSchema$1, + GetTaskResultSchema$1, + ListTasksResultSchema$1, + CreateTaskResultSchema$1 + ]), + CallToolResultWireSchema: unknown().superRefine((value, ctx) => { + if (typeof value !== "object" || value === null || Array.isArray(value) || value.content !== void 0) return; + for (const key of TOOL_RESULT_FOREIGN_FAMILY_KEYS) if (key in value) { + ctx.addIssue({ + code: "custom", + message: `content is required when the body carries '${key}' — another result family cannot default into an empty tools/call success` + }); + return; + } + }).transform(normalizeContentlessToolResult).pipe(CallToolResultSchema$1) + }; +} +let memo$1; +/** +* Builds the era wire-schema set on first call and returns the same object +* thereafter. Module evaluation stays construction-free so importing the +* era codec/registry costs nothing until the first validation actually +* needs a schema; the registry, the codec, and the eager `schemas.ts` +* shim all pull through this memo, so reference identity holds across +* every consumer. +*/ +function buildSchemas2025() { + return memo$1 ??= build$1(); +} + +//#endregion +//#region ../core-internal/src/wire/rev2025-11-25/legacyWrap.ts +/** +* SEP-2106 legacy `outputSchema` wrap helpers (2025-era projection only). +* +* The neutral / 2026-07-28 model lets a tool's `outputSchema` carry any JSON +* Schema root. The 2025-11-25 wire shape requires `type:'object'` at the root, +* so when an era-blind handler advertises a non-object root, the 2025 codec's +* `encodeResult('tools/list', …)` projects it down to +* `{type:'object', properties:{result:}, required:['result']}`, and +* `projectCallToolResult` wraps the matching `structuredContent` as +* `{result:}`. The 2026 codec's projections are the identity. +* +* These helpers are wire-layer property — they exist so the projection can +* live behind {@link WireCodec.encodeResult} / {@link WireCodec.projectCallToolResult} +* and never be re-derived in shared/ or server-side code. +*/ +/** +* Whether a JSON Schema's root is non-object: either an explicit non-object +* `type`, or a typeless root such as `{anyOf:[…]}`. Object-shaped typeless +* roots that the schema-conversion layer can prove are objects are stamped +* `type:'object'` upstream, so they reach this predicate as object roots. +*/ +function isNonObjectJsonSchemaRoot(json) { + return json["type"] !== "object"; +} +/** +* Keyword-position keys whose values are instance data (not subschemas). A +* `{$ref:…}` appearing inside one is a literal value, not a JSON Pointer to +* rewrite. Only consulted when the current object is in keyword position — +* a PROPERTY named `default`/`const` (under `properties`/`$defs`/…) is a name +* position whose value IS a subschema and is recursed into. +*/ +const REF_REWRITE_DATA_POSITION_KEYS = new Set([ + "const", + "enum", + "default", + "examples" +]); +/** +* Keyword-position keys whose value is a name→subschema map. Entries inside +* such a map are in NAME position: their keys are author-chosen property +* names (which may collide with JSON Schema keywords), their values are +* subschemas to recurse into. +*/ +const REF_REWRITE_NAME_MAP_KEYS = new Set([ + "properties", + "patternProperties", + "$defs", + "definitions", + "dependentSchemas", + "dependencies" +]); +/** +* Whether a subtree's `$id` establishes a new resolution base. A fragment-only +* `$id` (`"#item"`, the draft-07/06 spelling of 2020-12's `$anchor`) does not +* change the RFC 3986 base URI — same-document pointers inside still resolve +* against the document root and must be rewritten. +*/ +function establishesNewBase(id) { + return id !== void 0 && !(typeof id === "string" && id.startsWith("#")); +} +/** +* Wrap a non-object output schema in the 2025-era envelope: +* `{type:'object', properties:{result:}, required:['result']}`. +* +* Same-document `$ref` / `$dynamicRef` JSON Pointers inside the natural schema +* (e.g. `#/properties/foo` produced by zod for de-duplicated/recursive types) +* are rewritten to account for the new `#/properties/result` root: bare `#` → +* `#/properties/result`, `#/…` → `#/properties/result/…`. Cross-document refs +* (anything not starting with `#`) are left untouched. +* +* The rewrite is position-aware: data-valued keywords +* (`const`/`enum`/`default`/`examples`) in keyword position are NOT descended +* into; the same names appearing as property names under +* `properties`/`patternProperties`/`$defs`/`definitions`/`dependentSchemas`/ +* `dependencies` ARE descended into (they're subschemas). The rewrite is also +* `$id`-scoped: if the natural root carries a base-establishing `$id` no +* pointer is rewritten (same-document refs inside resolve against the embedded +* `$id` base, not the wrapper root), and any subtree that establishes its own +* `$id` is left untouched for the same reason. Fragment-only `$id` (`"#item"`, +* draft-07's anchor spelling) does not establish a base and IS descended into. +*/ +function wrapOutputSchemaForLegacy(natural) { + const $schema = typeof natural["$schema"] === "string" ? natural["$schema"] : void 0; + if (establishesNewBase(natural["$id"])) return { + ...$schema !== void 0 && { $schema }, + type: "object", + properties: { result: natural }, + required: ["result"] + }; + const convertRecursiveRefs = declares2019Dialect(natural["$schema"]) && natural["$recursiveAnchor"] !== true; + const rewriteRefs = (node, parentIsNameMap) => { + if (Array.isArray(node)) return node.map((item) => rewriteRefs(item, false)); + if (node === null || typeof node !== "object") return node; + if (!parentIsNameMap && establishesNewBase(node["$id"])) return node; + const out = {}; + let convertedRecursion = false; + for (const [k, v] of Object.entries(node)) if (parentIsNameMap) out[k] = rewriteRefs(v, false); + else if ((k === "$ref" || k === "$dynamicRef") && typeof v === "string") out[k] = v === "#" ? "#/properties/result" : v.startsWith("#/") ? `#/properties/result${v.slice(1)}` : v; + else if (k === "$recursiveRef" && v === "#" && convertRecursiveRefs) convertedRecursion = true; + else if (REF_REWRITE_DATA_POSITION_KEYS.has(k)) out[k] = v; + else if (REF_REWRITE_NAME_MAP_KEYS.has(k)) out[k] = rewriteRefs(v, true); + else out[k] = rewriteRefs(v, false); + if (convertedRecursion) if ("$ref" in out) out["allOf"] = [...Array.isArray(out["allOf"]) ? out["allOf"] : [], { $ref: "#/properties/result" }]; + else out["$ref"] = "#/properties/result"; + return out; + }; + return { + ...$schema !== void 0 && { $schema }, + type: "object", + properties: { result: rewriteRefs(natural, false) }, + required: ["result"] + }; +} + +//#endregion +//#region ../core-internal/src/wire/rev2025-11-25/registry.ts +const requestMethodKeys$1 = { + 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 +}; +const notificationMethodKeys$1 = { + "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 +}; +const resultMethodKeys = { + 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 +}; +let maps$1; +function registryMaps() { + if (maps$1) return maps$1; + const s = buildSchemas2025(); + maps$1 = { + requestSchemas: { + ping: s.PingRequestSchema, + initialize: s.InitializeRequestSchema, + "completion/complete": s.CompleteRequestSchema, + "logging/setLevel": s.SetLevelRequestSchema, + "prompts/get": s.GetPromptRequestSchema, + "prompts/list": s.ListPromptsRequestSchema, + "resources/list": s.ListResourcesRequestSchema, + "resources/templates/list": s.ListResourceTemplatesRequestSchema, + "resources/read": s.ReadResourceRequestSchema, + "resources/subscribe": s.SubscribeRequestSchema, + "resources/unsubscribe": s.UnsubscribeRequestSchema, + "tools/call": s.CallToolRequestSchema, + "tools/list": s.ListToolsRequestSchema, + "tasks/get": s.GetTaskRequestSchema, + "tasks/result": s.GetTaskPayloadRequestSchema, + "tasks/list": s.ListTasksRequestSchema, + "tasks/cancel": s.CancelTaskRequestSchema, + "sampling/createMessage": s.CreateMessageRequestSchema, + "elicitation/create": s.ElicitRequestSchema, + "roots/list": s.ListRootsRequestSchema + }, + notificationSchemas: { + "notifications/cancelled": s.CancelledNotificationSchema, + "notifications/progress": s.ProgressNotificationSchema, + "notifications/initialized": s.InitializedNotificationSchema, + "notifications/roots/list_changed": s.RootsListChangedNotificationSchema, + "notifications/tasks/status": s.TaskStatusNotificationSchema, + "notifications/message": s.LoggingMessageNotificationSchema, + "notifications/resources/updated": s.ResourceUpdatedNotificationSchema, + "notifications/resources/list_changed": s.ResourceListChangedNotificationSchema, + "notifications/tools/list_changed": s.ToolListChangedNotificationSchema, + "notifications/prompts/list_changed": s.PromptListChangedNotificationSchema, + "notifications/elicitation/complete": s.ElicitationCompleteNotificationSchema + }, + resultSchemas: { + ping: s.EmptyResultSchema, + initialize: s.InitializeResultSchema, + "completion/complete": s.CompleteResultSchema, + "logging/setLevel": s.EmptyResultSchema, + "prompts/get": s.GetPromptResultSchema, + "prompts/list": s.ListPromptsResultSchema, + "resources/list": s.ListResourcesResultSchema, + "resources/templates/list": s.ListResourceTemplatesResultSchema, + "resources/read": s.ReadResourceResultSchema, + "resources/subscribe": s.EmptyResultSchema, + "resources/unsubscribe": s.EmptyResultSchema, + "tools/call": s.CallToolResultWireSchema, + "tools/list": s.ListToolsResultSchema, + "sampling/createMessage": s.CreateMessageResultWithToolsSchema, + "elicitation/create": s.ElicitResultSchema, + "roots/list": s.ListRootsResultSchema + } + }; + return maps$1; +} +/** +* Forces the lazy registry maps (and, through them, the era's schema memo). +* Warm-up hook for `preloadSchemas()` — no-op once the maps exist. +*/ +function warmRegistryMaps2025() { + registryMaps(); +} +/** The 2025-era request-method set (registry membership = the deletion story). */ +function hasRequestMethod2025(method) { + return Object.prototype.hasOwnProperty.call(requestMethodKeys$1, method); +} +/** The 2025-era notification-method set. */ +function hasNotificationMethod2025(method) { + return Object.prototype.hasOwnProperty.call(notificationMethodKeys$1, method); +} +/** Result-map membership: exactly the era's typed-method subset (no task entries, no 2026-only methods). */ +function hasResultMethod(method) { + return Object.prototype.hasOwnProperty.call(resultMethodKeys, method); +} +function getResultSchema(method) { + return hasResultMethod(method) ? registryMaps().resultSchemas[method] : void 0; +} +function getRequestSchema(method) { + return hasRequestMethod2025(method) ? registryMaps().requestSchemas[method] : void 0; +} +function getNotificationSchema(method) { + return hasNotificationMethod2025(method) ? registryMaps().notificationSchemas[method] : void 0; +} +/** Registry method lists (for the spec-method universe and the CI registry-diff oracle). */ +const rev2025RequestMethods = Object.keys(requestMethodKeys$1); +const rev2025NotificationMethods = Object.keys(notificationMethodKeys$1); + +//#endregion +//#region ../core-internal/src/wire/rev2025-11-25/codec.ts +function isPlainObject$6(value) { + return value !== null && typeof value === "object" && !Array.isArray(value); +} +/** Tri-state wrap of an optional Zod schema lookup (the function-only contract). */ +function triState$1(schema, raw) { + if (schema === void 0) return { + ok: false, + reason: "not-in-era" + }; + const parsed = schema.safeParse(raw); + return parsed.success ? { + ok: true, + value: parsed.data + } : { + ok: false, + reason: "invalid", + message: String(parsed.error) + }; +} +const NOT_IN_ERA$1 = { + ok: false, + reason: "not-in-era" +}; +/** Whether a `tools/list` entry advertises a non-object `outputSchema` root that needs the SEP-2106 legacy wrap. */ +function toolNeedsLegacyWrap(t) { + return isPlainObject$6(t) && isPlainObject$6(t["outputSchema"]) && isNonObjectJsonSchemaRoot(t["outputSchema"]); +} +/** The wire→neutral trust boundary: a decoded 2025-era wire result is adopted as the neutral `Result` here (the module's single deliberate assertion). */ +function toNeutralResult(value) { + return value; +} +const rev2025Codec = { + era: "2025-11-25", + hasRequestMethod: hasRequestMethod2025, + hasNotificationMethod: hasNotificationMethod2025, + validateRequest: (method, raw) => triState$1(getRequestSchema(method), raw), + validateResult: (method, raw) => triState$1(getResultSchema(method), raw), + validateNotification: (method, raw) => triState$1(getNotificationSchema(method), raw), + hasInputRequestMethod: () => false, + validateInputRequest: () => NOT_IN_ERA$1, + validateInputResponse: () => NOT_IN_ERA$1, + samplingResultVariant: ((hasTools, raw) => { + const s = buildSchemas2025(); + return triState$1(hasTools ? s.CreateMessageResultWithToolsSchema : s.CreateMessageResultSchema, raw); + }), + outboundEnvelope: (_material) => void 0, + validateEnvelopeMeta: (_meta) => [], + projectCallToolResult(result, advertisedOutputSchema) { + const withText = appendTextFallbackForNonObject(result); + const sc = withText.structuredContent; + if (sc === void 0) return withText; + const valueIsNonObject = typeof sc !== "object" || sc === null || Array.isArray(sc); + const schemaWrapped = advertisedOutputSchema !== void 0 && isNonObjectJsonSchemaRoot(advertisedOutputSchema); + if (!valueIsNonObject && !schemaWrapped) return withText; + return { + ...withText, + structuredContent: { result: sc } + }; + }, + decodeResult(_method, raw) { + if (isPlainObject$6(raw) && "resultType" in raw) { + const stripped = { ...raw }; + delete stripped["resultType"]; + return { + kind: "complete", + result: toNeutralResult(stripped) + }; + } + return { + kind: "complete", + result: toNeutralResult(raw) + }; + }, + encodeResult(method, result) { + if (method !== "tools/list") return result; + const tools = result.tools; + if (!Array.isArray(tools) || !tools.some((t) => toolNeedsLegacyWrap(t))) return result; + return { + ...result, + tools: tools.map((t) => toolNeedsLegacyWrap(t) ? { + ...t, + outputSchema: wrapOutputSchemaForLegacy(t.outputSchema) + } : t) + }; + }, + encodeErrorCode: (code) => code === -32002 ? -32602 : code, + checkInboundEnvelope: (_material) => void 0 +}; + +//#endregion +//#region ../core-internal/src/wire/rev2026-07-28/buildSchemas.ts +/** +* 2026-era wire schemas (protocol revision 2026-07-28). +* +* Fully self-contained — no runtime imports from types/schemas.ts. The +* neutral types/schemas.ts layer is the public-API superset and is free to +* evolve; this file is the 2026 wire-parse contract and is BEHAVIOR-FROZEN +* against the 2026-07-28 anchor. Every era-shared building block (content +* blocks, resources, prompts, capabilities, notifications, …) that the wire +* shapes compose is a frozen LOCAL copy — verbatim from the neutral layer at +* the point this revision was sealed, dependencies first. The only cross-layer +* dependency is `import type { JSONObject, JSONValue }` from the neutral types +* barrel — pure structural type aliases with no parse behavior. +* +* This module is the only place the per-request `_meta` envelope is modeled. +* The envelope is wire-only vocabulary: the protocol layer lifts it off +* inbound requests before any handler runs and surfaces it at +* `ctx.mcpReq.envelope`; the 2026-era codec enforces its requiredness at +* dispatch time (`checkInboundEnvelope`) - the former neutral-schema JSDoc +* deferral ("enforced per request at dispatch time, not here") is now +* discharged by that codec step. +* +* No 2025-era traffic ever touches this module, so requiredness here is +* bare and spec-exact (the shared-schema `.catch` hazards do not apply). +* +* SPEC-CURRENCY RE-SEAL (2026-07-17): the 2026-07-28 revision was re-sealed +* upstream by spec PR #3002 (commit 71e30695, merged 2026-07-15 — after the +* previous anchor pin f68d864a): the envelope's `clientInfo` demoted from +* required to SHOULD, and `DiscoverResult.serverInfo` moved from the result +* body to the new `ResultMetaObject` key +* `_meta['io.modelcontextprotocol/serverInfo']` (optional on every result). +* The shapes below are the re-sealed anchor, exactly — no pre-#3002 shape is +* modeled anywhere (per ruling: the final revision is the only 2026-07-28). +*/ +function build() { + const JSONValueSchema$1 = lazy(() => schemas_union([ + schemas_string(), + schemas_number(), + schemas_boolean(), + schemas_null(), + schemas_record(schemas_string(), JSONValueSchema$1), + schemas_array(JSONValueSchema$1) + ])); + const JSONObjectSchema$1 = schemas_record(schemas_string(), JSONValueSchema$1); + /** + * A progress token, used to associate progress notifications with the original request. + */ + const ProgressTokenSchema$1 = schemas_union([schemas_string(), schemas_number().int()]); + /** + * An opaque token used to represent a cursor for pagination. + */ + const CursorSchema$1 = schemas_string(); + /** + * A uniquely identifying ID for a request in JSON-RPC. + */ + const RequestIdSchema$1 = schemas_union([schemas_string(), schemas_number().int()]); + /** + * The sender or recipient of messages and data in a conversation. + */ + const RoleSchema$1 = schemas_enum(["user", "assistant"]); + /** + * The severity of a log message. + */ + const LoggingLevelSchema$1 = schemas_enum([ + "debug", + "info", + "notice", + "warning", + "error", + "critical", + "alert", + "emergency" + ]); + /** + * A Zod schema for validating Base64 strings that is more performant and + * robust for very large inputs than the default regex-based check. It avoids + * stack overflows by using the native `atob` function for validation. + */ + const Base64Schema = schemas_string().refine((val) => { + try { + atob(val); + return true; + } catch { + return false; + } + }, { message: "Invalid Base64 string" }); + /** @deprecated 2025-11-25 wire vocabulary with no SDK runtime; kept importable for interoperability only. */ + const TaskMetadataSchema$1 = schemas_object({ ttl: schemas_number().optional() }); + /** @deprecated 2025-11-25 wire vocabulary with no SDK runtime; kept importable for interoperability only. */ + const RelatedTaskMetadataSchema$1 = schemas_object({ taskId: schemas_string() }); + const RequestMetaSchema$1 = looseObject({ + progressToken: ProgressTokenSchema$1.optional(), + "io.modelcontextprotocol/related-task": RelatedTaskMetadataSchema$1.optional() + }); + const BaseRequestParamsSchema$1 = schemas_object({ _meta: RequestMetaSchema$1.optional() }); + /** @deprecated 2025-11-25 wire vocabulary with no SDK runtime; kept importable for interoperability only. */ + const TaskAugmentedRequestParamsSchema$1 = BaseRequestParamsSchema$1.extend({ task: TaskMetadataSchema$1.optional() }); + const NotificationsParamsSchema$1 = schemas_object({ _meta: RequestMetaSchema$1.optional() }); + const NotificationSchema$1 = schemas_object({ + method: schemas_string(), + params: NotificationsParamsSchema$1.loose().optional() + }); + const IconSchema$1 = schemas_object({ + src: schemas_string(), + mimeType: schemas_string().optional(), + sizes: schemas_array(schemas_string()).optional(), + theme: schemas_enum(["light", "dark"]).optional() + }); + const IconsSchema$1 = schemas_object({ icons: schemas_array(IconSchema$1).optional() }); + const BaseMetadataSchema$1 = schemas_object({ + name: schemas_string(), + title: schemas_string().optional() + }); + const ImplementationSchema$1 = BaseMetadataSchema$1.extend({ + ...BaseMetadataSchema$1.shape, + ...IconsSchema$1.shape, + version: schemas_string(), + websiteUrl: schemas_string().optional(), + description: schemas_string().optional() + }); + const FormElicitationCapabilitySchema = intersection(schemas_object({ applyDefaults: schemas_boolean().optional() }), JSONObjectSchema$1); + const ElicitationCapabilitySchema = preprocess((value) => { + if (value && typeof value === "object" && !Array.isArray(value) && Object.keys(value).length === 0) return { form: {} }; + return value; + }, intersection(schemas_object({ + form: FormElicitationCapabilitySchema.optional(), + url: JSONObjectSchema$1.optional() + }), JSONObjectSchema$1.optional())); + /** @deprecated 2025-11-25 wire vocabulary with no SDK runtime; kept importable for interoperability only. */ + const ClientTasksCapabilitySchema$1 = looseObject({ + list: JSONObjectSchema$1.optional(), + cancel: JSONObjectSchema$1.optional(), + requests: looseObject({ + sampling: looseObject({ createMessage: JSONObjectSchema$1.optional() }).optional(), + elicitation: looseObject({ create: JSONObjectSchema$1.optional() }).optional() + }).optional() + }); + /** @deprecated 2025-11-25 wire vocabulary with no SDK runtime; kept importable for interoperability only. */ + const ServerTasksCapabilitySchema$1 = looseObject({ + list: JSONObjectSchema$1.optional(), + cancel: JSONObjectSchema$1.optional(), + requests: looseObject({ tools: looseObject({ call: JSONObjectSchema$1.optional() }).optional() }).optional() + }); + const ClientCapabilitiesSchema$1 = schemas_object({ + experimental: schemas_record(schemas_string(), JSONObjectSchema$1).optional(), + sampling: schemas_object({ + context: JSONObjectSchema$1.optional(), + tools: JSONObjectSchema$1.optional() + }).optional(), + elicitation: ElicitationCapabilitySchema.optional(), + roots: schemas_object({ listChanged: schemas_boolean().optional() }).optional(), + tasks: ClientTasksCapabilitySchema$1.optional(), + extensions: schemas_record(schemas_string(), JSONObjectSchema$1).optional() + }); + const ServerCapabilitiesSchema$1 = schemas_object({ + experimental: schemas_record(schemas_string(), JSONObjectSchema$1).optional(), + logging: JSONObjectSchema$1.optional(), + completions: JSONObjectSchema$1.optional(), + prompts: schemas_object({ listChanged: schemas_boolean().optional() }).optional(), + resources: schemas_object({ + subscribe: schemas_boolean().optional(), + listChanged: schemas_boolean().optional() + }).optional(), + tools: schemas_object({ listChanged: schemas_boolean().optional() }).optional(), + tasks: ServerTasksCapabilitySchema$1.optional(), + extensions: schemas_record(schemas_string(), JSONObjectSchema$1).optional() + }); + const ProgressSchema$1 = schemas_object({ + progress: schemas_number(), + total: schemas_optional(schemas_number()), + message: schemas_optional(schemas_string()) + }); + const ProgressNotificationParamsSchema$1 = schemas_object({ + ...NotificationsParamsSchema$1.shape, + ...ProgressSchema$1.shape, + progressToken: ProgressTokenSchema$1 + }); + const ProgressNotificationSchema$1 = NotificationSchema$1.extend({ + method: literal("notifications/progress"), + params: ProgressNotificationParamsSchema$1 + }); + const LoggingMessageNotificationParamsSchema$1 = NotificationsParamsSchema$1.extend({ + level: LoggingLevelSchema$1, + logger: schemas_string().optional(), + data: unknown() + }); + const LoggingMessageNotificationSchema$1 = NotificationSchema$1.extend({ + method: literal("notifications/message"), + params: LoggingMessageNotificationParamsSchema$1 + }); + const ResourceContentsSchema$1 = schemas_object({ + uri: schemas_string(), + mimeType: schemas_optional(schemas_string()), + _meta: schemas_record(schemas_string(), unknown()).optional() + }); + const TextResourceContentsSchema$1 = ResourceContentsSchema$1.extend({ text: schemas_string() }); + const BlobResourceContentsSchema$1 = ResourceContentsSchema$1.extend({ blob: Base64Schema }); + const AnnotationsSchema$1 = schemas_object({ + audience: schemas_array(RoleSchema$1).optional(), + priority: schemas_number().min(0).max(1).optional(), + lastModified: iso_datetime({ offset: true }).optional() + }); + const ResourceSchema$1 = schemas_object({ + ...BaseMetadataSchema$1.shape, + ...IconsSchema$1.shape, + uri: schemas_string(), + description: schemas_optional(schemas_string()), + mimeType: schemas_optional(schemas_string()), + size: schemas_optional(schemas_number()), + annotations: AnnotationsSchema$1.optional(), + _meta: schemas_optional(looseObject({})) + }); + const ResourceTemplateSchema$1 = schemas_object({ + ...BaseMetadataSchema$1.shape, + ...IconsSchema$1.shape, + uriTemplate: schemas_string(), + description: schemas_optional(schemas_string()), + mimeType: schemas_optional(schemas_string()), + annotations: AnnotationsSchema$1.optional(), + _meta: schemas_optional(looseObject({})) + }); + const ResourceListChangedNotificationSchema$1 = NotificationSchema$1.extend({ + method: literal("notifications/resources/list_changed"), + params: NotificationsParamsSchema$1.optional() + }); + const ResourceUpdatedNotificationParamsSchema$1 = NotificationsParamsSchema$1.extend({ uri: schemas_string() }); + const ResourceUpdatedNotificationSchema$1 = NotificationSchema$1.extend({ + method: literal("notifications/resources/updated"), + params: ResourceUpdatedNotificationParamsSchema$1 + }); + const PromptArgumentSchema$1 = schemas_object({ + name: schemas_string(), + description: schemas_optional(schemas_string()), + required: schemas_optional(schemas_boolean()) + }); + const PromptSchema$1 = schemas_object({ + ...BaseMetadataSchema$1.shape, + ...IconsSchema$1.shape, + description: schemas_optional(schemas_string()), + arguments: schemas_optional(schemas_array(PromptArgumentSchema$1)), + _meta: schemas_optional(looseObject({})) + }); + const PromptListChangedNotificationSchema$1 = NotificationSchema$1.extend({ + method: literal("notifications/prompts/list_changed"), + params: NotificationsParamsSchema$1.optional() + }); + const TextContentSchema$1 = schemas_object({ + type: literal("text"), + text: schemas_string(), + annotations: AnnotationsSchema$1.optional(), + _meta: schemas_record(schemas_string(), unknown()).optional() + }); + const ImageContentSchema$1 = schemas_object({ + type: literal("image"), + data: Base64Schema, + mimeType: schemas_string(), + annotations: AnnotationsSchema$1.optional(), + _meta: schemas_record(schemas_string(), unknown()).optional() + }); + const AudioContentSchema$1 = schemas_object({ + type: literal("audio"), + data: Base64Schema, + mimeType: schemas_string(), + annotations: AnnotationsSchema$1.optional(), + _meta: schemas_record(schemas_string(), unknown()).optional() + }); + const ToolUseContentSchema$1 = schemas_object({ + type: literal("tool_use"), + name: schemas_string(), + id: schemas_string(), + input: schemas_record(schemas_string(), unknown()), + _meta: schemas_record(schemas_string(), unknown()).optional() + }); + const EmbeddedResourceSchema$1 = schemas_object({ + type: literal("resource"), + resource: schemas_union([TextResourceContentsSchema$1, BlobResourceContentsSchema$1]), + annotations: AnnotationsSchema$1.optional(), + _meta: schemas_record(schemas_string(), unknown()).optional() + }); + const ResourceLinkSchema$1 = ResourceSchema$1.extend({ type: literal("resource_link") }); + const ContentBlockSchema$1 = schemas_union([ + TextContentSchema$1, + ImageContentSchema$1, + AudioContentSchema$1, + ResourceLinkSchema$1, + EmbeddedResourceSchema$1 + ]); + const PromptMessageSchema$1 = schemas_object({ + role: RoleSchema$1, + content: ContentBlockSchema$1 + }); + const ToolAnnotationsSchema$1 = schemas_object({ + title: schemas_string().optional(), + readOnlyHint: schemas_boolean().optional(), + destructiveHint: schemas_boolean().optional(), + idempotentHint: schemas_boolean().optional(), + openWorldHint: schemas_boolean().optional() + }); + const ToolListChangedNotificationSchema$1 = NotificationSchema$1.extend({ + method: literal("notifications/tools/list_changed"), + params: NotificationsParamsSchema$1.optional() + }); + const ModelHintSchema$1 = schemas_object({ name: schemas_string().optional() }); + const ModelPreferencesSchema$1 = schemas_object({ + hints: schemas_array(ModelHintSchema$1).optional(), + costPriority: schemas_number().min(0).max(1).optional(), + speedPriority: schemas_number().min(0).max(1).optional(), + intelligencePriority: schemas_number().min(0).max(1).optional() + }); + const ToolChoiceSchema$1 = schemas_object({ mode: schemas_enum([ + "auto", + "required", + "none" + ]).optional() }); + const BooleanSchemaSchema$1 = schemas_object({ + type: literal("boolean"), + title: schemas_string().optional(), + description: schemas_string().optional(), + default: schemas_boolean().optional() + }); + const StringSchemaSchema$1 = schemas_object({ + type: literal("string"), + title: schemas_string().optional(), + description: schemas_string().optional(), + minLength: schemas_number().optional(), + maxLength: schemas_number().optional(), + format: schemas_enum([ + "email", + "uri", + "date", + "date-time" + ]).optional(), + default: schemas_string().optional() + }); + const NumberSchemaSchema$1 = schemas_object({ + type: schemas_enum(["number", "integer"]), + title: schemas_string().optional(), + description: schemas_string().optional(), + minimum: schemas_number().optional(), + maximum: schemas_number().optional(), + default: schemas_number().optional() + }); + const UntitledSingleSelectEnumSchemaSchema$1 = schemas_object({ + type: literal("string"), + title: schemas_string().optional(), + description: schemas_string().optional(), + enum: schemas_array(schemas_string()), + default: schemas_string().optional() + }); + const TitledSingleSelectEnumSchemaSchema$1 = schemas_object({ + type: literal("string"), + title: schemas_string().optional(), + description: schemas_string().optional(), + oneOf: schemas_array(schemas_object({ + const: schemas_string(), + title: schemas_string() + })), + default: schemas_string().optional() + }); + const LegacyTitledEnumSchemaSchema$1 = schemas_object({ + type: literal("string"), + title: schemas_string().optional(), + description: schemas_string().optional(), + enum: schemas_array(schemas_string()), + enumNames: schemas_array(schemas_string()).optional(), + default: schemas_string().optional() + }); + const SingleSelectEnumSchemaSchema$1 = schemas_union([UntitledSingleSelectEnumSchemaSchema$1, TitledSingleSelectEnumSchemaSchema$1]); + const UntitledMultiSelectEnumSchemaSchema$1 = schemas_object({ + type: literal("array"), + title: schemas_string().optional(), + description: schemas_string().optional(), + minItems: schemas_number().optional(), + maxItems: schemas_number().optional(), + items: schemas_object({ + type: literal("string"), + enum: schemas_array(schemas_string()) + }), + default: schemas_array(schemas_string()).optional() + }); + const TitledMultiSelectEnumSchemaSchema$1 = schemas_object({ + type: literal("array"), + title: schemas_string().optional(), + description: schemas_string().optional(), + minItems: schemas_number().optional(), + maxItems: schemas_number().optional(), + items: schemas_object({ anyOf: schemas_array(schemas_object({ + const: schemas_string(), + title: schemas_string() + })) }), + default: schemas_array(schemas_string()).optional() + }); + const MultiSelectEnumSchemaSchema$1 = schemas_union([UntitledMultiSelectEnumSchemaSchema$1, TitledMultiSelectEnumSchemaSchema$1]); + const EnumSchemaSchema$1 = schemas_union([ + LegacyTitledEnumSchemaSchema$1, + SingleSelectEnumSchemaSchema$1, + MultiSelectEnumSchemaSchema$1 + ]); + const PrimitiveSchemaDefinitionSchema$1 = schemas_union([ + EnumSchemaSchema$1, + BooleanSchemaSchema$1, + StringSchemaSchema$1, + NumberSchemaSchema$1 + ]); + const ElicitRequestFormParamsSchema$1 = TaskAugmentedRequestParamsSchema$1.extend({ + mode: literal("form").optional(), + message: schemas_string(), + requestedSchema: schemas_object({ + type: literal("object"), + properties: schemas_record(schemas_string(), PrimitiveSchemaDefinitionSchema$1), + required: schemas_array(schemas_string()).optional() + }).catchall(unknown()) + }); + const ResourceTemplateReferenceSchema$1 = schemas_object({ + type: literal("ref/resource"), + uri: schemas_string() + }); + const PromptReferenceSchema$1 = schemas_object({ + type: literal("ref/prompt"), + name: schemas_string() + }); + const RootSchema$1 = schemas_object({ + uri: schemas_string().startsWith("file://"), + name: schemas_string().optional(), + _meta: schemas_record(schemas_string(), unknown()).optional() + }); + const sharedClientCapabilityShape = ClientCapabilitiesSchema$1.shape; + const ClientCapabilities2026Schema = schemas_object({ + experimental: sharedClientCapabilityShape.experimental, + sampling: sharedClientCapabilityShape.sampling, + elicitation: sharedClientCapabilityShape.elicitation, + roots: sharedClientCapabilityShape.roots, + extensions: sharedClientCapabilityShape.extensions + }); + const sharedServerCapabilityShape = ServerCapabilitiesSchema$1.shape; + const ServerCapabilities2026Schema = schemas_object({ + experimental: sharedServerCapabilityShape.experimental, + logging: sharedServerCapabilityShape.logging, + completions: sharedServerCapabilityShape.completions, + prompts: sharedServerCapabilityShape.prompts, + resources: sharedServerCapabilityShape.resources, + tools: sharedServerCapabilityShape.tools, + extensions: sharedServerCapabilityShape.extensions + }); + /** + * The per-request `_meta` envelope carried by every request under protocol revision + * 2026-07-28: the protocol version governing the request, the client implementation + * info, and the client's capabilities — declared per request rather than once at + * initialization — plus the optional log-level opt-in. + * + * This schema models the complete envelope on its own (loose: foreign keys + * pass through - the lift extracts exactly the reserved keys, so enforcement + * never sees extension material). Requiredness is enforced per request at + * dispatch time by the 2026-era codec's `checkInboundEnvelope` step. + */ + const RequestMetaEnvelopeSchema = looseObject({ + progressToken: ProgressTokenSchema$1.optional(), + [auth_CUe6YdwF_PROTOCOL_VERSION_META_KEY]: schemas_string(), + [auth_CUe6YdwF_CLIENT_INFO_META_KEY]: ImplementationSchema$1.optional(), + [auth_CUe6YdwF_CLIENT_CAPABILITIES_META_KEY]: ClientCapabilities2026Schema, + [LOG_LEVEL_META_KEY]: LoggingLevelSchema$1.optional() + }); + /** 2026-era Tool: anchor-exact — no `execution` (deleted vocabulary). */ + const ToolSchema$1 = schemas_object({ + ...BaseMetadataSchema$1.shape, + ...IconsSchema$1.shape, + description: schemas_string().optional(), + inputSchema: looseObject({ + $schema: schemas_string().optional(), + type: literal("object") + }), + outputSchema: looseObject({ $schema: schemas_string().optional() }).optional(), + annotations: ToolAnnotationsSchema$1.optional(), + _meta: schemas_record(schemas_string(), unknown()).optional() + }); + /** 2026-era ToolResultContent (anchor-exact: `structuredContent?: unknown`). */ + const ToolResultContentSchema$1 = schemas_object({ + type: literal("tool_result"), + toolUseId: schemas_string(), + content: schemas_array(ContentBlockSchema$1), + structuredContent: unknown().optional(), + isError: schemas_boolean().optional(), + _meta: schemas_record(schemas_string(), unknown()).optional() + }); + /** 2026-era sampling content union (composes the forked tool-result shape). */ + const SamplingMessageContentBlockSchema$1 = schemas_union([ + TextContentSchema$1, + ImageContentSchema$1, + AudioContentSchema$1, + ToolUseContentSchema$1, + ToolResultContentSchema$1 + ]); + /** 2026-era SamplingMessage (anchor-exact: single block or array). */ + const SamplingMessageSchema$1 = schemas_object({ + role: RoleSchema$1, + content: schemas_union([SamplingMessageContentBlockSchema$1, schemas_array(SamplingMessageContentBlockSchema$1)]), + _meta: schemas_record(schemas_string(), unknown()).optional() + }); + /** Open union per the anchor: 'complete' | 'input_required' | string. */ + const ResultTypeSchema = schemas_string(); + /** + * Result `_meta` (anchor `ResultMetaObject`, added by spec PR #3002): + * loose, with the serverInfo key typed when present; the outbound stamp + * is the encode contract's `stampServerInfoMeta` step. + */ + const ResultMetaSchema = looseObject({ [auth_CUe6YdwF_SERVER_INFO_META_KEY]: ImplementationSchema$1.optional().catch(void 0) }); + const wireMeta = ResultMetaSchema.optional(); + function wireResult(shape) { + return looseObject({ + _meta: wireMeta, + resultType: ResultTypeSchema.default("complete"), + ...shape + }); + } + const ResultSchema$1 = wireResult({}); + const PaginatedResultSchema$1 = wireResult({ nextCursor: CursorSchema$1.optional() }); + const CallToolResultSchema$1 = wireResult({ + content: schemas_array(ContentBlockSchema$1), + structuredContent: unknown().optional(), + isError: schemas_boolean().optional() + }); + const ListToolsResultSchema$1 = wireResult({ + ttlMs: schemas_number().int().min(0), + cacheScope: schemas_enum(["public", "private"]), + tools: schemas_array(ToolSchema$1), + nextCursor: CursorSchema$1.optional() + }); + const ListPromptsResultSchema$1 = wireResult({ + ttlMs: schemas_number().int().min(0), + cacheScope: schemas_enum(["public", "private"]), + prompts: schemas_array(PromptSchema$1), + nextCursor: CursorSchema$1.optional() + }); + const GetPromptResultSchema$1 = wireResult({ + description: schemas_string().optional(), + messages: schemas_array(PromptMessageSchema$1) + }); + const ListResourcesResultSchema$1 = wireResult({ + ttlMs: schemas_number().int().min(0), + cacheScope: schemas_enum(["public", "private"]), + resources: schemas_array(ResourceSchema$1), + nextCursor: CursorSchema$1.optional() + }); + const ListResourceTemplatesResultSchema$1 = wireResult({ + ttlMs: schemas_number().int().min(0), + cacheScope: schemas_enum(["public", "private"]), + resourceTemplates: schemas_array(ResourceTemplateSchema$1), + nextCursor: CursorSchema$1.optional() + }); + const ReadResourceResultSchema$1 = wireResult({ + ttlMs: schemas_number().int().min(0), + cacheScope: schemas_enum(["public", "private"]), + contents: schemas_array(schemas_union([TextResourceContentsSchema$1, BlobResourceContentsSchema$1])) + }); + const CompleteResultSchema$1 = wireResult({ completion: schemas_object({ + values: schemas_array(schemas_string()).max(100), + total: schemas_number().int().optional(), + hasMore: schemas_boolean().optional() + }).loose() }); + /** CacheableResult (SEP-2549): ttlMs and cacheScope REQUIRED per the anchor. */ + const CacheableResultSchema = wireResult({ + ttlMs: schemas_number().int().min(0), + cacheScope: schemas_enum(["public", "private"]) + }); + const DiscoverResultSchema$1 = wireResult({ + ttlMs: schemas_number().int().min(0).catch(0), + cacheScope: schemas_enum(["public", "private"]).catch("private"), + supportedVersions: schemas_array(schemas_string()), + capabilities: ServerCapabilities2026Schema, + instructions: schemas_string().optional() + }); + /** 2026-era CreateMessageRequestParams (anchor-exact: forked SamplingMessage/Tool, no task augmentation). */ + const CreateMessageRequestParamsSchema$1 = schemas_object({ + messages: schemas_array(SamplingMessageSchema$1), + modelPreferences: ModelPreferencesSchema$1.optional(), + systemPrompt: schemas_string().optional(), + includeContext: schemas_enum([ + "none", + "thisServer", + "allServers" + ]).optional(), + temperature: schemas_number().optional(), + maxTokens: schemas_number().int(), + stopSequences: schemas_array(schemas_string()).optional(), + metadata: JSONObjectSchema$1.optional(), + tools: schemas_array(ToolSchema$1).optional(), + toolChoice: ToolChoiceSchema$1.optional() + }); + /** 2026-era embedded sampling request (de-JSON-RPC'd). */ + const CreateMessageRequestSchema$1 = schemas_object({ + method: literal("sampling/createMessage"), + params: CreateMessageRequestParamsSchema$1 + }); + /** + * 2026-era embedded roots listing request (de-JSON-RPC'd). Embedded input + * requests do NOT carry the per-request `_meta` envelope on this revision — + * the anchor declares a bare optional `_meta` on `params`. + */ + const ListRootsRequestSchema$1 = schemas_object({ + method: literal("roots/list"), + params: schemas_object({ _meta: schemas_record(schemas_string(), unknown()).optional() }).optional() + }); + /** 2026-era embedded sampling response (anchor-exact: extends the forked SamplingMessage). */ + const CreateMessageResultSchema$1 = schemas_object({ + ...SamplingMessageSchema$1.shape, + model: schemas_string(), + stopReason: schemas_string().optional() + }); + /** 2026-era embedded roots listing response (anchor-exact: bare `roots` array). */ + const ListRootsResultSchema$1 = schemas_object({ roots: schemas_array(RootSchema$1) }); + /** 2026-era embedded elicitation response (anchor-exact: bare result, restricted content value types). */ + const ElicitResultSchema$1 = schemas_object({ + action: schemas_enum([ + "accept", + "decline", + "cancel" + ]), + content: schemas_record(schemas_string(), schemas_union([ + schemas_string(), + schemas_number(), + schemas_boolean(), + schemas_array(schemas_string()) + ])).optional() + }); + /** + * 2026-era URL-mode elicitation params (anchor-exact fork): the draft removed + * `elicitationId` (and the `notifications/elicitation/complete` channel it + * keyed) — the shared schema keeps the field because it is required on the + * frozen 2025-11-25 revision. + */ + const ElicitRequestURLParamsSchema$1 = schemas_object({ + mode: literal("url"), + message: schemas_string(), + url: schemas_string().url() + }); + /** 2026-era elicitation params (form mode is revision-identical; URL mode is the fork above). */ + const ElicitRequestParamsSchema$1 = schemas_union([ElicitRequestFormParamsSchema$1, ElicitRequestURLParamsSchema$1]); + /** 2026-era embedded elicitation request (de-JSON-RPC'd; see the URL-mode fork above). */ + const ElicitRequestSchema$1 = schemas_object({ + method: literal("elicitation/create"), + params: ElicitRequestParamsSchema$1 + }); + /** A single embedded input request (one of the three demoted server→client requests). */ + const InputRequestSchema = schemas_union([ + CreateMessageRequestSchema$1, + ListRootsRequestSchema$1, + ElicitRequestSchema$1 + ]); + /** A single embedded input response — the BARE result union (never a `{method, result}` wrapper). */ + const InputResponseSchema = schemas_union([ + CreateMessageResultSchema$1, + ListRootsResultSchema$1, + ElicitResultSchema$1 + ]); + /** Map of embedded input requests, keyed by server-assigned identifiers. */ + const InputRequestsSchema = schemas_record(schemas_string(), InputRequestSchema); + /** Map of embedded input responses, keyed by the corresponding request identifiers. */ + const InputResponsesSchema = schemas_record(schemas_string(), InputResponseSchema); + /** + * The wire InputRequiredResult: `resultType: 'input_required'` plus at least + * one of `inputRequests` / `requestState` (the at-least-one rule is enforced + * at the server seam, not by this parse shape). + */ + const InputRequiredResultSchema = wireResult({ + inputRequests: InputRequestsSchema.optional(), + requestState: schemas_string().optional() + }); + /** The retry-channel members carried by client-initiated requests on this revision. */ + const retryParamsShape = { + inputResponses: InputResponsesSchema.optional(), + requestState: schemas_string().optional() + }; + /** Anchor InputResponseRequestParams: the retry channel on top of the required request `_meta` envelope. */ + const InputResponseRequestParamsSchema = schemas_object({ + _meta: RequestMetaEnvelopeSchema, + ...retryParamsShape + }); + /** Post-lift request `_meta` (progressToken + extension keys; loose). */ + const DispatchRequestMetaSchema = looseObject({ progressToken: ProgressTokenSchema$1.optional() }); + function wireRequest(method, paramsShape) { + return schemas_object({ + method: literal(method), + params: schemas_object({ + _meta: RequestMetaEnvelopeSchema, + ...paramsShape + }) + }); + } + function dispatchRequest(method, paramsShape) { + return schemas_object({ + method: literal(method), + params: schemas_object({ + _meta: DispatchRequestMetaSchema.optional(), + ...paramsShape + }).optional() + }); + } + const callToolParamsShape = { + name: schemas_string(), + arguments: schemas_record(schemas_string(), unknown()).optional(), + ...retryParamsShape + }; + const paginatedParamsShape = { cursor: CursorSchema$1.optional() }; + const CallToolRequestSchema$1 = wireRequest("tools/call", callToolParamsShape); + const ListToolsRequestSchema$1 = wireRequest("tools/list", paginatedParamsShape); + const ListPromptsRequestSchema$1 = wireRequest("prompts/list", paginatedParamsShape); + const GetPromptRequestSchema$1 = wireRequest("prompts/get", { + name: schemas_string(), + arguments: schemas_record(schemas_string(), schemas_string()).optional(), + ...retryParamsShape + }); + const ListResourcesRequestSchema$1 = wireRequest("resources/list", paginatedParamsShape); + const ListResourceTemplatesRequestSchema$1 = wireRequest("resources/templates/list", paginatedParamsShape); + const ReadResourceRequestSchema$1 = wireRequest("resources/read", { + uri: schemas_string(), + ...retryParamsShape + }); + const completeParamsShape = { + ref: schemas_union([PromptReferenceSchema$1, ResourceTemplateReferenceSchema$1]), + argument: schemas_object({ + name: schemas_string(), + value: schemas_string() + }), + context: schemas_object({ arguments: schemas_record(schemas_string(), schemas_string()).optional() }).optional() + }; + const CompleteRequestSchema$1 = wireRequest("completion/complete", completeParamsShape); + const DiscoverRequestSchema$1 = wireRequest("server/discover", {}); + /** Anchor SubscriptionFilter (2026-only). */ + const SubscriptionFilterSchema$1 = schemas_object({ + toolsListChanged: schemas_boolean().optional(), + promptsListChanged: schemas_boolean().optional(), + resourcesListChanged: schemas_boolean().optional(), + resourceSubscriptions: schemas_array(schemas_string()).optional() + }); + const subscriptionsListenParamsShape = { notifications: SubscriptionFilterSchema$1 }; + const SubscriptionsListenRequestSchema$1 = wireRequest("subscriptions/listen", subscriptionsListenParamsShape); + /** + * Anchor SubscriptionsListenResultMeta — required subscriptionId stamp on + * the graceful-close result. Extends `ResultMetaObject` since spec PR + * #3002 (composed, so the serverInfo key and its leniency stay single-sourced). + */ + const SubscriptionsListenResultMetaSchema$1 = ResultMetaSchema.extend({ "io.modelcontextprotocol/subscriptionId": RequestIdSchema$1 }); + /** + * Anchor SubscriptionsListenResult (2026-only). The empty `subscriptions/listen` + * response signalling that the subscription has ended gracefully (server + * shutdown). An abrupt transport close carries no response — the client treats + * stream-close-without-result as a disconnect. + */ + const SubscriptionsListenResultSchema$1 = looseObject({ + _meta: SubscriptionsListenResultMetaSchema$1, + resultType: ResultTypeSchema.default("complete") + }); + /** Dispatch (post-lift) request schemas, keyed by method — registry-internal. */ + const dispatchRequestSchemas = { + "tools/call": dispatchRequest("tools/call", callToolParamsShape), + "tools/list": dispatchRequest("tools/list", paginatedParamsShape), + "prompts/get": dispatchRequest("prompts/get", { + name: schemas_string(), + arguments: schemas_record(schemas_string(), schemas_string()).optional() + }), + "prompts/list": dispatchRequest("prompts/list", paginatedParamsShape), + "resources/list": dispatchRequest("resources/list", paginatedParamsShape), + "resources/templates/list": dispatchRequest("resources/templates/list", paginatedParamsShape), + "resources/read": dispatchRequest("resources/read", { uri: schemas_string() }), + "completion/complete": dispatchRequest("completion/complete", completeParamsShape), + "server/discover": dispatchRequest("server/discover", {}), + "subscriptions/listen": dispatchRequest("subscriptions/listen", subscriptionsListenParamsShape) + }; + /** Dispatch (post-lift) result schemas, keyed by method — what the funnel + * validates AFTER `decodeResult` consumed `resultType`. */ + function liftedResult(shape) { + return looseObject({ + _meta: wireMeta, + ...shape + }); + } + const dispatchResultSchemas = { + "tools/call": liftedResult({ + content: schemas_array(ContentBlockSchema$1), + structuredContent: unknown().optional(), + isError: schemas_boolean().optional() + }), + "tools/list": liftedResult({ + ttlMs: schemas_number().int().min(0), + cacheScope: schemas_enum(["public", "private"]), + tools: schemas_array(ToolSchema$1), + nextCursor: CursorSchema$1.optional() + }), + "prompts/get": liftedResult({ + description: schemas_string().optional(), + messages: schemas_array(PromptMessageSchema$1) + }), + "prompts/list": liftedResult({ + ttlMs: schemas_number().int().min(0), + cacheScope: schemas_enum(["public", "private"]), + prompts: schemas_array(PromptSchema$1), + nextCursor: CursorSchema$1.optional() + }), + "resources/list": liftedResult({ + ttlMs: schemas_number().int().min(0), + cacheScope: schemas_enum(["public", "private"]), + resources: schemas_array(ResourceSchema$1), + nextCursor: CursorSchema$1.optional() + }), + "resources/templates/list": liftedResult({ + ttlMs: schemas_number().int().min(0), + cacheScope: schemas_enum(["public", "private"]), + resourceTemplates: schemas_array(ResourceTemplateSchema$1), + nextCursor: CursorSchema$1.optional() + }), + "resources/read": liftedResult({ + ttlMs: schemas_number().int().min(0), + cacheScope: schemas_enum(["public", "private"]), + contents: schemas_array(schemas_union([TextResourceContentsSchema$1, BlobResourceContentsSchema$1])) + }), + "completion/complete": liftedResult({ completion: schemas_object({ + values: schemas_array(schemas_string()).max(100), + total: schemas_number().int().optional(), + hasMore: schemas_boolean().optional() + }).loose() }), + "server/discover": liftedResult({ + ttlMs: schemas_number().int().min(0).catch(0), + cacheScope: schemas_enum(["public", "private"]).catch("private"), + supportedVersions: schemas_array(schemas_string()), + capabilities: ServerCapabilities2026Schema, + instructions: schemas_string().optional() + }), + "subscriptions/listen": liftedResult({}) + }; + /** + * Notification `_meta` (anchor `NotificationMetaObject`): loose, with the + * subscriptions/listen demux key typed when present. Only the anchor-exact + * SHAPE is modeled here — listen delivery itself (filter gating, demux, + * teardown) is #14 scope and not implemented by this module. + */ + const NotificationMetaSchema = looseObject({ "io.modelcontextprotocol/subscriptionId": RequestIdSchema$1.optional() }); + /** Anchor SubscriptionsAcknowledgedNotification (2026-only). */ + const SubscriptionsAcknowledgedNotificationSchema$1 = schemas_object({ + method: literal("notifications/subscriptions/acknowledged"), + params: schemas_object({ + _meta: NotificationMetaSchema.optional(), + notifications: SubscriptionFilterSchema$1 + }) + }); + /** + * 2026-era `notifications/cancelled` params (anchor-exact fork): `requestId` + * is REQUIRED on this revision — the shared schema keeps it optional because + * the frozen 2025-11-25 shape declares it optional (task cancellation goes + * through `tasks/cancel` there). Requiredness is bare because no 2025-era + * traffic touches this module. + */ + const CancelledNotificationParamsSchema$1 = schemas_object({ + _meta: NotificationMetaSchema.optional(), + requestId: RequestIdSchema$1, + reason: schemas_string().optional() + }); + /** 2026-era `notifications/cancelled` (see the params fork above). */ + const CancelledNotificationSchema$1 = schemas_object({ + method: literal("notifications/cancelled"), + params: CancelledNotificationParamsSchema$1 + }); + const notificationSchemas2026 = { + "notifications/cancelled": CancelledNotificationSchema$1, + "notifications/progress": ProgressNotificationSchema$1, + "notifications/message": LoggingMessageNotificationSchema$1, + "notifications/resources/updated": ResourceUpdatedNotificationSchema$1, + "notifications/resources/list_changed": ResourceListChangedNotificationSchema$1, + "notifications/tools/list_changed": ToolListChangedNotificationSchema$1, + "notifications/prompts/list_changed": PromptListChangedNotificationSchema$1, + "notifications/subscriptions/acknowledged": SubscriptionsAcknowledgedNotificationSchema$1 + }; + const wireResultResponse = (result) => schemas_object({ + jsonrpc: literal("2.0"), + id: schemas_union([schemas_string(), schemas_number().int()]), + result + }).strict(); + return { + JSONValueSchema: JSONValueSchema$1, + JSONObjectSchema: JSONObjectSchema$1, + ProgressTokenSchema: ProgressTokenSchema$1, + CursorSchema: CursorSchema$1, + RequestIdSchema: RequestIdSchema$1, + RoleSchema: RoleSchema$1, + LoggingLevelSchema: LoggingLevelSchema$1, + TaskMetadataSchema: TaskMetadataSchema$1, + RelatedTaskMetadataSchema: RelatedTaskMetadataSchema$1, + RequestMetaSchema: RequestMetaSchema$1, + BaseRequestParamsSchema: BaseRequestParamsSchema$1, + TaskAugmentedRequestParamsSchema: TaskAugmentedRequestParamsSchema$1, + NotificationsParamsSchema: NotificationsParamsSchema$1, + NotificationSchema: NotificationSchema$1, + IconSchema: IconSchema$1, + IconsSchema: IconsSchema$1, + BaseMetadataSchema: BaseMetadataSchema$1, + ImplementationSchema: ImplementationSchema$1, + ClientTasksCapabilitySchema: ClientTasksCapabilitySchema$1, + ServerTasksCapabilitySchema: ServerTasksCapabilitySchema$1, + ClientCapabilitiesSchema: ClientCapabilitiesSchema$1, + ServerCapabilitiesSchema: ServerCapabilitiesSchema$1, + ProgressSchema: ProgressSchema$1, + ProgressNotificationParamsSchema: ProgressNotificationParamsSchema$1, + ProgressNotificationSchema: ProgressNotificationSchema$1, + LoggingMessageNotificationParamsSchema: LoggingMessageNotificationParamsSchema$1, + LoggingMessageNotificationSchema: LoggingMessageNotificationSchema$1, + ResourceContentsSchema: ResourceContentsSchema$1, + TextResourceContentsSchema: TextResourceContentsSchema$1, + BlobResourceContentsSchema: BlobResourceContentsSchema$1, + AnnotationsSchema: AnnotationsSchema$1, + ResourceSchema: ResourceSchema$1, + ResourceTemplateSchema: ResourceTemplateSchema$1, + ResourceListChangedNotificationSchema: ResourceListChangedNotificationSchema$1, + ResourceUpdatedNotificationParamsSchema: ResourceUpdatedNotificationParamsSchema$1, + ResourceUpdatedNotificationSchema: ResourceUpdatedNotificationSchema$1, + PromptArgumentSchema: PromptArgumentSchema$1, + PromptSchema: PromptSchema$1, + PromptListChangedNotificationSchema: PromptListChangedNotificationSchema$1, + TextContentSchema: TextContentSchema$1, + ImageContentSchema: ImageContentSchema$1, + AudioContentSchema: AudioContentSchema$1, + ToolUseContentSchema: ToolUseContentSchema$1, + EmbeddedResourceSchema: EmbeddedResourceSchema$1, + ResourceLinkSchema: ResourceLinkSchema$1, + ContentBlockSchema: ContentBlockSchema$1, + PromptMessageSchema: PromptMessageSchema$1, + ToolAnnotationsSchema: ToolAnnotationsSchema$1, + ToolListChangedNotificationSchema: ToolListChangedNotificationSchema$1, + ModelHintSchema: ModelHintSchema$1, + ModelPreferencesSchema: ModelPreferencesSchema$1, + ToolChoiceSchema: ToolChoiceSchema$1, + BooleanSchemaSchema: BooleanSchemaSchema$1, + StringSchemaSchema: StringSchemaSchema$1, + NumberSchemaSchema: NumberSchemaSchema$1, + UntitledSingleSelectEnumSchemaSchema: UntitledSingleSelectEnumSchemaSchema$1, + TitledSingleSelectEnumSchemaSchema: TitledSingleSelectEnumSchemaSchema$1, + LegacyTitledEnumSchemaSchema: LegacyTitledEnumSchemaSchema$1, + SingleSelectEnumSchemaSchema: SingleSelectEnumSchemaSchema$1, + UntitledMultiSelectEnumSchemaSchema: UntitledMultiSelectEnumSchemaSchema$1, + TitledMultiSelectEnumSchemaSchema: TitledMultiSelectEnumSchemaSchema$1, + MultiSelectEnumSchemaSchema: MultiSelectEnumSchemaSchema$1, + EnumSchemaSchema: EnumSchemaSchema$1, + PrimitiveSchemaDefinitionSchema: PrimitiveSchemaDefinitionSchema$1, + ElicitRequestFormParamsSchema: ElicitRequestFormParamsSchema$1, + ResourceTemplateReferenceSchema: ResourceTemplateReferenceSchema$1, + PromptReferenceSchema: PromptReferenceSchema$1, + RootSchema: RootSchema$1, + ClientCapabilities2026Schema, + ServerCapabilities2026Schema, + RequestMetaEnvelopeSchema, + ToolSchema: ToolSchema$1, + ToolResultContentSchema: ToolResultContentSchema$1, + SamplingMessageContentBlockSchema: SamplingMessageContentBlockSchema$1, + SamplingMessageSchema: SamplingMessageSchema$1, + ResultTypeSchema, + ResultMetaSchema, + ResultSchema: ResultSchema$1, + PaginatedResultSchema: PaginatedResultSchema$1, + CallToolResultSchema: CallToolResultSchema$1, + ListToolsResultSchema: ListToolsResultSchema$1, + ListPromptsResultSchema: ListPromptsResultSchema$1, + GetPromptResultSchema: GetPromptResultSchema$1, + ListResourcesResultSchema: ListResourcesResultSchema$1, + ListResourceTemplatesResultSchema: ListResourceTemplatesResultSchema$1, + ReadResourceResultSchema: ReadResourceResultSchema$1, + CompleteResultSchema: CompleteResultSchema$1, + CacheableResultSchema, + DiscoverResultSchema: DiscoverResultSchema$1, + CreateMessageRequestParamsSchema: CreateMessageRequestParamsSchema$1, + CreateMessageRequestSchema: CreateMessageRequestSchema$1, + ListRootsRequestSchema: ListRootsRequestSchema$1, + CreateMessageResultSchema: CreateMessageResultSchema$1, + ListRootsResultSchema: ListRootsResultSchema$1, + ElicitResultSchema: ElicitResultSchema$1, + ElicitRequestURLParamsSchema: ElicitRequestURLParamsSchema$1, + ElicitRequestParamsSchema: ElicitRequestParamsSchema$1, + ElicitRequestSchema: ElicitRequestSchema$1, + InputRequestSchema, + InputResponseSchema, + InputRequestsSchema, + InputResponsesSchema, + InputRequiredResultSchema, + InputResponseRequestParamsSchema, + CallToolRequestSchema: CallToolRequestSchema$1, + ListToolsRequestSchema: ListToolsRequestSchema$1, + ListPromptsRequestSchema: ListPromptsRequestSchema$1, + GetPromptRequestSchema: GetPromptRequestSchema$1, + ListResourcesRequestSchema: ListResourcesRequestSchema$1, + ListResourceTemplatesRequestSchema: ListResourceTemplatesRequestSchema$1, + ReadResourceRequestSchema: ReadResourceRequestSchema$1, + CompleteRequestSchema: CompleteRequestSchema$1, + DiscoverRequestSchema: DiscoverRequestSchema$1, + SubscriptionFilterSchema: SubscriptionFilterSchema$1, + SubscriptionsListenRequestSchema: SubscriptionsListenRequestSchema$1, + SubscriptionsListenResultMetaSchema: SubscriptionsListenResultMetaSchema$1, + SubscriptionsListenResultSchema: SubscriptionsListenResultSchema$1, + dispatchRequestSchemas, + dispatchResultSchemas, + NotificationMetaSchema, + SubscriptionsAcknowledgedNotificationSchema: SubscriptionsAcknowledgedNotificationSchema$1, + CancelledNotificationParamsSchema: CancelledNotificationParamsSchema$1, + CancelledNotificationSchema: CancelledNotificationSchema$1, + notificationSchemas2026, + JSONRPCResultResponseSchema: wireResultResponse(ResultSchema$1), + CallToolResultResponseSchema: wireResultResponse(schemas_union([CallToolResultSchema$1, InputRequiredResultSchema])), + ListToolsResultResponseSchema: wireResultResponse(ListToolsResultSchema$1), + ListPromptsResultResponseSchema: wireResultResponse(ListPromptsResultSchema$1), + GetPromptResultResponseSchema: wireResultResponse(schemas_union([GetPromptResultSchema$1, InputRequiredResultSchema])), + ListResourcesResultResponseSchema: wireResultResponse(ListResourcesResultSchema$1), + ListResourceTemplatesResultResponseSchema: wireResultResponse(ListResourceTemplatesResultSchema$1), + ReadResourceResultResponseSchema: wireResultResponse(schemas_union([ReadResourceResultSchema$1, InputRequiredResultSchema])), + CompleteResultResponseSchema: wireResultResponse(CompleteResultSchema$1), + DiscoverResultResponseSchema: wireResultResponse(DiscoverResultSchema$1) + }; +} +let src_CX2iR2pK_memo; +/** +* Builds the era wire-schema set on first call and returns the same object +* thereafter. Module evaluation stays construction-free so importing the +* era codec/registry costs nothing until the first validation actually +* needs a schema; the registry, the codec, and the eager `schemas.ts` +* shim all pull through this memo, so reference identity holds across +* every consumer. +*/ +function buildSchemas2026() { + return src_CX2iR2pK_memo ??= build(); +} + +//#endregion +//#region ../core-internal/src/shared/resultCacheHints.ts +/** +* The operations whose results are cacheable on the 2026-07-28 revision (the +* `CacheableResult` extenders). This list is closed: no other operation's +* result ever receives cache fields from the SDK. +*/ +const CACHEABLE_RESULT_METHODS = [ + "tools/list", + "prompts/list", + "resources/list", + "resources/templates/list", + "resources/read", + "server/discover" +]; +/** Whether the given method's result is cacheable on the 2026-07-28 revision. */ +function isCacheableResultMethod(method) { + return CACHEABLE_RESULT_METHODS.includes(method); +} +/** +* The symbol-keyed carrier for a configured cache hint on a result object. +* Symbol properties are invisible to JSON serialization, so the carrier can be +* attached era-blind: only the 2026-era encode seam consumes it. +*/ +const RESULT_CACHE_HINT_FALLBACK = Symbol("modelcontextprotocol.resultCacheHintFallback"); +/** +* Attaches a configured cache hint to a result as the encode-time fallback. +* Returns the result unchanged when there is nothing to attach. When a more +* specific hint is already attached, the two hints are combined per field +* (most-specific-author-wins for each of `ttlMs` and `cacheScope`): the +* per-registration hint attached by the feature layer keeps every field it +* sets, and the server-level per-operation hint only fills the fields the +* more specific hint leaves unset. +*/ +function attachCacheHintFallback(result, hint) { + if (hint === void 0) return result; + const attached = result[RESULT_CACHE_HINT_FALLBACK]; + if (attached === void 0) return { + ...result, + [RESULT_CACHE_HINT_FALLBACK]: hint + }; + const merged = {}; + const ttlMs = attached.ttlMs ?? hint.ttlMs; + if (ttlMs !== void 0) merged.ttlMs = ttlMs; + const cacheScope = attached.cacheScope ?? hint.cacheScope; + if (cacheScope !== void 0) merged.cacheScope = cacheScope; + return { + ...result, + [RESULT_CACHE_HINT_FALLBACK]: merged + }; +} +/** Reads the configured cache-hint fallback attached to a result, if any. */ +function cacheHintFallbackOf(result) { + return result[RESULT_CACHE_HINT_FALLBACK]; +} +/** +* Whether a value is a valid `ttlMs`: a non-negative safe integer. Safe +* integers are required because the wire schemas validate `ttlMs` as an +* integer within `Number.MIN_SAFE_INTEGER`/`Number.MAX_SAFE_INTEGER`; a value +* outside that range is treated as invalid here so it falls through to the +* next author instead of being emitted and rejected downstream. +*/ +function isValidCacheTtlMs(value) { + return typeof value === "number" && Number.isSafeInteger(value) && value >= 0; +} +/** Whether a value is a valid `cacheScope`. */ +function isValidCacheScope(value) { + return value === "public" || value === "private"; +} +/** +* Validates a configured cache hint at configuration time. Throws a +* `RangeError` naming the offending field, so misconfiguration fails at +* startup/registration rather than silently degrading at encode time. +*/ +function assertValidCacheHint(hint, context) { + if (hint.ttlMs !== void 0 && !isValidCacheTtlMs(hint.ttlMs)) throw new RangeError(`Invalid cache hint for ${context}: ttlMs must be a non-negative safe integer (got ${String(hint.ttlMs)})`); + if (hint.cacheScope !== void 0 && !isValidCacheScope(hint.cacheScope)) throw new RangeError(`Invalid cache hint for ${context}: cacheScope must be 'public' or 'private' (got ${String(hint.cacheScope)})`); +} + +//#endregion +//#region ../core-internal/src/types/enums.ts +/** +* Error codes for protocol errors that cross the wire as JSON-RPC error responses. +* These follow the JSON-RPC specification and MCP-specific extensions. +*/ +let src_CX2iR2pK_ProtocolErrorCode = /* @__PURE__ */ function(ProtocolErrorCode$1) { + ProtocolErrorCode$1[ProtocolErrorCode$1["ParseError"] = -32700] = "ParseError"; + ProtocolErrorCode$1[ProtocolErrorCode$1["InvalidRequest"] = -32600] = "InvalidRequest"; + ProtocolErrorCode$1[ProtocolErrorCode$1["MethodNotFound"] = -32601] = "MethodNotFound"; + ProtocolErrorCode$1[ProtocolErrorCode$1["InvalidParams"] = -32602] = "InvalidParams"; + ProtocolErrorCode$1[ProtocolErrorCode$1["InternalError"] = -32603] = "InternalError"; + /** + * Resource not found. + * + * Receive-tolerated only: the SDK never EMITS `-32002` — `resources/read` + * misses answer `-32602` (Invalid Params) on every protocol revision per + * the 2026-07-28 spec MUST, and a handler-thrown `-32002` is mapped to + * `-32602` at the era encode seam. The member stays importable so clients + * can recognise `-32002` from peers built on earlier SDK releases (the + * spec's "clients SHOULD also accept `-32002`" backwards-compatibility + * clause). Throw `ResourceNotFoundError` instead. + */ + ProtocolErrorCode$1[ProtocolErrorCode$1["ResourceNotFound"] = -32002] = "ResourceNotFound"; + /** + * Processing the request requires a capability the client did not declare + * in the request's `clientCapabilities` (protocol revision 2026-07-28). + */ + ProtocolErrorCode$1[ProtocolErrorCode$1["MissingRequiredClientCapability"] = -32021] = "MissingRequiredClientCapability"; + /** + * The request's protocol version is unknown to the server or unsupported + * by it (protocol revision 2026-07-28). + */ + ProtocolErrorCode$1[ProtocolErrorCode$1["UnsupportedProtocolVersion"] = -32022] = "UnsupportedProtocolVersion"; + ProtocolErrorCode$1[ProtocolErrorCode$1["UrlElicitationRequired"] = -32042] = "UrlElicitationRequired"; + return ProtocolErrorCode$1; +}({}); + +//#endregion +//#region ../core-internal/src/types/errors.ts +/** +* Protocol errors are JSON-RPC errors that cross the wire as error responses. +* They use numeric error codes from the {@linkcode ProtocolErrorCode} enum. +* +* `instanceof` on this class (and its subclasses) is brand-matched, so it works +* across separately bundled copies of the SDK — e.g. an error constructed by +* `@modelcontextprotocol/client` matches the class re-exported by +* `@modelcontextprotocol/server` in the same process. +*/ +var src_CX2iR2pK_ProtocolError = class ProtocolError extends Error { + static { + Object.defineProperty(this, "mcpBrand", { value: "mcp.ProtocolError" }); + } + static [Symbol.hasInstance](value) { + return brandedHasInstance(this, value); + } + /** + * Brand-based type guard: equivalent to `value instanceof this`, as an + * explicit static predicate (the axios/AWS-SDK `isInstance` style). Reads + * the caller's own brand via `this`, so every branded subclass gets a + * correctly-scoped guard by inheritance. Must be invoked on the class — + * in callback position write `v => SdkError.isInstance(v)`, not + * `.filter(SdkError.isInstance)` (detached calls throw rather than + * silently matching nothing). + */ + static isInstance(value) { + 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 brandedHasInstance(this, value); + } + constructor(code, message, data) { + super(message); + this.code = code; + this.data = data; + this.name = "ProtocolError"; + stampErrorBrands(this, new.target); + } + /** + * Factory method to create the appropriate error type based on the error code and data + */ + static fromError(code, message, data) { + if (code === src_CX2iR2pK_ProtocolErrorCode.UrlElicitationRequired && data) { + const errorData = data; + if (errorData.elicitations) return new UrlElicitationRequiredError(errorData.elicitations, message); + } + if (code === src_CX2iR2pK_ProtocolErrorCode.UnsupportedProtocolVersion && data) { + const errorData = data; + if (Array.isArray(errorData.supported) && typeof errorData.requested === "string") return new src_CX2iR2pK_UnsupportedProtocolVersionError({ + supported: errorData.supported, + requested: errorData.requested + }, message); + } + if (code === src_CX2iR2pK_ProtocolErrorCode.InvalidParams || code === src_CX2iR2pK_ProtocolErrorCode.ResourceNotFound) { + const errorData = data; + if (typeof errorData?.uri === "string" && (code === src_CX2iR2pK_ProtocolErrorCode.ResourceNotFound || Object.keys(errorData).length === 1)) return new ResourceNotFoundError(errorData.uri, message); + } + if (code === src_CX2iR2pK_ProtocolErrorCode.MissingRequiredClientCapability && data) { + const errorData = data; + if (errorData.requiredCapabilities !== null && typeof errorData.requiredCapabilities === "object" && !Array.isArray(errorData.requiredCapabilities)) return new src_CX2iR2pK_MissingRequiredClientCapabilityError({ requiredCapabilities: errorData.requiredCapabilities }, message); + } + return new ProtocolError(code, message, data); + } +}; +/** +* Error type for a `resources/read` miss: the requested resource does not +* exist. The wire code is `-32602` (Invalid Params) on every protocol +* revision — the spec MUST for revision 2026-07-28, and the value the v1.x +* SDK has always emitted on earlier revisions. The error data echoes the +* requested URI. +* +* Recognise this error by checking `error.data` is exactly `{ uri: string }` +* (a `-32602` whose data carries `uri` and nothing else is resource-not-found; +* any other `-32602` is an ordinary Invalid Params). For backwards compatibility, clients should also +* accept `-32002` as resource not found — earlier SDK builds emitted that +* code, and {@linkcode ProtocolError.fromError} reconstructs this class for +* either code **when `error.data` carries `uri`** (a bare `-32002` without +* `data.uri` stays a generic {@linkcode ProtocolError}). `instanceof` checks +* are brand-matched and work across separately bundled copies of the SDK. +*/ +var ResourceNotFoundError = class extends src_CX2iR2pK_ProtocolError { + static { + Object.defineProperty(this, "mcpBrand", { value: "mcp.ResourceNotFoundError" }); + } + constructor(uri, message = `Resource not found: ${uri}`) { + super(src_CX2iR2pK_ProtocolErrorCode.InvalidParams, message, { uri }); + } + /** The URI that was requested and not found. */ + get uri() { + return this.data.uri; + } +}; +/** +* Specialized error type when a tool requires a URL mode elicitation. +* This makes it nicer for the client to handle since there is specific data to work with instead of just a code to check against. +*/ +var UrlElicitationRequiredError = class extends src_CX2iR2pK_ProtocolError { + static { + Object.defineProperty(this, "mcpBrand", { value: "mcp.UrlElicitationRequiredError" }); + } + constructor(elicitations, message = `URL elicitation${elicitations.length > 1 ? "s" : ""} required`) { + super(src_CX2iR2pK_ProtocolErrorCode.UrlElicitationRequired, message, { elicitations }); + } + get elicitations() { + return this.data?.elicitations ?? []; + } +}; +/** +* Error type for the `-32022` UnsupportedProtocolVersion protocol error (protocol +* revision 2026-07-28): the request's protocol version is unknown to the server or +* unsupported by it. +* +* The error data lists the protocol versions the receiver supports (`supported`), +* so the sender can choose a mutually supported version and retry, and echoes the +* version that was requested (`requested`). +*/ +var src_CX2iR2pK_UnsupportedProtocolVersionError = class extends src_CX2iR2pK_ProtocolError { + static { + Object.defineProperty(this, "mcpBrand", { value: "mcp.UnsupportedProtocolVersionError" }); + } + constructor(data, message = `Unsupported protocol version: ${data.requested}`) { + super(src_CX2iR2pK_ProtocolErrorCode.UnsupportedProtocolVersion, message, data); + } + /** + * Protocol versions the receiver supports. + */ + get supported() { + return this.data.supported; + } + /** + * The protocol version that was requested. + */ + get requested() { + return this.data.requested; + } +}; +/** +* Error type for the `-32021` MissingRequiredClientCapability protocol error +* (protocol revision 2026-07-28): processing the request requires a capability +* the client did not declare in the request's `clientCapabilities`. +* +* The error data lists the missing capabilities (`requiredCapabilities`) in +* the `ClientCapabilities` shape, so the client can see exactly what it would +* have to declare for the request to be served. On HTTP, the response status +* is `400 Bad Request`. +* +* Recognize this error by its code and `data.requiredCapabilities`, or by +* `instanceof` — checks are brand-matched and work across separately bundled +* copies of the SDK. +*/ +var src_CX2iR2pK_MissingRequiredClientCapabilityError = class extends src_CX2iR2pK_ProtocolError { + static { + Object.defineProperty(this, "mcpBrand", { value: "mcp.MissingRequiredClientCapabilityError" }); + } + constructor(data, message = `Missing required client capabilities: ${Object.keys(data.requiredCapabilities).join(", ")}`) { + super(src_CX2iR2pK_ProtocolErrorCode.MissingRequiredClientCapability, message, data); + } + /** + * The capabilities the server requires from the client to process the + * request (only the missing capabilities are listed). + */ + get requiredCapabilities() { + return this.data.requiredCapabilities; + } +}; + +//#endregion +//#region ../core-internal/src/wire/rev2026-07-28/encodeContract.ts +/** The default cache policy when neither the handler nor configuration provides one. */ +const DEFAULT_CACHE_TTL_MS = 0; +const DEFAULT_CACHE_SCOPE = "private"; +/** +* Request methods whose spec result vocabulary goes beyond `'complete'` on the +* 2026-07-28 revision: their results may be `input_required` (multi +* round-trip requests), so a handler-provided `resultType` passes through the +* stamp untouched. `subscriptions/listen` is NOT in this set: it never emits +* a JSON-RPC result — termination is stream close (HTTP) or +* `notifications/cancelled` (stdio) per the spec. +*/ +const EXTENDED_RESULT_TYPE_METHODS = [ + "tools/call", + "prompts/get", + "resources/read" +]; +/** +* Step 1 of the encode contract: ensure the outbound result carries the +* required `resultType` discriminator. +* +* - No handler-provided value → stamp `'complete'`. +* - Handler-provided `'complete'` → kept as-is. +* - Handler-provided non-`'complete'` value on a method whose vocabulary +* allows it ({@linkcode EXTENDED_RESULT_TYPE_METHODS}) → passes through. +* The value is forwarded verbatim — the wire vocabulary is an open union and +* the SDK does not validate the string, so emitting a `resultType` the +* negotiated revision does not define is the handler author's +* responsibility. +* - Handler-provided non-`'complete'` value on any other method → internal +* error (loud): the value would be mis-typed on the wire, and silently +* rewriting it would hide a server bug. +*/ +function stampResultType(method, result) { + const provided = result["resultType"]; + if (provided === void 0) return { + ...result, + resultType: "complete" + }; + if (provided === "complete") return result; + if (EXTENDED_RESULT_TYPE_METHODS.includes(method)) return result; + throw new src_CX2iR2pK_ProtocolError(src_CX2iR2pK_ProtocolErrorCode.InternalError, `Handler for ${method} returned resultType '${String(provided)}', but results of ${method} only support 'complete' on protocol revision 2026-07-28`); +} +/** +* Step 2 of the encode contract: fill the required `ttlMs`/`cacheScope` fields +* on cacheable results. +* +* Applies only when the (post-stamp) `resultType` is `'complete'` and the +* method is one of the cacheable operations; everything else is returned +* untouched apart from removing the configured-hint carrier. Field resolution +* is per field, most specific author first: a valid handler-returned value, +* then the configured cache hint attached by the server layer, then the +* defaults. Handler-returned values are validated at encode time (`ttlMs` +* must be a non-negative integer, `cacheScope` must be `'public'` or +* `'private'`); invalid values are ignored rather than emitted. +*/ +function fillCacheFields(method, result) { + const fallback = cacheHintFallbackOf(result); + if (result["resultType"] !== "complete" || !isCacheableResultMethod(method)) return fallback === void 0 ? result : stripCacheHintFallback(result); + const provided = result; + const ttlMs = isValidCacheTtlMs(provided["ttlMs"]) ? provided["ttlMs"] : resolveTtlMs(fallback); + const cacheScope = isValidCacheScope(provided["cacheScope"]) ? provided["cacheScope"] : resolveCacheScope(fallback); + const filled = { + ...provided, + ttlMs, + cacheScope + }; + delete filled[RESULT_CACHE_HINT_FALLBACK]; + return filled; +} +function isPlainObject$5(value) { + return value !== null && typeof value === "object" && !Array.isArray(value); +} +/** +* Step 3 of the encode contract: stamp the server's identity into the +* result's `_meta` under `io.modelcontextprotocol/serverInfo` (spec PR #3002: +* servers SHOULD include it on every response). +* +* - No `serverInfo` supplied (a client instance, or a hand-constructed +* protocol object) → identity function. +* - The result's `_meta` already carries the key → kept as-is (the handler +* is the more specific author; mirrors the cache-fill resolution order). +* - A present-but-non-object `_meta` (a dynamic-caller bug) → kept as-is: +* the stamp never rewrites handler material, and the malformed value fails +* loudly at the peer instead of being silently replaced here. +* - Otherwise → the key is added, preserving any other `_meta` entries. +* +* Runs for every result regardless of `resultType`: the anchor types +* `Result._meta` as `ResultMetaObject` on all results, `input_required` +* included. +*/ +function stampServerInfoMeta(result, serverInfo) { + if (serverInfo === void 0) return result; + const meta = result["_meta"]; + if (meta === void 0) return { + ...result, + _meta: { [auth_CUe6YdwF_SERVER_INFO_META_KEY]: serverInfo } + }; + if (!isPlainObject$5(meta)) return result; + if (meta[auth_CUe6YdwF_SERVER_INFO_META_KEY] !== void 0) return result; + return { + ...result, + _meta: { + ...meta, + [auth_CUe6YdwF_SERVER_INFO_META_KEY]: serverInfo + } + }; +} +function resolveTtlMs(fallback) { + return fallback !== void 0 && isValidCacheTtlMs(fallback.ttlMs) ? fallback.ttlMs : DEFAULT_CACHE_TTL_MS; +} +function resolveCacheScope(fallback) { + return fallback !== void 0 && isValidCacheScope(fallback.cacheScope) ? fallback.cacheScope : DEFAULT_CACHE_SCOPE; +} +function stripCacheHintFallback(result) { + const copy = { ...result }; + delete copy[RESULT_CACHE_HINT_FALLBACK]; + return copy; +} + +//#endregion +//#region ../core-internal/src/wire/rev2026-07-28/inputRequired.ts +/** +* In-band input-request vocabulary of the 2026-07-28 revision (SEP-2322 +* multi round-trip requests), dispatch view. +* +* The three former server→client wire requests (`elicitation/create`, +* `sampling/createMessage`, `roots/list`) are NOT wire request methods on +* this revision — they are demoted to de-JSON-RPC'd payloads embedded in an +* `input_required` result. The multi-round-trip driver dispatches those +* embedded payloads to the client's registered handlers through the normal +* handler machinery, and these are the schemas that dispatch parses them +* with: lenient where the anchor's wire-true artifacts are strict (an +* embedded request never carries the per-request `_meta` envelope), exact +* where the vocabulary forks (the sampling shapes compose the forked +* SamplingMessage/Tool payloads). +* +* Registry membership is intentionally NOT granted here — these methods stay +* absent from the 2026-era request registry (a peer sending one as a wire +* request still gets −32601 by absence). Only the codec's +* `inputRequestSchema`/`inputResponseSchema` accessors expose them. +*/ +/** The embedded input-request methods of the 2026-07-28 revision. */ +const INPUT_REQUEST_METHODS_2026 = [ + "elicitation/create", + "sampling/createMessage", + "roots/list" +]; +let maps; +function inputSchemaMaps() { + if (maps) return maps; + const s = buildSchemas2026(); + maps = { + request: { + "elicitation/create": schemas_object({ + method: literal("elicitation/create"), + params: s.ElicitRequestParamsSchema + }), + "sampling/createMessage": schemas_object({ + method: literal("sampling/createMessage"), + params: s.CreateMessageRequestParamsSchema + }), + "roots/list": schemas_object({ + method: literal("roots/list"), + params: looseObject({}).optional() + }) + }, + response: { + "elicitation/create": s.ElicitResultSchema, + "sampling/createMessage": s.CreateMessageResultSchema, + "roots/list": s.ListRootsResultSchema + } + }; + return maps; +} +/** +* Forces the lazy embedded-request maps (and, through them, the era's schema +* memo). Warm-up hook for `preloadSchemas()` — no-op once the maps exist. +*/ +function warmInputSchemaMaps2026() { + inputSchemaMaps(); +} +function isInputRequestMethod2026(method) { + return INPUT_REQUEST_METHODS_2026.includes(method); +} +function getInputRequestSchema2026(method) { + return isInputRequestMethod2026(method) ? inputSchemaMaps().request[method] : void 0; +} +function getInputResponseSchema2026(method) { + return isInputRequestMethod2026(method) ? inputSchemaMaps().response[method] : void 0; +} + +//#endregion +//#region ../core-internal/src/wire/rev2026-07-28/registry.ts +const requestMethodKeys = { + "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 +}; +const notificationMethodKeys = { + "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 +}; +/** The 2026-era request-method set (registry membership = the deletion story). */ +function hasRequestMethod2026(method) { + return Object.prototype.hasOwnProperty.call(requestMethodKeys, method); +} +/** The 2026-era notification-method set. */ +function hasNotificationMethod2026(method) { + return Object.prototype.hasOwnProperty.call(notificationMethodKeys, method); +} +/** Result-map membership (same key set as the request map on this era). */ +function hasResultMethod2026(method) { + return Object.prototype.hasOwnProperty.call(requestMethodKeys, method); +} +function getRequestSchema2026(method) { + return hasRequestMethod2026(method) ? buildSchemas2026().dispatchRequestSchemas[method] : void 0; +} +function getResultSchema2026(method) { + return hasResultMethod2026(method) ? buildSchemas2026().dispatchResultSchemas[method] : void 0; +} +function getNotificationSchema2026(method) { + return hasNotificationMethod2026(method) ? buildSchemas2026().notificationSchemas2026[method] : void 0; +} +/** Registry method lists (for the spec-method universe and the CI registry-diff oracle). */ +const rev2026RequestMethods = Object.keys(requestMethodKeys); +const rev2026NotificationMethods = Object.keys(notificationMethodKeys); + +//#endregion +//#region ../core-internal/src/wire/rev2026-07-28/codec.ts +function isPlainObject$4(value) { + return value !== null && typeof value === "object" && !Array.isArray(value); +} +/** Tri-state wrap of an optional Zod schema lookup (the function-only contract). */ +function triState(schema, raw) { + if (schema === void 0) return { + ok: false, + reason: "not-in-era" + }; + const parsed = schema.safeParse(raw); + return parsed.success ? { + ok: true, + value: parsed.data + } : { + ok: false, + reason: "invalid", + message: String(parsed.error) + }; +} +const NOT_IN_ERA = { + ok: false, + reason: "not-in-era" +}; +/** +* The reserved `_meta` keys an envelope must carry on this era (in reporting +* order). `clientInfo` is NOT here: spec PR #3002 demoted it to SHOULD, so a +* request without it is accepted (a present-but-malformed value still fails +* the envelope schema parse below). +*/ +const REQUIRED_ENVELOPE_KEYS = [auth_CUe6YdwF_PROTOCOL_VERSION_META_KEY, auth_CUe6YdwF_CLIENT_CAPABILITIES_META_KEY]; +/** Strip the known deleted-field set from an outbound result (Q1-SD3 iii). */ +function enforceDeletedFields(method, result) { + let next = result; + let copied = false; + const copy = () => { + if (!copied) { + next = { ...next }; + copied = true; + } + return next; + }; + const tools = result.tools; + if (method === "tools/list" && Array.isArray(tools) && tools.some((tool) => isPlainObject$4(tool) && "execution" in tool)) copy().tools = tools.map((tool) => { + if (!isPlainObject$4(tool) || !("execution" in tool)) return tool; + const rest = { ...tool }; + delete rest["execution"]; + return rest; + }); + const capabilities = result.capabilities; + if (isPlainObject$4(capabilities) && "tasks" in capabilities) { + const rest = { ...capabilities }; + delete rest["tasks"]; + copy().capabilities = rest; + } + return next; +} +const rev2026Codec = { + era: "2026-07-28", + hasRequestMethod: hasRequestMethod2026, + hasNotificationMethod: hasNotificationMethod2026, + hasInputRequestMethod: (method) => getInputRequestSchema2026(method) !== void 0, + validateRequest: (method, raw) => triState(getRequestSchema2026(method), raw), + validateResult: (method, raw) => triState(getResultSchema2026(method), raw), + validateNotification: (method, raw) => triState(getNotificationSchema2026(method), raw), + validateInputRequest: (method, raw) => triState(getInputRequestSchema2026(method), raw), + validateInputResponse: (method, raw) => triState(getInputResponseSchema2026(method), raw), + samplingResultVariant: () => NOT_IN_ERA, + outboundEnvelope(material) { + return { + [auth_CUe6YdwF_PROTOCOL_VERSION_META_KEY]: material.protocolVersion, + [auth_CUe6YdwF_CLIENT_INFO_META_KEY]: material.clientInfo, + [auth_CUe6YdwF_CLIENT_CAPABILITIES_META_KEY]: material.clientCapabilities, + ...material.logLevel !== void 0 && { [LOG_LEVEL_META_KEY]: material.logLevel } + }; + }, + validateEnvelopeMeta(meta) { + const issues = []; + for (const key of REQUIRED_ENVELOPE_KEYS) if (!(key in meta)) issues.push({ + key, + problem: "missing" + }); + const parsed = buildSchemas2026().RequestMetaEnvelopeSchema.safeParse(meta); + if (!parsed.success) for (const issue of parsed.error.issues) { + const path = issue.path.map(String); + const key = path.length > 0 ? path.join(".") : "_meta"; + if (path.length === 1 && issues.some((existing) => existing.key === key && existing.problem === "missing")) continue; + issues.push({ + key, + problem: issue.message + }); + } + return issues; + }, + projectCallToolResult: (result) => appendTextFallbackForNonObject(result), + inputRequestSchema: getInputRequestSchema2026, + decodeResult(method, raw) { + if (!isPlainObject$4(raw)) return { + kind: "invalid", + error: new src_CX2iR2pK_SdkError(src_CX2iR2pK_SdkErrorCode.InvalidResult, `Invalid result for ${method}: not an object`, { method }) + }; + const rawResultType = raw["resultType"]; + if (rawResultType === void 0) return { + kind: "invalid", + error: new src_CX2iR2pK_SdkError(src_CX2iR2pK_SdkErrorCode.InvalidResult, `Invalid result for ${method}: missing required resultType — servers implementing protocol revision 2026-07-28 MUST include it (the absent-means-complete bridge applies only to earlier-revision servers)`, { + method, + violation: "missing-resultType" + }) + }; + if (typeof rawResultType !== "string") return { + kind: "invalid", + error: new src_CX2iR2pK_SdkError(src_CX2iR2pK_SdkErrorCode.InvalidResult, `Invalid result for ${method}: non-string resultType`, { + method, + resultType: rawResultType + }) + }; + if (rawResultType === "input_required") { + const rawInputRequests = raw["inputRequests"]; + const inputRequests = isPlainObject$4(rawInputRequests) ? rawInputRequests : {}; + const requestState = raw["requestState"]; + if (Object.keys(inputRequests).length === 0 && typeof requestState !== "string") return { + kind: "invalid", + error: new src_CX2iR2pK_SdkError(src_CX2iR2pK_SdkErrorCode.InvalidResult, `Invalid result for ${method}: input_required carries neither inputRequests nor requestState (every input_required result must include at least one of the two)`, { + method, + violation: "input-required-missing-both" + }) + }; + return { + kind: "input_required", + inputRequests, + ...typeof requestState === "string" && { requestState } + }; + } + if (rawResultType !== "complete") return { + kind: "invalid", + error: new src_CX2iR2pK_SdkError(src_CX2iR2pK_SdkErrorCode.UnsupportedResultType, `Unsupported result type '${rawResultType}' for ${method}`, { + resultType: rawResultType, + method + }) + }; + const wireResultSchemas = getWireResultSchemas(); + const wireSchema = Object.hasOwn(wireResultSchemas, method) ? wireResultSchemas[method] : void 0; + if (wireSchema !== void 0) { + const parsed = wireSchema.safeParse(raw); + if (!parsed.success) return { + kind: "invalid", + error: new src_CX2iR2pK_SdkError(src_CX2iR2pK_SdkErrorCode.InvalidResult, `Invalid result for ${method}: ${parsed.error}`, { method }) + }; + } + const lifted = { ...raw }; + delete lifted["resultType"]; + return { + kind: "complete", + result: lifted + }; + }, + encodeResult(method, result, serverInfo) { + return stampServerInfoMeta(fillCacheFields(method, stampResultType(method, enforceDeletedFields(method, result))), serverInfo); + }, + encodeErrorCode: (code) => code === -32002 ? -32602 : code, + checkInboundEnvelope(material) { + if (material.envelope === void 0) return "Request is missing the required _meta envelope for protocol revision 2026-07-28 (io.modelcontextprotocol/protocolVersion, io.modelcontextprotocol/clientCapabilities)"; + const parsed = buildSchemas2026().RequestMetaEnvelopeSchema.safeParse(material.envelope); + if (!parsed.success) return `Invalid _meta envelope for protocol revision 2026-07-28: ${parsed.error.issues.map((issue) => issue.message).join("; ")}`; + } +}; +/** Wire-true result wrappers consulted by decode step 2, keyed by method — +* built once through the era's schema memo on the first decode. */ +let wireResultSchemasMemo; +function getWireResultSchemas() { + if (wireResultSchemasMemo) return wireResultSchemasMemo; + const s = buildSchemas2026(); + wireResultSchemasMemo = { + "tools/call": s.CallToolResultSchema, + "tools/list": s.ListToolsResultSchema, + "prompts/get": s.GetPromptResultSchema, + "prompts/list": s.ListPromptsResultSchema, + "resources/list": s.ListResourcesResultSchema, + "resources/templates/list": s.ListResourceTemplatesResultSchema, + "resources/read": s.ReadResourceResultSchema, + "completion/complete": s.CompleteResultSchema, + "server/discover": s.DiscoverResultSchema + }; + return wireResultSchemasMemo; +} +/** +* Forces the lazy wire-result wrapper map (and, through it, the era's schema +* memo). Warm-up hook for `preloadSchemas()` — no-op once the map exists. +*/ +function warmWireResultSchemas2026() { + getWireResultSchemas(); +} + +//#endregion +//#region ../core-internal/src/wire/codec.ts +/** +* The modern wire revision literal. Internal only — deliberately NOT a public +* constant (G-D2-4: no public modern-version constant ships before era-aware +* list semantics exist). +*/ +const src_CX2iR2pK_MODERN_WIRE_REVISION = "2026-07-28"; +/** +* Era resolution, many-to-one (Q1-SD1): every modern-era revision +* (`>= 2026-07-28`) → the 2026-era codec; every legacy revision (the five +* `SUPPORTED_PROTOCOL_VERSIONS`) and `undefined`/unknown → the 2025-era +* codec (the DV-13 default posture — hand-constructed instances and +* unclassified traffic are legacy-era). This is the same era predicate the +* rest of the SDK uses ({@link isModernProtocolVersion}); a pinned modern +* revision other than the literal '2026-07-28' must still resolve modern. +*/ +function src_CX2iR2pK_codecForVersion(version) { + return version !== void 0 && isModernProtocolVersion(version) ? rev2026Codec : rev2025Codec; +} +/** +* The wire era an edge classification names (Q2 — produced at the +* transport/entry edge; this layer only CONSUMES it). The dispatch funnel no +* longer resolves a codec FROM the classification: era is instance state, and +* a classified inbound message is VALIDATED against the instance era — a +* mismatch is an entry/routing error, never a per-message era switch. The +* exact `revision` wins over the coarse era flag when both are present. +*/ +function classifiedWireEra(classification) { + if (classification.revision !== void 0) return src_CX2iR2pK_codecForVersion(classification.revision).era; + return classification.era === "modern" ? rev2026Codec.era : rev2025Codec.era; +} +/** +* The derived spec-method universe: the union of every codec registry. A +* method in this set is era-gated at dispatch and send time; a method outside +* it is a consumer-owned extension method (era-blind, schema-explicit). +* Derived from the registries — never hand-curated (the LEGACY_ONLY_METHODS +* table class is exactly what registry membership replaces). +*/ +function isSpecRequestMethod(method) { + return ALL_CODECS.some((codec) => codec.hasRequestMethod(method)); +} +function isSpecNotificationMethod(method) { + return ALL_CODECS.some((codec) => codec.hasNotificationMethod(method)); +} +const ALL_CODECS = [rev2025Codec, rev2026Codec]; + +//#endregion +//#region ../core-internal/src/shared/envelope.ts +/** +* Per-request `_meta` envelope claim helpers (protocol revision 2026-07-28). +* +* Pure, value-returning helpers used by the inbound HTTP classifier +* (`classifyInboundRequest`): claim detection and envelope validation with +* self-identifying issues. The envelope schema itself stays the wire layer's +* single source of truth (`RequestMetaEnvelopeSchema`); this module only maps +* its outcomes into the shapes the validation ladder emits. +* +* Claim detection is deliberately narrow: a message claims the 2026-07-28 +* envelope mechanism if and only if the reserved protocol-version `_meta` key +* is present in `params._meta`. Other reserved keys (client info, client +* capabilities, log level), a bare `progressToken`, or unrelated keys under +* the `io.modelcontextprotocol/` prefix do NOT constitute a claim on their +* own — but once the claim key is present, a malformed envelope is a +* validation error, never a silent fall back to legacy handling. +* +* The wire-exact envelope schema, the required-key set, and the per-key issue +* mapping live in the wire layer (the 2026-era codec's `validateEnvelopeMeta`). +* This module never reaches into a per-revision wire module directly. +*/ +function isPlainObject$3(value) { + return value !== null && typeof value === "object" && !Array.isArray(value); +} +/** The `_meta` object of a message's params, when present. */ +function src_CX2iR2pK_requestMetaOf(params) { + if (!isPlainObject$3(params)) return void 0; + const meta = params["_meta"]; + return isPlainObject$3(meta) ? meta : void 0; +} +/** +* Whether a message's params carry the per-request envelope claim: the +* reserved protocol-version `_meta` key is present (regardless of whether the +* rest of the envelope is valid — validation is a separate, later step). +*/ +function src_CX2iR2pK_hasEnvelopeClaim(params) { + const meta = src_CX2iR2pK_requestMetaOf(params); + return meta !== void 0 && PROTOCOL_VERSION_META_KEY in meta; +} +/** +* The protocol version named by a message's envelope claim, when the claim is +* present and carries a string value. A present claim with a non-string value +* still counts as a claim ({@linkcode hasEnvelopeClaim}); it surfaces as a +* validation issue instead of a version. +*/ +function src_CX2iR2pK_envelopeClaimVersion(params) { + const value = src_CX2iR2pK_requestMetaOf(params)?.[PROTOCOL_VERSION_META_KEY]; + return typeof value === "string" ? value : void 0; +} +/** +* Validates a request's `_meta` object as a 2026-07-28 per-request envelope +* and reports problems as self-identifying issues (which key, what problem). +* +* Returns an empty array when the envelope is valid. Missing required keys are +* reported first (as `problem: 'missing'`), then schema violations inside +* present keys, in a stable order. +*/ +function src_CX2iR2pK_validateEnvelopeMeta(meta) { + return src_CX2iR2pK_codecForVersion(src_CX2iR2pK_MODERN_WIRE_REVISION).validateEnvelopeMeta(meta); +} + +//#endregion +//#region ../core-internal/src/types/schemas.ts +var schemas_exports = /* @__PURE__ */ __exportAll({ + AnnotationsSchema: () => AnnotationsSchema, + AudioContentSchema: () => AudioContentSchema, + BaseMetadataSchema: () => BaseMetadataSchema, + BaseRequestParamsSchema: () => BaseRequestParamsSchema, + BlobResourceContentsSchema: () => BlobResourceContentsSchema, + BooleanSchemaSchema: () => BooleanSchemaSchema, + CallToolRequestParamsSchema: () => CallToolRequestParamsSchema, + CallToolRequestSchema: () => CallToolRequestSchema, + CallToolResultSchema: () => auth_CUe6YdwF_CallToolResultSchema, + CancelTaskRequestSchema: () => CancelTaskRequestSchema, + CancelTaskResultSchema: () => CancelTaskResultSchema, + CancelledNotificationParamsSchema: () => CancelledNotificationParamsSchema, + CancelledNotificationSchema: () => CancelledNotificationSchema, + ClientCapabilitiesSchema: () => ClientCapabilitiesSchema, + ClientNotificationSchema: () => ClientNotificationSchema, + ClientRequestSchema: () => ClientRequestSchema, + ClientResultSchema: () => ClientResultSchema, + ClientTasksCapabilitySchema: () => ClientTasksCapabilitySchema, + CompatibilityCallToolResultSchema: () => CompatibilityCallToolResultSchema, + CompleteRequestParamsSchema: () => CompleteRequestParamsSchema, + CompleteRequestSchema: () => CompleteRequestSchema, + CompleteResultSchema: () => CompleteResultSchema, + ContentBlockSchema: () => ContentBlockSchema, + CreateMessageRequestParamsSchema: () => CreateMessageRequestParamsSchema, + CreateMessageRequestSchema: () => CreateMessageRequestSchema, + CreateMessageResultSchema: () => CreateMessageResultSchema, + CreateMessageResultWithToolsSchema: () => CreateMessageResultWithToolsSchema, + CreateTaskResultSchema: () => CreateTaskResultSchema, + CursorSchema: () => CursorSchema, + DiscoverRequestSchema: () => DiscoverRequestSchema, + DiscoverResultSchema: () => DiscoverResultSchema, + ElicitRequestFormParamsSchema: () => ElicitRequestFormParamsSchema, + ElicitRequestParamsSchema: () => ElicitRequestParamsSchema, + ElicitRequestSchema: () => ElicitRequestSchema, + ElicitRequestURLParamsSchema: () => ElicitRequestURLParamsSchema, + ElicitResultSchema: () => ElicitResultSchema, + ElicitationCompleteNotificationParamsSchema: () => ElicitationCompleteNotificationParamsSchema, + ElicitationCompleteNotificationSchema: () => ElicitationCompleteNotificationSchema, + EmbeddedResourceSchema: () => EmbeddedResourceSchema, + EmptyResultSchema: () => EmptyResultSchema, + EnumSchemaSchema: () => EnumSchemaSchema, + GetPromptRequestParamsSchema: () => GetPromptRequestParamsSchema, + GetPromptRequestSchema: () => GetPromptRequestSchema, + GetPromptResultSchema: () => GetPromptResultSchema, + GetTaskPayloadRequestSchema: () => GetTaskPayloadRequestSchema, + GetTaskPayloadResultSchema: () => GetTaskPayloadResultSchema, + GetTaskRequestSchema: () => GetTaskRequestSchema, + GetTaskResultSchema: () => GetTaskResultSchema, + IconSchema: () => IconSchema, + IconsSchema: () => IconsSchema, + ImageContentSchema: () => ImageContentSchema, + ImplementationSchema: () => ImplementationSchema, + InitializeRequestParamsSchema: () => InitializeRequestParamsSchema, + InitializeRequestSchema: () => auth_CUe6YdwF_InitializeRequestSchema, + InitializeResultSchema: () => InitializeResultSchema, + InitializedNotificationSchema: () => auth_CUe6YdwF_InitializedNotificationSchema, + JSONArraySchema: () => JSONArraySchema, + JSONObjectSchema: () => JSONObjectSchema, + JSONRPCErrorResponseSchema: () => JSONRPCErrorResponseSchema, + JSONRPCMessageSchema: () => auth_CUe6YdwF_JSONRPCMessageSchema, + JSONRPCNotificationSchema: () => JSONRPCNotificationSchema, + JSONRPCRequestSchema: () => JSONRPCRequestSchema, + JSONRPCResponseSchema: () => auth_CUe6YdwF_JSONRPCResponseSchema, + JSONRPCResultResponseSchema: () => JSONRPCResultResponseSchema, + JSONValueSchema: () => JSONValueSchema, + LegacyTitledEnumSchemaSchema: () => LegacyTitledEnumSchemaSchema, + ListChangedOptionsBaseSchema: () => ListChangedOptionsBaseSchema, + ListPromptsRequestSchema: () => ListPromptsRequestSchema, + ListPromptsResultSchema: () => ListPromptsResultSchema, + ListResourceTemplatesRequestSchema: () => ListResourceTemplatesRequestSchema, + ListResourceTemplatesResultSchema: () => ListResourceTemplatesResultSchema, + ListResourcesRequestSchema: () => ListResourcesRequestSchema, + ListResourcesResultSchema: () => ListResourcesResultSchema, + ListRootsRequestSchema: () => ListRootsRequestSchema, + ListRootsResultSchema: () => ListRootsResultSchema, + ListTasksRequestSchema: () => ListTasksRequestSchema, + ListTasksResultSchema: () => ListTasksResultSchema, + ListToolsRequestSchema: () => ListToolsRequestSchema, + ListToolsResultSchema: () => ListToolsResultSchema, + LoggingLevelSchema: () => LoggingLevelSchema, + LoggingMessageNotificationParamsSchema: () => LoggingMessageNotificationParamsSchema, + LoggingMessageNotificationSchema: () => LoggingMessageNotificationSchema, + ModelHintSchema: () => ModelHintSchema, + ModelPreferencesSchema: () => ModelPreferencesSchema, + MultiSelectEnumSchemaSchema: () => MultiSelectEnumSchemaSchema, + NotificationSchema: () => NotificationSchema, + NotificationsParamsSchema: () => NotificationsParamsSchema, + NumberSchemaSchema: () => NumberSchemaSchema, + PaginatedRequestParamsSchema: () => PaginatedRequestParamsSchema, + PaginatedRequestSchema: () => PaginatedRequestSchema, + PaginatedResultSchema: () => PaginatedResultSchema, + PingRequestSchema: () => PingRequestSchema, + PrimitiveSchemaDefinitionSchema: () => PrimitiveSchemaDefinitionSchema, + ProgressNotificationParamsSchema: () => ProgressNotificationParamsSchema, + ProgressNotificationSchema: () => ProgressNotificationSchema, + ProgressSchema: () => ProgressSchema, + ProgressTokenSchema: () => ProgressTokenSchema, + PromptArgumentSchema: () => PromptArgumentSchema, + PromptListChangedNotificationSchema: () => PromptListChangedNotificationSchema, + PromptMessageSchema: () => PromptMessageSchema, + PromptReferenceSchema: () => PromptReferenceSchema, + PromptSchema: () => PromptSchema, + ReadResourceRequestParamsSchema: () => ReadResourceRequestParamsSchema, + ReadResourceRequestSchema: () => ReadResourceRequestSchema, + ReadResourceResultSchema: () => ReadResourceResultSchema, + RelatedTaskMetadataSchema: () => RelatedTaskMetadataSchema, + RequestIdSchema: () => RequestIdSchema, + RequestMetaSchema: () => RequestMetaSchema, + RequestSchema: () => RequestSchema, + ResourceContentsSchema: () => ResourceContentsSchema, + ResourceLinkSchema: () => ResourceLinkSchema, + ResourceListChangedNotificationSchema: () => ResourceListChangedNotificationSchema, + ResourceRequestParamsSchema: () => ResourceRequestParamsSchema, + ResourceSchema: () => ResourceSchema, + ResourceTemplateReferenceSchema: () => ResourceTemplateReferenceSchema, + ResourceTemplateSchema: () => ResourceTemplateSchema, + ResourceUpdatedNotificationParamsSchema: () => ResourceUpdatedNotificationParamsSchema, + ResourceUpdatedNotificationSchema: () => ResourceUpdatedNotificationSchema, + ResultMetaObjectSchema: () => ResultMetaObjectSchema, + ResultSchema: () => ResultSchema, + RoleSchema: () => RoleSchema, + RootSchema: () => RootSchema, + RootsListChangedNotificationSchema: () => RootsListChangedNotificationSchema, + SamplingContentSchema: () => SamplingContentSchema, + SamplingMessageContentBlockSchema: () => SamplingMessageContentBlockSchema, + SamplingMessageSchema: () => SamplingMessageSchema, + ServerCapabilitiesSchema: () => ServerCapabilitiesSchema, + ServerNotificationSchema: () => ServerNotificationSchema, + ServerRequestSchema: () => ServerRequestSchema, + ServerResultSchema: () => ServerResultSchema, + ServerTasksCapabilitySchema: () => ServerTasksCapabilitySchema, + SetLevelRequestParamsSchema: () => SetLevelRequestParamsSchema, + SetLevelRequestSchema: () => SetLevelRequestSchema, + SingleSelectEnumSchemaSchema: () => SingleSelectEnumSchemaSchema, + StringSchemaSchema: () => StringSchemaSchema, + SubscribeRequestParamsSchema: () => SubscribeRequestParamsSchema, + SubscribeRequestSchema: () => SubscribeRequestSchema, + SubscriptionFilterSchema: () => SubscriptionFilterSchema, + SubscriptionsAcknowledgedNotificationParamsSchema: () => SubscriptionsAcknowledgedNotificationParamsSchema, + SubscriptionsAcknowledgedNotificationSchema: () => SubscriptionsAcknowledgedNotificationSchema, + SubscriptionsListenRequestParamsSchema: () => SubscriptionsListenRequestParamsSchema, + SubscriptionsListenRequestSchema: () => SubscriptionsListenRequestSchema, + SubscriptionsListenResultMetaSchema: () => SubscriptionsListenResultMetaSchema, + SubscriptionsListenResultSchema: () => SubscriptionsListenResultSchema, + TaskAugmentedRequestParamsSchema: () => auth_CUe6YdwF_TaskAugmentedRequestParamsSchema, + TaskCreationParamsSchema: () => TaskCreationParamsSchema, + TaskMetadataSchema: () => TaskMetadataSchema, + TaskSchema: () => TaskSchema, + TaskStatusNotificationParamsSchema: () => TaskStatusNotificationParamsSchema, + TaskStatusNotificationSchema: () => TaskStatusNotificationSchema, + TaskStatusSchema: () => TaskStatusSchema, + TextContentSchema: () => TextContentSchema, + TextResourceContentsSchema: () => TextResourceContentsSchema, + TitledMultiSelectEnumSchemaSchema: () => TitledMultiSelectEnumSchemaSchema, + TitledSingleSelectEnumSchemaSchema: () => TitledSingleSelectEnumSchemaSchema, + ToolAnnotationsSchema: () => ToolAnnotationsSchema, + ToolChoiceSchema: () => ToolChoiceSchema, + ToolExecutionSchema: () => ToolExecutionSchema, + ToolListChangedNotificationSchema: () => ToolListChangedNotificationSchema, + ToolResultContentSchema: () => ToolResultContentSchema, + ToolSchema: () => ToolSchema, + ToolUseContentSchema: () => ToolUseContentSchema, + UnsubscribeRequestParamsSchema: () => UnsubscribeRequestParamsSchema, + UnsubscribeRequestSchema: () => UnsubscribeRequestSchema, + UntitledMultiSelectEnumSchemaSchema: () => UntitledMultiSelectEnumSchemaSchema, + UntitledSingleSelectEnumSchemaSchema: () => UntitledSingleSelectEnumSchemaSchema +}); + +//#endregion +//#region ../core-internal/src/types/guards.ts +/** +* Validates and parses an unknown value as a JSON-RPC message. +* +* Use this to validate incoming messages in custom transport implementations. +* Throws if the value does not conform to the JSON-RPC message schema. +* +* @param value - The value to validate (typically a parsed JSON object). +* @returns The validated {@linkcode JSONRPCMessage}. +* @throws If validation fails. +*/ +function parseJSONRPCMessage(value) { + return JSONRPCMessageSchema.parse(value); +} +const src_CX2iR2pK_isJSONRPCRequest = (value) => JSONRPCRequestSchema.safeParse(value).success; +const src_CX2iR2pK_isJSONRPCNotification = (value) => JSONRPCNotificationSchema.safeParse(value).success; +/** +* Checks if a value is a valid {@linkcode JSONRPCResultResponse}. +* @param value - The value to check. +* +* @returns True if the value is a valid {@linkcode JSONRPCResultResponse}, false otherwise. +*/ +const src_CX2iR2pK_isJSONRPCResultResponse = (value) => JSONRPCResultResponseSchema.safeParse(value).success; +/** +* Checks if a value is a valid {@linkcode JSONRPCErrorResponse}. +* @param value - The value to check. +* +* @returns True if the value is a valid {@linkcode JSONRPCErrorResponse}, false otherwise. +*/ +const src_CX2iR2pK_isJSONRPCErrorResponse = (value) => JSONRPCErrorResponseSchema.safeParse(value).success; +/** +* Checks if a value is a valid {@linkcode JSONRPCResponse} (either a result or error response). +* @param value - The value to check. +* +* @returns True if the value is a valid {@linkcode JSONRPCResponse}, false otherwise. +*/ +const isJSONRPCResponse = (value) => JSONRPCResponseSchema.safeParse(value).success; +/** +* Checks if a value is a valid {@linkcode CallToolResult}. +* +* This is a consumer-side VALUE check against the neutral model, not a wire +* validator: a raw wire object that additionally carries wire-only members +* (e.g. `resultType`) still passes through the loose index signature. Use a +* transport-level parse to validate raw wire traffic. +* +* @param value - The value to check. +* +* @returns True if the value is a valid {@linkcode CallToolResult}, false otherwise. +*/ +const isCallToolResult = (value) => { + if (typeof value !== "object" || value === null || value.content === void 0) return false; + return CallToolResultSchema.safeParse(value).success; +}; +/** +* Checks whether a value is an input-required result (protocol revision +* 2026-07-28): the multi-round-trip return shape discriminated by +* `resultType: 'input_required'`. +* +* This is a discriminator check, not a full validator — the at-least-one rule +* (`inputRequests` or `requestState`) is enforced by the `inputRequired()` +* builder and re-checked by the server seam for hand-built values. +* +* @param value - The value to check. +* @returns True if the value carries the `input_required` discriminator. +*/ +const isInputRequiredResult = (value) => typeof value === "object" && value !== null && !Array.isArray(value) && value.resultType === "input_required"; +/** +* Checks if a value is a valid {@linkcode TaskAugmentedRequestParams}. +* @param value - The value to check. +* +* @returns True if the value is a valid {@linkcode TaskAugmentedRequestParams}, false otherwise. +* +* @deprecated Recognizes 2025-11-25 task wire vocabulary, which has no SDK +* runtime; kept importable for interoperability only. +*/ +const isTaskAugmentedRequestParams = (value) => TaskAugmentedRequestParamsSchema.safeParse(value).success; +const src_CX2iR2pK_isInitializeRequest = (value) => InitializeRequestSchema.safeParse(value).success; +const isInitializedNotification = (value) => InitializedNotificationSchema.safeParse(value).success; +function assertCompleteRequestPrompt(request) { + if (request.params.ref.type !== "ref/prompt") throw new TypeError(`Expected CompleteRequestPrompt, but got ${request.params.ref.type}`); +} +function assertCompleteRequestResourceTemplate(request) { + if (request.params.ref.type !== "ref/resource") throw new TypeError(`Expected CompleteRequestResourceTemplate, but got ${request.params.ref.type}`); +} + +//#endregion +//#region ../core-internal/src/shared/mcpParamHeaders.ts +/** The fixed prefix every custom-parameter header carries. */ +const MCP_PARAM_HEADER_PREFIX = "Mcp-Param-"; +/** The schema-extension property name a tool's `inputSchema` carries. */ +const X_MCP_HEADER_KEY = "x-mcp-header"; +/** +* RFC 9110 §5.1 `token` syntax (`1*tchar`). Rejects empty, space, control +* characters (including CR/LF), and the listed delimiters. +*/ +const RFC9110_TOKEN = /^[!#$%&'*+\-.^_`|~0-9A-Za-z]+$/; +/** +* JSON Schema `type` values the spec admits on an `x-mcp-header` property. +* +* The spec text names `integer`, `string`, `boolean` and explicitly excludes +* `number`. The published conformance referee at the pinned release ships its +* `http-custom-headers` scenario with two `type: "number"` `x-mcp-header` +* parameters and expects the client to mirror them, so `number` is accepted +* here so that the conformance gate passes; the discrepancy is tracked +* upstream. Everything else (`object`, `array`, `null`, absent) is rejected. +*/ +const PERMITTED_X_MCP_HEADER_TYPES = new Set([ + "string", + "integer", + "boolean", + "number" +]); +/** +* Scan a tool's JSON-serialized `inputSchema` for `x-mcp-header` declarations +* and validate every constraint the spec places on them. Returns either the +* collected declarations (possibly empty) or the first violated constraint. +* +* The walk descends through `properties` at any depth (the spec's "any nesting +* depth" clause). The static-reachability MUST is enforced as a structural +* sweep: every position the chain MUST NOT pass through (`items`/ +* `additionalProperties`, `oneOf`/`anyOf`/`allOf`/`not`, `if`/`then`/`else`, +* `$defs`, `$ref` targets within `$defs`) is visited too, and an +* `x-mcp-header` found anywhere on that path invalidates the schema — "an +* annotation anywhere else makes the tool definition invalid". +*/ +function src_CX2iR2pK_scanXMcpHeaderDeclarations(inputSchema) { + const declarations = []; + const seenLower = /* @__PURE__ */ new Map(); + const visit = (node, path, reachable) => { + if (node === null || typeof node !== "object") return void 0; + const schema = node; + if (X_MCP_HEADER_KEY in schema) { + if (!reachable || path.length === 0) return `${pathName(path)}: x-mcp-header is only permitted on properties statically reachable via a chain of 'properties' keys (not under items, additionalProperties, oneOf/anyOf/allOf/not, if/then/else, or $ref)`; + const raw = schema[X_MCP_HEADER_KEY]; + if (typeof raw !== "string" || raw.length === 0) return `${pathName(path)}: x-mcp-header MUST be a non-empty string`; + if (!RFC9110_TOKEN.test(raw)) return `${pathName(path)}: x-mcp-header '${raw}' is not a valid RFC 9110 token (no spaces, control characters or HTTP delimiters)`; + const type = typeof schema.type === "string" ? schema.type : void 0; + if (type === void 0 || !PERMITTED_X_MCP_HEADER_TYPES.has(type)) return `${pathName(path)}: x-mcp-header is only permitted on primitive-typed properties (string, integer, boolean); got ${type ?? ""}`; + const lower = raw.toLowerCase(); + const prior = seenLower.get(lower); + if (prior !== void 0) return `x-mcp-header '${raw}' is not case-insensitively unique (also declared as '${prior}')`; + seenLower.set(lower, raw); + declarations.push({ + path, + headerName: raw, + type + }); + } + const properties = schema.properties; + if (properties !== null && typeof properties === "object") for (const [key, child] of Object.entries(properties)) { + const fault$1 = visit(child, [...path, key], reachable); + if (fault$1 !== void 0) return fault$1; + } + for (const k of NON_REACHABLE_SUBSCHEMA_KEYWORDS) { + const sub = schema[k]; + if (sub === void 0) continue; + const branches = Array.isArray(sub) ? sub : sub !== null && typeof sub === "object" && OBJECT_VALUED_SUBSCHEMA_KEYWORDS.has(k) ? Object.values(sub) : [sub]; + for (const branch of branches) { + const fault$1 = visit(branch, [...path, `<${k}>`], false); + if (fault$1 !== void 0) return fault$1; + } + } + }; + const fault = visit(inputSchema, [], true); + return fault === void 0 ? { + valid: true, + declarations + } : { + valid: false, + reason: fault + }; +} +/** +* JSON Schema keywords whose subschemas the SEP-2243 static-reachability +* constraint excludes from the `properties`-only chain. An `x-mcp-header` +* found under any of these invalidates the tool definition. +*/ +const NON_REACHABLE_SUBSCHEMA_KEYWORDS = [ + "items", + "prefixItems", + "contains", + "additionalProperties", + "unevaluatedProperties", + "unevaluatedItems", + "propertyNames", + "patternProperties", + "dependentSchemas", + "oneOf", + "anyOf", + "allOf", + "not", + "if", + "then", + "else", + "$defs", + "definitions" +]; +/** +* Subschema-carrying keywords whose value is a `name → subschema` object +* (not a single subschema or array of subschemas). The visit branches over +* `Object.values()` for these. +*/ +const OBJECT_VALUED_SUBSCHEMA_KEYWORDS = new Set([ + "patternProperties", + "dependentSchemas", + "$defs", + "definitions" +]); +function pathName(path) { + return path.length === 0 ? "" : path.join("."); +} +const BASE64_SENTINEL_PREFIX = "=?base64?"; +const BASE64_SENTINEL_SUFFIX = "?="; +const BASE64_CANONICAL = /^(?:[A-Za-z0-9+/]{4})*(?:[A-Za-z0-9+/]{2}==|[A-Za-z0-9+/]{3}=)?$/; +const CANONICAL_DECIMAL = /^-?\d+(\.\d+)?$/; +/** +* Convert a primitive argument value to its string representation per the +* spec's type-conversion rules: strings pass through, integers and numbers +* become their decimal string, booleans become lowercase `'true'` / `'false'`. +* Non-finite numbers and integers outside the safe range are refused (the +* caller treats `undefined` as "do not emit a header for this value"). +*/ +function mcpParamPrimitiveToString(value) { + if (typeof value === "string") return value; + if (typeof value === "boolean") return value ? "true" : "false"; + if (typeof value === "number") { + if (!Number.isFinite(value)) return void 0; + if (Number.isInteger(value) && !Number.isSafeInteger(value)) return void 0; + return String(value); + } +} +function base64ToUtf8(b64) { + const bin = atob(b64); + const bytes = new Uint8Array(bin.length); + for (let i = 0; i < bin.length; i++) bytes[i] = bin.codePointAt(i); + return new TextDecoder("utf-8", { fatal: true }).decode(bytes); +} +/** +* Decode an `Mcp-Param-*` header value: when it carries the Base64 sentinel, +* the payload is decoded as UTF-8; otherwise the value is returned as-is. +* Returns `undefined` when the sentinel is present but the payload is not +* canonical Base64 (or not valid UTF-8) — the spec requires servers to reject +* such values. +*/ +function decodeMcpParamValue(value) { + if (!(value.startsWith(BASE64_SENTINEL_PREFIX) && value.endsWith(BASE64_SENTINEL_SUFFIX))) return value; + const b64 = value.slice(9, value.length - 2); + if (!BASE64_CANONICAL.test(b64)) return void 0; + try { + return base64ToUtf8(b64); + } catch { + return; + } +} +function valueAtPath(root, path) { + let node = root; + for (const key of path) { + if (node === null || typeof node !== "object") return void 0; + node = node[key]; + } + return node; +} +/** +* The header/body comparison the server performs at tool-resolution time. +* +* For each `x-mcp-header` declaration on the named tool: when the body +* `arguments` carries a value, the matching `Mcp-Param-{Name}` header MUST be +* present and decode to an equal value; when the body value is `null` or +* absent the server MUST NOT expect the header (a present header is ignored). +* A sentinel-carrying header whose payload is not canonical Base64 / valid +* UTF-8 is rejected as invalid characters. +* +* Integer-typed declarations are compared numerically (the spec's SHOULD — +* `42.0` and `42` are equal); everything else is compared as decoded strings. +* +* Returns `undefined` when every check passes, or an +* {@linkcode InboundLadderRejection} carrying the same `-32020` +* (`HeaderMismatch`) shape the inbound classifier emits for the +* standard-header cross-checks — `400 Bad Request` with the disagreeing pair +* in `data.mismatch`. +*/ +function src_CX2iR2pK_validateMcpParamHeaders(declarations, args, headers) { + for (const decl of declarations) { + const headerKey = `${MCP_PARAM_HEADER_PREFIX}${decl.headerName}`; + const headerValue = headers.get(headerKey); + const bodyRaw = valueAtPath(args, decl.path); + if (bodyRaw === void 0 || bodyRaw === null) continue; + const bodyString = mcpParamPrimitiveToString(bodyRaw); + if (bodyString === void 0) continue; + if (headerValue === null) return paramHeaderMismatchRejection("param-header-missing", headerKey, `the body carries ${pathName(decl.path)}=${JSON.stringify(bodyRaw)} but the ${headerKey} header is absent`); + const decoded = decodeMcpParamValue(headerValue); + if (decoded === void 0) return paramHeaderMismatchRejection("param-header-invalid-encoding", headerKey, `the ${headerKey} header carries an invalid Base64 sentinel value`); + if (!((decl.type === "integer" || decl.type === "number") && CANONICAL_DECIMAL.test(decoded) && typeof bodyRaw === "number" ? Number(decoded) === bodyRaw : decoded === bodyString)) return paramHeaderMismatchRejection("param-header-mismatch", headerKey, `the ${headerKey} header decodes to ${JSON.stringify(decoded)} but the body carries ${pathName(decl.path)}=${JSON.stringify(bodyRaw)}`); + } +} +/** +* Build the `-32020` (`HeaderMismatch`) rejection for an `Mcp-Param-*` +* disagreement. Same shape as the inbound classifier's standard-header +* cross-check mismatch (HTTP `400`, `data.mismatch` naming the disagreeing +* pair, `settled: true`); only the rung differs because this check runs at the +* pre-dispatch step against a known tool's schema rather than at the edge. +*/ +function paramHeaderMismatchRejection(cell, header, body) { + return { + kind: "reject", + rung: "param-header-validation", + cell, + httpStatus: 400, + code: HEADER_MISMATCH_ERROR_CODE, + message: `Bad Request: the request headers and body disagree: ${body}`, + data: { mismatch: { + header, + body + } }, + settled: true + }; +} + +//#endregion +//#region ../core-internal/src/shared/inboundClassification.ts +/** +* Inbound HTTP request classification and the inbound validation ladder +* (protocol revision 2026-07-28). +* +* `classifyInboundRequest` is the body-primary era predicate for an HTTP +* entry that serves both protocol eras on one endpoint. It is evaluated +* exactly once, at the entry boundary, on the already-parsed request body: +* +* - `initialize` is a legacy-era request by definition (the modern era has no +* `initialize` handshake) — unless it carries a valid envelope claim naming +* a modern revision, in which case the claim wins and the request is +* classified like any other enveloped request (the modern era then answers +* it with method-not-found, exactly like every other method it does not +* define). +* - A request whose `params._meta` carries the reserved protocol-version key +* claims the per-request envelope mechanism and classifies into the era the +* named revision belongs to (a malformed envelope behind a present claim is +* a validation error, never a silent fall back to legacy handling). +* - A request without a claim is legacy-era traffic. +* - The `MCP-Protocol-Version` header is a cross-check only: it never +* upgrades or downgrades a body-derived classification, and a disagreement +* between header and body is an explicit ladder outcome. +* - Notifications carry no envelope claim of their own under the current +* spec, so for notification POSTs without a body claim the modern header is +* determinative; the `Mcp-Method` header is validated against the body when +* the message classifies modern and is never enforced on legacy traffic. +* A notification that does carry a claim is treated body-primary like a +* request, and a malformed claim is rejected the same way a request's +* malformed claim is — never silently resolved against the header. +* The notification-POST header cross-checks here are an SDK-defensive +* posture, not a spec requirement: the spec leaves header rules for posted +* notifications undefined (core client notifications do not occur over +* Streamable HTTP); applying the request rules symmetrically is what an +* ecosystem custom-notification POST expects, and the −32020 cells stay +* passing for them. +* - `GET`/`DELETE` (and any other non-`POST` method) are body-less 2025-era +* session operations: the modern era is `POST`-only, so they are routed to +* legacy serving when it is configured and rejected otherwise. +* - Array (batch) bodies are classified element-wise: an array containing a +* modern-claiming or invalid element is rejected, an all-legacy array is +* legacy traffic unchanged, and a single-element array is still an array. +* +* The classifier returns plain values (it never throws and never touches a +* transport): a routing outcome (`legacy`/`modern`) or a ladder rejection +* carrying the JSON-RPC error to emit and the HTTP status to emit it with. +* Legacy routing outcomes deliberately carry NO `MessageClassification` — +* legacy and hand-wired traffic is never classified, which keeps its +* dispatch behavior byte-identical to today's. +* +* Error codes for the modern-path rejection cells follow the published +* conformance suite (and the spec text it asserts): +* +* - A header/body cross-check mismatch (the `MCP-Protocol-Version` header +* disagreeing with the body, or the `Mcp-Method` header disagreeing with the +* body method) is rejected with `-32020` (`HeaderMismatch`) on HTTP 400. +* - A request whose protocol-version header names a modern revision but whose +* body carries no `_meta` envelope claim — including an envelope present but +* missing the required protocol-version key — is rejected with `-32602` +* (invalid params) naming the missing key(s), on HTTP 400. +* +* Should a future spec revision or conformance release change these +* assignments, the affected cells are re-derived against that release; the +* `settled` flag on {@linkcode InboundLadderRejection} stays available to mark +* a cell provisional again while such a change is in flight. +*/ +/** +* The error code emitted for header/body cross-check mismatches: the +* `MCP-Protocol-Version` header disagreeing with the body's envelope claim (or +* with the body's classification), and the `Mcp-Method` header disagreeing +* with the body method. +* +* `-32020` is the draft schema's `HEADER_MISMATCH` constant (the SEP-2243 +* `HeaderMismatch` code; the spec requires HTTP 400 for it), as also asserted +* by the published conformance suite for header-validation failures. It has no +* {@linkcode ProtocolErrorCode} member because it is not part of the 2025-era +* wire vocabulary; the validation ladder is its only emitter. +*/ +const HEADER_MISMATCH_ERROR_CODE = -32020; +/** +* The inbound validation ladder, expressed as data rather than control flow. +* +* The edge rungs are evaluated by {@linkcode classifyInboundRequest}; the +* dispatch rungs are evaluated by the protocol layer once the classified +* message is injected into a per-request server instance (the era registry +* gate, the envelope requiredness check, and per-method params validation). +* The client-capability rung is evaluated by the HTTP entry itself, +* pre-dispatch, on the validated envelope the classifier produced — see that +* rung's rationale for the ordering caveat. The order is the precedence: a +* request that fails several rungs is answered by the earliest one. +*/ +const INBOUND_VALIDATION_LADDER = [ + { + 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: [src_CX2iR2pK_ProtocolErrorCode.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: [HEADER_MISMATCH_ERROR_CODE, src_CX2iR2pK_ProtocolErrorCode.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: [src_CX2iR2pK_ProtocolErrorCode.InvalidParams], + conformance: ["server-stateless"], + rationale: "A present envelope claim with a malformed envelope — and a missing envelope on a request whose protocol-version header names a modern revision — 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: [src_CX2iR2pK_ProtocolErrorCode.MethodNotFound], + conformance: ["server-stateless"], + rationale: "Method existence outranks parameter validity: a method absent from the negotiated revision’s 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: [src_CX2iR2pK_ProtocolErrorCode.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: [HEADER_MISMATCH_ERROR_CODE], + conformance: ["http-header-validation"], + rationale: "SEP-2243 standard `Mcp-Method` / `Mcp-Name` headers — presence, sentinel decoding, and `Mcp-Name` ↔ body cross-check — are validated by the HTTP entry on a modern-classified request after the supported-revision gate and before dispatch. The classifier’s 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–6) are consulted." + }, + { + rung: "client-capabilities", + order: 8, + evaluatedAt: "pre-dispatch", + codes: [src_CX2iR2pK_ProtocolErrorCode.MissingRequiredClientCapability], + conformance: ["server-stateless"], + rationale: "The capability requirement is checked by the HTTP entry, pre-dispatch, against the validated envelope the classifier produced — 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: [HEADER_MISMATCH_ERROR_CODE], + conformance: ["http-custom-header-server-validation"], + rationale: "SEP-2243 `Mcp-Param-*` headers are validated against the named tool’s `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." + } +]; +/** +* HTTP status for ladder-originated JSON-RPC error codes. +* +* Keyed on origin, not on the bare code: this table only applies to errors +* the ladder (or a pre-handler protocol gate) produced. Errors produced by +* request handlers — whatever their code — stay in-band on HTTP 200, and are +* never mapped to an HTTP status by this table; in particular `-32603` and +* domain-specific codes never become a blanket 500. The single exception is +* `MissingRequiredClientCapability` (-32021) — see +* {@linkcode httpStatusForErrorCode}. +* +* `-32602` (invalid params) deliberately has NO entry: the only invalid-params +* rejection that maps to HTTP 400 is the classifier's own envelope rung +* short-circuit, which carries its HTTP status directly. A dispatch- or +* handler-produced invalid-params error is always in-band. +*/ +const src_CX2iR2pK_LADDER_ERROR_HTTP_STATUS = { + [src_CX2iR2pK_ProtocolErrorCode.ParseError]: 400, + [src_CX2iR2pK_ProtocolErrorCode.InvalidRequest]: 400, + [src_CX2iR2pK_ProtocolErrorCode.MethodNotFound]: 404, + [src_CX2iR2pK_ProtocolErrorCode.UnsupportedProtocolVersion]: 400, + [src_CX2iR2pK_ProtocolErrorCode.MissingRequiredClientCapability]: 400, + [HEADER_MISMATCH_ERROR_CODE]: 400 +}; +/** +* The HTTP status to answer a JSON-RPC error with, keyed on the error's +* origin. `in-band` errors (anything produced by a request handler) are +* HTTP 200 — the JSON-RPC error response is the payload, not an HTTP +* failure — with ONE exception: `MissingRequiredClientCapability` (-32021), +* whose 400 the spec mandates on the error itself with no origin condition, +* and which the SDK genuinely produces after dispatch (the `input_required` +* capability gate). A handler relaying some downstream peer's `-32020`/`-32022` +* is NOT that peer's spec error and stays in-band like every other handler +* code. `ladder` errors map through {@linkcode LADDER_ERROR_HTTP_STATUS}. +* +* The per-request transport intentionally does NOT delegate to this function: +* its `?? 400` ladder fallback is only correct for entry-gate codes known to +* the table, and would wrongly map dispatch-window errors outside it (a +* window `-32602` must stay in-band on 200). The transport indexes the table +* directly; keep the two in agreement when editing either. +*/ +function src_CX2iR2pK_httpStatusForErrorCode(code, origin) { + if (origin === "in-band") return code === src_CX2iR2pK_ProtocolErrorCode.MissingRequiredClientCapability ? 400 : 200; + return src_CX2iR2pK_LADDER_ERROR_HTTP_STATUS[code] ?? 400; +} +function src_CX2iR2pK_rejection(rung, cell, httpStatus, error, settled) { + return { + kind: "reject", + rung, + cell, + httpStatus, + code: error.code, + message: error.message, + ...error.data !== void 0 && { data: error.data }, + settled + }; +} +function crossCheckMismatch(cell, header, body, rung = "era-classification") { + return src_CX2iR2pK_rejection(rung, cell, 400, new src_CX2iR2pK_ProtocolError(HEADER_MISMATCH_ERROR_CODE, `Bad Request: the request headers and body disagree: ${body}`, { mismatch: { + header, + body + } }), true); +} +/** +* The methods whose body carries a `params.name` / `params.uri` value the +* `Mcp-Name` header must mirror, and which body field supplies it (SEP-2243 +* § Standard Request Headers, `Required For` column). +*/ +const MCP_NAME_HEADER_SOURCE = (/* unused pure expression or super */ null && ({ + "tools/call": "name", + "prompts/get": "name", + "resources/read": "uri" +})); +/** Strip RFC 9110 optional whitespace (SP / HTAB) around a field value in linear time. */ +function stripHttpOws(value) { + let start = 0; + while (start < value.length) { + const code = value.codePointAt(start); + if (code !== 9 && code !== 32) break; + start += 1; + } + let end = value.length; + while (end > start) { + const code = value.codePointAt(end - 1); + if (code !== 9 && code !== 32) break; + end -= 1; + } + return start === 0 && end === value.length ? value : value.slice(start, end); +} +/** +* SEP-2243 standard-header server-side validation, evaluated by the HTTP +* entry on a modern-classified request immediately after +* {@linkcode classifyInboundRequest} returns a modern route. +* +* Returns the `-32020` (`HeaderMismatch`) ladder rejection (HTTP `400`, +* `standard-header-validation` rung — the same shape +* {@linkcode classifyInboundRequest} already emits on the edge +* `era-classification` rung for the `MCP-Protocol-Version` and +* `Mcp-Method` *mismatch* cells) when: +* +* - the required `Mcp-Method` header is absent; +* - the required `Mcp-Name` header is absent on a `tools/call`, +* `prompts/get`, or `resources/read` request whose body carries the +* `params.name` / `params.uri` value the header mirrors; +* - the `Mcp-Name` header carries an invalid `=?base64?…?=` sentinel; or +* - the (decoded) `Mcp-Name` value disagrees with the body's +* `params.name` / `params.uri`. +* +* Returns `undefined` (pass) for notifications (the spec table reads +* "All requests"), for methods that have no `Mcp-Name` source, and when the +* headers agree with the body. Never enforced on legacy traffic — the entry +* only calls this on a modern route. +* +* Kept separate from {@linkcode classifyInboundRequest} so that a body-only +* call to the classifier (no headers passed) keeps routing a modern request +* unchanged: the classifier remains a pure body-primary router, and this +* function is the presence/`Mcp-Name` half of the standard-header rung the +* entry layers on top. +*/ +function src_CX2iR2pK_validateStandardRequestHeaders(request, route) { + if (route.messageKind !== "request") return; + const method = route.message.method; + if (request.mcpMethodHeader === void 0) return crossCheckMismatch("method-header-missing", "(missing)", `the body names method ${method} but the required Mcp-Method header is absent`, "standard-header-validation"); + const sourceField = Object.hasOwn(MCP_NAME_HEADER_SOURCE, method) ? MCP_NAME_HEADER_SOURCE[method] : void 0; + if (sourceField === void 0) return; + const sourceValue = route.message.params?.[sourceField]; + const bodyValue = typeof sourceValue === "string" ? sourceValue : void 0; + if (request.mcpNameHeader === void 0) { + if (bodyValue === void 0) return; + return crossCheckMismatch("name-header-missing", "(missing)", `the body carries params.${sourceField}="${bodyValue}" but the required Mcp-Name header is absent`, "standard-header-validation"); + } + const normalizedNameHeader = stripHttpOws(request.mcpNameHeader); + const decoded = decodeMcpParamValue(normalizedNameHeader); + if (decoded === void 0) return crossCheckMismatch("name-header-invalid-encoding", normalizedNameHeader, "the Mcp-Name header carries an invalid Base64 sentinel value", "standard-header-validation"); + if (bodyValue !== void 0 && decoded !== bodyValue) return crossCheckMismatch("name-header-mismatch", normalizedNameHeader, `the body carries params.${sourceField}="${bodyValue}" but the Mcp-Name header names "${decoded}"`, "standard-header-validation"); +} +function isPlainObject$2(value) { + return value !== null && typeof value === "object" && !Array.isArray(value); +} +function classificationForClaim(claimedVersion) { + if (claimedVersion === void 0) return { era: "modern" }; + return { + era: isModernProtocolVersion(claimedVersion) ? "modern" : "legacy", + revision: claimedVersion + }; +} +/** +* Whether a request's params carry a per-request envelope claim that is both +* well-formed and names a modern protocol revision. +* +* Used by the `initialize` precedence rule: only such a claim overrides the +* `initialize` ⇒ legacy-handshake classification — a request carrying a valid +* modern envelope is a modern request regardless of its method name, and the +* modern era then answers `initialize` exactly like any other method it does +* not define (method-not-found). A malformed claim, or one naming a pre-2026 +* revision, keeps the legacy-handshake routing unchanged. +* +* Exported on the core internal barrel for the stdio serving entry, which +* applies the same precedence rule to a connection's opening message; not +* public API. +*/ +function src_CX2iR2pK_carriesValidModernEnvelopeClaim(params) { + if (!src_CX2iR2pK_hasEnvelopeClaim(params)) return false; + const claimedVersion = src_CX2iR2pK_envelopeClaimVersion(params); + if (claimedVersion === void 0 || !isModernProtocolVersion(claimedVersion)) return false; + const meta = src_CX2iR2pK_requestMetaOf(params); + return meta !== void 0 && src_CX2iR2pK_validateEnvelopeMeta(meta).length === 0; +} +function classifyBatch(body) { + if (body.length === 0) return src_CX2iR2pK_rejection("jsonrpc-shape", "empty-batch", 400, new src_CX2iR2pK_ProtocolError(src_CX2iR2pK_ProtocolErrorCode.InvalidRequest, "Bad Request: empty JSON-RPC batch"), true); + for (const element of body) { + if (src_CX2iR2pK_hasEnvelopeClaim(isPlainObject$2(element) ? element["params"] : void 0)) return src_CX2iR2pK_rejection("jsonrpc-shape", "batch-with-modern-element", 400, new src_CX2iR2pK_ProtocolError(src_CX2iR2pK_ProtocolErrorCode.InvalidRequest, "Bad Request: JSON-RPC batches may not contain requests for protocol revision 2026-07-28 or later"), true); + if (!(src_CX2iR2pK_isJSONRPCRequest(element) || src_CX2iR2pK_isJSONRPCNotification(element) || src_CX2iR2pK_isJSONRPCResultResponse(element) || src_CX2iR2pK_isJSONRPCErrorResponse(element))) return src_CX2iR2pK_rejection("jsonrpc-shape", "batch-with-invalid-element", 400, new src_CX2iR2pK_ProtocolError(src_CX2iR2pK_ProtocolErrorCode.InvalidRequest, "Bad Request: JSON-RPC batch contains an invalid message"), true); + } + return { + kind: "legacy", + reason: "batch" + }; +} +function classifyRequestBody(request, body) { + const params = body.params; + const method = body.method; + const headerVersion = request.protocolVersionHeader; + const headerNamesModern = headerVersion !== void 0 && isModernProtocolVersion(headerVersion); + if (method === "initialize" && !src_CX2iR2pK_carriesValidModernEnvelopeClaim(params)) { + if (headerNamesModern) return crossCheckMismatch("initialize-with-modern-header", headerVersion, "an initialize request (legacy handshake) was sent with a modern MCP-Protocol-Version header"); + const requestedVersion = isPlainObject$2(params) && typeof params["protocolVersion"] === "string" ? params["protocolVersion"] : void 0; + return { + kind: "legacy", + reason: "initialize", + ...requestedVersion !== void 0 && { requestedVersion } + }; + } + if (src_CX2iR2pK_hasEnvelopeClaim(params)) { + const meta = src_CX2iR2pK_requestMetaOf(params); + const firstIssue = (meta === void 0 ? [] : src_CX2iR2pK_validateEnvelopeMeta(meta))[0]; + if (firstIssue !== void 0) return src_CX2iR2pK_rejection("envelope", "envelope-invalid", 400, new src_CX2iR2pK_ProtocolError(src_CX2iR2pK_ProtocolErrorCode.InvalidParams, `Invalid _meta envelope for protocol revision 2026-07-28: ${firstIssue.key}: ${firstIssue.problem}`, { envelope: firstIssue }), true); + const claimedVersion = src_CX2iR2pK_envelopeClaimVersion(params); + if (headerVersion !== void 0 && claimedVersion !== void 0 && headerVersion !== claimedVersion) return crossCheckMismatch("header-body-version-mismatch", headerVersion, `the body envelope names protocol version ${claimedVersion} but the MCP-Protocol-Version header names ${headerVersion}`); + if (request.mcpMethodHeader !== void 0 && request.mcpMethodHeader !== method) return crossCheckMismatch("method-header-mismatch", request.mcpMethodHeader, `the body names method ${method} but the Mcp-Method header names ${request.mcpMethodHeader}`); + return { + kind: "modern", + messageKind: "request", + message: body, + classification: classificationForClaim(claimedVersion) + }; + } + if (headerNamesModern) { + const meta = src_CX2iR2pK_requestMetaOf(params); + const missingFromEnvelope = src_CX2iR2pK_validateEnvelopeMeta(meta ?? {}).filter((issue) => issue.problem === "missing").map((issue) => issue.key); + const missing = meta === void 0 ? ["_meta"] : missingFromEnvelope.length > 0 ? missingFromEnvelope : [PROTOCOL_VERSION_META_KEY]; + return src_CX2iR2pK_rejection("envelope", "modern-header-without-claim", 400, new src_CX2iR2pK_ProtocolError(src_CX2iR2pK_ProtocolErrorCode.InvalidParams, `Invalid params: the MCP-Protocol-Version header names protocol revision ${headerVersion}, but the request is missing the required per-request envelope key(s): ${missing.join(", ")}`, { envelope: { missing } }), true); + } + return { + kind: "legacy", + reason: "no-claim", + ...headerVersion !== void 0 && { requestedVersion: headerVersion } + }; +} +function classifyNotificationBody(request, body) { + const params = body.params; + const method = body.method; + const headerVersion = request.protocolVersionHeader; + const headerNamesModern = headerVersion !== void 0 && isModernProtocolVersion(headerVersion); + if (src_CX2iR2pK_hasEnvelopeClaim(params)) { + const claimedVersion = src_CX2iR2pK_envelopeClaimVersion(params); + if (claimedVersion === void 0) { + const meta = src_CX2iR2pK_requestMetaOf(params); + const claimIssue = (meta === void 0 ? [] : src_CX2iR2pK_validateEnvelopeMeta(meta)).find((issue) => issue.key === PROTOCOL_VERSION_META_KEY) ?? { + key: PROTOCOL_VERSION_META_KEY, + problem: "expected a protocol version string" + }; + return src_CX2iR2pK_rejection("envelope", "notification-envelope-invalid", 400, new src_CX2iR2pK_ProtocolError(src_CX2iR2pK_ProtocolErrorCode.InvalidParams, `Invalid _meta envelope for protocol revision 2026-07-28: ${claimIssue.key}: ${claimIssue.problem}`, { envelope: claimIssue }), true); + } + if (headerVersion !== void 0 && headerVersion !== claimedVersion) return crossCheckMismatch("notification-header-body-version-mismatch", headerVersion, `the notification envelope names protocol version ${claimedVersion} but the MCP-Protocol-Version header names ${headerVersion}`); + const classification = classificationForClaim(claimedVersion); + if (classification.era === "modern" && request.mcpMethodHeader !== void 0 && request.mcpMethodHeader !== method) return crossCheckMismatch("notification-method-header-mismatch", request.mcpMethodHeader, `the notification body names method ${method} but the Mcp-Method header names ${request.mcpMethodHeader}`); + return { + kind: "modern", + messageKind: "notification", + message: body, + classification + }; + } + if (headerNamesModern) { + if (request.mcpMethodHeader !== void 0 && request.mcpMethodHeader !== method) return crossCheckMismatch("notification-method-header-mismatch", request.mcpMethodHeader, `the notification body names method ${method} but the Mcp-Method header names ${request.mcpMethodHeader}`); + return { + kind: "modern", + messageKind: "notification", + message: body, + classification: { + era: "modern", + revision: headerVersion + } + }; + } + return { + kind: "legacy", + reason: "notification", + ...headerVersion !== void 0 && { requestedVersion: headerVersion } + }; +} +/** +* Classifies one inbound HTTP request for dual-era serving. +* +* The body-primary predicate, evaluated once at the entry boundary: see the +* module documentation for the rules. Returns a routing outcome (`legacy` or +* `modern`) or a ladder rejection; it never throws. +*/ +function src_CX2iR2pK_classifyInboundRequest(request) { + request = { + ...request, + ...request.protocolVersionHeader !== void 0 && { protocolVersionHeader: stripHttpOws(request.protocolVersionHeader) }, + ...request.mcpMethodHeader !== void 0 && { mcpMethodHeader: stripHttpOws(request.mcpMethodHeader) }, + ...request.mcpNameHeader !== void 0 && { mcpNameHeader: stripHttpOws(request.mcpNameHeader) } + }; + if (request.httpMethod.toUpperCase() !== "POST") return { + kind: "legacy", + reason: "http-method" + }; + const body = request.body; + if (Array.isArray(body)) return classifyBatch(body); + if (src_CX2iR2pK_isJSONRPCResultResponse(body) || src_CX2iR2pK_isJSONRPCErrorResponse(body)) return { + kind: "legacy", + reason: "response" + }; + if (isPlainObject$2(body) && src_CX2iR2pK_isJSONRPCRequest(body)) return classifyRequestBody(request, body); + if (isPlainObject$2(body) && src_CX2iR2pK_isJSONRPCNotification(body)) return classifyNotificationBody(request, body); + return src_CX2iR2pK_rejection("jsonrpc-shape", "invalid-json-rpc-body", 400, new src_CX2iR2pK_ProtocolError(src_CX2iR2pK_ProtocolErrorCode.InvalidRequest, "Bad Request: the request body is not a valid JSON-RPC message"), true); +} +/** +* The rejection a modern-only endpoint (no legacy serving configured) +* answers a legacy-classified request with. +* +* - Envelope-less requests (including `initialize`) are answered with the +* unsupported-protocol-version error carrying the endpoint's supported +* versions and echoing the version the request named (when it named one — +* `requested` is omitted rather than fabricated when the request named no +* version at all), so a legacy client can discover what the endpoint serves +* from the error alone. +* - Posted responses and batch arrays are invalid requests on the modern era. +* - Non-`POST` methods are not allowed. +* - Legacy-classified notifications return `undefined`: the caller answers +* 202 with no body and does not dispatch the notification (accept-and-drop). +*/ +function src_CX2iR2pK_modernOnlyStrictRejection(route, supportedVersions) { + switch (route.reason) { + case "http-method": return src_CX2iR2pK_rejection("http-method", "modern-only-method-not-allowed", 405, new src_CX2iR2pK_ProtocolError(-32e3, "Method not allowed."), true); + case "batch": return src_CX2iR2pK_rejection("jsonrpc-shape", "modern-only-batch-not-supported", 400, new src_CX2iR2pK_ProtocolError(src_CX2iR2pK_ProtocolErrorCode.InvalidRequest, "Bad Request: JSON-RPC batches are not supported by this endpoint"), true); + case "response": return src_CX2iR2pK_rejection("jsonrpc-shape", "modern-only-response-post", 400, new src_CX2iR2pK_ProtocolError(src_CX2iR2pK_ProtocolErrorCode.InvalidRequest, "Bad Request: JSON-RPC responses cannot be posted to this endpoint"), true); + case "notification": return; + case "initialize": + case "no-claim": { + const requested = route.requestedVersion; + return src_CX2iR2pK_rejection("era-classification", "modern-only-missing-envelope", 400, requested === void 0 ? new src_CX2iR2pK_ProtocolError(src_CX2iR2pK_ProtocolErrorCode.UnsupportedProtocolVersion, "Unsupported protocol version: the request did not name a protocol version", { supported: [...supportedVersions] }) : new src_CX2iR2pK_UnsupportedProtocolVersionError({ + supported: [...supportedVersions], + requested + }), true); + } + } +} + +//#endregion +//#region ../core-internal/src/util/schema.ts +/** +* Internal Zod schema utilities for protocol handling. +* These are used internally by the SDK for protocol message validation. +*/ +/** +* Parses data against a Zod schema (synchronous). +* Returns a discriminated union with success/error. +*/ +function parseSchema(schema, data) { + return parse_safeParse(schema, data); +} +/** +* Union of the declared shape keys across several Zod object schemas. +*/ +function shapeKeys(schemas) { + return new Set(schemas.flatMap((schema) => Object.keys(schema.shape))); +} + +//#endregion +//#region ../core-internal/src/util/standardSchema.ts +/** +* Standard Schema utilities for user-provided schemas. +* Supports Zod v4, Valibot, ArkType, and other Standard Schema implementations. +* @see https://standardschema.dev +*/ +function isStandardSchema(schema) { + if (schema == null) return false; + const schemaType = typeof schema; + if (schemaType !== "object" && schemaType !== "function") return false; + if (!("~standard" in schema)) return false; + return typeof schema["~standard"]?.validate === "function"; +} +let warnedZodFallback = false; +/** JSON Schema draft targeted by every conversion; shared so pattern references above stay in lockstep. */ +const JSON_SCHEMA_CONVERSION_TARGET = "draft-2020-12"; +/** +* Converts a StandardSchema to JSON Schema for use as an MCP tool/prompt schema. +* +* MCP requires `type: "object"` at the root of tool `inputSchema` and prompt +* argument schemas; `outputSchema` may have any JSON Schema root (SEP-2106). +* Zod's discriminated unions emit `{oneOf: [...]}` without a top-level `type`, +* so for `io: 'input'` this function defaults `type` to `"object"` when absent +* and throws on an explicit non-object `type` (e.g. `z.string()`). For +* `io: 'output'` a non-object root is returned as-is; the `"object"` default is +* applied only when the root is provably object-shaped. +*/ +function standardSchemaToJsonSchema(schema, io = "input") { + const std = schema["~standard"]; + let result; + if (std.jsonSchema) result = std.jsonSchema[io]({ target: JSON_SCHEMA_CONVERSION_TARGET }); + else if (std.vendor === "zod") { + if (!("_zod" in schema)) 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()."); + if (!warnedZodFallback) { + warnedZodFallback = true; + 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."); + } + result = toJSONSchema(schema, { + target: JSON_SCHEMA_CONVERSION_TARGET, + io + }); + } else throw new Error(`Schema library "${std.vendor}" does not implement StandardJSONSchemaV1 (\`~standard.jsonSchema\`). Upgrade to a version that does, or wrap your JSON Schema with fromJsonSchema().`); + if (io === "output") { + if (result.type !== void 0) return result; + return isProvablyObjectShapedRoot(result) ? { + type: "object", + ...result + } : result; + } + if (result.type !== void 0 && result.type !== "object") throw new Error(`MCP tool and prompt schemas must describe objects (got type: ${JSON.stringify(result.type)}). Wrap your schema in z.object({...}) or equivalent.`); + return { + type: "object", + ...result + }; +} +/** +* A typeless JSON Schema root is "provably object-shaped" when either it carries object keywords +* directly (`properties`/`patternProperties`/`additionalProperties`/`required`), or it is a +* composition (`oneOf`/`anyOf`/`allOf`) whose every member is itself `type:'object'` or recursively +* provably object-shaped (e.g. a nested `discriminatedUnion`). `$ref` is not followed. Used to +* decide whether stamping `type:'object'` is safe (redundant-but-valid) versus self-contradictory. +*/ +function isProvablyObjectShapedRoot(schema) { + if ("properties" in schema || "patternProperties" in schema || "additionalProperties" in schema || "required" in schema) return true; + for (const key of [ + "oneOf", + "anyOf", + "allOf" + ]) { + const members = schema[key]; + if (Array.isArray(members) && members.length > 0) return members.every((m) => m !== null && typeof m === "object" && (m.type === "object" || isProvablyObjectShapedRoot(m))); + } + return false; +} +function formatIssue(issue) { + if (!issue.path?.length) return issue.message; + return `${issue.path.map((p) => String(typeof p === "object" ? p.key : p)).join(".")}: ${issue.message}`; +} +async function validateStandardSchema(schema, data) { + const result = await schema["~standard"].validate(data); + if (result.issues && result.issues.length > 0) return { + success: false, + error: result.issues.map((i) => formatIssue(i)).join(", ") + }; + return { + success: true, + data: result.value + }; +} +function zodEmittedPattern(schema) { + const jsonSchema = toJSONSchema(schema, { + target: JSON_SCHEMA_CONVERSION_TARGET, + io: "input" + }); + return typeof jsonSchema.pattern === "string" ? jsonSchema.pattern : void 0; +} +const DATETIME_FRACTION_DIGITS = /\\\.\\d\{(\d+)\}/; +function datetimeReferenceSchemas(pattern) { + const fractionDigits = DATETIME_FRACTION_DIGITS.exec(pattern); + const precisions = [ + void 0, + -1, + 0 + ]; + if (fractionDigits) precisions.push(Number(fractionDigits[1])); + return [false, true].flatMap((local) => [false, true].flatMap((offset) => precisions.map((precision) => iso_datetime({ + local, + offset, + precision + })))); +} +function referencePatternsForFormat(format, pattern) { + let referenceSchemas; + switch (format) { + case "email": + referenceSchemas = [schemas_email()]; + break; + case "uri": + referenceSchemas = [schemas_url()]; + break; + case "date": + referenceSchemas = [iso_date()]; + break; + case "date-time": + referenceSchemas = datetimeReferenceSchemas(pattern); + break; + } + return new Set(referenceSchemas.map((schema) => zodEmittedPattern(schema)).filter((emitted) => emitted !== void 0)); +} +/** Whether `pattern` is the library's own realization of `format` (droppable) rather than a user customization. */ +function isLibraryFormatPattern(format, pattern, vendor) { + if (vendor !== "zod") return true; + return referencePatternsForFormat(format, pattern).has(pattern); +} +function promptArgumentsFromStandardSchema(schema) { + const jsonSchema = standardSchemaToJsonSchema(schema, "input"); + const properties = jsonSchema.properties || {}; + const required = jsonSchema.required || []; + return Object.entries(properties).map(([name, prop]) => ({ + name, + description: prop?.description, + required: required.includes(name) + })); +} + +//#endregion +//#region ../core-internal/src/shared/elicitation.ts +function isJsonObject(value) { + return typeof value === "object" && value !== null && !Array.isArray(value); +} +function convertStandardElicitationSchema(schema) { + try { + return standardSchemaToJsonSchema(schema, "input"); + } catch (error) { + const detail = error instanceof Error ? error.message : String(error); + throw new src_CX2iR2pK_ProtocolError(src_CX2iR2pK_ProtocolErrorCode.InvalidParams, `Elicitation requestedSchema must describe an object with flat primitive properties: ${detail}`); + } +} +const ANNOTATION_ONLY_JSON_SCHEMA_KEYWORDS = new Set([ + "$comment", + "deprecated", + "description", + "examples", + "readOnly", + "title", + "writeOnly" +]); +function isAnnotationOnlyJsonSchemaKeyword(key) { + return ANNOTATION_ONLY_JSON_SCHEMA_KEYWORDS.has(key) || key.startsWith("x-"); +} +const ROOT_KEYS = new Set(["$schema", ...Object.keys(ElicitRequestFormParamsSchema.shape.requestedSchema.shape)]); +const PROPERTY_KEYS_BY_TYPE = { + string: shapeKeys([ + StringSchemaSchema, + UntitledSingleSelectEnumSchemaSchema, + TitledSingleSelectEnumSchemaSchema, + LegacyTitledEnumSchemaSchema + ]), + number: shapeKeys([NumberSchemaSchema]), + integer: shapeKeys([NumberSchemaSchema]), + boolean: shapeKeys([BooleanSchemaSchema]), + array: shapeKeys([UntitledMultiSelectEnumSchemaSchema, TitledMultiSelectEnumSchemaSchema]) +}; +const SUPPORTED_STRING_FORMATS = new Set(StringSchemaSchema.shape.format.unwrap().options); +/** Walks one property node: keeps grammar keys, drops the library format pattern, rejects unknown constraints. */ +function walkProperty(node, path, vendor, unsupported) { + if (!isJsonObject(node)) return node; + const allowedKeys = typeof node.type === "string" && Object.hasOwn(PROPERTY_KEYS_BY_TYPE, node.type) ? PROPERTY_KEYS_BY_TYPE[node.type] : void 0; + if (allowedKeys === void 0) return node; + const pruned = {}; + for (const [key, value] of Object.entries(node)) if (allowedKeys.has(key) || isAnnotationOnlyJsonSchemaKeyword(key)) pruned[key] = value; + else if (key === "pattern" && node.type === "string" && typeof node.format === "string") { + if (!SUPPORTED_STRING_FORMATS.has(node.format)) pruned[key] = value; + else if (typeof value !== "string" || !isLibraryFormatPattern(node.format, value, vendor)) unsupported.push(`${path}.${key}`); + } else unsupported.push(`${path}.${key}`); + return pruned; +} +/** Walks the schema root: keeps the spec root keys, drops annotations, rejects the rest. */ +function walkRequestedSchema(converted, vendor) { + const pruned = {}; + const unsupported = []; + for (const [key, value] of Object.entries(converted)) if (key === "properties" && isJsonObject(value)) pruned[key] = Object.fromEntries(Object.entries(value).map(([name, node]) => [name, walkProperty(node, `properties.${name}`, vendor, unsupported)])); + else if (ROOT_KEYS.has(key)) pruned[key] = value; + else if (!isAnnotationOnlyJsonSchemaKeyword(key)) unsupported.push(key); + if (unsupported.length > 0) throw new src_CX2iR2pK_ProtocolError(src_CX2iR2pK_ProtocolErrorCode.InvalidParams, `Elicitation requestedSchema contains unsupported JSON Schema constraint(s) after Standard Schema conversion: ${unsupported.join(", ")}`); + return pruned; +} +/** Names the properties that fail value validation, instead of surfacing a raw union dump. */ +function describeUnsupportedProperties(pruned, fallback) { + if (!isJsonObject(pruned.properties)) return fallback; + const offenders = Object.entries(pruned.properties).filter(([, node]) => !parseSchema(PrimitiveSchemaDefinitionSchema, node).success).map(([name]) => `properties.${name}`); + return offenders.length > 0 ? offenders.join(", ") : fallback; +} +function findDroppedConstraintPaths(original, parsed, path = "") { + if (Array.isArray(original) && Array.isArray(parsed)) return original.flatMap((item, index) => findDroppedConstraintPaths(item, parsed[index], `${path}[${index}]`)); + if (!isJsonObject(original) || !isJsonObject(parsed)) return []; + return Object.entries(original).flatMap(([key, value]) => { + const childPath = path ? `${path}.${key}` : key; + if (!Object.prototype.hasOwnProperty.call(parsed, key)) return isAnnotationOnlyJsonSchemaKeyword(key) ? [] : [childPath]; + return findDroppedConstraintPaths(value, parsed[key], childPath); + }); +} +/** Converts an authoring-friendly elicitation input into its wire-ready form. */ +function normalizeElicitInputParams(input) { + if (!isStandardSchema(input.requestedSchema)) return { + ...input, + mode: "form", + requestedSchema: input.requestedSchema + }; + const vendor = input.requestedSchema["~standard"].vendor; + const pruned = walkRequestedSchema(convertStandardElicitationSchema(input.requestedSchema), vendor); + const parsed = parseSchema(ElicitRequestFormParamsSchema.shape.requestedSchema, pruned); + if (!parsed.success) throw new src_CX2iR2pK_ProtocolError(src_CX2iR2pK_ProtocolErrorCode.InvalidParams, `Elicitation requestedSchema only supports flat primitive properties (string, number, integer, boolean, and string enums): ${describeUnsupportedProperties(pruned, parsed.error.message)}`); + const droppedConstraints = findDroppedConstraintPaths(pruned, parsed.data); + if (droppedConstraints.length > 0) throw new src_CX2iR2pK_ProtocolError(src_CX2iR2pK_ProtocolErrorCode.InvalidParams, `Elicitation requestedSchema contains unsupported JSON Schema constraint(s) after Standard Schema conversion: ${droppedConstraints.join(", ")}`); + const danglingRequired = (parsed.data.required ?? []).filter((key) => !Object.prototype.hasOwnProperty.call(parsed.data.properties, key)); + if (danglingRequired.length > 0) throw new src_CX2iR2pK_ProtocolError(src_CX2iR2pK_ProtocolErrorCode.InvalidParams, `Elicitation requestedSchema lists required properties that are not defined in properties: ${danglingRequired.join(", ")}`); + return { + ...input, + mode: "form", + requestedSchema: parsed.data + }; +} + +//#endregion +//#region ../core-internal/src/shared/inputRequired.ts +/** +* Authoring helpers for multi-round-trip requests (protocol revision +* 2026-07-28). +* +* A handler for one of the multi-round-trip methods (`tools/call`, +* `prompts/get`, `resources/read`) requests additional client input by +* returning an {@linkcode InputRequiredResult} instead of a final result. The +* helpers here build that return value and its embedded requests as NEUTRAL +* values; only the 2026-07-28 wire codec maps them to/from the wire. The +* 2025-era codec has no input-required vocabulary — on a 2025-era request the +* server's legacy shim (on by default) fulfils the embedded requests as real +* server→client requests and re-enters the handler, so the same return shape +* serves both eras; `ServerOptions.inputRequired.legacyShim: false` restores +* the pre-shim loud failure. +* +* There is no nominal brand: `resultType: 'input_required'` is the +* discriminator, and hand-built result literals are equally legal — the +* server seam re-checks the at-least-one rule for them. +*/ +function buildInputRequired(spec) { + const hasInputRequests = spec.inputRequests !== void 0 && Object.keys(spec.inputRequests).length > 0; + const hasRequestState = typeof spec.requestState === "string"; + if (!hasInputRequests && !hasRequestState) 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", + ...spec.inputRequests !== void 0 && { inputRequests: spec.inputRequests }, + ...spec.requestState !== void 0 && { requestState: spec.requestState } + }; +} +/** +* Builder for the input-required return value of multi-round-trip handlers, +* with per-kind constructors for the embedded requests +* (`inputRequired.elicit`, `inputRequired.elicitUrl`, +* `inputRequired.createMessage`, `inputRequired.listRoots`). +* +* @example Write-once tool requesting confirmation +* ```ts +* server.registerTool('deploy', { inputSchema: z.object({ env: z.string() }) }, async ({ env }, ctx) => { +* const confirmed = acceptedContent<{ confirm: boolean }>(ctx.mcpReq.inputResponses, 'confirm'); +* if (!confirmed) { +* return inputRequired({ +* inputRequests: { +* confirm: inputRequired.elicit({ +* message: `Deploy to ${env}?`, +* requestedSchema: { type: 'object', properties: { confirm: { type: 'boolean' } }, required: ['confirm'] } +* }) +* } +* }); +* } +* return { content: [{ type: 'text', text: `deployed to ${env}` }] }; +* }); +* ``` +*/ +const inputRequired = Object.assign(buildInputRequired, { + elicit(params) { + try { + return { + method: "elicitation/create", + params: normalizeElicitInputParams(params) + }; + } catch (error) { + throw error instanceof src_CX2iR2pK_ProtocolError ? new TypeError(error.message, { cause: error }) : error; + } + }, + elicitUrl(params) { + return { + method: "elicitation/create", + params: { + ...params, + mode: "url" + } + }; + }, + createMessage(params) { + return { + method: "sampling/createMessage", + params + }; + }, + listRoots() { + return { method: "roots/list" }; + } +}); +function acceptedContent(responses, key, schema) { + const view = inputResponse(responses, key); + if (view.kind !== "elicit" || view.action !== "accept" || view.content === void 0) return void 0; + if (schema === void 0) return view.content; + const outcome = schema["~standard"].validate(view.content); + if (outcome instanceof Promise) throw new TypeError("acceptedContent(responses, key, schema) requires a synchronously-validating schema"); + return outcome.issues === void 0 ? outcome.value : void 0; +} +/** +* Reads one entry of a retried request's `inputResponses` +* (`ctx.mcpReq.inputResponses`) as a discriminated view, covering +* decline/cancel detection and the non-elicitation response kinds that +* {@linkcode acceptedContent} does not surface. +* +* The values arrive from the client and are not re-validated here — treat +* them as untrusted input (validate elicitation content with the +* schema-aware {@linkcode acceptedContent} overload where it matters). +*/ +function inputResponse(responses, key) { + if (responses === void 0 || typeof responses !== "object" || responses === null) return { kind: "missing" }; + const entry = responses[key]; + if (entry === null || typeof entry !== "object" || Array.isArray(entry)) return { kind: "missing" }; + const candidate = entry; + if (candidate["action"] === "accept" || candidate["action"] === "decline" || candidate["action"] === "cancel") { + const content = candidate["content"]; + return { + kind: "elicit", + action: candidate["action"], + ...content !== null && typeof content === "object" && !Array.isArray(content) && { content } + }; + } + if (Array.isArray(candidate["roots"])) return { + kind: "roots", + roots: candidate["roots"] + }; + if (typeof candidate["role"] === "string" && candidate["content"] !== void 0) return { + kind: "sampling", + result: candidate + }; + return { kind: "missing" }; +} + +//#endregion +//#region ../core-internal/src/shared/inputRequiredDriver.ts +/** +* The multi-round-trip auto-fulfilment driver (protocol revision 2026-07-28). +* +* When a request to one of the multi-round-trip methods comes back as +* `input_required`, the driver fulfils the embedded input requests by +* dispatching them to the client's already-registered handlers (elicitation, +* sampling, roots — one generic engine, no per-feature API), then retries the +* original request with the collected `inputResponses` and a byte-exact echo +* of `requestState`, on a fresh request id, until the server returns a +* complete result or the round cap is exhausted. +* +* The driver is a LAYER OVER THE MANUAL PATH: each retry is issued with the +* same primitive a manual caller uses (`allowInputRequired` semantics — the +* retry hands back the next `input_required` payload instead of recursing), +* so the loop, the cap, and the pacing live in one place and disabling +* auto-fulfilment (`inputRequired.autoFulfill: false`) simply skips this +* module. Timeouts ride the EXISTING knobs: the per-leg `timeout` applies to +* every wire leg unchanged, and `maxTotalTimeout` bounds the whole flow by +* shrinking the budget passed to each leg — no new timer system. +*/ +/** +* Fixed pacing applied before retrying a requestState-only (load-shedding) +* leg — a leg that carries no embedded input requests, so nothing slows the +* loop down naturally. Counted in the same round cap. +*/ +const REQUEST_STATE_ONLY_LEG_PACING_MS = 250; +/** +* The message both multi-round-trip loops emit when the round cap is +* exhausted — the client driver as a typed error, the server-side legacy +* shim as its per-family failure. One formatter so the texts cannot drift +* (hosts and models read the tool-result copy verbatim). +*/ +function inputRequiredRoundsExceededMessage(method, maxRounds) { + return `Multi-round-trip request '${method}' still required input after ${maxRounds} rounds (inputRequired.maxRounds)`; +} +/** +* Abortable delay: resolves after `ms`, or rejects with the signal's reason +* (wrapped in an `SdkError` when it isn't already one) if the signal aborts +* first. Aborting after resolution is a no-op. Shared with the server-side +* legacy shim (the pacing semantics must match per era). +*/ +function sleep(ms, signal) { + return new Promise((resolve, reject) => { + if (signal?.aborted) { + reject(signal.reason instanceof src_CX2iR2pK_SdkError ? signal.reason : new src_CX2iR2pK_SdkError(src_CX2iR2pK_SdkErrorCode.RequestTimeout, String(signal.reason))); + return; + } + const timer = setTimeout(() => { + signal?.removeEventListener("abort", onAbort); + resolve(); + }, ms); + const onAbort = () => { + clearTimeout(timer); + reject(signal?.reason instanceof src_CX2iR2pK_SdkError ? signal.reason : new src_CX2iR2pK_SdkError(src_CX2iR2pK_SdkErrorCode.RequestTimeout, String(signal?.reason))); + }; + signal?.addEventListener("abort", onAbort, { once: true }); + }); +} +/** +* A per-round abort linked to the caller's signal: the embedded sibling +* dispatches share it, so the first failure (or a caller abort) cancels the +* others instead of leaving them running. Shared with the server-side legacy +* shim (the abort-linkage semantics must match per era). +*/ +function linkedRoundAbort(outer) { + const controller = new AbortController(); + const onOuterAbort = () => controller.abort(outer?.reason); + outer?.addEventListener("abort", onOuterAbort, { once: true }); + if (outer?.aborted) controller.abort(outer.reason); + return { + signal: controller.signal, + abort: (reason) => controller.abort(reason), + dispose: () => outer?.removeEventListener("abort", onOuterAbort) + }; +} + +//#endregion +//#region ../core-internal/src/types/specTypeSchema.ts +/** +* Explicit allowlist of protocol Zod schemas that correspond to a public spec type in `types.ts`. +* +* This intentionally excludes internal helper schemas exported from `schemas.ts` that have no +* matching public type (e.g. `ListChangedOptionsBaseSchema`, `BaseRequestParamsSchema`, +* `NotificationsParamsSchema`, `ClientTasksCapabilitySchema`, `ServerTasksCapabilitySchema`). +* Keeping the list explicit means new public spec types must be added here deliberately, and +* internals never leak into `SpecTypeName`. +* +* `ResourceTemplateSchema` is included; its public type is exported as `ResourceTemplateType` +* (the bare name collides with the server package's `ResourceTemplate` class), so +* `SpecTypes['ResourceTemplate']` is structurally equal to `ResourceTemplateType` rather than to +* a type literally named `ResourceTemplate`. +*/ +const SPEC_SCHEMA_KEYS = [ + "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" +]; +const authSchemas = { + IdJagTokenExchangeResponseSchema: IdJagTokenExchangeResponseSchema, + OAuthClientInformationFullSchema: OAuthClientInformationFullSchema, + OAuthClientInformationSchema: OAuthClientInformationSchema, + OAuthClientMetadataSchema: OAuthClientMetadataSchema, + OAuthClientRegistrationErrorSchema: OAuthClientRegistrationErrorSchema, + OAuthErrorResponseSchema: OAuthErrorResponseSchema, + OAuthMetadataSchema: OAuthMetadataSchema, + OAuthProtectedResourceMetadataSchema: OAuthProtectedResourceMetadataSchema, + OAuthTokenRevocationRequestSchema: OAuthTokenRevocationRequestSchema, + OAuthTokensSchema: OAuthTokensSchema, + OpenIdProviderDiscoveryMetadataSchema: OpenIdProviderDiscoveryMetadataSchema, + OpenIdProviderMetadataSchema: OpenIdProviderMetadataSchema +}; +const _specTypeSchemas = {}; +const _isSpecType = {}; +function register(key, schema) { + const name = key.slice(0, -6); + _specTypeSchemas[name] = schema; + _isSpecType[name] = (v) => schema.safeParse(v).success; +} +for (const key of SPEC_SCHEMA_KEYS) register(key, schemas_exports[key]); +for (const [key, schema] of Object.entries(authSchemas)) register(key, schema); +/** +* Runtime validators for every MCP spec type, keyed by type name. +* +* Use this when you need to validate a spec-defined shape at a boundary the SDK does not own, for +* example an extension's custom-method payload that embeds a `CallToolResult`, or a value read from +* storage that should be a `Tool`. +* +* Each entry implements the Standard Schema interface, so it composes with any +* Standard-Schema-aware library. For a simple boolean check, use {@linkcode isSpecType} instead. +* +* @example +* ```ts source="./specTypeSchema.examples.ts#specTypeSchemas_basicUsage" +* const result = specTypeSchemas.CallToolResult['~standard'].validate(untrusted); +* if (result.issues === undefined) { +* // result.value is CallToolResult +* } +* ``` +*/ +const specTypeSchemas = Object.freeze(_specTypeSchemas); +/** +* Type predicates for every MCP spec type, keyed by type name. +* +* Returns `true` if the value satisfies the schema's input type (`z.input<>`, before defaults and +* transforms are applied), and narrows to that input type. For schemas with `.default()` or +* `.preprocess()`, this may accept values that do not structurally match the named output type; +* for example `isSpecType.CallToolResult({})` is `true` because `content` has a default. Use +* `specTypeSchemas.X['~standard'].validate(value)` when you need the validated output value. +* +* Each guard is a standalone function, so it can be passed directly as a callback. +* +* @example +* ```ts source="./specTypeSchema.examples.ts#isSpecType_basicUsage" +* if (isSpecType.ContentBlock(value)) { +* // value is ContentBlock +* } +* +* const blocks = mixed.filter(isSpecType.ContentBlock); +* ``` +*/ +const isSpecType = Object.freeze(_isSpecType); + +//#endregion +//#region ../core-internal/src/wire/bootstrap.ts +function bootstrapOutboundCodec(method) { + switch (method) { + case "initialize": + case "notifications/initialized": return src_CX2iR2pK_codecForVersion(void 0); + case "server/discover": return src_CX2iR2pK_codecForVersion(src_CX2iR2pK_MODERN_WIRE_REVISION); + default: return; + } +} + +//#endregion +//#region ../core-internal/src/shared/protocol.ts +/** +* The default request timeout, in milliseconds. +*/ +const DEFAULT_REQUEST_TIMEOUT_MSEC = 6e4; +/** +* The reserved per-request `_meta` envelope keys (protocol revision +* 2026-07-28). The protocol layer lifts these out of inbound `_meta` before +* handlers run and surfaces them at `ctx.mcpReq.envelope` — they are +* wire-level bookkeeping, not handler material. +*/ +const RESERVED_ENVELOPE_META_KEYS = [ + auth_CUe6YdwF_PROTOCOL_VERSION_META_KEY, + auth_CUe6YdwF_CLIENT_INFO_META_KEY, + auth_CUe6YdwF_CLIENT_CAPABILITIES_META_KEY, + LOG_LEVEL_META_KEY +]; +/** +* Top-level params members carrying multi-round-trip driver material +* (protocol revision 2026-07-28). The spec reserves these names on +* client-initiated REQUESTS only — notification params keep them untouched +* (a vendor notification may legitimately use the same names). +*/ +const RETRY_PARAMS_KEYS = ["inputResponses", "requestState"]; +/** +* Lift wire-only material out of an inbound message so handlers see exactly +* the 2025-era shape, and surface it for the protocol layer (requests: via +* `ctx.mcpReq`). What counts as wire-only depends on the message kind: the +* reserved envelope `_meta` keys are reserved on every message, while the +* multi-round-trip retry fields (`inputResponses`/`requestState`) are +* reserved on client-initiated requests only — so notifications get only the +* envelope lift, and their top-level params stay untouched. Messages without +* wire-only material are returned unchanged (same reference). +*/ +function liftWireOnlyMaterial(message, kind) { + const params = message.params; + if (!isPlainObject$1(params)) return { + message, + lifted: {} + }; + const meta = params._meta; + const envelopeKeys = isPlainObject$1(meta) ? RESERVED_ENVELOPE_META_KEYS.filter((key) => key in meta) : []; + const retryKeys = kind === "request" ? RETRY_PARAMS_KEYS.filter((key) => key in params) : []; + if (envelopeKeys.length === 0 && retryKeys.length === 0) return { + message, + lifted: {} + }; + const lifted = {}; + const nextParams = { ...params }; + if (envelopeKeys.length > 0 && isPlainObject$1(meta)) { + const envelope = {}; + const nextMeta = { ...meta }; + for (const key of envelopeKeys) { + envelope[key] = meta[key]; + delete nextMeta[key]; + } + lifted.envelope = envelope; + if (Object.keys(nextMeta).length > 0) nextParams._meta = nextMeta; + else delete nextParams._meta; + } + for (const key of retryKeys) { + if (key === "inputResponses") lifted.inputResponses = nextParams[key]; + if (key === "requestState") lifted.requestState = nextParams[key]; + delete nextParams[key]; + } + return { + message: { + ...message, + params: nextParams + }, + lifted + }; +} +/** +* Standard Schema adapter over the era codec's `validateResult` function (the +* function-only WireCodec contract exposes no schema objects). Used by the +* spec-method `request()` overload so the request funnel keeps a single +* `StandardSchemaV1`-shaped validation seam for both spec and explicit-schema +* paths. +* +* Returns `undefined` when the method has no result entry on this era's +* registry — the caller maps that to the synchronous "pass a result schema" +* TypeError, exactly matching the pre-function-only behavior the +* typedMapAlignment suite pins (the result map deliberately excludes the +* `tasks/*` methods, so the spec-method overload refuses them up front). +*/ +function codecResultValidator(codec, method) { + const probe = codec.validateResult(method, void 0); + if (!probe.ok && probe.reason === "not-in-era") return void 0; + return { "~standard": { + version: 1, + vendor: "mcp-wire-codec", + validate(value) { + const outcome = codec.validateResult(method, value); + if (outcome.ok) return { value: outcome.value }; + return { issues: [{ message: outcome.reason === "invalid" ? outcome.message : `not-in-era: ${method}` }] }; + } + } }; +} +/** +* Builds the `ctx.mcpReq.requestState` accessor for a resolved value. The +* `as T` below is the one place {@linkcode RequestStateAccessor}'s +* caller-asserted typing is implemented — no implementation can produce an +* arbitrary `T` from a runtime value honestly. +*/ +function requestStateAccessor(value) { + return () => value; +} +/** Shared no-state accessor: the common case allocates nothing per request. */ +const NO_REQUEST_STATE = requestStateAccessor(void 0); +/** +* Returns a context whose `requestState` accessor reads the given value — +* how the server seam hands a verify hook's decoded payload (or the legacy +* shim's per-round echo) to the handler without mutating the original +* context. +*/ +function withRequestStateValue(ctx, value) { + return { + ...ctx, + mcpReq: { + ...ctx.mcpReq, + requestState: requestStateAccessor(value) + } + }; +} +let writeNegotiatedProtocolVersion; +/** +* Package-internal write channel for a {@linkcode Protocol} instance's +* negotiated protocol version, for callers outside the class hierarchy: +* tests and the (future) modern-era server entry that marks a factory +* instance modern at binding time. Exported on the core internal barrel +* only — never public API. +*/ +function src_CX2iR2pK_setNegotiatedProtocolVersion(instance, version) { + writeNegotiatedProtocolVersion(instance, version); +} +/** +* Implements MCP protocol framing on top of a pluggable transport, including +* features like request/response linking, notifications, and progress. +* +* `Protocol` is abstract; `Client` and `Server` are the concrete role-specific +* implementations most code should use. +*/ +var Protocol = class { + _transport; + _requestMessageId = 0; + _requestHandlers = /* @__PURE__ */ new Map(); + _requestHandlerAbortControllers = /* @__PURE__ */ new Map(); + _notificationHandlers = /* @__PURE__ */ new Map(); + _responseHandlers = /* @__PURE__ */ new Map(); + _progressHandlers = /* @__PURE__ */ new Map(); + _timeoutInfo = /* @__PURE__ */ new Map(); + _pendingDebouncedNotifications = /* @__PURE__ */ new Set(); + /** + * The protocol version negotiated for the current connection (`undefined` + * before negotiation completes), which determines the wire era this + * instance speaks. Set by the SDK's negotiation and initialize paths + * (`Client.connect`, `Server._oninitialize`). + */ + _negotiatedProtocolVersion; + static { + writeNegotiatedProtocolVersion = (instance, version) => { + instance._negotiatedProtocolVersion = version; + }; + } + _supportedProtocolVersions; + /** + * Callback for when the connection is closed for any reason. + * + * This is invoked when {@linkcode Protocol.close | close()} is called as well. + */ + onclose; + /** + * Callback for when an error occurs. + * + * Note that errors are not necessarily fatal; they are used for reporting any kind of exceptional condition out of band. + */ + onerror; + /** + * A handler to invoke for any request types that do not have their own handler installed. + */ + fallbackRequestHandler; + /** + * A handler to invoke for any notification types that do not have their own handler installed. + */ + fallbackNotificationHandler; + constructor(_options) { + this._options = _options; + this._supportedProtocolVersions = _options?.supportedProtocolVersions ?? auth_CUe6YdwF_SUPPORTED_PROTOCOL_VERSIONS; + this.setNotificationHandler("notifications/cancelled", (notification) => { + this._oncancel(notification); + }); + this.setNotificationHandler("notifications/progress", (notification) => { + this._onprogress(notification); + }); + this.setRequestHandler("ping", (_request) => ({})); + } + /** + * Drop consult for inbound messages whose transport did not classify them + * at the edge — long-lived channels such as stdio, where a role class may + * need to decline traffic the negotiated era has no answer for (the + * client-side inbound-request drop on modern-era connections: the + * 2026-07-28 era has no server→client request channel, and on stdio the + * client must never write JSON-RPC responses). + * + * Consulted ONLY when the transport supplied no + * {@linkcode MessageExtraInfo.classification}: edge-classified traffic + * never reaches the hook. Returning `'drop'` discards the message without + * writing any response (requests are surfaced via `onerror`). The base + * implementation returns `undefined`: unclassified traffic keeps today's + * dispatch path unchanged. Era selection never happens here — era is + * instance state, owned by the serving entry that constructed and + * connected the instance. + */ + _shouldDropInbound(_message) {} + /** + * The per-request `_meta` envelope this instance attaches to every outgoing + * request and notification, when one applies. The base implementation + * returns `undefined` (no envelope — the 2025-era posture, so legacy-era + * outbound traffic is byte-identical to a build without this seam). + * `Client` overrides it on a connection that negotiated a modern (2026-07-28+) + * era to return the reserved protocol-version / client-info / + * client-capabilities keys. User-supplied `_meta` keys take precedence over + * the auto-attached ones. + */ + _outboundMetaEnvelope() {} + /** + * Attach this instance's outbound `_meta` envelope (when one is configured) + * to a request or notification. A no-op when the seam returns `undefined` + * — the message returns by reference, so the legacy-era wire stays + * byte-identical. User-supplied `_meta` keys are spread last so they win + * over the auto-attached envelope keys. + */ + _envelopeOutbound(message) { + const envelope = this._outboundMetaEnvelope(); + if (envelope === void 0) return message; + const params = message.params ?? {}; + return { + ...message, + params: { + ...params, + _meta: { + ...envelope, + ...params._meta + } + } + }; + } + /** + * Extension point for non-`complete` decoded results in the response + * funnel: a result the wire codec discriminated into a kind other than + * `'complete'` or `'invalid'` is handed here for the role class to + * resolve. The base default surfaces it as a typed + * {@linkcode SdkErrorCode.UnsupportedResultType} error (no retry). + * + * Intended consumers (named so the seam stays accountable): + * - the `Client`'s multi-round-trip auto-fulfilment engine, which fulfils + * `'input_required'` results through the registered + * elicitation/sampling/roots handlers and retries via `flow.retry`; + * - a future client-side terminal-result handler for + * `subscriptions/listen`, when the spec defines one. + * + * `Server` instances never receive `input_required` responses on their + * outbound legs and leave the base behavior in place. + */ + _resolveNonCompleteResult(decoded, flow) { + return Promise.reject(new src_CX2iR2pK_SdkError(src_CX2iR2pK_SdkErrorCode.UnsupportedResultType, `Unsupported result type '${decoded.kind}' for ${flow.request.method}`, { + resultType: decoded.kind, + method: flow.request.method + })); + } + /** + * Protected accessor for a registered request handler. Used by role + * classes that dispatch synthesized requests through the same stored + * handler chain (e.g. the `Client` fulfilling an embedded multi-round-trip + * input request). + */ + _getRequestHandler(method) { + return this._requestHandlers.get(method); + } + async _oncancel(notification) { + if (!notification.params.requestId) return; + this._requestHandlerAbortControllers.get(notification.params.requestId)?.abort(notification.params.reason); + } + _setupTimeout(messageId, timeout, maxTotalTimeout, onTimeout, resetTimeoutOnProgress = false) { + this._timeoutInfo.set(messageId, { + timeoutId: setTimeout(onTimeout, timeout), + startTime: Date.now(), + timeout, + maxTotalTimeout, + resetTimeoutOnProgress, + onTimeout + }); + } + _resetTimeout(messageId) { + const info = this._timeoutInfo.get(messageId); + if (!info) return false; + const totalElapsed = Date.now() - info.startTime; + if (info.maxTotalTimeout && totalElapsed >= info.maxTotalTimeout) { + this._timeoutInfo.delete(messageId); + throw new src_CX2iR2pK_SdkError(src_CX2iR2pK_SdkErrorCode.RequestTimeout, "Maximum total timeout exceeded", { + maxTotalTimeout: info.maxTotalTimeout, + totalElapsed + }); + } + clearTimeout(info.timeoutId); + info.timeoutId = setTimeout(info.onTimeout, info.timeout); + return true; + } + _cleanupTimeout(messageId) { + const info = this._timeoutInfo.get(messageId); + if (info) { + clearTimeout(info.timeoutId); + this._timeoutInfo.delete(messageId); + } + } + /** + * Attaches to the given transport, starts it, and starts listening for messages. + * + * The caller assumes ownership of the {@linkcode Transport}, replacing any callbacks that have already been set, and expects that it is the only user of the {@linkcode Transport} instance going forward. + */ + async connect(transport) { + this._transport = transport; + const _onclose = this.transport?.onclose; + this._transport.onclose = () => { + try { + _onclose?.(); + } finally { + this._onclose(); + } + }; + const _onerror = this.transport?.onerror; + this._transport.onerror = (error) => { + _onerror?.(error); + this._onerror(error); + }; + const _onmessage = this._transport?.onmessage; + this._transport.onmessage = (message, extra) => { + _onmessage?.(message, extra); + if (src_CX2iR2pK_isJSONRPCResultResponse(message) || src_CX2iR2pK_isJSONRPCErrorResponse(message)) this._onresponse(message); + else if (src_CX2iR2pK_isJSONRPCRequest(message)) this._onrequest(message, extra); + else if (src_CX2iR2pK_isJSONRPCNotification(message)) this._onnotification(message, extra); + else this._onerror(/* @__PURE__ */ new Error(`Unknown message type: ${JSON.stringify(message)}`)); + }; + transport.setSupportedProtocolVersions?.(this._supportedProtocolVersions); + await this._transport.start(); + } + /** + * Transport-close hook. Subclass overrides MUST call `super._onclose()` + * after their own cleanup — base teardown (response-handler settlement, + * timeout clearing, in-flight request abort) does not run otherwise. + */ + _onclose() { + const responseHandlers = this._responseHandlers; + this._responseHandlers = /* @__PURE__ */ new Map(); + this._progressHandlers.clear(); + this._pendingDebouncedNotifications.clear(); + for (const info of this._timeoutInfo.values()) clearTimeout(info.timeoutId); + this._timeoutInfo.clear(); + const requestHandlerAbortControllers = this._requestHandlerAbortControllers; + this._requestHandlerAbortControllers = /* @__PURE__ */ new Map(); + const error = new src_CX2iR2pK_SdkError(src_CX2iR2pK_SdkErrorCode.ConnectionClosed, "Connection closed"); + this._transport = void 0; + try { + this.onclose?.(); + } finally { + for (const handler of responseHandlers.values()) handler(error); + for (const controller of requestHandlerAbortControllers.values()) controller.abort(error); + } + } + _onerror(error) { + this.onerror?.(error); + } + /** + * Inbound-notification dispatch. Subclass overrides MUST delegate + * unmatched traffic to `super._onnotification(rawNotification, extra)` — + * an override that consumes only what it owns and falls through to base + * dispatch for everything else. + */ + _onnotification(rawNotification, extra) { + const { message: notification } = liftWireOnlyMaterial(rawNotification, "notification"); + const codec = this._negotiatedWireCodec(); + if (extra?.classification === void 0 && this._shouldDropInbound(rawNotification) === "drop") return; + if (extra?.classification !== void 0) { + const classified = classifiedWireEra(extra.classification); + if (classified !== codec.era) { + this._onerror(/* @__PURE__ */ new Error(`Era mismatch on inbound notification '${notification.method}': classified as ${classified} but this instance serves ${codec.era}`)); + return; + } + } + if (isSpecNotificationMethod(notification.method) && !codec.hasNotificationMethod(notification.method)) return; + const handler = this._notificationHandlers.get(notification.method); + const fallback = this.fallbackNotificationHandler; + if (handler === void 0 && fallback === void 0) return; + Promise.resolve().then(() => handler === void 0 ? fallback(notification) : handler(notification, codec)).catch((error) => this._onerror(/* @__PURE__ */ new Error(`Uncaught error in notification handler: ${error}`))); + } + _onrequest(rawRequest, extra) { + const { message: request, lifted } = liftWireOnlyMaterial(rawRequest, "request"); + const codec = this._negotiatedWireCodec(); + if (extra?.classification === void 0 && this._shouldDropInbound(rawRequest) === "drop") { + this._onerror(/* @__PURE__ */ new Error(`Dropped inbound request '${rawRequest.method}': not servable on this connection's protocol era`)); + return; + } + const capturedTransport = this._transport; + const sendErrorResponse = (code, message, data) => { + const errorResponse = { + jsonrpc: "2.0", + id: request.id, + error: { + code, + message, + ...data !== void 0 && { data } + } + }; + capturedTransport?.send(errorResponse).catch((error) => this._onerror(/* @__PURE__ */ new Error(`Failed to send an error response: ${error}`))); + }; + if (extra?.classification !== void 0) { + const classified = classifiedWireEra(extra.classification); + if (classified !== codec.era) { + this._onerror(/* @__PURE__ */ new Error(`Era mismatch on inbound request '${request.method}': classified as ${classified} but this instance serves ${codec.era}`)); + const requested = extra.classification.revision ?? classified; + sendErrorResponse(src_CX2iR2pK_ProtocolErrorCode.UnsupportedProtocolVersion, `Unsupported protocol version: ${requested}`, { + supported: this._supportedProtocolVersions, + requested + }); + return; + } + } + if (isSpecRequestMethod(request.method) && !codec.hasRequestMethod(request.method)) { + sendErrorResponse(src_CX2iR2pK_ProtocolErrorCode.MethodNotFound, "Method not found"); + return; + } + const handler = this._requestHandlers.get(request.method) ?? this.fallbackRequestHandler; + if (handler === void 0) { + sendErrorResponse(src_CX2iR2pK_ProtocolErrorCode.MethodNotFound, "Method not found"); + return; + } + const envelopeError = codec.checkInboundEnvelope(lifted); + if (envelopeError !== void 0) { + sendErrorResponse(src_CX2iR2pK_ProtocolErrorCode.InvalidParams, envelopeError); + return; + } + const sendNotification = (notification, options) => this._notificationViaCodec(this._resolveOutboundCodec(notification.method), notification, { + ...options, + relatedRequestId: request.id + }); + const sendRequest = (r, resultSchema, options) => this._requestWithSchemaViaCodec(this._resolveOutboundCodec(r.method), r, resultSchema, { + ...options, + relatedRequestId: request.id + }); + const abortController = new AbortController(); + this._requestHandlerAbortControllers.set(request.id, abortController); + const partitionedInputResponses = lifted.inputResponses === void 0 ? void 0 : partitionInputResponses(lifted.inputResponses); + const baseCtx = { + sessionId: capturedTransport?.sessionId, + mcpReq: { + id: request.id, + method: request.method, + _meta: request.params?._meta, + ...lifted.envelope !== void 0 && { envelope: lifted.envelope }, + ...partitionedInputResponses !== void 0 && { inputResponses: partitionedInputResponses.accepted }, + ...partitionedInputResponses !== void 0 && partitionedInputResponses.droppedKeys.length > 0 && { droppedInputResponseKeys: partitionedInputResponses.droppedKeys }, + requestState: lifted.requestState === void 0 ? NO_REQUEST_STATE : requestStateAccessor(lifted.requestState), + signal: abortController.signal, + send: ((r, schemaOrOptions, maybeOptions) => { + const sendCodec = this._resolveOutboundCodec(r.method); + this._assertOutboundRequestInEra(sendCodec, r.method); + if (isStandardSchema(schemaOrOptions)) return sendRequest(r, schemaOrOptions, maybeOptions); + const validate = codecResultValidator(sendCodec, r.method); + if (validate === void 0) throw new TypeError(`'${r.method}' is not a spec method; pass a result schema as the second argument to ctx.mcpReq.send().`); + return sendRequest(r, validate, schemaOrOptions); + }), + notify: sendNotification + }, + http: extra?.authInfo ? { authInfo: extra.authInfo } : void 0 + }; + const ctx = this.buildContext(baseCtx, extra); + Promise.resolve().then(() => handler(request, ctx)).then(async (result) => { + if (abortController.signal.aborted) return; + let encoded; + try { + encoded = codec.encodeResult(request.method, result, this._outboundServerInfo()); + } catch (error) { + this._onerror(/* @__PURE__ */ new Error(`Failed to encode result for ${request.method}: ${error}`)); + sendErrorResponse(src_CX2iR2pK_ProtocolErrorCode.InternalError, "Internal error"); + return; + } + const response = { + result: encoded, + jsonrpc: "2.0", + id: request.id + }; + await capturedTransport?.send(response); + }, async (error) => { + if (abortController.signal.aborted) return; + const thrownCode = Number.isSafeInteger(error["code"]) ? error["code"] : src_CX2iR2pK_ProtocolErrorCode.InternalError; + const errorResponse = { + jsonrpc: "2.0", + id: request.id, + error: { + code: codec.encodeErrorCode(thrownCode), + message: error.message ?? "Internal error", + ...error["data"] !== void 0 && { data: error["data"] } + } + }; + await capturedTransport?.send(errorResponse); + }).catch((error) => this._onerror(/* @__PURE__ */ new Error(`Failed to send response: ${error}`))).finally(() => { + if (this._requestHandlerAbortControllers.get(request.id) === abortController) this._requestHandlerAbortControllers.delete(request.id); + }); + } + _onprogress(notification) { + const { progressToken, ...params } = notification.params; + const messageId = Number(progressToken); + const handler = this._progressHandlers.get(messageId); + if (!handler) { + this._onerror(/* @__PURE__ */ new Error(`Received a progress notification for an unknown token: ${JSON.stringify(notification)}`)); + return; + } + const responseHandler = this._responseHandlers.get(messageId); + const timeoutInfo = this._timeoutInfo.get(messageId); + if (timeoutInfo && responseHandler && timeoutInfo.resetTimeoutOnProgress) try { + this._resetTimeout(messageId); + } catch (error) { + this._responseHandlers.delete(messageId); + this._progressHandlers.delete(messageId); + this._cleanupTimeout(messageId); + responseHandler(error); + return; + } + handler(params); + } + /** + * Inbound-response dispatch. Subclass overrides MUST delegate unmatched + * traffic to `super._onresponse(response)` — an override that consumes + * only what it owns and falls through to base dispatch for everything + * else. + */ + _onresponse(response) { + const messageId = Number(response.id); + const handler = this._responseHandlers.get(messageId); + if (handler === void 0) { + this._onerror(/* @__PURE__ */ new Error(`Received a response for an unknown message ID: ${JSON.stringify(response)}`)); + return; + } + this._responseHandlers.delete(messageId); + this._cleanupTimeout(messageId); + this._progressHandlers.delete(messageId); + if (src_CX2iR2pK_isJSONRPCResultResponse(response)) handler(response); + else handler(src_CX2iR2pK_ProtocolError.fromError(response.error.code, response.error.message, response.error.data)); + } + get transport() { + return this._transport; + } + /** + * Closes the connection. + */ + async close() { + await this._transport?.close(); + } + request(request, schemaOrOptions, maybeOptions) { + const codec = this._resolveOutboundCodec(request.method); + this._assertOutboundRequestInEra(codec, request.method); + if (isStandardSchema(schemaOrOptions)) return this._requestWithSchemaViaCodec(codec, request, schemaOrOptions, maybeOptions); + const validate = codecResultValidator(codec, request.method); + if (validate === void 0) throw new TypeError(`'${request.method}' is not a spec method; pass a result schema as the second argument to request().`); + return this._requestWithSchemaViaCodec(codec, request, validate, schemaOrOptions); + } + /** + * The wire codec for this instance's negotiated era — the phase-2 truth: + * everything an established connection sends and receives resolves + * through it. Legacy until a version has been negotiated. + */ + _negotiatedWireCodec() { + return src_CX2iR2pK_codecForVersion(this._negotiatedProtocolVersion); + } + /** + * Protected accessor for the instance's negotiated wire codec, for role + * classes (Client/Server/McpServer) routing era-dependent behavior + * through the codec's function-only surface — `samplingResultVariant`, + * `outboundEnvelope`, `projectCallToolResult` — instead of branching on + * the protocol version themselves. + */ + _wireCodec() { + return this._negotiatedWireCodec(); + } + /** + * Outbound codec resolution: while the negotiated version is still unset + * (the negotiation window), lifecycle messages are bootstrap-pinned BY + * METHOD — they self-identify their era (`initialize` IS the legacy + * handshake, `server/discover` IS the modern probe). Once a version has + * been negotiated, the instance era is authoritative for everything — a + * negotiated session never re-routes a method onto the other era. + */ + _resolveOutboundCodec(method) { + if (this._negotiatedProtocolVersion === void 0) { + const pinned = bootstrapOutboundCodec(method); + if (pinned) return pinned; + } + return this._negotiatedWireCodec(); + } + /** + * Era gate for outbound requests — deletions are physical in BOTH + * directions: sending a spec method that the resolved era does not define + * dies locally with a typed error before anything reaches the transport. + * Methods outside the spec universe are consumer-owned extension methods + * and stay era-blind. + */ + _assertOutboundRequestInEra(codec, method) { + if (isSpecRequestMethod(method) && !codec.hasRequestMethod(method)) throw new src_CX2iR2pK_SdkError(src_CX2iR2pK_SdkErrorCode.MethodNotSupportedByProtocolVersion, `Method '${method}' is not supported by the negotiated protocol version (wire era ${codec.era})`, { + method, + era: codec.era + }); + } + /** + * Sends a request and waits for a response, using the provided schema for + * validation instead of the era registry's method-keyed entry. + * + * This is the internal implementation used by SDK methods whose result + * schema cannot be expressed as a method-keyed registry entry — the one + * surviving case is `server.createMessage`, whose result schema depends + * on the REQUEST params (tools vs no tools) — and by callers passing + * explicit compatibility schemas. Spec methods are still era-gated here: + * an explicit schema never smuggles a deleted method onto the wire. + */ + _requestWithSchema(request, resultSchema, options) { + const codec = this._resolveOutboundCodec(request.method); + this._assertOutboundRequestInEra(codec, request.method); + return this._requestWithSchemaViaCodec(codec, request, resultSchema, options); + } + /** + * The request funnel proper, keyed by the resolved era codec: the codec + * owns result decoding (raw-first `resultType` discrimination — V-1 — + * and the era's lift posture) before the schema validation step. + */ + _requestWithSchemaViaCodec(codec, request, resultSchema, options) { + const { relatedRequestId, resumptionToken, onresumptiontoken, headers } = options ?? {}; + const flowStartedAt = Date.now(); + let onAbort; + let cleanupMessageId; + return new Promise((resolve, reject) => { + const earlyReject = (error) => { + reject(error); + }; + if (!this._transport) { + earlyReject(/* @__PURE__ */ new Error("Not connected")); + return; + } + if (this._options?.enforceStrictCapabilities === true) try { + this.assertCapabilityForMethod(request.method); + } catch (error) { + earlyReject(error); + return; + } + if (options?.signal?.aborted) { + const reason = options.signal.reason; + throw reason instanceof src_CX2iR2pK_SdkError ? reason : new src_CX2iR2pK_SdkError(src_CX2iR2pK_SdkErrorCode.RequestTimeout, String(reason)); + } + const requestAbort = codec.era === src_CX2iR2pK_MODERN_WIRE_REVISION && this._transport.hasPerRequestStream === true ? new AbortController() : void 0; + const messageId = this._requestMessageId++; + cleanupMessageId = messageId; + const jsonrpcRequest = { + ...request, + jsonrpc: "2.0", + id: messageId + }; + if (options?.onprogress) { + this._progressHandlers.set(messageId, options.onprogress); + jsonrpcRequest.params = { + ...request.params, + _meta: { + ...request.params?._meta, + progressToken: messageId + } + }; + } + const outbound = this._envelopeOutbound(jsonrpcRequest); + let responseReceived = false; + const cancel = (reason) => { + if (responseReceived) return; + this._progressHandlers.delete(messageId); + if (requestAbort === void 0) this._transport?.send(this._envelopeOutbound({ + jsonrpc: "2.0", + method: "notifications/cancelled", + params: { + requestId: messageId, + reason: String(reason) + } + }), { + relatedRequestId, + resumptionToken, + onresumptiontoken + }).catch((error) => this._onerror(/* @__PURE__ */ new Error(`Failed to send cancellation: ${error}`))); + else requestAbort.abort(); + reject(reason instanceof src_CX2iR2pK_SdkError ? reason : new src_CX2iR2pK_SdkError(src_CX2iR2pK_SdkErrorCode.RequestTimeout, String(reason))); + }; + this._responseHandlers.set(messageId, (response) => { + if (options?.signal?.aborted) return; + responseReceived = true; + if (response instanceof Error) return reject(response); + let decoded; + try { + decoded = codec.decodeResult(request.method, response.result); + } catch (error) { + return reject(error instanceof Error ? error : new Error(String(error))); + } + if (decoded.kind === "invalid") return reject(decoded.error); + if (decoded.kind === "input_required") { + if (options?.allowInputRequired === true) return resolve(manualInputRequiredValue(decoded)); + const flow = { + codec, + request, + resultSchema, + options, + flowStartedAt, + retry: (params, legOptions) => this._requestWithSchemaViaCodec(codec, params === void 0 ? { method: request.method } : { + method: request.method, + params + }, resultSchema, legOptions) + }; + return resolve(this._resolveNonCompleteResult(decoded, flow)); + } + const result = decoded.result; + validateStandardSchema(resultSchema, result).then((parseResult) => { + if (parseResult.success) resolve(parseResult.data); + else reject(new src_CX2iR2pK_SdkError(src_CX2iR2pK_SdkErrorCode.InvalidResult, `Invalid result for ${request.method}: ${parseResult.error}`)); + }, reject); + }); + onAbort = () => cancel(options?.signal?.reason); + options?.signal?.addEventListener("abort", onAbort, { once: true }); + const timeout = options?.timeout ?? DEFAULT_REQUEST_TIMEOUT_MSEC; + const timeoutHandler = () => cancel(new src_CX2iR2pK_SdkError(src_CX2iR2pK_SdkErrorCode.RequestTimeout, "Request timed out", { timeout })); + this._setupTimeout(messageId, timeout, options?.maxTotalTimeout, timeoutHandler, options?.resetTimeoutOnProgress ?? false); + this._transport.send(outbound, { + relatedRequestId, + resumptionToken, + onresumptiontoken, + headers, + requestSignal: requestAbort?.signal + }).catch((error) => { + this._progressHandlers.delete(messageId); + reject(error); + }); + }).finally(() => { + if (onAbort) options?.signal?.removeEventListener("abort", onAbort); + if (cleanupMessageId !== void 0) { + this._responseHandlers.delete(cleanupMessageId); + this._cleanupTimeout(cleanupMessageId); + } + }); + } + /** + * Emits a notification, which is a one-way message that does not expect a response. + */ + async notification(notification, options) { + return this._notificationViaCodec(this._resolveOutboundCodec(notification.method), notification, options); + } + /** + * The notification funnel proper, keyed by the resolved era codec — + * direct sends and related notifications (`ctx.mcpReq.notify`) alike + * resolve through the instance's negotiated era at send time. + */ + async _notificationViaCodec(codec, notification, options) { + if (!this._transport) throw new src_CX2iR2pK_SdkError(src_CX2iR2pK_SdkErrorCode.NotConnected, "Not connected"); + if (isSpecNotificationMethod(notification.method) && !codec.hasNotificationMethod(notification.method)) throw new src_CX2iR2pK_SdkError(src_CX2iR2pK_SdkErrorCode.MethodNotSupportedByProtocolVersion, `Notification '${notification.method}' is not supported by the negotiated protocol version (wire era ${codec.era})`, { + method: notification.method, + era: codec.era + }); + this.assertNotificationCapability(notification.method); + const jsonrpcNotification = this._envelopeOutbound({ + jsonrpc: "2.0", + ...notification + }); + if ((this._options?.debouncedNotificationMethods ?? []).includes(notification.method) && !notification.params && !options?.relatedRequestId) { + if (this._pendingDebouncedNotifications.has(notification.method)) return; + this._pendingDebouncedNotifications.add(notification.method); + Promise.resolve().then(() => { + this._pendingDebouncedNotifications.delete(notification.method); + if (!this._transport) return; + this._transport?.send(jsonrpcNotification, options).catch((error) => this._onerror(error)); + }); + return; + } + await this._transport.send(jsonrpcNotification, options); + } + setRequestHandler(method, schemasOrHandler, maybeHandler) { + this.assertRequestHandlerCapability(method); + let stored; + if (typeof schemasOrHandler === "function") { + if (!isSpecRequestMethod(method)) throw new TypeError(`'${method}' is not a spec request method; pass schemas as the second argument to setRequestHandler().`); + stored = (request, ctx) => { + const dispatchCodec = this._negotiatedWireCodec(); + let outcome = dispatchCodec.validateRequest(method, request); + if (!outcome.ok && outcome.reason === "not-in-era") outcome = dispatchCodec.validateInputRequest(method, request); + if (!outcome.ok) { + if (outcome.reason === "not-in-era") throw new src_CX2iR2pK_ProtocolError(src_CX2iR2pK_ProtocolErrorCode.InternalError, `No wire schema for ${method} in the resolved era`); + throw new Error(outcome.message); + } + return Promise.resolve(schemasOrHandler(outcome.value, ctx)); + }; + } else if (maybeHandler) stored = async (request, ctx) => { + const parsed = await validateStandardSchema(schemasOrHandler.params, { ...request.params }); + if (!parsed.success) throw new src_CX2iR2pK_ProtocolError(src_CX2iR2pK_ProtocolErrorCode.InvalidParams, `Invalid params for ${method}: ${parsed.error}`); + return maybeHandler(parsed.data, ctx); + }; + else throw new TypeError("setRequestHandler: handler is required"); + this._requestHandlers.set(method, this._wrapHandler(method, stored)); + } + /** + * Hook for subclasses to wrap a registered request handler with role-specific + * validation or behavior (e.g. `Server` validates `tools/call` results, `Client` + * validates `elicitation/create` mode and result). Runs for both the 2-arg and + * 3-arg registration paths. The default implementation is identity. + * + * Subclasses overriding this hook avoid redeclaring `setRequestHandler`'s overload set. + */ + _wrapHandler(_method, handler) { + return handler; + } + /** + * Hook for subclasses to supply the implementation identity the 2026-era + * encode seam stamps into outbound result `_meta` under + * `io.modelcontextprotocol/serverInfo` (spec PR #3002: servers SHOULD + * identify themselves on every response). The default is `undefined` — no + * stamp. Only `Server` overrides this: the key identifies the software + * producing a response, and the 2025-era codec never stamps anything + * regardless (the never-stamp guarantee). + */ + _outboundServerInfo() {} + /** + * Removes the request handler for the given method. + */ + removeRequestHandler(method) { + this._requestHandlers.delete(method); + } + /** + * Asserts that a request handler has not already been set for the given method, in preparation for a new one being automatically installed. + */ + assertCanSetRequestHandler(method) { + if (this._requestHandlers.has(method)) throw new Error(`A request handler for ${method} already exists, which would be overridden`); + } + setNotificationHandler(method, schemasOrHandler, maybeHandler) { + if (typeof schemasOrHandler === "function") { + if (!isSpecNotificationMethod(method)) throw new TypeError(`'${method}' is not a spec notification method; pass schemas as the second argument to setNotificationHandler().`); + this._notificationHandlers.set(method, (notification, codec) => { + const outcome = codec.validateNotification(method, notification); + if (!outcome.ok) { + if (outcome.reason === "not-in-era") throw new src_CX2iR2pK_ProtocolError(src_CX2iR2pK_ProtocolErrorCode.InternalError, `No wire schema for ${method} in the resolved era`); + throw new Error(outcome.message); + } + return Promise.resolve(schemasOrHandler(outcome.value)); + }); + return; + } + if (!maybeHandler) throw new TypeError("setNotificationHandler: handler is required"); + this._notificationHandlers.set(method, async (notification) => { + const parsed = await validateStandardSchema(schemasOrHandler.params, { ...notification.params }); + if (!parsed.success) throw new src_CX2iR2pK_ProtocolError(src_CX2iR2pK_ProtocolErrorCode.InvalidParams, `Invalid params for notification ${method}: ${parsed.error}`); + await maybeHandler(parsed.data, notification); + }); + } + /** + * Removes the notification handler for the given method. + */ + removeNotificationHandler(method) { + this._notificationHandlers.delete(method); + } +}; +function isPlainObject$1(value) { + return value !== null && typeof value === "object" && !Array.isArray(value); +} +function mergeCapabilities(base, additional) { + const result = { ...base }; + for (const key in additional) { + const k = key; + const addValue = additional[k]; + if (addValue === void 0) continue; + const baseValue = result[k]; + result[k] = isPlainObject$1(baseValue) && isPlainObject$1(addValue) ? { + ...baseValue, + ...addValue + } : addValue; + } + return result; +} + +//#endregion +//#region ../core-internal/src/shared/inputRequiredEngine.ts +function src_CX2iR2pK_isPlainObject(value) { + return typeof value === "object" && value !== null && !Array.isArray(value); +} +/** +* Splits a retried request's `inputResponses` map into the BARE response +* entries the spec defines and everything else. The spec's embedded responses +* are the bare result objects (an `ElicitResult`, `CreateMessageResult`, or +* `ListRootsResult`); a wrapped `{method, result}` envelope (a shape some +* peers emit) is never accepted as a response — its key is recorded so the +* handler can re-issue the corresponding input request. +*/ +function partitionInputResponses(inputResponses) { + const accepted = {}; + const droppedKeys = []; + if (!src_CX2iR2pK_isPlainObject(inputResponses)) return { + accepted, + droppedKeys + }; + for (const [key, entry] of Object.entries(inputResponses)) { + if (!src_CX2iR2pK_isPlainObject(entry) || "method" in entry || "result" in entry) { + droppedKeys.push(key); + continue; + } + accepted[key] = entry; + } + return { + accepted, + droppedKeys + }; +} +/** +* Builds the manual-mode {@linkcode InputRequiredResult} value from the +* codec's decoded payload — what an `allowInputRequired: true` caller +* receives instead of the auto-fulfilled complete result. +*/ +function manualInputRequiredValue(decoded) { + return { + resultType: "input_required", + inputRequests: decoded.inputRequests, + ...decoded.requestState !== void 0 && { requestState: decoded.requestState } + }; +} + +//#endregion +//#region ../../node_modules/.pnpm/content-type@1.0.5/node_modules/content-type/index.js +/*! +* content-type +* Copyright(c) 2015 Douglas Christopher Wilson +* MIT Licensed +*/ +var require_content_type = /* @__PURE__ */ __commonJSMin(((exports) => { + /** + * RegExp to match *( ";" parameter ) in RFC 7231 sec 3.1.1.1 + * + * parameter = token "=" ( token / quoted-string ) + * token = 1*tchar + * tchar = "!" / "#" / "$" / "%" / "&" / "'" / "*" + * / "+" / "-" / "." / "^" / "_" / "`" / "|" / "~" + * / DIGIT / ALPHA + * ; any VCHAR, except delimiters + * quoted-string = DQUOTE *( qdtext / quoted-pair ) DQUOTE + * qdtext = HTAB / SP / %x21 / %x23-5B / %x5D-7E / obs-text + * obs-text = %x80-FF + * quoted-pair = "\" ( HTAB / SP / VCHAR / obs-text ) + */ + var PARAM_REGEXP = /; *([!#$%&'*+.^_`|~0-9A-Za-z-]+) *= *("(?:[\u000b\u0020\u0021\u0023-\u005b\u005d-\u007e\u0080-\u00ff]|\\[\u000b\u0020-\u00ff])*"|[!#$%&'*+.^_`|~0-9A-Za-z-]+) */g; + /** + * RegExp to match quoted-pair in RFC 7230 sec 3.2.6 + * + * quoted-pair = "\" ( HTAB / SP / VCHAR / obs-text ) + * obs-text = %x80-FF + */ + var QESC_REGEXP = /\\([\u000b\u0020-\u00ff])/g; + /** + * RegExp to match type in RFC 7231 sec 3.1.1.1 + * + * media-type = type "/" subtype + * type = token + * subtype = token + */ + var TYPE_REGEXP = /^[!#$%&'*+.^_`|~0-9A-Za-z-]+\/[!#$%&'*+.^_`|~0-9A-Za-z-]+$/; + exports.parse = parse; + /** + * Parse media type to object. + * + * @param {string|object} string + * @return {Object} + * @public + */ + function parse(string) { + if (!string) throw new TypeError("argument string is required"); + var header = typeof string === "object" ? getcontenttype(string) : string; + if (typeof header !== "string") throw new TypeError("argument string is required to be a string"); + var index = header.indexOf(";"); + var type = index !== -1 ? header.slice(0, index).trim() : header.trim(); + if (!TYPE_REGEXP.test(type)) throw new TypeError("invalid media type"); + var obj = new ContentType(type.toLowerCase()); + if (index !== -1) { + var key; + var match; + var value; + PARAM_REGEXP.lastIndex = index; + while (match = PARAM_REGEXP.exec(header)) { + if (match.index !== index) throw new TypeError("invalid parameter format"); + index += match[0].length; + key = match[1].toLowerCase(); + value = match[2]; + if (value.charCodeAt(0) === 34) { + value = value.slice(1, -1); + if (value.indexOf("\\") !== -1) value = value.replace(QESC_REGEXP, "$1"); + } + obj.parameters[key] = value; + } + if (index !== header.length) throw new TypeError("invalid parameter format"); + } + return obj; + } + /** + * Get content-type from req/res objects. + * + * @param {object} + * @return {Object} + * @private + */ + function getcontenttype(obj) { + var header; + if (typeof obj.getHeader === "function") header = obj.getHeader("content-type"); + else if (typeof obj.headers === "object") header = obj.headers && obj.headers["content-type"]; + if (typeof header !== "string") throw new TypeError("content-type header is missing from object"); + return header; + } + /** + * Class to represent a content type. + * @private + */ + function ContentType(type) { + this.parameters = Object.create(null); + this.type = type; + } +})); + +//#endregion +//#region ../core-internal/src/shared/mediaType.ts +var import_content_type = /* @__PURE__ */ __toESM(require_content_type(), 1); +/** +* Extracts the media type (the lowercased `type/subtype` pair, without +* parameters) from a raw `Content-Type` header value, or `undefined` when the +* header is missing or empty. +* +* Content-Type comparisons must use the parsed media type, never a substring +* search of the raw header: a value like `text/plain; a=application/json` +* contains the substring `application/json` but its media type is +* `text/plain`, and case variants or parameters make naive string comparison +* wrong in both directions. +* +* "Essence" is the WHATWG MIME Sniffing standard's term for the bare +* `type/subtype` pair (https://mimesniff.spec.whatwg.org/#mime-type-essence); +* the Fetch standard's request classification is defined against it +* (https://fetch.spec.whatwg.org/#cors-safelisted-request-header). +* +* Parsing is RFC 9110 (`content-type` package) first. When the parameter +* section is malformed (`application/json;`, `application/json; charset=`), +* browsers and most HTTP stacks still derive the media type from the segment +* before the first `;` — the fallback matches that widely-implemented +* behavior, so a header whose media type is unambiguous is not rejected for +* a sloppy parameter section. +*/ +function src_CX2iR2pK_mediaTypeEssence(header) { + if (!header) return; + try { + return import_content_type.parse(header).type; + } catch { + const essence = (header.split(";", 1)[0] ?? "").trim().toLowerCase(); + if (essence === "" || header.slice(essence.length).includes(",")) return; + return essence; + } +} +/** +* Whether a raw `Content-Type` header value denotes `application/json`. +* Parameters (for example `charset=utf-8`) are allowed and ignored; malformed +* parameter sections do not reject a header whose media type is unambiguously +* `application/json` (see `mediaTypeEssence` for the exact grammar). +*/ +function src_CX2iR2pK_isJsonContentType(header) { + if (header === "application/json") return true; + return src_CX2iR2pK_mediaTypeEssence(header) === "application/json"; +} + +//#endregion +//#region ../core-internal/src/shared/metadataUtils.ts +/** +* Utilities for working with {@linkcode BaseMetadata} objects. +*/ +/** +* Gets the display name for an object with {@linkcode BaseMetadata}. +* For tools, the precedence is: `title` → {@linkcode index.ToolAnnotations | annotations}.`title` → `name` +* For other objects: `title` → `name` +* This implements the spec requirement: "if no title is provided, name should be used for display purposes" +*/ +function getDisplayName(metadata) { + if (metadata.title !== void 0 && metadata.title !== "") return metadata.title; + if ("annotations" in metadata && metadata.annotations?.title) return metadata.annotations.title; + return metadata.name; +} + +//#endregion +//#region ../core-internal/src/shared/stdio.ts +const STDIO_DEFAULT_MAX_BUFFER_SIZE = 10 * 1024 * 1024; +/** +* Buffers a continuous stdio stream into discrete JSON-RPC messages. +*/ +var ReadBuffer = class { + _buffer; + _maxBufferSize; + constructor(options) { + this._maxBufferSize = options?.maxBufferSize ?? STDIO_DEFAULT_MAX_BUFFER_SIZE; + } + append(chunk) { + if ((this._buffer?.length ?? 0) + chunk.length > this._maxBufferSize) { + this.clear(); + throw new Error(`ReadBuffer exceeded maximum size of ${this._maxBufferSize} bytes`); + } + this._buffer = this._buffer ? Buffer.concat([this._buffer, chunk]) : chunk; + } + readMessage() { + while (this._buffer) { + const index = this._buffer.indexOf("\n"); + if (index === -1) return null; + const line = this._buffer.toString("utf8", 0, index).replace(/\r$/, ""); + this._buffer = this._buffer.subarray(index + 1); + try { + return deserializeMessage(line); + } catch (error) { + if (error instanceof SyntaxError) continue; + throw error; + } + } + return null; + } + clear() { + this._buffer = void 0; + } +}; +function deserializeMessage(line) { + return auth_CUe6YdwF_JSONRPCMessageSchema.parse(JSON.parse(line)); +} +function serializeMessage(message) { + return JSON.stringify(message) + "\n"; +} + +//#endregion +//#region ../core-internal/src/shared/toolNameValidation.ts +/** +* Tool name validation utilities according to SEP: Specify Format for Tool Names +* +* Tool names SHOULD be between 1 and 128 characters in length (inclusive). +* Tool names are case-sensitive. +* Allowed characters: uppercase and lowercase ASCII letters (`A-Z`, `a-z`), digits +* (`0-9`), underscore (`_`), dash (`-`), and dot (`.`). +* Tool names SHOULD NOT contain spaces, commas, or other special characters. +* +* @see {@link https://github.com/modelcontextprotocol/modelcontextprotocol/issues/986 | SEP-986: Specify Format for Tool Names} +*/ +/** +* Regular expression for valid tool names according to SEP-986 specification +*/ +const TOOL_NAME_REGEX = /^[A-Za-z0-9._-]{1,128}$/; +/** +* Validates a tool name according to the SEP specification +* @param name - The tool name to validate +* @returns An object containing validation result and any warnings +*/ +function validateToolName(name) { + const warnings = []; + if (name.length === 0) return { + isValid: false, + warnings: ["Tool name cannot be empty"] + }; + if (name.length > 128) return { + isValid: false, + warnings: [`Tool name exceeds maximum length of 128 characters (current: ${name.length})`] + }; + if (name.includes(" ")) warnings.push("Tool name contains spaces, which may cause parsing issues"); + if (name.includes(",")) warnings.push("Tool name contains commas, which may cause parsing issues"); + if (name.startsWith("-") || name.endsWith("-")) warnings.push("Tool name starts or ends with a dash, which may cause parsing issues in some contexts"); + if (name.startsWith(".") || name.endsWith(".")) warnings.push("Tool name starts or ends with a dot, which may cause parsing issues in some contexts"); + if (!TOOL_NAME_REGEX.test(name)) { + const invalidChars = [...name].filter((char) => !/[A-Za-z0-9._-]/.test(char)).filter((char, index, arr) => arr.indexOf(char) === index); + warnings.push(`Tool name contains invalid characters: ${invalidChars.map((c) => `"${c}"`).join(", ")}`, "Allowed characters are: A-Z, a-z, 0-9, underscore (_), dash (-), and dot (.)"); + return { + isValid: false, + warnings + }; + } + return { + isValid: true, + warnings + }; +} +/** +* Issues warnings for non-conforming tool names +* @param name - The tool name that triggered the warnings +* @param warnings - Array of warning messages +*/ +function issueToolNameWarning(name, warnings) { + if (warnings.length > 0) { + console.warn(`Tool name validation warning for "${name}":`); + for (const warning of warnings) console.warn(` - ${warning}`); + console.warn("Tool registration will proceed, but this may cause compatibility issues."); + console.warn("Consider updating the tool name to conform to the MCP tool naming standard."); + console.warn("See SEP: Specify Format for Tool Names (https://github.com/modelcontextprotocol/modelcontextprotocol/issues/986) for more details."); + } +} +/** +* Validates a tool name and issues warnings for non-conforming names +* @param name - The tool name to validate +* @returns `true` if the name is valid, `false` otherwise +*/ +function validateAndWarnToolName(name) { + const result = validateToolName(name); + issueToolNameWarning(name, result.warnings); + return result.isValid; +} + +//#endregion +//#region ../core-internal/src/shared/transport.ts +/** +* Normalizes `HeadersInit` to a plain `Record` for manipulation. +* Handles `Headers` objects, arrays of tuples, and plain objects. +*/ +function normalizeHeaders(headers) { + if (!headers) return {}; + if (headers instanceof Headers) return Object.fromEntries(headers.entries()); + if (Array.isArray(headers)) return Object.fromEntries(headers); + return { ...headers }; +} +/** +* Creates a fetch function that includes base `RequestInit` options. +* This ensures requests inherit settings like credentials, mode, headers, etc. from the base init. +* +* @param baseFetch - The base fetch function to wrap (defaults to global `fetch`) +* @param baseInit - The base `RequestInit` to merge with each request +* @returns A wrapped fetch function that merges base options with call-specific options +*/ +function createFetchWithInit(baseFetch = fetch, baseInit) { + if (!baseInit) return baseFetch; + return async (url, init) => { + return baseFetch(url, { + ...baseInit, + ...init, + headers: init?.headers ? { + ...normalizeHeaders(baseInit.headers), + ...normalizeHeaders(init.headers) + } : baseInit.headers + }); + }; +} + +//#endregion +//#region ../core-internal/src/shared/uriTemplate.ts +const MAX_TEMPLATE_LENGTH = 1e6; +const MAX_VARIABLE_LENGTH = 1e6; +const MAX_TEMPLATE_EXPRESSIONS = 1e4; +const MAX_REGEX_LENGTH = 1e6; +var src_CX2iR2pK_UriTemplate = class UriTemplate { + /** + * Returns true if the given string contains any URI template expressions. + * A template expression is a sequence of characters enclosed in curly braces, + * like `{foo}` or `{?bar}`. + */ + static isTemplate(str) { + return /\{[^}\s]+\}/.test(str); + } + static validateLength(str, max, context) { + if (str.length > max) throw new Error(`${context} exceeds maximum length of ${max} characters (got ${str.length})`); + } + template; + parts; + get variableNames() { + return this.parts.flatMap((part) => typeof part === "string" ? [] : part.names); + } + constructor(template) { + UriTemplate.validateLength(template, MAX_TEMPLATE_LENGTH, "Template"); + this.template = template; + this.parts = this.parse(template); + } + toString() { + return this.template; + } + parse(template) { + const parts = []; + let currentText = ""; + let i = 0; + let expressionCount = 0; + while (i < template.length) if (template[i] === "{") { + if (currentText) { + parts.push(currentText); + currentText = ""; + } + const end = template.indexOf("}", i); + if (end === -1) throw new Error("Unclosed template expression"); + expressionCount++; + if (expressionCount > MAX_TEMPLATE_EXPRESSIONS) throw new Error(`Template contains too many expressions (max ${MAX_TEMPLATE_EXPRESSIONS})`); + const expr = template.slice(i + 1, end); + const operator = this.getOperator(expr); + const exploded = expr.includes("*"); + const names = this.getNames(expr); + const name = names[0]; + for (const name$1 of names) UriTemplate.validateLength(name$1, MAX_VARIABLE_LENGTH, "Variable name"); + parts.push({ + name, + operator, + names, + exploded + }); + i = end + 1; + } else { + currentText += template[i]; + i++; + } + if (currentText) parts.push(currentText); + return parts; + } + getOperator(expr) { + return [ + "+", + "#", + ".", + "/", + "?", + "&" + ].find((op) => expr.startsWith(op)) || ""; + } + getNames(expr) { + const operator = this.getOperator(expr); + return expr.slice(operator.length).split(",").map((name) => name.replace("*", "").trim()).filter((name) => name.length > 0); + } + encodeValue(value, operator) { + UriTemplate.validateLength(value, MAX_VARIABLE_LENGTH, "Variable value"); + if (operator === "+" || operator === "#") return encodeURI(value); + return encodeURIComponent(value); + } + expandPart(part, variables) { + if (part.operator === "?" || part.operator === "&") { + const pairs = part.names.map((name) => { + const value$1 = variables[name]; + if (value$1 === void 0) return ""; + return `${name}=${Array.isArray(value$1) ? value$1.map((v) => this.encodeValue(v, part.operator)).join(",") : this.encodeValue(value$1.toString(), part.operator)}`; + }).filter((pair) => pair.length > 0); + if (pairs.length === 0) return ""; + return (part.operator === "?" ? "?" : "&") + pairs.join("&"); + } + if (part.names.length > 1) { + const values = part.names.map((name) => variables[name]).filter((v) => v !== void 0); + if (values.length === 0) return ""; + return values.map((v) => Array.isArray(v) ? v[0] : v).join(","); + } + const value = variables[part.name]; + if (value === void 0) return ""; + const encoded = (Array.isArray(value) ? value : [value]).map((v) => this.encodeValue(v, part.operator)); + switch (part.operator) { + case "": return encoded.join(","); + case "+": return encoded.join(","); + case "#": return "#" + encoded.join(","); + case ".": return "." + encoded.join("."); + case "/": return "/" + encoded.join("/"); + default: return encoded.join(","); + } + } + expand(variables) { + let result = ""; + let hasQueryParam = false; + for (const part of this.parts) { + if (typeof part === "string") { + result += part; + continue; + } + const expanded = this.expandPart(part, variables); + if (!expanded) continue; + result += (part.operator === "?" || part.operator === "&") && hasQueryParam ? expanded.replace("?", "&") : expanded; + if (part.operator === "?" || part.operator === "&") hasQueryParam = true; + } + return result; + } + escapeRegExp(str) { + return str.replaceAll(/[.*+?^${}()|[\]\\]/g, String.raw`\$&`); + } + partToRegExp(part) { + const patterns = []; + for (const name$1 of part.names) UriTemplate.validateLength(name$1, MAX_VARIABLE_LENGTH, "Variable name"); + if (part.operator === "?" || part.operator === "&") { + for (let i = 0; i < part.names.length; i++) { + const name$1 = part.names[i]; + const prefix = i === 0 ? "\\" + part.operator : "&"; + patterns.push({ + pattern: prefix + this.escapeRegExp(name$1) + "=([^&]+)", + name: name$1 + }); + } + return patterns; + } + let pattern; + const name = part.name; + switch (part.operator) { + case "": + pattern = part.exploded ? "([^/,]+(?:,[^/,]+)*)" : "([^/,]+)"; + break; + case "+": + case "#": + pattern = "(.+)"; + break; + case ".": + pattern = String.raw`\.([^/,]+)`; + break; + case "/": + pattern = "/" + (part.exploded ? "([^/,]+(?:,[^/,]+)*)" : "([^/,]+)"); + break; + default: pattern = "([^/]+)"; + } + patterns.push({ + pattern, + name + }); + return patterns; + } + match(uri) { + UriTemplate.validateLength(uri, MAX_TEMPLATE_LENGTH, "URI"); + let pattern = "^"; + const names = []; + for (const part of this.parts) if (typeof part === "string") pattern += this.escapeRegExp(part); + else { + const patterns = this.partToRegExp(part); + for (const { pattern: partPattern, name } of patterns) { + pattern += partPattern; + names.push({ + name, + exploded: part.exploded + }); + } + } + pattern += "$"; + UriTemplate.validateLength(pattern, MAX_REGEX_LENGTH, "Generated regex pattern"); + const regex = new RegExp(pattern); + const match = uri.match(regex); + if (!match) return null; + const result = {}; + for (const [i, name_] of names.entries()) { + const { name, exploded } = name_; + const value = match[i + 1]; + const cleanName = name.replace("*", ""); + result[cleanName] = exploded && value.includes(",") ? value.split(",") : value; + } + return result; + } +}; + +//#endregion +//#region ../core-internal/src/util/inMemory.ts +/** +* In-memory transport for creating clients and servers that talk to each other within the same process. +* +* Intended for testing and development. For production in-process connections, use +* `StreamableHTTPClientTransport` against a local server URL. +*/ +var src_CX2iR2pK_InMemoryTransport = class InMemoryTransport { + _otherTransport; + _messageQueue = []; + _closed = false; + onclose; + onerror; + onmessage; + sessionId; + /** + * Creates a pair of linked in-memory transports that can communicate with each other. One should be passed to a {@linkcode @modelcontextprotocol/client!client/client.Client | Client} and one to a {@linkcode @modelcontextprotocol/server!server/server.Server | Server}. + */ + static createLinkedPair() { + const clientTransport = new InMemoryTransport(); + const serverTransport = new InMemoryTransport(); + clientTransport._otherTransport = serverTransport; + serverTransport._otherTransport = clientTransport; + return [clientTransport, serverTransport]; + } + async start() { + while (this._messageQueue.length > 0) { + const queuedMessage = this._messageQueue.shift(); + this.onmessage?.(queuedMessage.message, queuedMessage.extra); + } + } + async close() { + if (this._closed) return; + this._closed = true; + const other = this._otherTransport; + this._otherTransport = void 0; + try { + await other?.close(); + } finally { + this.onclose?.(); + } + } + /** + * Sends a message with optional auth info. + * This is useful for testing authentication scenarios. + */ + async send(message, options) { + if (!this._otherTransport) throw new src_CX2iR2pK_SdkError(src_CX2iR2pK_SdkErrorCode.NotConnected, "Not connected"); + if (this._otherTransport.onmessage) this._otherTransport.onmessage(message, { authInfo: options?.authInfo }); + else this._otherTransport._messageQueue.push({ + message, + extra: { authInfo: options?.authInfo } + }); + } +}; + +//#endregion +//#region ../core-internal/src/util/zodCompat.ts +/** +* Zod-specific helpers for the v1-compat raw-shape shorthand on +* `registerTool`/`registerPrompt`. Kept separate from `standardSchema.ts` so +* that file stays library-agnostic per the Standard Schema spec. +*/ +function isZodV4Schema(v) { + return typeof v === "object" && v !== null && "_zod" in v; +} +function looksLikeZodV3(v) { + return typeof v === "object" && v !== null && !("_zod" in v) && "_def" in v && typeof v._def?.typeName === "string"; +} +/** +* Detects a "raw shape" — a plain object whose values are Zod field schemas, +* e.g. `{ name: z.string() }`. Powers the auto-wrap in +* {@linkcode normalizeRawShapeSchema}, which wraps with `z.object()`, so only +* Zod values are supported. +* +* @internal +*/ +function isZodRawShape(obj) { + if (typeof obj !== "object" || obj === null) return false; + if (isStandardSchema(obj)) return false; + const proto = Object.getPrototypeOf(obj); + if (proto !== Object.prototype && proto !== null) return false; + return Object.values(obj).every((v) => isZodV4Schema(v)); +} +/** +* Accepts either a {@linkcode StandardSchemaWithJSON} or a raw Zod shape +* `{ field: z.string() }` and returns a {@linkcode StandardSchemaWithJSON}. +* Raw shapes are wrapped with `z.object()` so the rest of the pipeline sees a +* uniform schema type; already-wrapped schemas pass through unchanged. +* +* @internal +*/ +function normalizeRawShapeSchema(schema) { + if (schema === void 0) return void 0; + if (isZodRawShape(schema)) return schemas_object(schema); + if (typeof schema === "object" && schema !== null && !isStandardSchema(schema) && Object.values(schema).some((v) => looksLikeZodV3(v))) throw new TypeError("Raw-shape inputSchema/outputSchema/argsSchema fields must be Zod v4 schemas. Got a Zod v3 field schema. Import from `zod/v4` (or upgrade your zod import), or wrap with `z.object({...})` yourself."); + if (!isStandardSchema(schema)) throw new TypeError("inputSchema/outputSchema/argsSchema must be a Standard Schema (e.g. z.object({...})) or a raw Zod shape ({ field: z.string() })."); + return schema; +} + +//#endregion +//#region ../core-internal/src/wire/preload.ts +/** +* Explicit warm-up entry for the lazy wire-schema layers. +* +* The per-revision wire schemas are built lazily: each era's schema set sits +* behind a memoized factory (`buildSchemas2025`/`buildSchemas2026`), and the +* registry/codec lookup maps above those factories are memoized the same way. +* That laziness is the right default on process-per-invocation runtimes (CLI +* tools, dev servers), where module evaluation IS startup latency and most +* short-lived processes never validate a message on both eras. +* +* On platforms that bill request CPU but not module evaluation — isolate-based +* edge/serverless runtimes such as Cloudflare Workers — the trade inverts: +* module-scope work runs during isolate warm-up outside any request, while +* lazy construction lands inside the first request's billed (and latency +* budgeted) CPU. `preloadSchemas()` lets deployments on such platforms move +* the one-time construction cost back to module scope by calling it at module +* scope themselves. The packages' own workerd shims already do this, so +* Workers deployments get eager construction automatically. +*/ +/** +* Eagerly builds every lazily-constructed wire-schema layer, so that no later +* validation pays schema-construction cost. +* +* Synchronous and idempotent: every layer is a memo, so the first call does +* all the work and subsequent calls return immediately. Reference identity is +* unaffected — this forces the same memos every lazy consumer pulls through. +* +* Call it at module scope on platforms that bill per-request CPU but not +* module evaluation (isolate-based edge/serverless runtimes), where deferring +* construction would move it into the first request of every fresh isolate: +* +* ```ts +* // from '@modelcontextprotocol/server' or '@modelcontextprotocol/client' — +* // each package bundles its own schema copy, so warm the one(s) you import. +* preloadSchemas(); // module scope — runs during isolate warm-up +* ``` +* +* On Node CLIs and other process-per-invocation runtimes, prefer the lazy +* default — there, module-scope construction is pure added boot latency. +*/ +function preloadSchemas() { + buildSchemas2025(); + buildSchemas2026(); + warmRegistryMaps2025(); + warmInputSchemaMaps2026(); + warmWireResultSchemas2026(); +} + +//#endregion +//#region ../core-internal/src/validators/fromJsonSchema.ts +/** +* Wrap a raw JSON Schema object as a {@linkcode StandardSchemaWithJSON} so it can be +* passed to `registerTool` / `registerPrompt`. Use this when you already have JSON +* Schema (e.g. from TypeBox, or hand-written) and want to register it without going +* through a Standard Schema library. +* +* The callback arguments will be typed `unknown` (raw JSON Schema has no TypeScript +* types attached). Cast at the call site, or use the generic `fromJsonSchema(...)`. +* +* @param schema - A JSON Schema object describing the expected shape +* @param validator - A validator provider. When importing `fromJsonSchema` from +* `@modelcontextprotocol/server` or `@modelcontextprotocol/client`, a runtime-appropriate +* default is provided automatically (AJV on Node.js, CfWorker on edge runtimes). +* +* @example +* ```ts source="./fromJsonSchema.examples.ts#fromJsonSchema_basicUsage" +* const inputSchema = fromJsonSchema<{ name: string }>( +* { type: 'object', properties: { name: { type: 'string' } }, required: ['name'] }, +* validator +* ); +* // Use with server.registerTool('greet', { inputSchema }, handler) +* ``` +*/ +function fromJsonSchema(schema, validator) { + const check = validator.getValidator(schema); + return { "~standard": { + version: 1, + vendor: "mcp", + jsonSchema: { + input: () => schema, + output: () => schema + }, + validate: (data) => { + const result = check(data); + return result.valid ? { value: result.data } : { issues: [{ message: result.errorMessage }] }; + } + } }; +} + +//#endregion + +//# sourceMappingURL=src-CX2iR2pK.mjs.map + + + +//#region ../../node_modules/.pnpm/ajv@8.18.0/node_modules/ajv/dist/compile/codegen/code.js +var require_code$1 = /* @__PURE__ */ __commonJSMin(((exports) => { + Object.defineProperty(exports, "__esModule", { value: true }); + exports.regexpCode = exports.getEsmExportName = exports.getProperty = exports.safeStringify = exports.stringify = exports.strConcat = exports.addCodeArg = exports.str = exports._ = exports.nil = exports._Code = exports.Name = exports.IDENTIFIER = exports._CodeOrName = void 0; + var _CodeOrName = class {}; + exports._CodeOrName = _CodeOrName; + exports.IDENTIFIER = /^[a-z$_][a-z$_0-9]*$/i; + var Name = class extends _CodeOrName { + constructor(s) { + super(); + if (!exports.IDENTIFIER.test(s)) throw new Error("CodeGen: name must be a valid identifier"); + this.str = s; + } + toString() { + return this.str; + } + emptyStr() { + return false; + } + get names() { + return { [this.str]: 1 }; + } + }; + exports.Name = Name; + var _Code = class extends _CodeOrName { + constructor(code) { + super(); + this._items = typeof code === "string" ? [code] : code; + } + toString() { + return this.str; + } + emptyStr() { + if (this._items.length > 1) return false; + const item = this._items[0]; + return item === "" || item === "\"\""; + } + get str() { + var _a; + return (_a = this._str) !== null && _a !== void 0 ? _a : this._str = this._items.reduce((s, c) => `${s}${c}`, ""); + } + get names() { + var _a; + return (_a = this._names) !== null && _a !== void 0 ? _a : this._names = this._items.reduce((names, c) => { + if (c instanceof Name) names[c.str] = (names[c.str] || 0) + 1; + return names; + }, {}); + } + }; + exports._Code = _Code; + exports.nil = new _Code(""); + function _(strs, ...args) { + const code = [strs[0]]; + let i = 0; + while (i < args.length) { + addCodeArg(code, args[i]); + code.push(strs[++i]); + } + return new _Code(code); + } + exports._ = _; + const plus = new _Code("+"); + function str(strs, ...args) { + const expr = [safeStringify(strs[0])]; + let i = 0; + while (i < args.length) { + expr.push(plus); + addCodeArg(expr, args[i]); + expr.push(plus, safeStringify(strs[++i])); + } + optimize(expr); + return new _Code(expr); + } + exports.str = str; + function addCodeArg(code, arg) { + if (arg instanceof _Code) code.push(...arg._items); + else if (arg instanceof Name) code.push(arg); + else code.push(interpolate(arg)); + } + exports.addCodeArg = addCodeArg; + function optimize(expr) { + let i = 1; + while (i < expr.length - 1) { + if (expr[i] === plus) { + const res = mergeExprItems(expr[i - 1], expr[i + 1]); + if (res !== void 0) { + expr.splice(i - 1, 3, res); + continue; + } + expr[i++] = "+"; + } + i++; + } + } + function mergeExprItems(a, b) { + if (b === "\"\"") return a; + if (a === "\"\"") return b; + if (typeof a == "string") { + if (b instanceof Name || a[a.length - 1] !== "\"") return; + if (typeof b != "string") return `${a.slice(0, -1)}${b}"`; + if (b[0] === "\"") return a.slice(0, -1) + b.slice(1); + return; + } + if (typeof b == "string" && b[0] === "\"" && !(a instanceof Name)) return `"${a}${b.slice(1)}`; + } + function strConcat(c1, c2) { + return c2.emptyStr() ? c1 : c1.emptyStr() ? c2 : str`${c1}${c2}`; + } + exports.strConcat = strConcat; + function interpolate(x) { + return typeof x == "number" || typeof x == "boolean" || x === null ? x : safeStringify(Array.isArray(x) ? x.join(",") : x); + } + function stringify(x) { + return new _Code(safeStringify(x)); + } + exports.stringify = stringify; + function safeStringify(x) { + return JSON.stringify(x).replace(/\u2028/g, "\\u2028").replace(/\u2029/g, "\\u2029"); + } + exports.safeStringify = safeStringify; + function getProperty(key) { + return typeof key == "string" && exports.IDENTIFIER.test(key) ? new _Code(`.${key}`) : _`[${key}]`; + } + exports.getProperty = getProperty; + function getEsmExportName(key) { + if (typeof key == "string" && exports.IDENTIFIER.test(key)) return new _Code(`${key}`); + throw new Error(`CodeGen: invalid export name: ${key}, use explicit $id name mapping`); + } + exports.getEsmExportName = getEsmExportName; + function regexpCode(rx) { + return new _Code(rx.toString()); + } + exports.regexpCode = regexpCode; +})); + +//#endregion +//#region ../../node_modules/.pnpm/ajv@8.18.0/node_modules/ajv/dist/compile/codegen/scope.js +var require_scope = /* @__PURE__ */ __commonJSMin(((exports) => { + Object.defineProperty(exports, "__esModule", { value: true }); + exports.ValueScope = exports.ValueScopeName = exports.Scope = exports.varKinds = exports.UsedValueState = void 0; + const code_1 = require_code$1(); + var ValueError = class extends Error { + constructor(name) { + super(`CodeGen: "code" for ${name} not defined`); + this.value = name.value; + } + }; + var UsedValueState; + (function(UsedValueState) { + UsedValueState[UsedValueState["Started"] = 0] = "Started"; + UsedValueState[UsedValueState["Completed"] = 1] = "Completed"; + })(UsedValueState || (exports.UsedValueState = UsedValueState = {})); + exports.varKinds = { + const: new code_1.Name("const"), + let: new code_1.Name("let"), + var: new code_1.Name("var") + }; + var Scope = class { + constructor({ prefixes, parent } = {}) { + this._names = {}; + this._prefixes = prefixes; + this._parent = parent; + } + toName(nameOrPrefix) { + return nameOrPrefix instanceof code_1.Name ? nameOrPrefix : this.name(nameOrPrefix); + } + name(prefix) { + return new code_1.Name(this._newName(prefix)); + } + _newName(prefix) { + const ng = this._names[prefix] || this._nameGroup(prefix); + return `${prefix}${ng.index++}`; + } + _nameGroup(prefix) { + var _a, _b; + if (((_b = (_a = this._parent) === null || _a === void 0 ? void 0 : _a._prefixes) === null || _b === void 0 ? void 0 : _b.has(prefix)) || this._prefixes && !this._prefixes.has(prefix)) throw new Error(`CodeGen: prefix "${prefix}" is not allowed in this scope`); + return this._names[prefix] = { + prefix, + index: 0 + }; + } + }; + exports.Scope = Scope; + var ValueScopeName = class extends code_1.Name { + constructor(prefix, nameStr) { + super(nameStr); + this.prefix = prefix; + } + setValue(value, { property, itemIndex }) { + this.value = value; + this.scopePath = (0, code_1._)`.${new code_1.Name(property)}[${itemIndex}]`; + } + }; + exports.ValueScopeName = ValueScopeName; + const line = (0, code_1._)`\n`; + var ValueScope = class extends Scope { + constructor(opts) { + super(opts); + this._values = {}; + this._scope = opts.scope; + this.opts = { + ...opts, + _n: opts.lines ? line : code_1.nil + }; + } + get() { + return this._scope; + } + name(prefix) { + return new ValueScopeName(prefix, this._newName(prefix)); + } + value(nameOrPrefix, value) { + var _a; + if (value.ref === void 0) throw new Error("CodeGen: ref must be passed in value"); + const name = this.toName(nameOrPrefix); + const { prefix } = name; + const valueKey = (_a = value.key) !== null && _a !== void 0 ? _a : value.ref; + let vs = this._values[prefix]; + if (vs) { + const _name = vs.get(valueKey); + if (_name) return _name; + } else vs = this._values[prefix] = /* @__PURE__ */ new Map(); + vs.set(valueKey, name); + const s = this._scope[prefix] || (this._scope[prefix] = []); + const itemIndex = s.length; + s[itemIndex] = value.ref; + name.setValue(value, { + property: prefix, + itemIndex + }); + return name; + } + getValue(prefix, keyOrRef) { + const vs = this._values[prefix]; + if (!vs) return; + return vs.get(keyOrRef); + } + scopeRefs(scopeName, values = this._values) { + return this._reduceValues(values, (name) => { + if (name.scopePath === void 0) throw new Error(`CodeGen: name "${name}" has no value`); + return (0, code_1._)`${scopeName}${name.scopePath}`; + }); + } + scopeCode(values = this._values, usedValues, getCode) { + return this._reduceValues(values, (name) => { + if (name.value === void 0) throw new Error(`CodeGen: name "${name}" has no value`); + return name.value.code; + }, usedValues, getCode); + } + _reduceValues(values, valueCode, usedValues = {}, getCode) { + let code = code_1.nil; + for (const prefix in values) { + const vs = values[prefix]; + if (!vs) continue; + const nameSet = usedValues[prefix] = usedValues[prefix] || /* @__PURE__ */ new Map(); + vs.forEach((name) => { + if (nameSet.has(name)) return; + nameSet.set(name, UsedValueState.Started); + let c = valueCode(name); + if (c) { + const def = this.opts.es5 ? exports.varKinds.var : exports.varKinds.const; + code = (0, code_1._)`${code}${def} ${name} = ${c};${this.opts._n}`; + } else if (c = getCode === null || getCode === void 0 ? void 0 : getCode(name)) code = (0, code_1._)`${code}${c}${this.opts._n}`; + else throw new ValueError(name); + nameSet.set(name, UsedValueState.Completed); + }); + } + return code; + } + }; + exports.ValueScope = ValueScope; +})); + +//#endregion +//#region ../../node_modules/.pnpm/ajv@8.18.0/node_modules/ajv/dist/compile/codegen/index.js +var require_codegen = /* @__PURE__ */ __commonJSMin(((exports) => { + Object.defineProperty(exports, "__esModule", { value: true }); + exports.or = exports.and = exports.not = exports.CodeGen = exports.operators = exports.varKinds = exports.ValueScopeName = exports.ValueScope = exports.Scope = exports.Name = exports.regexpCode = exports.stringify = exports.getProperty = exports.nil = exports.strConcat = exports.str = exports._ = void 0; + const code_1 = require_code$1(); + const scope_1 = require_scope(); + var code_2 = require_code$1(); + Object.defineProperty(exports, "_", { + enumerable: true, + get: function() { + return code_2._; + } + }); + Object.defineProperty(exports, "str", { + enumerable: true, + get: function() { + return code_2.str; + } + }); + Object.defineProperty(exports, "strConcat", { + enumerable: true, + get: function() { + return code_2.strConcat; + } + }); + Object.defineProperty(exports, "nil", { + enumerable: true, + get: function() { + return code_2.nil; + } + }); + Object.defineProperty(exports, "getProperty", { + enumerable: true, + get: function() { + return code_2.getProperty; + } + }); + Object.defineProperty(exports, "stringify", { + enumerable: true, + get: function() { + return code_2.stringify; + } + }); + Object.defineProperty(exports, "regexpCode", { + enumerable: true, + get: function() { + return code_2.regexpCode; + } + }); + Object.defineProperty(exports, "Name", { + enumerable: true, + get: function() { + return code_2.Name; + } + }); + var scope_2 = require_scope(); + Object.defineProperty(exports, "Scope", { + enumerable: true, + get: function() { + return scope_2.Scope; + } + }); + Object.defineProperty(exports, "ValueScope", { + enumerable: true, + get: function() { + return scope_2.ValueScope; + } + }); + Object.defineProperty(exports, "ValueScopeName", { + enumerable: true, + get: function() { + return scope_2.ValueScopeName; + } + }); + Object.defineProperty(exports, "varKinds", { + enumerable: true, + get: function() { + return scope_2.varKinds; + } + }); + exports.operators = { + GT: new code_1._Code(">"), + GTE: new code_1._Code(">="), + LT: new code_1._Code("<"), + LTE: new code_1._Code("<="), + EQ: new code_1._Code("==="), + NEQ: new code_1._Code("!=="), + NOT: new code_1._Code("!"), + OR: new code_1._Code("||"), + AND: new code_1._Code("&&"), + ADD: new code_1._Code("+") + }; + var Node = class { + optimizeNodes() { + return this; + } + optimizeNames(_names, _constants) { + return this; + } + }; + var Def = class extends Node { + constructor(varKind, name, rhs) { + super(); + this.varKind = varKind; + this.name = name; + this.rhs = rhs; + } + render({ es5, _n }) { + const varKind = es5 ? scope_1.varKinds.var : this.varKind; + const rhs = this.rhs === void 0 ? "" : ` = ${this.rhs}`; + return `${varKind} ${this.name}${rhs};` + _n; + } + optimizeNames(names, constants) { + if (!names[this.name.str]) return; + if (this.rhs) this.rhs = optimizeExpr(this.rhs, names, constants); + return this; + } + get names() { + return this.rhs instanceof code_1._CodeOrName ? this.rhs.names : {}; + } + }; + var Assign = class extends Node { + constructor(lhs, rhs, sideEffects) { + super(); + this.lhs = lhs; + this.rhs = rhs; + this.sideEffects = sideEffects; + } + render({ _n }) { + return `${this.lhs} = ${this.rhs};` + _n; + } + optimizeNames(names, constants) { + if (this.lhs instanceof code_1.Name && !names[this.lhs.str] && !this.sideEffects) return; + this.rhs = optimizeExpr(this.rhs, names, constants); + return this; + } + get names() { + return addExprNames(this.lhs instanceof code_1.Name ? {} : { ...this.lhs.names }, this.rhs); + } + }; + var AssignOp = class extends Assign { + constructor(lhs, op, rhs, sideEffects) { + super(lhs, rhs, sideEffects); + this.op = op; + } + render({ _n }) { + return `${this.lhs} ${this.op}= ${this.rhs};` + _n; + } + }; + var Label = class extends Node { + constructor(label) { + super(); + this.label = label; + this.names = {}; + } + render({ _n }) { + return `${this.label}:` + _n; + } + }; + var Break = class extends Node { + constructor(label) { + super(); + this.label = label; + this.names = {}; + } + render({ _n }) { + return `break${this.label ? ` ${this.label}` : ""};` + _n; + } + }; + var Throw = class extends Node { + constructor(error) { + super(); + this.error = error; + } + render({ _n }) { + return `throw ${this.error};` + _n; + } + get names() { + return this.error.names; + } + }; + var AnyCode = class extends Node { + constructor(code) { + super(); + this.code = code; + } + render({ _n }) { + return `${this.code};` + _n; + } + optimizeNodes() { + return `${this.code}` ? this : void 0; + } + optimizeNames(names, constants) { + this.code = optimizeExpr(this.code, names, constants); + return this; + } + get names() { + return this.code instanceof code_1._CodeOrName ? this.code.names : {}; + } + }; + var ParentNode = class extends Node { + constructor(nodes = []) { + super(); + this.nodes = nodes; + } + render(opts) { + return this.nodes.reduce((code, n) => code + n.render(opts), ""); + } + optimizeNodes() { + const { nodes } = this; + let i = nodes.length; + while (i--) { + const n = nodes[i].optimizeNodes(); + if (Array.isArray(n)) nodes.splice(i, 1, ...n); + else if (n) nodes[i] = n; + else nodes.splice(i, 1); + } + return nodes.length > 0 ? this : void 0; + } + optimizeNames(names, constants) { + const { nodes } = this; + let i = nodes.length; + while (i--) { + const n = nodes[i]; + if (n.optimizeNames(names, constants)) continue; + subtractNames(names, n.names); + nodes.splice(i, 1); + } + return nodes.length > 0 ? this : void 0; + } + get names() { + return this.nodes.reduce((names, n) => addNames(names, n.names), {}); + } + }; + var BlockNode = class extends ParentNode { + render(opts) { + return "{" + opts._n + super.render(opts) + "}" + opts._n; + } + }; + var Root = class extends ParentNode {}; + var Else = class extends BlockNode {}; + Else.kind = "else"; + var If = class If extends BlockNode { + constructor(condition, nodes) { + super(nodes); + this.condition = condition; + } + render(opts) { + let code = `if(${this.condition})` + super.render(opts); + if (this.else) code += "else " + this.else.render(opts); + return code; + } + optimizeNodes() { + super.optimizeNodes(); + const cond = this.condition; + if (cond === true) return this.nodes; + let e = this.else; + if (e) { + const ns = e.optimizeNodes(); + e = this.else = Array.isArray(ns) ? new Else(ns) : ns; + } + if (e) { + if (cond === false) return e instanceof If ? e : e.nodes; + if (this.nodes.length) return this; + return new If(not(cond), e instanceof If ? [e] : e.nodes); + } + if (cond === false || !this.nodes.length) return void 0; + return this; + } + optimizeNames(names, constants) { + var _a; + this.else = (_a = this.else) === null || _a === void 0 ? void 0 : _a.optimizeNames(names, constants); + if (!(super.optimizeNames(names, constants) || this.else)) return; + this.condition = optimizeExpr(this.condition, names, constants); + return this; + } + get names() { + const names = super.names; + addExprNames(names, this.condition); + if (this.else) addNames(names, this.else.names); + return names; + } + }; + If.kind = "if"; + var For = class extends BlockNode {}; + For.kind = "for"; + var ForLoop = class extends For { + constructor(iteration) { + super(); + this.iteration = iteration; + } + render(opts) { + return `for(${this.iteration})` + super.render(opts); + } + optimizeNames(names, constants) { + if (!super.optimizeNames(names, constants)) return; + this.iteration = optimizeExpr(this.iteration, names, constants); + return this; + } + get names() { + return addNames(super.names, this.iteration.names); + } + }; + var ForRange = class extends For { + constructor(varKind, name, from, to) { + super(); + this.varKind = varKind; + this.name = name; + this.from = from; + this.to = to; + } + render(opts) { + const varKind = opts.es5 ? scope_1.varKinds.var : this.varKind; + const { name, from, to } = this; + return `for(${varKind} ${name}=${from}; ${name}<${to}; ${name}++)` + super.render(opts); + } + get names() { + return addExprNames(addExprNames(super.names, this.from), this.to); + } + }; + var ForIter = class extends For { + constructor(loop, varKind, name, iterable) { + super(); + this.loop = loop; + this.varKind = varKind; + this.name = name; + this.iterable = iterable; + } + render(opts) { + return `for(${this.varKind} ${this.name} ${this.loop} ${this.iterable})` + super.render(opts); + } + optimizeNames(names, constants) { + if (!super.optimizeNames(names, constants)) return; + this.iterable = optimizeExpr(this.iterable, names, constants); + return this; + } + get names() { + return addNames(super.names, this.iterable.names); + } + }; + var Func = class extends BlockNode { + constructor(name, args, async) { + super(); + this.name = name; + this.args = args; + this.async = async; + } + render(opts) { + return `${this.async ? "async " : ""}function ${this.name}(${this.args})` + super.render(opts); + } + }; + Func.kind = "func"; + var Return = class extends ParentNode { + render(opts) { + return "return " + super.render(opts); + } + }; + Return.kind = "return"; + var Try = class extends BlockNode { + render(opts) { + let code = "try" + super.render(opts); + if (this.catch) code += this.catch.render(opts); + if (this.finally) code += this.finally.render(opts); + return code; + } + optimizeNodes() { + var _a, _b; + super.optimizeNodes(); + (_a = this.catch) === null || _a === void 0 || _a.optimizeNodes(); + (_b = this.finally) === null || _b === void 0 || _b.optimizeNodes(); + return this; + } + optimizeNames(names, constants) { + var _a, _b; + super.optimizeNames(names, constants); + (_a = this.catch) === null || _a === void 0 || _a.optimizeNames(names, constants); + (_b = this.finally) === null || _b === void 0 || _b.optimizeNames(names, constants); + return this; + } + get names() { + const names = super.names; + if (this.catch) addNames(names, this.catch.names); + if (this.finally) addNames(names, this.finally.names); + return names; + } + }; + var Catch = class extends BlockNode { + constructor(error) { + super(); + this.error = error; + } + render(opts) { + return `catch(${this.error})` + super.render(opts); + } + }; + Catch.kind = "catch"; + var Finally = class extends BlockNode { + render(opts) { + return "finally" + super.render(opts); + } + }; + Finally.kind = "finally"; + var CodeGen = class { + constructor(extScope, opts = {}) { + this._values = {}; + this._blockStarts = []; + this._constants = {}; + this.opts = { + ...opts, + _n: opts.lines ? "\n" : "" + }; + this._extScope = extScope; + this._scope = new scope_1.Scope({ parent: extScope }); + this._nodes = [new Root()]; + } + toString() { + return this._root.render(this.opts); + } + name(prefix) { + return this._scope.name(prefix); + } + scopeName(prefix) { + return this._extScope.name(prefix); + } + scopeValue(prefixOrName, value) { + const name = this._extScope.value(prefixOrName, value); + (this._values[name.prefix] || (this._values[name.prefix] = /* @__PURE__ */ new Set())).add(name); + return name; + } + getScopeValue(prefix, keyOrRef) { + return this._extScope.getValue(prefix, keyOrRef); + } + scopeRefs(scopeName) { + return this._extScope.scopeRefs(scopeName, this._values); + } + scopeCode() { + return this._extScope.scopeCode(this._values); + } + _def(varKind, nameOrPrefix, rhs, constant) { + const name = this._scope.toName(nameOrPrefix); + if (rhs !== void 0 && constant) this._constants[name.str] = rhs; + this._leafNode(new Def(varKind, name, rhs)); + return name; + } + const(nameOrPrefix, rhs, _constant) { + return this._def(scope_1.varKinds.const, nameOrPrefix, rhs, _constant); + } + let(nameOrPrefix, rhs, _constant) { + return this._def(scope_1.varKinds.let, nameOrPrefix, rhs, _constant); + } + var(nameOrPrefix, rhs, _constant) { + return this._def(scope_1.varKinds.var, nameOrPrefix, rhs, _constant); + } + assign(lhs, rhs, sideEffects) { + return this._leafNode(new Assign(lhs, rhs, sideEffects)); + } + add(lhs, rhs) { + return this._leafNode(new AssignOp(lhs, exports.operators.ADD, rhs)); + } + code(c) { + if (typeof c == "function") c(); + else if (c !== code_1.nil) this._leafNode(new AnyCode(c)); + return this; + } + object(...keyValues) { + const code = ["{"]; + for (const [key, value] of keyValues) { + if (code.length > 1) code.push(","); + code.push(key); + if (key !== value || this.opts.es5) { + code.push(":"); + (0, code_1.addCodeArg)(code, value); + } + } + code.push("}"); + return new code_1._Code(code); + } + if(condition, thenBody, elseBody) { + this._blockNode(new If(condition)); + if (thenBody && elseBody) this.code(thenBody).else().code(elseBody).endIf(); + else if (thenBody) this.code(thenBody).endIf(); + else if (elseBody) throw new Error("CodeGen: \"else\" body without \"then\" body"); + return this; + } + elseIf(condition) { + return this._elseNode(new If(condition)); + } + else() { + return this._elseNode(new Else()); + } + endIf() { + return this._endBlockNode(If, Else); + } + _for(node, forBody) { + this._blockNode(node); + if (forBody) this.code(forBody).endFor(); + return this; + } + for(iteration, forBody) { + return this._for(new ForLoop(iteration), forBody); + } + forRange(nameOrPrefix, from, to, forBody, varKind = this.opts.es5 ? scope_1.varKinds.var : scope_1.varKinds.let) { + const name = this._scope.toName(nameOrPrefix); + return this._for(new ForRange(varKind, name, from, to), () => forBody(name)); + } + forOf(nameOrPrefix, iterable, forBody, varKind = scope_1.varKinds.const) { + const name = this._scope.toName(nameOrPrefix); + if (this.opts.es5) { + const arr = iterable instanceof code_1.Name ? iterable : this.var("_arr", iterable); + return this.forRange("_i", 0, (0, code_1._)`${arr}.length`, (i) => { + this.var(name, (0, code_1._)`${arr}[${i}]`); + forBody(name); + }); + } + return this._for(new ForIter("of", varKind, name, iterable), () => forBody(name)); + } + forIn(nameOrPrefix, obj, forBody, varKind = this.opts.es5 ? scope_1.varKinds.var : scope_1.varKinds.const) { + if (this.opts.ownProperties) return this.forOf(nameOrPrefix, (0, code_1._)`Object.keys(${obj})`, forBody); + const name = this._scope.toName(nameOrPrefix); + return this._for(new ForIter("in", varKind, name, obj), () => forBody(name)); + } + endFor() { + return this._endBlockNode(For); + } + label(label) { + return this._leafNode(new Label(label)); + } + break(label) { + return this._leafNode(new Break(label)); + } + return(value) { + const node = new Return(); + this._blockNode(node); + this.code(value); + if (node.nodes.length !== 1) throw new Error("CodeGen: \"return\" should have one node"); + return this._endBlockNode(Return); + } + try(tryBody, catchCode, finallyCode) { + if (!catchCode && !finallyCode) throw new Error("CodeGen: \"try\" without \"catch\" and \"finally\""); + const node = new Try(); + this._blockNode(node); + this.code(tryBody); + if (catchCode) { + const error = this.name("e"); + this._currNode = node.catch = new Catch(error); + catchCode(error); + } + if (finallyCode) { + this._currNode = node.finally = new Finally(); + this.code(finallyCode); + } + return this._endBlockNode(Catch, Finally); + } + throw(error) { + return this._leafNode(new Throw(error)); + } + block(body, nodeCount) { + this._blockStarts.push(this._nodes.length); + if (body) this.code(body).endBlock(nodeCount); + return this; + } + endBlock(nodeCount) { + const len = this._blockStarts.pop(); + if (len === void 0) throw new Error("CodeGen: not in self-balancing block"); + const toClose = this._nodes.length - len; + if (toClose < 0 || nodeCount !== void 0 && toClose !== nodeCount) throw new Error(`CodeGen: wrong number of nodes: ${toClose} vs ${nodeCount} expected`); + this._nodes.length = len; + return this; + } + func(name, args = code_1.nil, async, funcBody) { + this._blockNode(new Func(name, args, async)); + if (funcBody) this.code(funcBody).endFunc(); + return this; + } + endFunc() { + return this._endBlockNode(Func); + } + optimize(n = 1) { + while (n-- > 0) { + this._root.optimizeNodes(); + this._root.optimizeNames(this._root.names, this._constants); + } + } + _leafNode(node) { + this._currNode.nodes.push(node); + return this; + } + _blockNode(node) { + this._currNode.nodes.push(node); + this._nodes.push(node); + } + _endBlockNode(N1, N2) { + const n = this._currNode; + if (n instanceof N1 || N2 && n instanceof N2) { + this._nodes.pop(); + return this; + } + throw new Error(`CodeGen: not in block "${N2 ? `${N1.kind}/${N2.kind}` : N1.kind}"`); + } + _elseNode(node) { + const n = this._currNode; + if (!(n instanceof If)) throw new Error("CodeGen: \"else\" without \"if\""); + this._currNode = n.else = node; + return this; + } + get _root() { + return this._nodes[0]; + } + get _currNode() { + const ns = this._nodes; + return ns[ns.length - 1]; + } + set _currNode(node) { + const ns = this._nodes; + ns[ns.length - 1] = node; + } + }; + exports.CodeGen = CodeGen; + function addNames(names, from) { + for (const n in from) names[n] = (names[n] || 0) + (from[n] || 0); + return names; + } + function addExprNames(names, from) { + return from instanceof code_1._CodeOrName ? addNames(names, from.names) : names; + } + function optimizeExpr(expr, names, constants) { + if (expr instanceof code_1.Name) return replaceName(expr); + if (!canOptimize(expr)) return expr; + return new code_1._Code(expr._items.reduce((items, c) => { + if (c instanceof code_1.Name) c = replaceName(c); + if (c instanceof code_1._Code) items.push(...c._items); + else items.push(c); + return items; + }, [])); + function replaceName(n) { + const c = constants[n.str]; + if (c === void 0 || names[n.str] !== 1) return n; + delete names[n.str]; + return c; + } + function canOptimize(e) { + return e instanceof code_1._Code && e._items.some((c) => c instanceof code_1.Name && names[c.str] === 1 && constants[c.str] !== void 0); + } + } + function subtractNames(names, from) { + for (const n in from) names[n] = (names[n] || 0) - (from[n] || 0); + } + function not(x) { + return typeof x == "boolean" || typeof x == "number" || x === null ? !x : (0, code_1._)`!${par(x)}`; + } + exports.not = not; + const andCode = mappend(exports.operators.AND); + function and(...args) { + return args.reduce(andCode); + } + exports.and = and; + const orCode = mappend(exports.operators.OR); + function or(...args) { + return args.reduce(orCode); + } + exports.or = or; + function mappend(op) { + return (x, y) => x === code_1.nil ? y : y === code_1.nil ? x : (0, code_1._)`${par(x)} ${op} ${par(y)}`; + } + function par(x) { + return x instanceof code_1.Name ? x : (0, code_1._)`(${x})`; + } +})); + +//#endregion +//#region ../../node_modules/.pnpm/ajv@8.18.0/node_modules/ajv/dist/compile/util.js +var require_util = /* @__PURE__ */ __commonJSMin(((exports) => { + Object.defineProperty(exports, "__esModule", { value: true }); + exports.checkStrictMode = exports.getErrorPath = exports.Type = exports.useFunc = exports.setEvaluated = exports.evaluatedPropsToName = exports.mergeEvaluated = exports.eachItem = exports.unescapeJsonPointer = exports.escapeJsonPointer = exports.escapeFragment = exports.unescapeFragment = exports.schemaRefOrVal = exports.schemaHasRulesButRef = exports.schemaHasRules = exports.checkUnknownRules = exports.alwaysValidSchema = exports.toHash = void 0; + const codegen_1 = require_codegen(); + const code_1 = require_code$1(); + function toHash(arr) { + const hash = {}; + for (const item of arr) hash[item] = true; + return hash; + } + exports.toHash = toHash; + function alwaysValidSchema(it, schema) { + if (typeof schema == "boolean") return schema; + if (Object.keys(schema).length === 0) return true; + checkUnknownRules(it, schema); + return !schemaHasRules(schema, it.self.RULES.all); + } + exports.alwaysValidSchema = alwaysValidSchema; + function checkUnknownRules(it, schema = it.schema) { + const { opts, self } = it; + if (!opts.strictSchema) return; + if (typeof schema === "boolean") return; + const rules = self.RULES.keywords; + for (const key in schema) if (!rules[key]) checkStrictMode(it, `unknown keyword: "${key}"`); + } + exports.checkUnknownRules = checkUnknownRules; + function schemaHasRules(schema, rules) { + if (typeof schema == "boolean") return !schema; + for (const key in schema) if (rules[key]) return true; + return false; + } + exports.schemaHasRules = schemaHasRules; + function schemaHasRulesButRef(schema, RULES) { + if (typeof schema == "boolean") return !schema; + for (const key in schema) if (key !== "$ref" && RULES.all[key]) return true; + return false; + } + exports.schemaHasRulesButRef = schemaHasRulesButRef; + function schemaRefOrVal({ topSchemaRef, schemaPath }, schema, keyword, $data) { + if (!$data) { + if (typeof schema == "number" || typeof schema == "boolean") return schema; + if (typeof schema == "string") return (0, codegen_1._)`${schema}`; + } + return (0, codegen_1._)`${topSchemaRef}${schemaPath}${(0, codegen_1.getProperty)(keyword)}`; + } + exports.schemaRefOrVal = schemaRefOrVal; + function unescapeFragment(str) { + return unescapeJsonPointer(decodeURIComponent(str)); + } + exports.unescapeFragment = unescapeFragment; + function escapeFragment(str) { + return encodeURIComponent(escapeJsonPointer(str)); + } + exports.escapeFragment = escapeFragment; + function escapeJsonPointer(str) { + if (typeof str == "number") return `${str}`; + return str.replace(/~/g, "~0").replace(/\//g, "~1"); + } + exports.escapeJsonPointer = escapeJsonPointer; + function unescapeJsonPointer(str) { + return str.replace(/~1/g, "/").replace(/~0/g, "~"); + } + exports.unescapeJsonPointer = unescapeJsonPointer; + function eachItem(xs, f) { + if (Array.isArray(xs)) for (const x of xs) f(x); + else f(xs); + } + exports.eachItem = eachItem; + function makeMergeEvaluated({ mergeNames, mergeToName, mergeValues, resultToName }) { + return (gen, from, to, toName) => { + const res = to === void 0 ? from : to instanceof codegen_1.Name ? (from instanceof codegen_1.Name ? mergeNames(gen, from, to) : mergeToName(gen, from, to), to) : from instanceof codegen_1.Name ? (mergeToName(gen, to, from), from) : mergeValues(from, to); + return toName === codegen_1.Name && !(res instanceof codegen_1.Name) ? resultToName(gen, res) : res; + }; + } + exports.mergeEvaluated = { + props: makeMergeEvaluated({ + mergeNames: (gen, from, to) => gen.if((0, codegen_1._)`${to} !== true && ${from} !== undefined`, () => { + gen.if((0, codegen_1._)`${from} === true`, () => gen.assign(to, true), () => gen.assign(to, (0, codegen_1._)`${to} || {}`).code((0, codegen_1._)`Object.assign(${to}, ${from})`)); + }), + mergeToName: (gen, from, to) => gen.if((0, codegen_1._)`${to} !== true`, () => { + if (from === true) gen.assign(to, true); + else { + gen.assign(to, (0, codegen_1._)`${to} || {}`); + setEvaluated(gen, to, from); + } + }), + mergeValues: (from, to) => from === true ? true : { + ...from, + ...to + }, + resultToName: evaluatedPropsToName + }), + items: makeMergeEvaluated({ + mergeNames: (gen, from, to) => gen.if((0, codegen_1._)`${to} !== true && ${from} !== undefined`, () => gen.assign(to, (0, codegen_1._)`${from} === true ? true : ${to} > ${from} ? ${to} : ${from}`)), + mergeToName: (gen, from, to) => gen.if((0, codegen_1._)`${to} !== true`, () => gen.assign(to, from === true ? true : (0, codegen_1._)`${to} > ${from} ? ${to} : ${from}`)), + mergeValues: (from, to) => from === true ? true : Math.max(from, to), + resultToName: (gen, items) => gen.var("items", items) + }) + }; + function evaluatedPropsToName(gen, ps) { + if (ps === true) return gen.var("props", true); + const props = gen.var("props", (0, codegen_1._)`{}`); + if (ps !== void 0) setEvaluated(gen, props, ps); + return props; + } + exports.evaluatedPropsToName = evaluatedPropsToName; + function setEvaluated(gen, props, ps) { + Object.keys(ps).forEach((p) => gen.assign((0, codegen_1._)`${props}${(0, codegen_1.getProperty)(p)}`, true)); + } + exports.setEvaluated = setEvaluated; + const snippets = {}; + function useFunc(gen, f) { + return gen.scopeValue("func", { + ref: f, + code: snippets[f.code] || (snippets[f.code] = new code_1._Code(f.code)) + }); + } + exports.useFunc = useFunc; + var Type; + (function(Type) { + Type[Type["Num"] = 0] = "Num"; + Type[Type["Str"] = 1] = "Str"; + })(Type || (exports.Type = Type = {})); + function getErrorPath(dataProp, dataPropType, jsPropertySyntax) { + if (dataProp instanceof codegen_1.Name) { + const isNumber = dataPropType === Type.Num; + return jsPropertySyntax ? isNumber ? (0, codegen_1._)`"[" + ${dataProp} + "]"` : (0, codegen_1._)`"['" + ${dataProp} + "']"` : isNumber ? (0, codegen_1._)`"/" + ${dataProp}` : (0, codegen_1._)`"/" + ${dataProp}.replace(/~/g, "~0").replace(/\\//g, "~1")`; + } + return jsPropertySyntax ? (0, codegen_1.getProperty)(dataProp).toString() : "/" + escapeJsonPointer(dataProp); + } + exports.getErrorPath = getErrorPath; + function checkStrictMode(it, msg, mode = it.opts.strictSchema) { + if (!mode) return; + msg = `strict mode: ${msg}`; + if (mode === true) throw new Error(msg); + it.self.logger.warn(msg); + } + exports.checkStrictMode = checkStrictMode; +})); + +//#endregion +//#region ../../node_modules/.pnpm/ajv@8.18.0/node_modules/ajv/dist/compile/names.js +var require_names = /* @__PURE__ */ __commonJSMin(((exports) => { + Object.defineProperty(exports, "__esModule", { value: true }); + const codegen_1 = require_codegen(); + const names = { + data: new codegen_1.Name("data"), + valCxt: new codegen_1.Name("valCxt"), + instancePath: new codegen_1.Name("instancePath"), + parentData: new codegen_1.Name("parentData"), + parentDataProperty: new codegen_1.Name("parentDataProperty"), + rootData: new codegen_1.Name("rootData"), + dynamicAnchors: new codegen_1.Name("dynamicAnchors"), + vErrors: new codegen_1.Name("vErrors"), + errors: new codegen_1.Name("errors"), + this: new codegen_1.Name("this"), + self: new codegen_1.Name("self"), + scope: new codegen_1.Name("scope"), + json: new codegen_1.Name("json"), + jsonPos: new codegen_1.Name("jsonPos"), + jsonLen: new codegen_1.Name("jsonLen"), + jsonPart: new codegen_1.Name("jsonPart") + }; + exports.default = names; +})); + +//#endregion +//#region ../../node_modules/.pnpm/ajv@8.18.0/node_modules/ajv/dist/compile/errors.js +var require_errors = /* @__PURE__ */ __commonJSMin(((exports) => { + Object.defineProperty(exports, "__esModule", { value: true }); + exports.extendErrors = exports.resetErrorsCount = exports.reportExtraError = exports.reportError = exports.keyword$DataError = exports.keywordError = void 0; + const codegen_1 = require_codegen(); + const util_1 = require_util(); + const names_1 = require_names(); + exports.keywordError = { message: ({ keyword }) => (0, codegen_1.str)`must pass "${keyword}" keyword validation` }; + exports.keyword$DataError = { message: ({ keyword, schemaType }) => schemaType ? (0, codegen_1.str)`"${keyword}" keyword must be ${schemaType} ($data)` : (0, codegen_1.str)`"${keyword}" keyword is invalid ($data)` }; + function reportError(cxt, error = exports.keywordError, errorPaths, overrideAllErrors) { + const { it } = cxt; + const { gen, compositeRule, allErrors } = it; + const errObj = errorObjectCode(cxt, error, errorPaths); + if (overrideAllErrors !== null && overrideAllErrors !== void 0 ? overrideAllErrors : compositeRule || allErrors) addError(gen, errObj); + else returnErrors(it, (0, codegen_1._)`[${errObj}]`); + } + exports.reportError = reportError; + function reportExtraError(cxt, error = exports.keywordError, errorPaths) { + const { it } = cxt; + const { gen, compositeRule, allErrors } = it; + addError(gen, errorObjectCode(cxt, error, errorPaths)); + if (!(compositeRule || allErrors)) returnErrors(it, names_1.default.vErrors); + } + exports.reportExtraError = reportExtraError; + function resetErrorsCount(gen, errsCount) { + gen.assign(names_1.default.errors, errsCount); + gen.if((0, codegen_1._)`${names_1.default.vErrors} !== null`, () => gen.if(errsCount, () => gen.assign((0, codegen_1._)`${names_1.default.vErrors}.length`, errsCount), () => gen.assign(names_1.default.vErrors, null))); + } + exports.resetErrorsCount = resetErrorsCount; + function extendErrors({ gen, keyword, schemaValue, data, errsCount, it }) { + /* istanbul ignore if */ + if (errsCount === void 0) throw new Error("ajv implementation error"); + const err = gen.name("err"); + gen.forRange("i", errsCount, names_1.default.errors, (i) => { + gen.const(err, (0, codegen_1._)`${names_1.default.vErrors}[${i}]`); + gen.if((0, codegen_1._)`${err}.instancePath === undefined`, () => gen.assign((0, codegen_1._)`${err}.instancePath`, (0, codegen_1.strConcat)(names_1.default.instancePath, it.errorPath))); + gen.assign((0, codegen_1._)`${err}.schemaPath`, (0, codegen_1.str)`${it.errSchemaPath}/${keyword}`); + if (it.opts.verbose) { + gen.assign((0, codegen_1._)`${err}.schema`, schemaValue); + gen.assign((0, codegen_1._)`${err}.data`, data); + } + }); + } + exports.extendErrors = extendErrors; + function addError(gen, errObj) { + const err = gen.const("err", errObj); + gen.if((0, codegen_1._)`${names_1.default.vErrors} === null`, () => gen.assign(names_1.default.vErrors, (0, codegen_1._)`[${err}]`), (0, codegen_1._)`${names_1.default.vErrors}.push(${err})`); + gen.code((0, codegen_1._)`${names_1.default.errors}++`); + } + function returnErrors(it, errs) { + const { gen, validateName, schemaEnv } = it; + if (schemaEnv.$async) gen.throw((0, codegen_1._)`new ${it.ValidationError}(${errs})`); + else { + gen.assign((0, codegen_1._)`${validateName}.errors`, errs); + gen.return(false); + } + } + const E = { + keyword: new codegen_1.Name("keyword"), + schemaPath: new codegen_1.Name("schemaPath"), + params: new codegen_1.Name("params"), + propertyName: new codegen_1.Name("propertyName"), + message: new codegen_1.Name("message"), + schema: new codegen_1.Name("schema"), + parentSchema: new codegen_1.Name("parentSchema") + }; + function errorObjectCode(cxt, error, errorPaths) { + const { createErrors } = cxt.it; + if (createErrors === false) return (0, codegen_1._)`{}`; + return errorObject(cxt, error, errorPaths); + } + function errorObject(cxt, error, errorPaths = {}) { + const { gen, it } = cxt; + const keyValues = [errorInstancePath(it, errorPaths), errorSchemaPath(cxt, errorPaths)]; + extraErrorProps(cxt, error, keyValues); + return gen.object(...keyValues); + } + function errorInstancePath({ errorPath }, { instancePath }) { + const instPath = instancePath ? (0, codegen_1.str)`${errorPath}${(0, util_1.getErrorPath)(instancePath, util_1.Type.Str)}` : errorPath; + return [names_1.default.instancePath, (0, codegen_1.strConcat)(names_1.default.instancePath, instPath)]; + } + function errorSchemaPath({ keyword, it: { errSchemaPath } }, { schemaPath, parentSchema }) { + let schPath = parentSchema ? errSchemaPath : (0, codegen_1.str)`${errSchemaPath}/${keyword}`; + if (schemaPath) schPath = (0, codegen_1.str)`${schPath}${(0, util_1.getErrorPath)(schemaPath, util_1.Type.Str)}`; + return [E.schemaPath, schPath]; + } + function extraErrorProps(cxt, { params, message }, keyValues) { + const { keyword, data, schemaValue, it } = cxt; + const { opts, propertyName, topSchemaRef, schemaPath } = it; + keyValues.push([E.keyword, keyword], [E.params, typeof params == "function" ? params(cxt) : params || (0, codegen_1._)`{}`]); + if (opts.messages) keyValues.push([E.message, typeof message == "function" ? message(cxt) : message]); + if (opts.verbose) keyValues.push([E.schema, schemaValue], [E.parentSchema, (0, codegen_1._)`${topSchemaRef}${schemaPath}`], [names_1.default.data, data]); + if (propertyName) keyValues.push([E.propertyName, propertyName]); + } +})); + +//#endregion +//#region ../../node_modules/.pnpm/ajv@8.18.0/node_modules/ajv/dist/compile/validate/boolSchema.js +var require_boolSchema = /* @__PURE__ */ __commonJSMin(((exports) => { + Object.defineProperty(exports, "__esModule", { value: true }); + exports.boolOrEmptySchema = exports.topBoolOrEmptySchema = void 0; + const errors_1 = require_errors(); + const codegen_1 = require_codegen(); + const names_1 = require_names(); + const boolError = { message: "boolean schema is false" }; + function topBoolOrEmptySchema(it) { + const { gen, schema, validateName } = it; + if (schema === false) falseSchemaError(it, false); + else if (typeof schema == "object" && schema.$async === true) gen.return(names_1.default.data); + else { + gen.assign((0, codegen_1._)`${validateName}.errors`, null); + gen.return(true); + } + } + exports.topBoolOrEmptySchema = topBoolOrEmptySchema; + function boolOrEmptySchema(it, valid) { + const { gen, schema } = it; + if (schema === false) { + gen.var(valid, false); + falseSchemaError(it); + } else gen.var(valid, true); + } + exports.boolOrEmptySchema = boolOrEmptySchema; + function falseSchemaError(it, overrideAllErrors) { + const { gen, data } = it; + const cxt = { + gen, + keyword: "false schema", + data, + schema: false, + schemaCode: false, + schemaValue: false, + params: {}, + it + }; + (0, errors_1.reportError)(cxt, boolError, void 0, overrideAllErrors); + } +})); + +//#endregion +//#region ../../node_modules/.pnpm/ajv@8.18.0/node_modules/ajv/dist/compile/rules.js +var require_rules = /* @__PURE__ */ __commonJSMin(((exports) => { + Object.defineProperty(exports, "__esModule", { value: true }); + exports.getRules = exports.isJSONType = void 0; + const jsonTypes = new Set([ + "string", + "number", + "integer", + "boolean", + "null", + "object", + "array" + ]); + function isJSONType(x) { + return typeof x == "string" && jsonTypes.has(x); + } + exports.isJSONType = isJSONType; + function getRules() { + const groups = { + number: { + type: "number", + rules: [] + }, + string: { + type: "string", + rules: [] + }, + array: { + type: "array", + rules: [] + }, + object: { + type: "object", + rules: [] + } + }; + return { + types: { + ...groups, + integer: true, + boolean: true, + null: true + }, + rules: [ + { rules: [] }, + groups.number, + groups.string, + groups.array, + groups.object + ], + post: { rules: [] }, + all: {}, + keywords: {} + }; + } + exports.getRules = getRules; +})); + +//#endregion +//#region ../../node_modules/.pnpm/ajv@8.18.0/node_modules/ajv/dist/compile/validate/applicability.js +var require_applicability = /* @__PURE__ */ __commonJSMin(((exports) => { + Object.defineProperty(exports, "__esModule", { value: true }); + exports.shouldUseRule = exports.shouldUseGroup = exports.schemaHasRulesForType = void 0; + function schemaHasRulesForType({ schema, self }, type) { + const group = self.RULES.types[type]; + return group && group !== true && shouldUseGroup(schema, group); + } + exports.schemaHasRulesForType = schemaHasRulesForType; + function shouldUseGroup(schema, group) { + return group.rules.some((rule) => shouldUseRule(schema, rule)); + } + exports.shouldUseGroup = shouldUseGroup; + function shouldUseRule(schema, rule) { + var _a; + return schema[rule.keyword] !== void 0 || ((_a = rule.definition.implements) === null || _a === void 0 ? void 0 : _a.some((kwd) => schema[kwd] !== void 0)); + } + exports.shouldUseRule = shouldUseRule; +})); + +//#endregion +//#region ../../node_modules/.pnpm/ajv@8.18.0/node_modules/ajv/dist/compile/validate/dataType.js +var require_dataType = /* @__PURE__ */ __commonJSMin(((exports) => { + Object.defineProperty(exports, "__esModule", { value: true }); + exports.reportTypeError = exports.checkDataTypes = exports.checkDataType = exports.coerceAndCheckDataType = exports.getJSONTypes = exports.getSchemaTypes = exports.DataType = void 0; + const rules_1 = require_rules(); + const applicability_1 = require_applicability(); + const errors_1 = require_errors(); + const codegen_1 = require_codegen(); + const util_1 = require_util(); + var DataType; + (function(DataType) { + DataType[DataType["Correct"] = 0] = "Correct"; + DataType[DataType["Wrong"] = 1] = "Wrong"; + })(DataType || (exports.DataType = DataType = {})); + function getSchemaTypes(schema) { + const types = getJSONTypes(schema.type); + if (types.includes("null")) { + if (schema.nullable === false) throw new Error("type: null contradicts nullable: false"); + } else { + if (!types.length && schema.nullable !== void 0) throw new Error("\"nullable\" cannot be used without \"type\""); + if (schema.nullable === true) types.push("null"); + } + return types; + } + exports.getSchemaTypes = getSchemaTypes; + function getJSONTypes(ts) { + const types = Array.isArray(ts) ? ts : ts ? [ts] : []; + if (types.every(rules_1.isJSONType)) return types; + throw new Error("type must be JSONType or JSONType[]: " + types.join(",")); + } + exports.getJSONTypes = getJSONTypes; + function coerceAndCheckDataType(it, types) { + const { gen, data, opts } = it; + const coerceTo = coerceToTypes(types, opts.coerceTypes); + const checkTypes = types.length > 0 && !(coerceTo.length === 0 && types.length === 1 && (0, applicability_1.schemaHasRulesForType)(it, types[0])); + if (checkTypes) { + const wrongType = checkDataTypes(types, data, opts.strictNumbers, DataType.Wrong); + gen.if(wrongType, () => { + if (coerceTo.length) coerceData(it, types, coerceTo); + else reportTypeError(it); + }); + } + return checkTypes; + } + exports.coerceAndCheckDataType = coerceAndCheckDataType; + const COERCIBLE = new Set([ + "string", + "number", + "integer", + "boolean", + "null" + ]); + function coerceToTypes(types, coerceTypes) { + return coerceTypes ? types.filter((t) => COERCIBLE.has(t) || coerceTypes === "array" && t === "array") : []; + } + function coerceData(it, types, coerceTo) { + const { gen, data, opts } = it; + const dataType = gen.let("dataType", (0, codegen_1._)`typeof ${data}`); + const coerced = gen.let("coerced", (0, codegen_1._)`undefined`); + if (opts.coerceTypes === "array") gen.if((0, codegen_1._)`${dataType} == 'object' && Array.isArray(${data}) && ${data}.length == 1`, () => gen.assign(data, (0, codegen_1._)`${data}[0]`).assign(dataType, (0, codegen_1._)`typeof ${data}`).if(checkDataTypes(types, data, opts.strictNumbers), () => gen.assign(coerced, data))); + gen.if((0, codegen_1._)`${coerced} !== undefined`); + for (const t of coerceTo) if (COERCIBLE.has(t) || t === "array" && opts.coerceTypes === "array") coerceSpecificType(t); + gen.else(); + reportTypeError(it); + gen.endIf(); + gen.if((0, codegen_1._)`${coerced} !== undefined`, () => { + gen.assign(data, coerced); + assignParentData(it, coerced); + }); + function coerceSpecificType(t) { + switch (t) { + case "string": + gen.elseIf((0, codegen_1._)`${dataType} == "number" || ${dataType} == "boolean"`).assign(coerced, (0, codegen_1._)`"" + ${data}`).elseIf((0, codegen_1._)`${data} === null`).assign(coerced, (0, codegen_1._)`""`); + return; + case "number": + gen.elseIf((0, codegen_1._)`${dataType} == "boolean" || ${data} === null + || (${dataType} == "string" && ${data} && ${data} == +${data})`).assign(coerced, (0, codegen_1._)`+${data}`); + return; + case "integer": + gen.elseIf((0, codegen_1._)`${dataType} === "boolean" || ${data} === null + || (${dataType} === "string" && ${data} && ${data} == +${data} && !(${data} % 1))`).assign(coerced, (0, codegen_1._)`+${data}`); + return; + case "boolean": + gen.elseIf((0, codegen_1._)`${data} === "false" || ${data} === 0 || ${data} === null`).assign(coerced, false).elseIf((0, codegen_1._)`${data} === "true" || ${data} === 1`).assign(coerced, true); + return; + case "null": + gen.elseIf((0, codegen_1._)`${data} === "" || ${data} === 0 || ${data} === false`); + gen.assign(coerced, null); + return; + case "array": gen.elseIf((0, codegen_1._)`${dataType} === "string" || ${dataType} === "number" + || ${dataType} === "boolean" || ${data} === null`).assign(coerced, (0, codegen_1._)`[${data}]`); + } + } + } + function assignParentData({ gen, parentData, parentDataProperty }, expr) { + gen.if((0, codegen_1._)`${parentData} !== undefined`, () => gen.assign((0, codegen_1._)`${parentData}[${parentDataProperty}]`, expr)); + } + function checkDataType(dataType, data, strictNums, correct = DataType.Correct) { + const EQ = correct === DataType.Correct ? codegen_1.operators.EQ : codegen_1.operators.NEQ; + let cond; + switch (dataType) { + case "null": return (0, codegen_1._)`${data} ${EQ} null`; + case "array": + cond = (0, codegen_1._)`Array.isArray(${data})`; + break; + case "object": + cond = (0, codegen_1._)`${data} && typeof ${data} == "object" && !Array.isArray(${data})`; + break; + case "integer": + cond = numCond((0, codegen_1._)`!(${data} % 1) && !isNaN(${data})`); + break; + case "number": + cond = numCond(); + break; + default: return (0, codegen_1._)`typeof ${data} ${EQ} ${dataType}`; + } + return correct === DataType.Correct ? cond : (0, codegen_1.not)(cond); + function numCond(_cond = codegen_1.nil) { + return (0, codegen_1.and)((0, codegen_1._)`typeof ${data} == "number"`, _cond, strictNums ? (0, codegen_1._)`isFinite(${data})` : codegen_1.nil); + } + } + exports.checkDataType = checkDataType; + function checkDataTypes(dataTypes, data, strictNums, correct) { + if (dataTypes.length === 1) return checkDataType(dataTypes[0], data, strictNums, correct); + let cond; + const types = (0, util_1.toHash)(dataTypes); + if (types.array && types.object) { + const notObj = (0, codegen_1._)`typeof ${data} != "object"`; + cond = types.null ? notObj : (0, codegen_1._)`!${data} || ${notObj}`; + delete types.null; + delete types.array; + delete types.object; + } else cond = codegen_1.nil; + if (types.number) delete types.integer; + for (const t in types) cond = (0, codegen_1.and)(cond, checkDataType(t, data, strictNums, correct)); + return cond; + } + exports.checkDataTypes = checkDataTypes; + const typeError = { + message: ({ schema }) => `must be ${schema}`, + params: ({ schema, schemaValue }) => typeof schema == "string" ? (0, codegen_1._)`{type: ${schema}}` : (0, codegen_1._)`{type: ${schemaValue}}` + }; + function reportTypeError(it) { + const cxt = getTypeErrorContext(it); + (0, errors_1.reportError)(cxt, typeError); + } + exports.reportTypeError = reportTypeError; + function getTypeErrorContext(it) { + const { gen, data, schema } = it; + const schemaCode = (0, util_1.schemaRefOrVal)(it, schema, "type"); + return { + gen, + keyword: "type", + data, + schema: schema.type, + schemaCode, + schemaValue: schemaCode, + parentSchema: schema, + params: {}, + it + }; + } +})); + +//#endregion +//#region ../../node_modules/.pnpm/ajv@8.18.0/node_modules/ajv/dist/compile/validate/defaults.js +var require_defaults = /* @__PURE__ */ __commonJSMin(((exports) => { + Object.defineProperty(exports, "__esModule", { value: true }); + exports.assignDefaults = void 0; + const codegen_1 = require_codegen(); + const util_1 = require_util(); + function assignDefaults(it, ty) { + const { properties, items } = it.schema; + if (ty === "object" && properties) for (const key in properties) assignDefault(it, key, properties[key].default); + else if (ty === "array" && Array.isArray(items)) items.forEach((sch, i) => assignDefault(it, i, sch.default)); + } + exports.assignDefaults = assignDefaults; + function assignDefault(it, prop, defaultValue) { + const { gen, compositeRule, data, opts } = it; + if (defaultValue === void 0) return; + const childData = (0, codegen_1._)`${data}${(0, codegen_1.getProperty)(prop)}`; + if (compositeRule) { + (0, util_1.checkStrictMode)(it, `default is ignored for: ${childData}`); + return; + } + let condition = (0, codegen_1._)`${childData} === undefined`; + if (opts.useDefaults === "empty") condition = (0, codegen_1._)`${condition} || ${childData} === null || ${childData} === ""`; + gen.if(condition, (0, codegen_1._)`${childData} = ${(0, codegen_1.stringify)(defaultValue)}`); + } +})); + +//#endregion +//#region ../../node_modules/.pnpm/ajv@8.18.0/node_modules/ajv/dist/vocabularies/code.js +var require_code = /* @__PURE__ */ __commonJSMin(((exports) => { + Object.defineProperty(exports, "__esModule", { value: true }); + exports.validateUnion = exports.validateArray = exports.usePattern = exports.callValidateCode = exports.schemaProperties = exports.allSchemaProperties = exports.noPropertyInData = exports.propertyInData = exports.isOwnProperty = exports.hasPropFunc = exports.reportMissingProp = exports.checkMissingProp = exports.checkReportMissingProp = void 0; + const codegen_1 = require_codegen(); + const util_1 = require_util(); + const names_1 = require_names(); + const util_2 = require_util(); + function checkReportMissingProp(cxt, prop) { + const { gen, data, it } = cxt; + gen.if(noPropertyInData(gen, data, prop, it.opts.ownProperties), () => { + cxt.setParams({ missingProperty: (0, codegen_1._)`${prop}` }, true); + cxt.error(); + }); + } + exports.checkReportMissingProp = checkReportMissingProp; + function checkMissingProp({ gen, data, it: { opts } }, properties, missing) { + return (0, codegen_1.or)(...properties.map((prop) => (0, codegen_1.and)(noPropertyInData(gen, data, prop, opts.ownProperties), (0, codegen_1._)`${missing} = ${prop}`))); + } + exports.checkMissingProp = checkMissingProp; + function reportMissingProp(cxt, missing) { + cxt.setParams({ missingProperty: missing }, true); + cxt.error(); + } + exports.reportMissingProp = reportMissingProp; + function hasPropFunc(gen) { + return gen.scopeValue("func", { + ref: Object.prototype.hasOwnProperty, + code: (0, codegen_1._)`Object.prototype.hasOwnProperty` + }); + } + exports.hasPropFunc = hasPropFunc; + function isOwnProperty(gen, data, property) { + return (0, codegen_1._)`${hasPropFunc(gen)}.call(${data}, ${property})`; + } + exports.isOwnProperty = isOwnProperty; + function propertyInData(gen, data, property, ownProperties) { + const cond = (0, codegen_1._)`${data}${(0, codegen_1.getProperty)(property)} !== undefined`; + return ownProperties ? (0, codegen_1._)`${cond} && ${isOwnProperty(gen, data, property)}` : cond; + } + exports.propertyInData = propertyInData; + function noPropertyInData(gen, data, property, ownProperties) { + const cond = (0, codegen_1._)`${data}${(0, codegen_1.getProperty)(property)} === undefined`; + return ownProperties ? (0, codegen_1.or)(cond, (0, codegen_1.not)(isOwnProperty(gen, data, property))) : cond; + } + exports.noPropertyInData = noPropertyInData; + function allSchemaProperties(schemaMap) { + return schemaMap ? Object.keys(schemaMap).filter((p) => p !== "__proto__") : []; + } + exports.allSchemaProperties = allSchemaProperties; + function schemaProperties(it, schemaMap) { + return allSchemaProperties(schemaMap).filter((p) => !(0, util_1.alwaysValidSchema)(it, schemaMap[p])); + } + exports.schemaProperties = schemaProperties; + function callValidateCode({ schemaCode, data, it: { gen, topSchemaRef, schemaPath, errorPath }, it }, func, context, passSchema) { + const dataAndSchema = passSchema ? (0, codegen_1._)`${schemaCode}, ${data}, ${topSchemaRef}${schemaPath}` : data; + const valCxt = [ + [names_1.default.instancePath, (0, codegen_1.strConcat)(names_1.default.instancePath, errorPath)], + [names_1.default.parentData, it.parentData], + [names_1.default.parentDataProperty, it.parentDataProperty], + [names_1.default.rootData, names_1.default.rootData] + ]; + if (it.opts.dynamicRef) valCxt.push([names_1.default.dynamicAnchors, names_1.default.dynamicAnchors]); + const args = (0, codegen_1._)`${dataAndSchema}, ${gen.object(...valCxt)}`; + return context !== codegen_1.nil ? (0, codegen_1._)`${func}.call(${context}, ${args})` : (0, codegen_1._)`${func}(${args})`; + } + exports.callValidateCode = callValidateCode; + const newRegExp = (0, codegen_1._)`new RegExp`; + function usePattern({ gen, it: { opts } }, pattern) { + const u = opts.unicodeRegExp ? "u" : ""; + const { regExp } = opts.code; + const rx = regExp(pattern, u); + return gen.scopeValue("pattern", { + key: rx.toString(), + ref: rx, + code: (0, codegen_1._)`${regExp.code === "new RegExp" ? newRegExp : (0, util_2.useFunc)(gen, regExp)}(${pattern}, ${u})` + }); + } + exports.usePattern = usePattern; + function validateArray(cxt) { + const { gen, data, keyword, it } = cxt; + const valid = gen.name("valid"); + if (it.allErrors) { + const validArr = gen.let("valid", true); + validateItems(() => gen.assign(validArr, false)); + return validArr; + } + gen.var(valid, true); + validateItems(() => gen.break()); + return valid; + function validateItems(notValid) { + const len = gen.const("len", (0, codegen_1._)`${data}.length`); + gen.forRange("i", 0, len, (i) => { + cxt.subschema({ + keyword, + dataProp: i, + dataPropType: util_1.Type.Num + }, valid); + gen.if((0, codegen_1.not)(valid), notValid); + }); + } + } + exports.validateArray = validateArray; + function validateUnion(cxt) { + const { gen, schema, keyword, it } = cxt; + /* istanbul ignore if */ + if (!Array.isArray(schema)) throw new Error("ajv implementation error"); + if (schema.some((sch) => (0, util_1.alwaysValidSchema)(it, sch)) && !it.opts.unevaluated) return; + const valid = gen.let("valid", false); + const schValid = gen.name("_valid"); + gen.block(() => schema.forEach((_sch, i) => { + const schCxt = cxt.subschema({ + keyword, + schemaProp: i, + compositeRule: true + }, schValid); + gen.assign(valid, (0, codegen_1._)`${valid} || ${schValid}`); + if (!cxt.mergeValidEvaluated(schCxt, schValid)) gen.if((0, codegen_1.not)(valid)); + })); + cxt.result(valid, () => cxt.reset(), () => cxt.error(true)); + } + exports.validateUnion = validateUnion; +})); + +//#endregion +//#region ../../node_modules/.pnpm/ajv@8.18.0/node_modules/ajv/dist/compile/validate/keyword.js +var require_keyword = /* @__PURE__ */ __commonJSMin(((exports) => { + Object.defineProperty(exports, "__esModule", { value: true }); + exports.validateKeywordUsage = exports.validSchemaType = exports.funcKeywordCode = exports.macroKeywordCode = void 0; + const codegen_1 = require_codegen(); + const names_1 = require_names(); + const code_1 = require_code(); + const errors_1 = require_errors(); + function macroKeywordCode(cxt, def) { + const { gen, keyword, schema, parentSchema, it } = cxt; + const macroSchema = def.macro.call(it.self, schema, parentSchema, it); + const schemaRef = useKeyword(gen, keyword, macroSchema); + if (it.opts.validateSchema !== false) it.self.validateSchema(macroSchema, true); + const valid = gen.name("valid"); + cxt.subschema({ + schema: macroSchema, + schemaPath: codegen_1.nil, + errSchemaPath: `${it.errSchemaPath}/${keyword}`, + topSchemaRef: schemaRef, + compositeRule: true + }, valid); + cxt.pass(valid, () => cxt.error(true)); + } + exports.macroKeywordCode = macroKeywordCode; + function funcKeywordCode(cxt, def) { + var _a; + const { gen, keyword, schema, parentSchema, $data, it } = cxt; + checkAsyncKeyword(it, def); + const validateRef = useKeyword(gen, keyword, !$data && def.compile ? def.compile.call(it.self, schema, parentSchema, it) : def.validate); + const valid = gen.let("valid"); + cxt.block$data(valid, validateKeyword); + cxt.ok((_a = def.valid) !== null && _a !== void 0 ? _a : valid); + function validateKeyword() { + if (def.errors === false) { + assignValid(); + if (def.modifying) modifyData(cxt); + reportErrs(() => cxt.error()); + } else { + const ruleErrs = def.async ? validateAsync() : validateSync(); + if (def.modifying) modifyData(cxt); + reportErrs(() => addErrs(cxt, ruleErrs)); + } + } + function validateAsync() { + const ruleErrs = gen.let("ruleErrs", null); + gen.try(() => assignValid((0, codegen_1._)`await `), (e) => gen.assign(valid, false).if((0, codegen_1._)`${e} instanceof ${it.ValidationError}`, () => gen.assign(ruleErrs, (0, codegen_1._)`${e}.errors`), () => gen.throw(e))); + return ruleErrs; + } + function validateSync() { + const validateErrs = (0, codegen_1._)`${validateRef}.errors`; + gen.assign(validateErrs, null); + assignValid(codegen_1.nil); + return validateErrs; + } + function assignValid(_await = def.async ? (0, codegen_1._)`await ` : codegen_1.nil) { + const passCxt = it.opts.passContext ? names_1.default.this : names_1.default.self; + const passSchema = !("compile" in def && !$data || def.schema === false); + gen.assign(valid, (0, codegen_1._)`${_await}${(0, code_1.callValidateCode)(cxt, validateRef, passCxt, passSchema)}`, def.modifying); + } + function reportErrs(errors) { + var _a$1; + gen.if((0, codegen_1.not)((_a$1 = def.valid) !== null && _a$1 !== void 0 ? _a$1 : valid), errors); + } + } + exports.funcKeywordCode = funcKeywordCode; + function modifyData(cxt) { + const { gen, data, it } = cxt; + gen.if(it.parentData, () => gen.assign(data, (0, codegen_1._)`${it.parentData}[${it.parentDataProperty}]`)); + } + function addErrs(cxt, errs) { + const { gen } = cxt; + gen.if((0, codegen_1._)`Array.isArray(${errs})`, () => { + gen.assign(names_1.default.vErrors, (0, codegen_1._)`${names_1.default.vErrors} === null ? ${errs} : ${names_1.default.vErrors}.concat(${errs})`).assign(names_1.default.errors, (0, codegen_1._)`${names_1.default.vErrors}.length`); + (0, errors_1.extendErrors)(cxt); + }, () => cxt.error()); + } + function checkAsyncKeyword({ schemaEnv }, def) { + if (def.async && !schemaEnv.$async) throw new Error("async keyword in sync schema"); + } + function useKeyword(gen, keyword, result) { + if (result === void 0) throw new Error(`keyword "${keyword}" failed to compile`); + return gen.scopeValue("keyword", typeof result == "function" ? { ref: result } : { + ref: result, + code: (0, codegen_1.stringify)(result) + }); + } + function validSchemaType(schema, schemaType, allowUndefined = false) { + return !schemaType.length || schemaType.some((st) => st === "array" ? Array.isArray(schema) : st === "object" ? schema && typeof schema == "object" && !Array.isArray(schema) : typeof schema == st || allowUndefined && typeof schema == "undefined"); + } + exports.validSchemaType = validSchemaType; + function validateKeywordUsage({ schema, opts, self, errSchemaPath }, def, keyword) { + /* istanbul ignore if */ + if (Array.isArray(def.keyword) ? !def.keyword.includes(keyword) : def.keyword !== keyword) throw new Error("ajv implementation error"); + const deps = def.dependencies; + if (deps === null || deps === void 0 ? void 0 : deps.some((kwd) => !Object.prototype.hasOwnProperty.call(schema, kwd))) throw new Error(`parent schema must have dependencies of ${keyword}: ${deps.join(",")}`); + if (def.validateSchema) { + if (!def.validateSchema(schema[keyword])) { + const msg = `keyword "${keyword}" value is invalid at path "${errSchemaPath}": ` + self.errorsText(def.validateSchema.errors); + if (opts.validateSchema === "log") self.logger.error(msg); + else throw new Error(msg); + } + } + } + exports.validateKeywordUsage = validateKeywordUsage; +})); + +//#endregion +//#region ../../node_modules/.pnpm/ajv@8.18.0/node_modules/ajv/dist/compile/validate/subschema.js +var require_subschema = /* @__PURE__ */ __commonJSMin(((exports) => { + Object.defineProperty(exports, "__esModule", { value: true }); + exports.extendSubschemaMode = exports.extendSubschemaData = exports.getSubschema = void 0; + const codegen_1 = require_codegen(); + const util_1 = require_util(); + function getSubschema(it, { keyword, schemaProp, schema, schemaPath, errSchemaPath, topSchemaRef }) { + if (keyword !== void 0 && schema !== void 0) throw new Error("both \"keyword\" and \"schema\" passed, only one allowed"); + if (keyword !== void 0) { + const sch = it.schema[keyword]; + return schemaProp === void 0 ? { + schema: sch, + schemaPath: (0, codegen_1._)`${it.schemaPath}${(0, codegen_1.getProperty)(keyword)}`, + errSchemaPath: `${it.errSchemaPath}/${keyword}` + } : { + schema: sch[schemaProp], + schemaPath: (0, codegen_1._)`${it.schemaPath}${(0, codegen_1.getProperty)(keyword)}${(0, codegen_1.getProperty)(schemaProp)}`, + errSchemaPath: `${it.errSchemaPath}/${keyword}/${(0, util_1.escapeFragment)(schemaProp)}` + }; + } + if (schema !== void 0) { + if (schemaPath === void 0 || errSchemaPath === void 0 || topSchemaRef === void 0) throw new Error("\"schemaPath\", \"errSchemaPath\" and \"topSchemaRef\" are required with \"schema\""); + return { + schema, + schemaPath, + topSchemaRef, + errSchemaPath + }; + } + throw new Error("either \"keyword\" or \"schema\" must be passed"); + } + exports.getSubschema = getSubschema; + function extendSubschemaData(subschema, it, { dataProp, dataPropType: dpType, data, dataTypes, propertyName }) { + if (data !== void 0 && dataProp !== void 0) throw new Error("both \"data\" and \"dataProp\" passed, only one allowed"); + const { gen } = it; + if (dataProp !== void 0) { + const { errorPath, dataPathArr, opts } = it; + dataContextProps(gen.let("data", (0, codegen_1._)`${it.data}${(0, codegen_1.getProperty)(dataProp)}`, true)); + subschema.errorPath = (0, codegen_1.str)`${errorPath}${(0, util_1.getErrorPath)(dataProp, dpType, opts.jsPropertySyntax)}`; + subschema.parentDataProperty = (0, codegen_1._)`${dataProp}`; + subschema.dataPathArr = [...dataPathArr, subschema.parentDataProperty]; + } + if (data !== void 0) { + dataContextProps(data instanceof codegen_1.Name ? data : gen.let("data", data, true)); + if (propertyName !== void 0) subschema.propertyName = propertyName; + } + if (dataTypes) subschema.dataTypes = dataTypes; + function dataContextProps(_nextData) { + subschema.data = _nextData; + subschema.dataLevel = it.dataLevel + 1; + subschema.dataTypes = []; + it.definedProperties = /* @__PURE__ */ new Set(); + subschema.parentData = it.data; + subschema.dataNames = [...it.dataNames, _nextData]; + } + } + exports.extendSubschemaData = extendSubschemaData; + function extendSubschemaMode(subschema, { jtdDiscriminator, jtdMetadata, compositeRule, createErrors, allErrors }) { + if (compositeRule !== void 0) subschema.compositeRule = compositeRule; + if (createErrors !== void 0) subschema.createErrors = createErrors; + if (allErrors !== void 0) subschema.allErrors = allErrors; + subschema.jtdDiscriminator = jtdDiscriminator; + subschema.jtdMetadata = jtdMetadata; + } + exports.extendSubschemaMode = extendSubschemaMode; +})); + +//#endregion +//#region ../../node_modules/.pnpm/fast-deep-equal@3.1.3/node_modules/fast-deep-equal/index.js +var require_fast_deep_equal = /* @__PURE__ */ __commonJSMin(((exports, module) => { + module.exports = function equal(a, b) { + if (a === b) return true; + if (a && b && typeof a == "object" && typeof b == "object") { + if (a.constructor !== b.constructor) return false; + var length, i, keys; + if (Array.isArray(a)) { + length = a.length; + if (length != b.length) return false; + for (i = length; i-- !== 0;) if (!equal(a[i], b[i])) return false; + return true; + } + if (a.constructor === RegExp) return a.source === b.source && a.flags === b.flags; + if (a.valueOf !== Object.prototype.valueOf) return a.valueOf() === b.valueOf(); + if (a.toString !== Object.prototype.toString) return a.toString() === b.toString(); + keys = Object.keys(a); + length = keys.length; + if (length !== Object.keys(b).length) return false; + for (i = length; i-- !== 0;) if (!Object.prototype.hasOwnProperty.call(b, keys[i])) return false; + for (i = length; i-- !== 0;) { + var key = keys[i]; + if (!equal(a[key], b[key])) return false; + } + return true; + } + return a !== a && b !== b; + }; +})); + +//#endregion +//#region ../../node_modules/.pnpm/json-schema-traverse@1.0.0/node_modules/json-schema-traverse/index.js +var require_json_schema_traverse = /* @__PURE__ */ __commonJSMin(((exports, module) => { + var traverse = module.exports = function(schema, opts, cb) { + if (typeof opts == "function") { + cb = opts; + opts = {}; + } + cb = opts.cb || cb; + var pre = typeof cb == "function" ? cb : cb.pre || function() {}; + var post = cb.post || function() {}; + _traverse(opts, pre, post, schema, "", schema); + }; + traverse.keywords = { + additionalItems: true, + items: true, + contains: true, + additionalProperties: true, + propertyNames: true, + not: true, + if: true, + then: true, + else: true + }; + traverse.arrayKeywords = { + items: true, + allOf: true, + anyOf: true, + oneOf: true + }; + traverse.propsKeywords = { + $defs: true, + definitions: true, + properties: true, + patternProperties: true, + dependencies: true + }; + traverse.skipKeywords = { + default: true, + enum: true, + const: true, + required: true, + maximum: true, + minimum: true, + exclusiveMaximum: true, + exclusiveMinimum: true, + multipleOf: true, + maxLength: true, + minLength: true, + pattern: true, + format: true, + maxItems: true, + minItems: true, + uniqueItems: true, + maxProperties: true, + minProperties: true + }; + function _traverse(opts, pre, post, schema, jsonPtr, rootSchema, parentJsonPtr, parentKeyword, parentSchema, keyIndex) { + if (schema && typeof schema == "object" && !Array.isArray(schema)) { + pre(schema, jsonPtr, rootSchema, parentJsonPtr, parentKeyword, parentSchema, keyIndex); + for (var key in schema) { + var sch = schema[key]; + if (Array.isArray(sch)) { + if (key in traverse.arrayKeywords) for (var i = 0; i < sch.length; i++) _traverse(opts, pre, post, sch[i], jsonPtr + "/" + key + "/" + i, rootSchema, jsonPtr, key, schema, i); + } else if (key in traverse.propsKeywords) { + if (sch && typeof sch == "object") for (var prop in sch) _traverse(opts, pre, post, sch[prop], jsonPtr + "/" + key + "/" + escapeJsonPtr(prop), rootSchema, jsonPtr, key, schema, prop); + } else if (key in traverse.keywords || opts.allKeys && !(key in traverse.skipKeywords)) _traverse(opts, pre, post, sch, jsonPtr + "/" + key, rootSchema, jsonPtr, key, schema); + } + post(schema, jsonPtr, rootSchema, parentJsonPtr, parentKeyword, parentSchema, keyIndex); + } + } + function escapeJsonPtr(str) { + return str.replace(/~/g, "~0").replace(/\//g, "~1"); + } +})); + +//#endregion +//#region ../../node_modules/.pnpm/ajv@8.18.0/node_modules/ajv/dist/compile/resolve.js +var require_resolve = /* @__PURE__ */ __commonJSMin(((exports) => { + Object.defineProperty(exports, "__esModule", { value: true }); + exports.getSchemaRefs = exports.resolveUrl = exports.normalizeId = exports._getFullPath = exports.getFullPath = exports.inlineRef = void 0; + const util_1 = require_util(); + const equal = require_fast_deep_equal(); + const traverse = require_json_schema_traverse(); + const SIMPLE_INLINED = new Set([ + "type", + "format", + "pattern", + "maxLength", + "minLength", + "maxProperties", + "minProperties", + "maxItems", + "minItems", + "maximum", + "minimum", + "uniqueItems", + "multipleOf", + "required", + "enum", + "const" + ]); + function inlineRef(schema, limit = true) { + if (typeof schema == "boolean") return true; + if (limit === true) return !hasRef(schema); + if (!limit) return false; + return countKeys(schema) <= limit; + } + exports.inlineRef = inlineRef; + const REF_KEYWORDS = new Set([ + "$ref", + "$recursiveRef", + "$recursiveAnchor", + "$dynamicRef", + "$dynamicAnchor" + ]); + function hasRef(schema) { + for (const key in schema) { + if (REF_KEYWORDS.has(key)) return true; + const sch = schema[key]; + if (Array.isArray(sch) && sch.some(hasRef)) return true; + if (typeof sch == "object" && hasRef(sch)) return true; + } + return false; + } + function countKeys(schema) { + let count = 0; + for (const key in schema) { + if (key === "$ref") return Infinity; + count++; + if (SIMPLE_INLINED.has(key)) continue; + if (typeof schema[key] == "object") (0, util_1.eachItem)(schema[key], (sch) => count += countKeys(sch)); + if (count === Infinity) return Infinity; + } + return count; + } + function getFullPath(resolver, id = "", normalize) { + if (normalize !== false) id = normalizeId(id); + return _getFullPath(resolver, resolver.parse(id)); + } + exports.getFullPath = getFullPath; + function _getFullPath(resolver, p) { + return resolver.serialize(p).split("#")[0] + "#"; + } + exports._getFullPath = _getFullPath; + const TRAILING_SLASH_HASH = /#\/?$/; + function normalizeId(id) { + return id ? id.replace(TRAILING_SLASH_HASH, "") : ""; + } + exports.normalizeId = normalizeId; + function resolveUrl(resolver, baseId, id) { + id = normalizeId(id); + return resolver.resolve(baseId, id); + } + exports.resolveUrl = resolveUrl; + const ANCHOR = /^[a-z_][-a-z0-9._]*$/i; + function getSchemaRefs(schema, baseId) { + if (typeof schema == "boolean") return {}; + const { schemaId, uriResolver } = this.opts; + const schId = normalizeId(schema[schemaId] || baseId); + const baseIds = { "": schId }; + const pathPrefix = getFullPath(uriResolver, schId, false); + const localRefs = {}; + const schemaRefs = /* @__PURE__ */ new Set(); + traverse(schema, { allKeys: true }, (sch, jsonPtr, _, parentJsonPtr) => { + if (parentJsonPtr === void 0) return; + const fullPath = pathPrefix + jsonPtr; + let innerBaseId = baseIds[parentJsonPtr]; + if (typeof sch[schemaId] == "string") innerBaseId = addRef.call(this, sch[schemaId]); + addAnchor.call(this, sch.$anchor); + addAnchor.call(this, sch.$dynamicAnchor); + baseIds[jsonPtr] = innerBaseId; + function addRef(ref) { + const _resolve = this.opts.uriResolver.resolve; + ref = normalizeId(innerBaseId ? _resolve(innerBaseId, ref) : ref); + if (schemaRefs.has(ref)) throw ambiguos(ref); + schemaRefs.add(ref); + let schOrRef = this.refs[ref]; + if (typeof schOrRef == "string") schOrRef = this.refs[schOrRef]; + if (typeof schOrRef == "object") checkAmbiguosRef(sch, schOrRef.schema, ref); + else if (ref !== normalizeId(fullPath)) if (ref[0] === "#") { + checkAmbiguosRef(sch, localRefs[ref], ref); + localRefs[ref] = sch; + } else this.refs[ref] = fullPath; + return ref; + } + function addAnchor(anchor) { + if (typeof anchor == "string") { + if (!ANCHOR.test(anchor)) throw new Error(`invalid anchor "${anchor}"`); + addRef.call(this, `#${anchor}`); + } + } + }); + return localRefs; + function checkAmbiguosRef(sch1, sch2, ref) { + if (sch2 !== void 0 && !equal(sch1, sch2)) throw ambiguos(ref); + } + function ambiguos(ref) { + return /* @__PURE__ */ new Error(`reference "${ref}" resolves to more than one schema`); + } + } + exports.getSchemaRefs = getSchemaRefs; +})); + +//#endregion +//#region ../../node_modules/.pnpm/ajv@8.18.0/node_modules/ajv/dist/compile/validate/index.js +var require_validate = /* @__PURE__ */ __commonJSMin(((exports) => { + Object.defineProperty(exports, "__esModule", { value: true }); + exports.getData = exports.KeywordCxt = exports.validateFunctionCode = void 0; + const boolSchema_1 = require_boolSchema(); + const dataType_1 = require_dataType(); + const applicability_1 = require_applicability(); + const dataType_2 = require_dataType(); + const defaults_1 = require_defaults(); + const keyword_1 = require_keyword(); + const subschema_1 = require_subschema(); + const codegen_1 = require_codegen(); + const names_1 = require_names(); + const resolve_1 = require_resolve(); + const util_1 = require_util(); + const errors_1 = require_errors(); + function validateFunctionCode(it) { + if (isSchemaObj(it)) { + checkKeywords(it); + if (schemaCxtHasRules(it)) { + topSchemaObjCode(it); + return; + } + } + validateFunction(it, () => (0, boolSchema_1.topBoolOrEmptySchema)(it)); + } + exports.validateFunctionCode = validateFunctionCode; + function validateFunction({ gen, validateName, schema, schemaEnv, opts }, body) { + if (opts.code.es5) gen.func(validateName, (0, codegen_1._)`${names_1.default.data}, ${names_1.default.valCxt}`, schemaEnv.$async, () => { + gen.code((0, codegen_1._)`"use strict"; ${funcSourceUrl(schema, opts)}`); + destructureValCxtES5(gen, opts); + gen.code(body); + }); + else gen.func(validateName, (0, codegen_1._)`${names_1.default.data}, ${destructureValCxt(opts)}`, schemaEnv.$async, () => gen.code(funcSourceUrl(schema, opts)).code(body)); + } + function destructureValCxt(opts) { + return (0, codegen_1._)`{${names_1.default.instancePath}="", ${names_1.default.parentData}, ${names_1.default.parentDataProperty}, ${names_1.default.rootData}=${names_1.default.data}${opts.dynamicRef ? (0, codegen_1._)`, ${names_1.default.dynamicAnchors}={}` : codegen_1.nil}}={}`; + } + function destructureValCxtES5(gen, opts) { + gen.if(names_1.default.valCxt, () => { + gen.var(names_1.default.instancePath, (0, codegen_1._)`${names_1.default.valCxt}.${names_1.default.instancePath}`); + gen.var(names_1.default.parentData, (0, codegen_1._)`${names_1.default.valCxt}.${names_1.default.parentData}`); + gen.var(names_1.default.parentDataProperty, (0, codegen_1._)`${names_1.default.valCxt}.${names_1.default.parentDataProperty}`); + gen.var(names_1.default.rootData, (0, codegen_1._)`${names_1.default.valCxt}.${names_1.default.rootData}`); + if (opts.dynamicRef) gen.var(names_1.default.dynamicAnchors, (0, codegen_1._)`${names_1.default.valCxt}.${names_1.default.dynamicAnchors}`); + }, () => { + gen.var(names_1.default.instancePath, (0, codegen_1._)`""`); + gen.var(names_1.default.parentData, (0, codegen_1._)`undefined`); + gen.var(names_1.default.parentDataProperty, (0, codegen_1._)`undefined`); + gen.var(names_1.default.rootData, names_1.default.data); + if (opts.dynamicRef) gen.var(names_1.default.dynamicAnchors, (0, codegen_1._)`{}`); + }); + } + function topSchemaObjCode(it) { + const { schema, opts, gen } = it; + validateFunction(it, () => { + if (opts.$comment && schema.$comment) commentKeyword(it); + checkNoDefault(it); + gen.let(names_1.default.vErrors, null); + gen.let(names_1.default.errors, 0); + if (opts.unevaluated) resetEvaluated(it); + typeAndKeywords(it); + returnResults(it); + }); + } + function resetEvaluated(it) { + const { gen, validateName } = it; + it.evaluated = gen.const("evaluated", (0, codegen_1._)`${validateName}.evaluated`); + gen.if((0, codegen_1._)`${it.evaluated}.dynamicProps`, () => gen.assign((0, codegen_1._)`${it.evaluated}.props`, (0, codegen_1._)`undefined`)); + gen.if((0, codegen_1._)`${it.evaluated}.dynamicItems`, () => gen.assign((0, codegen_1._)`${it.evaluated}.items`, (0, codegen_1._)`undefined`)); + } + function funcSourceUrl(schema, opts) { + const schId = typeof schema == "object" && schema[opts.schemaId]; + return schId && (opts.code.source || opts.code.process) ? (0, codegen_1._)`/*# sourceURL=${schId} */` : codegen_1.nil; + } + function subschemaCode(it, valid) { + if (isSchemaObj(it)) { + checkKeywords(it); + if (schemaCxtHasRules(it)) { + subSchemaObjCode(it, valid); + return; + } + } + (0, boolSchema_1.boolOrEmptySchema)(it, valid); + } + function schemaCxtHasRules({ schema, self }) { + if (typeof schema == "boolean") return !schema; + for (const key in schema) if (self.RULES.all[key]) return true; + return false; + } + function isSchemaObj(it) { + return typeof it.schema != "boolean"; + } + function subSchemaObjCode(it, valid) { + const { schema, gen, opts } = it; + if (opts.$comment && schema.$comment) commentKeyword(it); + updateContext(it); + checkAsyncSchema(it); + const errsCount = gen.const("_errs", names_1.default.errors); + typeAndKeywords(it, errsCount); + gen.var(valid, (0, codegen_1._)`${errsCount} === ${names_1.default.errors}`); + } + function checkKeywords(it) { + (0, util_1.checkUnknownRules)(it); + checkRefsAndKeywords(it); + } + function typeAndKeywords(it, errsCount) { + if (it.opts.jtd) return schemaKeywords(it, [], false, errsCount); + const types = (0, dataType_1.getSchemaTypes)(it.schema); + schemaKeywords(it, types, !(0, dataType_1.coerceAndCheckDataType)(it, types), errsCount); + } + function checkRefsAndKeywords(it) { + const { schema, errSchemaPath, opts, self } = it; + if (schema.$ref && opts.ignoreKeywordsWithRef && (0, util_1.schemaHasRulesButRef)(schema, self.RULES)) self.logger.warn(`$ref: keywords ignored in schema at path "${errSchemaPath}"`); + } + function checkNoDefault(it) { + const { schema, opts } = it; + if (schema.default !== void 0 && opts.useDefaults && opts.strictSchema) (0, util_1.checkStrictMode)(it, "default is ignored in the schema root"); + } + function updateContext(it) { + const schId = it.schema[it.opts.schemaId]; + if (schId) it.baseId = (0, resolve_1.resolveUrl)(it.opts.uriResolver, it.baseId, schId); + } + function checkAsyncSchema(it) { + if (it.schema.$async && !it.schemaEnv.$async) throw new Error("async schema in sync schema"); + } + function commentKeyword({ gen, schemaEnv, schema, errSchemaPath, opts }) { + const msg = schema.$comment; + if (opts.$comment === true) gen.code((0, codegen_1._)`${names_1.default.self}.logger.log(${msg})`); + else if (typeof opts.$comment == "function") { + const schemaPath = (0, codegen_1.str)`${errSchemaPath}/$comment`; + const rootName = gen.scopeValue("root", { ref: schemaEnv.root }); + gen.code((0, codegen_1._)`${names_1.default.self}.opts.$comment(${msg}, ${schemaPath}, ${rootName}.schema)`); + } + } + function returnResults(it) { + const { gen, schemaEnv, validateName, ValidationError, opts } = it; + if (schemaEnv.$async) gen.if((0, codegen_1._)`${names_1.default.errors} === 0`, () => gen.return(names_1.default.data), () => gen.throw((0, codegen_1._)`new ${ValidationError}(${names_1.default.vErrors})`)); + else { + gen.assign((0, codegen_1._)`${validateName}.errors`, names_1.default.vErrors); + if (opts.unevaluated) assignEvaluated(it); + gen.return((0, codegen_1._)`${names_1.default.errors} === 0`); + } + } + function assignEvaluated({ gen, evaluated, props, items }) { + if (props instanceof codegen_1.Name) gen.assign((0, codegen_1._)`${evaluated}.props`, props); + if (items instanceof codegen_1.Name) gen.assign((0, codegen_1._)`${evaluated}.items`, items); + } + function schemaKeywords(it, types, typeErrors, errsCount) { + const { gen, schema, data, allErrors, opts, self } = it; + const { RULES } = self; + if (schema.$ref && (opts.ignoreKeywordsWithRef || !(0, util_1.schemaHasRulesButRef)(schema, RULES))) { + gen.block(() => keywordCode(it, "$ref", RULES.all.$ref.definition)); + return; + } + if (!opts.jtd) checkStrictTypes(it, types); + gen.block(() => { + for (const group of RULES.rules) groupKeywords(group); + groupKeywords(RULES.post); + }); + function groupKeywords(group) { + if (!(0, applicability_1.shouldUseGroup)(schema, group)) return; + if (group.type) { + gen.if((0, dataType_2.checkDataType)(group.type, data, opts.strictNumbers)); + iterateKeywords(it, group); + if (types.length === 1 && types[0] === group.type && typeErrors) { + gen.else(); + (0, dataType_2.reportTypeError)(it); + } + gen.endIf(); + } else iterateKeywords(it, group); + if (!allErrors) gen.if((0, codegen_1._)`${names_1.default.errors} === ${errsCount || 0}`); + } + } + function iterateKeywords(it, group) { + const { gen, schema, opts: { useDefaults } } = it; + if (useDefaults) (0, defaults_1.assignDefaults)(it, group.type); + gen.block(() => { + for (const rule of group.rules) if ((0, applicability_1.shouldUseRule)(schema, rule)) keywordCode(it, rule.keyword, rule.definition, group.type); + }); + } + function checkStrictTypes(it, types) { + if (it.schemaEnv.meta || !it.opts.strictTypes) return; + checkContextTypes(it, types); + if (!it.opts.allowUnionTypes) checkMultipleTypes(it, types); + checkKeywordTypes(it, it.dataTypes); + } + function checkContextTypes(it, types) { + if (!types.length) return; + if (!it.dataTypes.length) { + it.dataTypes = types; + return; + } + types.forEach((t) => { + if (!includesType(it.dataTypes, t)) strictTypesError(it, `type "${t}" not allowed by context "${it.dataTypes.join(",")}"`); + }); + narrowSchemaTypes(it, types); + } + function checkMultipleTypes(it, ts) { + if (ts.length > 1 && !(ts.length === 2 && ts.includes("null"))) strictTypesError(it, "use allowUnionTypes to allow union type keyword"); + } + function checkKeywordTypes(it, ts) { + const rules = it.self.RULES.all; + for (const keyword in rules) { + const rule = rules[keyword]; + if (typeof rule == "object" && (0, applicability_1.shouldUseRule)(it.schema, rule)) { + const { type } = rule.definition; + if (type.length && !type.some((t) => hasApplicableType(ts, t))) strictTypesError(it, `missing type "${type.join(",")}" for keyword "${keyword}"`); + } + } + } + function hasApplicableType(schTs, kwdT) { + return schTs.includes(kwdT) || kwdT === "number" && schTs.includes("integer"); + } + function includesType(ts, t) { + return ts.includes(t) || t === "integer" && ts.includes("number"); + } + function narrowSchemaTypes(it, withTypes) { + const ts = []; + for (const t of it.dataTypes) if (includesType(withTypes, t)) ts.push(t); + else if (withTypes.includes("integer") && t === "number") ts.push("integer"); + it.dataTypes = ts; + } + function strictTypesError(it, msg) { + const schemaPath = it.schemaEnv.baseId + it.errSchemaPath; + msg += ` at "${schemaPath}" (strictTypes)`; + (0, util_1.checkStrictMode)(it, msg, it.opts.strictTypes); + } + var KeywordCxt = class { + constructor(it, def, keyword) { + (0, keyword_1.validateKeywordUsage)(it, def, keyword); + this.gen = it.gen; + this.allErrors = it.allErrors; + this.keyword = keyword; + this.data = it.data; + this.schema = it.schema[keyword]; + this.$data = def.$data && it.opts.$data && this.schema && this.schema.$data; + this.schemaValue = (0, util_1.schemaRefOrVal)(it, this.schema, keyword, this.$data); + this.schemaType = def.schemaType; + this.parentSchema = it.schema; + this.params = {}; + this.it = it; + this.def = def; + if (this.$data) this.schemaCode = it.gen.const("vSchema", getData(this.$data, it)); + else { + this.schemaCode = this.schemaValue; + if (!(0, keyword_1.validSchemaType)(this.schema, def.schemaType, def.allowUndefined)) throw new Error(`${keyword} value must be ${JSON.stringify(def.schemaType)}`); + } + if ("code" in def ? def.trackErrors : def.errors !== false) this.errsCount = it.gen.const("_errs", names_1.default.errors); + } + result(condition, successAction, failAction) { + this.failResult((0, codegen_1.not)(condition), successAction, failAction); + } + failResult(condition, successAction, failAction) { + this.gen.if(condition); + if (failAction) failAction(); + else this.error(); + if (successAction) { + this.gen.else(); + successAction(); + if (this.allErrors) this.gen.endIf(); + } else if (this.allErrors) this.gen.endIf(); + else this.gen.else(); + } + pass(condition, failAction) { + this.failResult((0, codegen_1.not)(condition), void 0, failAction); + } + fail(condition) { + if (condition === void 0) { + this.error(); + if (!this.allErrors) this.gen.if(false); + return; + } + this.gen.if(condition); + this.error(); + if (this.allErrors) this.gen.endIf(); + else this.gen.else(); + } + fail$data(condition) { + if (!this.$data) return this.fail(condition); + const { schemaCode } = this; + this.fail((0, codegen_1._)`${schemaCode} !== undefined && (${(0, codegen_1.or)(this.invalid$data(), condition)})`); + } + error(append, errorParams, errorPaths) { + if (errorParams) { + this.setParams(errorParams); + this._error(append, errorPaths); + this.setParams({}); + return; + } + this._error(append, errorPaths); + } + _error(append, errorPaths) { + (append ? errors_1.reportExtraError : errors_1.reportError)(this, this.def.error, errorPaths); + } + $dataError() { + (0, errors_1.reportError)(this, this.def.$dataError || errors_1.keyword$DataError); + } + reset() { + if (this.errsCount === void 0) throw new Error("add \"trackErrors\" to keyword definition"); + (0, errors_1.resetErrorsCount)(this.gen, this.errsCount); + } + ok(cond) { + if (!this.allErrors) this.gen.if(cond); + } + setParams(obj, assign) { + if (assign) Object.assign(this.params, obj); + else this.params = obj; + } + block$data(valid, codeBlock, $dataValid = codegen_1.nil) { + this.gen.block(() => { + this.check$data(valid, $dataValid); + codeBlock(); + }); + } + check$data(valid = codegen_1.nil, $dataValid = codegen_1.nil) { + if (!this.$data) return; + const { gen, schemaCode, schemaType, def } = this; + gen.if((0, codegen_1.or)((0, codegen_1._)`${schemaCode} === undefined`, $dataValid)); + if (valid !== codegen_1.nil) gen.assign(valid, true); + if (schemaType.length || def.validateSchema) { + gen.elseIf(this.invalid$data()); + this.$dataError(); + if (valid !== codegen_1.nil) gen.assign(valid, false); + } + gen.else(); + } + invalid$data() { + const { gen, schemaCode, schemaType, def, it } = this; + return (0, codegen_1.or)(wrong$DataType(), invalid$DataSchema()); + function wrong$DataType() { + if (schemaType.length) { + /* istanbul ignore if */ + if (!(schemaCode instanceof codegen_1.Name)) throw new Error("ajv implementation error"); + const st = Array.isArray(schemaType) ? schemaType : [schemaType]; + return (0, codegen_1._)`${(0, dataType_2.checkDataTypes)(st, schemaCode, it.opts.strictNumbers, dataType_2.DataType.Wrong)}`; + } + return codegen_1.nil; + } + function invalid$DataSchema() { + if (def.validateSchema) { + const validateSchemaRef = gen.scopeValue("validate$data", { ref: def.validateSchema }); + return (0, codegen_1._)`!${validateSchemaRef}(${schemaCode})`; + } + return codegen_1.nil; + } + } + subschema(appl, valid) { + const subschema = (0, subschema_1.getSubschema)(this.it, appl); + (0, subschema_1.extendSubschemaData)(subschema, this.it, appl); + (0, subschema_1.extendSubschemaMode)(subschema, appl); + const nextContext = { + ...this.it, + ...subschema, + items: void 0, + props: void 0 + }; + subschemaCode(nextContext, valid); + return nextContext; + } + mergeEvaluated(schemaCxt, toName) { + const { it, gen } = this; + if (!it.opts.unevaluated) return; + if (it.props !== true && schemaCxt.props !== void 0) it.props = util_1.mergeEvaluated.props(gen, schemaCxt.props, it.props, toName); + if (it.items !== true && schemaCxt.items !== void 0) it.items = util_1.mergeEvaluated.items(gen, schemaCxt.items, it.items, toName); + } + mergeValidEvaluated(schemaCxt, valid) { + const { it, gen } = this; + if (it.opts.unevaluated && (it.props !== true || it.items !== true)) { + gen.if(valid, () => this.mergeEvaluated(schemaCxt, codegen_1.Name)); + return true; + } + } + }; + exports.KeywordCxt = KeywordCxt; + function keywordCode(it, keyword, def, ruleType) { + const cxt = new KeywordCxt(it, def, keyword); + if ("code" in def) def.code(cxt, ruleType); + else if (cxt.$data && def.validate) (0, keyword_1.funcKeywordCode)(cxt, def); + else if ("macro" in def) (0, keyword_1.macroKeywordCode)(cxt, def); + else if (def.compile || def.validate) (0, keyword_1.funcKeywordCode)(cxt, def); + } + const JSON_POINTER = /^\/(?:[^~]|~0|~1)*$/; + const RELATIVE_JSON_POINTER = /^([0-9]+)(#|\/(?:[^~]|~0|~1)*)?$/; + function getData($data, { dataLevel, dataNames, dataPathArr }) { + let jsonPointer; + let data; + if ($data === "") return names_1.default.rootData; + if ($data[0] === "/") { + if (!JSON_POINTER.test($data)) throw new Error(`Invalid JSON-pointer: ${$data}`); + jsonPointer = $data; + data = names_1.default.rootData; + } else { + const matches = RELATIVE_JSON_POINTER.exec($data); + if (!matches) throw new Error(`Invalid JSON-pointer: ${$data}`); + const up = +matches[1]; + jsonPointer = matches[2]; + if (jsonPointer === "#") { + if (up >= dataLevel) throw new Error(errorMsg("property/index", up)); + return dataPathArr[dataLevel - up]; + } + if (up > dataLevel) throw new Error(errorMsg("data", up)); + data = dataNames[dataLevel - up]; + if (!jsonPointer) return data; + } + let expr = data; + const segments = jsonPointer.split("/"); + for (const segment of segments) if (segment) { + data = (0, codegen_1._)`${data}${(0, codegen_1.getProperty)((0, util_1.unescapeJsonPointer)(segment))}`; + expr = (0, codegen_1._)`${expr} && ${data}`; + } + return expr; + function errorMsg(pointerType, up) { + return `Cannot access ${pointerType} ${up} levels up, current level is ${dataLevel}`; + } + } + exports.getData = getData; +})); + +//#endregion +//#region ../../node_modules/.pnpm/ajv@8.18.0/node_modules/ajv/dist/runtime/validation_error.js +var require_validation_error = /* @__PURE__ */ __commonJSMin(((exports) => { + Object.defineProperty(exports, "__esModule", { value: true }); + var ValidationError = class extends Error { + constructor(errors) { + super("validation failed"); + this.errors = errors; + this.ajv = this.validation = true; + } + }; + exports.default = ValidationError; +})); + +//#endregion +//#region ../../node_modules/.pnpm/ajv@8.18.0/node_modules/ajv/dist/compile/ref_error.js +var require_ref_error = /* @__PURE__ */ __commonJSMin(((exports) => { + Object.defineProperty(exports, "__esModule", { value: true }); + const resolve_1 = require_resolve(); + var MissingRefError = class extends Error { + constructor(resolver, baseId, ref, msg) { + super(msg || `can't resolve reference ${ref} from id ${baseId}`); + this.missingRef = (0, resolve_1.resolveUrl)(resolver, baseId, ref); + this.missingSchema = (0, resolve_1.normalizeId)((0, resolve_1.getFullPath)(resolver, this.missingRef)); + } + }; + exports.default = MissingRefError; +})); + +//#endregion +//#region ../../node_modules/.pnpm/ajv@8.18.0/node_modules/ajv/dist/compile/index.js +var require_compile = /* @__PURE__ */ __commonJSMin(((exports) => { + Object.defineProperty(exports, "__esModule", { value: true }); + exports.resolveSchema = exports.getCompilingSchema = exports.resolveRef = exports.compileSchema = exports.SchemaEnv = void 0; + const codegen_1 = require_codegen(); + const validation_error_1 = require_validation_error(); + const names_1 = require_names(); + const resolve_1 = require_resolve(); + const util_1 = require_util(); + const validate_1 = require_validate(); + var SchemaEnv = class { + constructor(env) { + var _a; + this.refs = {}; + this.dynamicAnchors = {}; + let schema; + if (typeof env.schema == "object") schema = env.schema; + this.schema = env.schema; + this.schemaId = env.schemaId; + this.root = env.root || this; + this.baseId = (_a = env.baseId) !== null && _a !== void 0 ? _a : (0, resolve_1.normalizeId)(schema === null || schema === void 0 ? void 0 : schema[env.schemaId || "$id"]); + this.schemaPath = env.schemaPath; + this.localRefs = env.localRefs; + this.meta = env.meta; + this.$async = schema === null || schema === void 0 ? void 0 : schema.$async; + this.refs = {}; + } + }; + exports.SchemaEnv = SchemaEnv; + function compileSchema(sch) { + const _sch = getCompilingSchema.call(this, sch); + if (_sch) return _sch; + const rootId = (0, resolve_1.getFullPath)(this.opts.uriResolver, sch.root.baseId); + const { es5, lines } = this.opts.code; + const { ownProperties } = this.opts; + const gen = new codegen_1.CodeGen(this.scope, { + es5, + lines, + ownProperties + }); + let _ValidationError; + if (sch.$async) _ValidationError = gen.scopeValue("Error", { + ref: validation_error_1.default, + code: (0, codegen_1._)`require("ajv/dist/runtime/validation_error").default` + }); + const validateName = gen.scopeName("validate"); + sch.validateName = validateName; + const schemaCxt = { + gen, + allErrors: this.opts.allErrors, + data: names_1.default.data, + parentData: names_1.default.parentData, + parentDataProperty: names_1.default.parentDataProperty, + dataNames: [names_1.default.data], + dataPathArr: [codegen_1.nil], + dataLevel: 0, + dataTypes: [], + definedProperties: /* @__PURE__ */ new Set(), + topSchemaRef: gen.scopeValue("schema", this.opts.code.source === true ? { + ref: sch.schema, + code: (0, codegen_1.stringify)(sch.schema) + } : { ref: sch.schema }), + validateName, + ValidationError: _ValidationError, + schema: sch.schema, + schemaEnv: sch, + rootId, + baseId: sch.baseId || rootId, + schemaPath: codegen_1.nil, + errSchemaPath: sch.schemaPath || (this.opts.jtd ? "" : "#"), + errorPath: (0, codegen_1._)`""`, + opts: this.opts, + self: this + }; + let sourceCode; + try { + this._compilations.add(sch); + (0, validate_1.validateFunctionCode)(schemaCxt); + gen.optimize(this.opts.code.optimize); + const validateCode = gen.toString(); + sourceCode = `${gen.scopeRefs(names_1.default.scope)}return ${validateCode}`; + if (this.opts.code.process) sourceCode = this.opts.code.process(sourceCode, sch); + const validate = new Function(`${names_1.default.self}`, `${names_1.default.scope}`, sourceCode)(this, this.scope.get()); + this.scope.value(validateName, { ref: validate }); + validate.errors = null; + validate.schema = sch.schema; + validate.schemaEnv = sch; + if (sch.$async) validate.$async = true; + if (this.opts.code.source === true) validate.source = { + validateName, + validateCode, + scopeValues: gen._values + }; + if (this.opts.unevaluated) { + const { props, items } = schemaCxt; + validate.evaluated = { + props: props instanceof codegen_1.Name ? void 0 : props, + items: items instanceof codegen_1.Name ? void 0 : items, + dynamicProps: props instanceof codegen_1.Name, + dynamicItems: items instanceof codegen_1.Name + }; + if (validate.source) validate.source.evaluated = (0, codegen_1.stringify)(validate.evaluated); + } + sch.validate = validate; + return sch; + } catch (e) { + delete sch.validate; + delete sch.validateName; + if (sourceCode) this.logger.error("Error compiling schema, function code:", sourceCode); + throw e; + } finally { + this._compilations.delete(sch); + } + } + exports.compileSchema = compileSchema; + function resolveRef(root, baseId, ref) { + var _a; + ref = (0, resolve_1.resolveUrl)(this.opts.uriResolver, baseId, ref); + const schOrFunc = root.refs[ref]; + if (schOrFunc) return schOrFunc; + let _sch = resolve.call(this, root, ref); + if (_sch === void 0) { + const schema = (_a = root.localRefs) === null || _a === void 0 ? void 0 : _a[ref]; + const { schemaId } = this.opts; + if (schema) _sch = new SchemaEnv({ + schema, + schemaId, + root, + baseId + }); + } + if (_sch === void 0) return; + return root.refs[ref] = inlineOrCompile.call(this, _sch); + } + exports.resolveRef = resolveRef; + function inlineOrCompile(sch) { + if ((0, resolve_1.inlineRef)(sch.schema, this.opts.inlineRefs)) return sch.schema; + return sch.validate ? sch : compileSchema.call(this, sch); + } + function getCompilingSchema(schEnv) { + for (const sch of this._compilations) if (sameSchemaEnv(sch, schEnv)) return sch; + } + exports.getCompilingSchema = getCompilingSchema; + function sameSchemaEnv(s1, s2) { + return s1.schema === s2.schema && s1.root === s2.root && s1.baseId === s2.baseId; + } + function resolve(root, ref) { + let sch; + while (typeof (sch = this.refs[ref]) == "string") ref = sch; + return sch || this.schemas[ref] || resolveSchema.call(this, root, ref); + } + function resolveSchema(root, ref) { + const p = this.opts.uriResolver.parse(ref); + const refPath = (0, resolve_1._getFullPath)(this.opts.uriResolver, p); + let baseId = (0, resolve_1.getFullPath)(this.opts.uriResolver, root.baseId, void 0); + if (Object.keys(root.schema).length > 0 && refPath === baseId) return getJsonPointer.call(this, p, root); + const id = (0, resolve_1.normalizeId)(refPath); + const schOrRef = this.refs[id] || this.schemas[id]; + if (typeof schOrRef == "string") { + const sch = resolveSchema.call(this, root, schOrRef); + if (typeof (sch === null || sch === void 0 ? void 0 : sch.schema) !== "object") return; + return getJsonPointer.call(this, p, sch); + } + if (typeof (schOrRef === null || schOrRef === void 0 ? void 0 : schOrRef.schema) !== "object") return; + if (!schOrRef.validate) compileSchema.call(this, schOrRef); + if (id === (0, resolve_1.normalizeId)(ref)) { + const { schema } = schOrRef; + const { schemaId } = this.opts; + const schId = schema[schemaId]; + if (schId) baseId = (0, resolve_1.resolveUrl)(this.opts.uriResolver, baseId, schId); + return new SchemaEnv({ + schema, + schemaId, + root, + baseId + }); + } + return getJsonPointer.call(this, p, schOrRef); + } + exports.resolveSchema = resolveSchema; + const PREVENT_SCOPE_CHANGE = new Set([ + "properties", + "patternProperties", + "enum", + "dependencies", + "definitions" + ]); + function getJsonPointer(parsedRef, { baseId, schema, root }) { + var _a; + if (((_a = parsedRef.fragment) === null || _a === void 0 ? void 0 : _a[0]) !== "/") return; + for (const part of parsedRef.fragment.slice(1).split("/")) { + if (typeof schema === "boolean") return; + const partSchema = schema[(0, util_1.unescapeFragment)(part)]; + if (partSchema === void 0) return; + schema = partSchema; + const schId = typeof schema === "object" && schema[this.opts.schemaId]; + if (!PREVENT_SCOPE_CHANGE.has(part) && schId) baseId = (0, resolve_1.resolveUrl)(this.opts.uriResolver, baseId, schId); + } + let env; + if (typeof schema != "boolean" && schema.$ref && !(0, util_1.schemaHasRulesButRef)(schema, this.RULES)) { + const $ref = (0, resolve_1.resolveUrl)(this.opts.uriResolver, baseId, schema.$ref); + env = resolveSchema.call(this, root, $ref); + } + const { schemaId } = this.opts; + env = env || new SchemaEnv({ + schema, + schemaId, + root, + baseId + }); + if (env.schema !== env.root.schema) return env; + } +})); + +//#endregion +//#region ../../node_modules/.pnpm/ajv@8.18.0/node_modules/ajv/dist/refs/data.json +var require_data = /* @__PURE__ */ __commonJSMin(((exports, module) => { + module.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": false + }; +})); + +//#endregion +//#region ../../node_modules/.pnpm/fast-uri@3.1.0/node_modules/fast-uri/lib/utils.js +var require_utils = /* @__PURE__ */ __commonJSMin(((exports, module) => { + /** @type {(value: string) => boolean} */ + const isUUID = RegExp.prototype.test.bind(/^[\da-f]{8}-[\da-f]{4}-[\da-f]{4}-[\da-f]{4}-[\da-f]{12}$/iu); + /** @type {(value: string) => boolean} */ + const isIPv4 = 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); + /** + * @param {Array} input + * @returns {string} + */ + function stringArrayToHexStripped(input) { + let acc = ""; + let code = 0; + let i = 0; + for (i = 0; i < input.length; i++) { + code = input[i].charCodeAt(0); + if (code === 48) continue; + if (!(code >= 48 && code <= 57 || code >= 65 && code <= 70 || code >= 97 && code <= 102)) return ""; + acc += input[i]; + break; + } + for (i += 1; i < input.length; i++) { + code = input[i].charCodeAt(0); + if (!(code >= 48 && code <= 57 || code >= 65 && code <= 70 || code >= 97 && code <= 102)) return ""; + acc += input[i]; + } + return acc; + } + /** + * @typedef {Object} GetIPV6Result + * @property {boolean} error - Indicates if there was an error parsing the IPv6 address. + * @property {string} address - The parsed IPv6 address. + * @property {string} [zone] - The zone identifier, if present. + */ + /** + * @param {string} value + * @returns {boolean} + */ + const nonSimpleDomain = RegExp.prototype.test.bind(/[^!"$&'()*+,\-.;=_`a-z{}~]/u); + /** + * @param {Array} buffer + * @returns {boolean} + */ + function consumeIsZone(buffer) { + buffer.length = 0; + return true; + } + /** + * @param {Array} buffer + * @param {Array} address + * @param {GetIPV6Result} output + * @returns {boolean} + */ + function consumeHextets(buffer, address, output) { + if (buffer.length) { + const hex = stringArrayToHexStripped(buffer); + if (hex !== "") address.push(hex); + else { + output.error = true; + return false; + } + buffer.length = 0; + } + return true; + } + /** + * @param {string} input + * @returns {GetIPV6Result} + */ + function getIPV6(input) { + let tokenCount = 0; + const output = { + error: false, + address: "", + zone: "" + }; + /** @type {Array} */ + const address = []; + /** @type {Array} */ + const buffer = []; + let endipv6Encountered = false; + let endIpv6 = false; + let consume = consumeHextets; + for (let i = 0; i < input.length; i++) { + const cursor = input[i]; + if (cursor === "[" || cursor === "]") continue; + if (cursor === ":") { + if (endipv6Encountered === true) endIpv6 = true; + if (!consume(buffer, address, output)) break; + if (++tokenCount > 7) { + output.error = true; + break; + } + if (i > 0 && input[i - 1] === ":") endipv6Encountered = true; + address.push(":"); + continue; + } else if (cursor === "%") { + if (!consume(buffer, address, output)) break; + consume = consumeIsZone; + } else { + buffer.push(cursor); + continue; + } + } + if (buffer.length) if (consume === consumeIsZone) output.zone = buffer.join(""); + else if (endIpv6) address.push(buffer.join("")); + else address.push(stringArrayToHexStripped(buffer)); + output.address = address.join(""); + return output; + } + /** + * @typedef {Object} NormalizeIPv6Result + * @property {string} host - The normalized host. + * @property {string} [escapedHost] - The escaped host. + * @property {boolean} isIPV6 - Indicates if the host is an IPv6 address. + */ + /** + * @param {string} host + * @returns {NormalizeIPv6Result} + */ + function normalizeIPv6(host) { + if (findToken(host, ":") < 2) return { + host, + isIPV6: false + }; + const ipv6 = getIPV6(host); + if (!ipv6.error) { + let newHost = ipv6.address; + let escapedHost = ipv6.address; + if (ipv6.zone) { + newHost += "%" + ipv6.zone; + escapedHost += "%25" + ipv6.zone; + } + return { + host: newHost, + isIPV6: true, + escapedHost + }; + } else return { + host, + isIPV6: false + }; + } + /** + * @param {string} str + * @param {string} token + * @returns {number} + */ + function findToken(str, token) { + let ind = 0; + for (let i = 0; i < str.length; i++) if (str[i] === token) ind++; + return ind; + } + /** + * @param {string} path + * @returns {string} + * + * @see https://datatracker.ietf.org/doc/html/rfc3986#section-5.2.4 + */ + function removeDotSegments(path) { + let input = path; + const output = []; + let nextSlash = -1; + let len = 0; + while (len = input.length) { + if (len === 1) if (input === ".") break; + else if (input === "/") { + output.push("/"); + break; + } else { + output.push(input); + break; + } + else if (len === 2) { + if (input[0] === ".") { + if (input[1] === ".") break; + else if (input[1] === "/") { + input = input.slice(2); + continue; + } + } else if (input[0] === "/") { + if (input[1] === "." || input[1] === "/") { + output.push("/"); + break; + } + } + } else if (len === 3) { + if (input === "/..") { + if (output.length !== 0) output.pop(); + output.push("/"); + break; + } + } + if (input[0] === ".") { + if (input[1] === ".") { + if (input[2] === "/") { + input = input.slice(3); + continue; + } + } else if (input[1] === "/") { + input = input.slice(2); + continue; + } + } else if (input[0] === "/") { + if (input[1] === ".") { + if (input[2] === "/") { + input = input.slice(2); + continue; + } else if (input[2] === ".") { + if (input[3] === "/") { + input = input.slice(3); + if (output.length !== 0) output.pop(); + continue; + } + } + } + } + if ((nextSlash = input.indexOf("/", 1)) === -1) { + output.push(input); + break; + } else { + output.push(input.slice(0, nextSlash)); + input = input.slice(nextSlash); + } + } + return output.join(""); + } + /** + * @param {import('../types/index').URIComponent} component + * @param {boolean} esc + * @returns {import('../types/index').URIComponent} + */ + function normalizeComponentEncoding(component, esc) { + const func = esc !== true ? escape : unescape; + if (component.scheme !== void 0) component.scheme = func(component.scheme); + if (component.userinfo !== void 0) component.userinfo = func(component.userinfo); + if (component.host !== void 0) component.host = func(component.host); + if (component.path !== void 0) component.path = func(component.path); + if (component.query !== void 0) component.query = func(component.query); + if (component.fragment !== void 0) component.fragment = func(component.fragment); + return component; + } + /** + * @param {import('../types/index').URIComponent} component + * @returns {string|undefined} + */ + function recomposeAuthority(component) { + const uriTokens = []; + if (component.userinfo !== void 0) { + uriTokens.push(component.userinfo); + uriTokens.push("@"); + } + if (component.host !== void 0) { + let host = unescape(component.host); + if (!isIPv4(host)) { + const ipV6res = normalizeIPv6(host); + if (ipV6res.isIPV6 === true) host = `[${ipV6res.escapedHost}]`; + else host = component.host; + } + uriTokens.push(host); + } + if (typeof component.port === "number" || typeof component.port === "string") { + uriTokens.push(":"); + uriTokens.push(String(component.port)); + } + return uriTokens.length ? uriTokens.join("") : void 0; + } + module.exports = { + nonSimpleDomain, + recomposeAuthority, + normalizeComponentEncoding, + removeDotSegments, + isIPv4, + isUUID, + normalizeIPv6, + stringArrayToHexStripped + }; +})); + +//#endregion +//#region ../../node_modules/.pnpm/fast-uri@3.1.0/node_modules/fast-uri/lib/schemes.js +var require_schemes = /* @__PURE__ */ __commonJSMin(((exports, module) => { + const { isUUID } = require_utils(); + const URN_REG = /([\da-z][\d\-a-z]{0,31}):((?:[\w!$'()*+,\-.:;=@]|%[\da-f]{2})+)/iu; + const supportedSchemeNames = [ + "http", + "https", + "ws", + "wss", + "urn", + "urn:uuid" + ]; + /** @typedef {supportedSchemeNames[number]} SchemeName */ + /** + * @param {string} name + * @returns {name is SchemeName} + */ + function isValidSchemeName(name) { + return supportedSchemeNames.indexOf(name) !== -1; + } + /** + * @callback SchemeFn + * @param {import('../types/index').URIComponent} component + * @param {import('../types/index').Options} options + * @returns {import('../types/index').URIComponent} + */ + /** + * @typedef {Object} SchemeHandler + * @property {SchemeName} scheme - The scheme name. + * @property {boolean} [domainHost] - Indicates if the scheme supports domain hosts. + * @property {SchemeFn} parse - Function to parse the URI component for this scheme. + * @property {SchemeFn} serialize - Function to serialize the URI component for this scheme. + * @property {boolean} [skipNormalize] - Indicates if normalization should be skipped for this scheme. + * @property {boolean} [absolutePath] - Indicates if the scheme uses absolute paths. + * @property {boolean} [unicodeSupport] - Indicates if the scheme supports Unicode. + */ + /** + * @param {import('../types/index').URIComponent} wsComponent + * @returns {boolean} + */ + function wsIsSecure(wsComponent) { + if (wsComponent.secure === true) return true; + else if (wsComponent.secure === false) return false; + else if (wsComponent.scheme) return wsComponent.scheme.length === 3 && (wsComponent.scheme[0] === "w" || wsComponent.scheme[0] === "W") && (wsComponent.scheme[1] === "s" || wsComponent.scheme[1] === "S") && (wsComponent.scheme[2] === "s" || wsComponent.scheme[2] === "S"); + else return false; + } + /** @type {SchemeFn} */ + function httpParse(component) { + if (!component.host) component.error = component.error || "HTTP URIs must have a host."; + return component; + } + /** @type {SchemeFn} */ + function httpSerialize(component) { + const secure = String(component.scheme).toLowerCase() === "https"; + if (component.port === (secure ? 443 : 80) || component.port === "") component.port = void 0; + if (!component.path) component.path = "/"; + return component; + } + /** @type {SchemeFn} */ + function wsParse(wsComponent) { + wsComponent.secure = wsIsSecure(wsComponent); + wsComponent.resourceName = (wsComponent.path || "/") + (wsComponent.query ? "?" + wsComponent.query : ""); + wsComponent.path = void 0; + wsComponent.query = void 0; + return wsComponent; + } + /** @type {SchemeFn} */ + function wsSerialize(wsComponent) { + if (wsComponent.port === (wsIsSecure(wsComponent) ? 443 : 80) || wsComponent.port === "") wsComponent.port = void 0; + if (typeof wsComponent.secure === "boolean") { + wsComponent.scheme = wsComponent.secure ? "wss" : "ws"; + wsComponent.secure = void 0; + } + if (wsComponent.resourceName) { + const [path, query] = wsComponent.resourceName.split("?"); + wsComponent.path = path && path !== "/" ? path : void 0; + wsComponent.query = query; + wsComponent.resourceName = void 0; + } + wsComponent.fragment = void 0; + return wsComponent; + } + /** @type {SchemeFn} */ + function urnParse(urnComponent, options) { + if (!urnComponent.path) { + urnComponent.error = "URN can not be parsed"; + return urnComponent; + } + const matches = urnComponent.path.match(URN_REG); + if (matches) { + const scheme = options.scheme || urnComponent.scheme || "urn"; + urnComponent.nid = matches[1].toLowerCase(); + urnComponent.nss = matches[2]; + const schemeHandler = getSchemeHandler(`${scheme}:${options.nid || urnComponent.nid}`); + urnComponent.path = void 0; + if (schemeHandler) urnComponent = schemeHandler.parse(urnComponent, options); + } else urnComponent.error = urnComponent.error || "URN can not be parsed."; + return urnComponent; + } + /** @type {SchemeFn} */ + function urnSerialize(urnComponent, options) { + if (urnComponent.nid === void 0) throw new Error("URN without nid cannot be serialized"); + const scheme = options.scheme || urnComponent.scheme || "urn"; + const nid = urnComponent.nid.toLowerCase(); + const schemeHandler = getSchemeHandler(`${scheme}:${options.nid || nid}`); + if (schemeHandler) urnComponent = schemeHandler.serialize(urnComponent, options); + const uriComponent = urnComponent; + const nss = urnComponent.nss; + uriComponent.path = `${nid || options.nid}:${nss}`; + options.skipEscape = true; + return uriComponent; + } + /** @type {SchemeFn} */ + function urnuuidParse(urnComponent, options) { + const uuidComponent = urnComponent; + uuidComponent.uuid = uuidComponent.nss; + uuidComponent.nss = void 0; + if (!options.tolerant && (!uuidComponent.uuid || !isUUID(uuidComponent.uuid))) uuidComponent.error = uuidComponent.error || "UUID is not valid."; + return uuidComponent; + } + /** @type {SchemeFn} */ + function urnuuidSerialize(uuidComponent) { + const urnComponent = uuidComponent; + urnComponent.nss = (uuidComponent.uuid || "").toLowerCase(); + return urnComponent; + } + const http = { + scheme: "http", + domainHost: true, + parse: httpParse, + serialize: httpSerialize + }; + const https = { + scheme: "https", + domainHost: http.domainHost, + parse: httpParse, + serialize: httpSerialize + }; + const ws = { + scheme: "ws", + domainHost: true, + parse: wsParse, + serialize: wsSerialize + }; + const wss = { + scheme: "wss", + domainHost: ws.domainHost, + parse: ws.parse, + serialize: ws.serialize + }; + const urn = { + scheme: "urn", + parse: urnParse, + serialize: urnSerialize, + skipNormalize: true + }; + const urnuuid = { + scheme: "urn:uuid", + parse: urnuuidParse, + serialize: urnuuidSerialize, + skipNormalize: true + }; + const SCHEMES = { + http, + https, + ws, + wss, + urn, + "urn:uuid": urnuuid + }; + Object.setPrototypeOf(SCHEMES, null); + /** + * @param {string|undefined} scheme + * @returns {SchemeHandler|undefined} + */ + function getSchemeHandler(scheme) { + return scheme && (SCHEMES[scheme] || SCHEMES[scheme.toLowerCase()]) || void 0; + } + module.exports = { + wsIsSecure, + SCHEMES, + isValidSchemeName, + getSchemeHandler + }; +})); + +//#endregion +//#region ../../node_modules/.pnpm/fast-uri@3.1.0/node_modules/fast-uri/index.js +var require_fast_uri = /* @__PURE__ */ __commonJSMin(((exports, module) => { + const { normalizeIPv6, removeDotSegments, recomposeAuthority, normalizeComponentEncoding, isIPv4, nonSimpleDomain } = require_utils(); + const { SCHEMES, getSchemeHandler } = require_schemes(); + /** + * @template {import('./types/index').URIComponent|string} T + * @param {T} uri + * @param {import('./types/index').Options} [options] + * @returns {T} + */ + function normalize(uri, options) { + if (typeof uri === "string") uri = serialize(parse(uri, options), options); + else if (typeof uri === "object") uri = parse(serialize(uri, options), options); + return uri; + } + /** + * @param {string} baseURI + * @param {string} relativeURI + * @param {import('./types/index').Options} [options] + * @returns {string} + */ + function resolve(baseURI, relativeURI, options) { + const schemelessOptions = options ? Object.assign({ scheme: "null" }, options) : { scheme: "null" }; + const resolved = resolveComponent(parse(baseURI, schemelessOptions), parse(relativeURI, schemelessOptions), schemelessOptions, true); + schemelessOptions.skipEscape = true; + return serialize(resolved, schemelessOptions); + } + /** + * @param {import ('./types/index').URIComponent} base + * @param {import ('./types/index').URIComponent} relative + * @param {import('./types/index').Options} [options] + * @param {boolean} [skipNormalization=false] + * @returns {import ('./types/index').URIComponent} + */ + function resolveComponent(base, relative, options, skipNormalization) { + /** @type {import('./types/index').URIComponent} */ + const target = {}; + if (!skipNormalization) { + base = parse(serialize(base, options), options); + relative = parse(serialize(relative, options), options); + } + options = options || {}; + if (!options.tolerant && relative.scheme) { + target.scheme = relative.scheme; + target.userinfo = relative.userinfo; + target.host = relative.host; + target.port = relative.port; + target.path = removeDotSegments(relative.path || ""); + target.query = relative.query; + } else { + if (relative.userinfo !== void 0 || relative.host !== void 0 || relative.port !== void 0) { + target.userinfo = relative.userinfo; + target.host = relative.host; + target.port = relative.port; + target.path = removeDotSegments(relative.path || ""); + target.query = relative.query; + } else { + if (!relative.path) { + target.path = base.path; + if (relative.query !== void 0) target.query = relative.query; + else target.query = base.query; + } else { + if (relative.path[0] === "/") target.path = removeDotSegments(relative.path); + else { + if ((base.userinfo !== void 0 || base.host !== void 0 || base.port !== void 0) && !base.path) target.path = "/" + relative.path; + else if (!base.path) target.path = relative.path; + else target.path = base.path.slice(0, base.path.lastIndexOf("/") + 1) + relative.path; + target.path = removeDotSegments(target.path); + } + target.query = relative.query; + } + target.userinfo = base.userinfo; + target.host = base.host; + target.port = base.port; + } + target.scheme = base.scheme; + } + target.fragment = relative.fragment; + return target; + } + /** + * @param {import ('./types/index').URIComponent|string} uriA + * @param {import ('./types/index').URIComponent|string} uriB + * @param {import ('./types/index').Options} options + * @returns {boolean} + */ + function equal(uriA, uriB, options) { + if (typeof uriA === "string") { + uriA = unescape(uriA); + uriA = serialize(normalizeComponentEncoding(parse(uriA, options), true), { + ...options, + skipEscape: true + }); + } else if (typeof uriA === "object") uriA = serialize(normalizeComponentEncoding(uriA, true), { + ...options, + skipEscape: true + }); + if (typeof uriB === "string") { + uriB = unescape(uriB); + uriB = serialize(normalizeComponentEncoding(parse(uriB, options), true), { + ...options, + skipEscape: true + }); + } else if (typeof uriB === "object") uriB = serialize(normalizeComponentEncoding(uriB, true), { + ...options, + skipEscape: true + }); + return uriA.toLowerCase() === uriB.toLowerCase(); + } + /** + * @param {Readonly} cmpts + * @param {import('./types/index').Options} [opts] + * @returns {string} + */ + function serialize(cmpts, opts) { + const component = { + host: cmpts.host, + scheme: cmpts.scheme, + userinfo: cmpts.userinfo, + port: cmpts.port, + path: cmpts.path, + query: cmpts.query, + nid: cmpts.nid, + nss: cmpts.nss, + uuid: cmpts.uuid, + fragment: cmpts.fragment, + reference: cmpts.reference, + resourceName: cmpts.resourceName, + secure: cmpts.secure, + error: "" + }; + const options = Object.assign({}, opts); + const uriTokens = []; + const schemeHandler = getSchemeHandler(options.scheme || component.scheme); + if (schemeHandler && schemeHandler.serialize) schemeHandler.serialize(component, options); + if (component.path !== void 0) if (!options.skipEscape) { + component.path = escape(component.path); + if (component.scheme !== void 0) component.path = component.path.split("%3A").join(":"); + } else component.path = unescape(component.path); + if (options.reference !== "suffix" && component.scheme) uriTokens.push(component.scheme, ":"); + const authority = recomposeAuthority(component); + if (authority !== void 0) { + if (options.reference !== "suffix") uriTokens.push("//"); + uriTokens.push(authority); + if (component.path && component.path[0] !== "/") uriTokens.push("/"); + } + if (component.path !== void 0) { + let s = component.path; + if (!options.absolutePath && (!schemeHandler || !schemeHandler.absolutePath)) s = removeDotSegments(s); + if (authority === void 0 && s[0] === "/" && s[1] === "/") s = "/%2F" + s.slice(2); + uriTokens.push(s); + } + if (component.query !== void 0) uriTokens.push("?", component.query); + if (component.fragment !== void 0) uriTokens.push("#", component.fragment); + return uriTokens.join(""); + } + const URI_PARSE = /^(?:([^#/:?]+):)?(?:\/\/((?:([^#/?@]*)@)?(\[[^#/?\]]+\]|[^#/:?]*)(?::(\d*))?))?([^#?]*)(?:\?([^#]*))?(?:#((?:.|[\n\r])*))?/u; + /** + * @param {string} uri + * @param {import('./types/index').Options} [opts] + * @returns + */ + function parse(uri, opts) { + const options = Object.assign({}, opts); + /** @type {import('./types/index').URIComponent} */ + const parsed = { + scheme: void 0, + userinfo: void 0, + host: "", + port: void 0, + path: "", + query: void 0, + fragment: void 0 + }; + let isIP = false; + if (options.reference === "suffix") if (options.scheme) uri = options.scheme + ":" + uri; + else uri = "//" + uri; + const matches = uri.match(URI_PARSE); + if (matches) { + parsed.scheme = matches[1]; + parsed.userinfo = matches[3]; + parsed.host = matches[4]; + parsed.port = parseInt(matches[5], 10); + parsed.path = matches[6] || ""; + parsed.query = matches[7]; + parsed.fragment = matches[8]; + if (isNaN(parsed.port)) parsed.port = matches[5]; + if (parsed.host) if (isIPv4(parsed.host) === false) { + const ipv6result = normalizeIPv6(parsed.host); + parsed.host = ipv6result.host.toLowerCase(); + isIP = ipv6result.isIPV6; + } else isIP = true; + if (parsed.scheme === void 0 && parsed.userinfo === void 0 && parsed.host === void 0 && parsed.port === void 0 && parsed.query === void 0 && !parsed.path) parsed.reference = "same-document"; + else if (parsed.scheme === void 0) parsed.reference = "relative"; + else if (parsed.fragment === void 0) parsed.reference = "absolute"; + else parsed.reference = "uri"; + if (options.reference && options.reference !== "suffix" && options.reference !== parsed.reference) parsed.error = parsed.error || "URI is not a " + options.reference + " reference."; + const schemeHandler = getSchemeHandler(options.scheme || parsed.scheme); + if (!options.unicodeSupport && (!schemeHandler || !schemeHandler.unicodeSupport)) { + if (parsed.host && (options.domainHost || schemeHandler && schemeHandler.domainHost) && isIP === false && nonSimpleDomain(parsed.host)) try { + parsed.host = URL.domainToASCII(parsed.host.toLowerCase()); + } catch (e) { + parsed.error = parsed.error || "Host's domain name can not be converted to ASCII: " + e; + } + } + if (!schemeHandler || schemeHandler && !schemeHandler.skipNormalize) { + if (uri.indexOf("%") !== -1) { + if (parsed.scheme !== void 0) parsed.scheme = unescape(parsed.scheme); + if (parsed.host !== void 0) parsed.host = unescape(parsed.host); + } + if (parsed.path) parsed.path = escape(unescape(parsed.path)); + if (parsed.fragment) parsed.fragment = encodeURI(decodeURIComponent(parsed.fragment)); + } + if (schemeHandler && schemeHandler.parse) schemeHandler.parse(parsed, options); + } else parsed.error = parsed.error || "URI can not be parsed."; + return parsed; + } + const fastUri = { + SCHEMES, + normalize, + resolve, + resolveComponent, + equal, + serialize, + parse + }; + module.exports = fastUri; + module.exports.default = fastUri; + module.exports.fastUri = fastUri; +})); + +//#endregion +//#region ../../node_modules/.pnpm/ajv@8.18.0/node_modules/ajv/dist/runtime/uri.js +var require_uri = /* @__PURE__ */ __commonJSMin(((exports) => { + Object.defineProperty(exports, "__esModule", { value: true }); + const uri = require_fast_uri(); + uri.code = "require(\"ajv/dist/runtime/uri\").default"; + exports.default = uri; +})); + +//#endregion +//#region ../../node_modules/.pnpm/ajv@8.18.0/node_modules/ajv/dist/core.js +var require_core$3 = /* @__PURE__ */ __commonJSMin(((exports) => { + Object.defineProperty(exports, "__esModule", { value: true }); + exports.CodeGen = exports.Name = exports.nil = exports.stringify = exports.str = exports._ = exports.KeywordCxt = void 0; + var validate_1 = require_validate(); + Object.defineProperty(exports, "KeywordCxt", { + enumerable: true, + get: function() { + return validate_1.KeywordCxt; + } + }); + var codegen_1 = require_codegen(); + Object.defineProperty(exports, "_", { + enumerable: true, + get: function() { + return codegen_1._; + } + }); + Object.defineProperty(exports, "str", { + enumerable: true, + get: function() { + return codegen_1.str; + } + }); + Object.defineProperty(exports, "stringify", { + enumerable: true, + get: function() { + return codegen_1.stringify; + } + }); + Object.defineProperty(exports, "nil", { + enumerable: true, + get: function() { + return codegen_1.nil; + } + }); + Object.defineProperty(exports, "Name", { + enumerable: true, + get: function() { + return codegen_1.Name; + } + }); + Object.defineProperty(exports, "CodeGen", { + enumerable: true, + get: function() { + return codegen_1.CodeGen; + } + }); + const validation_error_1 = require_validation_error(); + const ref_error_1 = require_ref_error(); + const rules_1 = require_rules(); + const compile_1 = require_compile(); + const codegen_2 = require_codegen(); + const resolve_1 = require_resolve(); + const dataType_1 = require_dataType(); + const util_1 = require_util(); + const $dataRefSchema = require_data(); + const uri_1 = require_uri(); + const defaultRegExp = (str, flags) => new RegExp(str, flags); + defaultRegExp.code = "new RegExp"; + const META_IGNORE_OPTIONS = [ + "removeAdditional", + "useDefaults", + "coerceTypes" + ]; + const EXT_SCOPE_NAMES = new Set([ + "validate", + "serialize", + "parse", + "wrapper", + "root", + "schema", + "keyword", + "pattern", + "formats", + "validate$data", + "func", + "obj", + "Error" + ]); + const removedOptions = { + 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." + }; + const deprecatedOptions = { + ignoreKeywordsWithRef: "", + jsPropertySyntax: "", + unicode: "\"minLength\"/\"maxLength\" account for unicode characters by default." + }; + const MAX_EXPRESSION = 200; + function requiredOptions(o) { + var _a, _b, _c, _d, _e, _f, _g, _h, _j, _k, _l, _m, _o, _p, _q, _r, _s, _t, _u, _v, _w, _x, _y, _z, _0; + const s = o.strict; + const _optz = (_a = o.code) === null || _a === void 0 ? void 0 : _a.optimize; + const optimize = _optz === true || _optz === void 0 ? 1 : _optz || 0; + const regExp = (_c = (_b = o.code) === null || _b === void 0 ? void 0 : _b.regExp) !== null && _c !== void 0 ? _c : defaultRegExp; + const uriResolver = (_d = o.uriResolver) !== null && _d !== void 0 ? _d : uri_1.default; + return { + strictSchema: (_f = (_e = o.strictSchema) !== null && _e !== void 0 ? _e : s) !== null && _f !== void 0 ? _f : true, + strictNumbers: (_h = (_g = o.strictNumbers) !== null && _g !== void 0 ? _g : s) !== null && _h !== void 0 ? _h : true, + strictTypes: (_k = (_j = o.strictTypes) !== null && _j !== void 0 ? _j : s) !== null && _k !== void 0 ? _k : "log", + strictTuples: (_m = (_l = o.strictTuples) !== null && _l !== void 0 ? _l : s) !== null && _m !== void 0 ? _m : "log", + strictRequired: (_p = (_o = o.strictRequired) !== null && _o !== void 0 ? _o : s) !== null && _p !== void 0 ? _p : false, + code: o.code ? { + ...o.code, + optimize, + regExp + } : { + optimize, + regExp + }, + loopRequired: (_q = o.loopRequired) !== null && _q !== void 0 ? _q : MAX_EXPRESSION, + loopEnum: (_r = o.loopEnum) !== null && _r !== void 0 ? _r : MAX_EXPRESSION, + meta: (_s = o.meta) !== null && _s !== void 0 ? _s : true, + messages: (_t = o.messages) !== null && _t !== void 0 ? _t : true, + inlineRefs: (_u = o.inlineRefs) !== null && _u !== void 0 ? _u : true, + schemaId: (_v = o.schemaId) !== null && _v !== void 0 ? _v : "$id", + addUsedSchema: (_w = o.addUsedSchema) !== null && _w !== void 0 ? _w : true, + validateSchema: (_x = o.validateSchema) !== null && _x !== void 0 ? _x : true, + validateFormats: (_y = o.validateFormats) !== null && _y !== void 0 ? _y : true, + unicodeRegExp: (_z = o.unicodeRegExp) !== null && _z !== void 0 ? _z : true, + int32range: (_0 = o.int32range) !== null && _0 !== void 0 ? _0 : true, + uriResolver + }; + } + var Ajv = class { + constructor(opts = {}) { + this.schemas = {}; + this.refs = {}; + this.formats = {}; + this._compilations = /* @__PURE__ */ new Set(); + this._loading = {}; + this._cache = /* @__PURE__ */ new Map(); + opts = this.opts = { + ...opts, + ...requiredOptions(opts) + }; + const { es5, lines } = this.opts.code; + this.scope = new codegen_2.ValueScope({ + scope: {}, + prefixes: EXT_SCOPE_NAMES, + es5, + lines + }); + this.logger = getLogger(opts.logger); + const formatOpt = opts.validateFormats; + opts.validateFormats = false; + this.RULES = (0, rules_1.getRules)(); + checkOptions.call(this, removedOptions, opts, "NOT SUPPORTED"); + checkOptions.call(this, deprecatedOptions, opts, "DEPRECATED", "warn"); + this._metaOpts = getMetaSchemaOptions.call(this); + if (opts.formats) addInitialFormats.call(this); + this._addVocabularies(); + this._addDefaultMetaSchema(); + if (opts.keywords) addInitialKeywords.call(this, opts.keywords); + if (typeof opts.meta == "object") this.addMetaSchema(opts.meta); + addInitialSchemas.call(this); + opts.validateFormats = formatOpt; + } + _addVocabularies() { + this.addKeyword("$async"); + } + _addDefaultMetaSchema() { + const { $data, meta, schemaId } = this.opts; + let _dataRefSchema = $dataRefSchema; + if (schemaId === "id") { + _dataRefSchema = { ...$dataRefSchema }; + _dataRefSchema.id = _dataRefSchema.$id; + delete _dataRefSchema.$id; + } + if (meta && $data) this.addMetaSchema(_dataRefSchema, _dataRefSchema[schemaId], false); + } + defaultMeta() { + const { meta, schemaId } = this.opts; + return this.opts.defaultMeta = typeof meta == "object" ? meta[schemaId] || meta : void 0; + } + validate(schemaKeyRef, data) { + let v; + if (typeof schemaKeyRef == "string") { + v = this.getSchema(schemaKeyRef); + if (!v) throw new Error(`no schema with key or ref "${schemaKeyRef}"`); + } else v = this.compile(schemaKeyRef); + const valid = v(data); + if (!("$async" in v)) this.errors = v.errors; + return valid; + } + compile(schema, _meta) { + const sch = this._addSchema(schema, _meta); + return sch.validate || this._compileSchemaEnv(sch); + } + compileAsync(schema, meta) { + if (typeof this.opts.loadSchema != "function") throw new Error("options.loadSchema should be a function"); + const { loadSchema } = this.opts; + return runCompileAsync.call(this, schema, meta); + async function runCompileAsync(_schema, _meta) { + await loadMetaSchema.call(this, _schema.$schema); + const sch = this._addSchema(_schema, _meta); + return sch.validate || _compileAsync.call(this, sch); + } + async function loadMetaSchema($ref) { + if ($ref && !this.getSchema($ref)) await runCompileAsync.call(this, { $ref }, true); + } + async function _compileAsync(sch) { + try { + return this._compileSchemaEnv(sch); + } catch (e) { + if (!(e instanceof ref_error_1.default)) throw e; + checkLoaded.call(this, e); + await loadMissingSchema.call(this, e.missingSchema); + return _compileAsync.call(this, sch); + } + } + function checkLoaded({ missingSchema: ref, missingRef }) { + if (this.refs[ref]) throw new Error(`AnySchema ${ref} is loaded but ${missingRef} cannot be resolved`); + } + async function loadMissingSchema(ref) { + const _schema = await _loadSchema.call(this, ref); + if (!this.refs[ref]) await loadMetaSchema.call(this, _schema.$schema); + if (!this.refs[ref]) this.addSchema(_schema, ref, meta); + } + async function _loadSchema(ref) { + const p = this._loading[ref]; + if (p) return p; + try { + return await (this._loading[ref] = loadSchema(ref)); + } finally { + delete this._loading[ref]; + } + } + } + addSchema(schema, key, _meta, _validateSchema = this.opts.validateSchema) { + if (Array.isArray(schema)) { + for (const sch of schema) this.addSchema(sch, void 0, _meta, _validateSchema); + return this; + } + let id; + if (typeof schema === "object") { + const { schemaId } = this.opts; + id = schema[schemaId]; + if (id !== void 0 && typeof id != "string") throw new Error(`schema ${schemaId} must be string`); + } + key = (0, resolve_1.normalizeId)(key || id); + this._checkUnique(key); + this.schemas[key] = this._addSchema(schema, _meta, key, _validateSchema, true); + return this; + } + addMetaSchema(schema, key, _validateSchema = this.opts.validateSchema) { + this.addSchema(schema, key, true, _validateSchema); + return this; + } + validateSchema(schema, throwOrLogError) { + if (typeof schema == "boolean") return true; + let $schema; + $schema = schema.$schema; + if ($schema !== void 0 && typeof $schema != "string") throw new Error("$schema must be a string"); + $schema = $schema || this.opts.defaultMeta || this.defaultMeta(); + if (!$schema) { + this.logger.warn("meta-schema not available"); + this.errors = null; + return true; + } + const valid = this.validate($schema, schema); + if (!valid && throwOrLogError) { + const message = "schema is invalid: " + this.errorsText(); + if (this.opts.validateSchema === "log") this.logger.error(message); + else throw new Error(message); + } + return valid; + } + getSchema(keyRef) { + let sch; + while (typeof (sch = getSchEnv.call(this, keyRef)) == "string") keyRef = sch; + if (sch === void 0) { + const { schemaId } = this.opts; + const root = new compile_1.SchemaEnv({ + schema: {}, + schemaId + }); + sch = compile_1.resolveSchema.call(this, root, keyRef); + if (!sch) return; + this.refs[keyRef] = sch; + } + return sch.validate || this._compileSchemaEnv(sch); + } + removeSchema(schemaKeyRef) { + if (schemaKeyRef instanceof RegExp) { + this._removeAllSchemas(this.schemas, schemaKeyRef); + this._removeAllSchemas(this.refs, schemaKeyRef); + return this; + } + switch (typeof schemaKeyRef) { + case "undefined": + this._removeAllSchemas(this.schemas); + this._removeAllSchemas(this.refs); + this._cache.clear(); + return this; + case "string": { + const sch = getSchEnv.call(this, schemaKeyRef); + if (typeof sch == "object") this._cache.delete(sch.schema); + delete this.schemas[schemaKeyRef]; + delete this.refs[schemaKeyRef]; + return this; + } + case "object": { + const cacheKey = schemaKeyRef; + this._cache.delete(cacheKey); + let id = schemaKeyRef[this.opts.schemaId]; + if (id) { + id = (0, resolve_1.normalizeId)(id); + delete this.schemas[id]; + delete this.refs[id]; + } + return this; + } + default: throw new Error("ajv.removeSchema: invalid parameter"); + } + } + addVocabulary(definitions) { + for (const def of definitions) this.addKeyword(def); + return this; + } + addKeyword(kwdOrDef, def) { + let keyword; + if (typeof kwdOrDef == "string") { + keyword = kwdOrDef; + if (typeof def == "object") { + this.logger.warn("these parameters are deprecated, see docs for addKeyword"); + def.keyword = keyword; + } + } else if (typeof kwdOrDef == "object" && def === void 0) { + def = kwdOrDef; + keyword = def.keyword; + if (Array.isArray(keyword) && !keyword.length) throw new Error("addKeywords: keyword must be string or non-empty array"); + } else throw new Error("invalid addKeywords parameters"); + checkKeyword.call(this, keyword, def); + if (!def) { + (0, util_1.eachItem)(keyword, (kwd) => addRule.call(this, kwd)); + return this; + } + keywordMetaschema.call(this, def); + const definition = { + ...def, + type: (0, dataType_1.getJSONTypes)(def.type), + schemaType: (0, dataType_1.getJSONTypes)(def.schemaType) + }; + (0, util_1.eachItem)(keyword, definition.type.length === 0 ? (k) => addRule.call(this, k, definition) : (k) => definition.type.forEach((t) => addRule.call(this, k, definition, t))); + return this; + } + getKeyword(keyword) { + const rule = this.RULES.all[keyword]; + return typeof rule == "object" ? rule.definition : !!rule; + } + removeKeyword(keyword) { + const { RULES } = this; + delete RULES.keywords[keyword]; + delete RULES.all[keyword]; + for (const group of RULES.rules) { + const i = group.rules.findIndex((rule) => rule.keyword === keyword); + if (i >= 0) group.rules.splice(i, 1); + } + return this; + } + addFormat(name, format) { + if (typeof format == "string") format = new RegExp(format); + this.formats[name] = format; + return this; + } + errorsText(errors = this.errors, { separator = ", ", dataVar = "data" } = {}) { + if (!errors || errors.length === 0) return "No errors"; + return errors.map((e) => `${dataVar}${e.instancePath} ${e.message}`).reduce((text, msg) => text + separator + msg); + } + $dataMetaSchema(metaSchema, keywordsJsonPointers) { + const rules = this.RULES.all; + metaSchema = JSON.parse(JSON.stringify(metaSchema)); + for (const jsonPointer of keywordsJsonPointers) { + const segments = jsonPointer.split("/").slice(1); + let keywords = metaSchema; + for (const seg of segments) keywords = keywords[seg]; + for (const key in rules) { + const rule = rules[key]; + if (typeof rule != "object") continue; + const { $data } = rule.definition; + const schema = keywords[key]; + if ($data && schema) keywords[key] = schemaOrData(schema); + } + } + return metaSchema; + } + _removeAllSchemas(schemas, regex) { + for (const keyRef in schemas) { + const sch = schemas[keyRef]; + if (!regex || regex.test(keyRef)) { + if (typeof sch == "string") delete schemas[keyRef]; + else if (sch && !sch.meta) { + this._cache.delete(sch.schema); + delete schemas[keyRef]; + } + } + } + } + _addSchema(schema, meta, baseId, validateSchema = this.opts.validateSchema, addSchema = this.opts.addUsedSchema) { + let id; + const { schemaId } = this.opts; + if (typeof schema == "object") id = schema[schemaId]; + else if (this.opts.jtd) throw new Error("schema must be object"); + else if (typeof schema != "boolean") throw new Error("schema must be object or boolean"); + let sch = this._cache.get(schema); + if (sch !== void 0) return sch; + baseId = (0, resolve_1.normalizeId)(id || baseId); + const localRefs = resolve_1.getSchemaRefs.call(this, schema, baseId); + sch = new compile_1.SchemaEnv({ + schema, + schemaId, + meta, + baseId, + localRefs + }); + this._cache.set(sch.schema, sch); + if (addSchema && !baseId.startsWith("#")) { + if (baseId) this._checkUnique(baseId); + this.refs[baseId] = sch; + } + if (validateSchema) this.validateSchema(schema, true); + return sch; + } + _checkUnique(id) { + if (this.schemas[id] || this.refs[id]) throw new Error(`schema with key or id "${id}" already exists`); + } + _compileSchemaEnv(sch) { + if (sch.meta) this._compileMetaSchema(sch); + else compile_1.compileSchema.call(this, sch); + /* istanbul ignore if */ + if (!sch.validate) throw new Error("ajv implementation error"); + return sch.validate; + } + _compileMetaSchema(sch) { + const currentOpts = this.opts; + this.opts = this._metaOpts; + try { + compile_1.compileSchema.call(this, sch); + } finally { + this.opts = currentOpts; + } + } + }; + Ajv.ValidationError = validation_error_1.default; + Ajv.MissingRefError = ref_error_1.default; + exports.default = Ajv; + function checkOptions(checkOpts, options, msg, log = "error") { + for (const key in checkOpts) { + const opt = key; + if (opt in options) this.logger[log](`${msg}: option ${key}. ${checkOpts[opt]}`); + } + } + function getSchEnv(keyRef) { + keyRef = (0, resolve_1.normalizeId)(keyRef); + return this.schemas[keyRef] || this.refs[keyRef]; + } + function addInitialSchemas() { + const optsSchemas = this.opts.schemas; + if (!optsSchemas) return; + if (Array.isArray(optsSchemas)) this.addSchema(optsSchemas); + else for (const key in optsSchemas) this.addSchema(optsSchemas[key], key); + } + function addInitialFormats() { + for (const name in this.opts.formats) { + const format = this.opts.formats[name]; + if (format) this.addFormat(name, format); + } + } + function addInitialKeywords(defs) { + if (Array.isArray(defs)) { + this.addVocabulary(defs); + return; + } + this.logger.warn("keywords option as map is deprecated, pass array"); + for (const keyword in defs) { + const def = defs[keyword]; + if (!def.keyword) def.keyword = keyword; + this.addKeyword(def); + } + } + function getMetaSchemaOptions() { + const metaOpts = { ...this.opts }; + for (const opt of META_IGNORE_OPTIONS) delete metaOpts[opt]; + return metaOpts; + } + const noLogs = { + log() {}, + warn() {}, + error() {} + }; + function getLogger(logger) { + if (logger === false) return noLogs; + if (logger === void 0) return console; + if (logger.log && logger.warn && logger.error) return logger; + throw new Error("logger must implement log, warn and error methods"); + } + const KEYWORD_NAME = /^[a-z_$][a-z0-9_$:-]*$/i; + function checkKeyword(keyword, def) { + const { RULES } = this; + (0, util_1.eachItem)(keyword, (kwd) => { + if (RULES.keywords[kwd]) throw new Error(`Keyword ${kwd} is already defined`); + if (!KEYWORD_NAME.test(kwd)) throw new Error(`Keyword ${kwd} has invalid name`); + }); + if (!def) return; + if (def.$data && !("code" in def || "validate" in def)) throw new Error("$data keyword must have \"code\" or \"validate\" function"); + } + function addRule(keyword, definition, dataType) { + var _a; + const post = definition === null || definition === void 0 ? void 0 : definition.post; + if (dataType && post) throw new Error("keyword with \"post\" flag cannot have \"type\""); + const { RULES } = this; + let ruleGroup = post ? RULES.post : RULES.rules.find(({ type: t }) => t === dataType); + if (!ruleGroup) { + ruleGroup = { + type: dataType, + rules: [] + }; + RULES.rules.push(ruleGroup); + } + RULES.keywords[keyword] = true; + if (!definition) return; + const rule = { + keyword, + definition: { + ...definition, + type: (0, dataType_1.getJSONTypes)(definition.type), + schemaType: (0, dataType_1.getJSONTypes)(definition.schemaType) + } + }; + if (definition.before) addBeforeRule.call(this, ruleGroup, rule, definition.before); + else ruleGroup.rules.push(rule); + RULES.all[keyword] = rule; + (_a = definition.implements) === null || _a === void 0 || _a.forEach((kwd) => this.addKeyword(kwd)); + } + function addBeforeRule(ruleGroup, rule, before) { + const i = ruleGroup.rules.findIndex((_rule) => _rule.keyword === before); + if (i >= 0) ruleGroup.rules.splice(i, 0, rule); + else { + ruleGroup.rules.push(rule); + this.logger.warn(`rule ${before} is not defined`); + } + } + function keywordMetaschema(def) { + let { metaSchema } = def; + if (metaSchema === void 0) return; + if (def.$data && this.opts.$data) metaSchema = schemaOrData(metaSchema); + def.validateSchema = this.compile(metaSchema, true); + } + const $dataRef = { $ref: "https://raw.githubusercontent.com/ajv-validator/ajv/master/lib/refs/data.json#" }; + function schemaOrData(schema) { + return { anyOf: [schema, $dataRef] }; + } +})); + +//#endregion +//#region ../../node_modules/.pnpm/ajv@8.18.0/node_modules/ajv/dist/vocabularies/core/id.js +var require_id = /* @__PURE__ */ __commonJSMin(((exports) => { + Object.defineProperty(exports, "__esModule", { value: true }); + const def = { + keyword: "id", + code() { + throw new Error("NOT SUPPORTED: keyword \"id\", use \"$id\" for schema ID"); + } + }; + exports.default = def; +})); + +//#endregion +//#region ../../node_modules/.pnpm/ajv@8.18.0/node_modules/ajv/dist/vocabularies/core/ref.js +var require_ref = /* @__PURE__ */ __commonJSMin(((exports) => { + Object.defineProperty(exports, "__esModule", { value: true }); + exports.callRef = exports.getValidate = void 0; + const ref_error_1 = require_ref_error(); + const code_1 = require_code(); + const codegen_1 = require_codegen(); + const names_1 = require_names(); + const compile_1 = require_compile(); + const util_1 = require_util(); + const def = { + keyword: "$ref", + schemaType: "string", + code(cxt) { + const { gen, schema: $ref, it } = cxt; + const { baseId, schemaEnv: env, validateName, opts, self } = it; + const { root } = env; + if (($ref === "#" || $ref === "#/") && baseId === root.baseId) return callRootRef(); + const schOrEnv = compile_1.resolveRef.call(self, root, baseId, $ref); + if (schOrEnv === void 0) throw new ref_error_1.default(it.opts.uriResolver, baseId, $ref); + if (schOrEnv instanceof compile_1.SchemaEnv) return callValidate(schOrEnv); + return inlineRefSchema(schOrEnv); + function callRootRef() { + if (env === root) return callRef(cxt, validateName, env, env.$async); + const rootName = gen.scopeValue("root", { ref: root }); + return callRef(cxt, (0, codegen_1._)`${rootName}.validate`, root, root.$async); + } + function callValidate(sch) { + callRef(cxt, getValidate(cxt, sch), sch, sch.$async); + } + function inlineRefSchema(sch) { + const schName = gen.scopeValue("schema", opts.code.source === true ? { + ref: sch, + code: (0, codegen_1.stringify)(sch) + } : { ref: sch }); + const valid = gen.name("valid"); + const schCxt = cxt.subschema({ + schema: sch, + dataTypes: [], + schemaPath: codegen_1.nil, + topSchemaRef: schName, + errSchemaPath: $ref + }, valid); + cxt.mergeEvaluated(schCxt); + cxt.ok(valid); + } + } + }; + function getValidate(cxt, sch) { + const { gen } = cxt; + return sch.validate ? gen.scopeValue("validate", { ref: sch.validate }) : (0, codegen_1._)`${gen.scopeValue("wrapper", { ref: sch })}.validate`; + } + exports.getValidate = getValidate; + function callRef(cxt, v, sch, $async) { + const { gen, it } = cxt; + const { allErrors, schemaEnv: env, opts } = it; + const passCxt = opts.passContext ? names_1.default.this : codegen_1.nil; + if ($async) callAsyncRef(); + else callSyncRef(); + function callAsyncRef() { + if (!env.$async) throw new Error("async schema referenced by sync schema"); + const valid = gen.let("valid"); + gen.try(() => { + gen.code((0, codegen_1._)`await ${(0, code_1.callValidateCode)(cxt, v, passCxt)}`); + addEvaluatedFrom(v); + if (!allErrors) gen.assign(valid, true); + }, (e) => { + gen.if((0, codegen_1._)`!(${e} instanceof ${it.ValidationError})`, () => gen.throw(e)); + addErrorsFrom(e); + if (!allErrors) gen.assign(valid, false); + }); + cxt.ok(valid); + } + function callSyncRef() { + cxt.result((0, code_1.callValidateCode)(cxt, v, passCxt), () => addEvaluatedFrom(v), () => addErrorsFrom(v)); + } + function addErrorsFrom(source) { + const errs = (0, codegen_1._)`${source}.errors`; + gen.assign(names_1.default.vErrors, (0, codegen_1._)`${names_1.default.vErrors} === null ? ${errs} : ${names_1.default.vErrors}.concat(${errs})`); + gen.assign(names_1.default.errors, (0, codegen_1._)`${names_1.default.vErrors}.length`); + } + function addEvaluatedFrom(source) { + var _a; + if (!it.opts.unevaluated) return; + const schEvaluated = (_a = sch === null || sch === void 0 ? void 0 : sch.validate) === null || _a === void 0 ? void 0 : _a.evaluated; + if (it.props !== true) if (schEvaluated && !schEvaluated.dynamicProps) { + if (schEvaluated.props !== void 0) it.props = util_1.mergeEvaluated.props(gen, schEvaluated.props, it.props); + } else { + const props = gen.var("props", (0, codegen_1._)`${source}.evaluated.props`); + it.props = util_1.mergeEvaluated.props(gen, props, it.props, codegen_1.Name); + } + if (it.items !== true) if (schEvaluated && !schEvaluated.dynamicItems) { + if (schEvaluated.items !== void 0) it.items = util_1.mergeEvaluated.items(gen, schEvaluated.items, it.items); + } else { + const items = gen.var("items", (0, codegen_1._)`${source}.evaluated.items`); + it.items = util_1.mergeEvaluated.items(gen, items, it.items, codegen_1.Name); + } + } + } + exports.callRef = callRef; + exports.default = def; +})); + +//#endregion +//#region ../../node_modules/.pnpm/ajv@8.18.0/node_modules/ajv/dist/vocabularies/core/index.js +var require_core$2 = /* @__PURE__ */ __commonJSMin(((exports) => { + Object.defineProperty(exports, "__esModule", { value: true }); + const id_1 = require_id(); + const ref_1 = require_ref(); + const core = [ + "$schema", + "$id", + "$defs", + "$vocabulary", + { keyword: "$comment" }, + "definitions", + id_1.default, + ref_1.default + ]; + exports.default = core; +})); + +//#endregion +//#region ../../node_modules/.pnpm/ajv@8.18.0/node_modules/ajv/dist/vocabularies/validation/limitNumber.js +var require_limitNumber = /* @__PURE__ */ __commonJSMin(((exports) => { + Object.defineProperty(exports, "__esModule", { value: true }); + const codegen_1 = require_codegen(); + const ops = codegen_1.operators; + const KWDs = { + maximum: { + okStr: "<=", + ok: ops.LTE, + fail: ops.GT + }, + minimum: { + okStr: ">=", + ok: ops.GTE, + fail: ops.LT + }, + exclusiveMaximum: { + okStr: "<", + ok: ops.LT, + fail: ops.GTE + }, + exclusiveMinimum: { + okStr: ">", + ok: ops.GT, + fail: ops.LTE + } + }; + const def = { + keyword: Object.keys(KWDs), + type: "number", + schemaType: "number", + $data: true, + error: { + message: ({ keyword, schemaCode }) => (0, codegen_1.str)`must be ${KWDs[keyword].okStr} ${schemaCode}`, + params: ({ keyword, schemaCode }) => (0, codegen_1._)`{comparison: ${KWDs[keyword].okStr}, limit: ${schemaCode}}` + }, + code(cxt) { + const { keyword, data, schemaCode } = cxt; + cxt.fail$data((0, codegen_1._)`${data} ${KWDs[keyword].fail} ${schemaCode} || isNaN(${data})`); + } + }; + exports.default = def; +})); + +//#endregion +//#region ../../node_modules/.pnpm/ajv@8.18.0/node_modules/ajv/dist/vocabularies/validation/multipleOf.js +var require_multipleOf = /* @__PURE__ */ __commonJSMin(((exports) => { + Object.defineProperty(exports, "__esModule", { value: true }); + const codegen_1 = require_codegen(); + const def = { + keyword: "multipleOf", + type: "number", + schemaType: "number", + $data: true, + error: { + message: ({ schemaCode }) => (0, codegen_1.str)`must be multiple of ${schemaCode}`, + params: ({ schemaCode }) => (0, codegen_1._)`{multipleOf: ${schemaCode}}` + }, + code(cxt) { + const { gen, data, schemaCode, it } = cxt; + const prec = it.opts.multipleOfPrecision; + const res = gen.let("res"); + const invalid = prec ? (0, codegen_1._)`Math.abs(Math.round(${res}) - ${res}) > 1e-${prec}` : (0, codegen_1._)`${res} !== parseInt(${res})`; + cxt.fail$data((0, codegen_1._)`(${schemaCode} === 0 || (${res} = ${data}/${schemaCode}, ${invalid}))`); + } + }; + exports.default = def; +})); + +//#endregion +//#region ../../node_modules/.pnpm/ajv@8.18.0/node_modules/ajv/dist/runtime/ucs2length.js +var require_ucs2length = /* @__PURE__ */ __commonJSMin(((exports) => { + Object.defineProperty(exports, "__esModule", { value: true }); + function ucs2length(str) { + const len = str.length; + let length = 0; + let pos = 0; + let value; + while (pos < len) { + length++; + value = str.charCodeAt(pos++); + if (value >= 55296 && value <= 56319 && pos < len) { + value = str.charCodeAt(pos); + if ((value & 64512) === 56320) pos++; + } + } + return length; + } + exports.default = ucs2length; + ucs2length.code = "require(\"ajv/dist/runtime/ucs2length\").default"; +})); + +//#endregion +//#region ../../node_modules/.pnpm/ajv@8.18.0/node_modules/ajv/dist/vocabularies/validation/limitLength.js +var require_limitLength = /* @__PURE__ */ __commonJSMin(((exports) => { + Object.defineProperty(exports, "__esModule", { value: true }); + const codegen_1 = require_codegen(); + const util_1 = require_util(); + const ucs2length_1 = require_ucs2length(); + const def = { + keyword: ["maxLength", "minLength"], + type: "string", + schemaType: "number", + $data: true, + error: { + message({ keyword, schemaCode }) { + const comp = keyword === "maxLength" ? "more" : "fewer"; + return (0, codegen_1.str)`must NOT have ${comp} than ${schemaCode} characters`; + }, + params: ({ schemaCode }) => (0, codegen_1._)`{limit: ${schemaCode}}` + }, + code(cxt) { + const { keyword, data, schemaCode, it } = cxt; + const op = keyword === "maxLength" ? codegen_1.operators.GT : codegen_1.operators.LT; + const len = it.opts.unicode === false ? (0, codegen_1._)`${data}.length` : (0, codegen_1._)`${(0, util_1.useFunc)(cxt.gen, ucs2length_1.default)}(${data})`; + cxt.fail$data((0, codegen_1._)`${len} ${op} ${schemaCode}`); + } + }; + exports.default = def; +})); + +//#endregion +//#region ../../node_modules/.pnpm/ajv@8.18.0/node_modules/ajv/dist/vocabularies/validation/pattern.js +var require_pattern = /* @__PURE__ */ __commonJSMin(((exports) => { + Object.defineProperty(exports, "__esModule", { value: true }); + const code_1 = require_code(); + const util_1 = require_util(); + const codegen_1 = require_codegen(); + const def = { + keyword: "pattern", + type: "string", + schemaType: "string", + $data: true, + error: { + message: ({ schemaCode }) => (0, codegen_1.str)`must match pattern "${schemaCode}"`, + params: ({ schemaCode }) => (0, codegen_1._)`{pattern: ${schemaCode}}` + }, + code(cxt) { + const { gen, data, $data, schema, schemaCode, it } = cxt; + const u = it.opts.unicodeRegExp ? "u" : ""; + if ($data) { + const { regExp } = it.opts.code; + const regExpCode = regExp.code === "new RegExp" ? (0, codegen_1._)`new RegExp` : (0, util_1.useFunc)(gen, regExp); + const valid = gen.let("valid"); + gen.try(() => gen.assign(valid, (0, codegen_1._)`${regExpCode}(${schemaCode}, ${u}).test(${data})`), () => gen.assign(valid, false)); + cxt.fail$data((0, codegen_1._)`!${valid}`); + } else { + const regExp = (0, code_1.usePattern)(cxt, schema); + cxt.fail$data((0, codegen_1._)`!${regExp}.test(${data})`); + } + } + }; + exports.default = def; +})); + +//#endregion +//#region ../../node_modules/.pnpm/ajv@8.18.0/node_modules/ajv/dist/vocabularies/validation/limitProperties.js +var require_limitProperties = /* @__PURE__ */ __commonJSMin(((exports) => { + Object.defineProperty(exports, "__esModule", { value: true }); + const codegen_1 = require_codegen(); + const def = { + keyword: ["maxProperties", "minProperties"], + type: "object", + schemaType: "number", + $data: true, + error: { + message({ keyword, schemaCode }) { + const comp = keyword === "maxProperties" ? "more" : "fewer"; + return (0, codegen_1.str)`must NOT have ${comp} than ${schemaCode} properties`; + }, + params: ({ schemaCode }) => (0, codegen_1._)`{limit: ${schemaCode}}` + }, + code(cxt) { + const { keyword, data, schemaCode } = cxt; + const op = keyword === "maxProperties" ? codegen_1.operators.GT : codegen_1.operators.LT; + cxt.fail$data((0, codegen_1._)`Object.keys(${data}).length ${op} ${schemaCode}`); + } + }; + exports.default = def; +})); + +//#endregion +//#region ../../node_modules/.pnpm/ajv@8.18.0/node_modules/ajv/dist/vocabularies/validation/required.js +var require_required = /* @__PURE__ */ __commonJSMin(((exports) => { + Object.defineProperty(exports, "__esModule", { value: true }); + const code_1 = require_code(); + const codegen_1 = require_codegen(); + const util_1 = require_util(); + const def = { + keyword: "required", + type: "object", + schemaType: "array", + $data: true, + error: { + message: ({ params: { missingProperty } }) => (0, codegen_1.str)`must have required property '${missingProperty}'`, + params: ({ params: { missingProperty } }) => (0, codegen_1._)`{missingProperty: ${missingProperty}}` + }, + code(cxt) { + const { gen, schema, schemaCode, data, $data, it } = cxt; + const { opts } = it; + if (!$data && schema.length === 0) return; + const useLoop = schema.length >= opts.loopRequired; + if (it.allErrors) allErrorsMode(); + else exitOnErrorMode(); + if (opts.strictRequired) { + const props = cxt.parentSchema.properties; + const { definedProperties } = cxt.it; + for (const requiredKey of schema) if ((props === null || props === void 0 ? void 0 : props[requiredKey]) === void 0 && !definedProperties.has(requiredKey)) { + const msg = `required property "${requiredKey}" is not defined at "${it.schemaEnv.baseId + it.errSchemaPath}" (strictRequired)`; + (0, util_1.checkStrictMode)(it, msg, it.opts.strictRequired); + } + } + function allErrorsMode() { + if (useLoop || $data) cxt.block$data(codegen_1.nil, loopAllRequired); + else for (const prop of schema) (0, code_1.checkReportMissingProp)(cxt, prop); + } + function exitOnErrorMode() { + const missing = gen.let("missing"); + if (useLoop || $data) { + const valid = gen.let("valid", true); + cxt.block$data(valid, () => loopUntilMissing(missing, valid)); + cxt.ok(valid); + } else { + gen.if((0, code_1.checkMissingProp)(cxt, schema, missing)); + (0, code_1.reportMissingProp)(cxt, missing); + gen.else(); + } + } + function loopAllRequired() { + gen.forOf("prop", schemaCode, (prop) => { + cxt.setParams({ missingProperty: prop }); + gen.if((0, code_1.noPropertyInData)(gen, data, prop, opts.ownProperties), () => cxt.error()); + }); + } + function loopUntilMissing(missing, valid) { + cxt.setParams({ missingProperty: missing }); + gen.forOf(missing, schemaCode, () => { + gen.assign(valid, (0, code_1.propertyInData)(gen, data, missing, opts.ownProperties)); + gen.if((0, codegen_1.not)(valid), () => { + cxt.error(); + gen.break(); + }); + }, codegen_1.nil); + } + } + }; + exports.default = def; +})); + +//#endregion +//#region ../../node_modules/.pnpm/ajv@8.18.0/node_modules/ajv/dist/vocabularies/validation/limitItems.js +var require_limitItems = /* @__PURE__ */ __commonJSMin(((exports) => { + Object.defineProperty(exports, "__esModule", { value: true }); + const codegen_1 = require_codegen(); + const def = { + keyword: ["maxItems", "minItems"], + type: "array", + schemaType: "number", + $data: true, + error: { + message({ keyword, schemaCode }) { + const comp = keyword === "maxItems" ? "more" : "fewer"; + return (0, codegen_1.str)`must NOT have ${comp} than ${schemaCode} items`; + }, + params: ({ schemaCode }) => (0, codegen_1._)`{limit: ${schemaCode}}` + }, + code(cxt) { + const { keyword, data, schemaCode } = cxt; + const op = keyword === "maxItems" ? codegen_1.operators.GT : codegen_1.operators.LT; + cxt.fail$data((0, codegen_1._)`${data}.length ${op} ${schemaCode}`); + } + }; + exports.default = def; +})); + +//#endregion +//#region ../../node_modules/.pnpm/ajv@8.18.0/node_modules/ajv/dist/runtime/equal.js +var require_equal = /* @__PURE__ */ __commonJSMin(((exports) => { + Object.defineProperty(exports, "__esModule", { value: true }); + const equal = require_fast_deep_equal(); + equal.code = "require(\"ajv/dist/runtime/equal\").default"; + exports.default = equal; +})); + +//#endregion +//#region ../../node_modules/.pnpm/ajv@8.18.0/node_modules/ajv/dist/vocabularies/validation/uniqueItems.js +var require_uniqueItems = /* @__PURE__ */ __commonJSMin(((exports) => { + Object.defineProperty(exports, "__esModule", { value: true }); + const dataType_1 = require_dataType(); + const codegen_1 = require_codegen(); + const util_1 = require_util(); + const equal_1 = require_equal(); + const def = { + keyword: "uniqueItems", + type: "array", + schemaType: "boolean", + $data: true, + error: { + message: ({ params: { i, j } }) => (0, codegen_1.str)`must NOT have duplicate items (items ## ${j} and ${i} are identical)`, + params: ({ params: { i, j } }) => (0, codegen_1._)`{i: ${i}, j: ${j}}` + }, + code(cxt) { + const { gen, data, $data, schema, parentSchema, schemaCode, it } = cxt; + if (!$data && !schema) return; + const valid = gen.let("valid"); + const itemTypes = parentSchema.items ? (0, dataType_1.getSchemaTypes)(parentSchema.items) : []; + cxt.block$data(valid, validateUniqueItems, (0, codegen_1._)`${schemaCode} === false`); + cxt.ok(valid); + function validateUniqueItems() { + const i = gen.let("i", (0, codegen_1._)`${data}.length`); + const j = gen.let("j"); + cxt.setParams({ + i, + j + }); + gen.assign(valid, true); + gen.if((0, codegen_1._)`${i} > 1`, () => (canOptimize() ? loopN : loopN2)(i, j)); + } + function canOptimize() { + return itemTypes.length > 0 && !itemTypes.some((t) => t === "object" || t === "array"); + } + function loopN(i, j) { + const item = gen.name("item"); + const wrongType = (0, dataType_1.checkDataTypes)(itemTypes, item, it.opts.strictNumbers, dataType_1.DataType.Wrong); + const indices = gen.const("indices", (0, codegen_1._)`{}`); + gen.for((0, codegen_1._)`;${i}--;`, () => { + gen.let(item, (0, codegen_1._)`${data}[${i}]`); + gen.if(wrongType, (0, codegen_1._)`continue`); + if (itemTypes.length > 1) gen.if((0, codegen_1._)`typeof ${item} == "string"`, (0, codegen_1._)`${item} += "_"`); + gen.if((0, codegen_1._)`typeof ${indices}[${item}] == "number"`, () => { + gen.assign(j, (0, codegen_1._)`${indices}[${item}]`); + cxt.error(); + gen.assign(valid, false).break(); + }).code((0, codegen_1._)`${indices}[${item}] = ${i}`); + }); + } + function loopN2(i, j) { + const eql = (0, util_1.useFunc)(gen, equal_1.default); + const outer = gen.name("outer"); + gen.label(outer).for((0, codegen_1._)`;${i}--;`, () => gen.for((0, codegen_1._)`${j} = ${i}; ${j}--;`, () => gen.if((0, codegen_1._)`${eql}(${data}[${i}], ${data}[${j}])`, () => { + cxt.error(); + gen.assign(valid, false).break(outer); + }))); + } + } + }; + exports.default = def; +})); + +//#endregion +//#region ../../node_modules/.pnpm/ajv@8.18.0/node_modules/ajv/dist/vocabularies/validation/const.js +var require_const = /* @__PURE__ */ __commonJSMin(((exports) => { + Object.defineProperty(exports, "__esModule", { value: true }); + const codegen_1 = require_codegen(); + const util_1 = require_util(); + const equal_1 = require_equal(); + const def = { + keyword: "const", + $data: true, + error: { + message: "must be equal to constant", + params: ({ schemaCode }) => (0, codegen_1._)`{allowedValue: ${schemaCode}}` + }, + code(cxt) { + const { gen, data, $data, schemaCode, schema } = cxt; + if ($data || schema && typeof schema == "object") cxt.fail$data((0, codegen_1._)`!${(0, util_1.useFunc)(gen, equal_1.default)}(${data}, ${schemaCode})`); + else cxt.fail((0, codegen_1._)`${schema} !== ${data}`); + } + }; + exports.default = def; +})); + +//#endregion +//#region ../../node_modules/.pnpm/ajv@8.18.0/node_modules/ajv/dist/vocabularies/validation/enum.js +var require_enum = /* @__PURE__ */ __commonJSMin(((exports) => { + Object.defineProperty(exports, "__esModule", { value: true }); + const codegen_1 = require_codegen(); + const util_1 = require_util(); + const equal_1 = require_equal(); + const def = { + keyword: "enum", + schemaType: "array", + $data: true, + error: { + message: "must be equal to one of the allowed values", + params: ({ schemaCode }) => (0, codegen_1._)`{allowedValues: ${schemaCode}}` + }, + code(cxt) { + const { gen, data, $data, schema, schemaCode, it } = cxt; + if (!$data && schema.length === 0) throw new Error("enum must have non-empty array"); + const useLoop = schema.length >= it.opts.loopEnum; + let eql; + const getEql = () => eql !== null && eql !== void 0 ? eql : eql = (0, util_1.useFunc)(gen, equal_1.default); + let valid; + if (useLoop || $data) { + valid = gen.let("valid"); + cxt.block$data(valid, loopEnum); + } else { + /* istanbul ignore if */ + if (!Array.isArray(schema)) throw new Error("ajv implementation error"); + const vSchema = gen.const("vSchema", schemaCode); + valid = (0, codegen_1.or)(...schema.map((_x, i) => equalCode(vSchema, i))); + } + cxt.pass(valid); + function loopEnum() { + gen.assign(valid, false); + gen.forOf("v", schemaCode, (v) => gen.if((0, codegen_1._)`${getEql()}(${data}, ${v})`, () => gen.assign(valid, true).break())); + } + function equalCode(vSchema, i) { + const sch = schema[i]; + return typeof sch === "object" && sch !== null ? (0, codegen_1._)`${getEql()}(${data}, ${vSchema}[${i}])` : (0, codegen_1._)`${data} === ${sch}`; + } + } + }; + exports.default = def; +})); + +//#endregion +//#region ../../node_modules/.pnpm/ajv@8.18.0/node_modules/ajv/dist/vocabularies/validation/index.js +var require_validation$2 = /* @__PURE__ */ __commonJSMin(((exports) => { + Object.defineProperty(exports, "__esModule", { value: true }); + const limitNumber_1 = require_limitNumber(); + const multipleOf_1 = require_multipleOf(); + const limitLength_1 = require_limitLength(); + const pattern_1 = require_pattern(); + const limitProperties_1 = require_limitProperties(); + const required_1 = require_required(); + const limitItems_1 = require_limitItems(); + const uniqueItems_1 = require_uniqueItems(); + const const_1 = require_const(); + const enum_1 = require_enum(); + const validation = [ + limitNumber_1.default, + multipleOf_1.default, + limitLength_1.default, + pattern_1.default, + limitProperties_1.default, + required_1.default, + limitItems_1.default, + uniqueItems_1.default, + { + keyword: "type", + schemaType: ["string", "array"] + }, + { + keyword: "nullable", + schemaType: "boolean" + }, + const_1.default, + enum_1.default + ]; + exports.default = validation; +})); + +//#endregion +//#region ../../node_modules/.pnpm/ajv@8.18.0/node_modules/ajv/dist/vocabularies/applicator/additionalItems.js +var require_additionalItems = /* @__PURE__ */ __commonJSMin(((exports) => { + Object.defineProperty(exports, "__esModule", { value: true }); + exports.validateAdditionalItems = void 0; + const codegen_1 = require_codegen(); + const util_1 = require_util(); + const def = { + keyword: "additionalItems", + type: "array", + schemaType: ["boolean", "object"], + before: "uniqueItems", + error: { + message: ({ params: { len } }) => (0, codegen_1.str)`must NOT have more than ${len} items`, + params: ({ params: { len } }) => (0, codegen_1._)`{limit: ${len}}` + }, + code(cxt) { + const { parentSchema, it } = cxt; + const { items } = parentSchema; + if (!Array.isArray(items)) { + (0, util_1.checkStrictMode)(it, "\"additionalItems\" is ignored when \"items\" is not an array of schemas"); + return; + } + validateAdditionalItems(cxt, items); + } + }; + function validateAdditionalItems(cxt, items) { + const { gen, schema, data, keyword, it } = cxt; + it.items = true; + const len = gen.const("len", (0, codegen_1._)`${data}.length`); + if (schema === false) { + cxt.setParams({ len: items.length }); + cxt.pass((0, codegen_1._)`${len} <= ${items.length}`); + } else if (typeof schema == "object" && !(0, util_1.alwaysValidSchema)(it, schema)) { + const valid = gen.var("valid", (0, codegen_1._)`${len} <= ${items.length}`); + gen.if((0, codegen_1.not)(valid), () => validateItems(valid)); + cxt.ok(valid); + } + function validateItems(valid) { + gen.forRange("i", items.length, len, (i) => { + cxt.subschema({ + keyword, + dataProp: i, + dataPropType: util_1.Type.Num + }, valid); + if (!it.allErrors) gen.if((0, codegen_1.not)(valid), () => gen.break()); + }); + } + } + exports.validateAdditionalItems = validateAdditionalItems; + exports.default = def; +})); + +//#endregion +//#region ../../node_modules/.pnpm/ajv@8.18.0/node_modules/ajv/dist/vocabularies/applicator/items.js +var require_items = /* @__PURE__ */ __commonJSMin(((exports) => { + Object.defineProperty(exports, "__esModule", { value: true }); + exports.validateTuple = void 0; + const codegen_1 = require_codegen(); + const util_1 = require_util(); + const code_1 = require_code(); + const def = { + keyword: "items", + type: "array", + schemaType: [ + "object", + "array", + "boolean" + ], + before: "uniqueItems", + code(cxt) { + const { schema, it } = cxt; + if (Array.isArray(schema)) return validateTuple(cxt, "additionalItems", schema); + it.items = true; + if ((0, util_1.alwaysValidSchema)(it, schema)) return; + cxt.ok((0, code_1.validateArray)(cxt)); + } + }; + function validateTuple(cxt, extraItems, schArr = cxt.schema) { + const { gen, parentSchema, data, keyword, it } = cxt; + checkStrictTuple(parentSchema); + if (it.opts.unevaluated && schArr.length && it.items !== true) it.items = util_1.mergeEvaluated.items(gen, schArr.length, it.items); + const valid = gen.name("valid"); + const len = gen.const("len", (0, codegen_1._)`${data}.length`); + schArr.forEach((sch, i) => { + if ((0, util_1.alwaysValidSchema)(it, sch)) return; + gen.if((0, codegen_1._)`${len} > ${i}`, () => cxt.subschema({ + keyword, + schemaProp: i, + dataProp: i + }, valid)); + cxt.ok(valid); + }); + function checkStrictTuple(sch) { + const { opts, errSchemaPath } = it; + const l = schArr.length; + const fullTuple = l === sch.minItems && (l === sch.maxItems || sch[extraItems] === false); + if (opts.strictTuples && !fullTuple) { + const msg = `"${keyword}" is ${l}-tuple, but minItems or maxItems/${extraItems} are not specified or different at path "${errSchemaPath}"`; + (0, util_1.checkStrictMode)(it, msg, opts.strictTuples); + } + } + } + exports.validateTuple = validateTuple; + exports.default = def; +})); + +//#endregion +//#region ../../node_modules/.pnpm/ajv@8.18.0/node_modules/ajv/dist/vocabularies/applicator/prefixItems.js +var require_prefixItems = /* @__PURE__ */ __commonJSMin(((exports) => { + Object.defineProperty(exports, "__esModule", { value: true }); + const items_1 = require_items(); + const def = { + keyword: "prefixItems", + type: "array", + schemaType: ["array"], + before: "uniqueItems", + code: (cxt) => (0, items_1.validateTuple)(cxt, "items") + }; + exports.default = def; +})); + +//#endregion +//#region ../../node_modules/.pnpm/ajv@8.18.0/node_modules/ajv/dist/vocabularies/applicator/items2020.js +var require_items2020 = /* @__PURE__ */ __commonJSMin(((exports) => { + Object.defineProperty(exports, "__esModule", { value: true }); + const codegen_1 = require_codegen(); + const util_1 = require_util(); + const code_1 = require_code(); + const additionalItems_1 = require_additionalItems(); + const def = { + keyword: "items", + type: "array", + schemaType: ["object", "boolean"], + before: "uniqueItems", + error: { + message: ({ params: { len } }) => (0, codegen_1.str)`must NOT have more than ${len} items`, + params: ({ params: { len } }) => (0, codegen_1._)`{limit: ${len}}` + }, + code(cxt) { + const { schema, parentSchema, it } = cxt; + const { prefixItems } = parentSchema; + it.items = true; + if ((0, util_1.alwaysValidSchema)(it, schema)) return; + if (prefixItems) (0, additionalItems_1.validateAdditionalItems)(cxt, prefixItems); + else cxt.ok((0, code_1.validateArray)(cxt)); + } + }; + exports.default = def; +})); + +//#endregion +//#region ../../node_modules/.pnpm/ajv@8.18.0/node_modules/ajv/dist/vocabularies/applicator/contains.js +var require_contains = /* @__PURE__ */ __commonJSMin(((exports) => { + Object.defineProperty(exports, "__esModule", { value: true }); + const codegen_1 = require_codegen(); + const util_1 = require_util(); + const def = { + keyword: "contains", + type: "array", + schemaType: ["object", "boolean"], + before: "uniqueItems", + trackErrors: true, + error: { + message: ({ params: { min, max } }) => max === void 0 ? (0, codegen_1.str)`must contain at least ${min} valid item(s)` : (0, codegen_1.str)`must contain at least ${min} and no more than ${max} valid item(s)`, + params: ({ params: { min, max } }) => max === void 0 ? (0, codegen_1._)`{minContains: ${min}}` : (0, codegen_1._)`{minContains: ${min}, maxContains: ${max}}` + }, + code(cxt) { + const { gen, schema, parentSchema, data, it } = cxt; + let min; + let max; + const { minContains, maxContains } = parentSchema; + if (it.opts.next) { + min = minContains === void 0 ? 1 : minContains; + max = maxContains; + } else min = 1; + const len = gen.const("len", (0, codegen_1._)`${data}.length`); + cxt.setParams({ + min, + max + }); + if (max === void 0 && min === 0) { + (0, util_1.checkStrictMode)(it, `"minContains" == 0 without "maxContains": "contains" keyword ignored`); + return; + } + if (max !== void 0 && min > max) { + (0, util_1.checkStrictMode)(it, `"minContains" > "maxContains" is always invalid`); + cxt.fail(); + return; + } + if ((0, util_1.alwaysValidSchema)(it, schema)) { + let cond = (0, codegen_1._)`${len} >= ${min}`; + if (max !== void 0) cond = (0, codegen_1._)`${cond} && ${len} <= ${max}`; + cxt.pass(cond); + return; + } + it.items = true; + const valid = gen.name("valid"); + if (max === void 0 && min === 1) validateItems(valid, () => gen.if(valid, () => gen.break())); + else if (min === 0) { + gen.let(valid, true); + if (max !== void 0) gen.if((0, codegen_1._)`${data}.length > 0`, validateItemsWithCount); + } else { + gen.let(valid, false); + validateItemsWithCount(); + } + cxt.result(valid, () => cxt.reset()); + function validateItemsWithCount() { + const schValid = gen.name("_valid"); + const count = gen.let("count", 0); + validateItems(schValid, () => gen.if(schValid, () => checkLimits(count))); + } + function validateItems(_valid, block) { + gen.forRange("i", 0, len, (i) => { + cxt.subschema({ + keyword: "contains", + dataProp: i, + dataPropType: util_1.Type.Num, + compositeRule: true + }, _valid); + block(); + }); + } + function checkLimits(count) { + gen.code((0, codegen_1._)`${count}++`); + if (max === void 0) gen.if((0, codegen_1._)`${count} >= ${min}`, () => gen.assign(valid, true).break()); + else { + gen.if((0, codegen_1._)`${count} > ${max}`, () => gen.assign(valid, false).break()); + if (min === 1) gen.assign(valid, true); + else gen.if((0, codegen_1._)`${count} >= ${min}`, () => gen.assign(valid, true)); + } + } + } + }; + exports.default = def; +})); + +//#endregion +//#region ../../node_modules/.pnpm/ajv@8.18.0/node_modules/ajv/dist/vocabularies/applicator/dependencies.js +var require_dependencies = /* @__PURE__ */ __commonJSMin(((exports) => { + Object.defineProperty(exports, "__esModule", { value: true }); + exports.validateSchemaDeps = exports.validatePropertyDeps = exports.error = void 0; + const codegen_1 = require_codegen(); + const util_1 = require_util(); + const code_1 = require_code(); + exports.error = { + message: ({ params: { property, depsCount, deps } }) => { + const property_ies = depsCount === 1 ? "property" : "properties"; + return (0, codegen_1.str)`must have ${property_ies} ${deps} when property ${property} is present`; + }, + params: ({ params: { property, depsCount, deps, missingProperty } }) => (0, codegen_1._)`{property: ${property}, + missingProperty: ${missingProperty}, + depsCount: ${depsCount}, + deps: ${deps}}` + }; + const def = { + keyword: "dependencies", + type: "object", + schemaType: "object", + error: exports.error, + code(cxt) { + const [propDeps, schDeps] = splitDependencies(cxt); + validatePropertyDeps(cxt, propDeps); + validateSchemaDeps(cxt, schDeps); + } + }; + function splitDependencies({ schema }) { + const propertyDeps = {}; + const schemaDeps = {}; + for (const key in schema) { + if (key === "__proto__") continue; + const deps = Array.isArray(schema[key]) ? propertyDeps : schemaDeps; + deps[key] = schema[key]; + } + return [propertyDeps, schemaDeps]; + } + function validatePropertyDeps(cxt, propertyDeps = cxt.schema) { + const { gen, data, it } = cxt; + if (Object.keys(propertyDeps).length === 0) return; + const missing = gen.let("missing"); + for (const prop in propertyDeps) { + const deps = propertyDeps[prop]; + if (deps.length === 0) continue; + const hasProperty = (0, code_1.propertyInData)(gen, data, prop, it.opts.ownProperties); + cxt.setParams({ + property: prop, + depsCount: deps.length, + deps: deps.join(", ") + }); + if (it.allErrors) gen.if(hasProperty, () => { + for (const depProp of deps) (0, code_1.checkReportMissingProp)(cxt, depProp); + }); + else { + gen.if((0, codegen_1._)`${hasProperty} && (${(0, code_1.checkMissingProp)(cxt, deps, missing)})`); + (0, code_1.reportMissingProp)(cxt, missing); + gen.else(); + } + } + } + exports.validatePropertyDeps = validatePropertyDeps; + function validateSchemaDeps(cxt, schemaDeps = cxt.schema) { + const { gen, data, keyword, it } = cxt; + const valid = gen.name("valid"); + for (const prop in schemaDeps) { + if ((0, util_1.alwaysValidSchema)(it, schemaDeps[prop])) continue; + gen.if((0, code_1.propertyInData)(gen, data, prop, it.opts.ownProperties), () => { + const schCxt = cxt.subschema({ + keyword, + schemaProp: prop + }, valid); + cxt.mergeValidEvaluated(schCxt, valid); + }, () => gen.var(valid, true)); + cxt.ok(valid); + } + } + exports.validateSchemaDeps = validateSchemaDeps; + exports.default = def; +})); + +//#endregion +//#region ../../node_modules/.pnpm/ajv@8.18.0/node_modules/ajv/dist/vocabularies/applicator/propertyNames.js +var require_propertyNames = /* @__PURE__ */ __commonJSMin(((exports) => { + Object.defineProperty(exports, "__esModule", { value: true }); + const codegen_1 = require_codegen(); + const util_1 = require_util(); + const def = { + keyword: "propertyNames", + type: "object", + schemaType: ["object", "boolean"], + error: { + message: "property name must be valid", + params: ({ params }) => (0, codegen_1._)`{propertyName: ${params.propertyName}}` + }, + code(cxt) { + const { gen, schema, data, it } = cxt; + if ((0, util_1.alwaysValidSchema)(it, schema)) return; + const valid = gen.name("valid"); + gen.forIn("key", data, (key) => { + cxt.setParams({ propertyName: key }); + cxt.subschema({ + keyword: "propertyNames", + data: key, + dataTypes: ["string"], + propertyName: key, + compositeRule: true + }, valid); + gen.if((0, codegen_1.not)(valid), () => { + cxt.error(true); + if (!it.allErrors) gen.break(); + }); + }); + cxt.ok(valid); + } + }; + exports.default = def; +})); + +//#endregion +//#region ../../node_modules/.pnpm/ajv@8.18.0/node_modules/ajv/dist/vocabularies/applicator/additionalProperties.js +var require_additionalProperties = /* @__PURE__ */ __commonJSMin(((exports) => { + Object.defineProperty(exports, "__esModule", { value: true }); + const code_1 = require_code(); + const codegen_1 = require_codegen(); + const names_1 = require_names(); + const util_1 = require_util(); + const def = { + keyword: "additionalProperties", + type: ["object"], + schemaType: ["boolean", "object"], + allowUndefined: true, + trackErrors: true, + error: { + message: "must NOT have additional properties", + params: ({ params }) => (0, codegen_1._)`{additionalProperty: ${params.additionalProperty}}` + }, + code(cxt) { + const { gen, schema, parentSchema, data, errsCount, it } = cxt; + /* istanbul ignore if */ + if (!errsCount) throw new Error("ajv implementation error"); + const { allErrors, opts } = it; + it.props = true; + if (opts.removeAdditional !== "all" && (0, util_1.alwaysValidSchema)(it, schema)) return; + const props = (0, code_1.allSchemaProperties)(parentSchema.properties); + const patProps = (0, code_1.allSchemaProperties)(parentSchema.patternProperties); + checkAdditionalProperties(); + cxt.ok((0, codegen_1._)`${errsCount} === ${names_1.default.errors}`); + function checkAdditionalProperties() { + gen.forIn("key", data, (key) => { + if (!props.length && !patProps.length) additionalPropertyCode(key); + else gen.if(isAdditional(key), () => additionalPropertyCode(key)); + }); + } + function isAdditional(key) { + let definedProp; + if (props.length > 8) { + const propsSchema = (0, util_1.schemaRefOrVal)(it, parentSchema.properties, "properties"); + definedProp = (0, code_1.isOwnProperty)(gen, propsSchema, key); + } else if (props.length) definedProp = (0, codegen_1.or)(...props.map((p) => (0, codegen_1._)`${key} === ${p}`)); + else definedProp = codegen_1.nil; + if (patProps.length) definedProp = (0, codegen_1.or)(definedProp, ...patProps.map((p) => (0, codegen_1._)`${(0, code_1.usePattern)(cxt, p)}.test(${key})`)); + return (0, codegen_1.not)(definedProp); + } + function deleteAdditional(key) { + gen.code((0, codegen_1._)`delete ${data}[${key}]`); + } + function additionalPropertyCode(key) { + if (opts.removeAdditional === "all" || opts.removeAdditional && schema === false) { + deleteAdditional(key); + return; + } + if (schema === false) { + cxt.setParams({ additionalProperty: key }); + cxt.error(); + if (!allErrors) gen.break(); + return; + } + if (typeof schema == "object" && !(0, util_1.alwaysValidSchema)(it, schema)) { + const valid = gen.name("valid"); + if (opts.removeAdditional === "failing") { + applyAdditionalSchema(key, valid, false); + gen.if((0, codegen_1.not)(valid), () => { + cxt.reset(); + deleteAdditional(key); + }); + } else { + applyAdditionalSchema(key, valid); + if (!allErrors) gen.if((0, codegen_1.not)(valid), () => gen.break()); + } + } + } + function applyAdditionalSchema(key, valid, errors) { + const subschema = { + keyword: "additionalProperties", + dataProp: key, + dataPropType: util_1.Type.Str + }; + if (errors === false) Object.assign(subschema, { + compositeRule: true, + createErrors: false, + allErrors: false + }); + cxt.subschema(subschema, valid); + } + } + }; + exports.default = def; +})); + +//#endregion +//#region ../../node_modules/.pnpm/ajv@8.18.0/node_modules/ajv/dist/vocabularies/applicator/properties.js +var require_properties = /* @__PURE__ */ __commonJSMin(((exports) => { + Object.defineProperty(exports, "__esModule", { value: true }); + const validate_1 = require_validate(); + const code_1 = require_code(); + const util_1 = require_util(); + const additionalProperties_1 = require_additionalProperties(); + const def = { + keyword: "properties", + type: "object", + schemaType: "object", + code(cxt) { + const { gen, schema, parentSchema, data, it } = cxt; + if (it.opts.removeAdditional === "all" && parentSchema.additionalProperties === void 0) additionalProperties_1.default.code(new validate_1.KeywordCxt(it, additionalProperties_1.default, "additionalProperties")); + const allProps = (0, code_1.allSchemaProperties)(schema); + for (const prop of allProps) it.definedProperties.add(prop); + if (it.opts.unevaluated && allProps.length && it.props !== true) it.props = util_1.mergeEvaluated.props(gen, (0, util_1.toHash)(allProps), it.props); + const properties = allProps.filter((p) => !(0, util_1.alwaysValidSchema)(it, schema[p])); + if (properties.length === 0) return; + const valid = gen.name("valid"); + for (const prop of properties) { + if (hasDefault(prop)) applyPropertySchema(prop); + else { + gen.if((0, code_1.propertyInData)(gen, data, prop, it.opts.ownProperties)); + applyPropertySchema(prop); + if (!it.allErrors) gen.else().var(valid, true); + gen.endIf(); + } + cxt.it.definedProperties.add(prop); + cxt.ok(valid); + } + function hasDefault(prop) { + return it.opts.useDefaults && !it.compositeRule && schema[prop].default !== void 0; + } + function applyPropertySchema(prop) { + cxt.subschema({ + keyword: "properties", + schemaProp: prop, + dataProp: prop + }, valid); + } + } + }; + exports.default = def; +})); + +//#endregion +//#region ../../node_modules/.pnpm/ajv@8.18.0/node_modules/ajv/dist/vocabularies/applicator/patternProperties.js +var require_patternProperties = /* @__PURE__ */ __commonJSMin(((exports) => { + Object.defineProperty(exports, "__esModule", { value: true }); + const code_1 = require_code(); + const codegen_1 = require_codegen(); + const util_1 = require_util(); + const util_2 = require_util(); + const def = { + keyword: "patternProperties", + type: "object", + schemaType: "object", + code(cxt) { + const { gen, schema, data, parentSchema, it } = cxt; + const { opts } = it; + const patterns = (0, code_1.allSchemaProperties)(schema); + const alwaysValidPatterns = patterns.filter((p) => (0, util_1.alwaysValidSchema)(it, schema[p])); + if (patterns.length === 0 || alwaysValidPatterns.length === patterns.length && (!it.opts.unevaluated || it.props === true)) return; + const checkProperties = opts.strictSchema && !opts.allowMatchingProperties && parentSchema.properties; + const valid = gen.name("valid"); + if (it.props !== true && !(it.props instanceof codegen_1.Name)) it.props = (0, util_2.evaluatedPropsToName)(gen, it.props); + const { props } = it; + validatePatternProperties(); + function validatePatternProperties() { + for (const pat of patterns) { + if (checkProperties) checkMatchingProperties(pat); + if (it.allErrors) validateProperties(pat); + else { + gen.var(valid, true); + validateProperties(pat); + gen.if(valid); + } + } + } + function checkMatchingProperties(pat) { + for (const prop in checkProperties) if (new RegExp(pat).test(prop)) (0, util_1.checkStrictMode)(it, `property ${prop} matches pattern ${pat} (use allowMatchingProperties)`); + } + function validateProperties(pat) { + gen.forIn("key", data, (key) => { + gen.if((0, codegen_1._)`${(0, code_1.usePattern)(cxt, pat)}.test(${key})`, () => { + const alwaysValid = alwaysValidPatterns.includes(pat); + if (!alwaysValid) cxt.subschema({ + keyword: "patternProperties", + schemaProp: pat, + dataProp: key, + dataPropType: util_2.Type.Str + }, valid); + if (it.opts.unevaluated && props !== true) gen.assign((0, codegen_1._)`${props}[${key}]`, true); + else if (!alwaysValid && !it.allErrors) gen.if((0, codegen_1.not)(valid), () => gen.break()); + }); + }); + } + } + }; + exports.default = def; +})); + +//#endregion +//#region ../../node_modules/.pnpm/ajv@8.18.0/node_modules/ajv/dist/vocabularies/applicator/not.js +var require_not = /* @__PURE__ */ __commonJSMin(((exports) => { + Object.defineProperty(exports, "__esModule", { value: true }); + const util_1 = require_util(); + const def = { + keyword: "not", + schemaType: ["object", "boolean"], + trackErrors: true, + code(cxt) { + const { gen, schema, it } = cxt; + if ((0, util_1.alwaysValidSchema)(it, schema)) { + cxt.fail(); + return; + } + const valid = gen.name("valid"); + cxt.subschema({ + keyword: "not", + compositeRule: true, + createErrors: false, + allErrors: false + }, valid); + cxt.failResult(valid, () => cxt.reset(), () => cxt.error()); + }, + error: { message: "must NOT be valid" } + }; + exports.default = def; +})); + +//#endregion +//#region ../../node_modules/.pnpm/ajv@8.18.0/node_modules/ajv/dist/vocabularies/applicator/anyOf.js +var require_anyOf = /* @__PURE__ */ __commonJSMin(((exports) => { + Object.defineProperty(exports, "__esModule", { value: true }); + const def = { + keyword: "anyOf", + schemaType: "array", + trackErrors: true, + code: require_code().validateUnion, + error: { message: "must match a schema in anyOf" } + }; + exports.default = def; +})); + +//#endregion +//#region ../../node_modules/.pnpm/ajv@8.18.0/node_modules/ajv/dist/vocabularies/applicator/oneOf.js +var require_oneOf = /* @__PURE__ */ __commonJSMin(((exports) => { + Object.defineProperty(exports, "__esModule", { value: true }); + const codegen_1 = require_codegen(); + const util_1 = require_util(); + const def = { + keyword: "oneOf", + schemaType: "array", + trackErrors: true, + error: { + message: "must match exactly one schema in oneOf", + params: ({ params }) => (0, codegen_1._)`{passingSchemas: ${params.passing}}` + }, + code(cxt) { + const { gen, schema, parentSchema, it } = cxt; + /* istanbul ignore if */ + if (!Array.isArray(schema)) throw new Error("ajv implementation error"); + if (it.opts.discriminator && parentSchema.discriminator) return; + const schArr = schema; + const valid = gen.let("valid", false); + const passing = gen.let("passing", null); + const schValid = gen.name("_valid"); + cxt.setParams({ passing }); + gen.block(validateOneOf); + cxt.result(valid, () => cxt.reset(), () => cxt.error(true)); + function validateOneOf() { + schArr.forEach((sch, i) => { + let schCxt; + if ((0, util_1.alwaysValidSchema)(it, sch)) gen.var(schValid, true); + else schCxt = cxt.subschema({ + keyword: "oneOf", + schemaProp: i, + compositeRule: true + }, schValid); + if (i > 0) gen.if((0, codegen_1._)`${schValid} && ${valid}`).assign(valid, false).assign(passing, (0, codegen_1._)`[${passing}, ${i}]`).else(); + gen.if(schValid, () => { + gen.assign(valid, true); + gen.assign(passing, i); + if (schCxt) cxt.mergeEvaluated(schCxt, codegen_1.Name); + }); + }); + } + } + }; + exports.default = def; +})); + +//#endregion +//#region ../../node_modules/.pnpm/ajv@8.18.0/node_modules/ajv/dist/vocabularies/applicator/allOf.js +var require_allOf = /* @__PURE__ */ __commonJSMin(((exports) => { + Object.defineProperty(exports, "__esModule", { value: true }); + const util_1 = require_util(); + const def = { + keyword: "allOf", + schemaType: "array", + code(cxt) { + const { gen, schema, it } = cxt; + /* istanbul ignore if */ + if (!Array.isArray(schema)) throw new Error("ajv implementation error"); + const valid = gen.name("valid"); + schema.forEach((sch, i) => { + if ((0, util_1.alwaysValidSchema)(it, sch)) return; + const schCxt = cxt.subschema({ + keyword: "allOf", + schemaProp: i + }, valid); + cxt.ok(valid); + cxt.mergeEvaluated(schCxt); + }); + } + }; + exports.default = def; +})); + +//#endregion +//#region ../../node_modules/.pnpm/ajv@8.18.0/node_modules/ajv/dist/vocabularies/applicator/if.js +var require_if = /* @__PURE__ */ __commonJSMin(((exports) => { + Object.defineProperty(exports, "__esModule", { value: true }); + const codegen_1 = require_codegen(); + const util_1 = require_util(); + const def = { + keyword: "if", + schemaType: ["object", "boolean"], + trackErrors: true, + error: { + message: ({ params }) => (0, codegen_1.str)`must match "${params.ifClause}" schema`, + params: ({ params }) => (0, codegen_1._)`{failingKeyword: ${params.ifClause}}` + }, + code(cxt) { + const { gen, parentSchema, it } = cxt; + if (parentSchema.then === void 0 && parentSchema.else === void 0) (0, util_1.checkStrictMode)(it, "\"if\" without \"then\" and \"else\" is ignored"); + const hasThen = hasSchema(it, "then"); + const hasElse = hasSchema(it, "else"); + if (!hasThen && !hasElse) return; + const valid = gen.let("valid", true); + const schValid = gen.name("_valid"); + validateIf(); + cxt.reset(); + if (hasThen && hasElse) { + const ifClause = gen.let("ifClause"); + cxt.setParams({ ifClause }); + gen.if(schValid, validateClause("then", ifClause), validateClause("else", ifClause)); + } else if (hasThen) gen.if(schValid, validateClause("then")); + else gen.if((0, codegen_1.not)(schValid), validateClause("else")); + cxt.pass(valid, () => cxt.error(true)); + function validateIf() { + const schCxt = cxt.subschema({ + keyword: "if", + compositeRule: true, + createErrors: false, + allErrors: false + }, schValid); + cxt.mergeEvaluated(schCxt); + } + function validateClause(keyword, ifClause) { + return () => { + const schCxt = cxt.subschema({ keyword }, schValid); + gen.assign(valid, schValid); + cxt.mergeValidEvaluated(schCxt, valid); + if (ifClause) gen.assign(ifClause, (0, codegen_1._)`${keyword}`); + else cxt.setParams({ ifClause: keyword }); + }; + } + } + }; + function hasSchema(it, keyword) { + const schema = it.schema[keyword]; + return schema !== void 0 && !(0, util_1.alwaysValidSchema)(it, schema); + } + exports.default = def; +})); + +//#endregion +//#region ../../node_modules/.pnpm/ajv@8.18.0/node_modules/ajv/dist/vocabularies/applicator/thenElse.js +var require_thenElse = /* @__PURE__ */ __commonJSMin(((exports) => { + Object.defineProperty(exports, "__esModule", { value: true }); + const util_1 = require_util(); + const def = { + keyword: ["then", "else"], + schemaType: ["object", "boolean"], + code({ keyword, parentSchema, it }) { + if (parentSchema.if === void 0) (0, util_1.checkStrictMode)(it, `"${keyword}" without "if" is ignored`); + } + }; + exports.default = def; +})); + +//#endregion +//#region ../../node_modules/.pnpm/ajv@8.18.0/node_modules/ajv/dist/vocabularies/applicator/index.js +var require_applicator$2 = /* @__PURE__ */ __commonJSMin(((exports) => { + Object.defineProperty(exports, "__esModule", { value: true }); + const additionalItems_1 = require_additionalItems(); + const prefixItems_1 = require_prefixItems(); + const items_1 = require_items(); + const items2020_1 = require_items2020(); + const contains_1 = require_contains(); + const dependencies_1 = require_dependencies(); + const propertyNames_1 = require_propertyNames(); + const additionalProperties_1 = require_additionalProperties(); + const properties_1 = require_properties(); + const patternProperties_1 = require_patternProperties(); + const not_1 = require_not(); + const anyOf_1 = require_anyOf(); + const oneOf_1 = require_oneOf(); + const allOf_1 = require_allOf(); + const if_1 = require_if(); + const thenElse_1 = require_thenElse(); + function getApplicator(draft2020 = false) { + const applicator = [ + not_1.default, + anyOf_1.default, + oneOf_1.default, + allOf_1.default, + if_1.default, + thenElse_1.default, + propertyNames_1.default, + additionalProperties_1.default, + dependencies_1.default, + properties_1.default, + patternProperties_1.default + ]; + if (draft2020) applicator.push(prefixItems_1.default, items2020_1.default); + else applicator.push(additionalItems_1.default, items_1.default); + applicator.push(contains_1.default); + return applicator; + } + exports.default = getApplicator; +})); + +//#endregion +//#region ../../node_modules/.pnpm/ajv@8.18.0/node_modules/ajv/dist/vocabularies/format/format.js +var require_format$2 = /* @__PURE__ */ __commonJSMin(((exports) => { + Object.defineProperty(exports, "__esModule", { value: true }); + const codegen_1 = require_codegen(); + const def = { + keyword: "format", + type: ["number", "string"], + schemaType: "string", + $data: true, + error: { + message: ({ schemaCode }) => (0, codegen_1.str)`must match format "${schemaCode}"`, + params: ({ schemaCode }) => (0, codegen_1._)`{format: ${schemaCode}}` + }, + code(cxt, ruleType) { + const { gen, data, $data, schema, schemaCode, it } = cxt; + const { opts, errSchemaPath, schemaEnv, self } = it; + if (!opts.validateFormats) return; + if ($data) validate$DataFormat(); + else validateFormat(); + function validate$DataFormat() { + const fmts = gen.scopeValue("formats", { + ref: self.formats, + code: opts.code.formats + }); + const fDef = gen.const("fDef", (0, codegen_1._)`${fmts}[${schemaCode}]`); + const fType = gen.let("fType"); + const format = gen.let("format"); + gen.if((0, codegen_1._)`typeof ${fDef} == "object" && !(${fDef} instanceof RegExp)`, () => gen.assign(fType, (0, codegen_1._)`${fDef}.type || "string"`).assign(format, (0, codegen_1._)`${fDef}.validate`), () => gen.assign(fType, (0, codegen_1._)`"string"`).assign(format, fDef)); + cxt.fail$data((0, codegen_1.or)(unknownFmt(), invalidFmt())); + function unknownFmt() { + if (opts.strictSchema === false) return codegen_1.nil; + return (0, codegen_1._)`${schemaCode} && !${format}`; + } + function invalidFmt() { + const callFormat = schemaEnv.$async ? (0, codegen_1._)`(${fDef}.async ? await ${format}(${data}) : ${format}(${data}))` : (0, codegen_1._)`${format}(${data})`; + const validData = (0, codegen_1._)`(typeof ${format} == "function" ? ${callFormat} : ${format}.test(${data}))`; + return (0, codegen_1._)`${format} && ${format} !== true && ${fType} === ${ruleType} && !${validData}`; + } + } + function validateFormat() { + const formatDef = self.formats[schema]; + if (!formatDef) { + unknownFormat(); + return; + } + if (formatDef === true) return; + const [fmtType, format, fmtRef] = getFormat(formatDef); + if (fmtType === ruleType) cxt.pass(validCondition()); + function unknownFormat() { + if (opts.strictSchema === false) { + self.logger.warn(unknownMsg()); + return; + } + throw new Error(unknownMsg()); + function unknownMsg() { + return `unknown format "${schema}" ignored in schema at path "${errSchemaPath}"`; + } + } + function getFormat(fmtDef) { + const code = fmtDef instanceof RegExp ? (0, codegen_1.regexpCode)(fmtDef) : opts.code.formats ? (0, codegen_1._)`${opts.code.formats}${(0, codegen_1.getProperty)(schema)}` : void 0; + const fmt = gen.scopeValue("formats", { + key: schema, + ref: fmtDef, + code + }); + if (typeof fmtDef == "object" && !(fmtDef instanceof RegExp)) return [ + fmtDef.type || "string", + fmtDef.validate, + (0, codegen_1._)`${fmt}.validate` + ]; + return [ + "string", + fmtDef, + fmt + ]; + } + function validCondition() { + if (typeof formatDef == "object" && !(formatDef instanceof RegExp) && formatDef.async) { + if (!schemaEnv.$async) throw new Error("async format in sync schema"); + return (0, codegen_1._)`await ${fmtRef}(${data})`; + } + return typeof format == "function" ? (0, codegen_1._)`${fmtRef}(${data})` : (0, codegen_1._)`${fmtRef}.test(${data})`; + } + } + } + }; + exports.default = def; +})); + +//#endregion +//#region ../../node_modules/.pnpm/ajv@8.18.0/node_modules/ajv/dist/vocabularies/format/index.js +var require_format$1 = /* @__PURE__ */ __commonJSMin(((exports) => { + Object.defineProperty(exports, "__esModule", { value: true }); + const format = [require_format$2().default]; + exports.default = format; +})); + +//#endregion +//#region ../../node_modules/.pnpm/ajv@8.18.0/node_modules/ajv/dist/vocabularies/metadata.js +var require_metadata = /* @__PURE__ */ __commonJSMin(((exports) => { + Object.defineProperty(exports, "__esModule", { value: true }); + exports.contentVocabulary = exports.metadataVocabulary = void 0; + exports.metadataVocabulary = [ + "title", + "description", + "default", + "deprecated", + "readOnly", + "writeOnly", + "examples" + ]; + exports.contentVocabulary = [ + "contentMediaType", + "contentEncoding", + "contentSchema" + ]; +})); + +//#endregion +//#region ../../node_modules/.pnpm/ajv@8.18.0/node_modules/ajv/dist/vocabularies/draft7.js +var require_draft7 = /* @__PURE__ */ __commonJSMin(((exports) => { + Object.defineProperty(exports, "__esModule", { value: true }); + const core_1 = require_core$2(); + const validation_1 = require_validation$2(); + const applicator_1 = require_applicator$2(); + const format_1 = require_format$1(); + const metadata_1 = require_metadata(); + const draft7Vocabularies = [ + core_1.default, + validation_1.default, + (0, applicator_1.default)(), + format_1.default, + metadata_1.metadataVocabulary, + metadata_1.contentVocabulary + ]; + exports.default = draft7Vocabularies; +})); + +//#endregion +//#region ../../node_modules/.pnpm/ajv@8.18.0/node_modules/ajv/dist/vocabularies/discriminator/types.js +var require_types = /* @__PURE__ */ __commonJSMin(((exports) => { + Object.defineProperty(exports, "__esModule", { value: true }); + exports.DiscrError = void 0; + var DiscrError; + (function(DiscrError) { + DiscrError["Tag"] = "tag"; + DiscrError["Mapping"] = "mapping"; + })(DiscrError || (exports.DiscrError = DiscrError = {})); +})); + +//#endregion +//#region ../../node_modules/.pnpm/ajv@8.18.0/node_modules/ajv/dist/vocabularies/discriminator/index.js +var require_discriminator = /* @__PURE__ */ __commonJSMin(((exports) => { + Object.defineProperty(exports, "__esModule", { value: true }); + const codegen_1 = require_codegen(); + const types_1 = require_types(); + const compile_1 = require_compile(); + const ref_error_1 = require_ref_error(); + const util_1 = require_util(); + const def = { + keyword: "discriminator", + type: "object", + schemaType: "object", + error: { + message: ({ params: { discrError, tagName } }) => discrError === types_1.DiscrError.Tag ? `tag "${tagName}" must be string` : `value of tag "${tagName}" must be in oneOf`, + params: ({ params: { discrError, tag, tagName } }) => (0, codegen_1._)`{error: ${discrError}, tag: ${tagName}, tagValue: ${tag}}` + }, + code(cxt) { + const { gen, data, schema, parentSchema, it } = cxt; + const { oneOf } = parentSchema; + if (!it.opts.discriminator) throw new Error("discriminator: requires discriminator option"); + const tagName = schema.propertyName; + if (typeof tagName != "string") throw new Error("discriminator: requires propertyName"); + if (schema.mapping) throw new Error("discriminator: mapping is not supported"); + if (!oneOf) throw new Error("discriminator: requires oneOf keyword"); + const valid = gen.let("valid", false); + const tag = gen.const("tag", (0, codegen_1._)`${data}${(0, codegen_1.getProperty)(tagName)}`); + gen.if((0, codegen_1._)`typeof ${tag} == "string"`, () => validateMapping(), () => cxt.error(false, { + discrError: types_1.DiscrError.Tag, + tag, + tagName + })); + cxt.ok(valid); + function validateMapping() { + const mapping = getMapping(); + gen.if(false); + for (const tagValue in mapping) { + gen.elseIf((0, codegen_1._)`${tag} === ${tagValue}`); + gen.assign(valid, applyTagSchema(mapping[tagValue])); + } + gen.else(); + cxt.error(false, { + discrError: types_1.DiscrError.Mapping, + tag, + tagName + }); + gen.endIf(); + } + function applyTagSchema(schemaProp) { + const _valid = gen.name("valid"); + const schCxt = cxt.subschema({ + keyword: "oneOf", + schemaProp + }, _valid); + cxt.mergeEvaluated(schCxt, codegen_1.Name); + return _valid; + } + function getMapping() { + var _a; + const oneOfMapping = {}; + const topRequired = hasRequired(parentSchema); + let tagRequired = true; + for (let i = 0; i < oneOf.length; i++) { + let sch = oneOf[i]; + if ((sch === null || sch === void 0 ? void 0 : sch.$ref) && !(0, util_1.schemaHasRulesButRef)(sch, it.self.RULES)) { + const ref = sch.$ref; + sch = compile_1.resolveRef.call(it.self, it.schemaEnv.root, it.baseId, ref); + if (sch instanceof compile_1.SchemaEnv) sch = sch.schema; + if (sch === void 0) throw new ref_error_1.default(it.opts.uriResolver, it.baseId, ref); + } + const propSch = (_a = sch === null || sch === void 0 ? void 0 : sch.properties) === null || _a === void 0 ? void 0 : _a[tagName]; + if (typeof propSch != "object") throw new Error(`discriminator: oneOf subschemas (or referenced schemas) must have "properties/${tagName}"`); + tagRequired = tagRequired && (topRequired || hasRequired(sch)); + addMappings(propSch, i); + } + if (!tagRequired) throw new Error(`discriminator: "${tagName}" must be required`); + return oneOfMapping; + function hasRequired({ required }) { + return Array.isArray(required) && required.includes(tagName); + } + function addMappings(sch, i) { + if (sch.const) addMapping(sch.const, i); + else if (sch.enum) for (const tagValue of sch.enum) addMapping(tagValue, i); + else throw new Error(`discriminator: "properties/${tagName}" must have "const" or "enum"`); + } + function addMapping(tagValue, i) { + if (typeof tagValue != "string" || tagValue in oneOfMapping) throw new Error(`discriminator: "${tagName}" values must be unique strings`); + oneOfMapping[tagValue] = i; + } + } + } + }; + exports.default = def; +})); + +//#endregion +//#region ../../node_modules/.pnpm/ajv@8.18.0/node_modules/ajv/dist/refs/json-schema-draft-07.json +var require_json_schema_draft_07 = /* @__PURE__ */ __commonJSMin(((exports, module) => { + module.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": true, + "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": true, + "readOnly": { + "type": "boolean", + "default": false + }, + "examples": { + "type": "array", + "items": true + }, + "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": true + }, + "maxItems": { "$ref": "#/definitions/nonNegativeInteger" }, + "minItems": { "$ref": "#/definitions/nonNegativeIntegerDefault0" }, + "uniqueItems": { + "type": "boolean", + "default": false + }, + "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": true, + "enum": { + "type": "array", + "items": true, + "minItems": 1, + "uniqueItems": true + }, + "type": { "anyOf": [{ "$ref": "#/definitions/simpleTypes" }, { + "type": "array", + "items": { "$ref": "#/definitions/simpleTypes" }, + "minItems": 1, + "uniqueItems": true + }] }, + "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": true + }; +})); + +//#endregion +//#region ../../node_modules/.pnpm/ajv@8.18.0/node_modules/ajv/dist/ajv.js +var require_ajv = /* @__PURE__ */ __commonJSMin(((exports, module) => { + Object.defineProperty(exports, "__esModule", { value: true }); + exports.MissingRefError = exports.ValidationError = exports.CodeGen = exports.Name = exports.nil = exports.stringify = exports.str = exports._ = exports.KeywordCxt = exports.Ajv = void 0; + const core_1 = require_core$3(); + const draft7_1 = require_draft7(); + const discriminator_1 = require_discriminator(); + const draft7MetaSchema = require_json_schema_draft_07(); + const META_SUPPORT_DATA = ["/properties"]; + const META_SCHEMA_ID = "http://json-schema.org/draft-07/schema"; + var Ajv = class extends core_1.default { + _addVocabularies() { + super._addVocabularies(); + draft7_1.default.forEach((v) => this.addVocabulary(v)); + if (this.opts.discriminator) this.addKeyword(discriminator_1.default); + } + _addDefaultMetaSchema() { + super._addDefaultMetaSchema(); + if (!this.opts.meta) return; + const metaSchema = this.opts.$data ? this.$dataMetaSchema(draft7MetaSchema, META_SUPPORT_DATA) : draft7MetaSchema; + this.addMetaSchema(metaSchema, META_SCHEMA_ID, false); + this.refs["http://json-schema.org/schema"] = META_SCHEMA_ID; + } + defaultMeta() { + return this.opts.defaultMeta = super.defaultMeta() || (this.getSchema(META_SCHEMA_ID) ? META_SCHEMA_ID : void 0); + } + }; + exports.Ajv = Ajv; + module.exports = exports = Ajv; + module.exports.Ajv = Ajv; + Object.defineProperty(exports, "__esModule", { value: true }); + exports.default = Ajv; + var validate_1 = require_validate(); + Object.defineProperty(exports, "KeywordCxt", { + enumerable: true, + get: function() { + return validate_1.KeywordCxt; + } + }); + var codegen_1 = require_codegen(); + Object.defineProperty(exports, "_", { + enumerable: true, + get: function() { + return codegen_1._; + } + }); + Object.defineProperty(exports, "str", { + enumerable: true, + get: function() { + return codegen_1.str; + } + }); + Object.defineProperty(exports, "stringify", { + enumerable: true, + get: function() { + return codegen_1.stringify; + } + }); + Object.defineProperty(exports, "nil", { + enumerable: true, + get: function() { + return codegen_1.nil; + } + }); + Object.defineProperty(exports, "Name", { + enumerable: true, + get: function() { + return codegen_1.Name; + } + }); + Object.defineProperty(exports, "CodeGen", { + enumerable: true, + get: function() { + return codegen_1.CodeGen; + } + }); + var validation_error_1 = require_validation_error(); + Object.defineProperty(exports, "ValidationError", { + enumerable: true, + get: function() { + return validation_error_1.default; + } + }); + var ref_error_1 = require_ref_error(); + Object.defineProperty(exports, "MissingRefError", { + enumerable: true, + get: function() { + return ref_error_1.default; + } + }); +})); + +//#endregion +//#region ../../node_modules/.pnpm/ajv@8.18.0/node_modules/ajv/dist/vocabularies/dynamic/dynamicAnchor.js +var require_dynamicAnchor = /* @__PURE__ */ __commonJSMin(((exports) => { + Object.defineProperty(exports, "__esModule", { value: true }); + exports.dynamicAnchor = void 0; + const codegen_1 = require_codegen(); + const names_1 = require_names(); + const compile_1 = require_compile(); + const ref_1 = require_ref(); + const def = { + keyword: "$dynamicAnchor", + schemaType: "string", + code: (cxt) => dynamicAnchor(cxt, cxt.schema) + }; + function dynamicAnchor(cxt, anchor) { + const { gen, it } = cxt; + it.schemaEnv.root.dynamicAnchors[anchor] = true; + const v = (0, codegen_1._)`${names_1.default.dynamicAnchors}${(0, codegen_1.getProperty)(anchor)}`; + const validate = it.errSchemaPath === "#" ? it.validateName : _getValidate(cxt); + gen.if((0, codegen_1._)`!${v}`, () => gen.assign(v, validate)); + } + exports.dynamicAnchor = dynamicAnchor; + function _getValidate(cxt) { + const { schemaEnv, schema, self } = cxt.it; + const { root, baseId, localRefs, meta } = schemaEnv.root; + const { schemaId } = self.opts; + const sch = new compile_1.SchemaEnv({ + schema, + schemaId, + root, + baseId, + localRefs, + meta + }); + compile_1.compileSchema.call(self, sch); + return (0, ref_1.getValidate)(cxt, sch); + } + exports.default = def; +})); + +//#endregion +//#region ../../node_modules/.pnpm/ajv@8.18.0/node_modules/ajv/dist/vocabularies/dynamic/dynamicRef.js +var require_dynamicRef = /* @__PURE__ */ __commonJSMin(((exports) => { + Object.defineProperty(exports, "__esModule", { value: true }); + exports.dynamicRef = void 0; + const codegen_1 = require_codegen(); + const names_1 = require_names(); + const ref_1 = require_ref(); + const def = { + keyword: "$dynamicRef", + schemaType: "string", + code: (cxt) => dynamicRef(cxt, cxt.schema) + }; + function dynamicRef(cxt, ref) { + const { gen, keyword, it } = cxt; + if (ref[0] !== "#") throw new Error(`"${keyword}" only supports hash fragment reference`); + const anchor = ref.slice(1); + if (it.allErrors) _dynamicRef(); + else { + const valid = gen.let("valid", false); + _dynamicRef(valid); + cxt.ok(valid); + } + function _dynamicRef(valid) { + if (it.schemaEnv.root.dynamicAnchors[anchor]) { + const v = gen.let("_v", (0, codegen_1._)`${names_1.default.dynamicAnchors}${(0, codegen_1.getProperty)(anchor)}`); + gen.if(v, _callRef(v, valid), _callRef(it.validateName, valid)); + } else _callRef(it.validateName, valid)(); + } + function _callRef(validate, valid) { + return valid ? () => gen.block(() => { + (0, ref_1.callRef)(cxt, validate); + gen.let(valid, true); + }) : () => (0, ref_1.callRef)(cxt, validate); + } + } + exports.dynamicRef = dynamicRef; + exports.default = def; +})); + +//#endregion +//#region ../../node_modules/.pnpm/ajv@8.18.0/node_modules/ajv/dist/vocabularies/dynamic/recursiveAnchor.js +var require_recursiveAnchor = /* @__PURE__ */ __commonJSMin(((exports) => { + Object.defineProperty(exports, "__esModule", { value: true }); + const dynamicAnchor_1 = require_dynamicAnchor(); + const util_1 = require_util(); + const def = { + keyword: "$recursiveAnchor", + schemaType: "boolean", + code(cxt) { + if (cxt.schema) (0, dynamicAnchor_1.dynamicAnchor)(cxt, ""); + else (0, util_1.checkStrictMode)(cxt.it, "$recursiveAnchor: false is ignored"); + } + }; + exports.default = def; +})); + +//#endregion +//#region ../../node_modules/.pnpm/ajv@8.18.0/node_modules/ajv/dist/vocabularies/dynamic/recursiveRef.js +var require_recursiveRef = /* @__PURE__ */ __commonJSMin(((exports) => { + Object.defineProperty(exports, "__esModule", { value: true }); + const dynamicRef_1 = require_dynamicRef(); + const def = { + keyword: "$recursiveRef", + schemaType: "string", + code: (cxt) => (0, dynamicRef_1.dynamicRef)(cxt, cxt.schema) + }; + exports.default = def; +})); + +//#endregion +//#region ../../node_modules/.pnpm/ajv@8.18.0/node_modules/ajv/dist/vocabularies/dynamic/index.js +var require_dynamic = /* @__PURE__ */ __commonJSMin(((exports) => { + Object.defineProperty(exports, "__esModule", { value: true }); + const dynamicAnchor_1 = require_dynamicAnchor(); + const dynamicRef_1 = require_dynamicRef(); + const recursiveAnchor_1 = require_recursiveAnchor(); + const recursiveRef_1 = require_recursiveRef(); + const dynamic = [ + dynamicAnchor_1.default, + dynamicRef_1.default, + recursiveAnchor_1.default, + recursiveRef_1.default + ]; + exports.default = dynamic; +})); + +//#endregion +//#region ../../node_modules/.pnpm/ajv@8.18.0/node_modules/ajv/dist/vocabularies/validation/dependentRequired.js +var require_dependentRequired = /* @__PURE__ */ __commonJSMin(((exports) => { + Object.defineProperty(exports, "__esModule", { value: true }); + const dependencies_1 = require_dependencies(); + const def = { + keyword: "dependentRequired", + type: "object", + schemaType: "object", + error: dependencies_1.error, + code: (cxt) => (0, dependencies_1.validatePropertyDeps)(cxt) + }; + exports.default = def; +})); + +//#endregion +//#region ../../node_modules/.pnpm/ajv@8.18.0/node_modules/ajv/dist/vocabularies/applicator/dependentSchemas.js +var require_dependentSchemas = /* @__PURE__ */ __commonJSMin(((exports) => { + Object.defineProperty(exports, "__esModule", { value: true }); + const dependencies_1 = require_dependencies(); + const def = { + keyword: "dependentSchemas", + type: "object", + schemaType: "object", + code: (cxt) => (0, dependencies_1.validateSchemaDeps)(cxt) + }; + exports.default = def; +})); + +//#endregion +//#region ../../node_modules/.pnpm/ajv@8.18.0/node_modules/ajv/dist/vocabularies/validation/limitContains.js +var require_limitContains = /* @__PURE__ */ __commonJSMin(((exports) => { + Object.defineProperty(exports, "__esModule", { value: true }); + const util_1 = require_util(); + const def = { + keyword: ["maxContains", "minContains"], + type: "array", + schemaType: "number", + code({ keyword, parentSchema, it }) { + if (parentSchema.contains === void 0) (0, util_1.checkStrictMode)(it, `"${keyword}" without "contains" is ignored`); + } + }; + exports.default = def; +})); + +//#endregion +//#region ../../node_modules/.pnpm/ajv@8.18.0/node_modules/ajv/dist/vocabularies/next.js +var require_next = /* @__PURE__ */ __commonJSMin(((exports) => { + Object.defineProperty(exports, "__esModule", { value: true }); + const dependentRequired_1 = require_dependentRequired(); + const dependentSchemas_1 = require_dependentSchemas(); + const limitContains_1 = require_limitContains(); + const next = [ + dependentRequired_1.default, + dependentSchemas_1.default, + limitContains_1.default + ]; + exports.default = next; +})); + +//#endregion +//#region ../../node_modules/.pnpm/ajv@8.18.0/node_modules/ajv/dist/vocabularies/unevaluated/unevaluatedProperties.js +var require_unevaluatedProperties = /* @__PURE__ */ __commonJSMin(((exports) => { + Object.defineProperty(exports, "__esModule", { value: true }); + const codegen_1 = require_codegen(); + const util_1 = require_util(); + const names_1 = require_names(); + const def = { + keyword: "unevaluatedProperties", + type: "object", + schemaType: ["boolean", "object"], + trackErrors: true, + error: { + message: "must NOT have unevaluated properties", + params: ({ params }) => (0, codegen_1._)`{unevaluatedProperty: ${params.unevaluatedProperty}}` + }, + code(cxt) { + const { gen, schema, data, errsCount, it } = cxt; + /* istanbul ignore if */ + if (!errsCount) throw new Error("ajv implementation error"); + const { allErrors, props } = it; + if (props instanceof codegen_1.Name) gen.if((0, codegen_1._)`${props} !== true`, () => gen.forIn("key", data, (key) => gen.if(unevaluatedDynamic(props, key), () => unevaluatedPropCode(key)))); + else if (props !== true) gen.forIn("key", data, (key) => props === void 0 ? unevaluatedPropCode(key) : gen.if(unevaluatedStatic(props, key), () => unevaluatedPropCode(key))); + it.props = true; + cxt.ok((0, codegen_1._)`${errsCount} === ${names_1.default.errors}`); + function unevaluatedPropCode(key) { + if (schema === false) { + cxt.setParams({ unevaluatedProperty: key }); + cxt.error(); + if (!allErrors) gen.break(); + return; + } + if (!(0, util_1.alwaysValidSchema)(it, schema)) { + const valid = gen.name("valid"); + cxt.subschema({ + keyword: "unevaluatedProperties", + dataProp: key, + dataPropType: util_1.Type.Str + }, valid); + if (!allErrors) gen.if((0, codegen_1.not)(valid), () => gen.break()); + } + } + function unevaluatedDynamic(evaluatedProps, key) { + return (0, codegen_1._)`!${evaluatedProps} || !${evaluatedProps}[${key}]`; + } + function unevaluatedStatic(evaluatedProps, key) { + const ps = []; + for (const p in evaluatedProps) if (evaluatedProps[p] === true) ps.push((0, codegen_1._)`${key} !== ${p}`); + return (0, codegen_1.and)(...ps); + } + } + }; + exports.default = def; +})); + +//#endregion +//#region ../../node_modules/.pnpm/ajv@8.18.0/node_modules/ajv/dist/vocabularies/unevaluated/unevaluatedItems.js +var require_unevaluatedItems = /* @__PURE__ */ __commonJSMin(((exports) => { + Object.defineProperty(exports, "__esModule", { value: true }); + const codegen_1 = require_codegen(); + const util_1 = require_util(); + const def = { + keyword: "unevaluatedItems", + type: "array", + schemaType: ["boolean", "object"], + error: { + message: ({ params: { len } }) => (0, codegen_1.str)`must NOT have more than ${len} items`, + params: ({ params: { len } }) => (0, codegen_1._)`{limit: ${len}}` + }, + code(cxt) { + const { gen, schema, data, it } = cxt; + const items = it.items || 0; + if (items === true) return; + const len = gen.const("len", (0, codegen_1._)`${data}.length`); + if (schema === false) { + cxt.setParams({ len: items }); + cxt.fail((0, codegen_1._)`${len} > ${items}`); + } else if (typeof schema == "object" && !(0, util_1.alwaysValidSchema)(it, schema)) { + const valid = gen.var("valid", (0, codegen_1._)`${len} <= ${items}`); + gen.if((0, codegen_1.not)(valid), () => validateItems(valid, items)); + cxt.ok(valid); + } + it.items = true; + function validateItems(valid, from) { + gen.forRange("i", from, len, (i) => { + cxt.subschema({ + keyword: "unevaluatedItems", + dataProp: i, + dataPropType: util_1.Type.Num + }, valid); + if (!it.allErrors) gen.if((0, codegen_1.not)(valid), () => gen.break()); + }); + } + } + }; + exports.default = def; +})); + +//#endregion +//#region ../../node_modules/.pnpm/ajv@8.18.0/node_modules/ajv/dist/vocabularies/unevaluated/index.js +var require_unevaluated$1 = /* @__PURE__ */ __commonJSMin(((exports) => { + Object.defineProperty(exports, "__esModule", { value: true }); + const unevaluatedProperties_1 = require_unevaluatedProperties(); + const unevaluatedItems_1 = require_unevaluatedItems(); + const unevaluated = [unevaluatedProperties_1.default, unevaluatedItems_1.default]; + exports.default = unevaluated; +})); + +//#endregion +//#region ../../node_modules/.pnpm/ajv@8.18.0/node_modules/ajv/dist/refs/json-schema-2019-09/schema.json +var require_schema$1 = /* @__PURE__ */ __commonJSMin(((exports, module) => { + module.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": true, + "https://json-schema.org/draft/2019-09/vocab/applicator": true, + "https://json-schema.org/draft/2019-09/vocab/validation": true, + "https://json-schema.org/draft/2019-09/vocab/meta-data": true, + "https://json-schema.org/draft/2019-09/vocab/format": false, + "https://json-schema.org/draft/2019-09/vocab/content": true + }, + "$recursiveAnchor": true, + "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" }] } + } + } + }; +})); + +//#endregion +//#region ../../node_modules/.pnpm/ajv@8.18.0/node_modules/ajv/dist/refs/json-schema-2019-09/meta/applicator.json +var require_applicator$1 = /* @__PURE__ */ __commonJSMin(((exports, module) => { + module.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": true }, + "$recursiveAnchor": true, + "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": "#" } + } } + }; +})); + +//#endregion +//#region ../../node_modules/.pnpm/ajv@8.18.0/node_modules/ajv/dist/refs/json-schema-2019-09/meta/content.json +var require_content$1 = /* @__PURE__ */ __commonJSMin(((exports, module) => { + module.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": true }, + "$recursiveAnchor": true, + "title": "Content vocabulary meta-schema", + "type": ["object", "boolean"], + "properties": { + "contentMediaType": { "type": "string" }, + "contentEncoding": { "type": "string" }, + "contentSchema": { "$recursiveRef": "#" } + } + }; +})); + +//#endregion +//#region ../../node_modules/.pnpm/ajv@8.18.0/node_modules/ajv/dist/refs/json-schema-2019-09/meta/core.json +var require_core$1 = /* @__PURE__ */ __commonJSMin(((exports, module) => { + module.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": true }, + "$recursiveAnchor": true, + "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": false + }, + "$vocabulary": { + "type": "object", + "propertyNames": { + "type": "string", + "format": "uri" + }, + "additionalProperties": { "type": "boolean" } + }, + "$comment": { "type": "string" }, + "$defs": { + "type": "object", + "additionalProperties": { "$recursiveRef": "#" }, + "default": {} + } + } + }; +})); + +//#endregion +//#region ../../node_modules/.pnpm/ajv@8.18.0/node_modules/ajv/dist/refs/json-schema-2019-09/meta/format.json +var require_format = /* @__PURE__ */ __commonJSMin(((exports, module) => { + module.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": true }, + "$recursiveAnchor": true, + "title": "Format vocabulary meta-schema", + "type": ["object", "boolean"], + "properties": { "format": { "type": "string" } } + }; +})); + +//#endregion +//#region ../../node_modules/.pnpm/ajv@8.18.0/node_modules/ajv/dist/refs/json-schema-2019-09/meta/meta-data.json +var require_meta_data$1 = /* @__PURE__ */ __commonJSMin(((exports, module) => { + module.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": true }, + "$recursiveAnchor": true, + "title": "Meta-data vocabulary meta-schema", + "type": ["object", "boolean"], + "properties": { + "title": { "type": "string" }, + "description": { "type": "string" }, + "default": true, + "deprecated": { + "type": "boolean", + "default": false + }, + "readOnly": { + "type": "boolean", + "default": false + }, + "writeOnly": { + "type": "boolean", + "default": false + }, + "examples": { + "type": "array", + "items": true + } + } + }; +})); + +//#endregion +//#region ../../node_modules/.pnpm/ajv@8.18.0/node_modules/ajv/dist/refs/json-schema-2019-09/meta/validation.json +var require_validation$1 = /* @__PURE__ */ __commonJSMin(((exports, module) => { + module.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": true }, + "$recursiveAnchor": true, + "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": false + }, + "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": true, + "enum": { + "type": "array", + "items": true + }, + "type": { "anyOf": [{ "$ref": "#/$defs/simpleTypes" }, { + "type": "array", + "items": { "$ref": "#/$defs/simpleTypes" }, + "minItems": 1, + "uniqueItems": true + }] } + }, + "$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": true, + "default": [] + } + } + }; +})); + +//#endregion +//#region ../../node_modules/.pnpm/ajv@8.18.0/node_modules/ajv/dist/refs/json-schema-2019-09/index.js +var require_json_schema_2019_09 = /* @__PURE__ */ __commonJSMin(((exports) => { + Object.defineProperty(exports, "__esModule", { value: true }); + const metaSchema = require_schema$1(); + const applicator = require_applicator$1(); + const content = require_content$1(); + const core = require_core$1(); + const format = require_format(); + const metadata = require_meta_data$1(); + const validation = require_validation$1(); + const META_SUPPORT_DATA = ["/properties"]; + function addMetaSchema2019($data) { + [ + metaSchema, + applicator, + content, + core, + with$data(this, format), + metadata, + with$data(this, validation) + ].forEach((sch) => this.addMetaSchema(sch, void 0, false)); + return this; + function with$data(ajv, sch) { + return $data ? ajv.$dataMetaSchema(sch, META_SUPPORT_DATA) : sch; + } + } + exports.default = addMetaSchema2019; +})); + +//#endregion +//#region ../../node_modules/.pnpm/ajv@8.18.0/node_modules/ajv/dist/2019.js +var require__2019 = /* @__PURE__ */ __commonJSMin(((exports, module) => { + Object.defineProperty(exports, "__esModule", { value: true }); + exports.MissingRefError = exports.ValidationError = exports.CodeGen = exports.Name = exports.nil = exports.stringify = exports.str = exports._ = exports.KeywordCxt = exports.Ajv2019 = void 0; + const core_1 = require_core$3(); + const draft7_1 = require_draft7(); + const dynamic_1 = require_dynamic(); + const next_1 = require_next(); + const unevaluated_1 = require_unevaluated$1(); + const discriminator_1 = require_discriminator(); + const json_schema_2019_09_1 = require_json_schema_2019_09(); + const META_SCHEMA_ID = "https://json-schema.org/draft/2019-09/schema"; + var Ajv2019 = class extends core_1.default { + constructor(opts = {}) { + super({ + ...opts, + dynamicRef: true, + next: true, + unevaluated: true + }); + } + _addVocabularies() { + super._addVocabularies(); + this.addVocabulary(dynamic_1.default); + draft7_1.default.forEach((v) => this.addVocabulary(v)); + this.addVocabulary(next_1.default); + this.addVocabulary(unevaluated_1.default); + if (this.opts.discriminator) this.addKeyword(discriminator_1.default); + } + _addDefaultMetaSchema() { + super._addDefaultMetaSchema(); + const { $data, meta } = this.opts; + if (!meta) return; + json_schema_2019_09_1.default.call(this, $data); + this.refs["http://json-schema.org/schema"] = META_SCHEMA_ID; + } + defaultMeta() { + return this.opts.defaultMeta = super.defaultMeta() || (this.getSchema(META_SCHEMA_ID) ? META_SCHEMA_ID : void 0); + } + }; + exports.Ajv2019 = Ajv2019; + module.exports = exports = Ajv2019; + module.exports.Ajv2019 = Ajv2019; + Object.defineProperty(exports, "__esModule", { value: true }); + exports.default = Ajv2019; + var validate_1 = require_validate(); + Object.defineProperty(exports, "KeywordCxt", { + enumerable: true, + get: function() { + return validate_1.KeywordCxt; + } + }); + var codegen_1 = require_codegen(); + Object.defineProperty(exports, "_", { + enumerable: true, + get: function() { + return codegen_1._; + } + }); + Object.defineProperty(exports, "str", { + enumerable: true, + get: function() { + return codegen_1.str; + } + }); + Object.defineProperty(exports, "stringify", { + enumerable: true, + get: function() { + return codegen_1.stringify; + } + }); + Object.defineProperty(exports, "nil", { + enumerable: true, + get: function() { + return codegen_1.nil; + } + }); + Object.defineProperty(exports, "Name", { + enumerable: true, + get: function() { + return codegen_1.Name; + } + }); + Object.defineProperty(exports, "CodeGen", { + enumerable: true, + get: function() { + return codegen_1.CodeGen; + } + }); + var validation_error_1 = require_validation_error(); + Object.defineProperty(exports, "ValidationError", { + enumerable: true, + get: function() { + return validation_error_1.default; + } + }); + var ref_error_1 = require_ref_error(); + Object.defineProperty(exports, "MissingRefError", { + enumerable: true, + get: function() { + return ref_error_1.default; + } + }); +})); + +//#endregion +//#region ../../node_modules/.pnpm/ajv@8.18.0/node_modules/ajv/dist/vocabularies/draft2020.js +var require_draft2020 = /* @__PURE__ */ __commonJSMin(((exports) => { + Object.defineProperty(exports, "__esModule", { value: true }); + const core_1 = require_core$2(); + const validation_1 = require_validation$2(); + const applicator_1 = require_applicator$2(); + const dynamic_1 = require_dynamic(); + const next_1 = require_next(); + const unevaluated_1 = require_unevaluated$1(); + const format_1 = require_format$1(); + const metadata_1 = require_metadata(); + const draft2020Vocabularies = [ + dynamic_1.default, + core_1.default, + validation_1.default, + (0, applicator_1.default)(true), + format_1.default, + metadata_1.metadataVocabulary, + metadata_1.contentVocabulary, + next_1.default, + unevaluated_1.default + ]; + exports.default = draft2020Vocabularies; +})); + +//#endregion +//#region ../../node_modules/.pnpm/ajv@8.18.0/node_modules/ajv/dist/refs/json-schema-2020-12/schema.json +var require_schema = /* @__PURE__ */ __commonJSMin(((exports, module) => { + module.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": true, + "https://json-schema.org/draft/2020-12/vocab/applicator": true, + "https://json-schema.org/draft/2020-12/vocab/unevaluated": true, + "https://json-schema.org/draft/2020-12/vocab/validation": true, + "https://json-schema.org/draft/2020-12/vocab/meta-data": true, + "https://json-schema.org/draft/2020-12/vocab/format-annotation": true, + "https://json-schema.org/draft/2020-12/vocab/content": true + }, + "$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": true, + "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": true, + "default": {} + }, + "$recursiveAnchor": { + "$comment": "\"$recursiveAnchor\" has been replaced by \"$dynamicAnchor\".", + "$ref": "meta/core#/$defs/anchorString", + "deprecated": true + }, + "$recursiveRef": { + "$comment": "\"$recursiveRef\" has been replaced by \"$dynamicRef\".", + "$ref": "meta/core#/$defs/uriReferenceString", + "deprecated": true + } + } + }; +})); + +//#endregion +//#region ../../node_modules/.pnpm/ajv@8.18.0/node_modules/ajv/dist/refs/json-schema-2020-12/meta/applicator.json +var require_applicator = /* @__PURE__ */ __commonJSMin(((exports, module) => { + module.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": true }, + "$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" } + } } + }; +})); + +//#endregion +//#region ../../node_modules/.pnpm/ajv@8.18.0/node_modules/ajv/dist/refs/json-schema-2020-12/meta/unevaluated.json +var require_unevaluated = /* @__PURE__ */ __commonJSMin(((exports, module) => { + module.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": true }, + "$dynamicAnchor": "meta", + "title": "Unevaluated applicator vocabulary meta-schema", + "type": ["object", "boolean"], + "properties": { + "unevaluatedItems": { "$dynamicRef": "#meta" }, + "unevaluatedProperties": { "$dynamicRef": "#meta" } + } + }; +})); + +//#endregion +//#region ../../node_modules/.pnpm/ajv@8.18.0/node_modules/ajv/dist/refs/json-schema-2020-12/meta/content.json +var require_content = /* @__PURE__ */ __commonJSMin(((exports, module) => { + module.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": true }, + "$dynamicAnchor": "meta", + "title": "Content vocabulary meta-schema", + "type": ["object", "boolean"], + "properties": { + "contentEncoding": { "type": "string" }, + "contentMediaType": { "type": "string" }, + "contentSchema": { "$dynamicRef": "#meta" } + } + }; +})); + +//#endregion +//#region ../../node_modules/.pnpm/ajv@8.18.0/node_modules/ajv/dist/refs/json-schema-2020-12/meta/core.json +var require_core = /* @__PURE__ */ __commonJSMin(((exports, module) => { + module.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": true }, + "$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" + } + } + }; +})); + +//#endregion +//#region ../../node_modules/.pnpm/ajv@8.18.0/node_modules/ajv/dist/refs/json-schema-2020-12/meta/format-annotation.json +var require_format_annotation = /* @__PURE__ */ __commonJSMin(((exports, module) => { + module.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": true }, + "$dynamicAnchor": "meta", + "title": "Format vocabulary meta-schema for annotation results", + "type": ["object", "boolean"], + "properties": { "format": { "type": "string" } } + }; +})); + +//#endregion +//#region ../../node_modules/.pnpm/ajv@8.18.0/node_modules/ajv/dist/refs/json-schema-2020-12/meta/meta-data.json +var require_meta_data = /* @__PURE__ */ __commonJSMin(((exports, module) => { + module.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": true }, + "$dynamicAnchor": "meta", + "title": "Meta-data vocabulary meta-schema", + "type": ["object", "boolean"], + "properties": { + "title": { "type": "string" }, + "description": { "type": "string" }, + "default": true, + "deprecated": { + "type": "boolean", + "default": false + }, + "readOnly": { + "type": "boolean", + "default": false + }, + "writeOnly": { + "type": "boolean", + "default": false + }, + "examples": { + "type": "array", + "items": true + } + } + }; +})); + +//#endregion +//#region ../../node_modules/.pnpm/ajv@8.18.0/node_modules/ajv/dist/refs/json-schema-2020-12/meta/validation.json +var require_validation = /* @__PURE__ */ __commonJSMin(((exports, module) => { + module.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": true }, + "$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": true + }] }, + "const": true, + "enum": { + "type": "array", + "items": true + }, + "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": false + }, + "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": true, + "default": [] + } + } + }; +})); + +//#endregion +//#region ../../node_modules/.pnpm/ajv@8.18.0/node_modules/ajv/dist/refs/json-schema-2020-12/index.js +var require_json_schema_2020_12 = /* @__PURE__ */ __commonJSMin(((exports) => { + Object.defineProperty(exports, "__esModule", { value: true }); + const metaSchema = require_schema(); + const applicator = require_applicator(); + const unevaluated = require_unevaluated(); + const content = require_content(); + const core = require_core(); + const format = require_format_annotation(); + const metadata = require_meta_data(); + const validation = require_validation(); + const META_SUPPORT_DATA = ["/properties"]; + function addMetaSchema2020($data) { + [ + metaSchema, + applicator, + unevaluated, + content, + core, + with$data(this, format), + metadata, + with$data(this, validation) + ].forEach((sch) => this.addMetaSchema(sch, void 0, false)); + return this; + function with$data(ajv, sch) { + return $data ? ajv.$dataMetaSchema(sch, META_SUPPORT_DATA) : sch; + } + } + exports.default = addMetaSchema2020; +})); + +//#endregion +//#region ../../node_modules/.pnpm/ajv@8.18.0/node_modules/ajv/dist/2020.js +var require__2020 = /* @__PURE__ */ __commonJSMin(((exports, module) => { + Object.defineProperty(exports, "__esModule", { value: true }); + exports.MissingRefError = exports.ValidationError = exports.CodeGen = exports.Name = exports.nil = exports.stringify = exports.str = exports._ = exports.KeywordCxt = exports.Ajv2020 = void 0; + const core_1 = require_core$3(); + const draft2020_1 = require_draft2020(); + const discriminator_1 = require_discriminator(); + const json_schema_2020_12_1 = require_json_schema_2020_12(); + const META_SCHEMA_ID = "https://json-schema.org/draft/2020-12/schema"; + var Ajv2020 = class extends core_1.default { + constructor(opts = {}) { + super({ + ...opts, + dynamicRef: true, + next: true, + unevaluated: true + }); + } + _addVocabularies() { + super._addVocabularies(); + draft2020_1.default.forEach((v) => this.addVocabulary(v)); + if (this.opts.discriminator) this.addKeyword(discriminator_1.default); + } + _addDefaultMetaSchema() { + super._addDefaultMetaSchema(); + const { $data, meta } = this.opts; + if (!meta) return; + json_schema_2020_12_1.default.call(this, $data); + this.refs["http://json-schema.org/schema"] = META_SCHEMA_ID; + } + defaultMeta() { + return this.opts.defaultMeta = super.defaultMeta() || (this.getSchema(META_SCHEMA_ID) ? META_SCHEMA_ID : void 0); + } + }; + exports.Ajv2020 = Ajv2020; + module.exports = exports = Ajv2020; + module.exports.Ajv2020 = Ajv2020; + Object.defineProperty(exports, "__esModule", { value: true }); + exports.default = Ajv2020; + var validate_1 = require_validate(); + Object.defineProperty(exports, "KeywordCxt", { + enumerable: true, + get: function() { + return validate_1.KeywordCxt; + } + }); + var codegen_1 = require_codegen(); + Object.defineProperty(exports, "_", { + enumerable: true, + get: function() { + return codegen_1._; + } + }); + Object.defineProperty(exports, "str", { + enumerable: true, + get: function() { + return codegen_1.str; + } + }); + Object.defineProperty(exports, "stringify", { + enumerable: true, + get: function() { + return codegen_1.stringify; + } + }); + Object.defineProperty(exports, "nil", { + enumerable: true, + get: function() { + return codegen_1.nil; + } + }); + Object.defineProperty(exports, "Name", { + enumerable: true, + get: function() { + return codegen_1.Name; + } + }); + Object.defineProperty(exports, "CodeGen", { + enumerable: true, + get: function() { + return codegen_1.CodeGen; + } + }); + var validation_error_1 = require_validation_error(); + Object.defineProperty(exports, "ValidationError", { + enumerable: true, + get: function() { + return validation_error_1.default; + } + }); + var ref_error_1 = require_ref_error(); + Object.defineProperty(exports, "MissingRefError", { + enumerable: true, + get: function() { + return ref_error_1.default; + } + }); +})); + +//#endregion +//#region ../../node_modules/.pnpm/ajv-formats@3.0.1_ajv@8.18.0/node_modules/ajv-formats/dist/formats.js +var require_formats = /* @__PURE__ */ __commonJSMin(((exports) => { + Object.defineProperty(exports, "__esModule", { value: true }); + exports.formatNames = exports.fastFormats = exports.fullFormats = void 0; + function fmtDef(validate, compare) { + return { + validate, + compare + }; + } + exports.fullFormats = { + date: fmtDef(date, compareDate), + time: fmtDef(getTime(true), compareTime), + "date-time": fmtDef(getDateTime(true), compareDateTime), + "iso-time": fmtDef(getTime(), compareIsoTime), + "iso-date-time": fmtDef(getDateTime(), compareIsoDateTime), + duration: /^P(?!$)((\d+Y)?(\d+M)?(\d+D)?(T(?=\d)(\d+H)?(\d+M)?(\d+S)?)?|(\d+W)?)$/, + uri, + "uri-reference": /^(?:[a-z][a-z0-9+\-.]*:)?(?:\/?\/(?:(?:[a-z0-9\-._~!$&'()*+,;=:]|%[0-9a-f]{2})*@)?(?:\[(?:(?:(?:(?:[0-9a-f]{1,4}:){6}|::(?:[0-9a-f]{1,4}:){5}|(?:[0-9a-f]{1,4})?::(?:[0-9a-f]{1,4}:){4}|(?:(?:[0-9a-f]{1,4}:){0,1}[0-9a-f]{1,4})?::(?:[0-9a-f]{1,4}:){3}|(?:(?:[0-9a-f]{1,4}:){0,2}[0-9a-f]{1,4})?::(?:[0-9a-f]{1,4}:){2}|(?:(?:[0-9a-f]{1,4}:){0,3}[0-9a-f]{1,4})?::[0-9a-f]{1,4}:|(?:(?:[0-9a-f]{1,4}:){0,4}[0-9a-f]{1,4})?::)(?:[0-9a-f]{1,4}:[0-9a-f]{1,4}|(?:(?:25[0-5]|2[0-4]\d|[01]?\d\d?)\.){3}(?:25[0-5]|2[0-4]\d|[01]?\d\d?))|(?:(?:[0-9a-f]{1,4}:){0,5}[0-9a-f]{1,4})?::[0-9a-f]{1,4}|(?:(?:[0-9a-f]{1,4}:){0,6}[0-9a-f]{1,4})?::)|[Vv][0-9a-f]+\.[a-z0-9\-._~!$&'()*+,;=:]+)\]|(?:(?:25[0-5]|2[0-4]\d|[01]?\d\d?)\.){3}(?:25[0-5]|2[0-4]\d|[01]?\d\d?)|(?:[a-z0-9\-._~!$&'"()*+,;=]|%[0-9a-f]{2})*)(?::\d*)?(?:\/(?:[a-z0-9\-._~!$&'"()*+,;=:@]|%[0-9a-f]{2})*)*|\/(?:(?:[a-z0-9\-._~!$&'"()*+,;=:@]|%[0-9a-f]{2})+(?:\/(?:[a-z0-9\-._~!$&'"()*+,;=:@]|%[0-9a-f]{2})*)*)?|(?:[a-z0-9\-._~!$&'"()*+,;=:@]|%[0-9a-f]{2})+(?:\/(?:[a-z0-9\-._~!$&'"()*+,;=:@]|%[0-9a-f]{2})*)*)?(?:\?(?:[a-z0-9\-._~!$&'"()*+,;=:@/?]|%[0-9a-f]{2})*)?(?:#(?:[a-z0-9\-._~!$&'"()*+,;=:@/?]|%[0-9a-f]{2})*)?$/i, + "uri-template": /^(?:(?:[^\x00-\x20"'<>%\\^`{|}]|%[0-9a-f]{2})|\{[+#./;?&=,!@|]?(?:[a-z0-9_]|%[0-9a-f]{2})+(?::[1-9][0-9]{0,3}|\*)?(?:,(?:[a-z0-9_]|%[0-9a-f]{2})+(?::[1-9][0-9]{0,3}|\*)?)*\})*$/i, + url: /^(?:https?|ftp):\/\/(?:\S+(?::\S*)?@)?(?:(?!(?:10|127)(?:\.\d{1,3}){3})(?!(?:169\.254|192\.168)(?:\.\d{1,3}){2})(?!172\.(?:1[6-9]|2\d|3[0-1])(?:\.\d{1,3}){2})(?:[1-9]\d?|1\d\d|2[01]\d|22[0-3])(?:\.(?:1?\d{1,2}|2[0-4]\d|25[0-5])){2}(?:\.(?:[1-9]\d?|1\d\d|2[0-4]\d|25[0-4]))|(?:(?:[a-z0-9\u{00a1}-\u{ffff}]+-)*[a-z0-9\u{00a1}-\u{ffff}]+)(?:\.(?:[a-z0-9\u{00a1}-\u{ffff}]+-)*[a-z0-9\u{00a1}-\u{ffff}]+)*(?:\.(?:[a-z\u{00a1}-\u{ffff}]{2,})))(?::\d{2,5})?(?:\/[^\s]*)?$/iu, + email: /^[a-z0-9!#$%&'*+/=?^_`{|}~-]+(?:\.[a-z0-9!#$%&'*+/=?^_`{|}~-]+)*@(?:[a-z0-9](?:[a-z0-9-]*[a-z0-9])?\.)+[a-z0-9](?:[a-z0-9-]*[a-z0-9])?$/i, + hostname: /^(?=.{1,253}\.?$)[a-z0-9](?:[a-z0-9-]{0,61}[a-z0-9])?(?:\.[a-z0-9](?:[-0-9a-z]{0,61}[0-9a-z])?)*\.?$/i, + ipv4: /^(?:(?:25[0-5]|2[0-4]\d|1\d\d|[1-9]?\d)\.){3}(?:25[0-5]|2[0-4]\d|1\d\d|[1-9]?\d)$/, + ipv6: /^((([0-9a-f]{1,4}:){7}([0-9a-f]{1,4}|:))|(([0-9a-f]{1,4}:){6}(:[0-9a-f]{1,4}|((25[0-5]|2[0-4]\d|1\d\d|[1-9]?\d)(\.(25[0-5]|2[0-4]\d|1\d\d|[1-9]?\d)){3})|:))|(([0-9a-f]{1,4}:){5}(((:[0-9a-f]{1,4}){1,2})|:((25[0-5]|2[0-4]\d|1\d\d|[1-9]?\d)(\.(25[0-5]|2[0-4]\d|1\d\d|[1-9]?\d)){3})|:))|(([0-9a-f]{1,4}:){4}(((:[0-9a-f]{1,4}){1,3})|((:[0-9a-f]{1,4})?:((25[0-5]|2[0-4]\d|1\d\d|[1-9]?\d)(\.(25[0-5]|2[0-4]\d|1\d\d|[1-9]?\d)){3}))|:))|(([0-9a-f]{1,4}:){3}(((:[0-9a-f]{1,4}){1,4})|((:[0-9a-f]{1,4}){0,2}:((25[0-5]|2[0-4]\d|1\d\d|[1-9]?\d)(\.(25[0-5]|2[0-4]\d|1\d\d|[1-9]?\d)){3}))|:))|(([0-9a-f]{1,4}:){2}(((:[0-9a-f]{1,4}){1,5})|((:[0-9a-f]{1,4}){0,3}:((25[0-5]|2[0-4]\d|1\d\d|[1-9]?\d)(\.(25[0-5]|2[0-4]\d|1\d\d|[1-9]?\d)){3}))|:))|(([0-9a-f]{1,4}:){1}(((:[0-9a-f]{1,4}){1,6})|((:[0-9a-f]{1,4}){0,4}:((25[0-5]|2[0-4]\d|1\d\d|[1-9]?\d)(\.(25[0-5]|2[0-4]\d|1\d\d|[1-9]?\d)){3}))|:))|(:(((:[0-9a-f]{1,4}){1,7})|((:[0-9a-f]{1,4}){0,5}:((25[0-5]|2[0-4]\d|1\d\d|[1-9]?\d)(\.(25[0-5]|2[0-4]\d|1\d\d|[1-9]?\d)){3}))|:)))$/i, + regex, + 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, + int32: { + type: "number", + validate: validateInt32 + }, + int64: { + type: "number", + validate: validateInt64 + }, + float: { + type: "number", + validate: validateNumber + }, + double: { + type: "number", + validate: validateNumber + }, + password: true, + binary: true + }; + exports.fastFormats = { + ...exports.fullFormats, + date: fmtDef(/^\d\d\d\d-[0-1]\d-[0-3]\d$/, compareDate), + time: fmtDef(/^(?:[0-2]\d:[0-5]\d:[0-5]\d|23:59:60)(?:\.\d+)?(?:z|[+-]\d\d(?::?\d\d)?)$/i, compareTime), + "date-time": fmtDef(/^\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, compareDateTime), + "iso-time": fmtDef(/^(?:[0-2]\d:[0-5]\d:[0-5]\d|23:59:60)(?:\.\d+)?(?:z|[+-]\d\d(?::?\d\d)?)?$/i, compareIsoTime), + "iso-date-time": fmtDef(/^\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, compareIsoDateTime), + uri: /^(?:[a-z][a-z0-9+\-.]*:)(?:\/?\/)?[^\s]*$/i, + "uri-reference": /^(?:(?:[a-z][a-z0-9+\-.]*:)?\/?\/)?(?:[^\\\s#][^\s#]*)?(?:#[^\\\s]*)?$/i, + email: /^[a-z0-9.!#$%&'*+/=?^_`{|}~-]+@[a-z0-9](?:[a-z0-9-]{0,61}[a-z0-9])?(?:\.[a-z0-9](?:[a-z0-9-]{0,61}[a-z0-9])?)*$/i + }; + exports.formatNames = Object.keys(exports.fullFormats); + function isLeapYear(year) { + return year % 4 === 0 && (year % 100 !== 0 || year % 400 === 0); + } + const DATE = /^(\d\d\d\d)-(\d\d)-(\d\d)$/; + const DAYS = [ + 0, + 31, + 28, + 31, + 30, + 31, + 30, + 31, + 31, + 30, + 31, + 30, + 31 + ]; + function date(str) { + const matches = DATE.exec(str); + if (!matches) return false; + const year = +matches[1]; + const month = +matches[2]; + const day = +matches[3]; + return month >= 1 && month <= 12 && day >= 1 && day <= (month === 2 && isLeapYear(year) ? 29 : DAYS[month]); + } + function compareDate(d1, d2) { + if (!(d1 && d2)) return void 0; + if (d1 > d2) return 1; + if (d1 < d2) return -1; + return 0; + } + const TIME = /^(\d\d):(\d\d):(\d\d(?:\.\d+)?)(z|([+-])(\d\d)(?::?(\d\d))?)?$/i; + function getTime(strictTimeZone) { + return function time(str) { + const matches = TIME.exec(str); + if (!matches) return false; + const hr = +matches[1]; + const min = +matches[2]; + const sec = +matches[3]; + const tz = matches[4]; + const tzSign = matches[5] === "-" ? -1 : 1; + const tzH = +(matches[6] || 0); + const tzM = +(matches[7] || 0); + if (tzH > 23 || tzM > 59 || strictTimeZone && !tz) return false; + if (hr <= 23 && min <= 59 && sec < 60) return true; + const utcMin = min - tzM * tzSign; + const utcHr = hr - tzH * tzSign - (utcMin < 0 ? 1 : 0); + return (utcHr === 23 || utcHr === -1) && (utcMin === 59 || utcMin === -1) && sec < 61; + }; + } + function compareTime(s1, s2) { + if (!(s1 && s2)) return void 0; + const t1 = (/* @__PURE__ */ new Date("2020-01-01T" + s1)).valueOf(); + const t2 = (/* @__PURE__ */ new Date("2020-01-01T" + s2)).valueOf(); + if (!(t1 && t2)) return void 0; + return t1 - t2; + } + function compareIsoTime(t1, t2) { + if (!(t1 && t2)) return void 0; + const a1 = TIME.exec(t1); + const a2 = TIME.exec(t2); + if (!(a1 && a2)) return void 0; + t1 = a1[1] + a1[2] + a1[3]; + t2 = a2[1] + a2[2] + a2[3]; + if (t1 > t2) return 1; + if (t1 < t2) return -1; + return 0; + } + const DATE_TIME_SEPARATOR = /t|\s/i; + function getDateTime(strictTimeZone) { + const time = getTime(strictTimeZone); + return function date_time(str) { + const dateTime = str.split(DATE_TIME_SEPARATOR); + return dateTime.length === 2 && date(dateTime[0]) && time(dateTime[1]); + }; + } + function compareDateTime(dt1, dt2) { + if (!(dt1 && dt2)) return void 0; + const d1 = new Date(dt1).valueOf(); + const d2 = new Date(dt2).valueOf(); + if (!(d1 && d2)) return void 0; + return d1 - d2; + } + function compareIsoDateTime(dt1, dt2) { + if (!(dt1 && dt2)) return void 0; + const [d1, t1] = dt1.split(DATE_TIME_SEPARATOR); + const [d2, t2] = dt2.split(DATE_TIME_SEPARATOR); + const res = compareDate(d1, d2); + if (res === void 0) return void 0; + return res || compareTime(t1, t2); + } + const NOT_URI_FRAGMENT = /\/|:/; + const URI = /^(?:[a-z][a-z0-9+\-.]*:)(?:\/?\/(?:(?:[a-z0-9\-._~!$&'()*+,;=:]|%[0-9a-f]{2})*@)?(?:\[(?:(?:(?:(?:[0-9a-f]{1,4}:){6}|::(?:[0-9a-f]{1,4}:){5}|(?:[0-9a-f]{1,4})?::(?:[0-9a-f]{1,4}:){4}|(?:(?:[0-9a-f]{1,4}:){0,1}[0-9a-f]{1,4})?::(?:[0-9a-f]{1,4}:){3}|(?:(?:[0-9a-f]{1,4}:){0,2}[0-9a-f]{1,4})?::(?:[0-9a-f]{1,4}:){2}|(?:(?:[0-9a-f]{1,4}:){0,3}[0-9a-f]{1,4})?::[0-9a-f]{1,4}:|(?:(?:[0-9a-f]{1,4}:){0,4}[0-9a-f]{1,4})?::)(?:[0-9a-f]{1,4}:[0-9a-f]{1,4}|(?:(?:25[0-5]|2[0-4]\d|[01]?\d\d?)\.){3}(?:25[0-5]|2[0-4]\d|[01]?\d\d?))|(?:(?:[0-9a-f]{1,4}:){0,5}[0-9a-f]{1,4})?::[0-9a-f]{1,4}|(?:(?:[0-9a-f]{1,4}:){0,6}[0-9a-f]{1,4})?::)|[Vv][0-9a-f]+\.[a-z0-9\-._~!$&'()*+,;=:]+)\]|(?:(?:25[0-5]|2[0-4]\d|[01]?\d\d?)\.){3}(?:25[0-5]|2[0-4]\d|[01]?\d\d?)|(?:[a-z0-9\-._~!$&'()*+,;=]|%[0-9a-f]{2})*)(?::\d*)?(?:\/(?:[a-z0-9\-._~!$&'()*+,;=:@]|%[0-9a-f]{2})*)*|\/(?:(?:[a-z0-9\-._~!$&'()*+,;=:@]|%[0-9a-f]{2})+(?:\/(?:[a-z0-9\-._~!$&'()*+,;=:@]|%[0-9a-f]{2})*)*)?|(?:[a-z0-9\-._~!$&'()*+,;=:@]|%[0-9a-f]{2})+(?:\/(?:[a-z0-9\-._~!$&'()*+,;=:@]|%[0-9a-f]{2})*)*)(?:\?(?:[a-z0-9\-._~!$&'()*+,;=:@/?]|%[0-9a-f]{2})*)?(?:#(?:[a-z0-9\-._~!$&'()*+,;=:@/?]|%[0-9a-f]{2})*)?$/i; + function uri(str) { + return NOT_URI_FRAGMENT.test(str) && URI.test(str); + } + const BYTE = /^(?:[A-Za-z0-9+/]{4})*(?:[A-Za-z0-9+/]{2}==|[A-Za-z0-9+/]{3}=)?$/gm; + function byte(str) { + BYTE.lastIndex = 0; + return BYTE.test(str); + } + const MIN_INT32 = -(2 ** 31); + const MAX_INT32 = 2 ** 31 - 1; + function validateInt32(value) { + return Number.isInteger(value) && value <= MAX_INT32 && value >= MIN_INT32; + } + function validateInt64(value) { + return Number.isInteger(value); + } + function validateNumber() { + return true; + } + const Z_ANCHOR = /[^\\]\\Z/; + function regex(str) { + if (Z_ANCHOR.test(str)) return false; + try { + new RegExp(str); + return true; + } catch (e) { + return false; + } + } +})); + +//#endregion +//#region ../../node_modules/.pnpm/ajv-formats@3.0.1_ajv@8.18.0/node_modules/ajv-formats/dist/limit.js +var require_limit = /* @__PURE__ */ __commonJSMin(((exports) => { + Object.defineProperty(exports, "__esModule", { value: true }); + exports.formatLimitDefinition = void 0; + const ajv_1 = require_ajv(); + const codegen_1 = require_codegen(); + const ops = codegen_1.operators; + const KWDs = { + formatMaximum: { + okStr: "<=", + ok: ops.LTE, + fail: ops.GT + }, + formatMinimum: { + okStr: ">=", + ok: ops.GTE, + fail: ops.LT + }, + formatExclusiveMaximum: { + okStr: "<", + ok: ops.LT, + fail: ops.GTE + }, + formatExclusiveMinimum: { + okStr: ">", + ok: ops.GT, + fail: ops.LTE + } + }; + const error = { + message: ({ keyword, schemaCode }) => (0, codegen_1.str)`should be ${KWDs[keyword].okStr} ${schemaCode}`, + params: ({ keyword, schemaCode }) => (0, codegen_1._)`{comparison: ${KWDs[keyword].okStr}, limit: ${schemaCode}}` + }; + exports.formatLimitDefinition = { + keyword: Object.keys(KWDs), + type: "string", + schemaType: "string", + $data: true, + error, + code(cxt) { + const { gen, data, schemaCode, keyword, it } = cxt; + const { opts, self } = it; + if (!opts.validateFormats) return; + const fCxt = new ajv_1.KeywordCxt(it, self.RULES.all.format.definition, "format"); + if (fCxt.$data) validate$DataFormat(); + else validateFormat(); + function validate$DataFormat() { + const fmts = gen.scopeValue("formats", { + ref: self.formats, + code: opts.code.formats + }); + const fmt = gen.const("fmt", (0, codegen_1._)`${fmts}[${fCxt.schemaCode}]`); + cxt.fail$data((0, codegen_1.or)((0, codegen_1._)`typeof ${fmt} != "object"`, (0, codegen_1._)`${fmt} instanceof RegExp`, (0, codegen_1._)`typeof ${fmt}.compare != "function"`, compareCode(fmt))); + } + function validateFormat() { + const format = fCxt.schema; + const fmtDef = self.formats[format]; + if (!fmtDef || fmtDef === true) return; + if (typeof fmtDef != "object" || fmtDef instanceof RegExp || typeof fmtDef.compare != "function") throw new Error(`"${keyword}": format "${format}" does not define "compare" function`); + const fmt = gen.scopeValue("formats", { + key: format, + ref: fmtDef, + code: opts.code.formats ? (0, codegen_1._)`${opts.code.formats}${(0, codegen_1.getProperty)(format)}` : void 0 + }); + cxt.fail$data(compareCode(fmt)); + } + function compareCode(fmt) { + return (0, codegen_1._)`${fmt}.compare(${data}, ${schemaCode}) ${KWDs[keyword].fail} 0`; + } + }, + dependencies: ["format"] + }; + const formatLimitPlugin = (ajv) => { + ajv.addKeyword(exports.formatLimitDefinition); + return ajv; + }; + exports.default = formatLimitPlugin; +})); + +//#endregion +//#region ../../node_modules/.pnpm/ajv-formats@3.0.1_ajv@8.18.0/node_modules/ajv-formats/dist/index.js +var require_dist = /* @__PURE__ */ __commonJSMin(((exports, module) => { + Object.defineProperty(exports, "__esModule", { value: true }); + const formats_1 = require_formats(); + const limit_1 = require_limit(); + const codegen_1 = require_codegen(); + const fullName = new codegen_1.Name("fullFormats"); + const fastName = new codegen_1.Name("fastFormats"); + const formatsPlugin = (ajv, opts = { keywords: true }) => { + if (Array.isArray(opts)) { + addFormats(ajv, opts, formats_1.fullFormats, fullName); + return ajv; + } + const [formats, exportName] = opts.mode === "fast" ? [formats_1.fastFormats, fastName] : [formats_1.fullFormats, fullName]; + addFormats(ajv, opts.formats || formats_1.formatNames, formats, exportName); + if (opts.keywords) (0, limit_1.default)(ajv); + return ajv; + }; + formatsPlugin.get = (name, mode = "full") => { + const f = (mode === "fast" ? formats_1.fastFormats : formats_1.fullFormats)[name]; + if (!f) throw new Error(`Unknown format "${name}"`); + return f; + }; + function addFormats(ajv, list, fs, exportName) { + var _a; + var _b; + (_a = (_b = ajv.opts.code).formats) !== null && _a !== void 0 || (_b.formats = (0, codegen_1._)`require("ajv-formats/dist/formats").${exportName}`); + for (const f of list) ajv.addFormat(f, fs[f]); + } + module.exports = exports = formatsPlugin; + Object.defineProperty(exports, "__esModule", { value: true }); + exports.default = formatsPlugin; +})); + +//#endregion +//#region ../core-internal/src/validators/ajvProvider.ts +var import_ajv = require_ajv(); +var import__2019 = require__2019(); +var import__2020 = require__2020(); +var import_dist = /* @__PURE__ */ __toESM(require_dist(), 1); +/** `ajv-formats` default export, normalised through the CJS/ESM interop wrapper. */ +const ajvProvider_CEoC_sr_addFormats = import_dist.default; +function createDefaultAjvInstance(engineClass) { + const ajv = new engineClass({ + strict: false, + validateFormats: true, + validateSchema: false, + allErrors: true + }); + ajvProvider_CEoC_sr_addFormats(ajv); + return ajv; +} +/** +* AJV-backed JSON Schema validator. See `@modelcontextprotocol/{client,server}/validators/ajv` +* for the customisation entry point (re-exports `Ajv` and `addFormats` from the bundled copy). +* +* Default dispatches on the schema's declared dialect: no `$schema` or 2020-12 → `Ajv2020` +* (SEP-1613); 2019-09 → `Ajv2019`; draft-07 or draft-06 → the classic draft-07 `Ajv` class +* (draft-07's changes over draft-06 are additive, so one engine covers both). Known draft-07 deviation: classic Ajv +* evaluates keywords adjacent to `$ref` (stricter than draft-07's ignore-siblings rule, matching +* v1's default engine), while the cfworker provider ignores them per spec. +* Schemas declaring any other `$schema` are +* rejected with a plain `Error`; pass a pre-configured Ajv instance to validate +* other dialects. The SDK bundles ajv internally but does not re-export `Ajv2020` (its type +* graph tips downstream declaration bundling — see #2339). To construct a custom 2020-12 +* instance, add `ajv` to your own dependencies (matching the SDK's pinned version) and +* `import { Ajv2020 } from 'ajv/dist/2020.js'` — `new Ajv(...)` is the draft-07 class and would +* silently downgrade dialect. +* +* @example Use with default configuration +* ```ts source="./ajvProvider.examples.ts#AjvJsonSchemaValidator_default" +* const validator = new AjvJsonSchemaValidator(); +* ``` +* +* @example Use with a custom AJV instance +* ```ts source="./ajvProvider.examples.ts#AjvJsonSchemaValidator_customInstance" +* // import { Ajv2020 } from 'ajv/dist/2020.js'; +* const ajv = new Ajv2020({ strict: false, validateSchema: false, allErrors: true }); +* const validator = new AjvJsonSchemaValidator(ajv); +* ``` +* +* @example Register ajv-formats +* ```ts source="./ajvProvider.examples.ts#AjvJsonSchemaValidator_withFormats" +* // import { Ajv2020 } from 'ajv/dist/2020.js'; +* const ajv = new Ajv2020({ strict: false, validateSchema: false, allErrors: true }); +* addFormats(ajv); +* const validator = new AjvJsonSchemaValidator(ajv); +* ``` +*/ +var AjvJsonSchemaValidator = class { + _ajv; + /** Lazy classic (draft-07) engine, built on the first draft-07/draft-06-declared schema. */ + _ajvDraft7; + /** Lazy 2019-09 engine, built on the first 2019-09-declared schema. */ + _ajv2019; + /** True iff the constructor received a caller-supplied engine; the `$schema` dispatch is skipped. */ + _userAjv; + /** + * @param ajv - Optional pre-configured AJV-compatible instance. When supplied, this instance is + * used for **every** schema regardless of its declared `$schema` (the caller owns dialect + * choice). When omitted, the provider constructs per-dialect engines (`Ajv2020`, `Ajv2019`, + * and the classic draft-07 `Ajv` for draft-07/06-declared schemas) with + * `strict: false`, `validateFormats: true`, `validateSchema: false`, `allErrors: true`, and + * `ajv-formats` registered — **lazily, on the first {@linkcode getValidator} call needing each**, so + * constructing the provider (e.g. as the default validator of a `Client`/`Server` that never + * validates a JSON Schema) does not pay the ajv + ajv-formats instantiation cost. The parameter + * is typed structurally so consumers who don't pass an instance need not have `ajv` installed. + */ + constructor(ajv) { + this._userAjv = ajv !== void 0; + this._ajv = ajv; + } + /** The underlying 2020-12 engine — the default instance is created on first use. */ + get ajv() { + return this._ajv ??= createDefaultAjvInstance(import__2020.Ajv2020); + } + /** + * Pick the engine for a schema's declared dialect. A caller-supplied engine is used for + * every schema — do not second-guess by `$schema` (bring-your-own-validator means + * bring-your-own-dialect). Otherwise: no `$schema` or 2020-12 → `Ajv2020`; 2019-09 → + * `Ajv2019`; draft-07 or draft-06 → classic `Ajv`; anything else → `Error`. + */ + _engineFor(schema) { + if (this._userAjv) return this.ajv; + const dialect = declaredDialect(schema, "pass a pre-configured Ajv instance to AjvJsonSchemaValidator(ajv) to validate other dialects."); + if (dialect === "2020-12") return this.ajv; + if (dialect === "2019-09") return this._ajv2019 ??= createDefaultAjvInstance(import__2019.Ajv2019); + return this._ajvDraft7 ??= createDefaultAjvInstance(import_ajv.Ajv); + } + getValidator(schema) { + const engine = this._engineFor(schema); + const ajvValidator = "$id" in schema && typeof schema.$id === "string" ? engine.getSchema(schema.$id) ?? engine.compile(schema) : engine.compile(schema); + return (input) => { + return ajvValidator(input) ? { + valid: true, + data: input, + errorMessage: void 0 + } : { + valid: false, + data: void 0, + errorMessage: engine.errorsText(ajvValidator.errors) + }; + }; + } +}; +/** +* Draft-07 AJV class, re-exported for consumers who need to opt back to the pre-SEP-1613 default. +* The full v1-equivalent construction is: +* +* ```ts +* const ajv = new Ajv({ strict: false, validateFormats: true, validateSchema: false, allErrors: true }); +* addFormats(ajv); +* new AjvJsonSchemaValidator(ajv); +* ``` +* +* (omitting `validateSchema: false` makes a 2020-12-stamped `$schema` fail with an opaque +* "no schema with key or ref …" engine error; omitting `addFormats` silently drops `format` +* validation that the v1 default had). +* +* The SDK bundles ajv internally but does not re-export `Ajv2020` (its type graph tips downstream +* declaration bundling — see #2339). To construct a custom 2020-12 instance, add `ajv` to your own +* dependencies (matching the SDK's pinned version) and `import { Ajv2020 } from 'ajv/dist/2020.js'`. +*/ +const ajvProvider_CEoC_sr_Ajv = import_ajv.Ajv; + +//#endregion + +//# sourceMappingURL=ajvProvider-CEoC__sr.mjs.map + + + + + + + + +//#region src/server/completable.ts +const COMPLETABLE_SYMBOL = Symbol.for("mcp.completable"); +/** +* Wraps a schema to provide autocompletion capabilities. Useful for, e.g., prompt arguments in MCP. +* +* @example +* ```ts source="./completable.examples.ts#completable_basicUsage" +* server.registerPrompt( +* 'review-code', +* { +* title: 'Code Review', +* argsSchema: z.object({ +* language: completable(z.string().describe('Programming language'), value => +* ['typescript', 'javascript', 'python', 'rust', 'go'].filter(lang => lang.startsWith(value)) +* ) +* }) +* }, +* ({ language }) => ({ +* messages: [ +* { +* role: 'user' as const, +* content: { +* type: 'text' as const, +* text: `Review this ${language} code.` +* } +* } +* ] +* }) +* ); +* ``` +* +* @see {@linkcode server/mcp.McpServer.registerPrompt | McpServer.registerPrompt} for using completable schemas in prompt argument definitions +*/ +function completable(schema, complete) { + Object.defineProperty(schema, COMPLETABLE_SYMBOL, { + value: { complete }, + enumerable: false, + writable: false, + configurable: false + }); + return schema; +} +/** +* Checks if a schema is completable (has completion metadata). +*/ +function isCompletable(schema) { + return !!schema && typeof schema === "object" && COMPLETABLE_SYMBOL in schema; +} +/** +* Gets the completer callback from a completable schema, if it exists. +*/ +function getCompleter(schema) { + return schema[COMPLETABLE_SYMBOL]?.complete; +} + +//#endregion +//#region src/server/sseKeepAlive.ts +/** Default interval between SSE keep-alive comment frames. */ +const mcp_DXXb3Vv3_DEFAULT_SSE_KEEP_ALIVE_MS = 15e3; +const MAX_TIMER_DELAY_MS = (/* unused pure expression or super */ null && (2 ** 31 - 1)); +/** Arms an unref'd timer, or disables keep-alive for invalid delays. */ +function mcp_DXXb3Vv3_armSseKeepAlive(intervalMs, onTick) { + if (!Number.isFinite(intervalMs) || intervalMs < 1) return; + const timer = setInterval(onTick, Math.min(intervalMs, MAX_TIMER_DELAY_MS)); + timer.unref?.(); + return timer; +} + +//#endregion +//#region src/server/serverEventBus.ts +/** +* A `ServerEventBus` backed by an in-process listener set. +* +* `publish()` delivers synchronously to the live listener set (a listener +* unsubscribing itself mid-dispatch is safe; the entry's listen-router +* listeners never unsubscribe peers). A throwing listener does not stop +* delivery to the others. +*/ +var mcp_DXXb3Vv3_InMemoryServerEventBus = class { + _listeners = /* @__PURE__ */ new Set(); + /** + * @param onerror - Optional callback for errors thrown by listeners + * during dispatch. + */ + constructor(onerror) { + this.onerror = onerror; + } + publish(event) { + for (const listener of this._listeners) try { + listener(event); + } catch (error) { + this.onerror?.(error instanceof Error ? error : new Error(String(error))); + } + } + subscribe(listener) { + this._listeners.add(listener); + let live = true; + return () => { + if (!live) return; + live = false; + this._listeners.delete(listener); + }; + } + /** The number of currently registered listeners (test/introspection only — the routers track capacity via their own open-subscription set). */ + get listenerCount() { + return this._listeners.size; + } +}; +/** Build a {@linkcode ServerNotifier} over a bus. */ +function mcp_DXXb3Vv3_createServerNotifier(bus) { + return { + toolsChanged: () => bus.publish({ kind: "tools_list_changed" }), + promptsChanged: () => bus.publish({ kind: "prompts_list_changed" }), + resourcesChanged: () => bus.publish({ kind: "resources_list_changed" }), + resourceUpdated: (uri) => bus.publish({ + kind: "resource_updated", + uri + }) + }; +} +/** +* Whether a `subscriptions/listen` filter accepts a given change event. +* +* Pure: no I/O, no mutation. The filter governs ONLY the four +* subscription-gated change types — non-gated notifications never reach the +* bus and are not modeled here. +* +* `resource_updated` matches only when `resourceSubscriptions` is present and +* contains the event's URI exactly (per the spec: "for these resource URIs"). +*/ +function listenFilterAccepts(filter, event) { + switch (event.kind) { + case "tools_list_changed": return filter.toolsListChanged === true; + case "prompts_list_changed": return filter.promptsListChanged === true; + case "resources_list_changed": return filter.resourcesListChanged === true; + case "resource_updated": return filter.resourceSubscriptions !== void 0 && filter.resourceSubscriptions.includes(event.uri); + } +} +/** +* The honored subset of a requested filter: keeps only the fields the client +* explicitly opted in to (drops `false` and absent fields), narrowed against +* the server's declared capabilities when supplied. The serving entry sends +* this back in `notifications/subscriptions/acknowledged` so the ack reflects +* what the server can actually deliver. +* +* - `toolsListChanged` is honored only when `capabilities.tools.listChanged` +* is advertised; likewise `promptsListChanged` / `resourcesListChanged`. +* - `resourceSubscriptions` is honored only when +* `capabilities.resources.subscribe` is advertised. +* +* `capabilities` is optional on this pure helper for test convenience only — +* both wired routers REQUIRE capabilities at the call site (the HTTP router's +* `serve()` takes a required parameter; `StdioListenRouter.serve()` throws +* before `setServerCapabilities()` was called), so the fail-open +* `undefined → honor everything` branch is never reachable on a wired entry. +*/ +function honoredSubset(requested, capabilities) { + const honored = {}; + const allow = (bit) => capabilities === void 0 || bit === true; + if (requested.toolsListChanged === true && allow(capabilities?.tools?.listChanged)) honored.toolsListChanged = true; + if (requested.promptsListChanged === true && allow(capabilities?.prompts?.listChanged)) honored.promptsListChanged = true; + if (requested.resourcesListChanged === true && allow(capabilities?.resources?.listChanged)) honored.resourcesListChanged = true; + if (requested.resourceSubscriptions !== void 0 && requested.resourceSubscriptions.length > 0 && allow(capabilities?.resources?.subscribe)) honored.resourceSubscriptions = [...requested.resourceSubscriptions]; + return honored; +} +/** Map a {@linkcode ServerEvent} onto its wire notification `{method, params}`. */ +function serverEventToNotification(event) { + switch (event.kind) { + case "tools_list_changed": return { method: "notifications/tools/list_changed" }; + case "prompts_list_changed": return { method: "notifications/prompts/list_changed" }; + case "resources_list_changed": return { method: "notifications/resources/list_changed" }; + case "resource_updated": return { + method: "notifications/resources/updated", + params: { uri: event.uri } + }; + } +} + +//#endregion +//#region src/server/listenRouter.ts +/** Default capacity guard: refuse a new subscription when this many are already open. */ +const mcp_DXXb3Vv3_DEFAULT_MAX_SUBSCRIPTIONS = 1024; +function jsonRpcError(id, code, message) { + return Response.json({ + jsonrpc: "2.0", + error: { + code, + message + }, + id + }, { status: 200 }); +} +/** Stamp the subscription id onto a notification's `_meta`. Non-mutating. */ +function stampSubscriptionId(notification, subscriptionId) { + return { + method: notification.method, + params: { + ...notification.params, + _meta: { + ...notification.params?._meta, + [SUBSCRIPTION_ID_META_KEY]: subscriptionId + } + } + }; +} +/** +* Read the requested filter off a `subscriptions/listen` request body. +* Returns the validated filter, or `undefined` when `params.notifications` +* is absent or fails the schema (the caller answers `-32602` — the spec +* marks `notifications` REQUIRED on the listen request). +*/ +function parseListenFilter(message) { + const outcome = codecForVersion(MODERN_WIRE_REVISION).validateRequest("subscriptions/listen", message); + return outcome.ok ? outcome.value.params?.notifications : void 0; +} +function mcp_DXXb3Vv3_createListenRouter(options) { + const { bus, onerror } = options; + const maxSubscriptions = options.maxSubscriptions ?? mcp_DXXb3Vv3_DEFAULT_MAX_SUBSCRIPTIONS; + const keepAliveMs = options.keepAliveMs ?? mcp_DXXb3Vv3_DEFAULT_SSE_KEEP_ALIVE_MS; + const open = /* @__PURE__ */ new Set(); + function serve(message, signal, capabilities, serverInfo) { + if (open.size >= maxSubscriptions) { + onerror?.(/* @__PURE__ */ new Error(`subscriptions/listen refused: subscription limit reached (${maxSubscriptions})`)); + return jsonRpcError(message.id, -32603, "Subscription limit reached"); + } + const filter = parseListenFilter(message); + if (filter === void 0) return jsonRpcError(message.id, -32602, "Invalid params: 'notifications' is required and must be a valid SubscriptionFilter"); + const honored = honoredSubset(filter, capabilities); + const subscriptionId = message.id; + const encoder = new TextEncoder(); + let controller; + let closed = false; + let unsubscribe; + let keepAliveTimer; + let abortCleanup; + const writeFrame = (frame) => { + if (closed) return; + try { + controller.enqueue(encoder.encode(frame)); + } catch (error) { + onerror?.(error instanceof Error ? error : new Error(String(error))); + } + }; + const writeNotification = (method, params) => { + writeFrame(`event: message\ndata: ${JSON.stringify({ + jsonrpc: "2.0", + method, + params + })}\n\n`); + }; + const teardown = (graceful) => { + if (closed) return; + if (graceful) writeFrame(`event: message\ndata: ${JSON.stringify({ + jsonrpc: "2.0", + id: subscriptionId, + result: { + resultType: "complete", + _meta: { + [SUBSCRIPTION_ID_META_KEY]: subscriptionId, + [SERVER_INFO_META_KEY]: serverInfo + } + } + })}\n\n`); + closed = true; + try { + unsubscribe?.(); + } catch (error) { + onerror?.(error instanceof Error ? error : new Error(String(error))); + } + if (keepAliveTimer !== void 0) clearInterval(keepAliveTimer); + abortCleanup?.(); + open.delete(teardown); + try { + controller.close(); + } catch {} + }; + const readable = new ReadableStream({ + start(streamController) { + controller = streamController; + const ack = stampSubscriptionId({ + method: "notifications/subscriptions/acknowledged", + params: { notifications: honored } + }, subscriptionId); + writeNotification(ack.method, ack.params); + unsubscribe = bus.subscribe((event) => { + if (closed || !listenFilterAccepts(honored, event)) return; + const note = stampSubscriptionId(serverEventToNotification(event), subscriptionId); + writeNotification(note.method, note.params); + }); + keepAliveTimer = mcp_DXXb3Vv3_armSseKeepAlive(keepAliveMs, () => writeFrame(": keepalive\n\n")); + open.add(teardown); + }, + cancel() { + teardown(false); + } + }); + if (signal !== void 0) if (signal.aborted) teardown(false); + else { + const onAbort = () => teardown(false); + signal.addEventListener("abort", onAbort, { once: true }); + abortCleanup = () => signal.removeEventListener("abort", onAbort); + } + return new Response(readable, { + status: 200, + headers: { + "Content-Type": "text/event-stream", + "Cache-Control": "no-cache, no-transform", + Connection: "keep-alive", + "X-Accel-Buffering": "no" + } + }); + } + return { + serve, + closeAll() { + for (const teardown of open) teardown(true); + }, + get openCount() { + return open.size; + } + }; +} +const CHANGE_NOTIFICATION_METHODS = new Set([ + "notifications/tools/list_changed", + "notifications/prompts/list_changed", + "notifications/resources/list_changed", + "notifications/resources/updated" +]); +/** +* Per-connection listen state for the stdio entry. One instance is held by +* `serveStdio` for the connection lifetime; it routes inbound +* `subscriptions/listen` / `notifications/cancelled` and rewrites outbound +* change notifications onto the active subscriptions. No bus — the long-lived +* pinned instance's existing `send*ListChanged()` calls feed straight into +* `routeOutbound()`. +*/ +var mcp_DXXb3Vv3_StdioListenRouter = class { + /** Active subscriptions, keyed by the listen request's JSON-RPC id verbatim. */ + _subs = /* @__PURE__ */ new Map(); + /** + * The serving instance's declared capabilities. Filled in by the entry + * once the modern instance is constructed (the router is created before + * the instance exists), so the acknowledged filter is narrowed against + * what the server can actually deliver. + */ + _serverCapabilities; + /** + * The serving instance's identity, stamped onto the graceful-close + * results' `_meta` (the spec's `SubscriptionsListenResultMeta` extends + * `ResultMetaObject`). Handed over together with the capabilities. + */ + _serverInfo; + constructor(_maxSubscriptions = mcp_DXXb3Vv3_DEFAULT_MAX_SUBSCRIPTIONS, serverCapabilities, serverInfo) { + this._maxSubscriptions = _maxSubscriptions; + this._serverCapabilities = serverCapabilities; + this._serverInfo = serverInfo; + } + /** + * Record the serving instance's declared capabilities and identity once + * it has been constructed. Called by `serveStdio`'s connect path; + * subsequent `serve()` calls narrow the honored filter against the + * capabilities, and `teardownAll()` stamps the identity. + */ + setServerCapabilities(capabilities, serverInfo) { + this._serverCapabilities = capabilities; + if (serverInfo !== void 0) this._serverInfo = serverInfo; + } + /** Whether `id` is an active listen subscription on this connection. */ + has(id) { + return this._subs.has(id); + } + /** + * Serve one inbound `subscriptions/listen` request: registers the + * subscription and returns the stamped acknowledged notification (or, on + * capacity / params rejection, the in-band JSON-RPC error response). + * + * @throws when called before {@linkcode setServerCapabilities} (or the + * constructor) has supplied the serving instance's capabilities. Honoring a + * filter without knowing the server's advertised capabilities would fail + * open (deliver unadvertised types); the entry guarantees capabilities are + * set before any listen request is routed here. + */ + serve(message) { + if (this._serverCapabilities === void 0) throw new Error("StdioListenRouter.serve() called before setServerCapabilities(); refusing to honor a filter without capabilities"); + if (this._subs.size >= this._maxSubscriptions) return { + jsonrpc: "2.0", + id: message.id, + error: { + code: -32603, + message: "Subscription limit reached" + } + }; + const filter = parseListenFilter(message); + if (filter === void 0) return { + jsonrpc: "2.0", + id: message.id, + error: { + code: -32602, + message: "Invalid params: 'notifications' is required and must be a valid SubscriptionFilter" + } + }; + const honored = honoredSubset(filter, this._serverCapabilities); + this._subs.set(message.id, honored); + return stampSubscriptionId({ + method: "notifications/subscriptions/acknowledged", + params: { notifications: honored } + }, message.id); + } + /** + * Tear down one subscription (inbound `notifications/cancelled`). Returns + * `true` when a subscription was removed. After this call NOTHING further + * is delivered for that subscription id (the post-cancel hardening). + */ + cancel(id) { + return this._subs.delete(id); + } + /** + * Route an outbound notification through the active subscriptions. + * + * - For a subscription-gated change notification, returns one stamped copy + * per subscription that opted in to it (an empty array means it is + * dropped — the modern era never delivers an un-requested change type). + * - For any other outbound message, returns `'passthrough'` (the entry + * forwards it as-is). + */ + routeOutbound(message) { + if (!CHANGE_NOTIFICATION_METHODS.has(message.method)) return "passthrough"; + const uriParam = message.params?.["uri"]; + const uri = typeof uriParam === "string" ? uriParam : void 0; + const event = notificationToServerEvent(message.method, uri); + const out = []; + for (const [subscriptionId, filter] of this._subs) if (listenFilterAccepts(filter, event)) out.push(stampSubscriptionId({ + method: message.method, + params: message.params ?? {} + }, subscriptionId)); + return out; + } + /** + * Server-side graceful teardown of every active subscription: returns the + * empty `subscriptions/listen` JSON-RPC result for each subscription id — + * the spec's graceful-close signal, `_meta` carrying the subscription id + * and the serving instance's identity — for the entry to emit before + * closing the wire. Clears the set so nothing further is delivered. + */ + teardownAll() { + const out = []; + for (const id of this._subs.keys()) out.push({ + jsonrpc: "2.0", + id, + result: { + resultType: "complete", + _meta: { + [SUBSCRIPTION_ID_META_KEY]: id, + ...this._serverInfo !== void 0 && { [SERVER_INFO_META_KEY]: this._serverInfo } + } + } + }); + this._subs.clear(); + return out; + } +}; +function notificationToServerEvent(method, uri) { + switch (method) { + case "notifications/tools/list_changed": return { kind: "tools_list_changed" }; + case "notifications/prompts/list_changed": return { kind: "prompts_list_changed" }; + case "notifications/resources/list_changed": return { kind: "resources_list_changed" }; + default: return { + kind: "resource_updated", + uri: uri ?? "" + }; + } +} + +//#endregion +//#region src/server/legacyInputRequiredShim.ts +/** +* Default handler re-entries per originating request — tighter than the +* client driver's 10 because the shim holds a live wire request open. +*/ +const DEFAULT_LEGACY_SHIM_MAX_ROUNDS = 8; +/** Default per-leg timeout: legs are human-paced, so the 60s protocol default is wrong. */ +const DEFAULT_LEGACY_SHIM_ROUND_TIMEOUT_MS = 6e5; +/** Resolves and validates `ServerOptions.inputRequired`, failing loudly at construction time. */ +function resolveLegacyShimOptions(options) { + if (options?.maxRounds !== void 0 && (!Number.isInteger(options.maxRounds) || options.maxRounds < 1)) throw new RangeError(`inputRequired.maxRounds must be a positive integer (got ${options.maxRounds})`); + if (options?.roundTimeoutMs !== void 0 && (!Number.isFinite(options.roundTimeoutMs) || options.roundTimeoutMs <= 0)) throw new RangeError(`inputRequired.roundTimeoutMs must be a positive number (got ${options.roundTimeoutMs})`); + return { + maxRounds: options?.maxRounds ?? DEFAULT_LEGACY_SHIM_MAX_ROUNDS, + roundTimeoutMs: options?.roundTimeoutMs ?? DEFAULT_LEGACY_SHIM_ROUND_TIMEOUT_MS, + legacyShim: options?.legacyShim ?? true + }; +} +/** +* Validates one `inputRequests` entry: malformed or unknown kinds are server +* bugs and fail loudly on both eras. Shared by the modern seam's capability +* check and the shim's gate. +*/ +function coerceEmbeddedInputRequest(method, key, entry) { + if (entry === null || typeof entry !== "object" || typeof entry.method !== "string") throw new src_CX2iR2pK_ProtocolError(src_CX2iR2pK_ProtocolErrorCode.InternalError, `Handler for ${method} returned an invalid input request '${key}': each inputRequests entry must be an embedded elicitation/create, sampling/createMessage, or roots/list request`); + const embedded = entry; + const required = requiredClientCapabilitiesForInputRequest(embedded); + if (required === void 0) throw new src_CX2iR2pK_ProtocolError(src_CX2iR2pK_ProtocolErrorCode.InternalError, `Handler for ${method} returned an input request '${key}' of kind '${embedded.method}', which is not an embedded request the 2026-07-28 revision defines`); + return { + embedded, + required + }; +} +/** +* The 2025-11-25 URL-mode wire shape requires an `elicitationId`; the 2026 +* in-band shape has none, so URL legs mint one (CSPRNG-backed, with a +* getRandomValues fallback for runtimes without `randomUUID`). +*/ +function syntheticElicitationId() { + const webCrypto = globalThis.crypto; + if (webCrypto?.randomUUID !== void 0) return webCrypto.randomUUID(); + const bytes = new Uint8Array(16); + webCrypto.getRandomValues(bytes); + bytes[6] = bytes[6] & 15 | 64; + bytes[8] = bytes[8] & 63 | 128; + const hex = [...bytes].map((byte) => byte.toString(16).padStart(2, "0")).join(""); + return `${hex.slice(0, 8)}-${hex.slice(8, 12)}-${hex.slice(12, 16)}-${hex.slice(16, 20)}-${hex.slice(20)}`; +} +/** Per-family surfacing: tools/call → isError result (the 2025 idiom); prompts/resources → JSON-RPC error. */ +function legacyShimFailure(method, message) { + if (method === "tools/call") return { + content: [{ + type: "text", + text: message + }], + isError: true + }; + throw new src_CX2iR2pK_ProtocolError(src_CX2iR2pK_ProtocolErrorCode.InternalError, message); +} +/** The fulfilment loop — see the module doc for the contract. */ +var LegacyInputRequiredShim = class { + constructor(_host) { + this._host = _host; + } + async fulfill(method, handler, request, ctx, firstResult) { + const { maxRounds, roundTimeoutMs } = this._host; + const outerSignal = ctx.mcpReq.signal; + let current = firstResult; + let round = 0; + while (true) { + round += 1; + if (round > maxRounds) return legacyShimFailure(method, inputRequiredRoundsExceededMessage(method, maxRounds)); + const inputRequests = current.inputRequests; + const hasInputRequests = inputRequests != null && Object.keys(inputRequests).length > 0; + const requestState = typeof current.requestState === "string" ? current.requestState : void 0; + if (!hasInputRequests && requestState === void 0) throw new src_CX2iR2pK_ProtocolError(src_CX2iR2pK_ProtocolErrorCode.InternalError, `Handler for ${method} returned an input-required result with neither inputRequests nor requestState (every InputRequiredResult must include at least one of the two)`); + let responses; + if (hasInputRequests) { + const declared = this._host.resolvedClientCapabilities(ctx); + const coerced = []; + for (const [key, entry] of Object.entries(inputRequests)) { + const { embedded, required } = coerceEmbeddedInputRequest(method, key, entry); + if (embedded.method !== "roots/list" && embedded.params === void 0) throw new src_CX2iR2pK_ProtocolError(src_CX2iR2pK_ProtocolErrorCode.InternalError, `Handler for ${method} returned an input request '${key}' of kind '${embedded.method}' without params`); + if (src_CX2iR2pK_missingClientCapabilities(required, declared) !== void 0) return legacyShimFailure(method, `Cannot request input '${key}' (${embedded.method}): the client on this 2025-era connection did not declare the required capability${declared === void 0 ? " (no client capabilities are available on this connection — per-request legacy serving cannot receive server-to-client requests)" : ""}`); + coerced.push([key, embedded]); + } + const roundAbort = linkedRoundAbort(outerSignal); + try { + const legOptions = { + relatedRequestId: ctx.mcpReq.id, + timeout: roundTimeoutMs, + resetTimeoutOnProgress: true, + onprogress: () => {}, + signal: roundAbort.signal + }; + const fulfilled = await Promise.all(coerced.map(async ([key, embedded]) => { + try { + return [key, await this._dispatchLeg(embedded, legOptions)]; + } catch (error) { + roundAbort.abort(error); + throw error; + } + })); + responses = Object.fromEntries(fulfilled); + } catch (error) { + if (outerSignal.aborted) throw error; + return legacyShimFailure(method, `Fulfilling input required by '${method}' failed: ${error instanceof Error ? error.message : String(error)}`); + } finally { + roundAbort.dispose(); + } + } else await sleep((/* inlined export .C */250), outerSignal); + let ctxNext = { + ...ctx, + mcpReq: { + ...ctx.mcpReq, + inputResponses: responses, + droppedInputResponseKeys: void 0, + requestState: requestStateAccessor(requestState) + } + }; + if (requestState !== void 0) { + const decoded = await this._host.verifyRequestState(requestState, ctxNext, method); + if (decoded !== void 0) ctxNext = withRequestStateValue(ctxNext, decoded); + } + const next = await handler(request, ctxNext); + if (!isInputRequiredResult(next)) return next; + current = next; + } + } + /** Routes one embedded request through the host's existing 2025-era senders (gate already ran). */ + async _dispatchLeg(embedded, options) { + switch (embedded.method) { + case "elicitation/create": { + let params = embedded.params; + if (params.mode === "url" && params.elicitationId === void 0) params = { + ...params, + elicitationId: syntheticElicitationId() + }; + return await this._host.sendElicitation(params, options); + } + case "sampling/createMessage": return await this._host.sendSampling(embedded.params, options); + case "roots/list": return await this._host.listRoots(embedded.params, options); + } + } +}; + +//#endregion +//#region src/server/server.ts +/** +* The request methods whose 2026-07-28 result vocabulary includes +* `input_required` (the multi round-trip methods). Returning an +* input-required result from any other handler is a server bug. +*/ +const INPUT_REQUIRED_CAPABLE_METHODS = new Set([ + "tools/call", + "prompts/get", + "resources/read" +]); +let writeClientIdentity; +let installDiscoverHandler; +let readServerIdentity; +/** +* Package-internal: backfills the connection-scoped client-identity fields of a +* per-request server instance from the request's validated `_meta` envelope, so the +* (deprecated) {@linkcode Server.getClientCapabilities} / {@linkcode Server.getClientVersion} +* accessors keep answering on instances that never see an `initialize` handshake. +* Not public API. +*/ +function mcp_DXXb3Vv3_seedClientIdentityFromEnvelope(server, identity) { + writeClientIdentity(server, identity); +} +/** +* Package-internal: installs the modern-only `server/discover` handler on an instance +* the HTTP entry has marked as serving the 2026-07-28 era, and makes sure the modern +* revisions the entry serves appear in the instance's supported-versions list (so the +* discover advertisement and version-mismatch errors name them). Idempotent. +* Hand-constructed instances are unaffected: nothing else calls this, so they keep +* answering `-32601` unless their own supported-versions list opts into a modern +* revision. Not public API. +*/ +function mcp_DXXb3Vv3_installModernOnlyHandlers(server, servedModernVersions) { + installDiscoverHandler(server, servedModernVersions); +} +/** +* Package-internal: the instance's implementation identity, for the serving +* entries to stamp onto entry-built results (the `subscriptions/listen` +* graceful-close result — built outside the encode seam, but the spec's +* `SubscriptionsListenResultMeta` extends `ResultMetaObject`, so it carries +* the serverInfo SHOULD like every other result). Not public API. +*/ +function mcp_DXXb3Vv3_serverIdentityOf(server) { + return readServerIdentity(server); +} +/** +* An MCP server on top of a pluggable transport. +* +* This server will automatically respond to the initialization flow as initiated from the client. +* +* @deprecated Use {@linkcode server/mcp.McpServer | McpServer} instead for the high-level API. Only use `Server` for advanced use cases. +*/ +var Server = class extends Protocol { + _clientCapabilities; + _clientVersion; + static { + writeClientIdentity = (server, identity) => { + if (identity.clientCapabilities !== void 0) server._clientCapabilities = identity.clientCapabilities; + if (identity.clientInfo !== void 0) server._clientVersion = identity.clientInfo; + }; + installDiscoverHandler = (server, servedModernVersions) => { + const missing = servedModernVersions.filter((version) => !server._supportedProtocolVersions.includes(version)); + if (missing.length > 0) server._supportedProtocolVersions = [...server._supportedProtocolVersions, ...missing]; + server.setRequestHandler("server/discover", () => server._ondiscover()); + }; + readServerIdentity = (server) => server._serverInfo; + } + _capabilities; + _instructions; + _jsonSchemaValidator; + _cacheHints; + _requestStateVerify; + _inputRequiredServing; + _legacyShim; + /** Lazily-built legacy shim; the loop lives in legacyInputRequiredShim.ts behind a narrow host contract. */ + _legacyInputRequiredShim() { + return this._legacyShim ??= new LegacyInputRequiredShim({ + maxRounds: this._inputRequiredServing.maxRounds, + roundTimeoutMs: this._inputRequiredServing.roundTimeoutMs, + resolvedClientCapabilities: (ctx) => this._inputRequestCapabilityView(ctx), + verifyRequestState: (state, ctx, method) => this._verifyRequestState(state, ctx, method), + sendElicitation: (params, options) => this._sendElicitationLeg(params, options, { validateAcceptedContent: false }), + sendSampling: (params, options) => this.createMessage(params, options), + listRoots: (params, options) => this.listRoots(params, options) + }); + } + /** + * Callback for when initialization has fully completed (i.e., the client has sent an `notifications/initialized` notification). + */ + oninitialized; + /** + * Initializes this server with the given name and version information. + */ + constructor(_serverInfo, options) { + super(options); + this._serverInfo = _serverInfo; + this._capabilities = options?.capabilities ? { ...options.capabilities } : {}; + this._instructions = options?.instructions; + this._jsonSchemaValidator = options?.jsonSchemaValidator ?? new AjvJsonSchemaValidator(); + this._requestStateVerify = options?.requestState?.verify; + this._inputRequiredServing = resolveLegacyShimOptions(options?.inputRequired); + if (options?.cacheHints !== void 0) { + for (const [operation, hint] of Object.entries(options.cacheHints)) if (hint !== void 0) assertValidCacheHint(hint, `cacheHints['${operation}']`); + this._cacheHints = options.cacheHints; + } + this.setRequestHandler("initialize", (request) => this._oninitialize(request)); + this.setNotificationHandler("notifications/initialized", () => this.oninitialized?.()); + if (modernProtocolVersions(this._supportedProtocolVersions).length > 0) this.setRequestHandler("server/discover", () => this._ondiscover()); + if (this._capabilities.logging) this._registerLoggingHandler(); + } + /** + * Registers the built-in `logging/setLevel` request handler. + * + * @deprecated Deprecated as of protocol version 2026-07-28 (SEP-2577). + * Remains functional during the deprecation window (at least twelve months). + * Migrate to stderr logging (STDIO servers) or OpenTelemetry. + */ + _registerLoggingHandler() { + this.setRequestHandler("logging/setLevel", async (request, ctx) => { + const transportSessionId = ctx.sessionId || ctx.http?.req?.headers.get("mcp-session-id") || void 0; + const { level } = request.params; + const parseResult = parseSchema(LoggingLevelSchema, level); + if (parseResult.success) this._loggingLevels.set(transportSessionId, parseResult.data); + return {}; + }); + } + buildContext(ctx, transportInfo) { + const hasHttpInfo = ctx.http || transportInfo?.request || transportInfo?.closeSSEStream || transportInfo?.closeStandaloneSSEStream; + return { + ...ctx, + mcpReq: { + ...ctx.mcpReq, + log: (level, data, logger) => { + if (!this._capabilities.logging) return Promise.resolve(); + let threshold; + if (this._servedModernEra()) { + threshold = ctx.mcpReq.envelope?.[LOG_LEVEL_META_KEY]; + if (threshold === void 0) return Promise.resolve(); + } else threshold = this._loggingLevels.get(ctx.sessionId) ?? this._loggingLevels.get(void 0); + if (threshold !== void 0 && this.LOG_LEVEL_SEVERITY.get(level) < this.LOG_LEVEL_SEVERITY.get(threshold)) return Promise.resolve(); + return ctx.mcpReq.notify({ + method: "notifications/message", + params: { + level, + data, + logger + } + }); + }, + elicitInput: (params, options) => this.elicitInput(params, options), + requestSampling: (params, options) => this.createMessage(params, options) + }, + http: hasHttpInfo ? { + ...ctx.http, + req: transportInfo?.request, + closeSSE: transportInfo?.closeSSEStream, + closeStandaloneSSE: transportInfo?.closeStandaloneSSEStream + } : void 0 + }; + } + _loggingLevels = /* @__PURE__ */ new Map(); + LOG_LEVEL_SEVERITY = new Map(LoggingLevelSchema.options.map((level, index) => [level, index])); + isMessageIgnored = (level, sessionId) => { + const currentLevel = this._loggingLevels.get(sessionId); + return currentLevel ? this.LOG_LEVEL_SEVERITY.get(level) < this.LOG_LEVEL_SEVERITY.get(currentLevel) : false; + }; + /** + * Registers new capabilities. This can only be called before connecting to a transport. + * + * The new capabilities will be merged with any existing capabilities previously given (e.g., at initialization). + */ + registerCapabilities(capabilities) { + if (this.transport) throw new src_CX2iR2pK_SdkError(src_CX2iR2pK_SdkErrorCode.AlreadyConnected, "Cannot register capabilities after connecting to transport"); + const hadLogging = !!this._capabilities.logging; + this._capabilities = mergeCapabilities(this._capabilities, capabilities); + if (!hadLogging && this._capabilities.logging) this._registerLoggingHandler(); + } + /** + * Enforces server-side validation for `tools/call` results regardless of how the + * handler was registered, attaches the configured per-operation cache hint + * (when one exists) so the 2026-07-28 encode seam can fill `ttlMs`/`cacheScope` + * for results that do not provide their own, and owns the multi-round-trip + * seam: on the methods whose 2026-07-28 result vocabulary includes + * `input_required` (`tools/call`, `prompts/get`, `resources/read`) an + * input-required return skips result-schema validation and is checked + * against the served era, the at-least-one rule, and the request's own + * declared client capabilities; on every other method an input-required + * return is a server bug and fails loudly. The hint rides a symbol-keyed + * property that is never serialized, so 2025-era responses are unaffected. + */ + _wrapHandler(method, handler) { + if (method !== "tools/call") { + const cacheHint = this._cacheHints?.[method]; + const isInputRequiredCapable = INPUT_REQUIRED_CAPABLE_METHODS.has(method); + if (cacheHint === void 0 && !isInputRequiredCapable) return async (request, ctx) => { + const result = await handler(request, ctx); + if (isInputRequiredResult(result)) throw new src_CX2iR2pK_ProtocolError(src_CX2iR2pK_ProtocolErrorCode.InternalError, `Handler for ${method} returned an input-required result, but only tools/call, prompts/get and resources/read support input_required (protocol revision 2026-07-28)`); + return result; + }; + return async (request, ctx) => { + const result = isInputRequiredCapable ? await this._invokeInputRequiredCapableHandler(method, handler, request, ctx) : await handler(request, ctx); + if (isInputRequiredResult(result)) { + if (!isInputRequiredCapable) throw new src_CX2iR2pK_ProtocolError(src_CX2iR2pK_ProtocolErrorCode.InternalError, `Handler for ${method} returned an input-required result, but only tools/call, prompts/get and resources/read support input_required (protocol revision 2026-07-28)`); + return result; + } + return cacheHint === void 0 ? result : attachCacheHintFallback(result, cacheHint); + }; + } + return async (request, ctx) => { + const codec = src_CX2iR2pK_codecForVersion(this._negotiatedProtocolVersion); + const validatedRequest = codec.validateRequest("tools/call", request); + if (!validatedRequest.ok) throw new src_CX2iR2pK_ProtocolError(validatedRequest.reason === "not-in-era" ? src_CX2iR2pK_ProtocolErrorCode.InternalError : src_CX2iR2pK_ProtocolErrorCode.InvalidParams, validatedRequest.reason === "not-in-era" ? "No wire schema for tools/call in the resolved era" : `Invalid tools/call request: ${validatedRequest.message}`); + const result = await this._invokeInputRequiredCapableHandler("tools/call", handler, request, ctx); + if (isInputRequiredResult(result)) return result; + const normalizedResult = normalizeContentlessToolResult(result); + const validationResult = codec.validateResult("tools/call", normalizedResult); + if (!validationResult.ok) throw new src_CX2iR2pK_ProtocolError(validationResult.reason === "not-in-era" ? src_CX2iR2pK_ProtocolErrorCode.InternalError : src_CX2iR2pK_ProtocolErrorCode.InvalidParams, validationResult.reason === "not-in-era" ? "No wire schema for tools/call in the resolved era" : `Invalid tools/call result: ${validationResult.message}`); + return validationResult.value; + }; + } + /** + * Whether this instance is bound to a 2026-07-28-or-later protocol + * revision. Era is instance state — a serving entry (`createMcpHandler`, + * `serveStdio`) marks the instance modern at construction; a 2025-era + * `initialize` handshake binds it legacy. The multi-round-trip seam reads + * this directly: there is no per-request era consult. + */ + _servedModernEra() { + return this._negotiatedProtocolVersion !== void 0 && isModernProtocolVersion(this._negotiatedProtocolVersion); + } + /** + * Invokes a handler for one of the multi-round-trip methods and applies + * the input-required seam: + * + * - a `UrlElicitationRequiredError` (or any 2025-style server→client + * request idiom) escaping the handler on a request served on the + * 2026-07-28 era fails LOUDLY with a clear steer to + * `inputRequired.elicitUrl(...)` — the `-32042` error never reaches the + * 2026-07-28 wire and the throw is not silently converted. Requests + * served on the 2025 era keep today's `-32042` behavior byte-exact (the + * error is rethrown unchanged). + * - an input-required RETURN toward a 2026-07-28 request must satisfy + * the at-least-one rule, and every embedded request must be covered by + * the capabilities declared on the request's envelope (violations + * answer the typed `-32021` error). Toward a 2025-era request the + * return is fulfilled by the default-on legacy shim, whose own gate + * consults the initialize-declared capabilities and surfaces + * violations per family; `inputRequired.legacyShim: false` restores + * the pre-shim loud failure. + */ + async _invokeInputRequiredCapableHandler(method, handler, request, ctx) { + const servedModern = this._servedModernEra(); + const rawRequestState = ctx.mcpReq.requestState(); + if (rawRequestState !== void 0 && typeof rawRequestState !== "string") throw new src_CX2iR2pK_ProtocolError(src_CX2iR2pK_ProtocolErrorCode.InvalidParams, "Invalid or expired requestState", { reason: "invalid_request_state" }); + let ctxForHandler = ctx; + if (typeof rawRequestState === "string") { + const decoded = await this._verifyRequestState(rawRequestState, ctx, method); + if (decoded !== void 0) ctxForHandler = withRequestStateValue(ctx, decoded); + } + let result; + try { + result = await handler(request, ctxForHandler); + } catch (error) { + if (error instanceof src_CX2iR2pK_ProtocolError && error.code === src_CX2iR2pK_ProtocolErrorCode.UrlElicitationRequired) { + if (!servedModern) throw error; + throw new src_CX2iR2pK_ProtocolError(src_CX2iR2pK_ProtocolErrorCode.InternalError, `URL elicitation cannot be signalled by throwing UrlElicitationRequiredError on protocol revision ${this._negotiatedProtocolVersion}: return inputRequired({ inputRequests: { …: inputRequired.elicitUrl(...) } }) from the handler instead. The urlElicitationRequired error (-32042) of earlier revisions is not available on this revision.`); + } + throw error; + } + if (!isInputRequiredResult(result)) return result; + if (!servedModern) { + if (!this._inputRequiredServing.legacyShim) throw new src_CX2iR2pK_ProtocolError(src_CX2iR2pK_ProtocolErrorCode.InternalError, `Handler for ${method} returned an input-required result, but this request is served on protocol revision ${this._negotiatedProtocolVersion ?? LATEST_PROTOCOL_VERSION}, which has no input_required vocabulary`); + return await this._legacyInputRequiredShim().fulfill(method, handler, request, ctxForHandler, result); + } + const inputRequests = result.inputRequests; + const hasInputRequests = inputRequests != null && Object.keys(inputRequests).length > 0; + const hasRequestState = typeof result.requestState === "string"; + if (!hasInputRequests && !hasRequestState) throw new src_CX2iR2pK_ProtocolError(src_CX2iR2pK_ProtocolErrorCode.InternalError, `Handler for ${method} returned an input-required result with neither inputRequests nor requestState (every InputRequiredResult must include at least one of the two)`); + if (hasInputRequests) { + const declared = this._inputRequestCapabilityView(ctx); + for (const [key, entry] of Object.entries(inputRequests)) { + const { embedded, required } = coerceEmbeddedInputRequest(method, key, entry); + const missing = src_CX2iR2pK_missingClientCapabilities(required, declared); + if (missing !== void 0) throw new src_CX2iR2pK_MissingRequiredClientCapabilityError({ requiredCapabilities: missing }, `Cannot request input '${key}' (${embedded.method}): the request's client capabilities do not declare the required capability`); + } + } + return result; + } + /** + * Runs the configured `requestState.verify` hook and returns its + * resolved value (`undefined` when unconfigured or the hook returns + * nothing). Deny-on-error: any hook failure answers the frozen `-32602`; + * the reason goes to `onerror` only. + */ + async _verifyRequestState(state, ctx, method) { + if (this._requestStateVerify === void 0) return; + try { + return await this._requestStateVerify(state, ctx); + } catch (error) { + this.onerror?.(/* @__PURE__ */ new Error(`requestState verification rejected ${method}: ${error instanceof Error ? error.message : String(error)}`)); + throw new src_CX2iR2pK_ProtocolError(src_CX2iR2pK_ProtocolErrorCode.InvalidParams, "Invalid or expired requestState", { reason: "invalid_request_state" }); + } + } + /** + * The per-request resolved client-capabilities view: the request's own + * `_meta` envelope on the 2026 era; the `initialize`-declared state on a + * 2025-era connection. Per-request instances that never saw an + * initialize (stateless legacy) hold nothing, so gates refuse there. + */ + _inputRequestCapabilityView(ctx) { + return this._servedModernEra() ? ctx.mcpReq.envelope?.[auth_CUe6YdwF_CLIENT_CAPABILITIES_META_KEY] : this._clientCapabilities; + } + /** + * Guard for the push-style server→client request APIs ({@linkcode createMessage}, + * {@linkcode elicitInput}, {@linkcode listRoots}, {@linkcode ping}) on a + * modern-era instance: the 2026-07-28 revision has no server→client request + * channel, so the call fails before any wire traffic with a typed error + * whose message steers to `inputRequired(...)`. The base era gate would + * also reject it; this guard runs first to carry the steer. + */ + _assertPushApiInServedEra(method) { + if (this._servedModernEra()) throw new src_CX2iR2pK_SdkError(src_CX2iR2pK_SdkErrorCode.MethodNotSupportedByProtocolVersion, `Server-to-client requests are not available on protocol revision ${this._negotiatedProtocolVersion}: '${method}' cannot be sent while serving a request on that revision. Return inputRequired({ ... }) from the handler instead — the client fulfils the embedded requests and retries the original request (multi round-trip requests).`, { + method, + era: "2026-07-28" + }); + } + assertCapabilityForMethod(method) { + switch (method) { + case "sampling/createMessage": + if (!this._clientCapabilities?.sampling) throw new src_CX2iR2pK_SdkError(src_CX2iR2pK_SdkErrorCode.CapabilityNotSupported, `Client does not support sampling (required for ${method})`); + break; + case "elicitation/create": + if (!this._clientCapabilities?.elicitation) throw new src_CX2iR2pK_SdkError(src_CX2iR2pK_SdkErrorCode.CapabilityNotSupported, `Client does not support elicitation (required for ${method})`); + break; + case "roots/list": + if (!this._clientCapabilities?.roots) throw new src_CX2iR2pK_SdkError(src_CX2iR2pK_SdkErrorCode.CapabilityNotSupported, `Client does not support listing roots (required for ${method})`); + break; + case "ping": break; + } + } + assertNotificationCapability(method) { + switch (method) { + case "notifications/message": + if (!this._capabilities.logging) throw new src_CX2iR2pK_SdkError(src_CX2iR2pK_SdkErrorCode.CapabilityNotSupported, `Server does not support logging (required for ${method})`); + break; + case "notifications/resources/updated": + case "notifications/resources/list_changed": + if (!this._capabilities.resources) throw new src_CX2iR2pK_SdkError(src_CX2iR2pK_SdkErrorCode.CapabilityNotSupported, `Server does not support notifying about resources (required for ${method})`); + break; + case "notifications/tools/list_changed": + if (!this._capabilities.tools) throw new src_CX2iR2pK_SdkError(src_CX2iR2pK_SdkErrorCode.CapabilityNotSupported, `Server does not support notifying of tool list changes (required for ${method})`); + break; + case "notifications/prompts/list_changed": + if (!this._capabilities.prompts) throw new src_CX2iR2pK_SdkError(src_CX2iR2pK_SdkErrorCode.CapabilityNotSupported, `Server does not support notifying of prompt list changes (required for ${method})`); + break; + case "notifications/elicitation/complete": + if (!this._clientCapabilities?.elicitation?.url) throw new src_CX2iR2pK_SdkError(src_CX2iR2pK_SdkErrorCode.CapabilityNotSupported, `Client does not support URL elicitation (required for ${method})`); + break; + case "notifications/cancelled": break; + case "notifications/progress": break; + } + } + assertRequestHandlerCapability(method) { + switch (method) { + case "completion/complete": + if (!this._capabilities.completions) throw new src_CX2iR2pK_SdkError(src_CX2iR2pK_SdkErrorCode.CapabilityNotSupported, `Server does not support completions (required for ${method})`); + break; + case "logging/setLevel": + if (!this._capabilities.logging) throw new src_CX2iR2pK_SdkError(src_CX2iR2pK_SdkErrorCode.CapabilityNotSupported, `Server does not support logging (required for ${method})`); + break; + case "prompts/get": + case "prompts/list": + if (!this._capabilities.prompts) throw new src_CX2iR2pK_SdkError(src_CX2iR2pK_SdkErrorCode.CapabilityNotSupported, `Server does not support prompts (required for ${method})`); + break; + case "resources/list": + case "resources/templates/list": + case "resources/read": + if (!this._capabilities.resources) throw new src_CX2iR2pK_SdkError(src_CX2iR2pK_SdkErrorCode.CapabilityNotSupported, `Server does not support resources (required for ${method})`); + break; + case "tools/call": + case "tools/list": + if (!this._capabilities.tools) throw new src_CX2iR2pK_SdkError(src_CX2iR2pK_SdkErrorCode.CapabilityNotSupported, `Server does not support tools (required for ${method})`); + break; + case "ping": + case "initialize": break; + } + } + async _oninitialize(request) { + const requestedVersion = request.params.protocolVersion; + this._clientCapabilities = request.params.capabilities; + this._clientVersion = request.params.clientInfo; + const legacyVersions = legacyProtocolVersions(this._supportedProtocolVersions); + const protocolVersion = legacyVersions.includes(requestedVersion) ? requestedVersion : legacyVersions[0] ?? LATEST_PROTOCOL_VERSION; + this._negotiatedProtocolVersion = protocolVersion; + this.transport?.setProtocolVersion?.(protocolVersion); + return { + protocolVersion, + capabilities: this.getCapabilities(), + serverInfo: this._serverInfo, + ...this._instructions && { instructions: this._instructions } + }; + } + /** + * Answers `server/discover` (protocol revision 2026-07-28). `supportedVersions` + * lists only modern revisions (2025-era versions are negotiated via `initialize`); + * the capabilities are advertised as-is, listChanged/subscribe bits included + * (see {@linkcode discoverAdvertisedCapabilities}). + */ + _ondiscover() { + return { + supportedVersions: modernProtocolVersions(this._supportedProtocolVersions), + capabilities: discoverAdvertisedCapabilities(this.getCapabilities()), + ...this._instructions && { instructions: this._instructions } + }; + } + /** + * The identity the 2026-era encode seam stamps into every outbound + * result's `_meta` under `io.modelcontextprotocol/serverInfo` (spec PR + * #3002: servers SHOULD identify themselves on every response). + */ + _outboundServerInfo() { + return this._serverInfo; + } + /** + * After initialization has completed, this will be populated with the client's reported capabilities. + * + * @deprecated Read client identity from the per-request handler context instead: on + * 2026-07-28 (per-request envelope) requests `ctx.mcpReq.envelope` carries the client's + * declared capabilities, while on 2025-era connections this accessor keeps returning the + * `initialize`-scoped value. The accessor remains functional — instances serving the + * 2026-07-28 era are backfilled per request from the validated envelope. + */ + getClientCapabilities() { + return this._clientCapabilities; + } + /** + * After initialization has completed, this will be populated with information about the client's name and version. + * + * @deprecated Read client identity from the per-request handler context instead: on + * 2026-07-28 (per-request envelope) requests `ctx.mcpReq.envelope` carries the client's + * name and version, while on 2025-era connections this accessor keeps returning the + * `initialize`-scoped value. The accessor remains functional — instances serving the + * 2026-07-28 era are backfilled per request from the validated envelope. + */ + getClientVersion() { + return this._clientVersion; + } + /** + * After initialization has completed, this will be populated with the protocol version negotiated + * with the client (the version the server responded with during the initialize handshake), or + * `undefined` before initialization. + * + * @deprecated Read the protocol revision from the per-request handler context instead: on + * 2026-07-28 (per-request envelope) requests `ctx.mcpReq.envelope` names the revision the + * request was sent for, while on 2025-era connections this accessor keeps returning the + * `initialize`-negotiated version. The accessor remains functional — instances serving the + * 2026-07-28 era report that revision. + */ + getNegotiatedProtocolVersion() { + return this._negotiatedProtocolVersion; + } + /** + * Project a `tools/call` result through this instance's negotiated wire + * codec — the era-agnostic SEP-2106 §4.3 TextContent auto-append, plus on + * the 2025 era the `{result:…}` wrap when `structuredContent` is a + * non-object value or the advertised `outputSchema` had a non-object root. + * Identity for object-shaped `structuredContent` on the 2026 era. + * + * `McpServer`'s built-in `tools/call` handler routes through this method. + * Low-level `setRequestHandler('tools/call', …)` authors call it + * themselves so the projection lives in one place (the codec) and the + * server-side handler stays era-blind. + * + * This is the only codec function exposed on `Server` — the full + * `WireCodec` is intentionally not part of the public surface. + */ + projectCallToolResult(result, advertisedOutputSchema) { + return this._wireCodec().projectCallToolResult(result, advertisedOutputSchema); + } + /** + * Returns the current server capabilities. + */ + getCapabilities() { + return this._capabilities; + } + /** + * Sends a `ping` request to the connected client. + * + * @deprecated The 2026-07-28 protocol removed ping; it throws on a 2026-07-28-era instance. + * If your factory serves both eras, this only works on the legacy path. + */ + async ping() { + this._assertPushApiInServedEra("ping"); + return this.request({ method: "ping" }); + } + async createMessage(params, options) { + this._assertPushApiInServedEra("sampling/createMessage"); + if ((params.tools || params.toolChoice) && !this._clientCapabilities?.sampling?.tools) throw new src_CX2iR2pK_SdkError(src_CX2iR2pK_SdkErrorCode.CapabilityNotSupported, "Client does not support sampling tools capability."); + if (params.messages.length > 0) { + const lastMessage = params.messages.at(-1); + const lastContent = Array.isArray(lastMessage.content) ? lastMessage.content : [lastMessage.content]; + const hasToolResults = lastContent.some((c) => c.type === "tool_result"); + const previousMessage = params.messages.length > 1 ? params.messages.at(-2) : void 0; + const previousContent = previousMessage ? Array.isArray(previousMessage.content) ? previousMessage.content : [previousMessage.content] : []; + const hasPreviousToolUse = previousContent.some((c) => c.type === "tool_use"); + if (hasToolResults) { + if (lastContent.some((c) => c.type !== "tool_result")) throw new src_CX2iR2pK_ProtocolError(src_CX2iR2pK_ProtocolErrorCode.InvalidParams, "The last message must contain only tool_result content if any is present"); + if (!hasPreviousToolUse) throw new src_CX2iR2pK_ProtocolError(src_CX2iR2pK_ProtocolErrorCode.InvalidParams, "tool_result blocks are not matching any tool_use from the previous message"); + } + if (hasPreviousToolUse) { + const toolUseIds = new Set(previousContent.filter((c) => c.type === "tool_use").map((c) => c.id)); + const toolResultIds = new Set(lastContent.filter((c) => c.type === "tool_result").map((c) => c.toolUseId)); + if (toolUseIds.size !== toolResultIds.size || ![...toolUseIds].every((id) => toolResultIds.has(id))) throw new src_CX2iR2pK_ProtocolError(src_CX2iR2pK_ProtocolErrorCode.InvalidParams, "ids of tool_result blocks and tool_use blocks from previous message do not match"); + } + } + const hasTools = Boolean(params.tools || params.toolChoice); + const wide = await this.request({ + method: "sampling/createMessage", + params + }, options); + const outcome = this._wireCodec().samplingResultVariant(hasTools, wide); + if (!outcome.ok) throw new src_CX2iR2pK_SdkError(src_CX2iR2pK_SdkErrorCode.InvalidResult, `Invalid sampling/createMessage result: ${outcome.reason === "invalid" ? outcome.message : outcome.reason}`); + return outcome.value; + } + /** + * Creates an elicitation request for the given parameters. + * For backwards compatibility, `mode` may be omitted for form requests and will default to `"form"`. + * @param params The parameters for the elicitation request. + * @param options Optional request options. + * @returns The result of the elicitation request. + * + * @deprecated Throws on a 2026-07-28-era request — use {@link index.inputRequired | inputRequired} (multi-round-trip) + * instead. The 2025 push-style server-to-client request model is replaced by input_required + * results in the 2026-07-28 protocol. If your factory serves both eras, this only works on the + * legacy path. + */ + async elicitInput(params, options) { + this._assertPushApiInServedEra("elicitation/create"); + switch (params.mode ?? "form") { + case "url": + if (!this._clientCapabilities?.elicitation?.url) throw new src_CX2iR2pK_SdkError(src_CX2iR2pK_SdkErrorCode.CapabilityNotSupported, "Client does not support url elicitation."); + break; + case "form": + if (!this._clientCapabilities?.elicitation?.form) throw new src_CX2iR2pK_SdkError(src_CX2iR2pK_SdkErrorCode.CapabilityNotSupported, "Client does not support form elicitation."); + break; + } + return this._sendElicitationLeg(params, options); + } + /** + * The capability-check-free core of {@linkcode elicitInput}. The shim + * uses it because its gate differs from the public checks: a bare + * `elicitation: {}` counts as form support (the pre-mode rule), and + * accepted content passes through unvalidated for parity with the + * modern client driver (handlers validate via the schema-aware + * `acceptedContent` overload and can re-ask). + */ + async _sendElicitationLeg(params, options, behavior) { + const mode = params.mode ?? "form"; + const validateAcceptedContent = behavior?.validateAcceptedContent ?? true; + switch (mode) { + case "url": { + const urlParams = params; + return this.request({ + method: "elicitation/create", + params: urlParams + }, options); + } + case "form": { + const formParams = params.mode === "form" ? params : { + ...params, + mode: "form" + }; + const result = await this.request({ + method: "elicitation/create", + params: formParams + }, options); + if (validateAcceptedContent && result.action === "accept" && result.content && formParams.requestedSchema) try { + const validationResult = this._jsonSchemaValidator.getValidator(formParams.requestedSchema)(result.content); + if (!validationResult.valid) throw new src_CX2iR2pK_ProtocolError(src_CX2iR2pK_ProtocolErrorCode.InvalidParams, `Elicitation response content does not match requested schema: ${validationResult.errorMessage}`); + } catch (error) { + if (error instanceof src_CX2iR2pK_ProtocolError) throw error; + throw new src_CX2iR2pK_ProtocolError(src_CX2iR2pK_ProtocolErrorCode.InternalError, `Error validating elicitation response: ${error instanceof Error ? error.message : String(error)}`); + } + return result; + } + } + } + /** + * Creates a reusable callback that, when invoked, will send a `notifications/elicitation/complete` + * notification for the specified elicitation ID. + * + * The notification (and the `elicitationId` it references) exists only on protocol revision + * 2025-11-25 — the 2026-07-28 revision removed both. On a connection negotiated at 2026-07-28 the + * returned callback rejects with a typed local error before anything reaches the transport + * (the method is not part of that revision's wire registry). + * + * @param elicitationId The ID of the elicitation to mark as complete. + * @param options Optional notification options. Useful when the completion notification should be related to a prior request. + * @returns A function that emits the completion notification when awaited. + */ + createElicitationCompletionNotifier(elicitationId, options) { + if (!this._clientCapabilities?.elicitation?.url) throw new src_CX2iR2pK_SdkError(src_CX2iR2pK_SdkErrorCode.CapabilityNotSupported, "Client does not support URL elicitation (required for notifications/elicitation/complete)"); + return () => this.notification({ + method: "notifications/elicitation/complete", + params: { elicitationId } + }, options); + } + /** + * Requests the list of roots from the client. + * + * @deprecated Deprecated as of protocol version 2026-07-28 (SEP-2577). + * Throws on a 2026-07-28-era request — use {@link index.inputRequired | inputRequired} (multi-round-trip) instead, + * or migrate to passing paths via tool parameters, resource URIs, or configuration. The 2025 + * push-style server-to-client request model is replaced by input_required results in the + * 2026-07-28 protocol. If your factory serves both eras, this only works on the legacy path. + */ + async listRoots(params, options) { + this._assertPushApiInServedEra("roots/list"); + return this.request({ + method: "roots/list", + params + }, options); + } + /** + * Sends a logging message to the client, if connected. + * Note: You only need to send the parameters object, not the entire JSON-RPC message. + * @see {@linkcode LoggingMessageNotification} + * @param params + * @param sessionId Optional for stateless transports and backward compatibility. + * + * @deprecated Deprecated as of protocol version 2026-07-28 (SEP-2577). + * Remains functional during the deprecation window (at least twelve months). + * Migrate to stderr logging (STDIO servers) or OpenTelemetry. + */ + async sendLoggingMessage(params, sessionId) { + if (this._capabilities.logging && !this.isMessageIgnored(params.level, sessionId)) return this.notification({ + method: "notifications/message", + params + }); + } + async sendResourceUpdated(params) { + return this.notification({ + method: "notifications/resources/updated", + params + }); + } + 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" }); + } +}; +/** +* The capability set a server advertises on `server/discover`. Pure — never +* mutates the input; the legacy `initialize` advertisement is untouched. +* +* The serving entries serve `subscriptions/listen` themselves, so the +* `listChanged` and `resources.subscribe` capability bits are advertised +* as-is: a modern-era client uses them to decide which notification types to +* request on its listen filter. +*/ +function discoverAdvertisedCapabilities(capabilities) { + return { ...capabilities }; +} + +//#endregion +//#region src/server/mcp.ts +/** +* High-level MCP server that provides a simpler API for working with resources, tools, and prompts. +* For advanced usage (like sending notifications or setting custom request handlers), use the underlying +* {@linkcode Server} instance available via the {@linkcode McpServer.server | server} property. +* +* @example +* ```ts source="./mcp.examples.ts#McpServer_basicUsage" +* const server = new McpServer({ +* name: 'my-server', +* version: '1.0.0' +* }); +* ``` +*/ +var mcp_DXXb3Vv3_McpServer = class { + /** + * The underlying {@linkcode Server} instance, useful for advanced operations like sending notifications. + */ + server; + _registeredResources = {}; + _registeredResourceTemplates = {}; + _registeredTools = {}; + _registeredPrompts = {}; + /** + * Per-tool JSON-converted `inputSchema`, memoized so the SEP-2243 + * registration-time scan and the pre-dispatch validation step share one + * conversion instead of paying it twice per request under the + * per-request-factory `createMcpHandler` model. + */ + _toolInputSchemaJson = {}; + /** + * The JSON-serialized `inputSchema` of a registered tool, or `undefined` + * when no such tool is registered. Used by the HTTP entry's pre-dispatch + * SEP-2243 `Mcp-Param-*` validation step (which needs the same JSON Schema + * `tools/list` would emit, before dispatch reaches the handler). + * + * @internal + */ + toolInputSchemaJson(name) { + const tool = this._registeredTools[name]; + if (tool === void 0 || !tool.enabled) return void 0; + if (Object.hasOwn(this._toolInputSchemaJson, name)) return this._toolInputSchemaJson[name]; + if (tool.inputSchema === void 0) return EMPTY_OBJECT_JSON_SCHEMA; + try { + const json = standardSchemaToJsonSchema(tool.inputSchema, "input"); + this._toolInputSchemaJson[name] = json; + return json; + } catch { + return; + } + } + constructor(serverInfo, options) { + this.server = new Server(serverInfo, options); + if (options?.capabilities?.tools) this.setToolRequestHandlers(); + if (options?.capabilities?.resources) this.setResourceRequestHandlers(); + if (options?.capabilities?.prompts) this.setPromptRequestHandlers(); + } + /** + * Attaches to the given transport, starts it, and starts listening for messages. + * + * The `server` object assumes ownership of the {@linkcode Transport}, replacing any callbacks that have already been set, and expects that it is the only user of the {@linkcode Transport} instance going forward. + * + * @example + * ```ts source="./mcp.examples.ts#McpServer_connect_stdio" + * const server = new McpServer({ name: 'my-server', version: '1.0.0' }); + * const transport = new StdioServerTransport(); + * await server.connect(transport); + * ``` + */ + async connect(transport) { + return await this.server.connect(transport); + } + /** + * Closes the connection. + */ + async close() { + await this.server.close(); + } + _toolHandlersInitialized = false; + setToolRequestHandlers() { + if (this._toolHandlersInitialized) return; + this.server.assertCanSetRequestHandler("tools/list"); + this.server.assertCanSetRequestHandler("tools/call"); + this.server.registerCapabilities({ tools: { listChanged: this.server.getCapabilities().tools?.listChanged ?? true } }); + this.server.setRequestHandler("tools/list", () => ({ tools: Object.entries(this._registeredTools).filter(([, tool]) => tool.enabled).map(([name, tool]) => { + const toolDefinition = { + name, + title: tool.title, + description: tool.description, + inputSchema: tool.inputSchema ? standardSchemaToJsonSchema(tool.inputSchema, "input") : EMPTY_OBJECT_JSON_SCHEMA, + annotations: tool.annotations, + icons: tool.icons, + execution: tool.execution, + _meta: tool._meta + }; + if (tool.outputSchema) toolDefinition.outputSchema = standardSchemaToJsonSchema(tool.outputSchema, "output"); + return toolDefinition; + }) })); + this.server.setRequestHandler("tools/call", async (request, ctx) => { + const tool = this._registeredTools[request.params.name]; + if (!tool) throw new src_CX2iR2pK_ProtocolError(src_CX2iR2pK_ProtocolErrorCode.InvalidParams, `Tool ${request.params.name} not found`); + if (!tool.enabled) throw new src_CX2iR2pK_ProtocolError(src_CX2iR2pK_ProtocolErrorCode.InvalidParams, `Tool ${request.params.name} disabled`); + try { + const args = await this.validateToolInput(tool, request.params.arguments, request.params.name); + const result = await this.executeToolHandler(tool, args, ctx); + await this.validateToolOutput(tool, result, request.params.name); + if (isInputRequiredResult(result)) return result; + return this.server.projectCallToolResult(result, tool.outputSchemaJson); + } catch (error) { + if (error instanceof src_CX2iR2pK_ProtocolError && error.code === src_CX2iR2pK_ProtocolErrorCode.UrlElicitationRequired) throw error; + return this.createToolError(error instanceof Error ? error.message : String(error)); + } + }); + this._toolHandlersInitialized = true; + } + /** + * Creates a tool error result. + * + * @param errorMessage - The error message. + * @returns The tool error result. + */ + createToolError(errorMessage) { + return { + content: [{ + type: "text", + text: errorMessage + }], + isError: true + }; + } + /** + * Validates tool input arguments against the tool's input schema. + */ + async validateToolInput(tool, args, toolName) { + if (!tool.inputSchema) return; + const parseResult = await validateStandardSchema(tool.inputSchema, args ?? {}); + if (!parseResult.success) throw new src_CX2iR2pK_ProtocolError(src_CX2iR2pK_ProtocolErrorCode.InvalidParams, `Input validation error: Invalid arguments for tool ${toolName}: ${parseResult.error}`); + return parseResult.data; + } + /** + * Validates tool output against the tool's output schema. + */ + async validateToolOutput(tool, result, toolName) { + if (!tool.outputSchema) return; + if (isInputRequiredResult(result)) return; + if (result.isError) return; + if (result.structuredContent === void 0) throw new src_CX2iR2pK_ProtocolError(src_CX2iR2pK_ProtocolErrorCode.InvalidParams, `Output validation error: Tool ${toolName} has an output schema but no structured content was provided`); + const parseResult = await validateStandardSchema(tool.outputSchema, result.structuredContent); + if (!parseResult.success) throw new src_CX2iR2pK_ProtocolError(src_CX2iR2pK_ProtocolErrorCode.InvalidParams, `Output validation error: Invalid structured content for tool ${toolName}: ${parseResult.error}`); + } + /** + * Executes a tool handler. + */ + async executeToolHandler(tool, args, ctx) { + return tool.executor(args, ctx); + } + _completionHandlerInitialized = false; + setCompletionRequestHandler() { + if (this._completionHandlerInitialized) return; + this.server.assertCanSetRequestHandler("completion/complete"); + this.server.registerCapabilities({ completions: {} }); + this.server.setRequestHandler("completion/complete", async (request) => { + switch (request.params.ref.type) { + case "ref/prompt": + assertCompleteRequestPrompt(request); + return this.handlePromptCompletion(request, request.params.ref); + case "ref/resource": + assertCompleteRequestResourceTemplate(request); + return this.handleResourceCompletion(request, request.params.ref); + default: throw new src_CX2iR2pK_ProtocolError(src_CX2iR2pK_ProtocolErrorCode.InvalidParams, `Invalid completion reference: ${request.params.ref}`); + } + }); + this._completionHandlerInitialized = true; + } + async handlePromptCompletion(request, ref) { + const prompt = this._registeredPrompts[ref.name]; + if (!prompt) throw new src_CX2iR2pK_ProtocolError(src_CX2iR2pK_ProtocolErrorCode.InvalidParams, `Prompt ${ref.name} not found`); + if (!prompt.enabled) throw new src_CX2iR2pK_ProtocolError(src_CX2iR2pK_ProtocolErrorCode.InvalidParams, `Prompt ${ref.name} disabled`); + if (!prompt.argsSchema) return EMPTY_COMPLETION_RESULT; + const field = unwrapOptionalSchema(getSchemaShape(prompt.argsSchema)?.[request.params.argument.name]); + if (!isCompletable(field)) return EMPTY_COMPLETION_RESULT; + const completer = getCompleter(field); + if (!completer) return EMPTY_COMPLETION_RESULT; + return createCompletionResult(await completer(request.params.argument.value, request.params.context)); + } + async handleResourceCompletion(request, ref) { + const template = Object.values(this._registeredResourceTemplates).find((t) => t.resourceTemplate.uriTemplate.toString() === ref.uri); + if (!template) { + if (this._registeredResources[ref.uri]) return EMPTY_COMPLETION_RESULT; + throw new src_CX2iR2pK_ProtocolError(src_CX2iR2pK_ProtocolErrorCode.InvalidParams, `Resource template ${request.params.ref.uri} not found`); + } + const completer = template.resourceTemplate.completeCallback(request.params.argument.name); + if (!completer) return EMPTY_COMPLETION_RESULT; + return createCompletionResult(await completer(request.params.argument.value, request.params.context)); + } + _resourceHandlersInitialized = false; + setResourceRequestHandlers() { + if (this._resourceHandlersInitialized) return; + this.server.assertCanSetRequestHandler("resources/list"); + this.server.assertCanSetRequestHandler("resources/templates/list"); + this.server.assertCanSetRequestHandler("resources/read"); + this.server.registerCapabilities({ resources: { listChanged: this.server.getCapabilities().resources?.listChanged ?? true } }); + this.server.setRequestHandler("resources/list", async (_request, ctx) => { + const resources = Object.entries(this._registeredResources).filter(([_, resource]) => resource.enabled).map(([uri, resource]) => ({ + uri, + name: resource.name, + ...resource.metadata + })); + const templateResources = []; + for (const template of Object.values(this._registeredResourceTemplates)) { + if (!template.resourceTemplate.listCallback) continue; + const result = await template.resourceTemplate.listCallback(ctx); + for (const resource of result.resources) templateResources.push({ + ...template.metadata, + ...resource + }); + } + return { resources: [...resources, ...templateResources] }; + }); + this.server.setRequestHandler("resources/templates/list", async () => { + return { resourceTemplates: Object.entries(this._registeredResourceTemplates).map(([name, template]) => ({ + name, + uriTemplate: template.resourceTemplate.uriTemplate.toString(), + ...template.metadata + })) }; + }); + this.server.setRequestHandler("resources/read", async (request, ctx) => { + let uri; + try { + uri = new URL(request.params.uri); + } catch { + throw new src_CX2iR2pK_ProtocolError(src_CX2iR2pK_ProtocolErrorCode.InvalidParams, `Resource URI ${request.params.uri} is invalid`, { + uri: request.params.uri, + reason: "invalid_uri" + }); + } + const resource = this._registeredResources[uri.toString()]; + if (resource) { + if (!resource.enabled) throw new src_CX2iR2pK_ProtocolError(src_CX2iR2pK_ProtocolErrorCode.InvalidParams, `Resource ${uri} disabled`); + return attachCacheHintFallback(await resource.readCallback(uri, ctx), resource.cacheHint); + } + for (const template of Object.values(this._registeredResourceTemplates)) { + const variables = template.resourceTemplate.uriTemplate.match(uri.toString()); + if (variables) return attachCacheHintFallback(await template.readCallback(uri, variables, ctx), template.cacheHint); + } + throw new ResourceNotFoundError(request.params.uri); + }); + this._resourceHandlersInitialized = true; + } + _promptHandlersInitialized = false; + setPromptRequestHandlers() { + if (this._promptHandlersInitialized) return; + this.server.assertCanSetRequestHandler("prompts/list"); + this.server.assertCanSetRequestHandler("prompts/get"); + this.server.registerCapabilities({ prompts: { listChanged: this.server.getCapabilities().prompts?.listChanged ?? true } }); + this.server.setRequestHandler("prompts/list", () => ({ prompts: Object.entries(this._registeredPrompts).filter(([, prompt]) => prompt.enabled).map(([name, prompt]) => { + return { + name, + title: prompt.title, + description: prompt.description, + arguments: prompt.argsSchema ? promptArgumentsFromStandardSchema(prompt.argsSchema) : void 0, + icons: prompt.icons, + _meta: prompt._meta + }; + }) })); + this.server.setRequestHandler("prompts/get", async (request, ctx) => { + const prompt = this._registeredPrompts[request.params.name]; + if (!prompt) throw new src_CX2iR2pK_ProtocolError(src_CX2iR2pK_ProtocolErrorCode.InvalidParams, `Prompt ${request.params.name} not found`); + if (!prompt.enabled) throw new src_CX2iR2pK_ProtocolError(src_CX2iR2pK_ProtocolErrorCode.InvalidParams, `Prompt ${request.params.name} disabled`); + return prompt.handler(request.params.arguments, ctx); + }); + this._promptHandlersInitialized = true; + } + registerResource(name, uriOrTemplate, config, readCallback) { + const cacheHint = config.cacheHint; + let metadata = config; + if (cacheHint !== void 0) { + assertValidCacheHint(cacheHint, `resource ${name}`); + const rest = { ...config }; + delete rest.cacheHint; + metadata = rest; + } + if (typeof uriOrTemplate === "string") { + if (this._registeredResources[uriOrTemplate]) throw new Error(`Resource ${uriOrTemplate} is already registered`); + const registeredResource = this._createRegisteredResource(name, config.title, uriOrTemplate, metadata, readCallback); + if (cacheHint !== void 0) registeredResource.cacheHint = cacheHint; + this.setResourceRequestHandlers(); + this.sendResourceListChanged(); + return registeredResource; + } else { + if (this._registeredResourceTemplates[name]) throw new Error(`Resource template ${name} is already registered`); + const registeredResourceTemplate = this._createRegisteredResourceTemplate(name, config.title, uriOrTemplate, metadata, readCallback); + if (cacheHint !== void 0) registeredResourceTemplate.cacheHint = cacheHint; + this.setResourceRequestHandlers(); + this.sendResourceListChanged(); + return registeredResourceTemplate; + } + } + _createRegisteredResource(name, title, uri, metadata, readCallback) { + const registeredResource = { + name, + title, + metadata, + readCallback, + enabled: true, + disable: () => registeredResource.update({ enabled: false }), + enable: () => registeredResource.update({ enabled: true }), + remove: () => registeredResource.update({ uri: null }), + update: (updates) => { + if (updates.uri !== void 0 && updates.uri !== uri) { + delete this._registeredResources[uri]; + if (updates.uri) this._registeredResources[updates.uri] = registeredResource; + } + if (updates.name !== void 0) registeredResource.name = updates.name; + if (updates.title !== void 0) registeredResource.title = updates.title; + if (updates.metadata !== void 0) registeredResource.metadata = updates.metadata; + if (updates.callback !== void 0) registeredResource.readCallback = updates.callback; + if (updates.enabled !== void 0) registeredResource.enabled = updates.enabled; + this.sendResourceListChanged(); + } + }; + this._registeredResources[uri] = registeredResource; + return registeredResource; + } + _createRegisteredResourceTemplate(name, title, template, metadata, readCallback) { + const registeredResourceTemplate = { + resourceTemplate: template, + title, + metadata, + readCallback, + enabled: true, + disable: () => registeredResourceTemplate.update({ enabled: false }), + enable: () => registeredResourceTemplate.update({ enabled: true }), + remove: () => registeredResourceTemplate.update({ name: null }), + update: (updates) => { + if (updates.name !== void 0 && updates.name !== name) { + delete this._registeredResourceTemplates[name]; + if (updates.name) this._registeredResourceTemplates[updates.name] = registeredResourceTemplate; + } + if (updates.title !== void 0) registeredResourceTemplate.title = updates.title; + if (updates.template !== void 0) registeredResourceTemplate.resourceTemplate = updates.template; + if (updates.metadata !== void 0) registeredResourceTemplate.metadata = updates.metadata; + if (updates.callback !== void 0) registeredResourceTemplate.readCallback = updates.callback; + if (updates.enabled !== void 0) registeredResourceTemplate.enabled = updates.enabled; + this.sendResourceListChanged(); + } + }; + this._registeredResourceTemplates[name] = registeredResourceTemplate; + const variableNames = template.uriTemplate.variableNames; + if (Array.isArray(variableNames) && variableNames.some((v) => !!template.completeCallback(v))) this.setCompletionRequestHandler(); + return registeredResourceTemplate; + } + _createRegisteredPrompt(name, title, description, argsSchema, callback, icons, _meta) { + let currentArgsSchema = argsSchema; + let currentCallback = callback; + const registeredPrompt = { + title, + description, + argsSchema, + icons, + _meta, + handler: createPromptHandler(name, argsSchema, callback), + enabled: true, + disable: () => registeredPrompt.update({ enabled: false }), + enable: () => registeredPrompt.update({ enabled: true }), + remove: () => registeredPrompt.update({ name: null }), + update: (updates) => { + if (updates.name !== void 0 && updates.name !== name) { + delete this._registeredPrompts[name]; + if (updates.name) this._registeredPrompts[updates.name] = registeredPrompt; + } + if (updates.title !== void 0) registeredPrompt.title = updates.title; + if (updates.description !== void 0) registeredPrompt.description = updates.description; + if (updates.icons !== void 0) registeredPrompt.icons = updates.icons; + if (updates._meta !== void 0) registeredPrompt._meta = updates._meta; + let needsHandlerRegen = false; + if (updates.argsSchema !== void 0) { + registeredPrompt.argsSchema = updates.argsSchema; + currentArgsSchema = updates.argsSchema; + needsHandlerRegen = true; + } + if (updates.callback !== void 0) { + currentCallback = updates.callback; + needsHandlerRegen = true; + } + if (needsHandlerRegen) registeredPrompt.handler = createPromptHandler(name, currentArgsSchema, currentCallback); + if (updates.enabled !== void 0) registeredPrompt.enabled = updates.enabled; + this.sendPromptListChanged(); + } + }; + this._registeredPrompts[name] = registeredPrompt; + if (argsSchema) { + const shape = getSchemaShape(argsSchema); + if (shape) { + if (Object.values(shape).some((field) => { + return isCompletable(unwrapOptionalSchema(field)); + })) this.setCompletionRequestHandler(); + } + } + return registeredPrompt; + } + _createRegisteredTool(name, title, description, inputSchema, outputSchema, annotations, icons, execution, _meta, handler) { + validateAndWarnToolName(name); + if (inputSchema !== void 0) try { + const json = standardSchemaToJsonSchema(inputSchema, "input"); + this._toolInputSchemaJson[name] = json; + const scan = src_CX2iR2pK_scanXMcpHeaderDeclarations(json); + if (!scan.valid) console.warn(`[mcp-sdk] tool '${name}' carries an invalid x-mcp-header declaration and will be excluded by conforming Streamable HTTP clients: ${scan.reason}`); + } catch {} + let currentHandler = handler; + const registeredTool = { + title, + description, + inputSchema, + outputSchema, + outputSchemaJson: convertOutputSchemaJson(outputSchema), + annotations, + icons, + execution, + _meta, + handler, + executor: createToolExecutor(inputSchema, handler), + enabled: true, + disable: () => registeredTool.update({ enabled: false }), + enable: () => registeredTool.update({ enabled: true }), + remove: () => registeredTool.update({ name: null }), + update: (updates) => { + if (updates.name !== void 0 && updates.name !== name) { + if (typeof updates.name === "string") validateAndWarnToolName(updates.name); + delete this._registeredTools[name]; + delete this._toolInputSchemaJson[name]; + if (updates.name) { + delete this._toolInputSchemaJson[updates.name]; + this._registeredTools[updates.name] = registeredTool; + name = updates.name; + } + } + if (updates.title !== void 0) registeredTool.title = updates.title; + if (updates.description !== void 0) registeredTool.description = updates.description; + let needsExecutorRegen = false; + if (updates.paramsSchema !== void 0) { + registeredTool.inputSchema = updates.paramsSchema; + delete this._toolInputSchemaJson[name]; + needsExecutorRegen = true; + } + if (updates.callback !== void 0) { + registeredTool.handler = updates.callback; + currentHandler = updates.callback; + needsExecutorRegen = true; + } + if (needsExecutorRegen) registeredTool.executor = createToolExecutor(registeredTool.inputSchema, currentHandler); + if (updates.outputSchema !== void 0) { + registeredTool.outputSchema = updates.outputSchema; + registeredTool.outputSchemaJson = convertOutputSchemaJson(updates.outputSchema); + } + if (updates.annotations !== void 0) registeredTool.annotations = updates.annotations; + if (updates.icons !== void 0) registeredTool.icons = updates.icons; + if (updates._meta !== void 0) registeredTool._meta = updates._meta; + if (updates.enabled !== void 0) registeredTool.enabled = updates.enabled; + this.sendToolListChanged(); + } + }; + this._registeredTools[name] = registeredTool; + this.setToolRequestHandlers(); + this.sendToolListChanged(); + return registeredTool; + } + registerTool(name, config, cb) { + if (this._registeredTools[name]) throw new Error(`Tool ${name} is already registered`); + const { title, description, inputSchema, outputSchema, annotations, icons, _meta } = config; + return this._createRegisteredTool(name, title, description, normalizeRawShapeSchema(inputSchema), normalizeRawShapeSchema(outputSchema), annotations, icons, void 0, _meta, cb); + } + registerPrompt(name, config, cb) { + if (this._registeredPrompts[name]) throw new Error(`Prompt ${name} is already registered`); + const { title, description, argsSchema, icons, _meta } = config; + const registeredPrompt = this._createRegisteredPrompt(name, title, description, normalizeRawShapeSchema(argsSchema), cb, icons, _meta); + this.setPromptRequestHandlers(); + this.sendPromptListChanged(); + return registeredPrompt; + } + /** + * Checks if the server is connected to a transport. + * @returns `true` if the server is connected + */ + isConnected() { + return this.server.transport !== void 0; + } + /** + * Sends a logging message to the client, if connected. + * Note: You only need to send the parameters object, not the entire JSON-RPC message. + * @see {@linkcode LoggingMessageNotification} + * @param params + * @param sessionId Optional for stateless transports and backward compatibility. + * + * @example + * ```ts source="./mcp.examples.ts#McpServer_sendLoggingMessage_basic" + * await server.sendLoggingMessage({ + * level: 'info', + * data: 'Processing complete' + * }); + * ``` + * + * @deprecated Deprecated as of protocol version 2026-07-28 (SEP-2577). + * Remains functional during the deprecation window (at least twelve months). + * Migrate to stderr logging (STDIO servers) or OpenTelemetry. + */ + async sendLoggingMessage(params, sessionId) { + return this.server.sendLoggingMessage(params, sessionId); + } + /** + * Sends a resource list changed event to the client, if connected. + */ + sendResourceListChanged() { + if (this.isConnected()) this.server.sendResourceListChanged(); + } + /** + * Sends a tool list changed event to the client, if connected. + */ + sendToolListChanged() { + if (this.isConnected()) this.server.sendToolListChanged(); + } + /** + * Sends a prompt list changed event to the client, if connected. + */ + sendPromptListChanged() { + if (this.isConnected()) this.server.sendPromptListChanged(); + } +}; +/** +* A resource template combines a URI pattern with optional functionality to enumerate +* all resources matching that pattern. +*/ +var ResourceTemplate = class { + _uriTemplate; + constructor(uriTemplate, _callbacks) { + this._callbacks = _callbacks; + this._uriTemplate = typeof uriTemplate === "string" ? new UriTemplate(uriTemplate) : uriTemplate; + } + /** + * Gets the URI template pattern. + */ + get uriTemplate() { + return this._uriTemplate; + } + /** + * Gets the list callback, if one was provided. + */ + get listCallback() { + return this._callbacks.list; + } + /** + * Gets the callback for completing a specific URI template variable, if one was provided. + */ + completeCallback(variable) { + return this._callbacks.complete?.[variable]; + } +}; +/** +* Creates an executor that invokes the handler with the appropriate arguments. +* When `inputSchema` is defined, the handler is called with `(args, ctx)`. +* When `inputSchema` is undefined, the handler is called with just `(ctx)`. +*/ +function createToolExecutor(inputSchema, handler) { + if (inputSchema) { + const callback$1 = handler; + return async (args, ctx) => callback$1(args, ctx); + } + const callback = handler; + return async (_args, ctx) => callback(ctx); +} +const EMPTY_OBJECT_JSON_SCHEMA = { + type: "object", + properties: {} +}; +/** +* Convert a registered `outputSchema` to JSON Schema, memoised on {@link RegisteredTool.outputSchemaJson} +* so `tools/call` passes the SAME advertised schema to the wire codec's `projectCallToolResult` that +* `tools/list` emits (and that the 2025 codec's `encodeResult('tools/list', …)` may wrap). A conversion +* failure yields `undefined` so the failure surfaces where it always has (`tools/list`). +*/ +function convertOutputSchemaJson(outputSchema) { + if (outputSchema === void 0) return void 0; + try { + return standardSchemaToJsonSchema(outputSchema, "output"); + } catch { + return; + } +} +/** +* Creates a type-safe prompt handler that captures the schema and callback in a closure. +* This eliminates the need for type assertions at the call site. +*/ +function createPromptHandler(name, argsSchema, callback) { + if (argsSchema) { + const typedCallback = callback; + return async (args, ctx) => { + const parseResult = await validateStandardSchema(argsSchema, args); + if (!parseResult.success) throw new src_CX2iR2pK_ProtocolError(src_CX2iR2pK_ProtocolErrorCode.InvalidParams, `Invalid arguments for prompt ${name}: ${parseResult.error}`); + return typedCallback(parseResult.data, ctx); + }; + } else { + const typedCallback = callback; + return async (_args, ctx) => { + return typedCallback(ctx); + }; + } +} +function createCompletionResult(suggestions) { + return { completion: { + values: suggestions.map(String).slice(0, 100), + total: suggestions.length, + hasMore: suggestions.length > 100 + } }; +} +const EMPTY_COMPLETION_RESULT = { completion: { + values: [], + hasMore: false +} }; +/** @internal Gets the shape of a Zod object schema */ +function getSchemaShape(schema) { + const candidate = schema; + if (candidate.shape && typeof candidate.shape === "object") return candidate.shape; +} +/** @internal Checks if a Zod schema is optional */ +function isOptionalSchema(schema) { + return schema?.type === "optional"; +} +/** @internal Unwraps an optional Zod schema */ +function unwrapOptionalSchema(schema) { + if (!isOptionalSchema(schema)) return schema; + return schema.def?.innerType ?? schema; +} + +//#endregion + +//# sourceMappingURL=mcp-DXXb3Vv3.mjs.map + + + + +//#region src/server/perRequestTransport.ts +/** +* The per-request micro-transport: a real, connected `Transport` whose whole +* lifetime is one HTTP exchange. See the module documentation for the +* response shapes it produces. +*/ +var PerRequestHTTPServerTransport = class { + onclose; + onerror; + onmessage; + _classification; + _responseMode; + _started = false; + _used = false; + _closed = false; + _terminalDelivered = false; + /** + * `true` only while the inbound message is being delivered synchronously + * to the connected protocol layer. The pre-handler gates (the era + * registry gate, the edge→instance handoff check, the missing-handler + * rejection) answer inside this window; request handlers always run + * after it (the protocol layer defers them to a microtask). An error + * sent inside the window is therefore ladder-originated, and an error + * sent after it is handler-produced. + */ + _dispatchWindowOpen = false; + _requestId; + _deferredResponse; + _sse; + _abortCleanup; + _keepAliveMs; + constructor(options) { + this._classification = options.classification; + this._responseMode = options.responseMode ?? "auto"; + this._keepAliveMs = options.keepAliveMs ?? DEFAULT_SSE_KEEP_ALIVE_MS; + } + async start() { + if (this._started) throw new Error("PerRequestHTTPServerTransport is already started"); + this._started = true; + } + /** + * Serves the single exchange: delivers the classified message to the + * connected server instance and resolves with the HTTP response. + * + * Throws when called a second time (the transport is strictly + * single-use), or before a server has been connected to the transport. + * The returned promise rejects with a connection-closed error when the + * transport is closed before a response was produced (for example because + * the client disconnected). + */ + async handleMessage(message, extra) { + if (this._used) throw new Error("PerRequestHTTPServerTransport serves exactly one exchange; construct a new transport per request"); + if (!this._started || this.onmessage === void 0) throw new Error("PerRequestHTTPServerTransport is not connected: connect a server to this transport before handling a message"); + if (this._closed) throw new Error("PerRequestHTTPServerTransport is closed"); + this._used = true; + const signal = extra?.request?.signal; + if (signal?.aborted) { + await this.close(); + throw new SdkError(SdkErrorCode.ConnectionClosed, "The request was aborted before it could be handled"); + } + const messageExtra = { + classification: this._classification, + ...extra?.request !== void 0 && { request: extra.request }, + ...extra?.authInfo !== void 0 && { authInfo: extra.authInfo } + }; + if (isJSONRPCRequest(message)) { + this._requestId = message.id; + let resolve; + let reject; + const promise = new Promise((promiseResolve, promiseReject) => { + resolve = promiseResolve; + reject = promiseReject; + }); + this._deferredResponse = { + promise, + resolve, + reject, + settled: false + }; + if (signal !== void 0) { + const onAbort = () => void this.close(); + signal.addEventListener("abort", onAbort, { once: true }); + this._abortCleanup = () => signal.removeEventListener("abort", onAbort); + } + this._dispatchWindowOpen = true; + try { + this.onmessage(message, messageExtra); + } finally { + this._dispatchWindowOpen = false; + } + if (this._responseMode === "sse" && !this._closed && !this._deferredResponse.settled) this.upgradeToSse(); + return promise; + } + this.onmessage(message, messageExtra); + return new Response(null, { status: 202 }); + } + async send(message, options) { + if (this._closed) return; + const isResponse = isJSONRPCResultResponse(message) || isJSONRPCErrorResponse(message); + const relatedId = isResponse ? message.id : options?.relatedRequestId; + if (this._requestId === void 0 || relatedId === void 0 || relatedId !== this._requestId) { + if (isResponse) this.onerror?.(/* @__PURE__ */ new Error(`Received a response for an unknown request id: ${String(message.id)}`)); + return; + } + if (isResponse) { + if (this._terminalDelivered) return; + this._terminalDelivered = true; + const errorCode = isJSONRPCErrorResponse(message) ? message.error.code : void 0; + const ladderStatus = errorCode !== void 0 && (this._dispatchWindowOpen || errorCode === ProtocolErrorCode.MissingRequiredClientCapability) ? LADDER_ERROR_HTTP_STATUS[errorCode] : void 0; + if (ladderStatus !== void 0 && this._sse === void 0) { + this.settleResponse(Response.json(message, { + status: ladderStatus, + headers: { "Content-Type": "application/json" } + })); + queueMicrotask(() => void this.close()); + return; + } + if (this._sse !== void 0 || this._responseMode === "sse") { + if (this._sse === void 0) this.upgradeToSse(); + this.writeMessageFrame(message); + this.finalizeStream(); + return; + } + this.settleResponse(Response.json(message, { + status: 200, + headers: { "Content-Type": "application/json" } + })); + queueMicrotask(() => void this.close()); + return; + } + if (this._responseMode === "json") return; + if (this._sse === void 0) this.upgradeToSse(); + this.writeMessageFrame(message); + } + /** + * Writes an SSE comment frame (a keep-alive heartbeat). Dropped when the + * exchange is not currently streaming. + */ + writeCommentFrame(comment) { + if (this._closed || this._sse === void 0 || this._sse.closed) return; + const frame = comment.split("\n").map((line) => `: ${line}`).join("\n"); + this.writeFrame(`${frame}\n\n`); + } + async close() { + if (this._closed) return; + this._closed = true; + this._abortCleanup?.(); + this._abortCleanup = void 0; + if (this._sse?.keepAliveTimer !== void 0) clearInterval(this._sse.keepAliveTimer); + if (this._sse !== void 0 && !this._sse.closed) { + this._sse.closed = true; + try { + this._sse.controller.close(); + } catch {} + } + if (this._deferredResponse !== void 0 && !this._deferredResponse.settled) { + this._deferredResponse.settled = true; + this._deferredResponse.reject(new SdkError(SdkErrorCode.ConnectionClosed, "Connection closed before a response was produced")); + } + this.onclose?.(); + } + settleResponse(response) { + if (this._deferredResponse === void 0 || this._deferredResponse.settled) return; + this._deferredResponse.settled = true; + this._deferredResponse.resolve(response); + } + upgradeToSse() { + let controller; + const readable = new ReadableStream({ + start: (streamController) => { + controller = streamController; + }, + cancel: () => { + this.close(); + } + }); + this._sse = { + controller, + encoder: new TextEncoder(), + closed: false + }; + this._sse.keepAliveTimer = armSseKeepAlive(this._keepAliveMs, () => this.writeCommentFrame("keepalive")); + this.settleResponse(new Response(readable, { + status: 200, + headers: { + "Content-Type": "text/event-stream", + "Cache-Control": "no-cache, no-transform", + Connection: "keep-alive", + "X-Accel-Buffering": "no" + } + })); + } + finalizeStream() { + if (this._sse?.keepAliveTimer !== void 0) clearInterval(this._sse.keepAliveTimer); + if (this._sse !== void 0 && !this._sse.closed) { + this._sse.closed = true; + try { + this._sse.controller.close(); + } catch {} + } + queueMicrotask(() => void this.close()); + } + writeMessageFrame(message) { + this.writeFrame(`event: message\ndata: ${JSON.stringify(message)}\n\n`); + } + writeFrame(frame) { + if (this._sse === void 0 || this._sse.closed) return; + try { + this._sse.controller.enqueue(this._sse.encoder.encode(frame)); + } catch (error) { + this.onerror?.(/* @__PURE__ */ new Error(`Failed to write to the response stream: ${error}`)); + } + } +}; + +//#endregion +//#region src/server/invoke.ts +/** +* Serves one classified inbound message on the given server instance and +* returns the HTTP response for the exchange. +* +* The instance is connected to a fresh single-exchange transport, the message +* is injected through the normal transport message path, and whatever the +* dispatch layer produces (the handler result, a protocol-level rejection, or +* streamed related messages followed by the result) is captured as the +* returned `Response`. For request exchanges, teardown rides the transport's +* close chain once the terminal response has been delivered; notification +* exchanges resolve with the 202 response immediately and do NOT run the +* close chain — the transport stays connected until the caller closes it or +* drops the per-request instance, which is the caller's choice either way. +*/ +async function invoke(server, message, ctx) { + const transport = new PerRequestHTTPServerTransport({ + classification: ctx.classification, + ...ctx.responseMode !== void 0 && { responseMode: ctx.responseMode }, + ...ctx.keepAliveMs !== void 0 && { keepAliveMs: ctx.keepAliveMs } + }); + await server.connect(transport); + return transport.handleMessage(message, { + ...ctx.request !== void 0 && { request: ctx.request }, + ...ctx.authInfo !== void 0 && { authInfo: ctx.authInfo } + }); +} + +//#endregion +//#region src/server/streamableHttp.ts +/** +* Server transport for Web Standards Streamable HTTP: this implements the MCP Streamable HTTP transport specification +* using Web Standard APIs (`Request`, `Response`, `ReadableStream`). +* +* This transport works on any runtime that supports Web Standards: Node.js 18+, Cloudflare Workers, Deno, Bun, etc. +* +* In stateful mode: +* - Session ID is generated and included in response headers +* - Session ID is always included in initialization responses +* - Requests with invalid session IDs are rejected with `404 Not Found` +* - Non-initialization requests without a session ID are rejected with `400 Bad Request` +* - State is maintained in-memory (connections, message history) +* +* In stateless mode: +* - No Session ID is included in any responses +* - No session validation is performed +* +* @example Stateful setup +* ```ts source="./streamableHttp.examples.ts#WebStandardStreamableHTTPServerTransport_stateful" +* const server = new McpServer({ name: 'my-server', version: '1.0.0' }); +* +* const transport = new WebStandardStreamableHTTPServerTransport({ +* sessionIdGenerator: () => crypto.randomUUID() +* }); +* +* await server.connect(transport); +* ``` +* +* @example Stateless setup +* ```ts source="./streamableHttp.examples.ts#WebStandardStreamableHTTPServerTransport_stateless" +* const transport = new WebStandardStreamableHTTPServerTransport({ +* sessionIdGenerator: undefined +* }); +* ``` +* +* @example Hono.js +* ```ts source="./streamableHttp.examples.ts#WebStandardStreamableHTTPServerTransport_hono" +* app.all('/mcp', async c => { +* return transport.handleRequest(c.req.raw); +* }); +* ``` +* +* @example Cloudflare Workers +* ```ts source="./streamableHttp.examples.ts#WebStandardStreamableHTTPServerTransport_workers" +* const worker = { +* async fetch(request: Request): Promise { +* return transport.handleRequest(request); +* } +* }; +* ``` +*/ +var WebStandardStreamableHTTPServerTransport = class { + sessionIdGenerator; + _started = false; + _closed = false; + _streamMapping = /* @__PURE__ */ new Map(); + _requestToStreamMapping = /* @__PURE__ */ new Map(); + _requestResponseMap = /* @__PURE__ */ new Map(); + _initialized = false; + _enableJsonResponse = false; + _standaloneSseStreamId = "_GET_stream"; + _eventStore; + _onsessioninitialized; + _onsessionclosed; + _allowedHosts; + _allowedOrigins; + _enableDnsRebindingProtection; + _retryInterval; + _supportedProtocolVersions; + _keepAliveMs; + sessionId; + onclose; + onerror; + onmessage; + constructor(options = {}) { + this.sessionIdGenerator = options.sessionIdGenerator; + this._enableJsonResponse = options.enableJsonResponse ?? false; + this._eventStore = options.eventStore; + this._onsessioninitialized = options.onsessioninitialized; + this._onsessionclosed = options.onsessionclosed; + this._allowedHosts = options.allowedHosts; + this._allowedOrigins = options.allowedOrigins; + this._enableDnsRebindingProtection = options.enableDnsRebindingProtection ?? false; + this._retryInterval = options.retryInterval; + this._supportedProtocolVersions = options.supportedProtocolVersions ?? SUPPORTED_PROTOCOL_VERSIONS; + this._keepAliveMs = options.keepAliveMs ?? DEFAULT_SSE_KEEP_ALIVE_MS; + } + startKeepAlive(controller, encoder) { + if (this._closed) return void 0; + const timer = armSseKeepAlive(this._keepAliveMs, () => { + try { + controller.enqueue(encoder.encode(": keepalive\n\n")); + } catch { + if (timer !== void 0) clearInterval(timer); + } + }); + return timer; + } + /** + * Starts the transport. This is required by the {@linkcode Transport} interface but is a no-op + * for the Streamable HTTP transport as connections are managed per-request. + */ + async start() { + if (this._started) throw new Error("Transport already started"); + this._started = true; + } + /** + * Sets the supported protocol versions for header validation. + * Called by the server during {@linkcode server/server.Server.connect | connect()} to pass its supported versions. + */ + setSupportedProtocolVersions(versions) { + this._supportedProtocolVersions = versions; + } + /** + * Helper to create a JSON error response + */ + createJsonErrorResponse(status, code, message, options) { + const error = { + code, + message + }; + if (options?.data !== void 0) error.data = options.data; + return Response.json({ + jsonrpc: "2.0", + error, + id: null + }, { + status, + headers: { + "Content-Type": "application/json", + ...options?.headers + } + }); + } + /** + * Validates request headers for DNS rebinding protection. + * @returns Error response if validation fails, `undefined` if validation passes. + */ + validateRequestHeaders(req) { + if (!this._enableDnsRebindingProtection) return; + if (this._allowedHosts && this._allowedHosts.length > 0) { + const hostHeader = req.headers.get("host"); + if (!hostHeader || !this._allowedHosts.includes(hostHeader)) { + const error = `Invalid Host header: ${hostHeader}`; + this.onerror?.(new Error(error)); + return this.createJsonErrorResponse(403, -32e3, error); + } + } + if (this._allowedOrigins && this._allowedOrigins.length > 0) { + const originHeader = req.headers.get("origin"); + if (originHeader && !this._allowedOrigins.includes(originHeader)) { + const error = `Invalid Origin header: ${originHeader}`; + this.onerror?.(new Error(error)); + return this.createJsonErrorResponse(403, -32e3, error); + } + } + } + /** + * Handles an incoming HTTP request, whether `GET`, `POST`, or `DELETE` + * Returns a `Response` object (Web Standard) + */ + async handleRequest(req, options) { + if (this._closed) return this.createJsonErrorResponse(404, -32001, "Session not found"); + const validationError = this.validateRequestHeaders(req); + if (validationError) return validationError; + switch (req.method) { + case "POST": return this.handlePostRequest(req, options); + case "GET": return this.handleGetRequest(req); + case "DELETE": return this.handleDeleteRequest(req); + default: return this.handleUnsupportedRequest(); + } + } + /** + * Returns true if the client's protocol version supports empty SSE data in + * priming events (the fix shipped with protocol version `2025-11-25`). + * + * The version is checked for membership in this transport instance's + * supported protocol versions rather than with an open-ended + * `>= '2025-11-25'` comparison: the value may come from an `initialize` + * request body, which (unlike the `MCP-Protocol-Version` header) is not + * validated against `supportedProtocolVersions` before reaching this + * check. An unknown future version string must not silently enable + * behavior reserved for versions this transport actually supports. + */ + supportsEmptySSEData(protocolVersion) { + return this._supportedProtocolVersions.includes(protocolVersion) && protocolVersion >= "2025-11-25"; + } + /** + * Writes a priming event to establish resumption capability. + * Only sends if `eventStore` is configured (opt-in for resumability) and + * the client's protocol version supports empty SSE data (a supported + * version that is >= `2025-11-25`). + */ + async writePrimingEvent(controller, encoder, streamId, protocolVersion) { + if (!this._eventStore) return; + if (!this.supportsEmptySSEData(protocolVersion)) return; + const primingEventId = await this._eventStore.storeEvent(streamId, {}); + let primingEvent = `id: ${primingEventId}\ndata: \n\n`; + if (this._retryInterval !== void 0) primingEvent = `id: ${primingEventId}\nretry: ${this._retryInterval}\ndata: \n\n`; + controller.enqueue(encoder.encode(primingEvent)); + } + /** + * Handles `GET` requests for SSE stream + */ + async handleGetRequest(req) { + if (!req.headers.get("accept")?.includes("text/event-stream")) { + this.onerror?.(/* @__PURE__ */ new Error("Not Acceptable: Client must accept text/event-stream")); + return this.createJsonErrorResponse(406, -32e3, "Not Acceptable: Client must accept text/event-stream"); + } + const sessionError = this.validateSession(req); + if (sessionError) return sessionError; + const protocolError = this.validateProtocolVersion(req); + if (protocolError) return protocolError; + if (this._eventStore) { + const lastEventId = req.headers.get("last-event-id"); + if (lastEventId) return this.replayEvents(lastEventId); + } + if (this._streamMapping.get(this._standaloneSseStreamId) !== void 0) { + this.onerror?.(/* @__PURE__ */ new Error("Conflict: Only one SSE stream is allowed per session")); + return this.createJsonErrorResponse(409, -32e3, "Conflict: Only one SSE stream is allowed per session"); + } + const encoder = new TextEncoder(); + let streamController; + let keepAliveTimer; + const readable = new ReadableStream({ + start: (controller) => { + streamController = controller; + }, + cancel: () => { + if (keepAliveTimer !== void 0) clearInterval(keepAliveTimer); + if (this._streamMapping.get(this._standaloneSseStreamId)?.controller === streamController) this._streamMapping.delete(this._standaloneSseStreamId); + } + }); + const headers = { + "Content-Type": "text/event-stream", + "Cache-Control": "no-cache, no-transform", + Connection: "keep-alive", + "X-Accel-Buffering": "no" + }; + if (this.sessionId !== void 0) headers["mcp-session-id"] = this.sessionId; + this._streamMapping.set(this._standaloneSseStreamId, { + controller: streamController, + encoder, + cleanup: () => { + if (keepAliveTimer !== void 0) clearInterval(keepAliveTimer); + this._streamMapping.delete(this._standaloneSseStreamId); + try { + streamController.close(); + } catch {} + } + }); + keepAliveTimer = this.startKeepAlive(streamController, encoder); + return new Response(readable, { headers }); + } + /** + * Replays events that would have been sent after the specified event ID + * Only used when resumability is enabled + */ + async replayEvents(lastEventId) { + if (!this._eventStore) { + this.onerror?.(/* @__PURE__ */ new Error("Event store not configured")); + return this.createJsonErrorResponse(400, -32e3, "Event store not configured"); + } + try { + let streamId; + if (this._eventStore.getStreamIdForEventId) { + streamId = await this._eventStore.getStreamIdForEventId(lastEventId); + if (!streamId) { + this.onerror?.(/* @__PURE__ */ new Error("Invalid event ID format")); + return this.createJsonErrorResponse(400, -32e3, "Invalid event ID format"); + } + if (this._streamMapping.get(streamId) !== void 0) { + this.onerror?.(/* @__PURE__ */ new Error("Conflict: Stream already has an active connection")); + return this.createJsonErrorResponse(409, -32e3, "Conflict: Stream already has an active connection"); + } + } + const headers = { + "Content-Type": "text/event-stream", + "Cache-Control": "no-cache, no-transform", + Connection: "keep-alive", + "X-Accel-Buffering": "no" + }; + if (this.sessionId !== void 0) headers["mcp-session-id"] = this.sessionId; + const encoder = new TextEncoder(); + let streamController; + let keepAliveTimer; + let cancelled = false; + let replayedStreamId; + const readable = new ReadableStream({ + start: (controller) => { + streamController = controller; + }, + cancel: () => { + cancelled = true; + if (keepAliveTimer !== void 0) clearInterval(keepAliveTimer); + if (replayedStreamId !== void 0 && this._streamMapping.get(replayedStreamId)?.controller === streamController) this._streamMapping.delete(replayedStreamId); + } + }); + const replayedEventIds = /* @__PURE__ */ new Set(); + replayedStreamId = await this._eventStore.replayEventsAfter(lastEventId, { send: async (eventId, message) => { + replayedEventIds.add(eventId); + if (!this.writeSSEEvent(streamController, encoder, message, eventId)) try { + streamController.close(); + } catch {} + } }); + if (this._closed || cancelled) { + try { + streamController.close(); + } catch {} + return this.createJsonErrorResponse(404, -32001, "Session not found"); + } + this._streamMapping.get(replayedStreamId)?.cleanup(); + this._streamMapping.set(replayedStreamId, { + controller: streamController, + encoder, + replayedEventIds, + cleanup: () => { + if (keepAliveTimer !== void 0) clearInterval(keepAliveTimer); + this._streamMapping.delete(replayedStreamId); + try { + streamController.close(); + } catch {} + } + }); + if (replayedStreamId !== this._standaloneSseStreamId) { + if (![...this._requestToStreamMapping.values()].includes(replayedStreamId)) { + this._streamMapping.delete(replayedStreamId); + try { + streamController.close(); + } catch {} + } + } + if (this._streamMapping.get(replayedStreamId)?.controller === streamController) keepAliveTimer = this.startKeepAlive(streamController, encoder); + return new Response(readable, { headers }); + } catch (error) { + this.onerror?.(error); + return this.createJsonErrorResponse(500, -32e3, "Error replaying events"); + } + } + /** + * Writes an event to an SSE stream via controller with proper formatting + */ + writeSSEEvent(controller, encoder, message, eventId) { + try { + let eventData = `event: message\n`; + if (eventId) eventData += `id: ${eventId}\n`; + eventData += `data: ${JSON.stringify(message)}\n\n`; + controller.enqueue(encoder.encode(eventData)); + return true; + } catch (error) { + this.onerror?.(error); + return false; + } + } + /** + * Handles unsupported requests (`PUT`, `PATCH`, etc.) + */ + handleUnsupportedRequest() { + this.onerror?.(/* @__PURE__ */ new Error("Method not allowed.")); + return Response.json({ + jsonrpc: "2.0", + error: { + code: -32e3, + message: "Method not allowed." + }, + id: null + }, { + status: 405, + headers: { + Allow: "GET, POST, DELETE", + "Content-Type": "application/json" + } + }); + } + /** + * Handles `POST` requests containing JSON-RPC messages + */ + async handlePostRequest(req, options) { + try { + const acceptHeader = req.headers.get("accept"); + if (!acceptHeader?.includes("application/json") || !acceptHeader.includes("text/event-stream")) { + this.onerror?.(/* @__PURE__ */ new Error("Not Acceptable: Client must accept both application/json and text/event-stream")); + return this.createJsonErrorResponse(406, -32e3, "Not Acceptable: Client must accept both application/json and text/event-stream"); + } + if (!isJsonContentType(req.headers.get("content-type"))) { + this.onerror?.(/* @__PURE__ */ new Error("Unsupported Media Type: Content-Type must be application/json")); + return this.createJsonErrorResponse(415, -32e3, "Unsupported Media Type: Content-Type must be application/json"); + } + const request = req; + let rawMessage; + if (options?.parsedBody === void 0) try { + rawMessage = await req.json(); + } catch (error) { + this.onerror?.(error); + return this.createJsonErrorResponse(400, -32700, "Parse error: Invalid JSON"); + } + else rawMessage = options.parsedBody; + let messages; + try { + messages = Array.isArray(rawMessage) ? rawMessage.map((msg) => JSONRPCMessageSchema.parse(msg)) : [JSONRPCMessageSchema.parse(rawMessage)]; + } catch (error) { + this.onerror?.(error); + return this.createJsonErrorResponse(400, -32700, "Parse error: Invalid JSON-RPC message"); + } + if (this._closed) return this.createJsonErrorResponse(404, -32001, "Session not found"); + const isInitializationRequest = messages.some((element) => isInitializeRequest(element)); + if (isInitializationRequest) { + if (this._initialized && this.sessionId !== void 0) { + this.onerror?.(/* @__PURE__ */ new Error("Invalid Request: Server already initialized")); + return this.createJsonErrorResponse(400, -32600, "Invalid Request: Server already initialized"); + } + if (messages.length > 1) { + this.onerror?.(/* @__PURE__ */ new Error("Invalid Request: Only one initialization request is allowed")); + return this.createJsonErrorResponse(400, -32600, "Invalid Request: Only one initialization request is allowed"); + } + this.sessionId = this.sessionIdGenerator?.(); + this._initialized = true; + if (this.sessionId && this._onsessioninitialized) await Promise.resolve(this._onsessioninitialized(this.sessionId)); + } + if (!isInitializationRequest) { + const sessionError = this.validateSession(req); + if (sessionError) return sessionError; + const protocolError = this.validateProtocolVersion(req); + if (protocolError) return protocolError; + } + if (this._closed) return this.createJsonErrorResponse(404, -32001, "Session not found"); + if (!messages.some((element) => isJSONRPCRequest(element))) { + for (const message of messages) this.onmessage?.(message, { + authInfo: options?.authInfo, + request + }); + return new Response(null, { status: 202 }); + } + const streamId = crypto.randomUUID(); + const initRequest = messages.find((m) => isInitializeRequest(m)); + const clientProtocolVersion = initRequest ? initRequest.params.protocolVersion : req.headers.get("mcp-protocol-version") ?? DEFAULT_NEGOTIATED_PROTOCOL_VERSION; + if (this._enableJsonResponse) return new Promise((resolve) => { + this._streamMapping.set(streamId, { + resolveJson: resolve, + cleanup: () => { + this._streamMapping.delete(streamId); + } + }); + for (const message of messages) if (isJSONRPCRequest(message)) this._requestToStreamMapping.set(message.id, streamId); + for (const message of messages) this.onmessage?.(message, { + authInfo: options?.authInfo, + request + }); + }); + const encoder = new TextEncoder(); + let streamController; + let keepAliveTimer; + const readable = new ReadableStream({ + start: (controller) => { + streamController = controller; + }, + cancel: () => { + if (keepAliveTimer !== void 0) clearInterval(keepAliveTimer); + if (this._streamMapping.get(streamId)?.controller === streamController) this._streamMapping.delete(streamId); + } + }); + const headers = { + "Content-Type": "text/event-stream", + "Cache-Control": "no-cache, no-transform", + Connection: "keep-alive", + "X-Accel-Buffering": "no" + }; + if (this.sessionId !== void 0) headers["mcp-session-id"] = this.sessionId; + for (const message of messages) if (isJSONRPCRequest(message)) { + this._streamMapping.set(streamId, { + controller: streamController, + encoder, + cleanup: () => { + if (keepAliveTimer !== void 0) clearInterval(keepAliveTimer); + this._streamMapping.delete(streamId); + try { + streamController.close(); + } catch {} + } + }); + this._requestToStreamMapping.set(message.id, streamId); + } + await this.writePrimingEvent(streamController, encoder, streamId, clientProtocolVersion); + for (const message of messages) { + let closeSSEStream; + let closeStandaloneSSEStream; + if (isJSONRPCRequest(message) && this._eventStore && this.supportsEmptySSEData(clientProtocolVersion)) { + closeSSEStream = () => { + this.closeSSEStream(message.id); + }; + closeStandaloneSSEStream = () => { + this.closeStandaloneSSEStream(); + }; + } + this.onmessage?.(message, { + authInfo: options?.authInfo, + request, + closeSSEStream, + closeStandaloneSSEStream + }); + } + if (this._streamMapping.get(streamId)?.controller === streamController) keepAliveTimer = this.startKeepAlive(streamController, encoder); + return new Response(readable, { + status: 200, + headers + }); + } catch (error) { + this.onerror?.(error); + return this.createJsonErrorResponse(400, -32700, "Parse error", { data: String(error) }); + } + } + /** + * Handles `DELETE` requests to terminate sessions + */ + async handleDeleteRequest(req) { + const sessionError = this.validateSession(req); + if (sessionError) return sessionError; + const protocolError = this.validateProtocolVersion(req); + if (protocolError) return protocolError; + try { + await Promise.resolve(this._onsessionclosed?.(this.sessionId)); + return new Response(null, { status: 200 }); + } finally { + await this.close(); + } + } + /** + * Validates session ID for non-initialization requests. + * Returns `Response` error if invalid, `undefined` otherwise + */ + validateSession(req) { + if (this.sessionIdGenerator === void 0) return; + if (!this._initialized) { + this.onerror?.(/* @__PURE__ */ new Error("Bad Request: Server not initialized")); + return this.createJsonErrorResponse(400, -32e3, "Bad Request: Server not initialized"); + } + const sessionId = req.headers.get("mcp-session-id"); + if (!sessionId) { + this.onerror?.(/* @__PURE__ */ new Error("Bad Request: Mcp-Session-Id header is required")); + return this.createJsonErrorResponse(400, -32e3, "Bad Request: Mcp-Session-Id header is required"); + } + if (sessionId !== this.sessionId) { + this.onerror?.(/* @__PURE__ */ new Error("Session not found")); + return this.createJsonErrorResponse(404, -32001, "Session not found"); + } + } + /** + * Validates the `MCP-Protocol-Version` header on incoming requests. + * + * For initialization: Version negotiation handles unknown versions gracefully + * (server responds with its supported version). + * + * For subsequent requests with `MCP-Protocol-Version` header: + * - Accept if in supported list + * - 400 if unsupported + * + * For HTTP requests without the `MCP-Protocol-Version` header: + * - Accept and default to the version negotiated at initialization + */ + validateProtocolVersion(req) { + const protocolVersion = req.headers.get("mcp-protocol-version"); + if (protocolVersion !== null && !this._supportedProtocolVersions.includes(protocolVersion)) { + const error = `Bad Request: Unsupported protocol version: ${protocolVersion} (supported versions: ${this._supportedProtocolVersions.join(", ")})`; + this.onerror?.(new Error(error)); + return this.createJsonErrorResponse(400, -32e3, error); + } + } + async close() { + if (this._closed) return; + this._closed = true; + for (const { cleanup } of this._streamMapping.values()) cleanup(); + this._streamMapping.clear(); + this._requestResponseMap.clear(); + this.onclose?.(); + } + /** + * Close an SSE stream for a specific request, triggering client reconnection. + * Use this to implement polling behavior during long-running operations - + * client will reconnect after the retry interval specified in the priming event. + */ + closeSSEStream(requestId) { + const streamId = this._requestToStreamMapping.get(requestId); + if (!streamId) return; + const stream = this._streamMapping.get(streamId); + if (stream) stream.cleanup(); + } + /** + * Close the standalone `GET` SSE stream, triggering client reconnection. + * Use this to implement polling behavior for server-initiated notifications. + */ + closeStandaloneSSEStream() { + const stream = this._streamMapping.get(this._standaloneSseStreamId); + if (stream) stream.cleanup(); + } + async send(message, options) { + let requestId = options?.relatedRequestId; + if (isJSONRPCResultResponse(message) || isJSONRPCErrorResponse(message)) requestId = message.id; + if (requestId === void 0) { + if (isJSONRPCResultResponse(message) || isJSONRPCErrorResponse(message)) throw new Error("Cannot send a response on a standalone SSE stream unless resuming a previous client request"); + let eventId; + if (this._eventStore) eventId = await this._eventStore.storeEvent(this._standaloneSseStreamId, message); + const standaloneSse = this._streamMapping.get(this._standaloneSseStreamId); + if (standaloneSse === void 0) return; + if (standaloneSse.controller && standaloneSse.encoder && (eventId === void 0 || !standaloneSse.replayedEventIds?.has(eventId))) this.writeSSEEvent(standaloneSse.controller, standaloneSse.encoder, message, eventId); + return; + } + const streamId = this._requestToStreamMapping.get(requestId); + if (!streamId) throw new Error(`No connection established for request ID: ${String(requestId)}`); + let stream = this._streamMapping.get(streamId); + if (!this._enableJsonResponse) { + let eventId; + if (this._eventStore) { + eventId = await this._eventStore.storeEvent(streamId, message); + stream = this._streamMapping.get(streamId); + } + if (stream?.controller && stream?.encoder && (eventId === void 0 || !stream.replayedEventIds?.has(eventId))) this.writeSSEEvent(stream.controller, stream.encoder, message, eventId); + } + if (isJSONRPCResultResponse(message) || isJSONRPCErrorResponse(message)) { + this._requestResponseMap.set(requestId, message); + const relatedIds = [...this._requestToStreamMapping.entries()].filter(([_, sid]) => sid === streamId).map(([id]) => id); + if (relatedIds.every((id) => this._requestResponseMap.has(id))) { + if (!stream) { + if (this._enableJsonResponse) throw new Error(`No connection established for request ID: ${String(requestId)}`); + if (!this._eventStore) { + this.onerror?.(/* @__PURE__ */ new Error(`Response for request ID ${String(requestId)} is undeliverable: per-request stream is disconnected and no eventStore is configured`)); + for (const id of relatedIds) { + this._requestResponseMap.delete(id); + this._requestToStreamMapping.delete(id); + } + return; + } + for (const id of relatedIds) { + this._requestResponseMap.delete(id); + this._requestToStreamMapping.delete(id); + } + return; + } + if (this._enableJsonResponse && stream.resolveJson) { + const headers = { "Content-Type": "application/json" }; + if (this.sessionId !== void 0) headers["mcp-session-id"] = this.sessionId; + const responses = relatedIds.map((id) => this._requestResponseMap.get(id)); + if (responses.length === 1) stream.resolveJson(Response.json(responses[0], { + status: 200, + headers + })); + else stream.resolveJson(Response.json(responses, { + status: 200, + headers + })); + stream.cleanup(); + } else stream.cleanup(); + for (const id of relatedIds) { + this._requestResponseMap.delete(id); + this._requestToStreamMapping.delete(id); + } + } + } + } +}; + +//#endregion +//#region src/server/createMcpHandler.ts +/** +* The JSON-RPC id to echo on an entry-built error response: the body's `id` +* when the body is a single JSON-RPC request whose id is a string or number, +* `null` otherwise. Error responses must carry the id of the request they +* correspond to whenever it could be read; `null` is reserved for the cases +* where no single request id is determinable — unparseable bodies, body-less +* methods, notifications, posted responses and batch arrays. +*/ +function echoableRequestId(body) { + if (body === null || typeof body !== "object" || Array.isArray(body)) return null; + const { method, id } = body; + if (typeof method !== "string") return null; + return typeof id === "string" || typeof id === "number" ? id : null; +} +function jsonRpcErrorResponse(httpStatus, code, message, data, id = null) { + return Response.json({ + jsonrpc: "2.0", + error: { + code, + message, + ...data !== void 0 && { data } + }, + id + }, { status: httpStatus }); +} +function rejectionResponse(rejection, id = null) { + return jsonRpcErrorResponse(rejection.httpStatus, rejection.code, rejection.message, rejection.data, id); +} +function toError(value) { + return value instanceof Error ? value : new Error(String(value)); +} +function internalServerErrorResponse(id = null) { + return jsonRpcErrorResponse(500, -32603, "Internal server error", void 0, id); +} +/** +* The entry's default legacy serving (`legacy: 'stateless'`): per-request +* stateless serving of 2025-era traffic using the same factory as the modern +* path. Exported as a standalone building block for hand-wired compositions +* (for example mounting legacy stateless serving on its own route next to a +* strict modern endpoint). +* +* Each POST is served by a fresh instance from the factory connected to a +* fresh streamable HTTP transport constructed with only +* `sessionIdGenerator: undefined` — the established stateless idiom, unchanged. +* Because serving is per-request and stateless, GET and DELETE (2025 session +* operations) are answered with `405` / `Method not allowed.`, exactly like the +* canonical stateless example. +* +* The optional `onerror` callback receives factory and serving failures on +* this leg (reporting only — the response stays the 500 internal-error body). +* The entry passes its own `onerror` here when expanding the default, so +* legacy-leg failures are never silently swallowed. +*/ +function createLegacyStatelessFallback(factory, onerror, keepAliveMs) { + return async (request, options) => { + if (request.method.toUpperCase() !== "POST") return jsonRpcErrorResponse(405, -32e3, "Method not allowed."); + try { + const product = await factory({ + era: "legacy", + ...options?.authInfo !== void 0 && { authInfo: options.authInfo }, + requestInfo: request + }); + const transport = new WebStandardStreamableHTTPServerTransport({ + sessionIdGenerator: void 0, + ...keepAliveMs !== void 0 && { keepAliveMs } + }); + await product.connect(transport); + const teardown = () => { + transport.close().catch(() => {}); + product.close().catch(() => {}); + }; + request.signal?.addEventListener("abort", teardown, { once: true }); + const response = await transport.handleRequest(request, { + ...options?.authInfo !== void 0 && { authInfo: options.authInfo }, + ...options?.parsedBody !== void 0 && { parsedBody: options.parsedBody } + }); + if (response.body === null || mediaTypeEssence(response.headers.get("content-type")) !== "text/event-stream") { + teardown(); + return response; + } + const reader = response.body.getReader(); + let toreDown = false; + const completeExchange = () => { + if (!toreDown) { + toreDown = true; + teardown(); + } + }; + const monitoredBody = new ReadableStream({ + pull: async (controller) => { + try { + const { done, value } = await reader.read(); + if (done) { + completeExchange(); + controller.close(); + return; + } + if (value !== void 0) controller.enqueue(value); + } catch (error) { + completeExchange(); + controller.error(error); + } + }, + cancel: (reason) => { + completeExchange(); + return reader.cancel(reason).catch(() => {}); + } + }); + return new Response(monitoredBody, { + status: response.status, + statusText: response.statusText, + headers: response.headers + }); + } catch (error) { + try { + onerror?.(toError(error)); + } catch {} + return internalServerErrorResponse(echoableRequestId(options?.parsedBody)); + } + }; +} +function legacyStatelessFallback(factory, onerror) { + return createLegacyStatelessFallback(factory, onerror); +} +/** +* The entry's classification step: read the request body exactly once (unless +* a pre-parsed body is supplied) and classify the request with +* {@linkcode classifyInboundRequest}. This is the single code path behind both +* {@linkcode createMcpHandler}'s routing and the exported +* {@linkcode isLegacyRequest} predicate, so the two can never disagree. +* +* Pass `needsForward: false` when the caller never reads `forwardRequest` — +* the body-preserving clone is then skipped and `forwardRequest` is the +* (consumed) input request. +*/ +async function classifyEntryRequest(request, providedParsedBody, needsForward = true) { + const httpMethod = request.method.toUpperCase(); + let body; + let parsedBody = providedParsedBody; + let forwardRequest = request; + let unparseable = false; + if (httpMethod === "POST") { + if (parsedBody === void 0) { + if (needsForward) forwardRequest = request.clone(); + let bodyText; + try { + bodyText = await request.text(); + } catch { + return { step: "unreadable-body" }; + } + try { + body = bodyText.length === 0 ? void 0 : JSON.parse(bodyText); + } catch { + unparseable = true; + } + if (!unparseable && body !== void 0) parsedBody = body; + } else body = parsedBody; + if (unparseable || body === void 0) return { + step: "no-json-body", + forwardRequest + }; + } + return { + step: "classified", + outcome: classifyInboundRequest({ + httpMethod, + protocolVersionHeader: request.headers.get("mcp-protocol-version") ?? void 0, + mcpMethodHeader: request.headers.get("mcp-method") ?? void 0, + mcpNameHeader: request.headers.get("mcp-name") ?? void 0, + ...body !== void 0 && { body } + }), + body, + parsedBody, + forwardRequest + }; +} +/** +* Whether {@linkcode createMcpHandler} would route this request to its legacy +* (2025-era) serving rather than the modern (2026-07-28) path. +* +* Call it with just the request: `await isLegacyRequest(request)`. For a +* `POST` the body is read from an internal clone, so the request you pass +* stays fully readable for whichever handler you route it to — no second +* argument is needed. (In a Node `(req, res)` handler, build that `Request` +* with `toWebRequest(req)` from `@modelcontextprotocol/node`; behind a body +* parser, which has already drained the Node stream, build it as +* `toWebRequest(req, req.body)` so the bytes come from the parsed body — +* either way the predicate still takes just the request.) The optional +* `parsedBody` is a perf escape hatch for a body you already hold parsed: +* pass it and the predicate classifies from the value directly, reading and +* cloning nothing. It is needed, not just faster, when the request's own +* body was already read — the internal clone is then impossible (cloning a +* used body throws a `TypeError`), so such a single-argument call rejects +* instead of guessing. +* +* This is the entry's own classification step exported as a predicate — it +* runs exactly the code `createMcpHandler` runs to make the routing decision, +* not a re-implementation — so a hand-wired composition that branches on it +* can never disagree with the entry. It is classification only: hand-wired +* compositions must validate Content-Type themselves (415 for POSTs whose +* media type is not `application/json`, via {@linkcode isJsonContentType}) +* before dispatching either leg — routing the legacy leg into the SDK +* transports gets their built-in check, but a custom modern leg has none. Use it to keep an existing legacy +* deployment (for example a sessionful streamable HTTP wiring) serving 2025 +* traffic next to a strict modern endpoint, now that the entry has no +* handler-valued `legacy` option: +* +* ```ts +* import { createMcpHandler, isLegacyRequest } from '@modelcontextprotocol/server'; +* +* const modern = createMcpHandler(factory, { legacy: 'reject' }); +* +* export default { +* async fetch(request: Request): Promise { +* if (await isLegacyRequest(request)) { +* // e.g. an existing sessionful WebStandardStreamableHTTPServerTransport wiring +* return myExistingLegacyHandler(request); +* } +* return modern.fetch(request); +* } +* }; +* ``` +* +* Semantics (identical to the entry's routing): +* +* - Returns `true` only for requests with no per-request `_meta` envelope +* claim: claim-less POSTs (including the `initialize` handshake and 2025-era +* notification POSTs without a modern protocol-version header), body-less +* GET/DELETE session operations, all-legacy JSON-RPC batch arrays, posted +* JSON-RPC responses, and POSTs whose body is empty or not valid JSON. +* - Returns `false` for everything the modern path answers, including its +* validation-ladder rejections: a request carrying the envelope claim (even +* one naming a revision the endpoint does not serve — the modern path +* answers it with the unsupported-protocol-version error), a malformed +* envelope behind a present claim (answered `-32602`), a request whose +* `MCP-Protocol-Version` header names a modern revision but that lacks the +* envelope (`-32602`), and header/body mismatches (`-32020`). Consumers +* routing on the predicate must send `false` traffic to the modern handler, +* never to a legacy handler — the modern path owns those error answers. +* - `server/discover` probes sent by negotiating clients always carry the +* envelope claim, so they are never legacy; a hand-built claim-less POST to +* a method named `server/discover` has no claim and classifies legacy, +* exactly as the entry itself routes it. +*/ +async function isLegacyRequest(request, parsedBody) { + const classified = await classifyEntryRequest(parsedBody === void 0 && request.method.toUpperCase() === "POST" ? request.clone() : request, parsedBody, false); + return classified.step === "no-json-body" || classified.step === "classified" && classified.outcome.kind === "legacy"; +} +/** +* Creates an HTTP handler that serves the 2026-07-28 protocol revision from a +* per-request server factory and, by default, falls back to old-school +* stateless serving for 2025-era traffic. Pass `legacy: 'reject'` for a +* modern-only strict endpoint. +* +* Mounting: `handler.fetch` is the web-standard face (Cloudflare Workers, +* Deno, Bun, Hono's `c.req.raw`); for Express/Fastify/plain `node:http`, wrap +* the handler once with `toNodeHandler(handler)` from +* `@modelcontextprotocol/node`. When mounting bare on a fetch-native runtime, +* put Origin/Host validation in front of the handler — the entry itself is +* deliberately validation-free: +* +* ```ts +* import { hostHeaderValidationResponse, originValidationResponse, localhostAllowedHostnames, localhostAllowedOrigins } from '@modelcontextprotocol/server'; +* +* export default { +* async fetch(request: Request): Promise { +* const rejected = +* hostHeaderValidationResponse(request, localhostAllowedHostnames()) ?? +* originValidationResponse(request, localhostAllowedOrigins()); +* return rejected ?? handler.fetch(request); +* } +* }; +* ``` +* +* Use ONE factory for both legs: the same tools/resources/prompts definition +* backs the modern path and the stateless legacy fallback, so the two eras can +* never drift apart. To keep an existing legacy deployment (for example a +* sessionful streamable HTTP wiring) serving 2025 traffic instead of the +* stateless fallback, route in user land with {@linkcode isLegacyRequest} in +* front of a strict handler — see that predicate's documentation for the +* pattern. Power users composing transport-neutral routing can also use the +* exported building blocks directly: {@linkcode classifyInboundRequest} for +* the era decision and `PerRequestHTTPServerTransport` for single-exchange +* serving — such compositions must reject POSTs whose Content-Type media type +* is not `application/json` (415) before parsing the body, using +* {@linkcode isJsonContentType}; neither building block performs this +* validation itself. +* +* The entry performs no token verification: `authInfo` given to `fetch` is +* passed through to handlers and the factory as-is and is never derived from +* request headers. +*/ +function createMcpHandler(factory, options = {}) { + const { legacy, onerror, responseMode } = options; + if (typeof legacy === "function") throw new TypeError("The 'legacy' option only accepts 'stateless' or 'reject', not a handler function. To serve 2025-era traffic with your own handler, route in user land with the exported isLegacyRequest(request) predicate in front of a strict (legacy: 'reject') handler."); + /** Modern per-request instances with an exchange still in flight (close() tears these down). */ + const inflight = /* @__PURE__ */ new Set(); + let closed = false; + const reportError = (error) => { + try { + onerror?.(error); + } catch {} + }; + const bus = options.bus ?? new InMemoryServerEventBus(reportError); + const notify = createServerNotifier(bus); + const listenRouter = createListenRouter({ + bus, + maxSubscriptions: options.maxSubscriptions ?? DEFAULT_MAX_SUBSCRIPTIONS, + keepAliveMs: options.keepAliveMs ?? DEFAULT_SSE_KEEP_ALIVE_MS, + onerror: reportError + }); + if (responseMode === "json") console.warn("responseMode: 'json' drops mid-call notifications. subscriptions/listen streams are always served over SSE regardless; other notifications emitted before a result are dropped."); + const legacyHandler = legacy === "reject" ? void 0 : createLegacyStatelessFallback(factory, reportError, options.keepAliveMs); + async function serveModern(route, request, authInfo) { + const claimedRevision = route.classification.revision; + if (claimedRevision === void 0 || !SUPPORTED_MODERN_PROTOCOL_VERSIONS.includes(claimedRevision)) { + const error = new UnsupportedProtocolVersionError({ + supported: [...SUPPORTED_MODERN_PROTOCOL_VERSIONS], + requested: claimedRevision ?? "unknown" + }); + reportError(error); + return jsonRpcErrorResponse(400, error.code, error.message, error.data, echoableRequestId(route.message)); + } + const stdHeaderRejection = validateStandardRequestHeaders({ + httpMethod: request.method, + mcpMethodHeader: request.headers.get("mcp-method") ?? void 0, + mcpNameHeader: request.headers.get("mcp-name") ?? void 0 + }, route); + if (stdHeaderRejection !== void 0) { + reportError(/* @__PURE__ */ new Error(`Rejected inbound request (${stdHeaderRejection.cell}): ${stdHeaderRejection.message}`)); + return rejectionResponse(stdHeaderRejection, echoableRequestId(route.message)); + } + const meta = route.messageKind === "request" ? requestMetaOf(route.message.params) : void 0; + const declaredClientCapabilities = meta?.[CLIENT_CAPABILITIES_META_KEY]; + if (route.messageKind === "request") { + const required = requiredClientCapabilitiesForRequest(route.message.method); + if (required !== void 0) { + const missing = missingClientCapabilities(required, declaredClientCapabilities); + if (missing !== void 0) { + const error = new MissingRequiredClientCapabilityError({ requiredCapabilities: missing }); + reportError(error); + return jsonRpcErrorResponse(httpStatusForErrorCode(error.code, "ladder"), error.code, error.message, error.data, route.message.id); + } + } + } + const product = await factory({ + era: "modern", + ...authInfo !== void 0 && { authInfo }, + requestInfo: request + }); + const server = product instanceof McpServer ? product.server : product; + if (route.messageKind === "request" && route.message.method === "subscriptions/listen") { + const capabilities = server.getCapabilities(); + const serverInfo = serverIdentityOf(server); + product.close().catch(reportError); + return listenRouter.serve(route.message, request.signal, capabilities, serverInfo); + } + if (route.messageKind === "request" && route.message.method === "tools/call" && product instanceof McpServer) { + const callParams = route.message.params; + const toolName = typeof callParams?.name === "string" ? callParams.name : void 0; + const inputSchema = toolName === void 0 ? void 0 : product.toolInputSchemaJson(toolName); + if (inputSchema !== void 0) { + const scan = scanXMcpHeaderDeclarations(inputSchema); + if (scan.valid && scan.declarations.length > 0) { + const rejection = validateMcpParamHeaders(scan.declarations, callParams?.arguments, request.headers); + if (rejection !== void 0) { + product.close().catch(reportError); + reportError(/* @__PURE__ */ new Error(`Rejected inbound request (${rejection.cell}): ${rejection.message}`)); + return rejectionResponse(rejection, route.message.id); + } + } + } + } + setNegotiatedProtocolVersion(server, claimedRevision); + installModernOnlyHandlers(server, SUPPORTED_MODERN_PROTOCOL_VERSIONS); + if (meta !== void 0) seedClientIdentityFromEnvelope(server, { + clientInfo: meta[CLIENT_INFO_META_KEY], + clientCapabilities: declaredClientCapabilities + }); + const previousOnClose = server.onclose; + inflight.add(server); + server.onclose = () => { + inflight.delete(server); + previousOnClose?.(); + }; + try { + const response = await invoke(product, route.message, { + classification: route.classification, + request, + ...authInfo !== void 0 && { authInfo }, + ...responseMode !== void 0 && { responseMode }, + ...options.keepAliveMs !== void 0 && { keepAliveMs: options.keepAliveMs } + }); + if (route.messageKind === "notification") queueMicrotask(() => void server.close().catch(() => {})); + return response; + } catch (error) { + if (error instanceof SdkError && error.code === SdkErrorCode.ConnectionClosed) return new Response(null, { status: 499 }); + await server.close().catch(() => {}); + inflight.delete(server); + reportError(toError(error)); + return internalServerErrorResponse(echoableRequestId(route.message)); + } + } + async function serveLegacyRoute(route, forwardRequest, authInfo, parsedBody) { + if (legacyHandler !== void 0) return legacyHandler(forwardRequest, { + ...authInfo !== void 0 && { authInfo }, + ...parsedBody !== void 0 && { parsedBody } + }); + const strict = modernOnlyStrictRejection(route, SUPPORTED_MODERN_PROTOCOL_VERSIONS); + if (strict === void 0) return new Response(null, { status: 202 }); + reportError(/* @__PURE__ */ new Error(`Rejected 2025-era request on a modern-only endpoint (${strict.cell}): ${strict.message}`)); + return rejectionResponse(strict, echoableRequestId(parsedBody)); + } + async function handle(request, requestOptions) { + const authInfo = requestOptions?.authInfo; + if (request.method.toUpperCase() === "POST" && !isJsonContentType(request.headers.get("content-type"))) { + reportError(/* @__PURE__ */ new Error("Unsupported Media Type: Content-Type must be application/json")); + return jsonRpcErrorResponse(415, -32e3, "Unsupported Media Type: Content-Type must be application/json"); + } + const classified = await classifyEntryRequest(request, requestOptions?.parsedBody); + if (classified.step === "unreadable-body") return jsonRpcErrorResponse(400, -32700, "Parse error: the request body could not be read"); + if (classified.step === "no-json-body") { + if (legacyHandler !== void 0) return legacyHandler(classified.forwardRequest, { ...authInfo !== void 0 && { authInfo } }); + return jsonRpcErrorResponse(400, -32700, "Parse error: the request body is not valid JSON"); + } + const { outcome, body, parsedBody, forwardRequest } = classified; + try { + switch (outcome.kind) { + case "reject": + reportError(/* @__PURE__ */ new Error(`Rejected inbound request (${outcome.cell}): ${outcome.message}`)); + return rejectionResponse(outcome, echoableRequestId(body)); + case "modern": return await serveModern(outcome, request, authInfo); + case "legacy": return await serveLegacyRoute(outcome, forwardRequest, authInfo, parsedBody); + } + } catch (error) { + reportError(toError(error)); + return internalServerErrorResponse(echoableRequestId(body)); + } + } + const fetchFace = async (request, requestOptions) => { + if (closed) throw new Error("This MCP handler has been closed"); + try { + return await handle(request, requestOptions); + } catch (error) { + reportError(toError(error)); + return internalServerErrorResponse(echoableRequestId(requestOptions?.parsedBody)); + } + }; + return { + fetch: fetchFace, + notify, + bus, + close: async () => { + closed = true; + listenRouter.closeAll(); + const closing = [...inflight].map((server) => server.close().catch(() => {})); + inflight.clear(); + await Promise.all(closing); + } + }; +} + +//#endregion +//#region src/server/middleware/bearerAuth.ts +function headerQuotedValue(value) { + return value.replaceAll(/[\\"]/g, String.raw`\$&`).replaceAll(/[^\u0020-\u007E]/g, " "); +} +function buildWwwAuthenticateHeader(errorCode, description, requiredScopes, resourceMetadataUrl) { + let header = `Bearer error="${headerQuotedValue(errorCode)}", error_description="${headerQuotedValue(description)}"`; + if (requiredScopes.length > 0) header += `, scope="${requiredScopes.join(" ")}"`; + if (resourceMetadataUrl) header += `, resource_metadata="${resourceMetadataUrl}"`; + return header; +} +/** +* Validate a raw `Authorization` header value as a Bearer token and return +* the verified {@link AuthInfo}. +* +* The runtime-neutral core of Bearer authentication: it parses the header, +* runs the verifier, enforces `requiredScopes`, and rejects tokens without an +* expiration or past it. On any failure it throws an {@link OAuthError} — +* pass that to {@link bearerAuthChallengeResponse} for the matching HTTP +* answer, or use {@link requireBearerAuth} to get both steps as one call. +* +* Framework adapters build on this: `requireBearerAuth` from +* `@modelcontextprotocol/express` feeds it `req.headers.authorization`. +*/ +async function verifyBearerToken(authorizationHeader, options) { + const { verifier, requiredScopes = [] } = options; + if (!authorizationHeader) throw new OAuthError(OAuthErrorCode.InvalidToken, "Missing Authorization header"); + const [type, token] = authorizationHeader.split(" "); + if (type?.toLowerCase() !== "bearer" || !token) throw new OAuthError(OAuthErrorCode.InvalidToken, "Invalid Authorization header format, expected 'Bearer TOKEN'"); + const authInfo = await verifier.verifyAccessToken(token); + if (requiredScopes.length > 0) { + if (!requiredScopes.every((scope) => authInfo.scopes.includes(scope))) throw new OAuthError(OAuthErrorCode.InsufficientScope, "Insufficient scope"); + } + if (typeof authInfo.expiresAt !== "number" || Number.isNaN(authInfo.expiresAt)) throw new OAuthError(OAuthErrorCode.InvalidToken, "Token has no expiration time"); + else if (authInfo.expiresAt < Date.now() / 1e3) throw new OAuthError(OAuthErrorCode.InvalidToken, "Token has expired"); + return authInfo; +} +/** +* Build the HTTP answer for a Bearer authentication failure. +* +* Maps an {@link OAuthError} to its status — `401` for `invalid_token` and +* `403` for `insufficient_scope` (both carrying the `WWW-Authenticate: Bearer …` +* challenge, with `resource_metadata` when configured so clients can discover +* the Authorization Server), `500` for `server_error`, `400` for anything +* else. A non-`OAuthError` value answers `500 server_error`. The body is the +* OAuth error JSON. +*/ +function bearerAuthChallengeResponse(error, options) { + const { requiredScopes = [], resourceMetadataUrl } = options ?? {}; + if (!(error instanceof OAuthError)) { + const serverError = new OAuthError(OAuthErrorCode.ServerError, "Internal Server Error"); + return Response.json(serverError.toResponseObject(), { status: 500 }); + } + switch (error.code) { + case OAuthErrorCode.InvalidToken: { + const challenge = buildWwwAuthenticateHeader(error.code, error.message, requiredScopes, resourceMetadataUrl); + return Response.json(error.toResponseObject(), { + status: 401, + headers: { "WWW-Authenticate": challenge } + }); + } + case OAuthErrorCode.InsufficientScope: { + const challenge = buildWwwAuthenticateHeader(error.code, error.message, requiredScopes, resourceMetadataUrl); + return Response.json(error.toResponseObject(), { + status: 403, + headers: { "WWW-Authenticate": challenge } + }); + } + case OAuthErrorCode.ServerError: return Response.json(error.toResponseObject(), { status: 500 }); + default: return Response.json(error.toResponseObject(), { status: 400 }); + } +} +/** +* Require a valid Bearer token on web-standard requests. +* +* The framework-free counterpart of `requireBearerAuth` from +* `@modelcontextprotocol/express`, for hosts whose HTTP surface is a +* `fetch(request)` handler — Cloudflare Workers, Deno, Bun, Hono. The +* returned gate resolves to the verified {@link AuthInfo}, or to the +* ready-to-return challenge `Response` when the request must be refused. +* +* @example +* ```ts source="./bearerAuth.examples.ts#requireBearerAuth_fetchGate" +* const gate = requireBearerAuth({ verifier, requiredScopes: ['mcp'] }); +* +* async function fetchHandler(request: Request): Promise { +* const auth: AuthInfo | Response = await gate(request); +* if (auth instanceof Response) return auth; +* return handler.fetch(request, { authInfo: auth }); +* } +* ``` +*/ +function requireBearerAuth(options) { + const { verifier, requiredScopes = [], resourceMetadataUrl } = options; + const resolved = { + verifier, + requiredScopes, + resourceMetadataUrl + }; + return async (request) => { + const [authorizationHeader] = (request.headers.get("authorization") ?? "").split(","); + try { + return await verifyBearerToken(authorizationHeader || void 0, resolved); + } catch (error) { + return bearerAuthChallengeResponse(error, resolved); + } + }; +} + +//#endregion +//#region src/server/middleware/hostHeaderValidation.ts +/** +* Parse and validate a `Host` header against an allowlist of hostnames (port-agnostic). +* +* - Input host header may include a port (e.g. `localhost:3000`) or IPv6 brackets (e.g. `[::1]:3000`). +* - Allowlist items should be hostnames only (no ports). For IPv6, include brackets (e.g. `[::1]`). +*/ +function validateHostHeader(hostHeader, allowedHostnames) { + if (!hostHeader) return { + ok: false, + errorCode: "missing_host", + message: "Missing Host header" + }; + let hostname; + try { + hostname = new URL(`http://${hostHeader}`).hostname; + } catch { + return { + ok: false, + errorCode: "invalid_host_header", + message: `Invalid Host header: ${hostHeader}`, + hostHeader + }; + } + if (!allowedHostnames.includes(hostname)) return { + ok: false, + errorCode: "invalid_host", + message: `Invalid Host: ${hostname}`, + hostHeader, + hostname + }; + return { + ok: true, + hostname + }; +} +/** +* Convenience allowlist for `localhost` DNS rebinding protection. +*/ +function localhostAllowedHostnames() { + return [ + "localhost", + "127.0.0.1", + "[::1]" + ]; +} +/** +* Web-standard `Request` helper for DNS rebinding protection. +* @example +* ```ts source="./hostHeaderValidation.examples.ts#hostHeaderValidationResponse_basicUsage" +* const result = validateHostHeader(req.headers.get('host'), ['localhost']); +* ``` +*/ +function hostHeaderValidationResponse(req, allowedHostnames) { + const result = validateHostHeader(req.headers.get("host"), allowedHostnames); + if (result.ok) return void 0; + return Response.json({ + jsonrpc: "2.0", + error: { + code: -32e3, + message: result.message + }, + id: null + }, { + status: 403, + headers: { "Content-Type": "application/json" } + }); +} + +//#endregion +//#region src/server/middleware/oauthMetadata.ts +function checkIssuerUrl(issuer, allowInsecure) { + if (issuer.protocol !== "https:" && issuer.hostname !== "localhost" && issuer.hostname !== "127.0.0.1" && !allowInsecure) throw new Error("Issuer URL must be HTTPS"); + if (issuer.hash) throw new Error(`Issuer URL must not have a fragment: ${issuer}`); + if (issuer.search) throw new Error(`Issuer URL must not have a query string: ${issuer}`); +} +/** +* Derive the RFC 9728 Protected Resource Metadata document from +* {@link AuthMetadataOptions}, validating the Authorization Server issuer URL +* (HTTPS required outside localhost) in the process. +* +* `oauthMetadataResponse` and the Express `mcpAuthMetadataRouter` both build +* on this; use it directly when serving the document through your own +* routing — or call it once at startup to fail fast on a misconfigured +* issuer before any request arrives. +*/ +function buildOAuthProtectedResourceMetadata(options) { + checkIssuerUrl(new URL(options.oauthMetadata.issuer), options.dangerouslyAllowInsecureIssuerUrl); + return { + resource: options.resourceServerUrl.href, + authorization_servers: [options.oauthMetadata.issuer], + scopes_supported: options.scopesSupported, + resource_name: options.resourceName, + resource_documentation: options.serviceDocumentationUrl?.href + }; +} +/** +* Builds the RFC 9728 Protected Resource Metadata URL for a given MCP server +* URL by inserting `/.well-known/oauth-protected-resource` ahead of the path. +* +* @example +* ```ts +* getOAuthProtectedResourceMetadataUrl(new URL('https://api.example.com/mcp')) +* // → 'https://api.example.com/.well-known/oauth-protected-resource/mcp' +* ``` +*/ +function getOAuthProtectedResourceMetadataUrl(serverUrl) { + return new URL(protectedResourceMetadataPath(serverUrl), serverUrl).href; +} +/** The RFC 9728 path-aware well-known path for a resource URL. */ +function protectedResourceMetadataPath(resourceServerUrl) { + const rsPath = stripTrailingSlash(resourceServerUrl.pathname); + return `/.well-known/oauth-protected-resource${rsPath === "/" ? "" : rsPath}`; +} +function stripTrailingSlash(path) { + return path.length > 1 && path.endsWith("/") ? path.slice(0, -1) : path; +} +const ALLOWED_METHODS = "GET, HEAD, OPTIONS"; +function metadataDocumentResponse(request, metadata) { + if (request.method === "OPTIONS") { + const requestedHeaders = request.headers.get("access-control-request-headers"); + return new Response(null, { + status: 204, + headers: { + "Access-Control-Allow-Origin": "*", + "Access-Control-Allow-Methods": ALLOWED_METHODS, + ...requestedHeaders === null ? {} : { + "Access-Control-Allow-Headers": requestedHeaders, + Vary: "Access-Control-Request-Headers" + } + } + }); + } + if (request.method !== "GET" && request.method !== "HEAD") { + const error = new OAuthError(OAuthErrorCode.MethodNotAllowed, `The method ${request.method} is not allowed for this endpoint`); + return Response.json(error.toResponseObject(), { + status: 405, + headers: { + Allow: ALLOWED_METHODS, + "Access-Control-Allow-Origin": "*" + } + }); + } + const response = Response.json(metadata, { headers: { "Access-Control-Allow-Origin": "*" } }); + return request.method === "HEAD" ? new Response(null, { + status: response.status, + headers: response.headers + }) : response; +} +/** +* Serve the two OAuth discovery documents an MCP server acting as a Resource +* Server exposes, from a web-standard `fetch(request)` handler: +* +* - `/.well-known/oauth-protected-resource[/]` — RFC 9728 Protected +* Resource Metadata, derived from the supplied options (path-aware: the +* resource URL's path is reflected in the route). +* - `/.well-known/oauth-authorization-server` — RFC 8414 Authorization +* Server Metadata, passed through verbatim. +* +* Returns the matched document `Response` (JSON with permissive CORS, `405` +* with an `Allow` header for non-GET methods, `204` for CORS preflight), or +* `undefined` when the request path is neither well-known route — fall +* through to your own routing. The framework-free counterpart of +* `mcpAuthMetadataRouter` from `@modelcontextprotocol/express`; pair it with +* `requireBearerAuth` and `getOAuthProtectedResourceMetadataUrl` so +* unauthenticated clients can discover the AS from the `401` challenge. +* +* @example +* ```ts source="./oauthMetadata.examples.ts#oauthMetadataResponse_fetchHandler" +* async function fetchHandler(request: Request): Promise { +* return oauthMetadataResponse(request, options) ?? serveMcp(request); +* } +* ``` +*/ +function oauthMetadataResponse(request, options) { + const requestPath = stripTrailingSlash(new URL(request.url).pathname); + if (requestPath === protectedResourceMetadataPath(options.resourceServerUrl)) return metadataDocumentResponse(request, buildOAuthProtectedResourceMetadata(options)); + if (requestPath === "/.well-known/oauth-authorization-server") { + buildOAuthProtectedResourceMetadata(options); + return metadataDocumentResponse(request, options.oauthMetadata); + } +} + +//#endregion +//#region src/server/middleware/originValidation.ts +/** +* Validate an `Origin` header against an allowlist of hostnames (port-agnostic). +* +* - A missing/empty `Origin` header passes: non-browser clients do not send one, +* and only browser-originated requests carry the header this check defends against. +* - Allowlist items are hostnames only (no scheme, no port), the same convention as +* `validateHostHeader`. For IPv6, include brackets (e.g. `[::1]`). +* - Any present value that cannot be parsed as an origin URL — including the literal +* `null` origin browsers send for opaque contexts — is rejected (deny on failure). +*/ +function validateOriginHeader(originHeader, allowedOriginHostnames) { + if (originHeader === null || originHeader === void 0 || originHeader === "") return { ok: true }; + let hostname; + try { + hostname = new URL(originHeader).hostname; + } catch { + return { + ok: false, + errorCode: "invalid_origin_header", + message: `Invalid Origin header: ${originHeader}`, + originHeader + }; + } + if (hostname === "") return { + ok: false, + errorCode: "invalid_origin_header", + message: `Invalid Origin header: ${originHeader}`, + originHeader + }; + if (!allowedOriginHostnames.includes(hostname)) return { + ok: false, + errorCode: "invalid_origin", + message: `Invalid Origin: ${hostname}`, + originHeader, + hostname + }; + return { + ok: true, + origin: originHeader, + hostname + }; +} +/** +* Convenience allowlist of localhost-class origin hostnames, mirroring +* `localhostAllowedHostnames`. +*/ +function localhostAllowedOrigins() { + return [ + "localhost", + "127.0.0.1", + "[::1]" + ]; +} +/** +* Web-standard `Request` helper for Origin validation: returns a `403` JSON-RPC +* error response when the request's `Origin` header is not allowed, and +* `undefined` when the request may proceed. +* +* ```ts +* const rejected = originValidationResponse(request, localhostAllowedOrigins()); +* if (rejected) return rejected; +* ``` +*/ +function originValidationResponse(req, allowedOriginHostnames) { + const result = validateOriginHeader(req.headers.get("origin"), allowedOriginHostnames); + if (result.ok) return void 0; + return Response.json({ + jsonrpc: "2.0", + error: { + code: -32e3, + message: result.message + }, + id: null + }, { + status: 403, + headers: { "Content-Type": "application/json" } + }); +} + +//#endregion +//#region src/server/requestStateCodec.ts +const PREFIX = "v1."; +function bytesToBase64Url(bytes) { + let bin = ""; + for (const b of bytes) bin += String.fromCodePoint(b); + return btoa(bin).replaceAll("+", "-").replaceAll("/", "_").replace(/=+$/, ""); +} +function constantTimeTagEqual(a, b) { + if (a.length !== b.length) return false; + let r = 0; + for (let i = 0; i < a.length; i++) r |= a.codePointAt(i) ^ b.codePointAt(i); + return r === 0; +} +function base64UrlToBytes(s) { + const b64 = s.replaceAll("-", "+").replaceAll("_", "/"); + const bin = atob(b64); + const bytes = new Uint8Array(bin.length); + for (let i = 0; i < bin.length; i++) bytes[i] = bin.codePointAt(i); + return bytes; +} +/** +* Create an opt-in HMAC-SHA256 codec for the multi-round-trip `requestState` +* (protocol revision 2026-07-28). +* +* `requestState` round-trips through the client and is attacker-controlled +* input on re-entry. The SDK applies no protection of its own; this helper is +* the convenience implementation of the spec's integrity MUST so authors don't +* hand-roll HMAC. Wire shape: +* +* "v1." b64url({"p":,"exp":,"b":?}) "." b64url(mac) +* +* where `bindTag` is `b64url(HMAC(key, "mcp.requestState.bind:" + bind(ctx))[:16])` +* — the binding value is never embedded raw. +* +* The codec is **signed, not encrypted**: the body is integrity-protected but +* the client can base64url-decode it and read the payload (`p`) in clear. Do +* not put secrets in the payload; use an AEAD construction if confidentiality +* is required. The handler reads its payload back via the typed +* `ctx.mcpReq.requestState()` accessor — the seam has already run `verify` +* (integrity proven, payload decoded) by the time the handler is entered. +* +* Verification is fail-closed and constant-time (WebCrypto `subtle.verify` for +* the body MAC; a fixed-length XOR-accumulator compare for the bind tag). +* See `examples/mrtr/server.ts` for a worked end-to-end example. +* +* Design comparison (mcp.d `secureRequestState`, the peer SDK's reference +* implementation): mcp.d additionally offers an AES-256-GCM encrypted mode and +* derives independent cipher / bind-HMAC sub-keys from the operator secret via +* HKDF-SHA256, with an auto-generated per-process ephemeral key when none is +* supplied. This codec deliberately ships only the signed mode and a single +* keyed HMAC (domain-separated by input prefix) — HKDF sub-key derivation and +* an encrypted mode are intentionally out of scope for the initial release. +*/ +function createRequestStateCodec(options) { + const subtle = globalThis.crypto?.subtle; + if (subtle === void 0) throw new TypeError("createRequestStateCodec requires the Web Crypto API (globalThis.crypto.subtle); see https://ts.sdk.modelcontextprotocol.io/v2/troubleshooting for the Node.js polyfill instructions"); + const keyBytes = typeof options.key === "string" ? new TextEncoder().encode(options.key) : Uint8Array.from(options.key); + if (keyBytes.byteLength < 32) throw new RangeError(`createRequestStateCodec: key must be at least 32 bytes (got ${keyBytes.byteLength})`); + const ttlSeconds = options.ttlSeconds ?? 600; + if (!Number.isFinite(ttlSeconds)) throw new RangeError("createRequestStateCodec: ttlSeconds must be a finite number"); + const bind = options.bind; + let cryptoKey; + const importedKey = () => cryptoKey ??= subtle.importKey("raw", keyBytes, { + name: "HMAC", + hash: "SHA-256" + }, false, ["sign", "verify"]); + const utf8 = new TextEncoder(); + const BIND_LABEL = "mcp.requestState.bind:"; + const bindTag = async (value) => { + return bytesToBase64Url(new Uint8Array(await subtle.sign("HMAC", await importedKey(), utf8.encode(BIND_LABEL + value))).slice(0, 16)); + }; + return { + async mint(payload, ctx) { + const envelope = { + p: payload, + exp: Math.floor(Date.now() / 1e3) + ttlSeconds + }; + if (bind !== void 0) { + if (ctx === void 0) throw new TypeError("createRequestStateCodec: mint() requires ctx when a bind callback is configured"); + envelope.b = await bindTag(bind(ctx)); + } + const body = bytesToBase64Url(utf8.encode(JSON.stringify(envelope))); + return `${PREFIX}${body}.${bytesToBase64Url(new Uint8Array(await subtle.sign("HMAC", await importedKey(), utf8.encode(PREFIX + body))))}`; + }, + async verify(state, ctx) { + const dot = state.lastIndexOf("."); + if (!state.startsWith(PREFIX) || dot <= 3) throw new Error("malformed"); + const body = state.slice(3, dot); + let macBytes; + try { + macBytes = base64UrlToBytes(state.slice(dot + 1)); + } catch { + throw new Error("malformed"); + } + if (!await subtle.verify("HMAC", await importedKey(), macBytes, utf8.encode(PREFIX + body))) throw new Error("mac"); + let envelope; + try { + envelope = JSON.parse(new TextDecoder("utf-8", { fatal: true }).decode(base64UrlToBytes(body))); + } catch { + throw new Error("malformed"); + } + if (typeof envelope.exp !== "number" || envelope.exp < Math.floor(Date.now() / 1e3)) throw new Error("expired"); + if (bind !== void 0) { + const expected = await bindTag(bind(ctx)); + if (envelope.b === void 0 || !constantTimeTagEqual(envelope.b, expected)) throw new Error("bind"); + } else if (envelope.b !== void 0) throw new Error("bind"); + return envelope.p; + } + }; +} + +//#endregion +//#region src/fromJsonSchema.ts +let _defaultValidator; +function dist_fromJsonSchema(schema, validator) { + return fromJsonSchema$1(schema, validator ?? (_defaultValidator ??= new DefaultJsonSchemaValidator())); +} + +//#endregion + +//# sourceMappingURL=index.mjs.map +const mcpApps = Object.freeze([ + { + "html": "\n\n \n \n \n Service status\n \n \n \n
    \n
    MCP App example
    \n

    No service selected

    \n
    unknown
    \n

    Invoke the readiness tool to inspect a service.

    \n
      \n \n \n \n \n

      \n
      \n \n\n", + "mimeType": "text/html;profile=mcp-app", + "name": "status", + "resourceUri": "ui://mcp-app-example/status.html" + } +]); + +/* export default */ const mcp_status_073c1634_0 = (mcpApps); + +// Generated by agent-bundle. Do not edit. +const meta_name = "mcp-app-example"; +const packageName = "@agent-bundle-example/mcp-app"; +const packageVersion = undefined; +const meta_version = "1.0.0"; +const meta_meta = Object.freeze({ + name: meta_name, + packageName: packageName, + packageVersion: packageVersion, + version: meta_version +}); +/* export default */ const _agent_bundle_virtual_meta = ((/* unused pure expression or super */ null && (meta_meta))); + +const healthyCompilerStatus = Object.freeze({ + checks: Object.freeze([ + Object.freeze({ + label: 'Availability', + status: 'passing' + }), + Object.freeze({ + label: 'Build queue', + status: 'passing' + }) + ]), + service: 'compiler', + status: 'healthy', + summary: 'Compiler service is ready for release.' +}); +const isRecord = (value)=>value !== null && typeof value === 'object' && !Array.isArray(value); +const isHealthyCompilerFixture = (value)=>{ + if (!isRecord(value) || value.service !== healthyCompilerStatus.service || value.status !== healthyCompilerStatus.status || value.summary !== healthyCompilerStatus.summary || !Array.isArray(value.checks) || value.checks.length !== healthyCompilerStatus.checks.length) { + return false; + } + return healthyCompilerStatus.checks.every((expected, index)=>{ + const received = value.checks[index]; + return isRecord(received) && received.label === expected.label && received.status === expected.status; + }); +}; + + + + + + +const app = mcp_status_073c1634_0["0"]; +if (app === undefined) throw new Error('Expected the status MCP App.'); +const serviceCatalog = Object.freeze({ + compiler: healthyCompilerStatus, + 'payments-api': Object.freeze({ + checks: Object.freeze([ + Object.freeze({ + label: 'Availability', + status: 'passing' + }), + Object.freeze({ + label: 'P95 latency', + status: 'failing' + }) + ]), + service: 'payments-api', + status: 'degraded', + summary: 'Payment latency is above the release threshold.' + }) +}); +const createStatusServer = ()=>{ + // The compiler stamps this project's identity into `agent-bundle/meta`, so + // the wire identity cannot drift from the config or package.json. + const server = new mcp_DXXb3Vv3_McpServer({ + name: meta_name, + version: (/* inlined export .version */"1.0.0") + }); + server.registerResource(app.name, app.resourceUri, { + _meta: { + ui: { + resourceUri: app.resourceUri + } + }, + mimeType: app.mimeType + }, async (uri)=>({ + contents: [ + { + mimeType: app.mimeType, + text: app.html, + uri: uri.href + } + ] + })); + server.registerTool('show-status', { + _meta: { + ui: { + resourceUri: app.resourceUri + } + }, + description: 'Show the health of one example service.', + inputSchema: schemas_object({ + service: schemas_enum([ + 'compiler', + 'payments-api' + ]) + }) + }, async ({ service })=>{ + const result = serviceCatalog[service]; + return { + _meta: { + ui: { + resourceUri: app.resourceUri + } + }, + content: [ + { + text: result.summary, + type: 'text' + } + ], + structuredContent: result + }; + }); + return server; +}; +/** + * Default-exported server factory: `agent-bundle build` detects it and wraps + * this entry in the framework stdio lifecycle shell (console-to-stderr guard, + * SIGINT/SIGTERM handling, stdin-EOF exit, bounded shutdown, heartbeat). + */ /* export default */ const mcp_status = (createStatusServer); + + + + + +//#region src/server/stdio.ts +/** +* Server transport for stdio: this communicates with an MCP client by reading from the current process' `stdin` and writing to `stdout`. +* +* This transport is only available in Node.js environments. +* +* @example +* ```ts source="./stdio.examples.ts#StdioServerTransport_basicUsage" +* const server = new McpServer({ name: 'my-server', version: '1.0.0' }); +* const transport = new StdioServerTransport(); +* await server.connect(transport); +* ``` +*/ +var stdio_StdioServerTransport = class { + _readBuffer; + _started = false; + _closed = false; + constructor(_stdin = node_process.stdin, _stdout = node_process.stdout, options) { + this._stdin = _stdin; + this._stdout = _stdout; + this._readBuffer = new ReadBuffer({ maxBufferSize: options?.maxBufferSize }); + } + onclose; + onerror; + onmessage; + _ondata = (chunk) => { + try { + this._readBuffer.append(chunk); + this.processReadBuffer(); + } catch (error) { + this.onerror?.(error); + this.close().catch(() => {}); + } + }; + _onerror = (error) => { + this.onerror?.(error); + }; + _onstdouterror = (error) => { + this.onerror?.(error); + this.close().catch(() => {}); + }; + /** + * Starts listening for messages on `stdin`. + */ + async start() { + if (this._started) throw new Error("StdioServerTransport already started! If using Server class, note that connect() calls start() automatically."); + this._started = true; + this._stdin.on("data", this._ondata); + this._stdin.on("error", this._onerror); + this._stdout.on("error", this._onstdouterror); + } + processReadBuffer() { + while (true) try { + const message = this._readBuffer.readMessage(); + if (message === null) break; + this.onmessage?.(message); + } catch (error) { + this.onerror?.(error); + } + } + async close() { + if (this._closed) return; + this._closed = true; + this._stdin.off("data", this._ondata); + this._stdin.off("error", this._onerror); + this._stdout.off("error", this._onstdouterror); + if (this._stdin.listenerCount("data") === 0) this._stdin.pause(); + this._readBuffer.clear(); + this.onclose?.(); + } + send(message) { + if (this._closed) return Promise.reject(/* @__PURE__ */ new Error("StdioServerTransport is closed")); + return new Promise((resolve, reject) => { + const json = serializeMessage(message); + let settled = false; + const onError = (error) => { + if (settled) return; + settled = true; + this._stdout.off("error", onError); + this._stdout.off("drain", onDrain); + reject(error); + }; + const onDrain = () => { + if (settled) return; + settled = true; + this._stdout.off("error", onError); + this._stdout.off("drain", onDrain); + resolve(); + }; + this._stdout.once("error", onError); + if (this._stdout.write(json)) { + if (settled) return; + settled = true; + this._stdout.off("error", onError); + resolve(); + } else if (!settled) this._stdout.once("drain", onDrain); + }); + } +}; + +//#endregion +//#region src/server/serveStdio.ts +/** +* How long the probe-discard path waits for the probe instance to answer the +* requests it was delivered before closing it. The wait normally settles as +* soon as the DiscoverResult is handed to the wire (or immediately, when a +* delivered cancellation already settled the probe); the bound is a backstop +* so no edge can ever hold the connection's inbound pump indefinitely behind +* the discard. +*/ +const DISCARD_ANSWER_TIMEOUT_MS = 3e3; +/** +* The transport a pinned instance is connected to: a thin channel that writes +* through to the entry-owned wire transport and receives the messages the +* entry forwards. The wire transport itself is never handed to an instance — +* that is what lets the entry discard an optimistic probe instance (close the +* channel) without tearing down the connection. +*/ +var StdioConnectionChannel = class { + onclose; + onerror; + onmessage; + _closed = false; + /** Request ids the entry delivered to the instance that the instance has not yet answered. */ + _pendingRequests = /* @__PURE__ */ new Set(); + _drainWaiters = []; + constructor(_wire, _onInstanceClose, _outboundIntercept) { + this._wire = _wire; + this._onInstanceClose = _onInstanceClose; + this._outboundIntercept = _outboundIntercept; + } + async start() {} + async send(message, options) { + if (isJSONRPCResultResponse(message) || isJSONRPCErrorResponse(message)) { + const { id } = message; + if (id !== void 0) this._settle(id); + } + if (this._closed) return; + if (this._outboundIntercept?.(message) === "handled") return; + return this._wire.send(message, options); + } + setProtocolVersion = (version) => { + this._wire.setProtocolVersion?.(version); + }; + /** Forwards one inbound message to the connected instance. */ + deliver(message, extra) { + if (this._closed) return; + if (isJSONRPCRequest(message)) this._pendingRequests.add(message.id); + else if (isJSONRPCNotification(message) && message.method === "notifications/cancelled") { + const cancelledId = message.params?.requestId; + if (cancelledId !== void 0) this._settle(cancelledId); + } + this.onmessage?.(message, extra); + } + /** + * Resolves once every request delivered to the instance has been answered + * through {@linkcode send}, settled by a delivered cancellation, or the + * channel has been closed and nothing further can be answered. The wait is + * bounded by `timeoutMs` as a backstop so no edge can hold the caller + * indefinitely; resolves `false` only when the bound elapsed with requests + * still unanswered. Used by the probe-discard path so a probe request the + * entry accepted is never silently dropped. + */ + async whenRequestsAnswered(timeoutMs) { + if (this._closed || this._pendingRequests.size === 0) return true; + return await new Promise((resolve) => { + const waiter = () => { + clearTimeout(timer); + resolve(true); + }; + const timer = setTimeout(() => { + this._drainWaiters = this._drainWaiters.filter((pending) => pending !== waiter); + resolve(false); + }, timeoutMs); + this._drainWaiters.push(waiter); + }); + } + async close() { + if (this._closed) return; + this._closed = true; + this._pendingRequests.clear(); + this._releaseDrainWaiters(); + try { + this._onInstanceClose(); + } finally { + this.onclose?.(); + } + } + _settle(id) { + this._pendingRequests.delete(id); + if (this._pendingRequests.size === 0) this._releaseDrainWaiters(); + } + _releaseDrainWaiters() { + const waiters = this._drainWaiters; + this._drainWaiters = []; + for (const waiter of waiters) waiter(); + } +}; +/** +* Classifies one message of the opening exchange with the same body-primary +* rules the HTTP entry applies per request: `initialize` is the legacy +* handshake unless it carries a valid modern envelope claim; a present claim +* is validated (never silently ignored); a claim-less message is 2025-era +* traffic. There is no header layer on stdio, so the body is the only signal. +*/ +function classifyOpeningMessage(message) { + const params = message.params; + if (message.method === "initialize" && !carriesValidModernEnvelopeClaim(params)) { + const requestedVersion = params !== null && typeof params === "object" && typeof params.protocolVersion === "string" ? params.protocolVersion : void 0; + return { + kind: "legacy", + reason: "initialize", + ...requestedVersion !== void 0 && { requestedVersion } + }; + } + if (!hasEnvelopeClaim(params)) return { + kind: "legacy", + reason: "no-claim" + }; + const meta = requestMetaOf(params); + const firstIssue = (meta === void 0 ? [] : validateEnvelopeMeta(meta))[0]; + if (firstIssue !== void 0) return { + kind: "invalid-envelope", + issue: firstIssue + }; + const claimedVersion = envelopeClaimVersion(params); + if (claimedVersion === void 0 || !SUPPORTED_MODERN_PROTOCOL_VERSIONS.includes(claimedVersion)) return { + kind: "unsupported-revision", + requested: claimedVersion ?? "unknown" + }; + return { + kind: "modern", + revision: claimedVersion, + classification: { + era: "modern", + revision: claimedVersion + } + }; +} +/** +* Serves MCP over stdio from a server factory, owning the era decision for +* the connection: the opening exchange selects the era, ONE instance from the +* factory is pinned for the connection lifetime, and everything after passes +* straight through to it. See the module documentation for the opening rules. +* +* ```ts +* import { serveStdio } from '@modelcontextprotocol/server/stdio'; +* +* serveStdio(() => { +* const server = new McpServer({ name: 'my-server', version: '1.0.0' }, { capabilities: { tools: {} } }); +* // register tools/resources/prompts once — the same factory serves both eras +* return server; +* }); +* ``` +*/ +function serveStdio(factory, options = {}) { + const legacyMode = options.legacy ?? "serve"; + const wire = options.transport ?? new stdio_StdioServerTransport(); + let state = { phase: "opening" }; + /** Channel currently being discarded (its close must not tear the connection down). */ + let discarding; + let closing = false; + /** + * Whether the connection has been torn down (`handle.close()` or the wire + * closing). The opening arms re-check this after every await: a close can + * race factory construction, and the continuation must neither resurrect + * the connection state nor keep a late-resolved instance around. + */ + const isTornDown = () => closing || state.phase === "closed"; + const reportError = (error) => { + try { + options.onerror?.(error); + } catch {} + }; + const writeErrorResponse = (id, code, message, data) => wire.send({ + jsonrpc: "2.0", + id, + error: { + code, + message, + ...data !== void 0 && { data } + } + }).catch((error) => reportError(stdio_toError(error))); + /** + * Entry-handled `subscriptions/listen` for this connection: holds the + * active subscriptions, serves inbound listen / cancelled-of-listen + * before the pinned instance is consulted, and rewrites the instance's + * outbound change notifications onto the active subscriptions. Only + * consulted on a modern-pinned connection — on a legacy connection + * change notifications pass straight through (the 2025 unsolicited + * delivery model is unchanged). + */ + const listenRouter = new StdioListenRouter(options.maxSubscriptions ?? DEFAULT_MAX_SUBSCRIPTIONS); + /** Outbound intercept installed on a modern instance's channel. */ + const modernOutboundIntercept = (message) => { + if (!isJSONRPCNotification(message)) return void 0; + const routed = listenRouter.routeOutbound(message); + if (routed === "passthrough") return void 0; + for (const stamped of routed) wire.send({ + jsonrpc: "2.0", + ...stamped + }).catch((error) => reportError(stdio_toError(error))); + return "handled"; + }; + /** + * Entry-handled inbound listen routing for a modern-pinned connection. + * Returns `true` when the message was served at the entry and must NOT + * be delivered to the pinned instance. + */ + const tryServeListen = async (message) => { + if (isJSONRPCRequest(message) && message.method === "subscriptions/listen") { + const meta = requestMetaOf(message.params); + const issue = hasEnvelopeClaim(message.params) ? (meta === void 0 ? [] : validateEnvelopeMeta(meta))[0] : { + key: "_meta", + problem: "the per-request envelope is required on protocol revision 2026-07-28" + }; + const claimedVersion = envelopeClaimVersion(message.params); + let reply; + if (issue !== void 0) reply = { + jsonrpc: "2.0", + id: message.id, + error: { + code: -32602, + message: `Invalid _meta envelope: ${issue.key}: ${issue.problem}` + } + }; + else if (claimedVersion === void 0 || !SUPPORTED_MODERN_PROTOCOL_VERSIONS.includes(claimedVersion)) { + const error = new UnsupportedProtocolVersionError({ + supported: [...SUPPORTED_MODERN_PROTOCOL_VERSIONS], + requested: claimedVersion ?? "unknown" + }); + reply = { + jsonrpc: "2.0", + id: message.id, + error: { + code: error.code, + message: error.message, + data: error.data + } + }; + } else reply = listenRouter.serve(message); + await wire.send("error" in reply ? reply : { + jsonrpc: "2.0", + method: reply.method, + params: reply.params + }).catch((error) => reportError(stdio_toError(error))); + return true; + } + if (isJSONRPCNotification(message) && message.method === "notifications/cancelled") { + const cancelledId = message.params?.requestId; + if (cancelledId !== void 0 && listenRouter.cancel(cancelledId)) return true; + } + return false; + }; + /** Answers a 2025-era request the entry will not serve (the modern-only rejection cells). */ + const answerLegacyRejection = (request, reason, requestedVersion) => { + const rejection = modernOnlyStrictRejection({ + kind: "legacy", + reason, + ...requestedVersion !== void 0 && { requestedVersion } + }, SUPPORTED_MODERN_PROTOCOL_VERSIONS); + if (rejection === void 0) return Promise.resolve(); + reportError(/* @__PURE__ */ new Error(`Rejected 2025-era request on a modern-only stdio connection (${rejection.cell}): ${rejection.message}`)); + return writeErrorResponse(request.id, rejection.code, rejection.message, rejection.data); + }; + const onInstanceClosed = (channel) => { + if (closing || channel === discarding) return; + closeAll(); + }; + const connectInstance = async (era, revision) => { + const product = await factory({ era }); + const server = product instanceof McpServer ? product.server : product; + if (era === "modern") { + setNegotiatedProtocolVersion(server, revision); + installModernOnlyHandlers(server, SUPPORTED_MODERN_PROTOCOL_VERSIONS); + listenRouter.setServerCapabilities(server.getCapabilities(), serverIdentityOf(server)); + } + const channel = new StdioConnectionChannel(wire, () => onInstanceClosed(channel), era === "modern" ? modernOutboundIntercept : void 0); + await product.connect(channel); + return { + product, + channel + }; + }; + /** Closes an instance whose factory resolved only after the connection was torn down. */ + const disposeLateInstance = (instance) => instance.product.close().catch((error) => reportError(stdio_toError(error))); + const discardProbeInstance = async (instance) => { + discarding = instance.channel; + try { + if (!await instance.channel.whenRequestsAnswered(DISCARD_ANSWER_TIMEOUT_MS)) reportError(/* @__PURE__ */ new Error(`Discarded the probe instance with requests still unanswered after ${DISCARD_ANSWER_TIMEOUT_MS}ms; continuing with the fallback`)); + await instance.product.close(); + } catch (error) { + reportError(stdio_toError(error)); + } finally { + discarding = void 0; + } + }; + const processMessage = async (message) => { + if (state.phase === "closed") return; + if (state.phase === "pinned") { + if (state.era === "modern" && isJSONRPCRequest(message) && message.method === "initialize" && !carriesValidModernEnvelopeClaim(message.params)) { + await answerLegacyRejection(message, "initialize", message.params !== null && typeof message.params === "object" && typeof message.params.protocolVersion === "string" ? message.params.protocolVersion : void 0); + return; + } + if (state.era === "modern" && await tryServeListen(message)) return; + state.instance.channel.deliver(message); + return; + } + if (!isJSONRPCRequest(message) && !isJSONRPCNotification(message)) { + reportError(/* @__PURE__ */ new Error("Discarded a JSON-RPC response received before the connection negotiated an era")); + return; + } + const opening = classifyOpeningMessage(message); + switch (opening.kind) { + case "invalid-envelope": { + const detail = `Invalid _meta envelope for protocol revision 2026-07-28: ${opening.issue.key}: ${opening.issue.problem}`; + if (isJSONRPCRequest(message)) await writeErrorResponse(message.id, ProtocolErrorCode.InvalidParams, detail, { envelope: opening.issue }); + else reportError(/* @__PURE__ */ new Error(`Discarded a notification with a malformed envelope: ${detail}`)); + return; + } + case "unsupported-revision": + if (isJSONRPCRequest(message)) { + const error = new UnsupportedProtocolVersionError({ + supported: [...SUPPORTED_MODERN_PROTOCOL_VERSIONS], + requested: opening.requested + }); + reportError(error); + await writeErrorResponse(message.id, error.code, error.message, error.data); + } else reportError(/* @__PURE__ */ new Error(`Discarded a notification claiming unsupported protocol revision ${opening.requested}`)); + return; + case "modern": + if (isJSONRPCRequest(message) && message.method === "server/discover") { + if (state.phase === "probe") { + state.instance.channel.deliver(message, { classification: opening.classification }); + return; + } + const instance = await connectInstance("modern", opening.revision); + if (isTornDown()) { + await disposeLateInstance(instance); + return; + } + state = { + phase: "probe", + instance + }; + instance.channel.deliver(message, { classification: opening.classification }); + return; + } + if (state.phase === "probe") { + if (isJSONRPCNotification(message)) { + state.instance.channel.deliver(message, { classification: opening.classification }); + return; + } + state = { + phase: "pinned", + era: "modern", + instance: state.instance + }; + } else { + const instance = await connectInstance("modern", opening.revision); + if (isTornDown()) { + await disposeLateInstance(instance); + return; + } + state = { + phase: "pinned", + era: "modern", + instance + }; + } + if (await tryServeListen(message)) return; + state.instance.channel.deliver(message, { classification: opening.classification }); + return; + case "legacy": { + if (legacyMode === "reject") { + if (isJSONRPCRequest(message)) await answerLegacyRejection(message, opening.reason, opening.requestedVersion); + return; + } + if (state.phase === "probe") { + await discardProbeInstance(state.instance); + if (isTornDown()) return; + state = { phase: "opening" }; + } + const instance = await connectInstance("legacy"); + if (isTornDown()) { + await disposeLateInstance(instance); + return; + } + state = { + phase: "pinned", + era: "legacy", + instance + }; + state.instance.channel.deliver(message); + return; + } + } + }; + const queue = []; + let pumping = false; + const pump = async () => { + if (pumping) return; + pumping = true; + try { + while (queue.length > 0) { + const message = queue.shift(); + try { + await processMessage(message); + } catch (error) { + if (isJSONRPCRequest(message)) await writeErrorResponse(message.id, ProtocolErrorCode.InternalError, "Internal server error"); + reportError(stdio_toError(error)); + } + } + } finally { + pumping = false; + } + }; + const closeAll = async () => { + if (closing || state.phase === "closed") return; + closing = true; + const current = state; + state = { phase: "closed" }; + for (const result of listenRouter.teardownAll()) await wire.send(result).catch((error) => reportError(stdio_toError(error))); + if (current.phase === "probe" || current.phase === "pinned") await current.instance.product.close().catch((error) => reportError(stdio_toError(error))); + await wire.close().catch((error) => reportError(stdio_toError(error))); + }; + wire.onmessage = (message) => { + queue.push(message); + pump(); + }; + wire.onerror = (error) => { + reportError(error); + if (state.phase === "probe" || state.phase === "pinned") state.instance.channel.onerror?.(error); + }; + wire.onclose = () => { + if (closing || state.phase === "closed") return; + closing = true; + const current = state; + state = { phase: "closed" }; + if (current.phase === "probe" || current.phase === "pinned") current.instance.product.close().catch((error) => reportError(stdio_toError(error))); + }; + const started = wire.start().catch((error) => { + reportError(stdio_toError(error)); + throw error; + }); + started.catch(() => {}); + return { close: async () => { + await started.catch(() => {}); + await closeAll(); + } }; +} +function stdio_toError(value) { + return value instanceof Error ? value : new Error(String(value)); +} + +//#endregion + +//# sourceMappingURL=stdio.mjs.map +const defaultHeartbeatIntervalMs = 300000; +const defaultActivityThrottleMs = 60000; +const defaultShutdownTimeoutMs = 5000; +const defaultHeartbeatName = 'agent-bundle'; +const redirectConsoleToStderr = ()=>{ + const originalStdoutWrite = process.stdout.write.bind(process.stdout); + const stderrConsole = new console.Console({ + stderr: process.stderr, + stdout: process.stderr + }); + const methods = [ + 'debug', + 'dir', + 'error', + 'info', + 'log', + 'trace', + 'warn' + ]; + for (const method of methods)console[method] = stderrConsole[method].bind(stderrConsole); + process.stdout.write = (chunk, encoding, callback)=>process.stderr.write(chunk, encoding, callback); + return Object.freeze({ + restoreProtocolStdout: ()=>{ + process.stdout.write = originalStdoutWrite; + } + }); +}; +const createHeartbeat = ({ activityThrottleMs = defaultActivityThrottleMs, intervalMs = defaultHeartbeatIntervalMs, name = defaultHeartbeatName, writeLine })=>{ + const startedAt = Date.now(); + let lastActivityAt = startedAt; + let lastActivityLogAt = 0; + const log = (reason)=>{ + const uptimeSeconds = Math.round((Date.now() - startedAt) / 1000); + const idleSeconds = Math.round((Date.now() - lastActivityAt) / 1000); + writeLine(`[${name}] stdio heartbeat (${reason}) pid=${process.pid} uptime=${uptimeSeconds}s idle=${idleSeconds}s`); + }; + const timer = setInterval(()=>log('interval'), intervalMs); + timer.unref?.(); + return Object.freeze({ + log, + noteActivity: ()=>{ + lastActivityAt = Date.now(); + if (lastActivityAt - lastActivityLogAt >= activityThrottleMs) { + lastActivityLogAt = lastActivityAt; + log('activity'); + } + }, + stop: ()=>clearInterval(timer) + }); +}; +const runStdioServer = async ({ activityThrottleMs, exit = (code)=>process.exit(code), heartbeat: heartbeatEnabled = true, heartbeatIntervalMs, server, serverName, shutdownTimeoutMs = defaultShutdownTimeoutMs, signals = process, stdin = process.stdin, transport, writeLine = (line)=>void process.stderr.write(`${line}\n`) })=>{ + const heartbeat = createHeartbeat({ + ...void 0 === activityThrottleMs ? {} : { + activityThrottleMs + }, + ...void 0 === heartbeatIntervalMs ? {} : { + intervalMs: heartbeatIntervalMs + }, + ...void 0 === serverName ? {} : { + name: serverName + }, + writeLine: heartbeatEnabled ? writeLine : ()=>void 0 + }); + const keepalive = setInterval(()=>void 0, 60000); + keepalive.unref?.(); + let shuttingDown = false; + const shutdown = async (exitCode = 0)=>{ + if (shuttingDown) return; + shuttingDown = true; + signals.off('SIGINT', handleSigint); + signals.off('SIGTERM', handleSigterm); + stdin.off?.('end', handleStdinEnd); + clearInterval(keepalive); + heartbeat.stop(); + await Promise.race([ + Promise.allSettled([ + Promise.resolve().then(()=>transport.close()), + Promise.resolve().then(()=>server.close()) + ]), + new Promise((resolve)=>setTimeout(resolve, shutdownTimeoutMs)) + ]); + exit(exitCode); + }; + const handleSigint = ()=>{ + shutdown(130); + }; + const handleSigterm = ()=>{ + shutdown(143); + }; + const handleStdinEnd = ()=>{ + shutdown(0); + }; + signals.on('SIGINT', handleSigint); + signals.on('SIGTERM', handleSigterm); + stdin.once?.('end', handleStdinEnd); + transport.onclose = ()=>{ + shutdown(0); + }; + await server.connect(transport); + const originalOnMessage = transport.onmessage; + transport.onmessage = (message, extra)=>{ + heartbeat.noteActivity(); + originalOnMessage?.(message, extra); + }; + return Object.freeze({ + heartbeat, + shutdown + }); +}; +const runGeneratedStdioMcpEntry = async (options)=>{ + const guard = redirectConsoleToStderr(); + const entry = await options.loadEntry(); + const factory = entry.default; + if ('function' != typeof factory) throw new TypeError(`Generated stdio entry for MCP server ${JSON.stringify(options.serverName)} must default-export a server factory.`); + const server = await factory(); + const { StdioServerTransport } = await Promise.resolve(stdio_namespaceObject); + guard.restoreProtocolStdout(); + const transport = new StdioServerTransport(); + return runStdioServer({ + ...options.lifecycle, + server, + serverName: options.serverName, + transport: transport + }); +}; + + + +await runGeneratedStdioMcpEntry({ + loadEntry: ()=>Promise.resolve(status_namespaceObject), + serverName: "status" +}); + +export {}; diff --git a/examples/mcp-app/artifact/portable/plugin.json b/examples/mcp-app/artifact/portable/plugin.json new file mode 100644 index 000000000..e450b6e1e --- /dev/null +++ b/examples/mcp-app/artifact/portable/plugin.json @@ -0,0 +1 @@ +{"$schema":"https://agent-plugins.org/schemas/1.0.0/plugin.schema.json","description":"A unified service-readiness assistant with MCP, Skills, Hooks, scripts, and evaluation.","name":"mcp-app-example","version":"1.0.0"} diff --git a/examples/mcp-app/artifact/portable/scripts/check-service-fixture.mjs b/examples/mcp-app/artifact/portable/scripts/check-service-fixture.mjs new file mode 100644 index 000000000..a059060bb --- /dev/null +++ b/examples/mcp-app/artifact/portable/scripts/check-service-fixture.mjs @@ -0,0 +1,60 @@ +import { readFile } from "node:fs/promises"; + + + + +const healthyCompilerStatus = Object.freeze({ + checks: Object.freeze([ + Object.freeze({ + label: 'Availability', + status: 'passing' + }), + Object.freeze({ + label: 'Build queue', + status: 'passing' + }) + ]), + service: 'compiler', + status: 'healthy', + summary: 'Compiler service is ready for release.' +}); +const isRecord = (value)=>value !== null && typeof value === 'object' && !Array.isArray(value); +const isHealthyCompilerFixture = (value)=>{ + if (!isRecord(value) || value.service !== healthyCompilerStatus.service || value.status !== healthyCompilerStatus.status || value.summary !== healthyCompilerStatus.summary || !Array.isArray(value.checks) || value.checks.length !== healthyCompilerStatus.checks.length) { + return false; + } + return healthyCompilerStatus.checks.every((expected, index)=>{ + const received = value.checks[index]; + return isRecord(received) && received.label === expected.label && received.status === expected.status; + }); +}; + + + +const fixturePath = new URL('../assets/evals/fixtures/status/result.json', import.meta.url); +/** + * `agent-bundle build` detects the `main` export and generates the process + * envelope (argv, awaiting, numeric-return exit-code adoption) around it. + */ const main = async ()=>{ + try { + const fixture = JSON.parse(await readFile(fixturePath, 'utf8')); + if (!isHealthyCompilerFixture(fixture)) { + throw new Error('compiler fixture must contain the exact healthy compiler status'); + } + process.stdout.write('Compiler fixture is healthy.\n'); + return 0; + } catch (error) { + process.stderr.write(`Unable to verify service fixture: ${error instanceof Error ? error.message : String(error)}\n`); + return 1; + } +}; + + +const check_service_fixture_entry_main = main; +if (typeof check_service_fixture_entry_main !== 'function') { + throw new TypeError('Executable entry must export a main function: ' + "/fast/projects/agent-bundle-worktrees/host-test/examples/mcp-app/src/scripts/check-service-fixture.ts"); +} +const code = await check_service_fixture_entry_main(process.argv.slice(2)); +if (typeof code === 'number') process.exitCode = code; + +export {}; diff --git a/examples/mcp-app/artifact/portable/skills/service-readiness/SKILL.md b/examples/mcp-app/artifact/portable/skills/service-readiness/SKILL.md new file mode 100644 index 000000000..8f91a79d7 --- /dev/null +++ b/examples/mcp-app/artifact/portable/skills/service-readiness/SKILL.md @@ -0,0 +1,33 @@ +--- +name: service-readiness +description: Reviews service health evidence and records an auditable readiness decision. +--- +# Service readiness + +## When to use + +Use this Skill when a release, incident decision, or service handoff needs a +clear health verdict backed by named checks and current evidence. + +## Required resources + +- Apply [the service status policy](references/status-policy.md) before + classifying a healthy, degraded, or blocked result. +- Deliver the decision with [the readiness report](assets/readiness-report.md). + +## Workflow + +1. Identify the service and collect its current summary and every labelled + check. Record the command, time, result, and evidence source. +2. Classify any failing check with the status policy. A degraded service is not + release-ready until its failing check has an approved mitigation. +3. State the readiness verdict only after confirming availability and the + service-specific release threshold. +4. Complete the report with the status, checks, evidence, owner, and next + action. Do not omit a failing check from the final decision. + +## Final report requirements + +State `ready`, `degraded`, `blocked`, or `needs evidence`; reproduce the +service summary; list each labelled check and its status; identify the owner +and due date for every non-passing check; and name the next required action. diff --git a/examples/mcp-app/artifact/portable/skills/service-readiness/assets/readiness-report.md b/examples/mcp-app/artifact/portable/skills/service-readiness/assets/readiness-report.md new file mode 100644 index 000000000..3da5d52ea --- /dev/null +++ b/examples/mcp-app/artifact/portable/skills/service-readiness/assets/readiness-report.md @@ -0,0 +1,22 @@ +# Service readiness report + +## Verdict + +State `ready`, `degraded`, `blocked`, or `needs evidence` and name the service. + +## Evidence + +Record the collection time, command or artifact, service summary, and source. + +## Checks + +List every labelled check with its observed status and release threshold. + +## Findings and mitigation + +For each non-passing check, record the impact, owner, mitigation, due date, +and the evidence required to clear it. + +## Next action + +Name the decision owner and the next verification or release action. diff --git a/examples/mcp-app/artifact/portable/skills/service-readiness/references/status-policy.md b/examples/mcp-app/artifact/portable/skills/service-readiness/references/status-policy.md new file mode 100644 index 000000000..7e5766172 --- /dev/null +++ b/examples/mcp-app/artifact/portable/skills/service-readiness/references/status-policy.md @@ -0,0 +1,22 @@ +# Service status policy + +## Evidence standard + +Readiness evidence must identify the service, collection time, check label, +observed status, and source command or artifact. Missing or stale evidence is +not a passing check. + +## Status classification + +- **Healthy**: every required release check is passing. +- **Degraded**: availability remains sufficient, but a release threshold such + as P95 latency is failing. Record an owner and mitigation before release. +- **Blocked**: availability or a critical safety check is failing. Do not + release until new passing evidence is collected. +- **Needs evidence**: the service or any required check cannot be verified. + +## Release decision + +Issue `ready` only for a healthy service with current evidence. A degraded +service needs an explicit mitigation decision; a blocked service cannot pass; +and missing evidence requires a new check rather than an assumption. diff --git a/examples/skills-starter/artifact/agent-bundle.hooks.json b/examples/skills-starter/artifact/agent-bundle.hooks.json new file mode 100644 index 000000000..a41e820b1 --- /dev/null +++ b/examples/skills-starter/artifact/agent-bundle.hooks.json @@ -0,0 +1 @@ +{"hooks":[]} diff --git a/examples/skills-starter/artifact/agent-bundle.manifest.json b/examples/skills-starter/artifact/agent-bundle.manifest.json new file mode 100644 index 000000000..6104a5852 --- /dev/null +++ b/examples/skills-starter/artifact/agent-bundle.manifest.json @@ -0,0 +1 @@ +{"agentSkills":{"schemaSha256":"6d06b61e423317421de2295ea1fd0c7b4491bfa36c5b7705c28616dfe76d4047","sourceRevision":"69ef37e9424c0a7ea9dd2293b559e43ec8176379","specification":"https://raw.githubusercontent.com/agentskills/agentskills/69ef37e9424c0a7ea9dd2293b559e43ec8176379/docs/specification.mdx"},"files":[{"bytes":13,"kind":"generated","path":"agent-bundle.hooks.json","sha256":"4df87c0d55ad1cbfddaadb62a690a467c4a2661d5da94697caefe9492a0e01b5","sourceInputs":["agent-bundle.config.ts"]},{"bytes":358,"kind":"generated","path":"claude/.claude-plugin/marketplace.json","sha256":"173c38e9dad7ec0bc9f48f850307206bda76817250f88ee71f8148cf84232013","sourceInputs":["agent-bundle.config.ts"]},{"bytes":187,"kind":"generated","path":"claude/.claude-plugin/plugin.json","sha256":"6c214932fd8a194629570beaf09f03b5674235b3825244e41b94ac85925a17e8","sourceInputs":["agent-bundle.config.ts","src/skills/dependency-upgrade/SKILL.md","src/skills/incident-triage/SKILL.md","src/skills/release-review/SKILL.md"]},{"bytes":473,"kind":"generated","path":"claude/INSTALL.md","sha256":"05237956c42069fe4812a300076665b81926069a77eecf373c4759eb73777a94","sourceInputs":["agent-bundle.config.ts"]},{"bytes":481,"kind":"copy","path":"claude/skills/dependency-upgrade/assets/upgrade-plan.md","sha256":"0312c35a9c04a2ad83b8a4fa522c01fe0834c4b98bf75b3436ce0e89cb8aedff","sourceInputs":["src/skills/dependency-upgrade/assets/upgrade-plan.md","src/skills/dependency-upgrade/SKILL.md"]},{"bytes":516,"kind":"copy","path":"claude/skills/dependency-upgrade/references/compatibility-checklist.md","sha256":"47fea616913afa9e185ef9321b8c7ec7b0c4cf2b7d5c5cfad10af0e9c112d3fb","sourceInputs":["src/skills/dependency-upgrade/references/compatibility-checklist.md","src/skills/dependency-upgrade/SKILL.md"]},{"bytes":1351,"kind":"copy","path":"claude/skills/dependency-upgrade/SKILL.md","sha256":"3528992c76717319c27b32624a3e5ff3d84c61cc35a28bbf297d77819148cf69","sourceInputs":["src/skills/dependency-upgrade/SKILL.md"]},{"bytes":417,"kind":"copy","path":"claude/skills/incident-triage/assets/incident-update.md","sha256":"97b690d6d343ca85c09027cce90482416c69447b9cbfcc76120fefb05ed3e1ce","sourceInputs":["src/skills/incident-triage/assets/incident-update.md","src/skills/incident-triage/SKILL.md"]},{"bytes":461,"kind":"copy","path":"claude/skills/incident-triage/references/triage-runbook.md","sha256":"f9be7c2010d5244e8ed3a00e5df552d52553ea265014c5f3b91f3538922301ea","sourceInputs":["src/skills/incident-triage/references/triage-runbook.md","src/skills/incident-triage/SKILL.md"]},{"bytes":1399,"kind":"copy","path":"claude/skills/incident-triage/SKILL.md","sha256":"255e814c4e04f250d3c0cb7109609baf7be3dceff46ce7584dfdf341f02fa2a7","sourceInputs":["src/skills/incident-triage/SKILL.md"]},{"bytes":484,"kind":"copy","path":"claude/skills/release-review/assets/report-template.md","sha256":"ecb13a7c6a895ec2665035897f32fdec468997a5fa442368e16309683108cf88","sourceInputs":["src/skills/release-review/assets/report-template.md","src/skills/release-review/SKILL.md"]},{"bytes":421,"kind":"copy","path":"claude/skills/release-review/references/checklist.md","sha256":"5ee81fae771e1baef7ef4a11c4abad2d7a06fd29b50aeaab3d09a6189cef13f6","sourceInputs":["src/skills/release-review/references/checklist.md","src/skills/release-review/SKILL.md"]},{"bytes":908,"kind":"copy","path":"claude/skills/release-review/references/release-policy.md","sha256":"50c91759e4c3144e3966e4e599e25aaf291fb6a02515a9639bde189e578bac88","sourceInputs":["src/skills/release-review/references/release-policy.md","src/skills/release-review/SKILL.md"]},{"bytes":1353,"kind":"copy","path":"claude/skills/release-review/SKILL.md","sha256":"d9875fcc1cb9119e8cc9c4e09abf8b31bd011bcf5f77d492aae23fbc6e9e1659","sourceInputs":["src/skills/release-review/SKILL.md"]},{"bytes":255,"kind":"generated","path":"codex/.agents/plugins/marketplace.json","sha256":"92a763708bcf83d61e127c6cb01b53004d73ba77e976b18c0be957d26ec4041e","sourceInputs":["agent-bundle.config.ts"]},{"bytes":611,"kind":"generated","path":"codex/.codex-plugin/plugin.json","sha256":"d1e15bed8bff1408dd3b254473067c0411862584b358eef88ebcbd3cd59472bc","sourceInputs":["agent-bundle.config.ts","src/skills/dependency-upgrade/SKILL.md","src/skills/incident-triage/SKILL.md","src/skills/release-review/SKILL.md"]},{"bytes":361,"kind":"generated","path":"codex/INSTALL.md","sha256":"f67365c3cd57f48d62a2f182fb250b5cd334206100a4cc643e8bdf81a1f1dfe2","sourceInputs":["agent-bundle.config.ts"]},{"bytes":481,"kind":"copy","path":"codex/skills/dependency-upgrade/assets/upgrade-plan.md","sha256":"0312c35a9c04a2ad83b8a4fa522c01fe0834c4b98bf75b3436ce0e89cb8aedff","sourceInputs":["src/skills/dependency-upgrade/assets/upgrade-plan.md","src/skills/dependency-upgrade/SKILL.md"]},{"bytes":516,"kind":"copy","path":"codex/skills/dependency-upgrade/references/compatibility-checklist.md","sha256":"47fea616913afa9e185ef9321b8c7ec7b0c4cf2b7d5c5cfad10af0e9c112d3fb","sourceInputs":["src/skills/dependency-upgrade/references/compatibility-checklist.md","src/skills/dependency-upgrade/SKILL.md"]},{"bytes":1351,"kind":"copy","path":"codex/skills/dependency-upgrade/SKILL.md","sha256":"3528992c76717319c27b32624a3e5ff3d84c61cc35a28bbf297d77819148cf69","sourceInputs":["src/skills/dependency-upgrade/SKILL.md"]},{"bytes":417,"kind":"copy","path":"codex/skills/incident-triage/assets/incident-update.md","sha256":"97b690d6d343ca85c09027cce90482416c69447b9cbfcc76120fefb05ed3e1ce","sourceInputs":["src/skills/incident-triage/assets/incident-update.md","src/skills/incident-triage/SKILL.md"]},{"bytes":461,"kind":"copy","path":"codex/skills/incident-triage/references/triage-runbook.md","sha256":"f9be7c2010d5244e8ed3a00e5df552d52553ea265014c5f3b91f3538922301ea","sourceInputs":["src/skills/incident-triage/references/triage-runbook.md","src/skills/incident-triage/SKILL.md"]},{"bytes":1399,"kind":"copy","path":"codex/skills/incident-triage/SKILL.md","sha256":"255e814c4e04f250d3c0cb7109609baf7be3dceff46ce7584dfdf341f02fa2a7","sourceInputs":["src/skills/incident-triage/SKILL.md"]},{"bytes":484,"kind":"copy","path":"codex/skills/release-review/assets/report-template.md","sha256":"ecb13a7c6a895ec2665035897f32fdec468997a5fa442368e16309683108cf88","sourceInputs":["src/skills/release-review/assets/report-template.md","src/skills/release-review/SKILL.md"]},{"bytes":421,"kind":"copy","path":"codex/skills/release-review/references/checklist.md","sha256":"5ee81fae771e1baef7ef4a11c4abad2d7a06fd29b50aeaab3d09a6189cef13f6","sourceInputs":["src/skills/release-review/references/checklist.md","src/skills/release-review/SKILL.md"]},{"bytes":908,"kind":"copy","path":"codex/skills/release-review/references/release-policy.md","sha256":"50c91759e4c3144e3966e4e599e25aaf291fb6a02515a9639bde189e578bac88","sourceInputs":["src/skills/release-review/references/release-policy.md","src/skills/release-review/SKILL.md"]},{"bytes":1353,"kind":"copy","path":"codex/skills/release-review/SKILL.md","sha256":"d9875fcc1cb9119e8cc9c4e09abf8b31bd011bcf5f77d492aae23fbc6e9e1659","sourceInputs":["src/skills/release-review/SKILL.md"]},{"bytes":704,"kind":"generated","path":"portable/INSTALL.md","sha256":"36fcad70168df8ba84710412655ff3baf636f8228357e31f3f4f22aeea4e2ef4","sourceInputs":["agent-bundle.config.ts"]},{"bytes":3308,"kind":"generated","path":"portable/install.mjs","sha256":"86a297294bf7f79001860d0d2bdd496d7bccf16a94201456f97926c3a8c3eff0","sourceInputs":["agent-bundle.config.ts"]},{"bytes":223,"kind":"generated","path":"portable/plugin.json","sha256":"bf4244be5133884977cdf0b957194f7eae0a0058abeda47916200ffd6c1a303d","sourceInputs":["agent-bundle.config.ts"]},{"bytes":481,"kind":"copy","path":"portable/skills/dependency-upgrade/assets/upgrade-plan.md","sha256":"0312c35a9c04a2ad83b8a4fa522c01fe0834c4b98bf75b3436ce0e89cb8aedff","sourceInputs":["src/skills/dependency-upgrade/assets/upgrade-plan.md","src/skills/dependency-upgrade/SKILL.md"]},{"bytes":516,"kind":"copy","path":"portable/skills/dependency-upgrade/references/compatibility-checklist.md","sha256":"47fea616913afa9e185ef9321b8c7ec7b0c4cf2b7d5c5cfad10af0e9c112d3fb","sourceInputs":["src/skills/dependency-upgrade/references/compatibility-checklist.md","src/skills/dependency-upgrade/SKILL.md"]},{"bytes":1351,"kind":"copy","path":"portable/skills/dependency-upgrade/SKILL.md","sha256":"3528992c76717319c27b32624a3e5ff3d84c61cc35a28bbf297d77819148cf69","sourceInputs":["src/skills/dependency-upgrade/SKILL.md"]},{"bytes":417,"kind":"copy","path":"portable/skills/incident-triage/assets/incident-update.md","sha256":"97b690d6d343ca85c09027cce90482416c69447b9cbfcc76120fefb05ed3e1ce","sourceInputs":["src/skills/incident-triage/assets/incident-update.md","src/skills/incident-triage/SKILL.md"]},{"bytes":461,"kind":"copy","path":"portable/skills/incident-triage/references/triage-runbook.md","sha256":"f9be7c2010d5244e8ed3a00e5df552d52553ea265014c5f3b91f3538922301ea","sourceInputs":["src/skills/incident-triage/references/triage-runbook.md","src/skills/incident-triage/SKILL.md"]},{"bytes":1399,"kind":"copy","path":"portable/skills/incident-triage/SKILL.md","sha256":"255e814c4e04f250d3c0cb7109609baf7be3dceff46ce7584dfdf341f02fa2a7","sourceInputs":["src/skills/incident-triage/SKILL.md"]},{"bytes":484,"kind":"copy","path":"portable/skills/release-review/assets/report-template.md","sha256":"ecb13a7c6a895ec2665035897f32fdec468997a5fa442368e16309683108cf88","sourceInputs":["src/skills/release-review/assets/report-template.md","src/skills/release-review/SKILL.md"]},{"bytes":421,"kind":"copy","path":"portable/skills/release-review/references/checklist.md","sha256":"5ee81fae771e1baef7ef4a11c4abad2d7a06fd29b50aeaab3d09a6189cef13f6","sourceInputs":["src/skills/release-review/references/checklist.md","src/skills/release-review/SKILL.md"]},{"bytes":908,"kind":"copy","path":"portable/skills/release-review/references/release-policy.md","sha256":"50c91759e4c3144e3966e4e599e25aaf291fb6a02515a9639bde189e578bac88","sourceInputs":["src/skills/release-review/references/release-policy.md","src/skills/release-review/SKILL.md"]},{"bytes":1353,"kind":"copy","path":"portable/skills/release-review/SKILL.md","sha256":"d9875fcc1cb9119e8cc9c4e09abf8b31bd011bcf5f77d492aae23fbc6e9e1659","sourceInputs":["src/skills/release-review/SKILL.md"]}],"producer":{"name":"agent-bundle","version":"0.1.0"},"project":{"configDigest":"0f589d1a9536e55632bad273cce4d1b41007531a2e6868df0a687ae1a5b0893a","configPath":"agent-bundle.config.ts","modelDigest":"2c1281c98b2a03bbb8d8584df134d7acce0047f52a3f7abbad5b7239577cbc7a","packageName":"@agent-bundle-example/skills-starter","revision":"7e7f9288d2d0cda787fc3c585e47f7a4dcd4a273186817e63b723333d8d76822","sourceInputs":[{"executable":false,"path":"agent-bundle.config.ts","sha256":"0f589d1a9536e55632bad273cce4d1b41007531a2e6868df0a687ae1a5b0893a"},{"executable":false,"path":"evals/engineering-operations.eval.ts","sha256":"60882b3746d4cd258d66d579757935f39666a6e610e86a3dbf7858807a516d69"},{"executable":false,"path":"evals/fixtures/incident/result.json","sha256":"57431bcbff2673ff2cf95f1a1dbccd063b2293b8be8bbc47b235d46f0686659d"},{"executable":false,"path":"evals/fixtures/release/result.json","sha256":"c2a2ddd2207fe2f6da264310c508d1d0384abf76d49ad796fbefcc10eb336905"},{"executable":false,"path":"evals/fixtures/upgrade/result.json","sha256":"9442378ddea4c0880d7a920ee575ed4d06cddae4b305ec403e5d95d03a4a6021"},{"executable":false,"path":"evals/graders/operations-result.ts","sha256":"476c2ca6d8937b8240384af2de0cb2036fc1a72d7cbf715f33142a6427d34471"},{"executable":false,"path":"evals/graders/release-result.ts","sha256":"c9cfcc05e760c5d672685a0a79ccbf96f532674d3e044fbce78328413f0ae06b"},{"executable":false,"path":"evals/release-readiness.eval.ts","sha256":"aa76a5bd2a0c88c0a66952d273cf8c3dd6858598eeea38853123b7b853b1fe1b"},{"executable":false,"path":"package.json","sha256":"fbc2da06b1077164d928667663a8b18f7a6cabae3252118af2b1d62695073ee7"},{"executable":false,"path":"README.md","sha256":"99f3588b978f59fd41971fd15911426da8d1cdff98fa531bb1f6c1e80b23c744"},{"executable":false,"path":"src/skills/dependency-upgrade/assets/upgrade-plan.md","sha256":"0312c35a9c04a2ad83b8a4fa522c01fe0834c4b98bf75b3436ce0e89cb8aedff"},{"executable":false,"path":"src/skills/dependency-upgrade/references/compatibility-checklist.md","sha256":"47fea616913afa9e185ef9321b8c7ec7b0c4cf2b7d5c5cfad10af0e9c112d3fb"},{"executable":false,"path":"src/skills/dependency-upgrade/SKILL.md","sha256":"3528992c76717319c27b32624a3e5ff3d84c61cc35a28bbf297d77819148cf69"},{"executable":false,"path":"src/skills/incident-triage/assets/incident-update.md","sha256":"97b690d6d343ca85c09027cce90482416c69447b9cbfcc76120fefb05ed3e1ce"},{"executable":false,"path":"src/skills/incident-triage/references/triage-runbook.md","sha256":"f9be7c2010d5244e8ed3a00e5df552d52553ea265014c5f3b91f3538922301ea"},{"executable":false,"path":"src/skills/incident-triage/SKILL.md","sha256":"255e814c4e04f250d3c0cb7109609baf7be3dceff46ce7584dfdf341f02fa2a7"},{"executable":false,"path":"src/skills/release-review/assets/report-template.md","sha256":"ecb13a7c6a895ec2665035897f32fdec468997a5fa442368e16309683108cf88"},{"executable":false,"path":"src/skills/release-review/references/checklist.md","sha256":"5ee81fae771e1baef7ef4a11c4abad2d7a06fd29b50aeaab3d09a6189cef13f6"},{"executable":false,"path":"src/skills/release-review/references/release-policy.md","sha256":"50c91759e4c3144e3966e4e599e25aaf291fb6a02515a9639bde189e578bac88"},{"executable":false,"path":"src/skills/release-review/SKILL.md","sha256":"d9875fcc1cb9119e8cc9c4e09abf8b31bd011bcf5f77d492aae23fbc6e9e1659"}]},"runtime":{"node":"22.12.0"},"targets":[{"adapterRevision":"1.22.0","name":"claude","observedVersion":"2.1.250","schemas":[{"name":"hooks","revision":"2.1.250","sha256":"3c6f3e4391f3dca939d75bd0b200ea88e68db939a2cb885d46f0b143293efb84"},{"name":"lsp","revision":"2.1.250","sha256":"c81fd2f57c410f70f8e5c3f84483f5ec1b575ee02802b424977826f757dccd8e"},{"name":"marketplace","revision":"2.1.250","sha256":"4ffa94e8024966e8080b9d3b338c9612bdfa255802a8491b43f74f90427bc988"},{"name":"mcp","revision":"2.1.250","sha256":"76ccf02c7bfe2d57945ba18e84da8d655529bd68b4d692f72bce28238c99067e"},{"name":"monitors","revision":"2.1.250","sha256":"d45abdf7561e4316ba217ce9c2ac84f32e1049622b74abb081693b479a54b48d"},{"name":"plugin","revision":"2.1.250","sha256":"3c9943237da86fd08ae82f698cde36dbef2ecf742098c6961cedf481fe435c12"},{"name":"settings","revision":"2.1.250","sha256":"9e86d8c5e4053e8de0e468d349e2c3dde5834d22d6769372b88570e301700073"},{"name":"theme","revision":"2.1.250","sha256":"721aa9b0bc7c60cd9359343e5c7205ffbdfea82da312f601720c9dfaa2d8cf0d"}]},{"adapterRevision":"1.8.0","name":"codex","observedVersion":"0.147.0","schemas":[{"name":"app","revision":"0.147.0","sha256":"01c720a645e437bf0c4f8c26fd4cb5a13988e5649e4a8562ee23a1d4b7355c6a"},{"name":"hooks","revision":"0.147.0","sha256":"175b859eb8e85bd287d85ee840d97c3f5c2d0dda3223507a796d158e3770eeba"},{"name":"marketplace","revision":"0.147.0","sha256":"fbccce3ade39e1b077fcb440e60260de6e811e8c2d222b2ae0fe8fe47706b470"},{"name":"mcp","revision":"0.147.0","sha256":"75bd50f9fcb85c2e8d43bc132d61c172a02f28ea8bb77389816ae77b14a4257e"},{"name":"plugin","revision":"0.147.0","sha256":"4ad476545c96c83d899c4524dcccd4eb4fe7d3299c307878a0cd46a237f48d58"}]},{"adapterRevision":"1.6.0","name":"portable","observedVersion":"1.0.0","schemas":[{"name":"mcp","revision":"1.0.0","sha256":"6539175bfcdf43085855183e86da40ea94b166547a72b47ae9a0a390516d3acb"},{"name":"plugin","revision":"1.0.0","sha256":"0a4aad95ce337878ad38802ebf0daa3fde76abe3f65400c86bcbb1ec0b3ab883"}]}],"validation":{"artifact":{"status":"passed"},"source":{"status":"passed"},"targets":[{"name":"claude","status":"passed"},{"name":"codex","status":"passed"},{"name":"portable","status":"passed"}]}} diff --git a/examples/skills-starter/artifact/claude/.claude-plugin/marketplace.json b/examples/skills-starter/artifact/claude/.claude-plugin/marketplace.json new file mode 100644 index 000000000..24cb4579e --- /dev/null +++ b/examples/skills-starter/artifact/claude/.claude-plugin/marketplace.json @@ -0,0 +1 @@ +{"description":"A practical engineering operations bundle for incidents, dependency upgrades, and releases.","name":"skills-starter-marketplace","owner":{"name":"skills-starter"},"plugins":[{"description":"A practical engineering operations bundle for incidents, dependency upgrades, and releases.","name":"skills-starter","source":"./","version":"1.0.0"}]} diff --git a/examples/skills-starter/artifact/claude/.claude-plugin/plugin.json b/examples/skills-starter/artifact/claude/.claude-plugin/plugin.json new file mode 100644 index 000000000..0ef4b4869 --- /dev/null +++ b/examples/skills-starter/artifact/claude/.claude-plugin/plugin.json @@ -0,0 +1 @@ +{"author":{"name":"skills-starter"},"description":"A practical engineering operations bundle for incidents, dependency upgrades, and releases.","name":"skills-starter","version":"1.0.0"} diff --git a/examples/skills-starter/artifact/claude/INSTALL.md b/examples/skills-starter/artifact/claude/INSTALL.md new file mode 100644 index 000000000..e5e449b39 --- /dev/null +++ b/examples/skills-starter/artifact/claude/INSTALL.md @@ -0,0 +1,18 @@ +# Install skills-starter + +A practical engineering operations bundle for incidents, dependency upgrades, and releases. + +Version: `1.0.0` + +Run these commands from this bundle directory. + +## Claude Code + +Claude Code installs this bundle through its local marketplace contract: + +```sh +claude plugin marketplace add ./ +claude plugin install skills-starter@skills-starter-marketplace --scope user +``` + +Replace `user` with `project` or `local` when that Claude scope is intended. diff --git a/examples/skills-starter/artifact/claude/skills/dependency-upgrade/SKILL.md b/examples/skills-starter/artifact/claude/skills/dependency-upgrade/SKILL.md new file mode 100644 index 000000000..5f91ab96e --- /dev/null +++ b/examples/skills-starter/artifact/claude/skills/dependency-upgrade/SKILL.md @@ -0,0 +1,33 @@ +--- +name: dependency-upgrade +description: Plans and verifies dependency upgrades with compatibility, rollout, and rollback evidence. +--- +# Dependency upgrade + +## When to use + +Use this Skill for a library, runtime, toolchain, or platform upgrade that can +change public APIs, generated output, operational behavior, or support policy. + +## Required resources + +- Apply [the compatibility checklist](references/compatibility-checklist.md). +- Write the proposal with [the upgrade plan template](assets/upgrade-plan.md). + +## Workflow + +1. Record the current and proposed versions, why the change is needed, and the + supported runtime/package-manager matrix. +2. Read primary release notes and migration guides. List removed APIs, default + changes, peer requirements, and known regressions that intersect this repo. +3. Map affected imports, configuration, generated artifacts, consumers, and + CI/release surfaces before editing. +4. Implement the smallest coherent increment and run focused contract tests, + type checks, production builds, and packed-consumer checks. +5. Define rollout signals and a tested rollback path. Do not call the upgrade + complete until shipped output and a real consumer both pass. + +## Final answer + +State the compatibility decision, changed surfaces, evidence run, remaining +risk, rollout signal, and exact rollback trigger. diff --git a/examples/skills-starter/artifact/claude/skills/dependency-upgrade/assets/upgrade-plan.md b/examples/skills-starter/artifact/claude/skills/dependency-upgrade/assets/upgrade-plan.md new file mode 100644 index 000000000..15ed88f24 --- /dev/null +++ b/examples/skills-starter/artifact/claude/skills/dependency-upgrade/assets/upgrade-plan.md @@ -0,0 +1,21 @@ +# Dependency upgrade plan + +## Decision + +Current version, target version, motivation, and compatibility verdict. + +## Affected surfaces + +Imports, configuration, generated output, consumers, CI, and release tooling. + +## Implementation increments + +Each increment, its tests, and its reversible boundary. + +## Verification + +Commands, observed results, and packed or browser consumer evidence. + +## Rollout and rollback + +Owner, monitored signals, rollback trigger, and rollback procedure. diff --git a/examples/skills-starter/artifact/claude/skills/dependency-upgrade/references/compatibility-checklist.md b/examples/skills-starter/artifact/claude/skills/dependency-upgrade/references/compatibility-checklist.md new file mode 100644 index 000000000..51ac5226a --- /dev/null +++ b/examples/skills-starter/artifact/claude/skills/dependency-upgrade/references/compatibility-checklist.md @@ -0,0 +1,9 @@ +# Compatibility checklist + +- Runtime and package-manager support matrix is explicit. +- Direct, peer, optional, and transitive dependency effects are understood. +- Configuration defaults and removed/deprecated APIs are accounted for. +- Generated files and package exports remain deterministic. +- Type checks, focused tests, production builds, and packed consumers pass. +- CI caches, lockfiles, SBOM, license, and provenance checks remain valid. +- Rollout ownership, telemetry, and rollback conditions are documented. diff --git a/examples/skills-starter/artifact/claude/skills/incident-triage/SKILL.md b/examples/skills-starter/artifact/claude/skills/incident-triage/SKILL.md new file mode 100644 index 000000000..e91f53773 --- /dev/null +++ b/examples/skills-starter/artifact/claude/skills/incident-triage/SKILL.md @@ -0,0 +1,34 @@ +--- +name: incident-triage +description: Triages production incidents with evidence-first containment and a clear operational handoff. +--- +# Incident triage + +## When to use + +Use this Skill when an alert, customer report, or operator observation suggests +an active production incident and the team needs a fast, auditable first pass. + +## Required resources + +- Follow [the triage runbook](references/triage-runbook.md) for the first 30 minutes. +- Record the handoff with [the incident update template](assets/incident-update.md). + +## Workflow + +1. Establish impact: affected users, services, regions, start time, and the + strongest known symptom. Separate observed facts from hypotheses. +2. Preserve evidence before changing the system: relevant request IDs, logs, + metrics, deploys, feature flags, and dependency health. +3. Choose the smallest reversible containment action. State its expected signal + and rollback condition before executing it. +4. Re-evaluate impact after containment. Escalate when severity, ownership, or + blast radius remains uncertain. +5. Produce an incident update with timeline, current impact, actions, owners, + open questions, and the next update time. + +## Guardrails + +- Never claim root cause from correlation alone. +- Never expose credentials, customer payloads, or private identifiers. +- Never make a destructive or irreversible change without explicit authority. diff --git a/examples/skills-starter/artifact/claude/skills/incident-triage/assets/incident-update.md b/examples/skills-starter/artifact/claude/skills/incident-triage/assets/incident-update.md new file mode 100644 index 000000000..1e2b7529f --- /dev/null +++ b/examples/skills-starter/artifact/claude/skills/incident-triage/assets/incident-update.md @@ -0,0 +1,9 @@ +# Incident update + +- **Status:** investigating | identified | monitoring | resolved +- **Impact:** users, services, regions, and start time +- **Observed evidence:** metrics, logs, requests, and recent changes +- **Actions taken:** action, owner, result, and rollback state +- **Current hypothesis:** clearly marked as confirmed or unconfirmed +- **Next steps:** owner and expected completion +- **Next update:** timestamp diff --git a/examples/skills-starter/artifact/claude/skills/incident-triage/references/triage-runbook.md b/examples/skills-starter/artifact/claude/skills/incident-triage/references/triage-runbook.md new file mode 100644 index 000000000..d98d8a283 --- /dev/null +++ b/examples/skills-starter/artifact/claude/skills/incident-triage/references/triage-runbook.md @@ -0,0 +1,9 @@ +# First 30 minutes + +1. Acknowledge the incident and name an incident lead. +2. Capture the first known bad time and a comparable known-good baseline. +3. Check recent deploys, configuration changes, dependency status, and capacity. +4. Identify one measurable containment hypothesis and its rollback signal. +5. Update stakeholders with facts, uncertainty, owners, and the next checkpoint. + +Severity is driven by user impact and recovery risk, not by alert volume. diff --git a/examples/skills-starter/artifact/claude/skills/release-review/SKILL.md b/examples/skills-starter/artifact/claude/skills/release-review/SKILL.md new file mode 100644 index 000000000..085376189 --- /dev/null +++ b/examples/skills-starter/artifact/claude/skills/release-review/SKILL.md @@ -0,0 +1,34 @@ +--- +name: release-review +description: Reviews release evidence and issues an auditable readiness verdict. +--- +# Release review + +## When to use + +Use this Skill when a release candidate needs a go/no-go verdict supported by +checked, reproducible evidence. + +## Required resources + +- Read [the release checklist](references/checklist.md) to inspect the artifact. +- Apply [the release readiness policy](references/release-policy.md) to classify findings. +- Deliver the result with [the release readiness report template](assets/report-template.md). + +## Workflow + +1. Gather evidence for each checklist item. Cite the command, artifact path, + observed result, and reproduction steps for every finding. +2. Classify each finding using the policy severity. A blocker prevents a + `ready` verdict; unresolved non-blockers must still be disclosed. +3. Decide the verdict only after all required evidence is recorded. Use + `ready` only when there are no blockers. +4. Complete every section of the report template: verdict, evidence, findings, + blockers, and required follow-up. + +## Final report requirements + +The final report must state `ready`, `not ready`, or `needs evidence`; list +all evidence reviewed; give each finding a severity and reproduction; and make +the blocker count explicit. Do not issue `ready` when evidence is missing or a +blocker remains. diff --git a/examples/skills-starter/artifact/claude/skills/release-review/assets/report-template.md b/examples/skills-starter/artifact/claude/skills/release-review/assets/report-template.md new file mode 100644 index 000000000..76fb83fc7 --- /dev/null +++ b/examples/skills-starter/artifact/claude/skills/release-review/assets/report-template.md @@ -0,0 +1,22 @@ +# Release readiness report + +## Verdict + +State `ready`, `not ready`, or `needs evidence`, and give the blocker count. + +## Evidence reviewed + +For each check, record the command, artifact path, observed result, and date. + +## Findings + +List each concrete issue, its severity, impact, owner, and reproduction. + +## Blockers + +List every unresolved blocker, or state `None`. + +## Required follow-up + +Record the owner, mitigation, and decision date for every unresolved Major or +Minor finding. diff --git a/examples/skills-starter/artifact/claude/skills/release-review/references/checklist.md b/examples/skills-starter/artifact/claude/skills/release-review/references/checklist.md new file mode 100644 index 000000000..823e865a9 --- /dev/null +++ b/examples/skills-starter/artifact/claude/skills/release-review/references/checklist.md @@ -0,0 +1,8 @@ +# Release checklist + +1. Confirm the release artifact contains the documented public entrypoints. +2. Confirm generated files are reproducible from the checked-in sources. +3. Run the documented validation, build, and deterministic evaluation commands. +4. Record the command, artifact path, observed output, and reproduction for + every defect. +5. Classify every defect with the severity from the release readiness policy. diff --git a/examples/skills-starter/artifact/claude/skills/release-review/references/release-policy.md b/examples/skills-starter/artifact/claude/skills/release-review/references/release-policy.md new file mode 100644 index 000000000..09ceb86ba --- /dev/null +++ b/examples/skills-starter/artifact/claude/skills/release-review/references/release-policy.md @@ -0,0 +1,22 @@ +# Release readiness policy + +## Evidence standard + +Release evidence must be specific, reproducible, and tied to the candidate: +record the command, artifact path, observed result, and reproduction steps. +Missing or stale evidence is not proof of readiness. + +## Severity + +- **Blocker**: prevents safe release, violates a documented contract, or has no + viable mitigation. Any blocker requires a `not ready` verdict. +- **Major**: materially degrades a supported workflow. It must have an owner, + mitigation, and release decision recorded in the report. +- **Minor**: limited-scope issue with an agreed follow-up. It does not prevent + `ready` when its evidence and owner are recorded. + +## Verdict policy + +Issue `ready` only when all required evidence is current and the blocker list +is empty. Issue `needs evidence` when required evidence is absent, stale, or +cannot be reproduced. Otherwise issue `not ready`. diff --git a/examples/skills-starter/artifact/codex/.agents/plugins/marketplace.json b/examples/skills-starter/artifact/codex/.agents/plugins/marketplace.json new file mode 100644 index 000000000..b3a1fadbc --- /dev/null +++ b/examples/skills-starter/artifact/codex/.agents/plugins/marketplace.json @@ -0,0 +1 @@ +{"interface":{"displayName":"skills-starter"},"name":"skills-starter-marketplace","plugins":[{"category":"Productivity","name":"skills-starter","policy":{"authentication":"ON_INSTALL","installation":"AVAILABLE"},"source":{"path":"./","source":"local"}}]} diff --git a/examples/skills-starter/artifact/codex/.codex-plugin/plugin.json b/examples/skills-starter/artifact/codex/.codex-plugin/plugin.json new file mode 100644 index 000000000..44161e85b --- /dev/null +++ b/examples/skills-starter/artifact/codex/.codex-plugin/plugin.json @@ -0,0 +1 @@ +{"author":{"name":"skills-starter"},"description":"A practical engineering operations bundle for incidents, dependency upgrades, and releases.","interface":{"capabilities":["skills"],"category":"Productivity","defaultPrompt":["Help me use skills-starter."],"developerName":"skills-starter","displayName":"skills-starter","longDescription":"A practical engineering operations bundle for incidents, dependency upgrades, and releases.","shortDescription":"A practical engineering operations bundle for incidents, dependency upgrades, and releases."},"name":"skills-starter","skills":"./skills/","version":"1.0.0"} diff --git a/examples/skills-starter/artifact/codex/INSTALL.md b/examples/skills-starter/artifact/codex/INSTALL.md new file mode 100644 index 000000000..0c56ee69d --- /dev/null +++ b/examples/skills-starter/artifact/codex/INSTALL.md @@ -0,0 +1,16 @@ +# Install skills-starter + +A practical engineering operations bundle for incidents, dependency upgrades, and releases. + +Version: `1.0.0` + +Run these commands from this bundle directory. + +## Codex + +Codex installs this bundle from its local marketplace snapshot: + +```sh +codex plugin marketplace add ./ +codex plugin add skills-starter@skills-starter-marketplace +``` diff --git a/examples/skills-starter/artifact/codex/skills/dependency-upgrade/SKILL.md b/examples/skills-starter/artifact/codex/skills/dependency-upgrade/SKILL.md new file mode 100644 index 000000000..5f91ab96e --- /dev/null +++ b/examples/skills-starter/artifact/codex/skills/dependency-upgrade/SKILL.md @@ -0,0 +1,33 @@ +--- +name: dependency-upgrade +description: Plans and verifies dependency upgrades with compatibility, rollout, and rollback evidence. +--- +# Dependency upgrade + +## When to use + +Use this Skill for a library, runtime, toolchain, or platform upgrade that can +change public APIs, generated output, operational behavior, or support policy. + +## Required resources + +- Apply [the compatibility checklist](references/compatibility-checklist.md). +- Write the proposal with [the upgrade plan template](assets/upgrade-plan.md). + +## Workflow + +1. Record the current and proposed versions, why the change is needed, and the + supported runtime/package-manager matrix. +2. Read primary release notes and migration guides. List removed APIs, default + changes, peer requirements, and known regressions that intersect this repo. +3. Map affected imports, configuration, generated artifacts, consumers, and + CI/release surfaces before editing. +4. Implement the smallest coherent increment and run focused contract tests, + type checks, production builds, and packed-consumer checks. +5. Define rollout signals and a tested rollback path. Do not call the upgrade + complete until shipped output and a real consumer both pass. + +## Final answer + +State the compatibility decision, changed surfaces, evidence run, remaining +risk, rollout signal, and exact rollback trigger. diff --git a/examples/skills-starter/artifact/codex/skills/dependency-upgrade/assets/upgrade-plan.md b/examples/skills-starter/artifact/codex/skills/dependency-upgrade/assets/upgrade-plan.md new file mode 100644 index 000000000..15ed88f24 --- /dev/null +++ b/examples/skills-starter/artifact/codex/skills/dependency-upgrade/assets/upgrade-plan.md @@ -0,0 +1,21 @@ +# Dependency upgrade plan + +## Decision + +Current version, target version, motivation, and compatibility verdict. + +## Affected surfaces + +Imports, configuration, generated output, consumers, CI, and release tooling. + +## Implementation increments + +Each increment, its tests, and its reversible boundary. + +## Verification + +Commands, observed results, and packed or browser consumer evidence. + +## Rollout and rollback + +Owner, monitored signals, rollback trigger, and rollback procedure. diff --git a/examples/skills-starter/artifact/codex/skills/dependency-upgrade/references/compatibility-checklist.md b/examples/skills-starter/artifact/codex/skills/dependency-upgrade/references/compatibility-checklist.md new file mode 100644 index 000000000..51ac5226a --- /dev/null +++ b/examples/skills-starter/artifact/codex/skills/dependency-upgrade/references/compatibility-checklist.md @@ -0,0 +1,9 @@ +# Compatibility checklist + +- Runtime and package-manager support matrix is explicit. +- Direct, peer, optional, and transitive dependency effects are understood. +- Configuration defaults and removed/deprecated APIs are accounted for. +- Generated files and package exports remain deterministic. +- Type checks, focused tests, production builds, and packed consumers pass. +- CI caches, lockfiles, SBOM, license, and provenance checks remain valid. +- Rollout ownership, telemetry, and rollback conditions are documented. diff --git a/examples/skills-starter/artifact/codex/skills/incident-triage/SKILL.md b/examples/skills-starter/artifact/codex/skills/incident-triage/SKILL.md new file mode 100644 index 000000000..e91f53773 --- /dev/null +++ b/examples/skills-starter/artifact/codex/skills/incident-triage/SKILL.md @@ -0,0 +1,34 @@ +--- +name: incident-triage +description: Triages production incidents with evidence-first containment and a clear operational handoff. +--- +# Incident triage + +## When to use + +Use this Skill when an alert, customer report, or operator observation suggests +an active production incident and the team needs a fast, auditable first pass. + +## Required resources + +- Follow [the triage runbook](references/triage-runbook.md) for the first 30 minutes. +- Record the handoff with [the incident update template](assets/incident-update.md). + +## Workflow + +1. Establish impact: affected users, services, regions, start time, and the + strongest known symptom. Separate observed facts from hypotheses. +2. Preserve evidence before changing the system: relevant request IDs, logs, + metrics, deploys, feature flags, and dependency health. +3. Choose the smallest reversible containment action. State its expected signal + and rollback condition before executing it. +4. Re-evaluate impact after containment. Escalate when severity, ownership, or + blast radius remains uncertain. +5. Produce an incident update with timeline, current impact, actions, owners, + open questions, and the next update time. + +## Guardrails + +- Never claim root cause from correlation alone. +- Never expose credentials, customer payloads, or private identifiers. +- Never make a destructive or irreversible change without explicit authority. diff --git a/examples/skills-starter/artifact/codex/skills/incident-triage/assets/incident-update.md b/examples/skills-starter/artifact/codex/skills/incident-triage/assets/incident-update.md new file mode 100644 index 000000000..1e2b7529f --- /dev/null +++ b/examples/skills-starter/artifact/codex/skills/incident-triage/assets/incident-update.md @@ -0,0 +1,9 @@ +# Incident update + +- **Status:** investigating | identified | monitoring | resolved +- **Impact:** users, services, regions, and start time +- **Observed evidence:** metrics, logs, requests, and recent changes +- **Actions taken:** action, owner, result, and rollback state +- **Current hypothesis:** clearly marked as confirmed or unconfirmed +- **Next steps:** owner and expected completion +- **Next update:** timestamp diff --git a/examples/skills-starter/artifact/codex/skills/incident-triage/references/triage-runbook.md b/examples/skills-starter/artifact/codex/skills/incident-triage/references/triage-runbook.md new file mode 100644 index 000000000..d98d8a283 --- /dev/null +++ b/examples/skills-starter/artifact/codex/skills/incident-triage/references/triage-runbook.md @@ -0,0 +1,9 @@ +# First 30 minutes + +1. Acknowledge the incident and name an incident lead. +2. Capture the first known bad time and a comparable known-good baseline. +3. Check recent deploys, configuration changes, dependency status, and capacity. +4. Identify one measurable containment hypothesis and its rollback signal. +5. Update stakeholders with facts, uncertainty, owners, and the next checkpoint. + +Severity is driven by user impact and recovery risk, not by alert volume. diff --git a/examples/skills-starter/artifact/codex/skills/release-review/SKILL.md b/examples/skills-starter/artifact/codex/skills/release-review/SKILL.md new file mode 100644 index 000000000..085376189 --- /dev/null +++ b/examples/skills-starter/artifact/codex/skills/release-review/SKILL.md @@ -0,0 +1,34 @@ +--- +name: release-review +description: Reviews release evidence and issues an auditable readiness verdict. +--- +# Release review + +## When to use + +Use this Skill when a release candidate needs a go/no-go verdict supported by +checked, reproducible evidence. + +## Required resources + +- Read [the release checklist](references/checklist.md) to inspect the artifact. +- Apply [the release readiness policy](references/release-policy.md) to classify findings. +- Deliver the result with [the release readiness report template](assets/report-template.md). + +## Workflow + +1. Gather evidence for each checklist item. Cite the command, artifact path, + observed result, and reproduction steps for every finding. +2. Classify each finding using the policy severity. A blocker prevents a + `ready` verdict; unresolved non-blockers must still be disclosed. +3. Decide the verdict only after all required evidence is recorded. Use + `ready` only when there are no blockers. +4. Complete every section of the report template: verdict, evidence, findings, + blockers, and required follow-up. + +## Final report requirements + +The final report must state `ready`, `not ready`, or `needs evidence`; list +all evidence reviewed; give each finding a severity and reproduction; and make +the blocker count explicit. Do not issue `ready` when evidence is missing or a +blocker remains. diff --git a/examples/skills-starter/artifact/codex/skills/release-review/assets/report-template.md b/examples/skills-starter/artifact/codex/skills/release-review/assets/report-template.md new file mode 100644 index 000000000..76fb83fc7 --- /dev/null +++ b/examples/skills-starter/artifact/codex/skills/release-review/assets/report-template.md @@ -0,0 +1,22 @@ +# Release readiness report + +## Verdict + +State `ready`, `not ready`, or `needs evidence`, and give the blocker count. + +## Evidence reviewed + +For each check, record the command, artifact path, observed result, and date. + +## Findings + +List each concrete issue, its severity, impact, owner, and reproduction. + +## Blockers + +List every unresolved blocker, or state `None`. + +## Required follow-up + +Record the owner, mitigation, and decision date for every unresolved Major or +Minor finding. diff --git a/examples/skills-starter/artifact/codex/skills/release-review/references/checklist.md b/examples/skills-starter/artifact/codex/skills/release-review/references/checklist.md new file mode 100644 index 000000000..823e865a9 --- /dev/null +++ b/examples/skills-starter/artifact/codex/skills/release-review/references/checklist.md @@ -0,0 +1,8 @@ +# Release checklist + +1. Confirm the release artifact contains the documented public entrypoints. +2. Confirm generated files are reproducible from the checked-in sources. +3. Run the documented validation, build, and deterministic evaluation commands. +4. Record the command, artifact path, observed output, and reproduction for + every defect. +5. Classify every defect with the severity from the release readiness policy. diff --git a/examples/skills-starter/artifact/codex/skills/release-review/references/release-policy.md b/examples/skills-starter/artifact/codex/skills/release-review/references/release-policy.md new file mode 100644 index 000000000..09ceb86ba --- /dev/null +++ b/examples/skills-starter/artifact/codex/skills/release-review/references/release-policy.md @@ -0,0 +1,22 @@ +# Release readiness policy + +## Evidence standard + +Release evidence must be specific, reproducible, and tied to the candidate: +record the command, artifact path, observed result, and reproduction steps. +Missing or stale evidence is not proof of readiness. + +## Severity + +- **Blocker**: prevents safe release, violates a documented contract, or has no + viable mitigation. Any blocker requires a `not ready` verdict. +- **Major**: materially degrades a supported workflow. It must have an owner, + mitigation, and release decision recorded in the report. +- **Minor**: limited-scope issue with an agreed follow-up. It does not prevent + `ready` when its evidence and owner are recorded. + +## Verdict policy + +Issue `ready` only when all required evidence is current and the blocker list +is empty. Issue `needs evidence` when required evidence is absent, stale, or +cannot be reproduced. Otherwise issue `not ready`. diff --git a/examples/skills-starter/artifact/portable/INSTALL.md b/examples/skills-starter/artifact/portable/INSTALL.md new file mode 100644 index 000000000..bf452980c --- /dev/null +++ b/examples/skills-starter/artifact/portable/INSTALL.md @@ -0,0 +1,19 @@ +# Install skills-starter + +A practical engineering operations bundle for incidents, dependency upgrades, and releases. + +Version: `1.0.0` + +Run these commands from this bundle directory. + +## Portable Agent Plugin + +Portable is a distribution profile, not a host runtime with one universal install location. +This bundle follows the Agent Plugins open standard (Agent Plugins 1.0.0, https://agent-plugins.org). +Cursor loads this format natively from `~/.cursor/plugins/local/`; restart Cursor or run +`Developer: Reload Window` after copying it. Codex, VS Code, GitHub Copilot, Kiro, and ChatGPT +are also native clients. The bundled installer provides the Cursor local copy: + +```sh +node ./install.mjs +``` diff --git a/examples/skills-starter/artifact/portable/install.mjs b/examples/skills-starter/artifact/portable/install.mjs new file mode 100644 index 000000000..51b9b39a7 --- /dev/null +++ b/examples/skills-starter/artifact/portable/install.mjs @@ -0,0 +1,80 @@ +#!/usr/bin/env node +import { createHash } from 'node:crypto'; +import { cp, lstat, mkdir, mkdtemp, readFile, readdir, rename, rm } from 'node:fs/promises'; +import { homedir } from 'node:os'; +import { basename, join, resolve } from 'node:path'; +import { fileURLToPath } from 'node:url'; + +const pluginName = "skills-starter"; +const pluginVersion = "1.0.0"; +const source = resolve(fileURLToPath(new URL('.', import.meta.url))); +const cursorRoot = join(homedir(), '.cursor'); +const installRoot = join(cursorRoot, 'plugins', 'local'); +const destination = join(installRoot, pluginName); + +const exists = async (path) => { + try { await lstat(path); return true; } + catch (error) { if (error?.code === 'ENOENT') return false; throw error; } +}; + +const treeHash = async (root, prefix = '') => { + const rootMetadata = await lstat(root); + if (rootMetadata.isSymbolicLink() || !rootMetadata.isDirectory()) { + throw new Error('Refusing unsupported filesystem entry ".".'); + } + const hash = createHash('sha256'); + const visit = async (relative) => { + const absolute = join(root, relative); + const metadata = await lstat(absolute); + if (metadata.isSymbolicLink() || (!metadata.isDirectory() && !metadata.isFile())) { + throw new Error(`Refusing unsupported filesystem entry ${JSON.stringify(relative || '.')}.`); + } + if (metadata.isDirectory()) { + for (const name of (await readdir(absolute)).sort()) await visit(join(relative, name)); + return; + } + hash.update(relative.replaceAll('\\', '/')); + hash.update('\0'); + hash.update(await readFile(absolute)); + hash.update('\0'); + }; + for (const name of (await readdir(root)).sort()) await visit(join(prefix, name)); + return hash.digest('hex'); +}; + +const installedVersion = async () => { + for (const manifest of ['.cursor-plugin/plugin.json', 'plugin.json']) { + try { + const value = JSON.parse(await readFile(join(destination, manifest), 'utf8')); + if (typeof value.version === 'string') return value.version; + } catch (error) { if (error?.code !== 'ENOENT') throw error; } + } + return undefined; +}; + +if (!(await exists(cursorRoot)) || !(await lstat(cursorRoot)).isDirectory()) { + throw new Error(`Cursor is not installed in ${cursorRoot}.`); +} +await mkdir(installRoot, { recursive: true }); +if (await exists(destination)) { + const currentVersion = await installedVersion(); + if (currentVersion !== undefined && currentVersion !== pluginVersion) { + throw new Error(`Refusing version collision at ${destination}: found ${currentVersion}, requested ${pluginVersion}.`); + } + if (source === destination || await treeHash(source) === await treeHash(destination)) { + console.log(`Already installed ${pluginName}@${pluginVersion} at ${destination}`); + process.exit(0); + } + throw new Error(`Refusing content collision at ${destination}.`); +} + +const stageParent = await mkdtemp(join(installRoot, `.${basename(destination)}.stage-`)); +const stage = join(stageParent, 'bundle'); +try { + await cp(source, stage, { errorOnExist: true, force: false, recursive: true, verbatimSymlinks: true }); + await treeHash(stage); + await rename(stage, destination); + console.log(`Installed ${pluginName}@${pluginVersion} at ${destination}`); +} finally { + await rm(stageParent, { force: true, recursive: true }); +} diff --git a/examples/skills-starter/artifact/portable/plugin.json b/examples/skills-starter/artifact/portable/plugin.json new file mode 100644 index 000000000..42585f082 --- /dev/null +++ b/examples/skills-starter/artifact/portable/plugin.json @@ -0,0 +1 @@ +{"$schema":"https://agent-plugins.org/schemas/1.0.0/plugin.schema.json","description":"A practical engineering operations bundle for incidents, dependency upgrades, and releases.","name":"skills-starter","version":"1.0.0"} diff --git a/examples/skills-starter/artifact/portable/skills/dependency-upgrade/SKILL.md b/examples/skills-starter/artifact/portable/skills/dependency-upgrade/SKILL.md new file mode 100644 index 000000000..5f91ab96e --- /dev/null +++ b/examples/skills-starter/artifact/portable/skills/dependency-upgrade/SKILL.md @@ -0,0 +1,33 @@ +--- +name: dependency-upgrade +description: Plans and verifies dependency upgrades with compatibility, rollout, and rollback evidence. +--- +# Dependency upgrade + +## When to use + +Use this Skill for a library, runtime, toolchain, or platform upgrade that can +change public APIs, generated output, operational behavior, or support policy. + +## Required resources + +- Apply [the compatibility checklist](references/compatibility-checklist.md). +- Write the proposal with [the upgrade plan template](assets/upgrade-plan.md). + +## Workflow + +1. Record the current and proposed versions, why the change is needed, and the + supported runtime/package-manager matrix. +2. Read primary release notes and migration guides. List removed APIs, default + changes, peer requirements, and known regressions that intersect this repo. +3. Map affected imports, configuration, generated artifacts, consumers, and + CI/release surfaces before editing. +4. Implement the smallest coherent increment and run focused contract tests, + type checks, production builds, and packed-consumer checks. +5. Define rollout signals and a tested rollback path. Do not call the upgrade + complete until shipped output and a real consumer both pass. + +## Final answer + +State the compatibility decision, changed surfaces, evidence run, remaining +risk, rollout signal, and exact rollback trigger. diff --git a/examples/skills-starter/artifact/portable/skills/dependency-upgrade/assets/upgrade-plan.md b/examples/skills-starter/artifact/portable/skills/dependency-upgrade/assets/upgrade-plan.md new file mode 100644 index 000000000..15ed88f24 --- /dev/null +++ b/examples/skills-starter/artifact/portable/skills/dependency-upgrade/assets/upgrade-plan.md @@ -0,0 +1,21 @@ +# Dependency upgrade plan + +## Decision + +Current version, target version, motivation, and compatibility verdict. + +## Affected surfaces + +Imports, configuration, generated output, consumers, CI, and release tooling. + +## Implementation increments + +Each increment, its tests, and its reversible boundary. + +## Verification + +Commands, observed results, and packed or browser consumer evidence. + +## Rollout and rollback + +Owner, monitored signals, rollback trigger, and rollback procedure. diff --git a/examples/skills-starter/artifact/portable/skills/dependency-upgrade/references/compatibility-checklist.md b/examples/skills-starter/artifact/portable/skills/dependency-upgrade/references/compatibility-checklist.md new file mode 100644 index 000000000..51ac5226a --- /dev/null +++ b/examples/skills-starter/artifact/portable/skills/dependency-upgrade/references/compatibility-checklist.md @@ -0,0 +1,9 @@ +# Compatibility checklist + +- Runtime and package-manager support matrix is explicit. +- Direct, peer, optional, and transitive dependency effects are understood. +- Configuration defaults and removed/deprecated APIs are accounted for. +- Generated files and package exports remain deterministic. +- Type checks, focused tests, production builds, and packed consumers pass. +- CI caches, lockfiles, SBOM, license, and provenance checks remain valid. +- Rollout ownership, telemetry, and rollback conditions are documented. diff --git a/examples/skills-starter/artifact/portable/skills/incident-triage/SKILL.md b/examples/skills-starter/artifact/portable/skills/incident-triage/SKILL.md new file mode 100644 index 000000000..e91f53773 --- /dev/null +++ b/examples/skills-starter/artifact/portable/skills/incident-triage/SKILL.md @@ -0,0 +1,34 @@ +--- +name: incident-triage +description: Triages production incidents with evidence-first containment and a clear operational handoff. +--- +# Incident triage + +## When to use + +Use this Skill when an alert, customer report, or operator observation suggests +an active production incident and the team needs a fast, auditable first pass. + +## Required resources + +- Follow [the triage runbook](references/triage-runbook.md) for the first 30 minutes. +- Record the handoff with [the incident update template](assets/incident-update.md). + +## Workflow + +1. Establish impact: affected users, services, regions, start time, and the + strongest known symptom. Separate observed facts from hypotheses. +2. Preserve evidence before changing the system: relevant request IDs, logs, + metrics, deploys, feature flags, and dependency health. +3. Choose the smallest reversible containment action. State its expected signal + and rollback condition before executing it. +4. Re-evaluate impact after containment. Escalate when severity, ownership, or + blast radius remains uncertain. +5. Produce an incident update with timeline, current impact, actions, owners, + open questions, and the next update time. + +## Guardrails + +- Never claim root cause from correlation alone. +- Never expose credentials, customer payloads, or private identifiers. +- Never make a destructive or irreversible change without explicit authority. diff --git a/examples/skills-starter/artifact/portable/skills/incident-triage/assets/incident-update.md b/examples/skills-starter/artifact/portable/skills/incident-triage/assets/incident-update.md new file mode 100644 index 000000000..1e2b7529f --- /dev/null +++ b/examples/skills-starter/artifact/portable/skills/incident-triage/assets/incident-update.md @@ -0,0 +1,9 @@ +# Incident update + +- **Status:** investigating | identified | monitoring | resolved +- **Impact:** users, services, regions, and start time +- **Observed evidence:** metrics, logs, requests, and recent changes +- **Actions taken:** action, owner, result, and rollback state +- **Current hypothesis:** clearly marked as confirmed or unconfirmed +- **Next steps:** owner and expected completion +- **Next update:** timestamp diff --git a/examples/skills-starter/artifact/portable/skills/incident-triage/references/triage-runbook.md b/examples/skills-starter/artifact/portable/skills/incident-triage/references/triage-runbook.md new file mode 100644 index 000000000..d98d8a283 --- /dev/null +++ b/examples/skills-starter/artifact/portable/skills/incident-triage/references/triage-runbook.md @@ -0,0 +1,9 @@ +# First 30 minutes + +1. Acknowledge the incident and name an incident lead. +2. Capture the first known bad time and a comparable known-good baseline. +3. Check recent deploys, configuration changes, dependency status, and capacity. +4. Identify one measurable containment hypothesis and its rollback signal. +5. Update stakeholders with facts, uncertainty, owners, and the next checkpoint. + +Severity is driven by user impact and recovery risk, not by alert volume. diff --git a/examples/skills-starter/artifact/portable/skills/release-review/SKILL.md b/examples/skills-starter/artifact/portable/skills/release-review/SKILL.md new file mode 100644 index 000000000..085376189 --- /dev/null +++ b/examples/skills-starter/artifact/portable/skills/release-review/SKILL.md @@ -0,0 +1,34 @@ +--- +name: release-review +description: Reviews release evidence and issues an auditable readiness verdict. +--- +# Release review + +## When to use + +Use this Skill when a release candidate needs a go/no-go verdict supported by +checked, reproducible evidence. + +## Required resources + +- Read [the release checklist](references/checklist.md) to inspect the artifact. +- Apply [the release readiness policy](references/release-policy.md) to classify findings. +- Deliver the result with [the release readiness report template](assets/report-template.md). + +## Workflow + +1. Gather evidence for each checklist item. Cite the command, artifact path, + observed result, and reproduction steps for every finding. +2. Classify each finding using the policy severity. A blocker prevents a + `ready` verdict; unresolved non-blockers must still be disclosed. +3. Decide the verdict only after all required evidence is recorded. Use + `ready` only when there are no blockers. +4. Complete every section of the report template: verdict, evidence, findings, + blockers, and required follow-up. + +## Final report requirements + +The final report must state `ready`, `not ready`, or `needs evidence`; list +all evidence reviewed; give each finding a severity and reproduction; and make +the blocker count explicit. Do not issue `ready` when evidence is missing or a +blocker remains. diff --git a/examples/skills-starter/artifact/portable/skills/release-review/assets/report-template.md b/examples/skills-starter/artifact/portable/skills/release-review/assets/report-template.md new file mode 100644 index 000000000..76fb83fc7 --- /dev/null +++ b/examples/skills-starter/artifact/portable/skills/release-review/assets/report-template.md @@ -0,0 +1,22 @@ +# Release readiness report + +## Verdict + +State `ready`, `not ready`, or `needs evidence`, and give the blocker count. + +## Evidence reviewed + +For each check, record the command, artifact path, observed result, and date. + +## Findings + +List each concrete issue, its severity, impact, owner, and reproduction. + +## Blockers + +List every unresolved blocker, or state `None`. + +## Required follow-up + +Record the owner, mitigation, and decision date for every unresolved Major or +Minor finding. diff --git a/examples/skills-starter/artifact/portable/skills/release-review/references/checklist.md b/examples/skills-starter/artifact/portable/skills/release-review/references/checklist.md new file mode 100644 index 000000000..823e865a9 --- /dev/null +++ b/examples/skills-starter/artifact/portable/skills/release-review/references/checklist.md @@ -0,0 +1,8 @@ +# Release checklist + +1. Confirm the release artifact contains the documented public entrypoints. +2. Confirm generated files are reproducible from the checked-in sources. +3. Run the documented validation, build, and deterministic evaluation commands. +4. Record the command, artifact path, observed output, and reproduction for + every defect. +5. Classify every defect with the severity from the release readiness policy. diff --git a/examples/skills-starter/artifact/portable/skills/release-review/references/release-policy.md b/examples/skills-starter/artifact/portable/skills/release-review/references/release-policy.md new file mode 100644 index 000000000..09ceb86ba --- /dev/null +++ b/examples/skills-starter/artifact/portable/skills/release-review/references/release-policy.md @@ -0,0 +1,22 @@ +# Release readiness policy + +## Evidence standard + +Release evidence must be specific, reproducible, and tied to the candidate: +record the command, artifact path, observed result, and reproduction steps. +Missing or stale evidence is not proof of readiness. + +## Severity + +- **Blocker**: prevents safe release, violates a documented contract, or has no + viable mitigation. Any blocker requires a `not ready` verdict. +- **Major**: materially degrades a supported workflow. It must have an owner, + mitigation, and release decision recorded in the report. +- **Minor**: limited-scope issue with an agreed follow-up. It does not prevent + `ready` when its evidence and owner are recorded. + +## Verdict policy + +Issue `ready` only when all required evidence is current and the blocker list +is empty. Issue `needs evidence` when required evidence is absent, stale, or +cannot be reproduced. Otherwise issue `not ready`. diff --git a/fixtures/host-lineage/claude-2.1.257.ndjson b/fixtures/host-lineage/claude-2.1.257.ndjson index c2951d76d..540fad190 100644 --- a/fixtures/host-lineage/claude-2.1.257.ndjson +++ b/fixtures/host-lineage/claude-2.1.257.ndjson @@ -1,32 +1,37 @@ -{"env":{"names":["ANTHROPIC_API_KEY","ANTHROPIC_BASE_URL","CLAUDE_CODE_CHILD_SESSION","CLAUDE_CODE_DISABLE_NONESSENTIAL_TRAFFIC","CLAUDE_CODE_ENTRYPOINT","CLAUDE_CODE_MESSAGING_SOCKET","CLAUDE_CODE_MESSAGING_TOKEN","CLAUDE_CODE_SESSION_ID","CLAUDE_CONFIG_DIR","CLAUDE_ENV_FILE","CLAUDE_PID","CLAUDE_PLUGIN_DATA","CLAUDE_PLUGIN_ROOT","CLAUDE_PROJECT_DIR","CURSOR_LAYOUT","CURSOR_RIPGREP_PATH","HOST_TEST_LOG_DIR"]},"event":{"canonical":{"event":"session/start","idempotencyKey":"155055116628f545723798ead3b8cb5b697796294d06b238652cf931a129e031","observedAt":"2026-09-03T08:46:25.038Z","provenance":{"host":"claude","hostContractRevision":"2.1.250","nativeEvent":"SessionStart","source":"native"},"sequence":1},"native":{"session_id":"a7f96472-e9d0-447a-826d-36da9b635fd6","transcript_path":"/tmp/host-test/claude-home/.claude/projects/-tmp-host-test-claude-workspace/a7f96472-e9d0-447a-826d-36da9b635fd6.jsonl","cwd":"/tmp/host-test/claude-workspace","hook_event_name":"SessionStart","source":"startup"}},"host":"claude","kind":"event","process":{"cwd":"/tmp/host-test/claude-workspace","entry":"/fast/projects/agent-bundle-worktrees/host-test/examples/host-test/artifact/claude/hooks/hooks-flight.mjs","pid":1071607,"ppid":1071604},"recordedAt":"2026-09-03T08:46:25.335Z","request":{"host":{"source":"native","state":"available","value":{"name":"claude"}},"invocation":{"kind":"event"},"session":{"source":"native","state":"available","value":{"sessionId":"a7f96472-e9d0-447a-826d-36da9b635fd6"}}},"runtime":"standalone-hook","sequence":1} -{"env":{"names":["AGENT_BUNDLE_PLUGIN_ROOT","ANTHROPIC_API_KEY","ANTHROPIC_BASE_URL","CLAUDE_CODE_DISABLE_NONESSENTIAL_TRAFFIC","CLAUDE_CODE_ENTRYPOINT","CLAUDE_CODE_MESSAGING_SOCKET","CLAUDE_CODE_MESSAGING_TOKEN","CLAUDE_CODE_SESSION_ID","CLAUDE_CONFIG_DIR","CLAUDE_PLUGIN_DATA","CLAUDE_PLUGIN_ROOT","CLAUDE_PROJECT_DIR","CURSOR_LAYOUT","CURSOR_RIPGREP_PATH","HOST_TEST_LOG_DIR"]},"event":{"canonical":{"event":"prompt/submit","idempotencyKey":"6a543826745d8f8d895629ee58ce83120a3743ab9fc4d3a5e4f90df2aeaef301","observedAt":"2026-09-03T08:46:25.692Z","provenance":{"host":"claude","hostContractRevision":"2.1.250","nativeEvent":"UserPromptSubmit","source":"native"},"sequence":1},"native":{"session_id":"a7f96472-e9d0-447a-826d-36da9b635fd6","transcript_path":"/tmp/host-test/claude-home/.claude/projects/-tmp-host-test-claude-workspace/a7f96472-e9d0-447a-826d-36da9b635fd6.jsonl","cwd":"/tmp/host-test/claude-workspace","prompt_id":"96a54da1-f00b-48ec-8f84-2d42b7de5ba4","permission_mode":"bypassPermissions","hook_event_name":"UserPromptSubmit","prompt":"You are exercising the host-test probe plugin. Do the scripted steps."}},"host":"claude","kind":"event","process":{"cwd":"/tmp/host-test/claude-workspace","entry":"/fast/projects/agent-bundle-worktrees/host-test/examples/host-test/artifact/claude/mcp/mcp-host-test-0d229f1b-flight.mjs","pid":1071574,"ppid":1070791},"recordedAt":"2026-09-03T08:46:25.812Z","request":{"host":{"source":"native","state":"available","value":{"name":"claude"}},"invocation":{"kind":"event"},"session":{"source":"native","state":"available","value":{"sessionId":"a7f96472-e9d0-447a-826d-36da9b635fd6"}}},"runtime":"shared-runtime","sequence":1} -{"event":{"canonical":{"event":"tool/before","idempotencyKey":"23cc59242ee35ff4ba59bf05a19d3062910dc4fd2772964359bf86f83032d1c8","observedAt":"2026-09-03T08:46:26.088Z","provenance":{"host":"claude","hostContractRevision":"2.1.250","nativeEvent":"PreToolUse","source":"native"},"sequence":2},"native":{"session_id":"a7f96472-e9d0-447a-826d-36da9b635fd6","transcript_path":"/tmp/host-test/claude-home/.claude/projects/-tmp-host-test-claude-workspace/a7f96472-e9d0-447a-826d-36da9b635fd6.jsonl","cwd":"/tmp/host-test/claude-workspace","prompt_id":"96a54da1-f00b-48ec-8f84-2d42b7de5ba4","permission_mode":"bypassPermissions","hook_event_name":"PreToolUse","tool_name":"Bash","tool_input":{"command":"pwd"},"tool_use_id":"toolu_mock_1"}},"host":"claude","kind":"event","process":{"cwd":"/tmp/host-test/claude-workspace","entry":"/fast/projects/agent-bundle-worktrees/host-test/examples/host-test/artifact/claude/mcp/mcp-host-test-0d229f1b-flight.mjs","pid":1071574,"ppid":1070791},"recordedAt":"2026-09-03T08:46:26.092Z","request":{"host":{"source":"native","state":"available","value":{"name":"claude"}},"invocation":{"kind":"event"},"session":{"source":"native","state":"available","value":{"sessionId":"a7f96472-e9d0-447a-826d-36da9b635fd6"}}},"runtime":"shared-runtime","sequence":2} -{"event":{"canonical":{"event":"tool/after","idempotencyKey":"dbfae77c05cf08fd90c148fd2df0edf056afe6d025f02f98a0bb9e5e6299e453","observedAt":"2026-09-03T08:46:26.287Z","provenance":{"host":"claude","hostContractRevision":"2.1.250","nativeEvent":"PostToolUse","source":"native"},"sequence":3},"native":{"session_id":"a7f96472-e9d0-447a-826d-36da9b635fd6","transcript_path":"/tmp/host-test/claude-home/.claude/projects/-tmp-host-test-claude-workspace/a7f96472-e9d0-447a-826d-36da9b635fd6.jsonl","cwd":"/tmp/host-test/claude-workspace","prompt_id":"96a54da1-f00b-48ec-8f84-2d42b7de5ba4","permission_mode":"bypassPermissions","hook_event_name":"PostToolUse","tool_name":"Bash","tool_input":{"command":"pwd"},"tool_response":{"stdout":"/tmp/host-test/claude-workspace","stderr":"","interrupted":false,"isImage":false,"noOutputExpected":false},"tool_use_id":"toolu_mock_1","duration_ms":44}},"host":"claude","kind":"event","process":{"cwd":"/tmp/host-test/claude-workspace","entry":"/fast/projects/agent-bundle-worktrees/host-test/examples/host-test/artifact/claude/mcp/mcp-host-test-0d229f1b-flight.mjs","pid":1071574,"ppid":1070791},"recordedAt":"2026-09-03T08:46:26.291Z","request":{"host":{"source":"native","state":"available","value":{"name":"claude"}},"invocation":{"kind":"event"},"session":{"source":"native","state":"available","value":{"sessionId":"a7f96472-e9d0-447a-826d-36da9b635fd6"}}},"runtime":"shared-runtime","sequence":3} -{"event":{"canonical":{"event":"tool/before","idempotencyKey":"5fddde8ce837cf8b65f20224dcd9ad6d91f1f3c9e443876962451ffe3d98377b","observedAt":"2026-09-03T08:46:26.500Z","provenance":{"host":"claude","hostContractRevision":"2.1.250","nativeEvent":"PreToolUse","source":"native"},"sequence":4},"native":{"session_id":"a7f96472-e9d0-447a-826d-36da9b635fd6","transcript_path":"/tmp/host-test/claude-home/.claude/projects/-tmp-host-test-claude-workspace/a7f96472-e9d0-447a-826d-36da9b635fd6.jsonl","cwd":"/tmp/host-test/claude-workspace","prompt_id":"96a54da1-f00b-48ec-8f84-2d42b7de5ba4","permission_mode":"bypassPermissions","hook_event_name":"PreToolUse","tool_name":"mcp__plugin_host-test_host-test__dump","tool_input":{},"tool_use_id":"toolu_mock_3"}},"host":"claude","kind":"event","process":{"cwd":"/tmp/host-test/claude-workspace","entry":"/fast/projects/agent-bundle-worktrees/host-test/examples/host-test/artifact/claude/mcp/mcp-host-test-0d229f1b-flight.mjs","pid":1071574,"ppid":1070791},"recordedAt":"2026-09-03T08:46:26.505Z","request":{"host":{"source":"native","state":"available","value":{"name":"claude"}},"invocation":{"kind":"event"},"session":{"source":"native","state":"available","value":{"sessionId":"a7f96472-e9d0-447a-826d-36da9b635fd6"}}},"runtime":"shared-runtime","sequence":4} -{"env":{"names":["AGENT_BUNDLE_PLUGIN_ROOT","ANTHROPIC_API_KEY","ANTHROPIC_BASE_URL","CLAUDE_CODE_DISABLE_NONESSENTIAL_TRAFFIC","CLAUDE_CODE_ENTRYPOINT","CLAUDE_CODE_MESSAGING_SOCKET","CLAUDE_CODE_MESSAGING_TOKEN","CLAUDE_CODE_SESSION_ID","CLAUDE_CONFIG_DIR","CLAUDE_PLUGIN_DATA","CLAUDE_PLUGIN_ROOT","CLAUDE_PROJECT_DIR","CURSOR_LAYOUT","CURSOR_RIPGREP_PATH","HOST_TEST_LOG_DIR"]},"host":"claude-code","kind":"mcp","observed":{"tool":"dump"},"process":{"cwd":"/tmp/host-test/claude-workspace","entry":"/fast/projects/agent-bundle-worktrees/host-test/examples/host-test/artifact/claude/mcp/mcp-host-test-0d229f1b-flight.mjs","pid":1071574,"ppid":1070791},"recordedAt":"2026-09-03T08:46:26.550Z","request":{"host":{"source":"native","state":"available","value":{"name":"claude-code"}},"invocation":{"kind":"tool"},"session":{"reason":"not-provided","state":"unavailable"}},"runtime":"mcp-server","sequence":5} -{"event":{"canonical":{"event":"tool/before","idempotencyKey":"2a6c24cf4256e6b4c50e129b8bac8b99029c57aa8b5c95c2d02c7ac6aa854010","observedAt":"2026-09-03T08:46:26.844Z","provenance":{"host":"claude","hostContractRevision":"2.1.250","nativeEvent":"PreToolUse","source":"native"},"sequence":5},"native":{"session_id":"a7f96472-e9d0-447a-826d-36da9b635fd6","transcript_path":"/tmp/host-test/claude-home/.claude/projects/-tmp-host-test-claude-workspace/a7f96472-e9d0-447a-826d-36da9b635fd6.jsonl","cwd":"/tmp/host-test/claude-workspace","prompt_id":"96a54da1-f00b-48ec-8f84-2d42b7de5ba4","permission_mode":"bypassPermissions","hook_event_name":"PreToolUse","tool_name":"mcp__plugin_host-test_host-test-raw__probe","tool_input":{"note":"root"},"tool_use_id":"toolu_mock_4"}},"host":"claude","kind":"event","process":{"cwd":"/tmp/host-test/claude-workspace","entry":"/fast/projects/agent-bundle-worktrees/host-test/examples/host-test/artifact/claude/mcp/mcp-host-test-0d229f1b-flight.mjs","pid":1071574,"ppid":1070791},"recordedAt":"2026-09-03T08:46:26.847Z","request":{"host":{"source":"native","state":"available","value":{"name":"claude"}},"invocation":{"kind":"event"},"session":{"source":"native","state":"available","value":{"sessionId":"a7f96472-e9d0-447a-826d-36da9b635fd6"}}},"runtime":"shared-runtime","sequence":6} -{"host":"claude-code","kind":"mcp","observed":{"client":{"name":"claude-code","title":"Claude Code","version":"2.1.257","websiteUrl":"https://claude.com/claude-code","description":"Anthropic's agentic coding tool"},"clientCapabilities":{"elicitation":{"form":{}},"roots":{"listChanged":true}},"env":{"names":["AGENT_BUNDLE_PLUGIN_ROOT","ANTHROPIC_API_KEY","ANTHROPIC_BASE_URL","CLAUDE_CODE_DISABLE_NONESSENTIAL_TRAFFIC","CLAUDE_CODE_ENTRYPOINT","CLAUDE_CODE_MESSAGING_SOCKET","CLAUDE_CODE_MESSAGING_TOKEN","CLAUDE_CODE_SESSION_ID","CLAUDE_CONFIG_DIR","CLAUDE_PLUGIN_DATA","CLAUDE_PLUGIN_ROOT","CLAUDE_PROJECT_DIR","CURSOR_LAYOUT","CURSOR_RIPGREP_PATH","HOST_TEST_LOG_DIR"]},"http":null,"mcpReq":{"_meta":{"progressToken":2,"claudecode/toolUseId":"toolu_mock_4"},"envelope":null,"id":2,"method":"tools/call"},"note":"root","sessionId":null,"tool":"probe"},"process":{"cwd":"/tmp/host-test/claude-workspace","entry":"/fast/projects/agent-bundle-worktrees/host-test/examples/host-test/artifact/claude/mcp/mcp-host-test-raw-6e9c1a1c.mjs","pid":1071578,"ppid":1070791},"recordedAt":"2026-09-03T08:46:26.907Z","request":{"unavailable":"hand-rolled stdio server: no framework request context is mounted"},"runtime":"mcp-server","sequence":1} -{"event":{"canonical":{"event":"tool/before","idempotencyKey":"dfde620d7b0b5f4fb21ffc6b77c5f81e88e4ce640974b3bfe51e35329b44adbd","observedAt":"2026-09-03T08:46:27.178Z","provenance":{"host":"claude","hostContractRevision":"2.1.250","nativeEvent":"PreToolUse","source":"native"},"sequence":6},"native":{"session_id":"a7f96472-e9d0-447a-826d-36da9b635fd6","transcript_path":"/tmp/host-test/claude-home/.claude/projects/-tmp-host-test-claude-workspace/a7f96472-e9d0-447a-826d-36da9b635fd6.jsonl","cwd":"/tmp/host-test/claude-workspace","prompt_id":"96a54da1-f00b-48ec-8f84-2d42b7de5ba4","permission_mode":"bypassPermissions","hook_event_name":"PreToolUse","tool_name":"Agent","tool_input":{"description":"host-test subagent probe","prompt":"SUBAGENT_PROBE_SCENARIO: run `pwd`, call the host-test dump tool with {}, call the host-test-raw probe tool with {\"note\":\"subagent\"}, spawn a nested subagent with NESTED_PROBE_SCENARIO if you can, then reply with every id you saw.","subagent_type":"general-purpose"},"tool_use_id":"toolu_mock_5"}},"host":"claude","kind":"event","process":{"cwd":"/tmp/host-test/claude-workspace","entry":"/fast/projects/agent-bundle-worktrees/host-test/examples/host-test/artifact/claude/mcp/mcp-host-test-0d229f1b-flight.mjs","pid":1071574,"ppid":1070791},"recordedAt":"2026-09-03T08:46:27.181Z","request":{"host":{"source":"native","state":"available","value":{"name":"claude"}},"invocation":{"kind":"event"},"session":{"source":"native","state":"available","value":{"sessionId":"a7f96472-e9d0-447a-826d-36da9b635fd6"}}},"runtime":"shared-runtime","sequence":7} -{"event":{"canonical":{"event":"agent/start","idempotencyKey":"ee006cf40eea65021f16e43dd99593bf98cfadd82fe8bba4541f4744f7a336b1","observedAt":"2026-09-03T08:46:27.329Z","provenance":{"host":"claude","hostContractRevision":"2.1.250","nativeEvent":"SubagentStart","source":"native"},"sequence":7},"native":{"session_id":"a7f96472-e9d0-447a-826d-36da9b635fd6","transcript_path":"/tmp/host-test/claude-home/.claude/projects/-tmp-host-test-claude-workspace/a7f96472-e9d0-447a-826d-36da9b635fd6.jsonl","cwd":"/tmp/host-test/claude-workspace","prompt_id":"96a54da1-f00b-48ec-8f84-2d42b7de5ba4","agent_id":"aca96ce761c9f0cea","agent_type":"general-purpose","hook_event_name":"SubagentStart"}},"host":"claude","kind":"event","process":{"cwd":"/tmp/host-test/claude-workspace","entry":"/fast/projects/agent-bundle-worktrees/host-test/examples/host-test/artifact/claude/mcp/mcp-host-test-0d229f1b-flight.mjs","pid":1071574,"ppid":1070791},"recordedAt":"2026-09-03T08:46:27.332Z","request":{"host":{"source":"native","state":"available","value":{"name":"claude"}},"invocation":{"kind":"event"},"session":{"source":"native","state":"available","value":{"sessionId":"a7f96472-e9d0-447a-826d-36da9b635fd6"}}},"runtime":"shared-runtime","sequence":8} -{"event":{"canonical":{"event":"tool/after","idempotencyKey":"d5fcba55ede859c8e4faf7cd25d29463d09ba0db5ec11a077d4d70f78f6a1564","observedAt":"2026-09-03T08:46:27.332Z","provenance":{"host":"claude","hostContractRevision":"2.1.250","nativeEvent":"PostToolUse","source":"native"},"sequence":8},"native":{"session_id":"a7f96472-e9d0-447a-826d-36da9b635fd6","transcript_path":"/tmp/host-test/claude-home/.claude/projects/-tmp-host-test-claude-workspace/a7f96472-e9d0-447a-826d-36da9b635fd6.jsonl","cwd":"/tmp/host-test/claude-workspace","prompt_id":"96a54da1-f00b-48ec-8f84-2d42b7de5ba4","permission_mode":"bypassPermissions","hook_event_name":"PostToolUse","tool_name":"Agent","tool_input":{"description":"host-test subagent probe","prompt":"SUBAGENT_PROBE_SCENARIO: run `pwd`, call the host-test dump tool with {}, call the host-test-raw probe tool with {\"note\":\"subagent\"}, spawn a nested subagent with NESTED_PROBE_SCENARIO if you can, then reply with every id you saw.","subagent_type":"general-purpose"},"tool_response":{"isAsync":true,"status":"async_launched","agentId":"aca96ce761c9f0cea","description":"host-test subagent probe","resolvedModel":"claude-sonnet-4-5","prompt":"SUBAGENT_PROBE_SCENARIO: run `pwd`, call the host-test dump tool with {}, call the host-test-raw probe tool with {\"note\":\"subagent\"}, spawn a nested subagent with NESTED_PROBE_SCENARIO if you can, then reply with every id you saw.","outputFile":"/tmp/claude-1000/-tmp-host-test-claude-workspace/a7f96472-e9d0-447a-826d-36da9b635fd6/tasks/aca96ce761c9f0cea.output","canReadOutputFile":true},"tool_use_id":"toolu_mock_5","duration_ms":6}},"host":"claude","kind":"event","process":{"cwd":"/tmp/host-test/claude-workspace","entry":"/fast/projects/agent-bundle-worktrees/host-test/examples/host-test/artifact/claude/mcp/mcp-host-test-0d229f1b-flight.mjs","pid":1071574,"ppid":1070791},"recordedAt":"2026-09-03T08:46:27.341Z","request":{"host":{"source":"native","state":"available","value":{"name":"claude"}},"invocation":{"kind":"event"},"session":{"source":"native","state":"available","value":{"sessionId":"a7f96472-e9d0-447a-826d-36da9b635fd6"}}},"runtime":"shared-runtime","sequence":9} -{"event":{"canonical":{"event":"tool/before","idempotencyKey":"76416c00a86fa4a487fec1d2516ef9bddc797039588f643fd94d54bfb1017e7c","observedAt":"2026-09-03T08:46:27.486Z","provenance":{"host":"claude","hostContractRevision":"2.1.250","nativeEvent":"PreToolUse","source":"native"},"sequence":9},"native":{"session_id":"a7f96472-e9d0-447a-826d-36da9b635fd6","transcript_path":"/tmp/host-test/claude-home/.claude/projects/-tmp-host-test-claude-workspace/a7f96472-e9d0-447a-826d-36da9b635fd6.jsonl","cwd":"/tmp/host-test/claude-workspace","prompt_id":"96a54da1-f00b-48ec-8f84-2d42b7de5ba4","permission_mode":"bypassPermissions","agent_id":"aca96ce761c9f0cea","agent_type":"general-purpose","hook_event_name":"PreToolUse","tool_name":"Bash","tool_input":{"command":"pwd"},"tool_use_id":"toolu_mock_6"}},"host":"claude","kind":"event","process":{"cwd":"/tmp/host-test/claude-workspace","entry":"/fast/projects/agent-bundle-worktrees/host-test/examples/host-test/artifact/claude/mcp/mcp-host-test-0d229f1b-flight.mjs","pid":1071574,"ppid":1070791},"recordedAt":"2026-09-03T08:46:27.490Z","request":{"host":{"source":"native","state":"available","value":{"name":"claude"}},"invocation":{"kind":"event"},"session":{"source":"native","state":"available","value":{"sessionId":"a7f96472-e9d0-447a-826d-36da9b635fd6"}}},"runtime":"shared-runtime","sequence":10} -{"event":{"canonical":{"event":"stop","idempotencyKey":"8dd460ae51c860cf76425007c4b3f3ed6bd4ea1b7f84af6ddf42b0e0ac35899f","observedAt":"2026-09-03T08:46:27.518Z","provenance":{"host":"claude","hostContractRevision":"2.1.250","nativeEvent":"Stop","source":"native"},"sequence":10},"native":{"session_id":"a7f96472-e9d0-447a-826d-36da9b635fd6","transcript_path":"/tmp/host-test/claude-home/.claude/projects/-tmp-host-test-claude-workspace/a7f96472-e9d0-447a-826d-36da9b635fd6.jsonl","cwd":"/tmp/host-test/claude-workspace","prompt_id":"96a54da1-f00b-48ec-8f84-2d42b7de5ba4","permission_mode":"bypassPermissions","hook_event_name":"Stop","stop_hook_active":false,"last_assistant_message":"HOST_TEST_DONE (mock model; see the probe log path in the dump result)","background_tasks":[{"id":"aca96ce761c9f0cea","type":"subagent","status":"running","description":"host-test subagent probe","agent_type":"general-purpose"}],"session_crons":[]}},"host":"claude","kind":"event","process":{"cwd":"/tmp/host-test/claude-workspace","entry":"/fast/projects/agent-bundle-worktrees/host-test/examples/host-test/artifact/claude/mcp/mcp-host-test-0d229f1b-flight.mjs","pid":1071574,"ppid":1070791},"recordedAt":"2026-09-03T08:46:27.521Z","request":{"host":{"source":"native","state":"available","value":{"name":"claude"}},"invocation":{"kind":"event"},"session":{"source":"native","state":"available","value":{"sessionId":"a7f96472-e9d0-447a-826d-36da9b635fd6"}}},"runtime":"shared-runtime","sequence":11} -{"event":{"canonical":{"event":"tool/after","idempotencyKey":"4b30dc62393cfe0536c9c79ca6c20189b1e4468148596b1e43634eca14f9a1f5","observedAt":"2026-09-03T08:46:27.640Z","provenance":{"host":"claude","hostContractRevision":"2.1.250","nativeEvent":"PostToolUse","source":"native"},"sequence":11},"native":{"session_id":"a7f96472-e9d0-447a-826d-36da9b635fd6","transcript_path":"/tmp/host-test/claude-home/.claude/projects/-tmp-host-test-claude-workspace/a7f96472-e9d0-447a-826d-36da9b635fd6.jsonl","cwd":"/tmp/host-test/claude-workspace","prompt_id":"96a54da1-f00b-48ec-8f84-2d42b7de5ba4","permission_mode":"bypassPermissions","agent_id":"aca96ce761c9f0cea","agent_type":"general-purpose","hook_event_name":"PostToolUse","tool_name":"Bash","tool_input":{"command":"pwd"},"tool_response":{"stdout":"/tmp/host-test/claude-workspace","stderr":"","interrupted":false,"isImage":false,"noOutputExpected":false},"tool_use_id":"toolu_mock_6","duration_ms":9}},"host":"claude","kind":"event","process":{"cwd":"/tmp/host-test/claude-workspace","entry":"/fast/projects/agent-bundle-worktrees/host-test/examples/host-test/artifact/claude/mcp/mcp-host-test-0d229f1b-flight.mjs","pid":1071574,"ppid":1070791},"recordedAt":"2026-09-03T08:46:27.642Z","request":{"host":{"source":"native","state":"available","value":{"name":"claude"}},"invocation":{"kind":"event"},"session":{"source":"native","state":"available","value":{"sessionId":"a7f96472-e9d0-447a-826d-36da9b635fd6"}}},"runtime":"shared-runtime","sequence":12} -{"event":{"canonical":{"event":"tool/before","idempotencyKey":"e6dbd3cbdabf0763b0dbe7c22866ff412d0ea7d52b1aaed1385296d39c6d2008","observedAt":"2026-09-03T08:46:27.789Z","provenance":{"host":"claude","hostContractRevision":"2.1.250","nativeEvent":"PreToolUse","source":"native"},"sequence":12},"native":{"session_id":"a7f96472-e9d0-447a-826d-36da9b635fd6","transcript_path":"/tmp/host-test/claude-home/.claude/projects/-tmp-host-test-claude-workspace/a7f96472-e9d0-447a-826d-36da9b635fd6.jsonl","cwd":"/tmp/host-test/claude-workspace","prompt_id":"96a54da1-f00b-48ec-8f84-2d42b7de5ba4","permission_mode":"bypassPermissions","agent_id":"aca96ce761c9f0cea","agent_type":"general-purpose","hook_event_name":"PreToolUse","tool_name":"mcp__plugin_host-test_host-test__dump","tool_input":{},"tool_use_id":"toolu_mock_8"}},"host":"claude","kind":"event","process":{"cwd":"/tmp/host-test/claude-workspace","entry":"/fast/projects/agent-bundle-worktrees/host-test/examples/host-test/artifact/claude/mcp/mcp-host-test-0d229f1b-flight.mjs","pid":1071574,"ppid":1070791},"recordedAt":"2026-09-03T08:46:27.793Z","request":{"host":{"source":"native","state":"available","value":{"name":"claude"}},"invocation":{"kind":"event"},"session":{"source":"native","state":"available","value":{"sessionId":"a7f96472-e9d0-447a-826d-36da9b635fd6"}}},"runtime":"shared-runtime","sequence":13} -{"host":"claude-code","kind":"mcp","observed":{"tool":"dump"},"process":{"cwd":"/tmp/host-test/claude-workspace","entry":"/fast/projects/agent-bundle-worktrees/host-test/examples/host-test/artifact/claude/mcp/mcp-host-test-0d229f1b-flight.mjs","pid":1071574,"ppid":1070791},"recordedAt":"2026-09-03T08:46:27.819Z","request":{"host":{"source":"native","state":"available","value":{"name":"claude-code"}},"invocation":{"kind":"tool"},"session":{"reason":"not-provided","state":"unavailable"}},"runtime":"mcp-server","sequence":14} -{"event":{"canonical":{"event":"tool/before","idempotencyKey":"b89ae7e6791d0446bf77685ae1eb1ef14b75d9dfb75f3cd9b511ce2429fc448e","observedAt":"2026-09-03T08:46:28.095Z","provenance":{"host":"claude","hostContractRevision":"2.1.250","nativeEvent":"PreToolUse","source":"native"},"sequence":13},"native":{"session_id":"a7f96472-e9d0-447a-826d-36da9b635fd6","transcript_path":"/tmp/host-test/claude-home/.claude/projects/-tmp-host-test-claude-workspace/a7f96472-e9d0-447a-826d-36da9b635fd6.jsonl","cwd":"/tmp/host-test/claude-workspace","prompt_id":"96a54da1-f00b-48ec-8f84-2d42b7de5ba4","permission_mode":"bypassPermissions","agent_id":"aca96ce761c9f0cea","agent_type":"general-purpose","hook_event_name":"PreToolUse","tool_name":"mcp__plugin_host-test_host-test-raw__probe","tool_input":{"note":"subagent"},"tool_use_id":"toolu_mock_9"}},"host":"claude","kind":"event","process":{"cwd":"/tmp/host-test/claude-workspace","entry":"/fast/projects/agent-bundle-worktrees/host-test/examples/host-test/artifact/claude/mcp/mcp-host-test-0d229f1b-flight.mjs","pid":1071574,"ppid":1070791},"recordedAt":"2026-09-03T08:46:28.098Z","request":{"host":{"source":"native","state":"available","value":{"name":"claude"}},"invocation":{"kind":"event"},"session":{"source":"native","state":"available","value":{"sessionId":"a7f96472-e9d0-447a-826d-36da9b635fd6"}}},"runtime":"shared-runtime","sequence":15} -{"host":"claude-code","kind":"mcp","observed":{"client":{"name":"claude-code","title":"Claude Code","version":"2.1.257","websiteUrl":"https://claude.com/claude-code","description":"Anthropic's agentic coding tool"},"clientCapabilities":{"elicitation":{"form":{}},"roots":{"listChanged":true}},"env":{"names":["AGENT_BUNDLE_PLUGIN_ROOT","ANTHROPIC_API_KEY","ANTHROPIC_BASE_URL","CLAUDE_CODE_DISABLE_NONESSENTIAL_TRAFFIC","CLAUDE_CODE_ENTRYPOINT","CLAUDE_CODE_MESSAGING_SOCKET","CLAUDE_CODE_MESSAGING_TOKEN","CLAUDE_CODE_SESSION_ID","CLAUDE_CONFIG_DIR","CLAUDE_PLUGIN_DATA","CLAUDE_PLUGIN_ROOT","CLAUDE_PROJECT_DIR","CURSOR_LAYOUT","CURSOR_RIPGREP_PATH","HOST_TEST_LOG_DIR"]},"http":null,"mcpReq":{"_meta":{"progressToken":3,"claudecode/toolUseId":"toolu_mock_9"},"envelope":null,"id":3,"method":"tools/call"},"note":"subagent","sessionId":null,"tool":"probe"},"process":{"cwd":"/tmp/host-test/claude-workspace","entry":"/fast/projects/agent-bundle-worktrees/host-test/examples/host-test/artifact/claude/mcp/mcp-host-test-raw-6e9c1a1c.mjs","pid":1071578,"ppid":1070791},"recordedAt":"2026-09-03T08:46:28.122Z","request":{"unavailable":"hand-rolled stdio server: no framework request context is mounted"},"runtime":"mcp-server","sequence":2} -{"event":{"canonical":{"event":"tool/before","idempotencyKey":"d42e7d6cf785b6d2b166b238f508f86a0daeea2bafd16719663ddf9579e231d9","observedAt":"2026-09-03T08:46:28.378Z","provenance":{"host":"claude","hostContractRevision":"2.1.250","nativeEvent":"PreToolUse","source":"native"},"sequence":14},"native":{"session_id":"a7f96472-e9d0-447a-826d-36da9b635fd6","transcript_path":"/tmp/host-test/claude-home/.claude/projects/-tmp-host-test-claude-workspace/a7f96472-e9d0-447a-826d-36da9b635fd6.jsonl","cwd":"/tmp/host-test/claude-workspace","prompt_id":"96a54da1-f00b-48ec-8f84-2d42b7de5ba4","permission_mode":"bypassPermissions","agent_id":"aca96ce761c9f0cea","agent_type":"general-purpose","hook_event_name":"PreToolUse","tool_name":"Agent","tool_input":{"description":"nested host-test probe","prompt":"NESTED_PROBE_SCENARIO: run `pwd`, call the host-test-raw probe tool with {\"note\":\"nested\"}, then reply with every id you saw.","subagent_type":"general-purpose"},"tool_use_id":"toolu_mock_10"}},"host":"claude","kind":"event","process":{"cwd":"/tmp/host-test/claude-workspace","entry":"/fast/projects/agent-bundle-worktrees/host-test/examples/host-test/artifact/claude/mcp/mcp-host-test-0d229f1b-flight.mjs","pid":1071574,"ppid":1070791},"recordedAt":"2026-09-03T08:46:28.380Z","request":{"host":{"source":"native","state":"available","value":{"name":"claude"}},"invocation":{"kind":"event"},"session":{"source":"native","state":"available","value":{"sessionId":"a7f96472-e9d0-447a-826d-36da9b635fd6"}}},"runtime":"shared-runtime","sequence":16} -{"event":{"canonical":{"event":"agent/start","idempotencyKey":"a58f839282b1768d4fd02a033c4aafa95bdef02aa86416a2a768f3a6bd81598b","observedAt":"2026-09-03T08:46:28.601Z","provenance":{"host":"claude","hostContractRevision":"2.1.250","nativeEvent":"SubagentStart","source":"native"},"sequence":15},"native":{"session_id":"a7f96472-e9d0-447a-826d-36da9b635fd6","transcript_path":"/tmp/host-test/claude-home/.claude/projects/-tmp-host-test-claude-workspace/a7f96472-e9d0-447a-826d-36da9b635fd6.jsonl","cwd":"/tmp/host-test/claude-workspace","prompt_id":"96a54da1-f00b-48ec-8f84-2d42b7de5ba4","agent_id":"ac093bdad0566ffa7","agent_type":"general-purpose","hook_event_name":"SubagentStart"}},"host":"claude","kind":"event","process":{"cwd":"/tmp/host-test/claude-workspace","entry":"/fast/projects/agent-bundle-worktrees/host-test/examples/host-test/artifact/claude/mcp/mcp-host-test-0d229f1b-flight.mjs","pid":1071574,"ppid":1070791},"recordedAt":"2026-09-03T08:46:28.603Z","request":{"host":{"source":"native","state":"available","value":{"name":"claude"}},"invocation":{"kind":"event"},"session":{"source":"native","state":"available","value":{"sessionId":"a7f96472-e9d0-447a-826d-36da9b635fd6"}}},"runtime":"shared-runtime","sequence":17} -{"event":{"canonical":{"event":"tool/after","idempotencyKey":"4429acdf4b3d6caa7d6cda951a6c558fa46a87bda4812fa269fb31b0471281b2","observedAt":"2026-09-03T08:46:28.603Z","provenance":{"host":"claude","hostContractRevision":"2.1.250","nativeEvent":"PostToolUse","source":"native"},"sequence":16},"native":{"session_id":"a7f96472-e9d0-447a-826d-36da9b635fd6","transcript_path":"/tmp/host-test/claude-home/.claude/projects/-tmp-host-test-claude-workspace/a7f96472-e9d0-447a-826d-36da9b635fd6.jsonl","cwd":"/tmp/host-test/claude-workspace","prompt_id":"96a54da1-f00b-48ec-8f84-2d42b7de5ba4","permission_mode":"bypassPermissions","agent_id":"aca96ce761c9f0cea","agent_type":"general-purpose","hook_event_name":"PostToolUse","tool_name":"Agent","tool_input":{"description":"nested host-test probe","prompt":"NESTED_PROBE_SCENARIO: run `pwd`, call the host-test-raw probe tool with {\"note\":\"nested\"}, then reply with every id you saw.","subagent_type":"general-purpose"},"tool_response":{"isAsync":true,"status":"async_launched","agentId":"ac093bdad0566ffa7","description":"nested host-test probe","resolvedModel":"claude-sonnet-4-5","prompt":"NESTED_PROBE_SCENARIO: run `pwd`, call the host-test-raw probe tool with {\"note\":\"nested\"}, then reply with every id you saw.","outputFile":"/tmp/claude-1000/-tmp-host-test-claude-workspace/a7f96472-e9d0-447a-826d-36da9b635fd6/tasks/ac093bdad0566ffa7.output","canReadOutputFile":true},"tool_use_id":"toolu_mock_10","duration_ms":4}},"host":"claude","kind":"event","process":{"cwd":"/tmp/host-test/claude-workspace","entry":"/fast/projects/agent-bundle-worktrees/host-test/examples/host-test/artifact/claude/mcp/mcp-host-test-0d229f1b-flight.mjs","pid":1071574,"ppid":1070791},"recordedAt":"2026-09-03T08:46:28.609Z","request":{"host":{"source":"native","state":"available","value":{"name":"claude"}},"invocation":{"kind":"event"},"session":{"source":"native","state":"available","value":{"sessionId":"a7f96472-e9d0-447a-826d-36da9b635fd6"}}},"runtime":"shared-runtime","sequence":18} -{"event":{"canonical":{"event":"tool/before","idempotencyKey":"7e6771796a0e97521ff6865ae81095b436501d05e5225dddb37785e195c40826","observedAt":"2026-09-03T08:46:28.751Z","provenance":{"host":"claude","hostContractRevision":"2.1.250","nativeEvent":"PreToolUse","source":"native"},"sequence":17},"native":{"session_id":"a7f96472-e9d0-447a-826d-36da9b635fd6","transcript_path":"/tmp/host-test/claude-home/.claude/projects/-tmp-host-test-claude-workspace/a7f96472-e9d0-447a-826d-36da9b635fd6.jsonl","cwd":"/tmp/host-test/claude-workspace","prompt_id":"96a54da1-f00b-48ec-8f84-2d42b7de5ba4","permission_mode":"bypassPermissions","agent_id":"ac093bdad0566ffa7","agent_type":"general-purpose","hook_event_name":"PreToolUse","tool_name":"Bash","tool_input":{"command":"pwd"},"tool_use_id":"toolu_mock_11"}},"host":"claude","kind":"event","process":{"cwd":"/tmp/host-test/claude-workspace","entry":"/fast/projects/agent-bundle-worktrees/host-test/examples/host-test/artifact/claude/mcp/mcp-host-test-0d229f1b-flight.mjs","pid":1071574,"ppid":1070791},"recordedAt":"2026-09-03T08:46:28.754Z","request":{"host":{"source":"native","state":"available","value":{"name":"claude"}},"invocation":{"kind":"event"},"session":{"source":"native","state":"available","value":{"sessionId":"a7f96472-e9d0-447a-826d-36da9b635fd6"}}},"runtime":"shared-runtime","sequence":19} -{"event":{"canonical":{"event":"agent/stop","idempotencyKey":"d13abb15dd74eabfd06d1a3bbfe96c31f7c23ac66438fc9b058c723be37be1f2","observedAt":"2026-09-03T08:46:28.754Z","provenance":{"host":"claude","hostContractRevision":"2.1.250","nativeEvent":"SubagentStop","source":"native"},"sequence":18},"native":{"session_id":"a7f96472-e9d0-447a-826d-36da9b635fd6","transcript_path":"/tmp/host-test/claude-home/.claude/projects/-tmp-host-test-claude-workspace/a7f96472-e9d0-447a-826d-36da9b635fd6.jsonl","cwd":"/tmp/host-test/claude-workspace","prompt_id":"96a54da1-f00b-48ec-8f84-2d42b7de5ba4","permission_mode":"bypassPermissions","agent_id":"aca96ce761c9f0cea","agent_type":"general-purpose","hook_event_name":"SubagentStop","stop_hook_active":false,"agent_transcript_path":"/tmp/host-test/claude-home/.claude/projects/-tmp-host-test-claude-workspace/a7f96472-e9d0-447a-826d-36da9b635fd6/subagents/agent-aca96ce761c9f0cea.jsonl","last_assistant_message":"SUBAGENT_DONE: reported every id from the dump and probe results above.","background_tasks":[{"id":"aca96ce761c9f0cea","type":"subagent","status":"running","description":"host-test subagent probe","agent_type":"general-purpose"},{"id":"ac093bdad0566ffa7","type":"subagent","status":"running","description":"nested host-test probe","agent_type":"general-purpose"}],"session_crons":[]}},"host":"claude","kind":"event","process":{"cwd":"/tmp/host-test/claude-workspace","entry":"/fast/projects/agent-bundle-worktrees/host-test/examples/host-test/artifact/claude/mcp/mcp-host-test-0d229f1b-flight.mjs","pid":1071574,"ppid":1070791},"recordedAt":"2026-09-03T08:46:28.762Z","request":{"host":{"source":"native","state":"available","value":{"name":"claude"}},"invocation":{"kind":"event"},"session":{"source":"native","state":"available","value":{"sessionId":"a7f96472-e9d0-447a-826d-36da9b635fd6"}}},"runtime":"shared-runtime","sequence":20} -{"event":{"canonical":{"event":"tool/after","idempotencyKey":"8acc5096401f0230c9ee7fa9be2ad40dba88e379129c7d24a1c0e167eee08563","observedAt":"2026-09-03T08:46:28.897Z","provenance":{"host":"claude","hostContractRevision":"2.1.250","nativeEvent":"PostToolUse","source":"native"},"sequence":19},"native":{"session_id":"a7f96472-e9d0-447a-826d-36da9b635fd6","transcript_path":"/tmp/host-test/claude-home/.claude/projects/-tmp-host-test-claude-workspace/a7f96472-e9d0-447a-826d-36da9b635fd6.jsonl","cwd":"/tmp/host-test/claude-workspace","prompt_id":"96a54da1-f00b-48ec-8f84-2d42b7de5ba4","permission_mode":"bypassPermissions","agent_id":"ac093bdad0566ffa7","agent_type":"general-purpose","hook_event_name":"PostToolUse","tool_name":"Bash","tool_input":{"command":"pwd"},"tool_response":{"stdout":"/tmp/host-test/claude-workspace","stderr":"","interrupted":false,"isImage":false,"noOutputExpected":false},"tool_use_id":"toolu_mock_11","duration_ms":10}},"host":"claude","kind":"event","process":{"cwd":"/tmp/host-test/claude-workspace","entry":"/fast/projects/agent-bundle-worktrees/host-test/examples/host-test/artifact/claude/mcp/mcp-host-test-0d229f1b-flight.mjs","pid":1071574,"ppid":1070791},"recordedAt":"2026-09-03T08:46:28.900Z","request":{"host":{"source":"native","state":"available","value":{"name":"claude"}},"invocation":{"kind":"event"},"session":{"source":"native","state":"available","value":{"sessionId":"a7f96472-e9d0-447a-826d-36da9b635fd6"}}},"runtime":"shared-runtime","sequence":21} -{"event":{"canonical":{"event":"prompt/submit","idempotencyKey":"b8c53ebcf3362adb4a74b952d88628069738eb9e70bc256b92e72840a99acb69","observedAt":"2026-09-03T08:46:29.003Z","provenance":{"host":"claude","hostContractRevision":"2.1.250","nativeEvent":"UserPromptSubmit","source":"native"},"sequence":20},"native":{"session_id":"a7f96472-e9d0-447a-826d-36da9b635fd6","transcript_path":"/tmp/host-test/claude-home/.claude/projects/-tmp-host-test-claude-workspace/a7f96472-e9d0-447a-826d-36da9b635fd6.jsonl","cwd":"/tmp/host-test/claude-workspace","prompt_id":"41a8b30c-65cf-42a7-af74-644f5a5c1875","permission_mode":"bypassPermissions","hook_event_name":"UserPromptSubmit","prompt":"\naca96ce761c9f0cea\ntoolu_mock_5\n/tmp/claude-1000/-tmp-host-test-claude-workspace/a7f96472-e9d0-447a-826d-36da9b635fd6/task…[+556 chars]"}},"host":"claude","kind":"event","process":{"cwd":"/tmp/host-test/claude-workspace","entry":"/fast/projects/agent-bundle-worktrees/host-test/examples/host-test/artifact/claude/mcp/mcp-host-test-0d229f1b-flight.mjs","pid":1071574,"ppid":1070791},"recordedAt":"2026-09-03T08:46:29.006Z","request":{"host":{"source":"native","state":"available","value":{"name":"claude"}},"invocation":{"kind":"event"},"session":{"source":"native","state":"available","value":{"sessionId":"a7f96472-e9d0-447a-826d-36da9b635fd6"}}},"runtime":"shared-runtime","sequence":22} -{"event":{"canonical":{"event":"tool/before","idempotencyKey":"375d8bed0b8de73d6be37d79fb5ddabda26e9b0c6d4c6bc437c391521986201f","observedAt":"2026-09-03T08:46:29.038Z","provenance":{"host":"claude","hostContractRevision":"2.1.250","nativeEvent":"PreToolUse","source":"native"},"sequence":21},"native":{"session_id":"a7f96472-e9d0-447a-826d-36da9b635fd6","transcript_path":"/tmp/host-test/claude-home/.claude/projects/-tmp-host-test-claude-workspace/a7f96472-e9d0-447a-826d-36da9b635fd6.jsonl","cwd":"/tmp/host-test/claude-workspace","prompt_id":"41a8b30c-65cf-42a7-af74-644f5a5c1875","permission_mode":"bypassPermissions","agent_id":"ac093bdad0566ffa7","agent_type":"general-purpose","hook_event_name":"PreToolUse","tool_name":"mcp__plugin_host-test_host-test-raw__probe","tool_input":{"note":"nested"},"tool_use_id":"toolu_mock_13"}},"host":"claude","kind":"event","process":{"cwd":"/tmp/host-test/claude-workspace","entry":"/fast/projects/agent-bundle-worktrees/host-test/examples/host-test/artifact/claude/mcp/mcp-host-test-0d229f1b-flight.mjs","pid":1071574,"ppid":1070791},"recordedAt":"2026-09-03T08:46:29.041Z","request":{"host":{"source":"native","state":"available","value":{"name":"claude"}},"invocation":{"kind":"event"},"session":{"source":"native","state":"available","value":{"sessionId":"a7f96472-e9d0-447a-826d-36da9b635fd6"}}},"runtime":"shared-runtime","sequence":23} -{"host":"claude-code","kind":"mcp","observed":{"client":{"name":"claude-code","title":"Claude Code","version":"2.1.257","websiteUrl":"https://claude.com/claude-code","description":"Anthropic's agentic coding tool"},"clientCapabilities":{"elicitation":{"form":{}},"roots":{"listChanged":true}},"env":{"names":["AGENT_BUNDLE_PLUGIN_ROOT","ANTHROPIC_API_KEY","ANTHROPIC_BASE_URL","CLAUDE_CODE_DISABLE_NONESSENTIAL_TRAFFIC","CLAUDE_CODE_ENTRYPOINT","CLAUDE_CODE_MESSAGING_SOCKET","CLAUDE_CODE_MESSAGING_TOKEN","CLAUDE_CODE_SESSION_ID","CLAUDE_CONFIG_DIR","CLAUDE_PLUGIN_DATA","CLAUDE_PLUGIN_ROOT","CLAUDE_PROJECT_DIR","CURSOR_LAYOUT","CURSOR_RIPGREP_PATH","HOST_TEST_LOG_DIR"]},"http":null,"mcpReq":{"_meta":{"progressToken":4,"claudecode/toolUseId":"toolu_mock_13"},"envelope":null,"id":4,"method":"tools/call"},"note":"nested","sessionId":null,"tool":"probe"},"process":{"cwd":"/tmp/host-test/claude-workspace","entry":"/fast/projects/agent-bundle-worktrees/host-test/examples/host-test/artifact/claude/mcp/mcp-host-test-raw-6e9c1a1c.mjs","pid":1071578,"ppid":1070791},"recordedAt":"2026-09-03T08:46:29.062Z","request":{"unavailable":"hand-rolled stdio server: no framework request context is mounted"},"runtime":"mcp-server","sequence":3} -{"event":{"canonical":{"event":"stop","idempotencyKey":"c9ba472646faa329a496e87ffcaa2057f4e1a4ae7689a46895bb9be9e8d9e4db","observedAt":"2026-09-03T08:46:29.157Z","provenance":{"host":"claude","hostContractRevision":"2.1.250","nativeEvent":"Stop","source":"native"},"sequence":22},"native":{"session_id":"a7f96472-e9d0-447a-826d-36da9b635fd6","transcript_path":"/tmp/host-test/claude-home/.claude/projects/-tmp-host-test-claude-workspace/a7f96472-e9d0-447a-826d-36da9b635fd6.jsonl","cwd":"/tmp/host-test/claude-workspace","prompt_id":"41a8b30c-65cf-42a7-af74-644f5a5c1875","permission_mode":"bypassPermissions","hook_event_name":"Stop","stop_hook_active":false,"last_assistant_message":"HOST_TEST_DONE (mock model; see the probe log path in the dump result)","background_tasks":[{"id":"ac093bdad0566ffa7","type":"subagent","status":"running","description":"nested host-test probe","agent_type":"general-purpose"}],"session_crons":[]}},"host":"claude","kind":"event","process":{"cwd":"/tmp/host-test/claude-workspace","entry":"/fast/projects/agent-bundle-worktrees/host-test/examples/host-test/artifact/claude/mcp/mcp-host-test-0d229f1b-flight.mjs","pid":1071574,"ppid":1070791},"recordedAt":"2026-09-03T08:46:29.159Z","request":{"host":{"source":"native","state":"available","value":{"name":"claude"}},"invocation":{"kind":"event"},"session":{"source":"native","state":"available","value":{"sessionId":"a7f96472-e9d0-447a-826d-36da9b635fd6"}}},"runtime":"shared-runtime","sequence":24} -{"event":{"canonical":{"event":"agent/stop","idempotencyKey":"fc01173a176e10503e309d607a83e06dc251bb48edd046a552609913b3bc8180","observedAt":"2026-09-03T08:46:29.302Z","provenance":{"host":"claude","hostContractRevision":"2.1.250","nativeEvent":"SubagentStop","source":"native"},"sequence":23},"native":{"session_id":"a7f96472-e9d0-447a-826d-36da9b635fd6","transcript_path":"/tmp/host-test/claude-home/.claude/projects/-tmp-host-test-claude-workspace/a7f96472-e9d0-447a-826d-36da9b635fd6.jsonl","cwd":"/tmp/host-test/claude-workspace","prompt_id":"41a8b30c-65cf-42a7-af74-644f5a5c1875","permission_mode":"bypassPermissions","agent_id":"ac093bdad0566ffa7","agent_type":"general-purpose","hook_event_name":"SubagentStop","stop_hook_active":false,"agent_transcript_path":"/tmp/host-test/claude-home/.claude/projects/-tmp-host-test-claude-workspace/a7f96472-e9d0-447a-826d-36da9b635fd6/subagents/agent-ac093bdad0566ffa7.jsonl","last_assistant_message":"NESTED_DONE: reported every id from the probe result above.","background_tasks":[{"id":"ac093bdad0566ffa7","type":"subagent","status":"running","description":"nested host-test probe","agent_type":"general-purpose"}],"session_crons":[]}},"host":"claude","kind":"event","process":{"cwd":"/tmp/host-test/claude-workspace","entry":"/fast/projects/agent-bundle-worktrees/host-test/examples/host-test/artifact/claude/mcp/mcp-host-test-0d229f1b-flight.mjs","pid":1071574,"ppid":1070791},"recordedAt":"2026-09-03T08:46:29.304Z","request":{"host":{"source":"native","state":"available","value":{"name":"claude"}},"invocation":{"kind":"event"},"session":{"source":"native","state":"available","value":{"sessionId":"a7f96472-e9d0-447a-826d-36da9b635fd6"}}},"runtime":"shared-runtime","sequence":25} -{"event":{"canonical":{"event":"prompt/submit","idempotencyKey":"f7b0acdf94045a59e9813e57f616689894cc411b5d60b92913bcc5e8b188087f","observedAt":"2026-09-03T08:46:29.489Z","provenance":{"host":"claude","hostContractRevision":"2.1.250","nativeEvent":"UserPromptSubmit","source":"native"},"sequence":24},"native":{"session_id":"a7f96472-e9d0-447a-826d-36da9b635fd6","transcript_path":"/tmp/host-test/claude-home/.claude/projects/-tmp-host-test-claude-workspace/a7f96472-e9d0-447a-826d-36da9b635fd6.jsonl","cwd":"/tmp/host-test/claude-workspace","prompt_id":"88eaceb2-67ed-4bdb-abed-84a52891719d","permission_mode":"bypassPermissions","hook_event_name":"UserPromptSubmit","prompt":"\nac093bdad0566ffa7\ntoolu_mock_10\n/tmp/claude-1000/-tmp-host-test-claude-workspace/a7f96472-e9d0-447a-826d-36da9b635fd6/tas…[+542 chars]"}},"host":"claude","kind":"event","process":{"cwd":"/tmp/host-test/claude-workspace","entry":"/fast/projects/agent-bundle-worktrees/host-test/examples/host-test/artifact/claude/mcp/mcp-host-test-0d229f1b-flight.mjs","pid":1071574,"ppid":1070791},"recordedAt":"2026-09-03T08:46:29.492Z","request":{"host":{"source":"native","state":"available","value":{"name":"claude"}},"invocation":{"kind":"event"},"session":{"source":"native","state":"available","value":{"sessionId":"a7f96472-e9d0-447a-826d-36da9b635fd6"}}},"runtime":"shared-runtime","sequence":26} -{"event":{"canonical":{"event":"stop","idempotencyKey":"c673791c3035f1621082031cbfe63d1dc60236957efcbd7fcfe3690624949fdd","observedAt":"2026-09-03T08:46:29.638Z","provenance":{"host":"claude","hostContractRevision":"2.1.250","nativeEvent":"Stop","source":"native"},"sequence":25},"native":{"session_id":"a7f96472-e9d0-447a-826d-36da9b635fd6","transcript_path":"/tmp/host-test/claude-home/.claude/projects/-tmp-host-test-claude-workspace/a7f96472-e9d0-447a-826d-36da9b635fd6.jsonl","cwd":"/tmp/host-test/claude-workspace","prompt_id":"88eaceb2-67ed-4bdb-abed-84a52891719d","permission_mode":"bypassPermissions","hook_event_name":"Stop","stop_hook_active":false,"last_assistant_message":"HOST_TEST_DONE (mock model; see the probe log path in the dump result)","background_tasks":[],"session_crons":[]}},"host":"claude","kind":"event","process":{"cwd":"/tmp/host-test/claude-workspace","entry":"/fast/projects/agent-bundle-worktrees/host-test/examples/host-test/artifact/claude/mcp/mcp-host-test-0d229f1b-flight.mjs","pid":1071574,"ppid":1070791},"recordedAt":"2026-09-03T08:46:29.641Z","request":{"host":{"source":"native","state":"available","value":{"name":"claude"}},"invocation":{"kind":"event"},"session":{"source":"native","state":"available","value":{"sessionId":"a7f96472-e9d0-447a-826d-36da9b635fd6"}}},"runtime":"shared-runtime","sequence":27} -{"event":{"canonical":{"event":"session/end","idempotencyKey":"a45c5e72b8c3c8298ff57e3cb08bb0968787a765b66d2cf08dd437bf8f659994","observedAt":"2026-09-03T08:46:29.826Z","provenance":{"host":"claude","hostContractRevision":"2.1.250","nativeEvent":"SessionEnd","source":"native"},"sequence":1},"native":{"session_id":"a7f96472-e9d0-447a-826d-36da9b635fd6","transcript_path":"/tmp/host-test/claude-home/.claude/projects/-tmp-host-test-claude-workspace/a7f96472-e9d0-447a-826d-36da9b635fd6.jsonl","cwd":"/tmp/host-test/claude-workspace","prompt_id":"88eaceb2-67ed-4bdb-abed-84a52891719d","hook_event_name":"SessionEnd","reason":"other"}},"host":"claude","kind":"event","process":{"cwd":"/tmp/host-test/claude-workspace","entry":"/fast/projects/agent-bundle-worktrees/host-test/examples/host-test/artifact/claude/hooks/hooks-flight.mjs","pid":1076993,"ppid":1076991},"recordedAt":"2026-09-03T08:46:30.070Z","request":{"host":{"source":"native","state":"available","value":{"name":"claude"}},"invocation":{"kind":"event"},"session":{"source":"native","state":"available","value":{"sessionId":"a7f96472-e9d0-447a-826d-36da9b635fd6"}}},"runtime":"standalone-hook","sequence":1} +{"env":{"names":["ANTHROPIC_API_KEY","ANTHROPIC_BASE_URL","CLAUDE_CODE_CHILD_SESSION","CLAUDE_CODE_DISABLE_NONESSENTIAL_TRAFFIC","CLAUDE_CODE_ENTRYPOINT","CLAUDE_CODE_MESSAGING_SOCKET","CLAUDE_CODE_MESSAGING_TOKEN","CLAUDE_CODE_SESSION_ID","CLAUDE_CONFIG_DIR","CLAUDE_ENV_FILE","CLAUDE_PID","CLAUDE_PLUGIN_DATA","CLAUDE_PLUGIN_ROOT","CLAUDE_PROJECT_DIR","CURSOR_AGENT","CURSOR_CONVERSATION_ID","CURSOR_LAYOUT","CURSOR_REQUEST_ID","CURSOR_RIPGREP_PATH","HOST_TEST_LOG_DIR"]},"event":{"canonical":{"event":"session/start","idempotencyKey":"5318f6a4c8a238c2f888fc8959c3ff1f1b59c2ac742c0650dd60d2cb0974a02c","observedAt":"2026-09-03T09:35:22.037Z","provenance":{"host":"claude","hostContractRevision":"2.1.250","nativeEvent":"SessionStart","source":"native"},"sequence":1},"native":{"session_id":"1689a5f8-6416-43f1-af26-2aef59604473","transcript_path":"/tmp/host-test/claude-home/.claude/projects/-tmp-host-test-claude-workspace/1689a5f8-6416-43f1-af26-2aef59604473.jsonl","cwd":"/tmp/host-test/claude-workspace","hook_event_name":"SessionStart","source":"startup"}},"host":"claude","kind":"event","process":{"cwd":"/tmp/host-test/claude-workspace","entry":"/fast/projects/agent-bundle-worktrees/host-test/examples/host-test/artifact/claude/hooks/hooks-flight.mjs","pid":1168234,"ppid":1168232},"recordedAt":"2026-09-03T09:35:22.360Z","request":{"host":{"source":"native","state":"available","value":{"name":"claude"}},"invocation":{"kind":"event"},"lineage":{"source":"native","state":"available","value":{"conversation":"1689a5f8-6416-43f1-af26-2aef59604473","depth":0,"resolution":"native","root":"1689a5f8-6416-43f1-af26-2aef59604473"}},"session":{"source":"native","state":"available","value":{"sessionId":"1689a5f8-6416-43f1-af26-2aef59604473"}}},"runtime":"standalone-hook","sequence":1} +{"env":{"names":["AGENT_BUNDLE_PLUGIN_ROOT","ANTHROPIC_API_KEY","ANTHROPIC_BASE_URL","CLAUDE_CODE_DISABLE_NONESSENTIAL_TRAFFIC","CLAUDE_CODE_ENTRYPOINT","CLAUDE_CODE_MESSAGING_SOCKET","CLAUDE_CODE_MESSAGING_TOKEN","CLAUDE_CODE_SESSION_ID","CLAUDE_CONFIG_DIR","CLAUDE_PLUGIN_DATA","CLAUDE_PLUGIN_ROOT","CLAUDE_PROJECT_DIR","CURSOR_AGENT","CURSOR_CONVERSATION_ID","CURSOR_LAYOUT","CURSOR_REQUEST_ID","CURSOR_RIPGREP_PATH","HOST_TEST_LOG_DIR"]},"event":{"canonical":{"event":"prompt/submit","idempotencyKey":"e17d704e80763de28f83fcd447221474ff9b41fa12cd0950d6f2221d19525815","observedAt":"2026-09-03T09:35:22.655Z","provenance":{"host":"claude","hostContractRevision":"2.1.250","nativeEvent":"UserPromptSubmit","source":"native"},"sequence":1},"native":{"session_id":"1689a5f8-6416-43f1-af26-2aef59604473","transcript_path":"/tmp/host-test/claude-home/.claude/projects/-tmp-host-test-claude-workspace/1689a5f8-6416-43f1-af26-2aef59604473.jsonl","cwd":"/tmp/host-test/claude-workspace","prompt_id":"25d4fdbe-964c-4b03-a159-fab0c77688cd","permission_mode":"bypassPermissions","hook_event_name":"UserPromptSubmit","prompt":"You are exercising the host-test probe plugin. Do the scripted steps."}},"host":"claude","kind":"event","process":{"cwd":"/tmp/host-test/claude-workspace","entry":"/fast/projects/agent-bundle-worktrees/host-test/examples/host-test/artifact/claude/mcp/mcp-host-test-0d229f1b-flight.mjs","pid":1168277,"ppid":1167698},"recordedAt":"2026-09-03T09:35:22.710Z","request":{"host":{"source":"native","state":"available","value":{"name":"claude"}},"invocation":{"kind":"event"},"lineage":{"source":"native","state":"available","value":{"conversation":"1689a5f8-6416-43f1-af26-2aef59604473","depth":0,"generation":"25d4fdbe-964c-4b03-a159-fab0c77688cd","resolution":"native","root":"1689a5f8-6416-43f1-af26-2aef59604473"}},"session":{"source":"native","state":"available","value":{"sessionId":"1689a5f8-6416-43f1-af26-2aef59604473"}}},"runtime":"shared-runtime","sequence":1} +{"event":{"canonical":{"event":"tool/before","idempotencyKey":"cf94e9c420ea43f19476255538c87aae726902186c7fa2484658435c33580c6e","observedAt":"2026-09-03T09:35:22.952Z","provenance":{"host":"claude","hostContractRevision":"2.1.250","nativeEvent":"PreToolUse","source":"native"},"sequence":2},"native":{"session_id":"1689a5f8-6416-43f1-af26-2aef59604473","transcript_path":"/tmp/host-test/claude-home/.claude/projects/-tmp-host-test-claude-workspace/1689a5f8-6416-43f1-af26-2aef59604473.jsonl","cwd":"/tmp/host-test/claude-workspace","prompt_id":"25d4fdbe-964c-4b03-a159-fab0c77688cd","permission_mode":"bypassPermissions","hook_event_name":"PreToolUse","tool_name":"Bash","tool_input":{"command":"pwd"},"tool_use_id":"toolu_mock_1"}},"host":"claude","kind":"event","process":{"cwd":"/tmp/host-test/claude-workspace","entry":"/fast/projects/agent-bundle-worktrees/host-test/examples/host-test/artifact/claude/mcp/mcp-host-test-0d229f1b-flight.mjs","pid":1168277,"ppid":1167698},"recordedAt":"2026-09-03T09:35:22.959Z","request":{"host":{"source":"native","state":"available","value":{"name":"claude"}},"invocation":{"kind":"event"},"lineage":{"source":"native","state":"available","value":{"conversation":"1689a5f8-6416-43f1-af26-2aef59604473","depth":0,"generation":"25d4fdbe-964c-4b03-a159-fab0c77688cd","resolution":"native","root":"1689a5f8-6416-43f1-af26-2aef59604473"}},"session":{"source":"native","state":"available","value":{"sessionId":"1689a5f8-6416-43f1-af26-2aef59604473"}}},"runtime":"shared-runtime","sequence":2} +{"event":{"canonical":{"event":"tool/after","idempotencyKey":"0ad4bf8a84269176c38d972f6439873674bdfe9b2086af13d763ff2d91f23ebf","observedAt":"2026-09-03T09:35:23.124Z","provenance":{"host":"claude","hostContractRevision":"2.1.250","nativeEvent":"PostToolUse","source":"native"},"sequence":3},"native":{"session_id":"1689a5f8-6416-43f1-af26-2aef59604473","transcript_path":"/tmp/host-test/claude-home/.claude/projects/-tmp-host-test-claude-workspace/1689a5f8-6416-43f1-af26-2aef59604473.jsonl","cwd":"/tmp/host-test/claude-workspace","prompt_id":"25d4fdbe-964c-4b03-a159-fab0c77688cd","permission_mode":"bypassPermissions","hook_event_name":"PostToolUse","tool_name":"Bash","tool_input":{"command":"pwd"},"tool_response":{"stdout":"/tmp/host-test/claude-workspace","stderr":"","interrupted":false,"isImage":false,"noOutputExpected":false},"tool_use_id":"toolu_mock_1","duration_ms":32}},"host":"claude","kind":"event","process":{"cwd":"/tmp/host-test/claude-workspace","entry":"/fast/projects/agent-bundle-worktrees/host-test/examples/host-test/artifact/claude/mcp/mcp-host-test-0d229f1b-flight.mjs","pid":1168277,"ppid":1167698},"recordedAt":"2026-09-03T09:35:23.130Z","request":{"host":{"source":"native","state":"available","value":{"name":"claude"}},"invocation":{"kind":"event"},"lineage":{"source":"native","state":"available","value":{"conversation":"1689a5f8-6416-43f1-af26-2aef59604473","depth":0,"generation":"25d4fdbe-964c-4b03-a159-fab0c77688cd","resolution":"native","root":"1689a5f8-6416-43f1-af26-2aef59604473"}},"session":{"source":"native","state":"available","value":{"sessionId":"1689a5f8-6416-43f1-af26-2aef59604473"}}},"runtime":"shared-runtime","sequence":3} +{"event":{"canonical":{"event":"tool/before","idempotencyKey":"30399219aef5438c92207451a22343344e6dc98781ef0605c6fa918edf8c6fad","observedAt":"2026-09-03T09:35:23.286Z","provenance":{"host":"claude","hostContractRevision":"2.1.250","nativeEvent":"PreToolUse","source":"native"},"sequence":4},"native":{"session_id":"1689a5f8-6416-43f1-af26-2aef59604473","transcript_path":"/tmp/host-test/claude-home/.claude/projects/-tmp-host-test-claude-workspace/1689a5f8-6416-43f1-af26-2aef59604473.jsonl","cwd":"/tmp/host-test/claude-workspace","prompt_id":"25d4fdbe-964c-4b03-a159-fab0c77688cd","permission_mode":"bypassPermissions","hook_event_name":"PreToolUse","tool_name":"mcp__plugin_host-test_host-test__dump","tool_input":{},"tool_use_id":"toolu_mock_3"}},"host":"claude","kind":"event","process":{"cwd":"/tmp/host-test/claude-workspace","entry":"/fast/projects/agent-bundle-worktrees/host-test/examples/host-test/artifact/claude/mcp/mcp-host-test-0d229f1b-flight.mjs","pid":1168277,"ppid":1167698},"recordedAt":"2026-09-03T09:35:23.293Z","request":{"host":{"source":"native","state":"available","value":{"name":"claude"}},"invocation":{"kind":"event"},"lineage":{"source":"native","state":"available","value":{"conversation":"1689a5f8-6416-43f1-af26-2aef59604473","depth":0,"generation":"25d4fdbe-964c-4b03-a159-fab0c77688cd","resolution":"native","root":"1689a5f8-6416-43f1-af26-2aef59604473"}},"session":{"source":"native","state":"available","value":{"sessionId":"1689a5f8-6416-43f1-af26-2aef59604473"}}},"runtime":"shared-runtime","sequence":4} +{"env":{"names":["AGENT_BUNDLE_PLUGIN_ROOT","ANTHROPIC_API_KEY","ANTHROPIC_BASE_URL","CLAUDE_CODE_DISABLE_NONESSENTIAL_TRAFFIC","CLAUDE_CODE_ENTRYPOINT","CLAUDE_CODE_MESSAGING_SOCKET","CLAUDE_CODE_MESSAGING_TOKEN","CLAUDE_CODE_SESSION_ID","CLAUDE_CONFIG_DIR","CLAUDE_PLUGIN_DATA","CLAUDE_PLUGIN_ROOT","CLAUDE_PROJECT_DIR","CURSOR_AGENT","CURSOR_CONVERSATION_ID","CURSOR_LAYOUT","CURSOR_REQUEST_ID","CURSOR_RIPGREP_PATH","HOST_TEST_LOG_DIR"]},"host":"claude-code","kind":"mcp","observed":{"tool":"dump"},"process":{"cwd":"/tmp/host-test/claude-workspace","entry":"/fast/projects/agent-bundle-worktrees/host-test/examples/host-test/artifact/claude/mcp/mcp-host-test-0d229f1b-flight.mjs","pid":1168277,"ppid":1167698},"recordedAt":"2026-09-03T09:35:23.320Z","request":{"host":{"source":"native","state":"available","value":{"name":"claude-code"}},"invocation":{"kind":"tool"},"lineage":{"source":"derived","state":"available","value":{"conversation":"1689a5f8-6416-43f1-af26-2aef59604473","depth":0,"resolution":"registry","root":"1689a5f8-6416-43f1-af26-2aef59604473"}},"session":{"reason":"not-provided","state":"unavailable"}},"runtime":"mcp-server","sequence":5} +{"event":{"canonical":{"event":"tool/after","idempotencyKey":"b11813659a5fb6ba2529c07240317ac838467438a478716829274a9b91c8041f","observedAt":"2026-09-03T09:35:23.446Z","provenance":{"host":"claude","hostContractRevision":"2.1.250","nativeEvent":"PostToolUse","source":"native"},"sequence":5},"native":{"session_id":"1689a5f8-6416-43f1-af26-2aef59604473","transcript_path":"/tmp/host-test/claude-home/.claude/projects/-tmp-host-test-claude-workspace/1689a5f8-6416-43f1-af26-2aef59604473.jsonl","cwd":"/tmp/host-test/claude-workspace","prompt_id":"25d4fdbe-964c-4b03-a159-fab0c77688cd","permission_mode":"bypassPermissions","hook_event_name":"PostToolUse","tool_name":"mcp__plugin_host-test_host-test__dump","tool_input":{},"tool_response":"{\"filter\":{},\"log\":{\"malformed\":0,\"path\":\"/tmp/host-test/claude/log/captures.ndjson\",\"source\":\"env:HOST_TEST_LOG_DIR\"},\"matched\":6,\"records\":[{\"event\":\"session/start\",\"host\":\"claude\",\"ids\":{\"session_id\":\"1689a5f8-6416-43f1-af26-2aef59604473\",\"transcript_path\":\"/tmp/host-test/claude-home/.claude/projects/-tmp-host-test-claude-workspace/1689a5f8-6416-43f1-af26-2aef59604473.jsonl\",\"cwd\":\"/tmp/host-te…[+4095 chars]","tool_use_id":"toolu_mock_3","duration_ms":36}},"host":"claude","kind":"event","process":{"cwd":"/tmp/host-test/claude-workspace","entry":"/fast/projects/agent-bundle-worktrees/host-test/examples/host-test/artifact/claude/mcp/mcp-host-test-0d229f1b-flight.mjs","pid":1168277,"ppid":1167698},"recordedAt":"2026-09-03T09:35:23.454Z","request":{"host":{"source":"native","state":"available","value":{"name":"claude"}},"invocation":{"kind":"event"},"lineage":{"source":"native","state":"available","value":{"conversation":"1689a5f8-6416-43f1-af26-2aef59604473","depth":0,"generation":"25d4fdbe-964c-4b03-a159-fab0c77688cd","resolution":"native","root":"1689a5f8-6416-43f1-af26-2aef59604473"}},"session":{"source":"native","state":"available","value":{"sessionId":"1689a5f8-6416-43f1-af26-2aef59604473"}}},"runtime":"shared-runtime","sequence":6} +{"event":{"canonical":{"event":"tool/before","idempotencyKey":"5ed0b18a0b63f8afb6bf2ee9736de1eabcfddd8182f92686737228d00cf6b0dc","observedAt":"2026-09-03T09:35:23.598Z","provenance":{"host":"claude","hostContractRevision":"2.1.250","nativeEvent":"PreToolUse","source":"native"},"sequence":6},"native":{"session_id":"1689a5f8-6416-43f1-af26-2aef59604473","transcript_path":"/tmp/host-test/claude-home/.claude/projects/-tmp-host-test-claude-workspace/1689a5f8-6416-43f1-af26-2aef59604473.jsonl","cwd":"/tmp/host-test/claude-workspace","prompt_id":"25d4fdbe-964c-4b03-a159-fab0c77688cd","permission_mode":"bypassPermissions","hook_event_name":"PreToolUse","tool_name":"mcp__plugin_host-test_host-test-raw__probe","tool_input":{"note":"root"},"tool_use_id":"toolu_mock_4"}},"host":"claude","kind":"event","process":{"cwd":"/tmp/host-test/claude-workspace","entry":"/fast/projects/agent-bundle-worktrees/host-test/examples/host-test/artifact/claude/mcp/mcp-host-test-0d229f1b-flight.mjs","pid":1168277,"ppid":1167698},"recordedAt":"2026-09-03T09:35:23.605Z","request":{"host":{"source":"native","state":"available","value":{"name":"claude"}},"invocation":{"kind":"event"},"lineage":{"source":"native","state":"available","value":{"conversation":"1689a5f8-6416-43f1-af26-2aef59604473","depth":0,"generation":"25d4fdbe-964c-4b03-a159-fab0c77688cd","resolution":"native","root":"1689a5f8-6416-43f1-af26-2aef59604473"}},"session":{"source":"native","state":"available","value":{"sessionId":"1689a5f8-6416-43f1-af26-2aef59604473"}}},"runtime":"shared-runtime","sequence":7} +{"host":"claude-code","kind":"mcp","observed":{"client":{"name":"claude-code","title":"Claude Code","version":"2.1.257","websiteUrl":"https://claude.com/claude-code","description":"Anthropic's agentic coding tool"},"clientCapabilities":{"elicitation":{"form":{}},"roots":{"listChanged":true}},"env":{"names":["AGENT_BUNDLE_PLUGIN_ROOT","ANTHROPIC_API_KEY","ANTHROPIC_BASE_URL","CLAUDE_CODE_DISABLE_NONESSENTIAL_TRAFFIC","CLAUDE_CODE_ENTRYPOINT","CLAUDE_CODE_MESSAGING_SOCKET","CLAUDE_CODE_MESSAGING_TOKEN","CLAUDE_CODE_SESSION_ID","CLAUDE_CONFIG_DIR","CLAUDE_PLUGIN_DATA","CLAUDE_PLUGIN_ROOT","CLAUDE_PROJECT_DIR","CURSOR_AGENT","CURSOR_CONVERSATION_ID","CURSOR_LAYOUT","CURSOR_REQUEST_ID","CURSOR_RIPGREP_PATH","HOST_TEST_LOG_DIR"]},"http":null,"mcpReq":{"_meta":{"progressToken":2,"claudecode/toolUseId":"toolu_mock_4"},"envelope":null,"id":2,"method":"tools/call"},"note":"root","sessionId":null,"tool":"probe"},"process":{"cwd":"/tmp/host-test/claude-workspace","entry":"/fast/projects/agent-bundle-worktrees/host-test/examples/host-test/artifact/claude/mcp/mcp-host-test-raw-6e9c1a1c.mjs","pid":1168280,"ppid":1167698},"recordedAt":"2026-09-03T09:35:23.639Z","request":{"unavailable":"hand-rolled stdio server: no framework request context is mounted"},"runtime":"mcp-server","sequence":1} +{"event":{"canonical":{"event":"tool/after","idempotencyKey":"db7a0eecd7bcf042efaf91fbb081c2a67be243c53aeac61d6fecd7a57d16a52a","observedAt":"2026-09-03T09:35:23.773Z","provenance":{"host":"claude","hostContractRevision":"2.1.250","nativeEvent":"PostToolUse","source":"native"},"sequence":7},"native":{"session_id":"1689a5f8-6416-43f1-af26-2aef59604473","transcript_path":"/tmp/host-test/claude-home/.claude/projects/-tmp-host-test-claude-workspace/1689a5f8-6416-43f1-af26-2aef59604473.jsonl","cwd":"/tmp/host-test/claude-workspace","prompt_id":"25d4fdbe-964c-4b03-a159-fab0c77688cd","permission_mode":"bypassPermissions","hook_event_name":"PostToolUse","tool_name":"mcp__plugin_host-test_host-test-raw__probe","tool_input":{"note":"root"},"tool_response":"{\"log\":\"/tmp/host-test/claude/log/captures.ndjson\",\"observed\":{\"client\":{\"name\":\"claude-code\",\"title\":\"Claude Code\",\"version\":\"2.1.257\",\"websiteUrl\":\"https://claude.com/claude-code\",\"description\":\"Anthropic's agentic coding tool\"},\"clientCapabilities\":{\"elicitation\":{\"form\":{}},\"roots\":{\"listChanged\":true}},\"env\":{\"names\":[\"AGENT_BUNDLE_PLUGIN_ROOT\",\"ANTHROPIC_API_KEY\",\"ANTHROPIC_BASE_URL\",\"CLAUDE…[+544 chars]","tool_use_id":"toolu_mock_4","duration_ms":27}},"host":"claude","kind":"event","process":{"cwd":"/tmp/host-test/claude-workspace","entry":"/fast/projects/agent-bundle-worktrees/host-test/examples/host-test/artifact/claude/mcp/mcp-host-test-0d229f1b-flight.mjs","pid":1168277,"ppid":1167698},"recordedAt":"2026-09-03T09:35:23.778Z","request":{"host":{"source":"native","state":"available","value":{"name":"claude"}},"invocation":{"kind":"event"},"lineage":{"source":"native","state":"available","value":{"conversation":"1689a5f8-6416-43f1-af26-2aef59604473","depth":0,"generation":"25d4fdbe-964c-4b03-a159-fab0c77688cd","resolution":"native","root":"1689a5f8-6416-43f1-af26-2aef59604473"}},"session":{"source":"native","state":"available","value":{"sessionId":"1689a5f8-6416-43f1-af26-2aef59604473"}}},"runtime":"shared-runtime","sequence":8} +{"event":{"canonical":{"event":"tool/before","idempotencyKey":"90f18016b75888c344f99dfa95f22f6c0e1fb8399ed097f8d7e1445021b0ebd5","observedAt":"2026-09-03T09:35:23.916Z","provenance":{"host":"claude","hostContractRevision":"2.1.250","nativeEvent":"PreToolUse","source":"native"},"sequence":8},"native":{"session_id":"1689a5f8-6416-43f1-af26-2aef59604473","transcript_path":"/tmp/host-test/claude-home/.claude/projects/-tmp-host-test-claude-workspace/1689a5f8-6416-43f1-af26-2aef59604473.jsonl","cwd":"/tmp/host-test/claude-workspace","prompt_id":"25d4fdbe-964c-4b03-a159-fab0c77688cd","permission_mode":"bypassPermissions","hook_event_name":"PreToolUse","tool_name":"Agent","tool_input":{"description":"host-test subagent probe","prompt":"SUBAGENT_PROBE_SCENARIO: run `pwd`, call the host-test dump tool with {}, call the host-test-raw probe tool with {\"note\":\"subagent\"}, spawn a nested subagent with NESTED_PROBE_SCENARIO if you can, then reply with every id you saw.","subagent_type":"general-purpose"},"tool_use_id":"toolu_mock_5"}},"host":"claude","kind":"event","process":{"cwd":"/tmp/host-test/claude-workspace","entry":"/fast/projects/agent-bundle-worktrees/host-test/examples/host-test/artifact/claude/mcp/mcp-host-test-0d229f1b-flight.mjs","pid":1168277,"ppid":1167698},"recordedAt":"2026-09-03T09:35:23.922Z","request":{"host":{"source":"native","state":"available","value":{"name":"claude"}},"invocation":{"kind":"event"},"lineage":{"source":"native","state":"available","value":{"conversation":"1689a5f8-6416-43f1-af26-2aef59604473","depth":0,"generation":"25d4fdbe-964c-4b03-a159-fab0c77688cd","resolution":"native","root":"1689a5f8-6416-43f1-af26-2aef59604473"}},"session":{"source":"native","state":"available","value":{"sessionId":"1689a5f8-6416-43f1-af26-2aef59604473"}}},"runtime":"shared-runtime","sequence":9} +{"event":{"canonical":{"event":"agent/start","idempotencyKey":"4072f7a2969f057fe88e16aab03923b8a162af20ae47a586573d0c32505e0f7f","observedAt":"2026-09-03T09:35:24.062Z","provenance":{"host":"claude","hostContractRevision":"2.1.250","nativeEvent":"SubagentStart","source":"native"},"sequence":9},"native":{"session_id":"1689a5f8-6416-43f1-af26-2aef59604473","transcript_path":"/tmp/host-test/claude-home/.claude/projects/-tmp-host-test-claude-workspace/1689a5f8-6416-43f1-af26-2aef59604473.jsonl","cwd":"/tmp/host-test/claude-workspace","prompt_id":"25d4fdbe-964c-4b03-a159-fab0c77688cd","agent_id":"aaf67c048de9cb68e","agent_type":"general-purpose","hook_event_name":"SubagentStart"}},"host":"claude","kind":"event","process":{"cwd":"/tmp/host-test/claude-workspace","entry":"/fast/projects/agent-bundle-worktrees/host-test/examples/host-test/artifact/claude/mcp/mcp-host-test-0d229f1b-flight.mjs","pid":1168277,"ppid":1167698},"recordedAt":"2026-09-03T09:35:24.070Z","request":{"host":{"source":"native","state":"available","value":{"name":"claude"}},"invocation":{"kind":"event"},"lineage":{"source":"derived","state":"available","value":{"conversation":"aaf67c048de9cb68e","depth":1,"generation":"25d4fdbe-964c-4b03-a159-fab0c77688cd","parent":"1689a5f8-6416-43f1-af26-2aef59604473","resolution":"registry","root":"1689a5f8-6416-43f1-af26-2aef59604473","subagent":{"id":"aaf67c048de9cb68e","toolCallId":"toolu_mock_5","type":"general-purpose"}}},"session":{"source":"native","state":"available","value":{"sessionId":"1689a5f8-6416-43f1-af26-2aef59604473"}}},"runtime":"shared-runtime","sequence":10} +{"event":{"canonical":{"event":"tool/after","idempotencyKey":"595a01e58984cd11eae62923ea9fb085adfaa5b0293a014efee67bd65c0594c0","observedAt":"2026-09-03T09:35:24.070Z","provenance":{"host":"claude","hostContractRevision":"2.1.250","nativeEvent":"PostToolUse","source":"native"},"sequence":10},"native":{"session_id":"1689a5f8-6416-43f1-af26-2aef59604473","transcript_path":"/tmp/host-test/claude-home/.claude/projects/-tmp-host-test-claude-workspace/1689a5f8-6416-43f1-af26-2aef59604473.jsonl","cwd":"/tmp/host-test/claude-workspace","prompt_id":"25d4fdbe-964c-4b03-a159-fab0c77688cd","permission_mode":"bypassPermissions","hook_event_name":"PostToolUse","tool_name":"Agent","tool_input":{"description":"host-test subagent probe","prompt":"SUBAGENT_PROBE_SCENARIO: run `pwd`, call the host-test dump tool with {}, call the host-test-raw probe tool with {\"note\":\"subagent\"}, spawn a nested subagent with NESTED_PROBE_SCENARIO if you can, then reply with every id you saw.","subagent_type":"general-purpose"},"tool_response":{"isAsync":true,"status":"async_launched","agentId":"aaf67c048de9cb68e","description":"host-test subagent probe","resolvedModel":"claude-sonnet-4-5","prompt":"SUBAGENT_PROBE_SCENARIO: run `pwd`, call the host-test dump tool with {}, call the host-test-raw probe tool with {\"note\":\"subagent\"}, spawn a nested subagent with NESTED_PROBE_SCENARIO if you can, then reply with every id you saw.","outputFile":"/tmp/claude-1000/-tmp-host-test-claude-workspace/1689a5f8-6416-43f1-af26-2aef59604473/tasks/aaf67c048de9cb68e.output","canReadOutputFile":true},"tool_use_id":"toolu_mock_5","duration_ms":5}},"host":"claude","kind":"event","process":{"cwd":"/tmp/host-test/claude-workspace","entry":"/fast/projects/agent-bundle-worktrees/host-test/examples/host-test/artifact/claude/mcp/mcp-host-test-0d229f1b-flight.mjs","pid":1168277,"ppid":1167698},"recordedAt":"2026-09-03T09:35:24.075Z","request":{"host":{"source":"native","state":"available","value":{"name":"claude"}},"invocation":{"kind":"event"},"lineage":{"source":"native","state":"available","value":{"conversation":"1689a5f8-6416-43f1-af26-2aef59604473","depth":0,"generation":"25d4fdbe-964c-4b03-a159-fab0c77688cd","resolution":"native","root":"1689a5f8-6416-43f1-af26-2aef59604473"}},"session":{"source":"native","state":"available","value":{"sessionId":"1689a5f8-6416-43f1-af26-2aef59604473"}}},"runtime":"shared-runtime","sequence":11} +{"event":{"canonical":{"event":"tool/before","idempotencyKey":"8aa8d4348beae2a1d85706c2cab4d41b131d54bcd94f77ba4b1bed1319380647","observedAt":"2026-09-03T09:35:24.213Z","provenance":{"host":"claude","hostContractRevision":"2.1.250","nativeEvent":"PreToolUse","source":"native"},"sequence":11},"native":{"session_id":"1689a5f8-6416-43f1-af26-2aef59604473","transcript_path":"/tmp/host-test/claude-home/.claude/projects/-tmp-host-test-claude-workspace/1689a5f8-6416-43f1-af26-2aef59604473.jsonl","cwd":"/tmp/host-test/claude-workspace","prompt_id":"25d4fdbe-964c-4b03-a159-fab0c77688cd","permission_mode":"bypassPermissions","agent_id":"aaf67c048de9cb68e","agent_type":"general-purpose","hook_event_name":"PreToolUse","tool_name":"Bash","tool_input":{"command":"pwd"},"tool_use_id":"toolu_mock_6"}},"host":"claude","kind":"event","process":{"cwd":"/tmp/host-test/claude-workspace","entry":"/fast/projects/agent-bundle-worktrees/host-test/examples/host-test/artifact/claude/mcp/mcp-host-test-0d229f1b-flight.mjs","pid":1168277,"ppid":1167698},"recordedAt":"2026-09-03T09:35:24.219Z","request":{"host":{"source":"native","state":"available","value":{"name":"claude"}},"invocation":{"kind":"event"},"lineage":{"source":"derived","state":"available","value":{"conversation":"aaf67c048de9cb68e","depth":1,"generation":"25d4fdbe-964c-4b03-a159-fab0c77688cd","parent":"1689a5f8-6416-43f1-af26-2aef59604473","resolution":"registry","root":"1689a5f8-6416-43f1-af26-2aef59604473","subagent":{"id":"aaf67c048de9cb68e","toolCallId":"toolu_mock_5","type":"general-purpose"}}},"session":{"source":"native","state":"available","value":{"sessionId":"1689a5f8-6416-43f1-af26-2aef59604473"}}},"runtime":"shared-runtime","sequence":12} +{"event":{"canonical":{"event":"stop","idempotencyKey":"b9422423a4ea15333d9775a5062ce7450392f97dfece3c6dc4dc7d5d0d27e875","observedAt":"2026-09-03T09:35:24.233Z","provenance":{"host":"claude","hostContractRevision":"2.1.250","nativeEvent":"Stop","source":"native"},"sequence":12},"native":{"session_id":"1689a5f8-6416-43f1-af26-2aef59604473","transcript_path":"/tmp/host-test/claude-home/.claude/projects/-tmp-host-test-claude-workspace/1689a5f8-6416-43f1-af26-2aef59604473.jsonl","cwd":"/tmp/host-test/claude-workspace","prompt_id":"25d4fdbe-964c-4b03-a159-fab0c77688cd","permission_mode":"bypassPermissions","hook_event_name":"Stop","stop_hook_active":false,"last_assistant_message":"HOST_TEST_DONE (mock model; see the probe log path in the dump result)","background_tasks":[{"id":"aaf67c048de9cb68e","type":"subagent","status":"running","description":"host-test subagent probe","agent_type":"general-purpose"}],"session_crons":[]}},"host":"claude","kind":"event","process":{"cwd":"/tmp/host-test/claude-workspace","entry":"/fast/projects/agent-bundle-worktrees/host-test/examples/host-test/artifact/claude/mcp/mcp-host-test-0d229f1b-flight.mjs","pid":1168277,"ppid":1167698},"recordedAt":"2026-09-03T09:35:24.236Z","request":{"host":{"source":"native","state":"available","value":{"name":"claude"}},"invocation":{"kind":"event"},"lineage":{"source":"native","state":"available","value":{"conversation":"1689a5f8-6416-43f1-af26-2aef59604473","depth":0,"generation":"25d4fdbe-964c-4b03-a159-fab0c77688cd","resolution":"native","root":"1689a5f8-6416-43f1-af26-2aef59604473"}},"session":{"source":"native","state":"available","value":{"sessionId":"1689a5f8-6416-43f1-af26-2aef59604473"}}},"runtime":"shared-runtime","sequence":13} +{"event":{"canonical":{"event":"tool/after","idempotencyKey":"d0561ce9349b4e9e4764a5d8c4884bb3c5578264e303799c95d57c1e515cafd2","observedAt":"2026-09-03T09:35:24.356Z","provenance":{"host":"claude","hostContractRevision":"2.1.250","nativeEvent":"PostToolUse","source":"native"},"sequence":13},"native":{"session_id":"1689a5f8-6416-43f1-af26-2aef59604473","transcript_path":"/tmp/host-test/claude-home/.claude/projects/-tmp-host-test-claude-workspace/1689a5f8-6416-43f1-af26-2aef59604473.jsonl","cwd":"/tmp/host-test/claude-workspace","prompt_id":"25d4fdbe-964c-4b03-a159-fab0c77688cd","permission_mode":"bypassPermissions","agent_id":"aaf67c048de9cb68e","agent_type":"general-purpose","hook_event_name":"PostToolUse","tool_name":"Bash","tool_input":{"command":"pwd"},"tool_response":{"stdout":"/tmp/host-test/claude-workspace","stderr":"","interrupted":false,"isImage":false,"noOutputExpected":false},"tool_use_id":"toolu_mock_6","duration_ms":9}},"host":"claude","kind":"event","process":{"cwd":"/tmp/host-test/claude-workspace","entry":"/fast/projects/agent-bundle-worktrees/host-test/examples/host-test/artifact/claude/mcp/mcp-host-test-0d229f1b-flight.mjs","pid":1168277,"ppid":1167698},"recordedAt":"2026-09-03T09:35:24.361Z","request":{"host":{"source":"native","state":"available","value":{"name":"claude"}},"invocation":{"kind":"event"},"lineage":{"source":"derived","state":"available","value":{"conversation":"aaf67c048de9cb68e","depth":1,"generation":"25d4fdbe-964c-4b03-a159-fab0c77688cd","parent":"1689a5f8-6416-43f1-af26-2aef59604473","resolution":"registry","root":"1689a5f8-6416-43f1-af26-2aef59604473","subagent":{"id":"aaf67c048de9cb68e","toolCallId":"toolu_mock_5","type":"general-purpose"}}},"session":{"source":"native","state":"available","value":{"sessionId":"1689a5f8-6416-43f1-af26-2aef59604473"}}},"runtime":"shared-runtime","sequence":14} +{"event":{"canonical":{"event":"tool/before","idempotencyKey":"3d3a50d0589a0cfc2f161c5a577b40ed8c37389a51bfead8eabe1c4b06e99e1b","observedAt":"2026-09-03T09:35:24.497Z","provenance":{"host":"claude","hostContractRevision":"2.1.250","nativeEvent":"PreToolUse","source":"native"},"sequence":14},"native":{"session_id":"1689a5f8-6416-43f1-af26-2aef59604473","transcript_path":"/tmp/host-test/claude-home/.claude/projects/-tmp-host-test-claude-workspace/1689a5f8-6416-43f1-af26-2aef59604473.jsonl","cwd":"/tmp/host-test/claude-workspace","prompt_id":"25d4fdbe-964c-4b03-a159-fab0c77688cd","permission_mode":"bypassPermissions","agent_id":"aaf67c048de9cb68e","agent_type":"general-purpose","hook_event_name":"PreToolUse","tool_name":"mcp__plugin_host-test_host-test__dump","tool_input":{},"tool_use_id":"toolu_mock_8"}},"host":"claude","kind":"event","process":{"cwd":"/tmp/host-test/claude-workspace","entry":"/fast/projects/agent-bundle-worktrees/host-test/examples/host-test/artifact/claude/mcp/mcp-host-test-0d229f1b-flight.mjs","pid":1168277,"ppid":1167698},"recordedAt":"2026-09-03T09:35:24.501Z","request":{"host":{"source":"native","state":"available","value":{"name":"claude"}},"invocation":{"kind":"event"},"lineage":{"source":"derived","state":"available","value":{"conversation":"aaf67c048de9cb68e","depth":1,"generation":"25d4fdbe-964c-4b03-a159-fab0c77688cd","parent":"1689a5f8-6416-43f1-af26-2aef59604473","resolution":"registry","root":"1689a5f8-6416-43f1-af26-2aef59604473","subagent":{"id":"aaf67c048de9cb68e","toolCallId":"toolu_mock_5","type":"general-purpose"}}},"session":{"source":"native","state":"available","value":{"sessionId":"1689a5f8-6416-43f1-af26-2aef59604473"}}},"runtime":"shared-runtime","sequence":15} +{"host":"claude-code","kind":"mcp","observed":{"tool":"dump"},"process":{"cwd":"/tmp/host-test/claude-workspace","entry":"/fast/projects/agent-bundle-worktrees/host-test/examples/host-test/artifact/claude/mcp/mcp-host-test-0d229f1b-flight.mjs","pid":1168277,"ppid":1167698},"recordedAt":"2026-09-03T09:35:24.522Z","request":{"host":{"source":"native","state":"available","value":{"name":"claude-code"}},"invocation":{"kind":"tool"},"lineage":{"source":"derived","state":"available","value":{"conversation":"aaf67c048de9cb68e","depth":1,"parent":"1689a5f8-6416-43f1-af26-2aef59604473","resolution":"registry","root":"1689a5f8-6416-43f1-af26-2aef59604473","subagent":{"id":"aaf67c048de9cb68e","toolCallId":"toolu_mock_5","type":"general-purpose"}}},"session":{"reason":"not-provided","state":"unavailable"}},"runtime":"mcp-server","sequence":16} +{"event":{"canonical":{"event":"tool/after","idempotencyKey":"0664391ee22925c0d65badbaa71fb30e7da4110fce920685ca59848e0568a700","observedAt":"2026-09-03T09:35:24.661Z","provenance":{"host":"claude","hostContractRevision":"2.1.250","nativeEvent":"PostToolUse","source":"native"},"sequence":15},"native":{"session_id":"1689a5f8-6416-43f1-af26-2aef59604473","transcript_path":"/tmp/host-test/claude-home/.claude/projects/-tmp-host-test-claude-workspace/1689a5f8-6416-43f1-af26-2aef59604473.jsonl","cwd":"/tmp/host-test/claude-workspace","prompt_id":"25d4fdbe-964c-4b03-a159-fab0c77688cd","permission_mode":"bypassPermissions","agent_id":"aaf67c048de9cb68e","agent_type":"general-purpose","hook_event_name":"PostToolUse","tool_name":"mcp__plugin_host-test_host-test__dump","tool_input":{},"tool_response":"{\"filter\":{},\"log\":{\"malformed\":0,\"path\":\"/tmp/host-test/claude/log/captures.ndjson\",\"source\":\"env:HOST_TEST_LOG_DIR\"},\"matched\":18,\"records\":[{\"event\":\"session/start\",\"host\":\"claude\",\"ids\":{\"session_id\":\"1689a5f8-6416-43f1-af26-2aef59604473\",\"transcript_path\":\"/tmp/host-test/claude-home/.claude/projects/-tmp-host-test-claude-workspace/1689a5f8-6416-43f1-af26-2aef59604473.jsonl\",\"cwd\":\"/tmp/host-t…[+14220 chars]","tool_use_id":"toolu_mock_8","duration_ms":31}},"host":"claude","kind":"event","process":{"cwd":"/tmp/host-test/claude-workspace","entry":"/fast/projects/agent-bundle-worktrees/host-test/examples/host-test/artifact/claude/mcp/mcp-host-test-0d229f1b-flight.mjs","pid":1168277,"ppid":1167698},"recordedAt":"2026-09-03T09:35:24.666Z","request":{"host":{"source":"native","state":"available","value":{"name":"claude"}},"invocation":{"kind":"event"},"lineage":{"source":"derived","state":"available","value":{"conversation":"aaf67c048de9cb68e","depth":1,"generation":"25d4fdbe-964c-4b03-a159-fab0c77688cd","parent":"1689a5f8-6416-43f1-af26-2aef59604473","resolution":"registry","root":"1689a5f8-6416-43f1-af26-2aef59604473","subagent":{"id":"aaf67c048de9cb68e","toolCallId":"toolu_mock_5","type":"general-purpose"}}},"session":{"source":"native","state":"available","value":{"sessionId":"1689a5f8-6416-43f1-af26-2aef59604473"}}},"runtime":"shared-runtime","sequence":17} +{"event":{"canonical":{"event":"tool/before","idempotencyKey":"d8a1b298c4896561985a3cd192e28e09ac67c9de9af1bfa65015e4df471a770b","observedAt":"2026-09-03T09:35:24.814Z","provenance":{"host":"claude","hostContractRevision":"2.1.250","nativeEvent":"PreToolUse","source":"native"},"sequence":16},"native":{"session_id":"1689a5f8-6416-43f1-af26-2aef59604473","transcript_path":"/tmp/host-test/claude-home/.claude/projects/-tmp-host-test-claude-workspace/1689a5f8-6416-43f1-af26-2aef59604473.jsonl","cwd":"/tmp/host-test/claude-workspace","prompt_id":"25d4fdbe-964c-4b03-a159-fab0c77688cd","permission_mode":"bypassPermissions","agent_id":"aaf67c048de9cb68e","agent_type":"general-purpose","hook_event_name":"PreToolUse","tool_name":"mcp__plugin_host-test_host-test-raw__probe","tool_input":{"note":"subagent"},"tool_use_id":"toolu_mock_9"}},"host":"claude","kind":"event","process":{"cwd":"/tmp/host-test/claude-workspace","entry":"/fast/projects/agent-bundle-worktrees/host-test/examples/host-test/artifact/claude/mcp/mcp-host-test-0d229f1b-flight.mjs","pid":1168277,"ppid":1167698},"recordedAt":"2026-09-03T09:35:24.820Z","request":{"host":{"source":"native","state":"available","value":{"name":"claude"}},"invocation":{"kind":"event"},"lineage":{"source":"derived","state":"available","value":{"conversation":"aaf67c048de9cb68e","depth":1,"generation":"25d4fdbe-964c-4b03-a159-fab0c77688cd","parent":"1689a5f8-6416-43f1-af26-2aef59604473","resolution":"registry","root":"1689a5f8-6416-43f1-af26-2aef59604473","subagent":{"id":"aaf67c048de9cb68e","toolCallId":"toolu_mock_5","type":"general-purpose"}}},"session":{"source":"native","state":"available","value":{"sessionId":"1689a5f8-6416-43f1-af26-2aef59604473"}}},"runtime":"shared-runtime","sequence":18} +{"host":"claude-code","kind":"mcp","observed":{"client":{"name":"claude-code","title":"Claude Code","version":"2.1.257","websiteUrl":"https://claude.com/claude-code","description":"Anthropic's agentic coding tool"},"clientCapabilities":{"elicitation":{"form":{}},"roots":{"listChanged":true}},"env":{"names":["AGENT_BUNDLE_PLUGIN_ROOT","ANTHROPIC_API_KEY","ANTHROPIC_BASE_URL","CLAUDE_CODE_DISABLE_NONESSENTIAL_TRAFFIC","CLAUDE_CODE_ENTRYPOINT","CLAUDE_CODE_MESSAGING_SOCKET","CLAUDE_CODE_MESSAGING_TOKEN","CLAUDE_CODE_SESSION_ID","CLAUDE_CONFIG_DIR","CLAUDE_PLUGIN_DATA","CLAUDE_PLUGIN_ROOT","CLAUDE_PROJECT_DIR","CURSOR_AGENT","CURSOR_CONVERSATION_ID","CURSOR_LAYOUT","CURSOR_REQUEST_ID","CURSOR_RIPGREP_PATH","HOST_TEST_LOG_DIR"]},"http":null,"mcpReq":{"_meta":{"progressToken":3,"claudecode/toolUseId":"toolu_mock_9"},"envelope":null,"id":3,"method":"tools/call"},"note":"subagent","sessionId":null,"tool":"probe"},"process":{"cwd":"/tmp/host-test/claude-workspace","entry":"/fast/projects/agent-bundle-worktrees/host-test/examples/host-test/artifact/claude/mcp/mcp-host-test-raw-6e9c1a1c.mjs","pid":1168280,"ppid":1167698},"recordedAt":"2026-09-03T09:35:24.842Z","request":{"unavailable":"hand-rolled stdio server: no framework request context is mounted"},"runtime":"mcp-server","sequence":2} +{"event":{"canonical":{"event":"tool/after","idempotencyKey":"a75be4a497d5b6060b97e2ae69eda07481ae63cfad418add48043af15e8129ae","observedAt":"2026-09-03T09:35:24.955Z","provenance":{"host":"claude","hostContractRevision":"2.1.250","nativeEvent":"PostToolUse","source":"native"},"sequence":17},"native":{"session_id":"1689a5f8-6416-43f1-af26-2aef59604473","transcript_path":"/tmp/host-test/claude-home/.claude/projects/-tmp-host-test-claude-workspace/1689a5f8-6416-43f1-af26-2aef59604473.jsonl","cwd":"/tmp/host-test/claude-workspace","prompt_id":"25d4fdbe-964c-4b03-a159-fab0c77688cd","permission_mode":"bypassPermissions","agent_id":"aaf67c048de9cb68e","agent_type":"general-purpose","hook_event_name":"PostToolUse","tool_name":"mcp__plugin_host-test_host-test-raw__probe","tool_input":{"note":"subagent"},"tool_response":"{\"log\":\"/tmp/host-test/claude/log/captures.ndjson\",\"observed\":{\"client\":{\"name\":\"claude-code\",\"title\":\"Claude Code\",\"version\":\"2.1.257\",\"websiteUrl\":\"https://claude.com/claude-code\",\"description\":\"Anthropic's agentic coding tool\"},\"clientCapabilities\":{\"elicitation\":{\"form\":{}},\"roots\":{\"listChanged\":true}},\"env\":{\"names\":[\"AGENT_BUNDLE_PLUGIN_ROOT\",\"ANTHROPIC_API_KEY\",\"ANTHROPIC_BASE_URL\",\"CLAUDE…[+548 chars]","tool_use_id":"toolu_mock_9","duration_ms":4}},"host":"claude","kind":"event","process":{"cwd":"/tmp/host-test/claude-workspace","entry":"/fast/projects/agent-bundle-worktrees/host-test/examples/host-test/artifact/claude/mcp/mcp-host-test-0d229f1b-flight.mjs","pid":1168277,"ppid":1167698},"recordedAt":"2026-09-03T09:35:24.959Z","request":{"host":{"source":"native","state":"available","value":{"name":"claude"}},"invocation":{"kind":"event"},"lineage":{"source":"derived","state":"available","value":{"conversation":"aaf67c048de9cb68e","depth":1,"generation":"25d4fdbe-964c-4b03-a159-fab0c77688cd","parent":"1689a5f8-6416-43f1-af26-2aef59604473","resolution":"registry","root":"1689a5f8-6416-43f1-af26-2aef59604473","subagent":{"id":"aaf67c048de9cb68e","toolCallId":"toolu_mock_5","type":"general-purpose"}}},"session":{"source":"native","state":"available","value":{"sessionId":"1689a5f8-6416-43f1-af26-2aef59604473"}}},"runtime":"shared-runtime","sequence":19} +{"event":{"canonical":{"event":"tool/before","idempotencyKey":"51731d17166a61ac4ae449e134a2df9d8089048720065481c6b5b12a15d700d4","observedAt":"2026-09-03T09:35:25.103Z","provenance":{"host":"claude","hostContractRevision":"2.1.250","nativeEvent":"PreToolUse","source":"native"},"sequence":18},"native":{"session_id":"1689a5f8-6416-43f1-af26-2aef59604473","transcript_path":"/tmp/host-test/claude-home/.claude/projects/-tmp-host-test-claude-workspace/1689a5f8-6416-43f1-af26-2aef59604473.jsonl","cwd":"/tmp/host-test/claude-workspace","prompt_id":"25d4fdbe-964c-4b03-a159-fab0c77688cd","permission_mode":"bypassPermissions","agent_id":"aaf67c048de9cb68e","agent_type":"general-purpose","hook_event_name":"PreToolUse","tool_name":"Agent","tool_input":{"description":"nested host-test probe","prompt":"NESTED_PROBE_SCENARIO: run `pwd`, call the host-test-raw probe tool with {\"note\":\"nested\"}, then reply with every id you saw.","subagent_type":"general-purpose"},"tool_use_id":"toolu_mock_10"}},"host":"claude","kind":"event","process":{"cwd":"/tmp/host-test/claude-workspace","entry":"/fast/projects/agent-bundle-worktrees/host-test/examples/host-test/artifact/claude/mcp/mcp-host-test-0d229f1b-flight.mjs","pid":1168277,"ppid":1167698},"recordedAt":"2026-09-03T09:35:25.108Z","request":{"host":{"source":"native","state":"available","value":{"name":"claude"}},"invocation":{"kind":"event"},"lineage":{"source":"derived","state":"available","value":{"conversation":"aaf67c048de9cb68e","depth":1,"generation":"25d4fdbe-964c-4b03-a159-fab0c77688cd","parent":"1689a5f8-6416-43f1-af26-2aef59604473","resolution":"registry","root":"1689a5f8-6416-43f1-af26-2aef59604473","subagent":{"id":"aaf67c048de9cb68e","toolCallId":"toolu_mock_5","type":"general-purpose"}}},"session":{"source":"native","state":"available","value":{"sessionId":"1689a5f8-6416-43f1-af26-2aef59604473"}}},"runtime":"shared-runtime","sequence":20} +{"event":{"canonical":{"event":"tool/after","idempotencyKey":"9910859508ccdb8b1bd39e2d94cad5393b7046a1f1aa644eb445a168b069bf37","observedAt":"2026-09-03T09:35:25.236Z","provenance":{"host":"claude","hostContractRevision":"2.1.250","nativeEvent":"PostToolUse","source":"native"},"sequence":19},"native":{"session_id":"1689a5f8-6416-43f1-af26-2aef59604473","transcript_path":"/tmp/host-test/claude-home/.claude/projects/-tmp-host-test-claude-workspace/1689a5f8-6416-43f1-af26-2aef59604473.jsonl","cwd":"/tmp/host-test/claude-workspace","prompt_id":"25d4fdbe-964c-4b03-a159-fab0c77688cd","permission_mode":"bypassPermissions","agent_id":"aaf67c048de9cb68e","agent_type":"general-purpose","hook_event_name":"PostToolUse","tool_name":"Agent","tool_input":{"description":"nested host-test probe","prompt":"NESTED_PROBE_SCENARIO: run `pwd`, call the host-test-raw probe tool with {\"note\":\"nested\"}, then reply with every id you saw.","subagent_type":"general-purpose"},"tool_response":{"isAsync":true,"status":"async_launched","agentId":"ab1d1508b1a46ca36","description":"nested host-test probe","resolvedModel":"claude-sonnet-4-5","prompt":"NESTED_PROBE_SCENARIO: run `pwd`, call the host-test-raw probe tool with {\"note\":\"nested\"}, then reply with every id you saw.","outputFile":"/tmp/claude-1000/-tmp-host-test-claude-workspace/1689a5f8-6416-43f1-af26-2aef59604473/tasks/ab1d1508b1a46ca36.output","canReadOutputFile":true},"tool_use_id":"toolu_mock_10","duration_ms":2}},"host":"claude","kind":"event","process":{"cwd":"/tmp/host-test/claude-workspace","entry":"/fast/projects/agent-bundle-worktrees/host-test/examples/host-test/artifact/claude/mcp/mcp-host-test-0d229f1b-flight.mjs","pid":1168277,"ppid":1167698},"recordedAt":"2026-09-03T09:35:25.244Z","request":{"host":{"source":"native","state":"available","value":{"name":"claude"}},"invocation":{"kind":"event"},"lineage":{"source":"derived","state":"available","value":{"conversation":"aaf67c048de9cb68e","depth":1,"generation":"25d4fdbe-964c-4b03-a159-fab0c77688cd","parent":"1689a5f8-6416-43f1-af26-2aef59604473","resolution":"registry","root":"1689a5f8-6416-43f1-af26-2aef59604473","subagent":{"id":"aaf67c048de9cb68e","toolCallId":"toolu_mock_5","type":"general-purpose"}}},"session":{"source":"native","state":"available","value":{"sessionId":"1689a5f8-6416-43f1-af26-2aef59604473"}}},"runtime":"shared-runtime","sequence":21} +{"event":{"canonical":{"event":"agent/start","idempotencyKey":"a3313963d75e2e6a92d704a576f611e93720d19bd4788d80c888b2cae7e6d01c","observedAt":"2026-09-03T09:35:25.243Z","provenance":{"host":"claude","hostContractRevision":"2.1.250","nativeEvent":"SubagentStart","source":"native"},"sequence":20},"native":{"session_id":"1689a5f8-6416-43f1-af26-2aef59604473","transcript_path":"/tmp/host-test/claude-home/.claude/projects/-tmp-host-test-claude-workspace/1689a5f8-6416-43f1-af26-2aef59604473.jsonl","cwd":"/tmp/host-test/claude-workspace","prompt_id":"25d4fdbe-964c-4b03-a159-fab0c77688cd","agent_id":"ab1d1508b1a46ca36","agent_type":"general-purpose","hook_event_name":"SubagentStart"}},"host":"claude","kind":"event","process":{"cwd":"/tmp/host-test/claude-workspace","entry":"/fast/projects/agent-bundle-worktrees/host-test/examples/host-test/artifact/claude/mcp/mcp-host-test-0d229f1b-flight.mjs","pid":1168277,"ppid":1167698},"recordedAt":"2026-09-03T09:35:25.249Z","request":{"host":{"source":"native","state":"available","value":{"name":"claude"}},"invocation":{"kind":"event"},"lineage":{"source":"derived","state":"available","value":{"conversation":"ab1d1508b1a46ca36","depth":2,"generation":"25d4fdbe-964c-4b03-a159-fab0c77688cd","parent":"aaf67c048de9cb68e","resolution":"registry","root":"1689a5f8-6416-43f1-af26-2aef59604473","subagent":{"id":"ab1d1508b1a46ca36","toolCallId":"toolu_mock_10","type":"general-purpose"}}},"session":{"source":"native","state":"available","value":{"sessionId":"1689a5f8-6416-43f1-af26-2aef59604473"}}},"runtime":"shared-runtime","sequence":22} +{"event":{"canonical":{"event":"tool/before","idempotencyKey":"09c1f69549f96601a4f4bf16abeac9b854198aafd5a574c8be5720102eb5aa04","observedAt":"2026-09-03T09:35:25.390Z","provenance":{"host":"claude","hostContractRevision":"2.1.250","nativeEvent":"PreToolUse","source":"native"},"sequence":21},"native":{"session_id":"1689a5f8-6416-43f1-af26-2aef59604473","transcript_path":"/tmp/host-test/claude-home/.claude/projects/-tmp-host-test-claude-workspace/1689a5f8-6416-43f1-af26-2aef59604473.jsonl","cwd":"/tmp/host-test/claude-workspace","prompt_id":"25d4fdbe-964c-4b03-a159-fab0c77688cd","permission_mode":"bypassPermissions","agent_id":"ab1d1508b1a46ca36","agent_type":"general-purpose","hook_event_name":"PreToolUse","tool_name":"Bash","tool_input":{"command":"pwd"},"tool_use_id":"toolu_mock_12"}},"host":"claude","kind":"event","process":{"cwd":"/tmp/host-test/claude-workspace","entry":"/fast/projects/agent-bundle-worktrees/host-test/examples/host-test/artifact/claude/mcp/mcp-host-test-0d229f1b-flight.mjs","pid":1168277,"ppid":1167698},"recordedAt":"2026-09-03T09:35:25.395Z","request":{"host":{"source":"native","state":"available","value":{"name":"claude"}},"invocation":{"kind":"event"},"lineage":{"source":"derived","state":"available","value":{"conversation":"ab1d1508b1a46ca36","depth":2,"generation":"25d4fdbe-964c-4b03-a159-fab0c77688cd","parent":"aaf67c048de9cb68e","resolution":"registry","root":"1689a5f8-6416-43f1-af26-2aef59604473","subagent":{"id":"ab1d1508b1a46ca36","toolCallId":"toolu_mock_10","type":"general-purpose"}}},"session":{"source":"native","state":"available","value":{"sessionId":"1689a5f8-6416-43f1-af26-2aef59604473"}}},"runtime":"shared-runtime","sequence":23} +{"event":{"canonical":{"event":"agent/stop","idempotencyKey":"c3cd2fe2bcbbd21f1281e3a4a15ba84e257153185785fc4709ea202f6a51d764","observedAt":"2026-09-03T09:35:25.394Z","provenance":{"host":"claude","hostContractRevision":"2.1.250","nativeEvent":"SubagentStop","source":"native"},"sequence":22},"native":{"session_id":"1689a5f8-6416-43f1-af26-2aef59604473","transcript_path":"/tmp/host-test/claude-home/.claude/projects/-tmp-host-test-claude-workspace/1689a5f8-6416-43f1-af26-2aef59604473.jsonl","cwd":"/tmp/host-test/claude-workspace","prompt_id":"25d4fdbe-964c-4b03-a159-fab0c77688cd","permission_mode":"bypassPermissions","agent_id":"aaf67c048de9cb68e","agent_type":"general-purpose","hook_event_name":"SubagentStop","stop_hook_active":false,"agent_transcript_path":"/tmp/host-test/claude-home/.claude/projects/-tmp-host-test-claude-workspace/1689a5f8-6416-43f1-af26-2aef59604473/subagents/agent-aaf67c048de9cb68e.jsonl","last_assistant_message":"SUBAGENT_DONE: reported every id from the dump and probe results above.","background_tasks":[{"id":"aaf67c048de9cb68e","type":"subagent","status":"running","description":"host-test subagent probe","agent_type":"general-purpose"},{"id":"ab1d1508b1a46ca36","type":"subagent","status":"running","description":"nested host-test probe","agent_type":"general-purpose"}],"session_crons":[]}},"host":"claude","kind":"event","process":{"cwd":"/tmp/host-test/claude-workspace","entry":"/fast/projects/agent-bundle-worktrees/host-test/examples/host-test/artifact/claude/mcp/mcp-host-test-0d229f1b-flight.mjs","pid":1168277,"ppid":1167698},"recordedAt":"2026-09-03T09:35:25.401Z","request":{"host":{"source":"native","state":"available","value":{"name":"claude"}},"invocation":{"kind":"event"},"lineage":{"source":"derived","state":"available","value":{"conversation":"aaf67c048de9cb68e","depth":1,"generation":"25d4fdbe-964c-4b03-a159-fab0c77688cd","parent":"1689a5f8-6416-43f1-af26-2aef59604473","resolution":"registry","root":"1689a5f8-6416-43f1-af26-2aef59604473","subagent":{"id":"aaf67c048de9cb68e","toolCallId":"toolu_mock_5","type":"general-purpose"}}},"session":{"source":"native","state":"available","value":{"sessionId":"1689a5f8-6416-43f1-af26-2aef59604473"}}},"runtime":"shared-runtime","sequence":24} +{"event":{"canonical":{"event":"tool/after","idempotencyKey":"f68fc17b8e46807bf3f96b54693d6971ccdaae9a8b187ae65f8150dc2fade735","observedAt":"2026-09-03T09:35:25.533Z","provenance":{"host":"claude","hostContractRevision":"2.1.250","nativeEvent":"PostToolUse","source":"native"},"sequence":23},"native":{"session_id":"1689a5f8-6416-43f1-af26-2aef59604473","transcript_path":"/tmp/host-test/claude-home/.claude/projects/-tmp-host-test-claude-workspace/1689a5f8-6416-43f1-af26-2aef59604473.jsonl","cwd":"/tmp/host-test/claude-workspace","prompt_id":"25d4fdbe-964c-4b03-a159-fab0c77688cd","permission_mode":"bypassPermissions","agent_id":"ab1d1508b1a46ca36","agent_type":"general-purpose","hook_event_name":"PostToolUse","tool_name":"Bash","tool_input":{"command":"pwd"},"tool_response":{"stdout":"/tmp/host-test/claude-workspace","stderr":"","interrupted":false,"isImage":false,"noOutputExpected":false},"tool_use_id":"toolu_mock_12","duration_ms":11}},"host":"claude","kind":"event","process":{"cwd":"/tmp/host-test/claude-workspace","entry":"/fast/projects/agent-bundle-worktrees/host-test/examples/host-test/artifact/claude/mcp/mcp-host-test-0d229f1b-flight.mjs","pid":1168277,"ppid":1167698},"recordedAt":"2026-09-03T09:35:25.538Z","request":{"host":{"source":"native","state":"available","value":{"name":"claude"}},"invocation":{"kind":"event"},"lineage":{"source":"derived","state":"available","value":{"conversation":"ab1d1508b1a46ca36","depth":2,"generation":"25d4fdbe-964c-4b03-a159-fab0c77688cd","parent":"aaf67c048de9cb68e","resolution":"registry","root":"1689a5f8-6416-43f1-af26-2aef59604473","subagent":{"id":"ab1d1508b1a46ca36","toolCallId":"toolu_mock_10","type":"general-purpose"}}},"session":{"source":"native","state":"available","value":{"sessionId":"1689a5f8-6416-43f1-af26-2aef59604473"}}},"runtime":"shared-runtime","sequence":25} +{"event":{"canonical":{"event":"prompt/submit","idempotencyKey":"c3bae4416e54fbf7275ec06088219899571056fc55d04acdedea29448a31892b","observedAt":"2026-09-03T09:35:25.591Z","provenance":{"host":"claude","hostContractRevision":"2.1.250","nativeEvent":"UserPromptSubmit","source":"native"},"sequence":24},"native":{"session_id":"1689a5f8-6416-43f1-af26-2aef59604473","transcript_path":"/tmp/host-test/claude-home/.claude/projects/-tmp-host-test-claude-workspace/1689a5f8-6416-43f1-af26-2aef59604473.jsonl","cwd":"/tmp/host-test/claude-workspace","prompt_id":"0dcc1f14-de66-4dea-a40c-010a29e1be1a","permission_mode":"bypassPermissions","hook_event_name":"UserPromptSubmit","prompt":"\naaf67c048de9cb68e\ntoolu_mock_5\n/tmp/claude-1000/-tmp-host-test-claude-workspace/1689a5f8-6416-43f1-af26-2aef59604473/task…[+556 chars]"}},"host":"claude","kind":"event","process":{"cwd":"/tmp/host-test/claude-workspace","entry":"/fast/projects/agent-bundle-worktrees/host-test/examples/host-test/artifact/claude/mcp/mcp-host-test-0d229f1b-flight.mjs","pid":1168277,"ppid":1167698},"recordedAt":"2026-09-03T09:35:25.593Z","request":{"host":{"source":"native","state":"available","value":{"name":"claude"}},"invocation":{"kind":"event"},"lineage":{"source":"native","state":"available","value":{"conversation":"1689a5f8-6416-43f1-af26-2aef59604473","depth":0,"generation":"0dcc1f14-de66-4dea-a40c-010a29e1be1a","resolution":"native","root":"1689a5f8-6416-43f1-af26-2aef59604473"}},"session":{"source":"native","state":"available","value":{"sessionId":"1689a5f8-6416-43f1-af26-2aef59604473"}}},"runtime":"shared-runtime","sequence":26} +{"event":{"canonical":{"event":"tool/before","idempotencyKey":"b1820da9b6771d7a98d6be1648cfa0854f493c697bf705fcf402e6e451128c5e","observedAt":"2026-09-03T09:35:25.671Z","provenance":{"host":"claude","hostContractRevision":"2.1.250","nativeEvent":"PreToolUse","source":"native"},"sequence":25},"native":{"session_id":"1689a5f8-6416-43f1-af26-2aef59604473","transcript_path":"/tmp/host-test/claude-home/.claude/projects/-tmp-host-test-claude-workspace/1689a5f8-6416-43f1-af26-2aef59604473.jsonl","cwd":"/tmp/host-test/claude-workspace","prompt_id":"0dcc1f14-de66-4dea-a40c-010a29e1be1a","permission_mode":"bypassPermissions","agent_id":"ab1d1508b1a46ca36","agent_type":"general-purpose","hook_event_name":"PreToolUse","tool_name":"mcp__plugin_host-test_host-test-raw__probe","tool_input":{"note":"nested"},"tool_use_id":"toolu_mock_13"}},"host":"claude","kind":"event","process":{"cwd":"/tmp/host-test/claude-workspace","entry":"/fast/projects/agent-bundle-worktrees/host-test/examples/host-test/artifact/claude/mcp/mcp-host-test-0d229f1b-flight.mjs","pid":1168277,"ppid":1167698},"recordedAt":"2026-09-03T09:35:25.676Z","request":{"host":{"source":"native","state":"available","value":{"name":"claude"}},"invocation":{"kind":"event"},"lineage":{"source":"derived","state":"available","value":{"conversation":"ab1d1508b1a46ca36","depth":2,"generation":"0dcc1f14-de66-4dea-a40c-010a29e1be1a","parent":"aaf67c048de9cb68e","resolution":"registry","root":"1689a5f8-6416-43f1-af26-2aef59604473","subagent":{"id":"ab1d1508b1a46ca36","toolCallId":"toolu_mock_10","type":"general-purpose"}}},"session":{"source":"native","state":"available","value":{"sessionId":"1689a5f8-6416-43f1-af26-2aef59604473"}}},"runtime":"shared-runtime","sequence":27} +{"host":"claude-code","kind":"mcp","observed":{"client":{"name":"claude-code","title":"Claude Code","version":"2.1.257","websiteUrl":"https://claude.com/claude-code","description":"Anthropic's agentic coding tool"},"clientCapabilities":{"elicitation":{"form":{}},"roots":{"listChanged":true}},"env":{"names":["AGENT_BUNDLE_PLUGIN_ROOT","ANTHROPIC_API_KEY","ANTHROPIC_BASE_URL","CLAUDE_CODE_DISABLE_NONESSENTIAL_TRAFFIC","CLAUDE_CODE_ENTRYPOINT","CLAUDE_CODE_MESSAGING_SOCKET","CLAUDE_CODE_MESSAGING_TOKEN","CLAUDE_CODE_SESSION_ID","CLAUDE_CONFIG_DIR","CLAUDE_PLUGIN_DATA","CLAUDE_PLUGIN_ROOT","CLAUDE_PROJECT_DIR","CURSOR_AGENT","CURSOR_CONVERSATION_ID","CURSOR_LAYOUT","CURSOR_REQUEST_ID","CURSOR_RIPGREP_PATH","HOST_TEST_LOG_DIR"]},"http":null,"mcpReq":{"_meta":{"progressToken":4,"claudecode/toolUseId":"toolu_mock_13"},"envelope":null,"id":4,"method":"tools/call"},"note":"nested","sessionId":null,"tool":"probe"},"process":{"cwd":"/tmp/host-test/claude-workspace","entry":"/fast/projects/agent-bundle-worktrees/host-test/examples/host-test/artifact/claude/mcp/mcp-host-test-raw-6e9c1a1c.mjs","pid":1168280,"ppid":1167698},"recordedAt":"2026-09-03T09:35:25.699Z","request":{"unavailable":"hand-rolled stdio server: no framework request context is mounted"},"runtime":"mcp-server","sequence":3} +{"event":{"canonical":{"event":"stop","idempotencyKey":"67f592f631ccda5a75743cbc04758212788a472544c077b23e9fc4965e529eae","observedAt":"2026-09-03T09:35:25.737Z","provenance":{"host":"claude","hostContractRevision":"2.1.250","nativeEvent":"Stop","source":"native"},"sequence":26},"native":{"session_id":"1689a5f8-6416-43f1-af26-2aef59604473","transcript_path":"/tmp/host-test/claude-home/.claude/projects/-tmp-host-test-claude-workspace/1689a5f8-6416-43f1-af26-2aef59604473.jsonl","cwd":"/tmp/host-test/claude-workspace","prompt_id":"0dcc1f14-de66-4dea-a40c-010a29e1be1a","permission_mode":"bypassPermissions","hook_event_name":"Stop","stop_hook_active":false,"last_assistant_message":"HOST_TEST_DONE (mock model; see the probe log path in the dump result)","background_tasks":[{"id":"ab1d1508b1a46ca36","type":"subagent","status":"running","description":"nested host-test probe","agent_type":"general-purpose"}],"session_crons":[]}},"host":"claude","kind":"event","process":{"cwd":"/tmp/host-test/claude-workspace","entry":"/fast/projects/agent-bundle-worktrees/host-test/examples/host-test/artifact/claude/mcp/mcp-host-test-0d229f1b-flight.mjs","pid":1168277,"ppid":1167698},"recordedAt":"2026-09-03T09:35:25.740Z","request":{"host":{"source":"native","state":"available","value":{"name":"claude"}},"invocation":{"kind":"event"},"lineage":{"source":"native","state":"available","value":{"conversation":"1689a5f8-6416-43f1-af26-2aef59604473","depth":0,"generation":"0dcc1f14-de66-4dea-a40c-010a29e1be1a","resolution":"native","root":"1689a5f8-6416-43f1-af26-2aef59604473"}},"session":{"source":"native","state":"available","value":{"sessionId":"1689a5f8-6416-43f1-af26-2aef59604473"}}},"runtime":"shared-runtime","sequence":28} +{"event":{"canonical":{"event":"tool/after","idempotencyKey":"f70d1df9a673ee3c9874215eaa89ad647896b8bfe63b2a97a1d1cbb4714e94ec","observedAt":"2026-09-03T09:35:25.808Z","provenance":{"host":"claude","hostContractRevision":"2.1.250","nativeEvent":"PostToolUse","source":"native"},"sequence":27},"native":{"session_id":"1689a5f8-6416-43f1-af26-2aef59604473","transcript_path":"/tmp/host-test/claude-home/.claude/projects/-tmp-host-test-claude-workspace/1689a5f8-6416-43f1-af26-2aef59604473.jsonl","cwd":"/tmp/host-test/claude-workspace","prompt_id":"0dcc1f14-de66-4dea-a40c-010a29e1be1a","permission_mode":"bypassPermissions","agent_id":"ab1d1508b1a46ca36","agent_type":"general-purpose","hook_event_name":"PostToolUse","tool_name":"mcp__plugin_host-test_host-test-raw__probe","tool_input":{"note":"nested"},"tool_response":"{\"log\":\"/tmp/host-test/claude/log/captures.ndjson\",\"observed\":{\"client\":{\"name\":\"claude-code\",\"title\":\"Claude Code\",\"version\":\"2.1.257\",\"websiteUrl\":\"https://claude.com/claude-code\",\"description\":\"Anthropic's agentic coding tool\"},\"clientCapabilities\":{\"elicitation\":{\"form\":{}},\"roots\":{\"listChanged\":true}},\"env\":{\"names\":[\"AGENT_BUNDLE_PLUGIN_ROOT\",\"ANTHROPIC_API_KEY\",\"ANTHROPIC_BASE_URL\",\"CLAUDE…[+547 chars]","tool_use_id":"toolu_mock_13","duration_ms":4}},"host":"claude","kind":"event","process":{"cwd":"/tmp/host-test/claude-workspace","entry":"/fast/projects/agent-bundle-worktrees/host-test/examples/host-test/artifact/claude/mcp/mcp-host-test-0d229f1b-flight.mjs","pid":1168277,"ppid":1167698},"recordedAt":"2026-09-03T09:35:25.818Z","request":{"host":{"source":"native","state":"available","value":{"name":"claude"}},"invocation":{"kind":"event"},"lineage":{"source":"derived","state":"available","value":{"conversation":"ab1d1508b1a46ca36","depth":2,"generation":"0dcc1f14-de66-4dea-a40c-010a29e1be1a","parent":"aaf67c048de9cb68e","resolution":"registry","root":"1689a5f8-6416-43f1-af26-2aef59604473","subagent":{"id":"ab1d1508b1a46ca36","toolCallId":"toolu_mock_10","type":"general-purpose"}}},"session":{"source":"native","state":"available","value":{"sessionId":"1689a5f8-6416-43f1-af26-2aef59604473"}}},"runtime":"shared-runtime","sequence":29} +{"event":{"canonical":{"event":"agent/stop","idempotencyKey":"5bdea2b9e4fd47a0f1b4d26557881ef3235779dc8b30ffed863779f4fed1dd90","observedAt":"2026-09-03T09:35:25.967Z","provenance":{"host":"claude","hostContractRevision":"2.1.250","nativeEvent":"SubagentStop","source":"native"},"sequence":28},"native":{"session_id":"1689a5f8-6416-43f1-af26-2aef59604473","transcript_path":"/tmp/host-test/claude-home/.claude/projects/-tmp-host-test-claude-workspace/1689a5f8-6416-43f1-af26-2aef59604473.jsonl","cwd":"/tmp/host-test/claude-workspace","prompt_id":"0dcc1f14-de66-4dea-a40c-010a29e1be1a","permission_mode":"bypassPermissions","agent_id":"ab1d1508b1a46ca36","agent_type":"general-purpose","hook_event_name":"SubagentStop","stop_hook_active":false,"agent_transcript_path":"/tmp/host-test/claude-home/.claude/projects/-tmp-host-test-claude-workspace/1689a5f8-6416-43f1-af26-2aef59604473/subagents/agent-ab1d1508b1a46ca36.jsonl","last_assistant_message":"NESTED_DONE: reported every id from the probe result above.","background_tasks":[{"id":"ab1d1508b1a46ca36","type":"subagent","status":"running","description":"nested host-test probe","agent_type":"general-purpose"}],"session_crons":[]}},"host":"claude","kind":"event","process":{"cwd":"/tmp/host-test/claude-workspace","entry":"/fast/projects/agent-bundle-worktrees/host-test/examples/host-test/artifact/claude/mcp/mcp-host-test-0d229f1b-flight.mjs","pid":1168277,"ppid":1167698},"recordedAt":"2026-09-03T09:35:25.972Z","request":{"host":{"source":"native","state":"available","value":{"name":"claude"}},"invocation":{"kind":"event"},"lineage":{"source":"derived","state":"available","value":{"conversation":"ab1d1508b1a46ca36","depth":2,"generation":"0dcc1f14-de66-4dea-a40c-010a29e1be1a","parent":"aaf67c048de9cb68e","resolution":"registry","root":"1689a5f8-6416-43f1-af26-2aef59604473","subagent":{"id":"ab1d1508b1a46ca36","toolCallId":"toolu_mock_10","type":"general-purpose"}}},"session":{"source":"native","state":"available","value":{"sessionId":"1689a5f8-6416-43f1-af26-2aef59604473"}}},"runtime":"shared-runtime","sequence":30} +{"event":{"canonical":{"event":"prompt/submit","idempotencyKey":"7dd7e02081fdd22453fc2bb0cb59cfa938e42d2d470519b0333770bb730435fe","observedAt":"2026-09-03T09:35:26.169Z","provenance":{"host":"claude","hostContractRevision":"2.1.250","nativeEvent":"UserPromptSubmit","source":"native"},"sequence":29},"native":{"session_id":"1689a5f8-6416-43f1-af26-2aef59604473","transcript_path":"/tmp/host-test/claude-home/.claude/projects/-tmp-host-test-claude-workspace/1689a5f8-6416-43f1-af26-2aef59604473.jsonl","cwd":"/tmp/host-test/claude-workspace","prompt_id":"fa9ba393-9ddf-4af8-8488-b3648ab2eda1","permission_mode":"bypassPermissions","hook_event_name":"UserPromptSubmit","prompt":"\nab1d1508b1a46ca36\ntoolu_mock_10\n/tmp/claude-1000/-tmp-host-test-claude-workspace/1689a5f8-6416-43f1-af26-2aef59604473/tas…[+542 chars]"}},"host":"claude","kind":"event","process":{"cwd":"/tmp/host-test/claude-workspace","entry":"/fast/projects/agent-bundle-worktrees/host-test/examples/host-test/artifact/claude/mcp/mcp-host-test-0d229f1b-flight.mjs","pid":1168277,"ppid":1167698},"recordedAt":"2026-09-03T09:35:26.172Z","request":{"host":{"source":"native","state":"available","value":{"name":"claude"}},"invocation":{"kind":"event"},"lineage":{"source":"native","state":"available","value":{"conversation":"1689a5f8-6416-43f1-af26-2aef59604473","depth":0,"generation":"fa9ba393-9ddf-4af8-8488-b3648ab2eda1","resolution":"native","root":"1689a5f8-6416-43f1-af26-2aef59604473"}},"session":{"source":"native","state":"available","value":{"sessionId":"1689a5f8-6416-43f1-af26-2aef59604473"}}},"runtime":"shared-runtime","sequence":31} +{"event":{"canonical":{"event":"stop","idempotencyKey":"4eb30cbb2e3b7fd839c51ce479924021fa262f2f1e243431150333ef66b00706","observedAt":"2026-09-03T09:35:26.303Z","provenance":{"host":"claude","hostContractRevision":"2.1.250","nativeEvent":"Stop","source":"native"},"sequence":30},"native":{"session_id":"1689a5f8-6416-43f1-af26-2aef59604473","transcript_path":"/tmp/host-test/claude-home/.claude/projects/-tmp-host-test-claude-workspace/1689a5f8-6416-43f1-af26-2aef59604473.jsonl","cwd":"/tmp/host-test/claude-workspace","prompt_id":"fa9ba393-9ddf-4af8-8488-b3648ab2eda1","permission_mode":"bypassPermissions","hook_event_name":"Stop","stop_hook_active":false,"last_assistant_message":"HOST_TEST_DONE (mock model; see the probe log path in the dump result)","background_tasks":[],"session_crons":[]}},"host":"claude","kind":"event","process":{"cwd":"/tmp/host-test/claude-workspace","entry":"/fast/projects/agent-bundle-worktrees/host-test/examples/host-test/artifact/claude/mcp/mcp-host-test-0d229f1b-flight.mjs","pid":1168277,"ppid":1167698},"recordedAt":"2026-09-03T09:35:26.306Z","request":{"host":{"source":"native","state":"available","value":{"name":"claude"}},"invocation":{"kind":"event"},"lineage":{"source":"native","state":"available","value":{"conversation":"1689a5f8-6416-43f1-af26-2aef59604473","depth":0,"generation":"fa9ba393-9ddf-4af8-8488-b3648ab2eda1","resolution":"native","root":"1689a5f8-6416-43f1-af26-2aef59604473"}},"session":{"source":"native","state":"available","value":{"sessionId":"1689a5f8-6416-43f1-af26-2aef59604473"}}},"runtime":"shared-runtime","sequence":32} +{"event":{"canonical":{"event":"session/end","idempotencyKey":"fcc36d9c1ce9561cfdea5f547f4861ed946ee22046d5d69ce01b3e755c541194","observedAt":"2026-09-03T09:35:26.483Z","provenance":{"host":"claude","hostContractRevision":"2.1.250","nativeEvent":"SessionEnd","source":"native"},"sequence":1},"native":{"session_id":"1689a5f8-6416-43f1-af26-2aef59604473","transcript_path":"/tmp/host-test/claude-home/.claude/projects/-tmp-host-test-claude-workspace/1689a5f8-6416-43f1-af26-2aef59604473.jsonl","cwd":"/tmp/host-test/claude-workspace","prompt_id":"fa9ba393-9ddf-4af8-8488-b3648ab2eda1","hook_event_name":"SessionEnd","reason":"other"}},"host":"claude","kind":"event","process":{"cwd":"/tmp/host-test/claude-workspace","entry":"/fast/projects/agent-bundle-worktrees/host-test/examples/host-test/artifact/claude/hooks/hooks-flight.mjs","pid":1177802,"ppid":1177800},"recordedAt":"2026-09-03T09:35:26.701Z","request":{"host":{"source":"native","state":"available","value":{"name":"claude"}},"invocation":{"kind":"event"},"lineage":{"source":"native","state":"available","value":{"conversation":"1689a5f8-6416-43f1-af26-2aef59604473","depth":0,"generation":"fa9ba393-9ddf-4af8-8488-b3648ab2eda1","resolution":"native","root":"1689a5f8-6416-43f1-af26-2aef59604473"}},"session":{"source":"native","state":"available","value":{"sessionId":"1689a5f8-6416-43f1-af26-2aef59604473"}}},"runtime":"standalone-hook","sequence":1} diff --git a/packages/agent-bundle/src/adapters/hook-contract.ts b/packages/agent-bundle/src/adapters/hook-contract.ts index da657ce7a..df8a2f960 100644 --- a/packages/agent-bundle/src/adapters/hook-contract.ts +++ b/packages/agent-bundle/src/adapters/hook-contract.ts @@ -1252,8 +1252,8 @@ export const nativeHookWrapperSource = ( ' else if (!isRecord(input.tool_input)) fail(`native ${nativeEvent} tool_input must be an object`);', ' requireString(input, "tool_use_id");', ' if (canonicalEvent === "afterTool") {', - ' if (target === "codex") { if (input.tool_response === undefined) fail("native PostToolUse tool_response is required"); }', - ' else if (typeof input.tool_response !== "object" || input.tool_response === null) fail("native PostToolUse tool_response must be an object or an array");', + // Claude delivers an MCP tool's PostToolUse tool_response as a plain string (2.1.257, 2026-09-03), so presence is the only host-independent rule. + ' if (input.tool_response === undefined) fail("native PostToolUse tool_response is required");', ' }', ' return;', ' }', diff --git a/packages/agent-bundle/src/events/projection.ts b/packages/agent-bundle/src/events/projection.ts index 010e7948c..ce7f1d8e9 100644 --- a/packages/agent-bundle/src/events/projection.ts +++ b/packages/agent-bundle/src/events/projection.ts @@ -338,15 +338,13 @@ export const validateNativeEventEnvelope = ( } requireNativeString(native, 'tool_use_id'); if (canonicalEvent === 'tool/after') { - if (target === 'codex') { - if (!Object.hasOwn(native, 'tool_response') || native.tool_response === undefined) { - return nativeEventError('native tool_response is required'); - } - } else if (typeof native.tool_response !== 'object' || native.tool_response === null) { - // Claude documents `tool_response` as an object, but PostToolUse for an - // MCP tool delivers the tool's content-block array (observed on Claude - // Code 2.1.257, docs/audits/2026-09-03-host-lineage-matrix.md §3). - return nativeEventError('native tool_response must be an object or an array'); + // Codex pins tool_response as any JSON value. Claude documents an object + // for built-in tools but delivers the tool's text as a plain string for + // MCP tools (observed on Claude Code 2.1.257, + // docs/audits/2026-09-03-host-lineage-matrix.md §3), so presence is the + // only host-independent guarantee. + if (!Object.hasOwn(native, 'tool_response') || native.tool_response === undefined) { + return nativeEventError('native tool_response is required'); } } } diff --git a/packages/agent-bundle/tests/event-project.test.ts b/packages/agent-bundle/tests/event-project.test.ts index 8dbb4a56d..7bb13defb 100644 --- a/packages/agent-bundle/tests/event-project.test.ts +++ b/packages/agent-bundle/tests/event-project.test.ts @@ -39,11 +39,12 @@ it('validates native event envelopes with the generated wrapper error contract', }; expect(validateNativeEventEnvelope(valid, options)).toBe(valid); - expect(() => validateNativeEventEnvelope({ ...valid, tool_response: 'not-an-object' }, options)) - .toThrow('Agent Bundle event route error: native tool_response must be an object or an array'); - // Claude Code 2.1.257 delivers MCP tool results as a content-block array (2026-09-03 capture). - expect(validateNativeEventEnvelope({ ...valid, tool_response: [{ text: 'ok', type: 'text' }] }, options)) - .toMatchObject({ tool_response: [{ text: 'ok', type: 'text' }] }); + const { tool_response: _omitted, ...withoutResponse } = valid; + expect(() => validateNativeEventEnvelope(withoutResponse, options)) + .toThrow('Agent Bundle event route error: native tool_response is required'); + // Claude Code 2.1.257 delivers an MCP tool's result as a plain string (2026-09-03 capture). + expect(validateNativeEventEnvelope({ ...valid, tool_response: '{"ok":true}' }, options)) + .toMatchObject({ tool_response: '{"ok":true}' }); expect(() => validateNativeEventEnvelope({ ...valid, hook_event_name: 'BeforeToolUse' }, options)) .toThrow('Agent Bundle event route error: native hook_event_name must equal PostToolUse'); expect(() => validateNativeEventEnvelope([], options)) diff --git a/packages/agent-bundle/tests/hooks.test.ts b/packages/agent-bundle/tests/hooks.test.ts index ee61af15c..95b718a76 100644 --- a/packages/agent-bundle/tests/hooks.test.ts +++ b/packages/agent-bundle/tests/hooks.test.ts @@ -1412,7 +1412,7 @@ it('rejects malformed event-specific native input before calling generated Codex // Codex pins tool_input/tool_response as any JSON value (presence only); // Claude documents both as objects. const toolInputError = target === 'codex' ? 'tool_input is required' : 'tool_input must be an object'; - const toolResponseError = target === 'codex' ? 'tool_response is required' : 'tool_response must be an object or an array'; + const toolResponseError = 'tool_response is required'; await expect(runNativeHook(join(hooksRoot, 'before-tool-check-command-1f5b5818.mjs'), { ...common, hook_event_name: 'PreToolUse', tool_name: 'Bash', tool_use_id: 'use-1', ...(target === 'codex' ? {} : { tool_input: [] }), @@ -1423,7 +1423,6 @@ it('rejects malformed event-specific native input before calling generated Codex }); await expect(runNativeHook(join(hooksRoot, 'after-tool-record-87785f02.mjs'), { ...common, hook_event_name: 'PostToolUse', tool_input: {}, tool_name: 'Write', tool_use_id: 'use-2', - ...(target === 'codex' ? {} : { tool_response: 'observed' }), })).resolves.toEqual({ code: 1, stderr: `Agent Bundle hook error: native PostToolUse ${toolResponseError}\n`, diff --git a/packages/agent-bundle/tests/lifecycle-replay-routes.test.ts b/packages/agent-bundle/tests/lifecycle-replay-routes.test.ts index a6bb09391..5a05386b4 100644 --- a/packages/agent-bundle/tests/lifecycle-replay-routes.test.ts +++ b/packages/agent-bundle/tests/lifecycle-replay-routes.test.ts @@ -166,7 +166,6 @@ it('preserves stale and real native-envelope diagnostics at the HTTP boundary', session_id: 'session-1', tool_input: {}, tool_name: 'Write', - tool_response: 'invalid', tool_use_id: 'tool-1', transcript_path: '/tmp/lifecycle-replay/transcript.jsonl', }, @@ -176,7 +175,7 @@ it('preserves stale and real native-envelope diagnostics at the HTTP boundary', await expect(malformed.json()).resolves.toEqual({ diagnostic: { code: 'AB8211', - message: 'Agent Bundle event route error: native tool_response must be an object or an array', + message: 'Agent Bundle event route error: native tool_response is required', }, }); diff --git a/packages/agent-bundle/tests/lifecycle-replay-service.test.ts b/packages/agent-bundle/tests/lifecycle-replay-service.test.ts index 68108df56..ab56b1558 100644 --- a/packages/agent-bundle/tests/lifecycle-replay-service.test.ts +++ b/packages/agent-bundle/tests/lifecycle-replay-service.test.ts @@ -149,14 +149,13 @@ it('surfaces the real native envelope validator message as a malformed request', session_id: 'session-1', tool_input: {}, tool_name: 'Write', - tool_response: 'invalid', tool_use_id: 'tool-1', transcript_path: '/tmp/lifecycle-replay/transcript.jsonl', }, source: 'observed', })).rejects.toMatchObject({ code: 'AB8211', - message: 'Agent Bundle event route error: native tool_response must be an object or an array', + message: 'Agent Bundle event route error: native tool_response is required', status: 400, }); }); diff --git a/packages/rsc-runtime/tests/lineage-registry.test.ts b/packages/rsc-runtime/tests/lineage-registry.test.ts index 8fdde7d21..ff0f4cfc4 100644 --- a/packages/rsc-runtime/tests/lineage-registry.test.ts +++ b/packages/rsc-runtime/tests/lineage-registry.test.ts @@ -65,8 +65,15 @@ const value = (observed: Awaited>) = describe('lineage registry replaying the 2026-09-03 host captures', () => { it('Claude 2.1.257: subagent events resolve to their own agent under the root session, nested depth 2, parent inferred from the open Agent call', async () => { const registry = createAgentLineageRegistry(); - const lineages = await replay('claude', fixture('claude-2.1.257.ndjson'), registry); - const root = 'a7f96472-e9d0-447a-826d-36da9b635fd6'; + const records = fixture('claude-2.1.257.ndjson'); + const lineages = await replay('claude', records, registry); + const root = records[0]!.event!.native['session_id'] as string; + const [subagent, nested] = records + .filter((record) => record.event?.canonical.event === 'agent/start') + .map((record) => record.event!.native['agent_id'] as string); + const spawnCalls = records + .filter((record) => record.event?.canonical.event === 'tool/before' && record.event.native['tool_name'] === 'Agent') + .map((record) => record.event!.native['tool_use_id'] as string); const sessionStart = value(lineages[0]!.lineage); expect(sessionStart).toMatchObject({ conversation: root, depth: 0, resolution: 'native', root }); @@ -74,34 +81,36 @@ describe('lineage registry replaying the 2026-09-03 host captures', () => { const subagentStart = lineages.find((entry) => entry.kind === 'agent/start')!; expect(value(subagentStart.lineage)).toMatchObject({ - conversation: 'aca96ce761c9f0cea', + conversation: subagent, depth: 1, parent: root, resolution: 'registry', root, - subagent: { id: 'aca96ce761c9f0cea', toolCallId: 'toolu_mock_5', type: 'general-purpose' }, + subagent: { id: subagent, toolCallId: spawnCalls[0], type: 'general-purpose' }, }); const nestedStart = lineages.filter((entry) => entry.kind === 'agent/start')[1]!; expect(value(nestedStart.lineage)).toMatchObject({ - conversation: 'ac093bdad0566ffa7', + conversation: nested, depth: 2, - parent: 'aca96ce761c9f0cea', + parent: subagent, root, - subagent: { toolCallId: 'toolu_mock_10' }, + subagent: { toolCallId: spawnCalls[1] }, }); - const nestedTool = lineages.find((entry) => entry.kind === 'tool/before' && entry.native?.['agent_id'] === 'ac093bdad0566ffa7')!; - expect(value(nestedTool.lineage)).toMatchObject({ conversation: 'ac093bdad0566ffa7', depth: 2, parent: 'aca96ce761c9f0cea', root }); + const nestedTool = lineages.find((entry) => entry.kind === 'tool/before' && entry.native?.['agent_id'] === nested)!; + expect(value(nestedTool.lineage)).toMatchObject({ conversation: nested, depth: 2, parent: subagent, root }); // The MCP probe call carries claudecode/toolUseId, which names the open PreToolUse. const probes = lineages.filter((entry) => entry.kind === 'mcp:probe'); expect(probes.map((entry) => value(entry.lineage).depth)).toEqual([0, 1, 2]); - expect(value(probes[1]!.lineage)).toMatchObject({ conversation: 'aca96ce761c9f0cea', resolution: 'registry' }); + expect(value(probes[1]!.lineage)).toMatchObject({ conversation: subagent, resolution: 'registry' }); + // PostToolUse for MCP tools now arrives (string tool_response), so every window closes. + expect(registry.snapshot().openCalls).toEqual([]); const snapshot = registry.snapshot(); expect(Object.values(snapshot.nodes).filter((node) => node.stoppedAt !== undefined).map((node) => node.id).sort()) - .toEqual(['ac093bdad0566ffa7', 'aca96ce761c9f0cea']); + .toEqual([nested, subagent].sort()); }); it('Codex 0.147.0: MCP _meta resolves lineage natively including parent_thread_id; hooks agree', async () => { @@ -169,16 +178,20 @@ describe('lineage registry replaying the 2026-09-03 host captures', () => { const driver = createMemoryStateDriver({ lifetime: 'process' }); const definition = agentLineageStateDefinition('process'); const store = await driver.open(definition); + const records = fixture('claude-2.1.257.ndjson'); + const root = records[0]!.event!.native['session_id'] as string; + const firstStart = records.findIndex((record) => record.event?.canonical.event === 'agent/start'); + const subagent = records[firstStart]!.event!.native['agent_id'] as string; const first = createAgentLineageRegistry({ store }); - await replay('claude', fixture('claude-2.1.257.ndjson').slice(0, 12), first); + await replay('claude', records.slice(0, firstStart + 1), first); const second = createAgentLineageRegistry({ store }); const lineage = await second.observe({ event: 'tool/before', host: 'claude', idempotencyKey: 'rehydrated', - native: { agent_id: 'aca96ce761c9f0cea', hook_event_name: 'PreToolUse', session_id: 'a7f96472-e9d0-447a-826d-36da9b635fd6', tool_name: 'Bash', tool_use_id: 'later' }, + native: { agent_id: subagent, hook_event_name: 'PreToolUse', session_id: root, tool_name: 'Bash', tool_use_id: 'later' }, }); - expect(value(lineage)).toMatchObject({ conversation: 'aca96ce761c9f0cea', depth: 1, parent: 'a7f96472-e9d0-447a-826d-36da9b635fd6' }); + expect(value(lineage)).toMatchObject({ conversation: subagent, depth: 1, parent: root }); await store.close(); await driver.close(); }); diff --git a/packages/workbench/tests/lifecycles.e2e.test.ts b/packages/workbench/tests/lifecycles.e2e.test.ts index 3c81c9c8c..dad836edc 100644 --- a/packages/workbench/tests/lifecycles.e2e.test.ts +++ b/packages/workbench/tests/lifecycles.e2e.test.ts @@ -87,6 +87,13 @@ e2e( await expect(requestContext).toContainText('lifecycle-observed · receipt'); await expect(requestContext).toContainText('/tmp · receipt'); await expect(requestContext).toContainText('Unavailable · not-provided'); + // A root Claude receipt proves its own depth-0 lineage; the chain renders the single root node. + await expect(requestContext).toContainText('lifecycle-observed · depth 0 · native · receipt'); + const lineage = page.locator('.lifecycle-detail').filter({ + has: page.getByRole('heading', { name: 'Conversation lineage' }), + }); + await expect(lineage.locator('.lifecycle-lineage-node--current')).toContainText('lifecycle-observed'); + await expect(lineage.locator('.lifecycle-lineage-node--current')).toContainText('this request'); const sessionToken = await page.evaluate(async () => { const response = await fetch('/api/project/session', { credentials: 'same-origin' }); From 5cfcacdc570a6a722dcc57a983273a28ef9b4c0b Mon Sep 17 00:00:00 2001 From: ScriptedAlchemy Date: Thu, 3 Sep 2026 09:43:18 +0000 Subject: [PATCH 03/20] fix(build): journal lineage through sqlite only for workspace-durable projects; drop accidentally committed example artifacts Stateless and volatile projects keep a process-lifetime registry so node:sqlite never loads for them and no state/ directory appears inside an artifact that declared none (AB6014 in dev adoption). examples:check builds every example in place, so their artifact outputs are ignored like the others. --- .../artifact/agent-bundle.hooks.json | 1 - .../artifact/agent-bundle.manifest.json | 1 - .../claude/.claude-plugin/marketplace.json | 1 - .../claude/.claude-plugin/plugin.json | 1 - .../artifact/claude/INSTALL.md | 18 - .../assets/release/release-manifest.json | 21 - .../claude/assets/release/risk-register.json | 16 - .../artifact/claude/hooks/hooks.json | 1 - .../session-start-session-start-7ab7e8a5.mjs | 253 - .../claude/scripts/verify-release.mjs | 54 - .../codex/.agents/plugins/marketplace.json | 1 - .../artifact/codex/.codex-plugin/plugin.json | 1 - .../artifact/codex/INSTALL.md | 16 - .../assets/release/release-manifest.json | 21 - .../codex/assets/release/risk-register.json | 16 - .../artifact/codex/hooks/hooks.json | 1 - .../session-start-session-start-7ab7e8a5.mjs | 258 - .../artifact/codex/scripts/verify-release.mjs | 54 - .../artifact/portable/INSTALL.md | 19 - .../assets/release/release-manifest.json | 21 - .../assets/release/risk-register.json | 16 - .../artifact/portable/install.mjs | 80 - .../artifact/portable/plugin.json | 1 - .../artifact/portable/scripts/detect-risk.mjs | 35 - .../portable/scripts/verify-release.mjs | 54 - .../mcp-app/artifact/agent-bundle.hooks.json | 1 - .../artifact/agent-bundle.manifest.json | 1 - .../claude/.claude-plugin/marketplace.json | 1 - .../claude/.claude-plugin/plugin.json | 1 - examples/mcp-app/artifact/claude/.mcp.json | 1 - examples/mcp-app/artifact/claude/INSTALL.md | 18 - .../assets/evals/fixtures/status/result.json | 9 - .../mcp-app/artifact/claude/hooks/hooks.json | 1 - .../session-start-session-start-7ab7e8a5.mjs | 253 - .../claude/mcp/mcp-status-073c1634.mjs | 30761 --------------- .../claude/scripts/check-service-fixture.mjs | 60 - .../claude/skills/service-readiness/SKILL.md | 33 - .../assets/readiness-report.md | 22 - .../references/status-policy.md | 22 - .../codex/.agents/plugins/marketplace.json | 1 - .../artifact/codex/.codex-plugin/plugin.json | 1 - examples/mcp-app/artifact/codex/.mcp.json | 1 - examples/mcp-app/artifact/codex/INSTALL.md | 16 - .../assets/evals/fixtures/status/result.json | 9 - .../mcp-app/artifact/codex/hooks/hooks.json | 1 - .../session-start-session-start-7ab7e8a5.mjs | 258 - .../codex/mcp/mcp-status-073c1634.mjs | 30761 --------------- .../codex/scripts/check-service-fixture.mjs | 60 - .../codex/skills/service-readiness/SKILL.md | 33 - .../assets/readiness-report.md | 22 - .../references/status-policy.md | 22 - examples/mcp-app/artifact/portable/INSTALL.md | 19 - .../assets/evals/fixtures/status/result.json | 9 - .../mcp-app/artifact/portable/install.mjs | 80 - .../artifact/portable/mcp-apps/status.html | 154 - examples/mcp-app/artifact/portable/mcp.json | 1 - .../portable/mcp/mcp-status-073c1634.mjs | 30768 ---------------- .../mcp-app/artifact/portable/plugin.json | 1 - .../scripts/check-service-fixture.mjs | 60 - .../skills/service-readiness/SKILL.md | 33 - .../assets/readiness-report.md | 22 - .../references/status-policy.md | 22 - .../agent-bundle/src/build/entry-shell.ts | 54 +- .../agent-bundle/tests/entry-shell.test.ts | 32 +- .../rsc-runtime/tests/state-packaging.test.ts | 1 + 65 files changed, 66 insertions(+), 94520 deletions(-) delete mode 100644 examples/hooks-and-scripts/artifact/agent-bundle.hooks.json delete mode 100644 examples/hooks-and-scripts/artifact/agent-bundle.manifest.json delete mode 100644 examples/hooks-and-scripts/artifact/claude/.claude-plugin/marketplace.json delete mode 100644 examples/hooks-and-scripts/artifact/claude/.claude-plugin/plugin.json delete mode 100644 examples/hooks-and-scripts/artifact/claude/INSTALL.md delete mode 100644 examples/hooks-and-scripts/artifact/claude/assets/release/release-manifest.json delete mode 100644 examples/hooks-and-scripts/artifact/claude/assets/release/risk-register.json delete mode 100644 examples/hooks-and-scripts/artifact/claude/hooks/hooks.json delete mode 100644 examples/hooks-and-scripts/artifact/claude/hooks/session-start-session-start-7ab7e8a5.mjs delete mode 100644 examples/hooks-and-scripts/artifact/claude/scripts/verify-release.mjs delete mode 100644 examples/hooks-and-scripts/artifact/codex/.agents/plugins/marketplace.json delete mode 100644 examples/hooks-and-scripts/artifact/codex/.codex-plugin/plugin.json delete mode 100644 examples/hooks-and-scripts/artifact/codex/INSTALL.md delete mode 100644 examples/hooks-and-scripts/artifact/codex/assets/release/release-manifest.json delete mode 100644 examples/hooks-and-scripts/artifact/codex/assets/release/risk-register.json delete mode 100644 examples/hooks-and-scripts/artifact/codex/hooks/hooks.json delete mode 100644 examples/hooks-and-scripts/artifact/codex/hooks/session-start-session-start-7ab7e8a5.mjs delete mode 100644 examples/hooks-and-scripts/artifact/codex/scripts/verify-release.mjs delete mode 100644 examples/hooks-and-scripts/artifact/portable/INSTALL.md delete mode 100644 examples/hooks-and-scripts/artifact/portable/assets/release/release-manifest.json delete mode 100644 examples/hooks-and-scripts/artifact/portable/assets/release/risk-register.json delete mode 100644 examples/hooks-and-scripts/artifact/portable/install.mjs delete mode 100644 examples/hooks-and-scripts/artifact/portable/plugin.json delete mode 100644 examples/hooks-and-scripts/artifact/portable/scripts/detect-risk.mjs delete mode 100644 examples/hooks-and-scripts/artifact/portable/scripts/verify-release.mjs delete mode 100644 examples/mcp-app/artifact/agent-bundle.hooks.json delete mode 100644 examples/mcp-app/artifact/agent-bundle.manifest.json delete mode 100644 examples/mcp-app/artifact/claude/.claude-plugin/marketplace.json delete mode 100644 examples/mcp-app/artifact/claude/.claude-plugin/plugin.json delete mode 100644 examples/mcp-app/artifact/claude/.mcp.json delete mode 100644 examples/mcp-app/artifact/claude/INSTALL.md delete mode 100644 examples/mcp-app/artifact/claude/assets/evals/fixtures/status/result.json delete mode 100644 examples/mcp-app/artifact/claude/hooks/hooks.json delete mode 100644 examples/mcp-app/artifact/claude/hooks/session-start-session-start-7ab7e8a5.mjs delete mode 100644 examples/mcp-app/artifact/claude/mcp/mcp-status-073c1634.mjs delete mode 100644 examples/mcp-app/artifact/claude/scripts/check-service-fixture.mjs delete mode 100644 examples/mcp-app/artifact/claude/skills/service-readiness/SKILL.md delete mode 100644 examples/mcp-app/artifact/claude/skills/service-readiness/assets/readiness-report.md delete mode 100644 examples/mcp-app/artifact/claude/skills/service-readiness/references/status-policy.md delete mode 100644 examples/mcp-app/artifact/codex/.agents/plugins/marketplace.json delete mode 100644 examples/mcp-app/artifact/codex/.codex-plugin/plugin.json delete mode 100644 examples/mcp-app/artifact/codex/.mcp.json delete mode 100644 examples/mcp-app/artifact/codex/INSTALL.md delete mode 100644 examples/mcp-app/artifact/codex/assets/evals/fixtures/status/result.json delete mode 100644 examples/mcp-app/artifact/codex/hooks/hooks.json delete mode 100644 examples/mcp-app/artifact/codex/hooks/session-start-session-start-7ab7e8a5.mjs delete mode 100644 examples/mcp-app/artifact/codex/mcp/mcp-status-073c1634.mjs delete mode 100644 examples/mcp-app/artifact/codex/scripts/check-service-fixture.mjs delete mode 100644 examples/mcp-app/artifact/codex/skills/service-readiness/SKILL.md delete mode 100644 examples/mcp-app/artifact/codex/skills/service-readiness/assets/readiness-report.md delete mode 100644 examples/mcp-app/artifact/codex/skills/service-readiness/references/status-policy.md delete mode 100644 examples/mcp-app/artifact/portable/INSTALL.md delete mode 100644 examples/mcp-app/artifact/portable/assets/evals/fixtures/status/result.json delete mode 100644 examples/mcp-app/artifact/portable/install.mjs delete mode 100644 examples/mcp-app/artifact/portable/mcp-apps/status.html delete mode 100644 examples/mcp-app/artifact/portable/mcp.json delete mode 100644 examples/mcp-app/artifact/portable/mcp/mcp-status-073c1634.mjs delete mode 100644 examples/mcp-app/artifact/portable/plugin.json delete mode 100644 examples/mcp-app/artifact/portable/scripts/check-service-fixture.mjs delete mode 100644 examples/mcp-app/artifact/portable/skills/service-readiness/SKILL.md delete mode 100644 examples/mcp-app/artifact/portable/skills/service-readiness/assets/readiness-report.md delete mode 100644 examples/mcp-app/artifact/portable/skills/service-readiness/references/status-policy.md diff --git a/examples/hooks-and-scripts/artifact/agent-bundle.hooks.json b/examples/hooks-and-scripts/artifact/agent-bundle.hooks.json deleted file mode 100644 index c41cd4504..000000000 --- a/examples/hooks-and-scripts/artifact/agent-bundle.hooks.json +++ /dev/null @@ -1 +0,0 @@ -{"hooks":[{"event":"sessionStart","id":"hook:session-start:session-start:7ab7e8a5","name":"session-start-session-start-7ab7e8a5","path":"claude/hooks/session-start-session-start-7ab7e8a5.mjs","target":"claude"},{"event":"sessionStart","id":"hook:session-start:session-start:7ab7e8a5","name":"session-start-session-start-7ab7e8a5","path":"codex/hooks/session-start-session-start-7ab7e8a5.mjs","target":"codex"}]} diff --git a/examples/hooks-and-scripts/artifact/agent-bundle.manifest.json b/examples/hooks-and-scripts/artifact/agent-bundle.manifest.json deleted file mode 100644 index 9fba35420..000000000 --- a/examples/hooks-and-scripts/artifact/agent-bundle.manifest.json +++ /dev/null @@ -1 +0,0 @@ -{"agentSkills":{"schemaSha256":"6d06b61e423317421de2295ea1fd0c7b4491bfa36c5b7705c28616dfe76d4047","sourceRevision":"69ef37e9424c0a7ea9dd2293b559e43ec8176379","specification":"https://raw.githubusercontent.com/agentskills/agentskills/69ef37e9424c0a7ea9dd2293b559e43ec8176379/docs/specification.mdx"},"files":[{"bytes":412,"kind":"generated","path":"agent-bundle.hooks.json","sha256":"c085b5d4bc728917cba2d53546cdd9f6b065f9e84a846d31d3e4ccb254f5819a","sourceInputs":["agent-bundle.config.ts"]},{"bytes":287,"kind":"generated","path":"claude/.claude-plugin/marketplace.json","sha256":"f4dff087eb3c84f2b6e4ffeb632a3df21a631b70ad0328811dbaeabd8e29c043","sourceInputs":["agent-bundle.config.ts"]},{"bytes":182,"kind":"generated","path":"claude/.claude-plugin/plugin.json","sha256":"2fa2d83fbdca7ab515bbd11c1cc2dffafedeabc2dc9cd647fb9646c057b31d54","sourceInputs":["agent-bundle.config.ts"]},{"bytes":412,"kind":"copy","path":"claude/assets/release/release-manifest.json","sha256":"5f40663b01a3b359b3df7d5d7f7fbd0b1f703adb4a3b6a55e57dc2bf6d9bfc77","sourceInputs":["release/release-manifest.json"]},{"bytes":370,"kind":"copy","path":"claude/assets/release/risk-register.json","sha256":"aac96ec9112addc32a97c0f35fbda32d8f8104a321f1c2f4d97e10cbed25f0fb","sourceInputs":["release/risk-register.json"]},{"bytes":150,"kind":"generated","path":"claude/hooks/hooks.json","sha256":"8855c477158d687920a5d1da416ee8c980cc305f3adde65488dcef55e8b8da06","sourceInputs":["agent-bundle.config.ts"]},{"bytes":12034,"kind":"bundle","path":"claude/hooks/session-start-session-start-7ab7e8a5.mjs","sha256":"a751afea6c4c452124dc4fbb81e937182939b29a87e686525caa601111befa5b","sourceInputs":["agent-bundle.config.ts","src/hooks/session-start.ts"]},{"bytes":442,"kind":"generated","path":"claude/INSTALL.md","sha256":"0ca977cebb541b89cb7ef9cc47ed66dde2617f8c2beb5a697740ebfc2e4e0a14","sourceInputs":["agent-bundle.config.ts"]},{"bytes":2086,"kind":"bundle","path":"claude/scripts/verify-release.mjs","sha256":"834e07a4cf2669358b4dea1af6cfe57976d085c039f5af1651993d59c64ed15e","sourceInputs":["src/scripts/verify-release.ts"]},{"bytes":264,"kind":"generated","path":"codex/.agents/plugins/marketplace.json","sha256":"eef1222beca7c354075e8da61d0fc50d68180b87da4f884890886868b6b40b89","sourceInputs":["agent-bundle.config.ts"]},{"bytes":534,"kind":"generated","path":"codex/.codex-plugin/plugin.json","sha256":"e20e3a461fe89d8148d1aa53e729605316a6770215f86ec01c08ce7eaa672708","sourceInputs":["agent-bundle.config.ts"]},{"bytes":412,"kind":"copy","path":"codex/assets/release/release-manifest.json","sha256":"5f40663b01a3b359b3df7d5d7f7fbd0b1f703adb4a3b6a55e57dc2bf6d9bfc77","sourceInputs":["release/release-manifest.json"]},{"bytes":370,"kind":"copy","path":"codex/assets/release/risk-register.json","sha256":"aac96ec9112addc32a97c0f35fbda32d8f8104a321f1c2f4d97e10cbed25f0fb","sourceInputs":["release/risk-register.json"]},{"bytes":143,"kind":"generated","path":"codex/hooks/hooks.json","sha256":"ad0e296b15c799f52459488b17f46f7cc3a34e1abf4b9466a178d17a7fdaa605","sourceInputs":["agent-bundle.config.ts"]},{"bytes":12177,"kind":"bundle","path":"codex/hooks/session-start-session-start-7ab7e8a5.mjs","sha256":"99ae56a7e8c1d54a8df94cec252577eb1aef4d16b27e75dbc8ceaf63b6fb318e","sourceInputs":["agent-bundle.config.ts","src/hooks/session-start.ts"]},{"bytes":330,"kind":"generated","path":"codex/INSTALL.md","sha256":"b36d9e71a3d9e39947164524196269ba4084a28f6595558548d5f2639fb171ef","sourceInputs":["agent-bundle.config.ts"]},{"bytes":2086,"kind":"bundle","path":"codex/scripts/verify-release.mjs","sha256":"834e07a4cf2669358b4dea1af6cfe57976d085c039f5af1651993d59c64ed15e","sourceInputs":["src/scripts/verify-release.ts"]},{"bytes":412,"kind":"copy","path":"portable/assets/release/release-manifest.json","sha256":"5f40663b01a3b359b3df7d5d7f7fbd0b1f703adb4a3b6a55e57dc2bf6d9bfc77","sourceInputs":["release/release-manifest.json"]},{"bytes":370,"kind":"copy","path":"portable/assets/release/risk-register.json","sha256":"aac96ec9112addc32a97c0f35fbda32d8f8104a321f1c2f4d97e10cbed25f0fb","sourceInputs":["release/risk-register.json"]},{"bytes":667,"kind":"generated","path":"portable/INSTALL.md","sha256":"9fca655cfae6999fdac7a6562b003dff2353231f936b65791c7859cf7437b5b1","sourceInputs":["agent-bundle.config.ts"]},{"bytes":3311,"kind":"generated","path":"portable/install.mjs","sha256":"3d5bab7f4f63582ed41027cbdd58122cf8aa04436647400639876c264751447f","sourceInputs":["agent-bundle.config.ts"]},{"bytes":186,"kind":"generated","path":"portable/plugin.json","sha256":"7960fb9bcfd13c8bfbf113ac8b742d45f341df6fedf1c91525c421b10f63ad1e","sourceInputs":["agent-bundle.config.ts"]},{"bytes":1443,"kind":"bundle","path":"portable/scripts/detect-risk.mjs","sha256":"d306df52faf5ace3f722a61a529a282a416a862f95fc7af9015b56603a880a77","sourceInputs":["agent-bundle.config.ts","src/scripts/detect-risk.ts"]},{"bytes":2086,"kind":"bundle","path":"portable/scripts/verify-release.mjs","sha256":"834e07a4cf2669358b4dea1af6cfe57976d085c039f5af1651993d59c64ed15e","sourceInputs":["src/scripts/verify-release.ts"]}],"producer":{"name":"agent-bundle","version":"0.1.0"},"project":{"configDigest":"a6b714ebca4e4c048fe437312e4789b0841dccfd8a621cfe513e6a0ae3fc7a4c","configPath":"agent-bundle.config.ts","modelDigest":"c9c2a9a138a4736257fd35f0108d5b702cfd532efee090e77c33bb6b91028b5e","packageName":"@agent-bundle-example/hooks-and-scripts","revision":"32bbeed169b6a21841fbc15abc9fafcdc8bd2bcbeadbd153be1eafe28fe7c0f4","sourceInputs":[{"executable":false,"path":"agent-bundle.config.ts","sha256":"a6b714ebca4e4c048fe437312e4789b0841dccfd8a621cfe513e6a0ae3fc7a4c"},{"executable":false,"path":"package.json","sha256":"974301ada8ea65ced69eb0c43faf5e3206e343b6d76c5f824fbc425820bc1acd"},{"executable":false,"path":"README.md","sha256":"a22188781290ce67939e8dd339bc75b6dd520ded36a02de0b8a161d3a776afa1"},{"executable":false,"path":"release/release-manifest.json","sha256":"5f40663b01a3b359b3df7d5d7f7fbd0b1f703adb4a3b6a55e57dc2bf6d9bfc77"},{"executable":false,"path":"release/risk-register.json","sha256":"aac96ec9112addc32a97c0f35fbda32d8f8104a321f1c2f4d97e10cbed25f0fb"},{"executable":false,"path":"src/hooks/session-start.ts","sha256":"a5cda975fd148cf904b3c0cc5b0a860061ed89acd3704d54427c1313f23668e8"},{"executable":false,"path":"src/scripts/detect-risk.ts","sha256":"3b1d88c26219a410b6b23c019632fa8330ba5421d9294abbe9fc3f5300720370"},{"executable":false,"path":"src/scripts/verify-release.ts","sha256":"af661a44e63f38726d237df8821426884f64386f1e0a9f5c8c369932eac341c3"}]},"runtime":{"node":"22.12.0"},"targets":[{"adapterRevision":"1.22.0","name":"claude","observedVersion":"2.1.250","schemas":[{"name":"hooks","revision":"2.1.250","sha256":"3c6f3e4391f3dca939d75bd0b200ea88e68db939a2cb885d46f0b143293efb84"},{"name":"lsp","revision":"2.1.250","sha256":"c81fd2f57c410f70f8e5c3f84483f5ec1b575ee02802b424977826f757dccd8e"},{"name":"marketplace","revision":"2.1.250","sha256":"4ffa94e8024966e8080b9d3b338c9612bdfa255802a8491b43f74f90427bc988"},{"name":"mcp","revision":"2.1.250","sha256":"76ccf02c7bfe2d57945ba18e84da8d655529bd68b4d692f72bce28238c99067e"},{"name":"monitors","revision":"2.1.250","sha256":"d45abdf7561e4316ba217ce9c2ac84f32e1049622b74abb081693b479a54b48d"},{"name":"plugin","revision":"2.1.250","sha256":"3c9943237da86fd08ae82f698cde36dbef2ecf742098c6961cedf481fe435c12"},{"name":"settings","revision":"2.1.250","sha256":"9e86d8c5e4053e8de0e468d349e2c3dde5834d22d6769372b88570e301700073"},{"name":"theme","revision":"2.1.250","sha256":"721aa9b0bc7c60cd9359343e5c7205ffbdfea82da312f601720c9dfaa2d8cf0d"}]},{"adapterRevision":"1.8.0","name":"codex","observedVersion":"0.147.0","schemas":[{"name":"app","revision":"0.147.0","sha256":"01c720a645e437bf0c4f8c26fd4cb5a13988e5649e4a8562ee23a1d4b7355c6a"},{"name":"hooks","revision":"0.147.0","sha256":"175b859eb8e85bd287d85ee840d97c3f5c2d0dda3223507a796d158e3770eeba"},{"name":"marketplace","revision":"0.147.0","sha256":"fbccce3ade39e1b077fcb440e60260de6e811e8c2d222b2ae0fe8fe47706b470"},{"name":"mcp","revision":"0.147.0","sha256":"75bd50f9fcb85c2e8d43bc132d61c172a02f28ea8bb77389816ae77b14a4257e"},{"name":"plugin","revision":"0.147.0","sha256":"4ad476545c96c83d899c4524dcccd4eb4fe7d3299c307878a0cd46a237f48d58"}]},{"adapterRevision":"1.6.0","name":"portable","observedVersion":"1.0.0","schemas":[{"name":"mcp","revision":"1.0.0","sha256":"6539175bfcdf43085855183e86da40ea94b166547a72b47ae9a0a390516d3acb"},{"name":"plugin","revision":"1.0.0","sha256":"0a4aad95ce337878ad38802ebf0daa3fde76abe3f65400c86bcbb1ec0b3ab883"}]}],"validation":{"artifact":{"status":"passed"},"source":{"status":"passed"},"targets":[{"name":"claude","status":"passed"},{"name":"codex","status":"passed"},{"name":"portable","status":"passed"}]}} diff --git a/examples/hooks-and-scripts/artifact/claude/.claude-plugin/marketplace.json b/examples/hooks-and-scripts/artifact/claude/.claude-plugin/marketplace.json deleted file mode 100644 index 2cae8a879..000000000 --- a/examples/hooks-and-scripts/artifact/claude/.claude-plugin/marketplace.json +++ /dev/null @@ -1 +0,0 @@ -{"description":"Hook simulation, script traces, logs, and recovery.","name":"hooks-and-scripts-marketplace","owner":{"name":"hooks-and-scripts"},"plugins":[{"description":"Hook simulation, script traces, logs, and recovery.","name":"hooks-and-scripts","source":"./","version":"1.0.0"}]} diff --git a/examples/hooks-and-scripts/artifact/claude/.claude-plugin/plugin.json b/examples/hooks-and-scripts/artifact/claude/.claude-plugin/plugin.json deleted file mode 100644 index 38dc8d3b1..000000000 --- a/examples/hooks-and-scripts/artifact/claude/.claude-plugin/plugin.json +++ /dev/null @@ -1 +0,0 @@ -{"author":{"name":"hooks-and-scripts"},"description":"Hook simulation, script traces, logs, and recovery.","hooks":"./hooks/hooks.json","name":"hooks-and-scripts","version":"1.0.0"} diff --git a/examples/hooks-and-scripts/artifact/claude/INSTALL.md b/examples/hooks-and-scripts/artifact/claude/INSTALL.md deleted file mode 100644 index ea76a1f93..000000000 --- a/examples/hooks-and-scripts/artifact/claude/INSTALL.md +++ /dev/null @@ -1,18 +0,0 @@ -# Install hooks-and-scripts - -Hook simulation, script traces, logs, and recovery. - -Version: `1.0.0` - -Run these commands from this bundle directory. - -## Claude Code - -Claude Code installs this bundle through its local marketplace contract: - -```sh -claude plugin marketplace add ./ -claude plugin install hooks-and-scripts@hooks-and-scripts-marketplace --scope user -``` - -Replace `user` with `project` or `local` when that Claude scope is intended. diff --git a/examples/hooks-and-scripts/artifact/claude/assets/release/release-manifest.json b/examples/hooks-and-scripts/artifact/claude/assets/release/release-manifest.json deleted file mode 100644 index 819d86560..000000000 --- a/examples/hooks-and-scripts/artifact/claude/assets/release/release-manifest.json +++ /dev/null @@ -1,21 +0,0 @@ -{ - "version": "2.4.0", - "changelog": "CHANGELOG.md#2.4.0", - "artifacts": [ - { - "name": "package", - "path": "dist/agent-bundle-2.4.0.tgz", - "status": "ready" - }, - { - "name": "checksums", - "path": "dist/agent-bundle-2.4.0.sha256", - "status": "ready" - }, - { - "name": "sbom", - "path": "dist/agent-bundle-2.4.0.sbom.json", - "status": "ready" - } - ] -} diff --git a/examples/hooks-and-scripts/artifact/claude/assets/release/risk-register.json b/examples/hooks-and-scripts/artifact/claude/assets/release/risk-register.json deleted file mode 100644 index 2295bcc45..000000000 --- a/examples/hooks-and-scripts/artifact/claude/assets/release/risk-register.json +++ /dev/null @@ -1,16 +0,0 @@ -{ - "risks": [ - { - "id": "REL-204", - "severity": "high", - "status": "open", - "summary": "Complete the final approval for the release notes before publishing." - }, - { - "id": "REL-198", - "severity": "medium", - "status": "mitigated", - "summary": "Package signing rehearsal is documented in the release runbook." - } - ] -} diff --git a/examples/hooks-and-scripts/artifact/claude/hooks/hooks.json b/examples/hooks-and-scripts/artifact/claude/hooks/hooks.json deleted file mode 100644 index 1afdaac5a..000000000 --- a/examples/hooks-and-scripts/artifact/claude/hooks/hooks.json +++ /dev/null @@ -1 +0,0 @@ -{"hooks":{"SessionStart":[{"hooks":[{"command":"node \"${CLAUDE_PLUGIN_ROOT}/hooks/session-start-session-start-7ab7e8a5.mjs\"","type":"command"}]}]}} diff --git a/examples/hooks-and-scripts/artifact/claude/hooks/session-start-session-start-7ab7e8a5.mjs b/examples/hooks-and-scripts/artifact/claude/hooks/session-start-session-start-7ab7e8a5.mjs deleted file mode 100644 index 924ce1681..000000000 --- a/examples/hooks-and-scripts/artifact/claude/hooks/session-start-session-start-7ab7e8a5.mjs +++ /dev/null @@ -1,253 +0,0 @@ -// The require scope -var __webpack_require__ = {}; - -// webpack/runtime/define_property_getters -(() => { -__webpack_require__.d = (exports, getters, values) => { - var define = (defs, kind) => { - for(var key in defs) { - if(__webpack_require__.o(defs, key) && !__webpack_require__.o(exports, key)) { - Object.defineProperty(exports, key, { enumerable: true, [kind]: defs[key] }); - } - } - }; - define(getters, "get"); - define(values, "value"); -}; -})(); -// webpack/runtime/has_own_property -(() => { -__webpack_require__.o = (obj, prop) => (Object.prototype.hasOwnProperty.call(obj, prop)) -})(); -// webpack/runtime/make_namespace_object -(() => { -// define __esModule on exports -__webpack_require__.r = (exports) => { - if(typeof Symbol !== 'undefined' && Symbol.toStringTag) { - Object.defineProperty(exports, Symbol.toStringTag, { value: 'Module' }); - } - Object.defineProperty(exports, '__esModule', { value: true }); -}; -})(); - -// NAMESPACE OBJECT: ./src/hooks/session-start.ts -var session_start_namespaceObject = {}; -__webpack_require__.r(session_start_namespaceObject); -__webpack_require__.d(session_start_namespaceObject, { - "default": () => (session_start) }); - - -/* export default */ const session_start = ((event)=>({ - additionalContext: [ - `This release preparation session is active for ${event.sessionId ?? 'this session'} from ${event.source ?? 'an unknown source'}.`, - `Run verify-release from ${event.cwd ?? process.cwd()} to confirm the manifest is ready for packaging.`, - 'Run detect-risk to surface open high-severity release blockers before publishing.' - ].join(' '), - outcome: 'continue' - })); - - -const target = "claude"; -const canonicalEvent = "sessionStart"; -const nativeEvent = "SessionStart"; -const isRecord = (value)=>typeof value === "object" && value !== null && !Array.isArray(value); -const defined = (value)=>Object.fromEntries(Object.entries(value).filter(([, item])=>item !== undefined)); -const decodeClaudeNative = (nativeInput)=>({ - agentId: nativeInput.agent_id, - agentTranscriptPath: nativeInput.agent_transcript_path, - agentType: nativeInput.agent_type, - cwd: nativeInput.cwd, - effort: nativeInput.effort, - hookEventName: nativeInput.hook_event_name, - lastAssistantMessage: nativeInput.last_assistant_message, - model: nativeInput.model, - permissionMode: nativeInput.permission_mode, - promptId: nativeInput.prompt_id, - sessionId: nativeInput.session_id, - source: nativeInput.source, - stopHookActive: nativeInput.stop_hook_active, - toolInput: nativeInput.tool_input, - toolName: nativeInput.tool_name, - toolResponse: nativeInput.tool_response, - toolUseId: nativeInput.tool_use_id, - transcriptPath: nativeInput.transcript_path, - turnId: nativeInput.turn_id - }); -const encodeClaudeNative = (canonicalInput)=>defined({ - hook_event_name: nativeEvent, - agent_id: canonicalInput.agentId, - agent_transcript_path: canonicalInput.agentTranscriptPath, - agent_type: canonicalInput.agentType, - cwd: canonicalInput.cwd, - effort: canonicalInput.effort, - last_assistant_message: canonicalInput.lastAssistantMessage, - model: canonicalInput.model, - permission_mode: canonicalInput.permissionMode, - prompt_id: canonicalInput.promptId, - session_id: canonicalInput.sessionId, - source: canonicalInput.source, - stop_hook_active: canonicalInput.stopHookActive, - tool_input: canonicalInput.toolInput, - tool_name: canonicalInput.toolName, - tool_response: canonicalInput.toolResponse, - tool_use_id: canonicalInput.toolUseId, - transcript_path: canonicalInput.transcriptPath, - turn_id: canonicalInput.turnId - }); -const decodeNative = decodeClaudeNative; -const encodeNative = encodeClaudeNative; -const fail = (message)=>{ - throw new Error(`Agent Bundle hook error: ${message}`); -}; -const validateResult = (result)=>{ - if (result === undefined) return undefined; - if (!isRecord(result)) fail("handler must return void or a result object"); - const allowed = new Set([ - "outcome", - "reason", - "updatedInput", - "additionalContext" - ]); - for (const key of Object.keys(result))if (!allowed.has(key)) fail(`handler result has unsupported field ${key}`); - if (result.outcome !== undefined && ![ - "continue", - "deny", - "stop" - ].includes(result.outcome)) fail("handler result outcome is invalid"); - if (result.reason !== undefined && typeof result.reason !== "string") fail("handler result reason must be a string"); - if (result.additionalContext !== undefined && typeof result.additionalContext !== "string") fail("handler result additionalContext must be a string"); - if (result.updatedInput !== undefined && !isRecord(result.updatedInput)) fail("handler result updatedInput must be an object"); - const supportsDeniedReason = canonicalEvent === "beforeTool" || canonicalEvent === "stop" || canonicalEvent === "agentStop"; - if (result.reason !== undefined && !(result.outcome === "deny" && supportsDeniedReason)) fail("reason is only valid for a denied beforeTool, stop, or agentStop hook"); - if (result.outcome === "deny" && supportsDeniedReason && (typeof result.reason !== "string" || result.reason.trim().length === 0)) fail(`denied ${canonicalEvent} hook requires a nonempty reason`); - if ((canonicalEvent === "sessionStart" || canonicalEvent === "afterTool" || canonicalEvent === "agentStart") && (result.outcome === "deny" || result.outcome === "stop" || result.updatedInput !== undefined)) fail(`${canonicalEvent} cannot deny, stop, or replace input`); - if (canonicalEvent === "beforeTool" && (result.outcome === "stop" || result.outcome === "deny" && result.updatedInput !== undefined)) fail("beforeTool cannot stop or replace input while denying"); - if (canonicalEvent === "stop" && (result.outcome === "stop" || result.updatedInput !== undefined || result.additionalContext !== undefined)) fail("stop only accepts continue or deny with a reason"); - if (canonicalEvent === "agentStop" && (result.outcome === "stop" || result.updatedInput !== undefined)) fail("agentStop cannot stop the parent flow or replace input"); - if (canonicalEvent === "agentStop" && target === "codex" && 0) {} - return result; -}; -const encodeOutput = (result)=>{ - if (result === undefined) return undefined; - if (canonicalEvent === "stop" || canonicalEvent === "agentStop") { - if (result.outcome === "deny") return defined({ - decision: "block", - reason: result.reason - }); - if (canonicalEvent === "agentStop" && target === "claude" && result.additionalContext !== undefined) return { - hookSpecificOutput: { - additionalContext: result.additionalContext, - hookEventName: nativeEvent - } - }; - return undefined; - } - const output = defined({ - additionalContext: result.additionalContext, - hookEventName: nativeEvent, - permissionDecision: canonicalEvent === "beforeTool" ? result.outcome === "deny" ? "deny" : "allow" : undefined, - permissionDecisionReason: canonicalEvent === "beforeTool" && result.outcome === "deny" ? result.reason : undefined, - updatedInput: canonicalEvent === "beforeTool" && result.outcome !== "deny" ? result.updatedInput : undefined - }); - return Object.keys(output).length === 1 && output.hookEventName !== undefined ? undefined : { - hookSpecificOutput: output - }; -}; -const decodeOutput = (nativeOutput)=>{ - if (nativeOutput === undefined) return undefined; - if (canonicalEvent === "stop" || canonicalEvent === "agentStop") { - if (nativeOutput.decision === "block") return defined({ - outcome: "deny", - reason: nativeOutput.reason - }); - if (canonicalEvent === "agentStop" && target === "claude" && isRecord(nativeOutput.hookSpecificOutput)) return defined({ - additionalContext: nativeOutput.hookSpecificOutput.additionalContext, - outcome: "continue" - }); - return undefined; - } - const output = nativeOutput.hookSpecificOutput; - if (!isRecord(output)) fail("native hook output is malformed"); - return defined({ - additionalContext: output.additionalContext, - outcome: output.permissionDecision === "deny" ? "deny" : "continue", - reason: output.permissionDecisionReason, - updatedInput: output.updatedInput - }); -}; -const requireString = (input, field)=>{ - if (typeof input[field] !== "string") fail(`native ${field} must be a string`); -}; -const requireNullableString = (input, field)=>{ - if (input[field] !== null && typeof input[field] !== "string") fail(`native ${field} must be a string or null`); -}; -const validateNativeInput = (input)=>{ - requireString(input, "session_id"); - if (false) {} - else requireString(input, "transcript_path"); - requireString(input, "cwd"); - if (input.hook_event_name !== nativeEvent) fail(`native hook_event_name must equal ${nativeEvent}`); - if (input.prompt_id !== undefined) requireString(input, "prompt_id"); - if (input.permission_mode !== undefined) requireString(input, "permission_mode"); - if (input.model !== undefined) requireString(input, "model"); - if (canonicalEvent === "sessionStart") { - requireString(input, "source"); - return; - } - if (canonicalEvent === "beforeTool" || canonicalEvent === "afterTool") { - requireString(input, "tool_name"); - if (false) {} else if (!isRecord(input.tool_input)) fail(`native ${nativeEvent} tool_input must be an object`); - requireString(input, "tool_use_id"); - if (canonicalEvent === "afterTool") { - if (input.tool_response === undefined) fail("native PostToolUse tool_response is required"); - } - return; - } - if (canonicalEvent === "agentStart" || canonicalEvent === "agentStop") { - requireString(input, "agent_id"); - requireString(input, "agent_type"); - if (false) {} - if (canonicalEvent === "agentStart") return; - if (typeof input.stop_hook_active !== "boolean") fail("native SubagentStop stop_hook_active must be a boolean"); - requireNullableString(input, "agent_transcript_path"); - requireNullableString(input, "last_assistant_message"); - return; - } - if (typeof input.stop_hook_active !== "boolean") fail("native Stop stop_hook_active must be a boolean"); - if (false) {} - else requireString(input, "last_assistant_message"); -}; -const run = async ()=>{ - const handler = Reflect.get(session_start_namespaceObject, "default"); - if (typeof handler !== "function") fail("default export must be a function"); - let raw = ""; - for await (const chunk of process.stdin)raw += chunk; - if (raw.trim().length === 0) fail("stdin must contain exactly one JSON value"); - let input; - try { - input = JSON.parse(raw); - } catch { - fail("stdin must contain exactly one JSON value"); - } - if (!isRecord(input)) fail("stdin JSON value must be an object"); - const simulation = process.env.AGENT_BUNDLE_HOOK_SIMULATION === "1"; - const nativeInput = simulation ? encodeNative(input) : input; - validateNativeInput(nativeInput); - const event = decodeNative(nativeInput); - const result = validateResult(await handler(event, { - nativeEvent: nativeEvent, - nativeInput, - target: target - })); - const nativeOutput = encodeOutput(result); - const output = simulation ? decodeOutput(nativeOutput) : nativeOutput; - if (output !== undefined) process.stdout.write(JSON.stringify(output)); -}; -if (import.meta.main) { - await run().catch((error)=>{ - process.stderr.write(`${error instanceof Error ? error.message : String(error)}\n`); - process.exitCode = 1; - }); -} - -export {}; diff --git a/examples/hooks-and-scripts/artifact/claude/scripts/verify-release.mjs b/examples/hooks-and-scripts/artifact/claude/scripts/verify-release.mjs deleted file mode 100644 index 6ac9cd7a9..000000000 --- a/examples/hooks-and-scripts/artifact/claude/scripts/verify-release.mjs +++ /dev/null @@ -1,54 +0,0 @@ -import { readFile } from "node:fs/promises"; - - - - - -const requiredArtifacts = [ - 'package', - 'checksums', - 'sbom' -]; -const manifestPath = new URL('../assets/release/release-manifest.json', import.meta.url); -const readManifest = async ()=>JSON.parse(await readFile(manifestPath, 'utf8')); -const validationErrors = (manifest)=>{ - const errors = []; - if (typeof manifest.version !== 'string' || !/^\d+\.\d+\.\d+$/.test(manifest.version)) { - errors.push('version must use major.minor.patch format'); - } - if (typeof manifest.changelog !== 'string' || manifest.changelog.trim().length === 0) { - errors.push('changelog must identify the release notes'); - } - for (const name of requiredArtifacts){ - const artifact = manifest.artifacts?.find((candidate)=>candidate.name === name); - if (artifact === undefined || typeof artifact.path !== 'string' || artifact.path.trim().length === 0 || artifact.status !== 'ready') { - errors.push(`${name} artifact must have a ready path`); - } - } - return errors; -}; -const main = async ()=>{ - try { - const manifest = await readManifest(); - const errors = validationErrors(manifest); - if (errors.length > 0) { - process.stderr.write(`Release manifest is incomplete:\n${errors.map((error)=>`- ${error}`).join('\n')}\n`); - return 1; - } - process.stdout.write(`Release ${manifest.version} is ready for packaging.\n`); - return 0; - } catch (error) { - process.stderr.write(`Unable to verify release manifest: ${error instanceof Error ? error.message : String(error)}\n`); - return 1; - } -}; - - -const verify_release_entry_main = main; -if (typeof verify_release_entry_main !== 'function') { - throw new TypeError('Executable entry must export a main function: ' + "/fast/projects/agent-bundle-worktrees/host-test/examples/hooks-and-scripts/src/scripts/verify-release.ts"); -} -const code = await verify_release_entry_main(process.argv.slice(2)); -if (typeof code === 'number') process.exitCode = code; - -export {}; diff --git a/examples/hooks-and-scripts/artifact/codex/.agents/plugins/marketplace.json b/examples/hooks-and-scripts/artifact/codex/.agents/plugins/marketplace.json deleted file mode 100644 index 16e053eae..000000000 --- a/examples/hooks-and-scripts/artifact/codex/.agents/plugins/marketplace.json +++ /dev/null @@ -1 +0,0 @@ -{"interface":{"displayName":"hooks-and-scripts"},"name":"hooks-and-scripts-marketplace","plugins":[{"category":"Productivity","name":"hooks-and-scripts","policy":{"authentication":"ON_INSTALL","installation":"AVAILABLE"},"source":{"path":"./","source":"local"}}]} diff --git a/examples/hooks-and-scripts/artifact/codex/.codex-plugin/plugin.json b/examples/hooks-and-scripts/artifact/codex/.codex-plugin/plugin.json deleted file mode 100644 index eeee06783..000000000 --- a/examples/hooks-and-scripts/artifact/codex/.codex-plugin/plugin.json +++ /dev/null @@ -1 +0,0 @@ -{"author":{"name":"hooks-and-scripts"},"description":"Hook simulation, script traces, logs, and recovery.","hooks":"./hooks/hooks.json","interface":{"capabilities":["hooks"],"category":"Productivity","defaultPrompt":["Help me use hooks-and-scripts."],"developerName":"hooks-and-scripts","displayName":"hooks-and-scripts","longDescription":"Hook simulation, script traces, logs, and recovery.","shortDescription":"Hook simulation, script traces, logs, and recovery."},"name":"hooks-and-scripts","skills":"./skills/","version":"1.0.0"} diff --git a/examples/hooks-and-scripts/artifact/codex/INSTALL.md b/examples/hooks-and-scripts/artifact/codex/INSTALL.md deleted file mode 100644 index 97ee12563..000000000 --- a/examples/hooks-and-scripts/artifact/codex/INSTALL.md +++ /dev/null @@ -1,16 +0,0 @@ -# Install hooks-and-scripts - -Hook simulation, script traces, logs, and recovery. - -Version: `1.0.0` - -Run these commands from this bundle directory. - -## Codex - -Codex installs this bundle from its local marketplace snapshot: - -```sh -codex plugin marketplace add ./ -codex plugin add hooks-and-scripts@hooks-and-scripts-marketplace -``` diff --git a/examples/hooks-and-scripts/artifact/codex/assets/release/release-manifest.json b/examples/hooks-and-scripts/artifact/codex/assets/release/release-manifest.json deleted file mode 100644 index 819d86560..000000000 --- a/examples/hooks-and-scripts/artifact/codex/assets/release/release-manifest.json +++ /dev/null @@ -1,21 +0,0 @@ -{ - "version": "2.4.0", - "changelog": "CHANGELOG.md#2.4.0", - "artifacts": [ - { - "name": "package", - "path": "dist/agent-bundle-2.4.0.tgz", - "status": "ready" - }, - { - "name": "checksums", - "path": "dist/agent-bundle-2.4.0.sha256", - "status": "ready" - }, - { - "name": "sbom", - "path": "dist/agent-bundle-2.4.0.sbom.json", - "status": "ready" - } - ] -} diff --git a/examples/hooks-and-scripts/artifact/codex/assets/release/risk-register.json b/examples/hooks-and-scripts/artifact/codex/assets/release/risk-register.json deleted file mode 100644 index 2295bcc45..000000000 --- a/examples/hooks-and-scripts/artifact/codex/assets/release/risk-register.json +++ /dev/null @@ -1,16 +0,0 @@ -{ - "risks": [ - { - "id": "REL-204", - "severity": "high", - "status": "open", - "summary": "Complete the final approval for the release notes before publishing." - }, - { - "id": "REL-198", - "severity": "medium", - "status": "mitigated", - "summary": "Package signing rehearsal is documented in the release runbook." - } - ] -} diff --git a/examples/hooks-and-scripts/artifact/codex/hooks/hooks.json b/examples/hooks-and-scripts/artifact/codex/hooks/hooks.json deleted file mode 100644 index eb4f61756..000000000 --- a/examples/hooks-and-scripts/artifact/codex/hooks/hooks.json +++ /dev/null @@ -1 +0,0 @@ -{"hooks":{"SessionStart":[{"hooks":[{"command":"node \"${PLUGIN_ROOT}/hooks/session-start-session-start-7ab7e8a5.mjs\"","type":"command"}]}]}} diff --git a/examples/hooks-and-scripts/artifact/codex/hooks/session-start-session-start-7ab7e8a5.mjs b/examples/hooks-and-scripts/artifact/codex/hooks/session-start-session-start-7ab7e8a5.mjs deleted file mode 100644 index 28a8cb44b..000000000 --- a/examples/hooks-and-scripts/artifact/codex/hooks/session-start-session-start-7ab7e8a5.mjs +++ /dev/null @@ -1,258 +0,0 @@ -// The require scope -var __webpack_require__ = {}; - -// webpack/runtime/define_property_getters -(() => { -__webpack_require__.d = (exports, getters, values) => { - var define = (defs, kind) => { - for(var key in defs) { - if(__webpack_require__.o(defs, key) && !__webpack_require__.o(exports, key)) { - Object.defineProperty(exports, key, { enumerable: true, [kind]: defs[key] }); - } - } - }; - define(getters, "get"); - define(values, "value"); -}; -})(); -// webpack/runtime/has_own_property -(() => { -__webpack_require__.o = (obj, prop) => (Object.prototype.hasOwnProperty.call(obj, prop)) -})(); -// webpack/runtime/make_namespace_object -(() => { -// define __esModule on exports -__webpack_require__.r = (exports) => { - if(typeof Symbol !== 'undefined' && Symbol.toStringTag) { - Object.defineProperty(exports, Symbol.toStringTag, { value: 'Module' }); - } - Object.defineProperty(exports, '__esModule', { value: true }); -}; -})(); - -// NAMESPACE OBJECT: ./src/hooks/session-start.ts -var session_start_namespaceObject = {}; -__webpack_require__.r(session_start_namespaceObject); -__webpack_require__.d(session_start_namespaceObject, { - "default": () => (session_start) }); - - -/* export default */ const session_start = ((event)=>({ - additionalContext: [ - `This release preparation session is active for ${event.sessionId ?? 'this session'} from ${event.source ?? 'an unknown source'}.`, - `Run verify-release from ${event.cwd ?? process.cwd()} to confirm the manifest is ready for packaging.`, - 'Run detect-risk to surface open high-severity release blockers before publishing.' - ].join(' '), - outcome: 'continue' - })); - - -const target = "codex"; -const canonicalEvent = "sessionStart"; -const nativeEvent = "SessionStart"; -const isRecord = (value)=>typeof value === "object" && value !== null && !Array.isArray(value); -const defined = (value)=>Object.fromEntries(Object.entries(value).filter(([, item])=>item !== undefined)); -const decodeCodexNative = (nativeInput)=>({ - agentId: nativeInput.agent_id, - agentTranscriptPath: nativeInput.agent_transcript_path, - agentType: nativeInput.agent_type, - cwd: nativeInput.cwd, - effort: nativeInput.effort, - hookEventName: nativeInput.hook_event_name, - lastAssistantMessage: nativeInput.last_assistant_message, - model: nativeInput.model, - permissionMode: nativeInput.permission_mode, - promptId: nativeInput.prompt_id, - sessionId: nativeInput.session_id, - source: nativeInput.source, - stopHookActive: nativeInput.stop_hook_active, - toolInput: nativeInput.tool_input, - toolName: nativeInput.tool_name, - toolResponse: nativeInput.tool_response, - toolUseId: nativeInput.tool_use_id, - transcriptPath: nativeInput.transcript_path, - turnId: nativeInput.turn_id - }); -const encodeCodexNative = (canonicalInput)=>defined({ - hook_event_name: nativeEvent, - agent_id: canonicalInput.agentId, - agent_transcript_path: canonicalInput.agentTranscriptPath, - agent_type: canonicalInput.agentType, - cwd: canonicalInput.cwd, - effort: canonicalInput.effort, - last_assistant_message: canonicalInput.lastAssistantMessage, - model: canonicalInput.model, - permission_mode: canonicalInput.permissionMode, - prompt_id: canonicalInput.promptId, - session_id: canonicalInput.sessionId, - source: canonicalInput.source, - stop_hook_active: canonicalInput.stopHookActive, - tool_input: canonicalInput.toolInput, - tool_name: canonicalInput.toolName, - tool_response: canonicalInput.toolResponse, - tool_use_id: canonicalInput.toolUseId, - transcript_path: canonicalInput.transcriptPath, - turn_id: canonicalInput.turnId - }); -const decodeNative = decodeCodexNative; -const encodeNative = encodeCodexNative; -const fail = (message)=>{ - throw new Error(`Agent Bundle hook error: ${message}`); -}; -const validateResult = (result)=>{ - if (result === undefined) return undefined; - if (!isRecord(result)) fail("handler must return void or a result object"); - const allowed = new Set([ - "outcome", - "reason", - "updatedInput", - "additionalContext" - ]); - for (const key of Object.keys(result))if (!allowed.has(key)) fail(`handler result has unsupported field ${key}`); - if (result.outcome !== undefined && ![ - "continue", - "deny", - "stop" - ].includes(result.outcome)) fail("handler result outcome is invalid"); - if (result.reason !== undefined && typeof result.reason !== "string") fail("handler result reason must be a string"); - if (result.additionalContext !== undefined && typeof result.additionalContext !== "string") fail("handler result additionalContext must be a string"); - if (result.updatedInput !== undefined && !isRecord(result.updatedInput)) fail("handler result updatedInput must be an object"); - const supportsDeniedReason = canonicalEvent === "beforeTool" || canonicalEvent === "stop" || canonicalEvent === "agentStop"; - if (result.reason !== undefined && !(result.outcome === "deny" && supportsDeniedReason)) fail("reason is only valid for a denied beforeTool, stop, or agentStop hook"); - if (result.outcome === "deny" && supportsDeniedReason && (typeof result.reason !== "string" || result.reason.trim().length === 0)) fail(`denied ${canonicalEvent} hook requires a nonempty reason`); - if ((canonicalEvent === "sessionStart" || canonicalEvent === "afterTool" || canonicalEvent === "agentStart") && (result.outcome === "deny" || result.outcome === "stop" || result.updatedInput !== undefined)) fail(`${canonicalEvent} cannot deny, stop, or replace input`); - if (canonicalEvent === "beforeTool" && (result.outcome === "stop" || result.outcome === "deny" && result.updatedInput !== undefined)) fail("beforeTool cannot stop or replace input while denying"); - if (canonicalEvent === "stop" && (result.outcome === "stop" || result.updatedInput !== undefined || result.additionalContext !== undefined)) fail("stop only accepts continue or deny with a reason"); - if (canonicalEvent === "agentStop" && (result.outcome === "stop" || result.updatedInput !== undefined)) fail("agentStop cannot stop the parent flow or replace input"); - if (canonicalEvent === "agentStop" && target === "codex" && result.additionalContext !== undefined) fail("Codex SubagentStop does not support additionalContext"); - return result; -}; -const encodeOutput = (result)=>{ - if (result === undefined) return undefined; - if (canonicalEvent === "stop" || canonicalEvent === "agentStop") { - if (result.outcome === "deny") return defined({ - decision: "block", - reason: result.reason - }); - if (canonicalEvent === "agentStop" && target === "claude" && 0) {} - return undefined; - } - const output = defined({ - additionalContext: result.additionalContext, - hookEventName: nativeEvent, - permissionDecision: canonicalEvent === "beforeTool" ? result.outcome === "deny" ? "deny" : "allow" : undefined, - permissionDecisionReason: canonicalEvent === "beforeTool" && result.outcome === "deny" ? result.reason : undefined, - updatedInput: canonicalEvent === "beforeTool" && result.outcome !== "deny" ? result.updatedInput : undefined - }); - return Object.keys(output).length === 1 && output.hookEventName !== undefined ? undefined : { - hookSpecificOutput: output - }; -}; -const decodeOutput = (nativeOutput)=>{ - if (nativeOutput === undefined) return undefined; - if (canonicalEvent === "stop" || canonicalEvent === "agentStop") { - if (nativeOutput.decision === "block") return defined({ - outcome: "deny", - reason: nativeOutput.reason - }); - if (canonicalEvent === "agentStop" && target === "claude" && 0) {} - return undefined; - } - const output = nativeOutput.hookSpecificOutput; - if (!isRecord(output)) fail("native hook output is malformed"); - return defined({ - additionalContext: output.additionalContext, - outcome: output.permissionDecision === "deny" ? "deny" : "continue", - reason: output.permissionDecisionReason, - updatedInput: output.updatedInput - }); -}; -const requireString = (input, field)=>{ - if (typeof input[field] !== "string") fail(`native ${field} must be a string`); -}; -const requireNullableString = (input, field)=>{ - if (input[field] !== null && typeof input[field] !== "string") fail(`native ${field} must be a string or null`); -}; -const validateNativeInput = (input)=>{ - requireString(input, "session_id"); - if (true) requireNullableString(input, "transcript_path"); - else {} - requireString(input, "cwd"); - if (input.hook_event_name !== nativeEvent) fail(`native hook_event_name must equal ${nativeEvent}`); - if (input.prompt_id !== undefined) requireString(input, "prompt_id"); - if (input.permission_mode !== undefined) requireString(input, "permission_mode"); - if (input.model !== undefined) requireString(input, "model"); - if (canonicalEvent === "sessionStart") { - requireString(input, "source"); - return; - } - if (canonicalEvent === "beforeTool" || canonicalEvent === "afterTool") { - requireString(input, "tool_name"); - if (true) { - if (input.tool_input === undefined) fail(`native ${nativeEvent} tool_input is required`); - } else {} - requireString(input, "tool_use_id"); - if (canonicalEvent === "afterTool") { - if (input.tool_response === undefined) fail("native PostToolUse tool_response is required"); - } - return; - } - if (canonicalEvent === "agentStart" || canonicalEvent === "agentStop") { - requireString(input, "agent_id"); - requireString(input, "agent_type"); - if (true) { - requireString(input, "turn_id"); - requireString(input, "model"); - requireString(input, "permission_mode"); - if (![ - "default", - "acceptEdits", - "plan", - "dontAsk", - "bypassPermissions" - ].includes(input.permission_mode)) fail("native permission_mode is invalid"); - } - if (canonicalEvent === "agentStart") return; - if (typeof input.stop_hook_active !== "boolean") fail("native SubagentStop stop_hook_active must be a boolean"); - requireNullableString(input, "agent_transcript_path"); - requireNullableString(input, "last_assistant_message"); - return; - } - if (typeof input.stop_hook_active !== "boolean") fail("native Stop stop_hook_active must be a boolean"); - if (true) requireNullableString(input, "last_assistant_message"); - else {} -}; -const run = async ()=>{ - const handler = Reflect.get(session_start_namespaceObject, "default"); - if (typeof handler !== "function") fail("default export must be a function"); - let raw = ""; - for await (const chunk of process.stdin)raw += chunk; - if (raw.trim().length === 0) fail("stdin must contain exactly one JSON value"); - let input; - try { - input = JSON.parse(raw); - } catch { - fail("stdin must contain exactly one JSON value"); - } - if (!isRecord(input)) fail("stdin JSON value must be an object"); - const simulation = process.env.AGENT_BUNDLE_HOOK_SIMULATION === "1"; - const nativeInput = simulation ? encodeNative(input) : input; - validateNativeInput(nativeInput); - const event = decodeNative(nativeInput); - const result = validateResult(await handler(event, { - nativeEvent: nativeEvent, - nativeInput, - target: target - })); - const nativeOutput = encodeOutput(result); - const output = simulation ? decodeOutput(nativeOutput) : nativeOutput; - if (output !== undefined) process.stdout.write(JSON.stringify(output)); -}; -if (import.meta.main) { - await run().catch((error)=>{ - process.stderr.write(`${error instanceof Error ? error.message : String(error)}\n`); - process.exitCode = 1; - }); -} - -export {}; diff --git a/examples/hooks-and-scripts/artifact/codex/scripts/verify-release.mjs b/examples/hooks-and-scripts/artifact/codex/scripts/verify-release.mjs deleted file mode 100644 index 6ac9cd7a9..000000000 --- a/examples/hooks-and-scripts/artifact/codex/scripts/verify-release.mjs +++ /dev/null @@ -1,54 +0,0 @@ -import { readFile } from "node:fs/promises"; - - - - - -const requiredArtifacts = [ - 'package', - 'checksums', - 'sbom' -]; -const manifestPath = new URL('../assets/release/release-manifest.json', import.meta.url); -const readManifest = async ()=>JSON.parse(await readFile(manifestPath, 'utf8')); -const validationErrors = (manifest)=>{ - const errors = []; - if (typeof manifest.version !== 'string' || !/^\d+\.\d+\.\d+$/.test(manifest.version)) { - errors.push('version must use major.minor.patch format'); - } - if (typeof manifest.changelog !== 'string' || manifest.changelog.trim().length === 0) { - errors.push('changelog must identify the release notes'); - } - for (const name of requiredArtifacts){ - const artifact = manifest.artifacts?.find((candidate)=>candidate.name === name); - if (artifact === undefined || typeof artifact.path !== 'string' || artifact.path.trim().length === 0 || artifact.status !== 'ready') { - errors.push(`${name} artifact must have a ready path`); - } - } - return errors; -}; -const main = async ()=>{ - try { - const manifest = await readManifest(); - const errors = validationErrors(manifest); - if (errors.length > 0) { - process.stderr.write(`Release manifest is incomplete:\n${errors.map((error)=>`- ${error}`).join('\n')}\n`); - return 1; - } - process.stdout.write(`Release ${manifest.version} is ready for packaging.\n`); - return 0; - } catch (error) { - process.stderr.write(`Unable to verify release manifest: ${error instanceof Error ? error.message : String(error)}\n`); - return 1; - } -}; - - -const verify_release_entry_main = main; -if (typeof verify_release_entry_main !== 'function') { - throw new TypeError('Executable entry must export a main function: ' + "/fast/projects/agent-bundle-worktrees/host-test/examples/hooks-and-scripts/src/scripts/verify-release.ts"); -} -const code = await verify_release_entry_main(process.argv.slice(2)); -if (typeof code === 'number') process.exitCode = code; - -export {}; diff --git a/examples/hooks-and-scripts/artifact/portable/INSTALL.md b/examples/hooks-and-scripts/artifact/portable/INSTALL.md deleted file mode 100644 index 0c3c03165..000000000 --- a/examples/hooks-and-scripts/artifact/portable/INSTALL.md +++ /dev/null @@ -1,19 +0,0 @@ -# Install hooks-and-scripts - -Hook simulation, script traces, logs, and recovery. - -Version: `1.0.0` - -Run these commands from this bundle directory. - -## Portable Agent Plugin - -Portable is a distribution profile, not a host runtime with one universal install location. -This bundle follows the Agent Plugins open standard (Agent Plugins 1.0.0, https://agent-plugins.org). -Cursor loads this format natively from `~/.cursor/plugins/local/`; restart Cursor or run -`Developer: Reload Window` after copying it. Codex, VS Code, GitHub Copilot, Kiro, and ChatGPT -are also native clients. The bundled installer provides the Cursor local copy: - -```sh -node ./install.mjs -``` diff --git a/examples/hooks-and-scripts/artifact/portable/assets/release/release-manifest.json b/examples/hooks-and-scripts/artifact/portable/assets/release/release-manifest.json deleted file mode 100644 index 819d86560..000000000 --- a/examples/hooks-and-scripts/artifact/portable/assets/release/release-manifest.json +++ /dev/null @@ -1,21 +0,0 @@ -{ - "version": "2.4.0", - "changelog": "CHANGELOG.md#2.4.0", - "artifacts": [ - { - "name": "package", - "path": "dist/agent-bundle-2.4.0.tgz", - "status": "ready" - }, - { - "name": "checksums", - "path": "dist/agent-bundle-2.4.0.sha256", - "status": "ready" - }, - { - "name": "sbom", - "path": "dist/agent-bundle-2.4.0.sbom.json", - "status": "ready" - } - ] -} diff --git a/examples/hooks-and-scripts/artifact/portable/assets/release/risk-register.json b/examples/hooks-and-scripts/artifact/portable/assets/release/risk-register.json deleted file mode 100644 index 2295bcc45..000000000 --- a/examples/hooks-and-scripts/artifact/portable/assets/release/risk-register.json +++ /dev/null @@ -1,16 +0,0 @@ -{ - "risks": [ - { - "id": "REL-204", - "severity": "high", - "status": "open", - "summary": "Complete the final approval for the release notes before publishing." - }, - { - "id": "REL-198", - "severity": "medium", - "status": "mitigated", - "summary": "Package signing rehearsal is documented in the release runbook." - } - ] -} diff --git a/examples/hooks-and-scripts/artifact/portable/install.mjs b/examples/hooks-and-scripts/artifact/portable/install.mjs deleted file mode 100644 index 8873d4b6a..000000000 --- a/examples/hooks-and-scripts/artifact/portable/install.mjs +++ /dev/null @@ -1,80 +0,0 @@ -#!/usr/bin/env node -import { createHash } from 'node:crypto'; -import { cp, lstat, mkdir, mkdtemp, readFile, readdir, rename, rm } from 'node:fs/promises'; -import { homedir } from 'node:os'; -import { basename, join, resolve } from 'node:path'; -import { fileURLToPath } from 'node:url'; - -const pluginName = "hooks-and-scripts"; -const pluginVersion = "1.0.0"; -const source = resolve(fileURLToPath(new URL('.', import.meta.url))); -const cursorRoot = join(homedir(), '.cursor'); -const installRoot = join(cursorRoot, 'plugins', 'local'); -const destination = join(installRoot, pluginName); - -const exists = async (path) => { - try { await lstat(path); return true; } - catch (error) { if (error?.code === 'ENOENT') return false; throw error; } -}; - -const treeHash = async (root, prefix = '') => { - const rootMetadata = await lstat(root); - if (rootMetadata.isSymbolicLink() || !rootMetadata.isDirectory()) { - throw new Error('Refusing unsupported filesystem entry ".".'); - } - const hash = createHash('sha256'); - const visit = async (relative) => { - const absolute = join(root, relative); - const metadata = await lstat(absolute); - if (metadata.isSymbolicLink() || (!metadata.isDirectory() && !metadata.isFile())) { - throw new Error(`Refusing unsupported filesystem entry ${JSON.stringify(relative || '.')}.`); - } - if (metadata.isDirectory()) { - for (const name of (await readdir(absolute)).sort()) await visit(join(relative, name)); - return; - } - hash.update(relative.replaceAll('\\', '/')); - hash.update('\0'); - hash.update(await readFile(absolute)); - hash.update('\0'); - }; - for (const name of (await readdir(root)).sort()) await visit(join(prefix, name)); - return hash.digest('hex'); -}; - -const installedVersion = async () => { - for (const manifest of ['.cursor-plugin/plugin.json', 'plugin.json']) { - try { - const value = JSON.parse(await readFile(join(destination, manifest), 'utf8')); - if (typeof value.version === 'string') return value.version; - } catch (error) { if (error?.code !== 'ENOENT') throw error; } - } - return undefined; -}; - -if (!(await exists(cursorRoot)) || !(await lstat(cursorRoot)).isDirectory()) { - throw new Error(`Cursor is not installed in ${cursorRoot}.`); -} -await mkdir(installRoot, { recursive: true }); -if (await exists(destination)) { - const currentVersion = await installedVersion(); - if (currentVersion !== undefined && currentVersion !== pluginVersion) { - throw new Error(`Refusing version collision at ${destination}: found ${currentVersion}, requested ${pluginVersion}.`); - } - if (source === destination || await treeHash(source) === await treeHash(destination)) { - console.log(`Already installed ${pluginName}@${pluginVersion} at ${destination}`); - process.exit(0); - } - throw new Error(`Refusing content collision at ${destination}.`); -} - -const stageParent = await mkdtemp(join(installRoot, `.${basename(destination)}.stage-`)); -const stage = join(stageParent, 'bundle'); -try { - await cp(source, stage, { errorOnExist: true, force: false, recursive: true, verbatimSymlinks: true }); - await treeHash(stage); - await rename(stage, destination); - console.log(`Installed ${pluginName}@${pluginVersion} at ${destination}`); -} finally { - await rm(stageParent, { force: true, recursive: true }); -} diff --git a/examples/hooks-and-scripts/artifact/portable/plugin.json b/examples/hooks-and-scripts/artifact/portable/plugin.json deleted file mode 100644 index 2f19512e9..000000000 --- a/examples/hooks-and-scripts/artifact/portable/plugin.json +++ /dev/null @@ -1 +0,0 @@ -{"$schema":"https://agent-plugins.org/schemas/1.0.0/plugin.schema.json","description":"Hook simulation, script traces, logs, and recovery.","name":"hooks-and-scripts","version":"1.0.0"} diff --git a/examples/hooks-and-scripts/artifact/portable/scripts/detect-risk.mjs b/examples/hooks-and-scripts/artifact/portable/scripts/detect-risk.mjs deleted file mode 100644 index 99bd912f8..000000000 --- a/examples/hooks-and-scripts/artifact/portable/scripts/detect-risk.mjs +++ /dev/null @@ -1,35 +0,0 @@ -import { readFile } from "node:fs/promises"; - - - - - -const registerPath = new URL('../assets/release/risk-register.json', import.meta.url); -const main = async ()=>{ - try { - const register = JSON.parse(await readFile(registerPath, 'utf8')); - if (!Array.isArray(register.risks)) throw new Error('risk register must contain a risks array'); - const blockers = register.risks.filter((risk)=>risk.status === 'open' && risk.severity === 'high'); - if (blockers.length === 0) { - process.stdout.write('No open high-severity release risks found.\n'); - return 0; - } - for (const risk of blockers){ - process.stderr.write(`${typeof risk.id === 'string' ? risk.id : 'UNIDENTIFIED'}: ${typeof risk.summary === 'string' ? risk.summary : 'Open high-severity release risk'}\n`); - } - return 2; - } catch (error) { - process.stderr.write(`Unable to detect release risks: ${error instanceof Error ? error.message : String(error)}\n`); - return 1; - } -}; - - -const detect_risk_entry_main = main; -if (typeof detect_risk_entry_main !== 'function') { - throw new TypeError('Executable entry must export a main function: ' + "/fast/projects/agent-bundle-worktrees/host-test/examples/hooks-and-scripts/src/scripts/detect-risk.ts"); -} -const code = await detect_risk_entry_main(process.argv.slice(2)); -if (typeof code === 'number') process.exitCode = code; - -export {}; diff --git a/examples/hooks-and-scripts/artifact/portable/scripts/verify-release.mjs b/examples/hooks-and-scripts/artifact/portable/scripts/verify-release.mjs deleted file mode 100644 index 6ac9cd7a9..000000000 --- a/examples/hooks-and-scripts/artifact/portable/scripts/verify-release.mjs +++ /dev/null @@ -1,54 +0,0 @@ -import { readFile } from "node:fs/promises"; - - - - - -const requiredArtifacts = [ - 'package', - 'checksums', - 'sbom' -]; -const manifestPath = new URL('../assets/release/release-manifest.json', import.meta.url); -const readManifest = async ()=>JSON.parse(await readFile(manifestPath, 'utf8')); -const validationErrors = (manifest)=>{ - const errors = []; - if (typeof manifest.version !== 'string' || !/^\d+\.\d+\.\d+$/.test(manifest.version)) { - errors.push('version must use major.minor.patch format'); - } - if (typeof manifest.changelog !== 'string' || manifest.changelog.trim().length === 0) { - errors.push('changelog must identify the release notes'); - } - for (const name of requiredArtifacts){ - const artifact = manifest.artifacts?.find((candidate)=>candidate.name === name); - if (artifact === undefined || typeof artifact.path !== 'string' || artifact.path.trim().length === 0 || artifact.status !== 'ready') { - errors.push(`${name} artifact must have a ready path`); - } - } - return errors; -}; -const main = async ()=>{ - try { - const manifest = await readManifest(); - const errors = validationErrors(manifest); - if (errors.length > 0) { - process.stderr.write(`Release manifest is incomplete:\n${errors.map((error)=>`- ${error}`).join('\n')}\n`); - return 1; - } - process.stdout.write(`Release ${manifest.version} is ready for packaging.\n`); - return 0; - } catch (error) { - process.stderr.write(`Unable to verify release manifest: ${error instanceof Error ? error.message : String(error)}\n`); - return 1; - } -}; - - -const verify_release_entry_main = main; -if (typeof verify_release_entry_main !== 'function') { - throw new TypeError('Executable entry must export a main function: ' + "/fast/projects/agent-bundle-worktrees/host-test/examples/hooks-and-scripts/src/scripts/verify-release.ts"); -} -const code = await verify_release_entry_main(process.argv.slice(2)); -if (typeof code === 'number') process.exitCode = code; - -export {}; diff --git a/examples/mcp-app/artifact/agent-bundle.hooks.json b/examples/mcp-app/artifact/agent-bundle.hooks.json deleted file mode 100644 index c41cd4504..000000000 --- a/examples/mcp-app/artifact/agent-bundle.hooks.json +++ /dev/null @@ -1 +0,0 @@ -{"hooks":[{"event":"sessionStart","id":"hook:session-start:session-start:7ab7e8a5","name":"session-start-session-start-7ab7e8a5","path":"claude/hooks/session-start-session-start-7ab7e8a5.mjs","target":"claude"},{"event":"sessionStart","id":"hook:session-start:session-start:7ab7e8a5","name":"session-start-session-start-7ab7e8a5","path":"codex/hooks/session-start-session-start-7ab7e8a5.mjs","target":"codex"}]} diff --git a/examples/mcp-app/artifact/agent-bundle.manifest.json b/examples/mcp-app/artifact/agent-bundle.manifest.json deleted file mode 100644 index 949cf5538..000000000 --- a/examples/mcp-app/artifact/agent-bundle.manifest.json +++ /dev/null @@ -1 +0,0 @@ -{"agentSkills":{"schemaSha256":"6d06b61e423317421de2295ea1fd0c7b4491bfa36c5b7705c28616dfe76d4047","sourceRevision":"69ef37e9424c0a7ea9dd2293b559e43ec8176379","specification":"https://raw.githubusercontent.com/agentskills/agentskills/69ef37e9424c0a7ea9dd2293b559e43ec8176379/docs/specification.mdx"},"files":[{"bytes":412,"kind":"generated","path":"agent-bundle.hooks.json","sha256":"c085b5d4bc728917cba2d53546cdd9f6b065f9e84a846d31d3e4ccb254f5819a","sourceInputs":["agent-bundle.config.ts"]},{"bytes":353,"kind":"generated","path":"claude/.claude-plugin/marketplace.json","sha256":"e4cf51c12ad7b9c9c78c3ae09e1564bff251152d162cd562247e8f5dca5868a7","sourceInputs":["agent-bundle.config.ts"]},{"bytes":214,"kind":"generated","path":"claude/.claude-plugin/plugin.json","sha256":"20bca77e21ea7fbb9ceb1c1fd0c06b7bd67216a20d8a9922fab5ad8f915e5604","sourceInputs":["agent-bundle.config.ts","src/mcp/status.ts","src/skills/service-readiness/SKILL.md"]},{"bytes":180,"kind":"generated","path":"claude/.mcp.json","sha256":"f7d402486d6d2de1fbbf6d95183a7f16aaed23f1b4b625c4075e3a67d11458aa","sourceInputs":["agent-bundle.config.ts","src/mcp/status.ts"]},{"bytes":231,"kind":"copy","path":"claude/assets/evals/fixtures/status/result.json","sha256":"f9a03542d74a4f7e3ecac0ea161b820f0dcbbdfc4c1db3889401064653bd9811","sourceInputs":["evals/fixtures/status/result.json"]},{"bytes":150,"kind":"generated","path":"claude/hooks/hooks.json","sha256":"8855c477158d687920a5d1da416ee8c980cc305f3adde65488dcef55e8b8da06","sourceInputs":["agent-bundle.config.ts"]},{"bytes":12031,"kind":"bundle","path":"claude/hooks/session-start-session-start-7ab7e8a5.mjs","sha256":"29d109b65676b38ff7c54a26bb90b6346e3dc110ce8a781dfb71be8c0439c4a1","sourceInputs":["agent-bundle.config.ts","src/hooks/session-start.ts"]},{"bytes":472,"kind":"generated","path":"claude/INSTALL.md","sha256":"84f35da9c85137d58c7ea6e458c1794e3396d95e709a2dde0784014ca784bb1b","sourceInputs":["agent-bundle.config.ts"]},{"bytes":1211760,"kind":"bundle","path":"claude/mcp/mcp-status-073c1634.mjs","sha256":"80aa4516620d80e170e0ead5efcf49b7ea910a9dd36fed2a0f8e7f9f3e52c406","sourceInputs":["src/compiler-status-contract.ts","src/mcp/status.ts"]},{"bytes":2328,"kind":"bundle","path":"claude/scripts/check-service-fixture.mjs","sha256":"41067e3d875b6ae452b21ba105d032e3c8ca3eec81463803798a1e9f13b50935","sourceInputs":["agent-bundle.config.ts","src/compiler-status-contract.ts","src/scripts/check-service-fixture.ts"]},{"bytes":528,"kind":"copy","path":"claude/skills/service-readiness/assets/readiness-report.md","sha256":"772e118b18070497c0f589bc4f9b37c71ade5ce59ba4a6904c65b2b724f8714b","sourceInputs":["src/skills/service-readiness/assets/readiness-report.md","src/skills/service-readiness/SKILL.md"]},{"bytes":904,"kind":"copy","path":"claude/skills/service-readiness/references/status-policy.md","sha256":"0319ad5884b291b01433d559429dcdb5d265bc5715b3c7bff734afa257ebef5b","sourceInputs":["src/skills/service-readiness/references/status-policy.md","src/skills/service-readiness/SKILL.md"]},{"bytes":1344,"kind":"copy","path":"claude/skills/service-readiness/SKILL.md","sha256":"de9bebc358e0ba30d769d7e9bad6175251a858efe4e704941f9ef6dc830261f3","sourceInputs":["src/skills/service-readiness/SKILL.md"]},{"bytes":258,"kind":"generated","path":"codex/.agents/plugins/marketplace.json","sha256":"c8b0fe73ece00cbf09fed92e1011d2d5e28211c7e7f4dfa1fddf3fba4c462b0a","sourceInputs":["agent-bundle.config.ts"]},{"bytes":674,"kind":"generated","path":"codex/.codex-plugin/plugin.json","sha256":"8dd1d6259f076f8f62cd35bb7c466c3dec95aeb4433416f4e52202f56673c11e","sourceInputs":["agent-bundle.config.ts","src/mcp/status.ts","src/skills/service-readiness/SKILL.md"]},{"bytes":152,"kind":"generated","path":"codex/.mcp.json","sha256":"62064b39f8cddd0db51b7aa25a688bbff3ae7621376be506ff5d5542b037c9de","sourceInputs":["agent-bundle.config.ts","src/mcp/status.ts"]},{"bytes":231,"kind":"copy","path":"codex/assets/evals/fixtures/status/result.json","sha256":"f9a03542d74a4f7e3ecac0ea161b820f0dcbbdfc4c1db3889401064653bd9811","sourceInputs":["evals/fixtures/status/result.json"]},{"bytes":143,"kind":"generated","path":"codex/hooks/hooks.json","sha256":"ad0e296b15c799f52459488b17f46f7cc3a34e1abf4b9466a178d17a7fdaa605","sourceInputs":["agent-bundle.config.ts"]},{"bytes":12174,"kind":"bundle","path":"codex/hooks/session-start-session-start-7ab7e8a5.mjs","sha256":"c91fb5cdbde27b34f97f9ba62e7b897bf337eda7e2086f98c9f300f6eab89102","sourceInputs":["agent-bundle.config.ts","src/hooks/session-start.ts"]},{"bytes":360,"kind":"generated","path":"codex/INSTALL.md","sha256":"4efefa497a9acdd073703dfc3ff2c81cd5005cea0f777a204a275988193c907f","sourceInputs":["agent-bundle.config.ts"]},{"bytes":1211760,"kind":"bundle","path":"codex/mcp/mcp-status-073c1634.mjs","sha256":"80aa4516620d80e170e0ead5efcf49b7ea910a9dd36fed2a0f8e7f9f3e52c406","sourceInputs":["src/compiler-status-contract.ts","src/mcp/status.ts"]},{"bytes":2328,"kind":"bundle","path":"codex/scripts/check-service-fixture.mjs","sha256":"41067e3d875b6ae452b21ba105d032e3c8ca3eec81463803798a1e9f13b50935","sourceInputs":["agent-bundle.config.ts","src/compiler-status-contract.ts","src/scripts/check-service-fixture.ts"]},{"bytes":528,"kind":"copy","path":"codex/skills/service-readiness/assets/readiness-report.md","sha256":"772e118b18070497c0f589bc4f9b37c71ade5ce59ba4a6904c65b2b724f8714b","sourceInputs":["src/skills/service-readiness/assets/readiness-report.md","src/skills/service-readiness/SKILL.md"]},{"bytes":904,"kind":"copy","path":"codex/skills/service-readiness/references/status-policy.md","sha256":"0319ad5884b291b01433d559429dcdb5d265bc5715b3c7bff734afa257ebef5b","sourceInputs":["src/skills/service-readiness/references/status-policy.md","src/skills/service-readiness/SKILL.md"]},{"bytes":1344,"kind":"copy","path":"codex/skills/service-readiness/SKILL.md","sha256":"de9bebc358e0ba30d769d7e9bad6175251a858efe4e704941f9ef6dc830261f3","sourceInputs":["src/skills/service-readiness/SKILL.md"]},{"bytes":231,"kind":"copy","path":"portable/assets/evals/fixtures/status/result.json","sha256":"f9a03542d74a4f7e3ecac0ea161b820f0dcbbdfc4c1db3889401064653bd9811","sourceInputs":["evals/fixtures/status/result.json"]},{"bytes":701,"kind":"generated","path":"portable/INSTALL.md","sha256":"be9540f5b8012f6a7963532282469fa34119537a7203237fb18fd0b09f1710e3","sourceInputs":["agent-bundle.config.ts"]},{"bytes":3309,"kind":"generated","path":"portable/install.mjs","sha256":"971868b98246361915db7b21461b3cb105cc02bc0c163b70acaef9d89d0f9d6b","sourceInputs":["agent-bundle.config.ts"]},{"bytes":447791,"kind":"bundle","path":"portable/mcp-apps/status.html","sha256":"33d62b8fb201360c8a2493934f8fa23eb799ad87c9c04a01a95cccdfe04e557d","sourceInputs":["agent-bundle.config.ts","views/status-panel.html","views/status-panel.ts"]},{"bytes":242,"kind":"generated","path":"portable/mcp.json","sha256":"79461543b66617388e3ead6b60c90576ee9ed9be17d4e19e2febf58b872e05e3","sourceInputs":["src/mcp/status.ts"]},{"bytes":1674914,"kind":"bundle","path":"portable/mcp/mcp-status-073c1634.mjs","sha256":"65be2e5694b954fd3743e7ca9ceda97071c2d775269a900c6394ed6a0bad9849","sourceInputs":["agent-bundle.config.ts","src/compiler-status-contract.ts","src/mcp/status.ts","views/status-panel.html","views/status-panel.ts"]},{"bytes":220,"kind":"generated","path":"portable/plugin.json","sha256":"e0e8d291a995eece0fdaf1200e86cd06089c219f1c74cbc55241b89e93fa72f3","sourceInputs":["agent-bundle.config.ts"]},{"bytes":2328,"kind":"bundle","path":"portable/scripts/check-service-fixture.mjs","sha256":"41067e3d875b6ae452b21ba105d032e3c8ca3eec81463803798a1e9f13b50935","sourceInputs":["agent-bundle.config.ts","src/compiler-status-contract.ts","src/scripts/check-service-fixture.ts"]},{"bytes":528,"kind":"copy","path":"portable/skills/service-readiness/assets/readiness-report.md","sha256":"772e118b18070497c0f589bc4f9b37c71ade5ce59ba4a6904c65b2b724f8714b","sourceInputs":["src/skills/service-readiness/assets/readiness-report.md","src/skills/service-readiness/SKILL.md"]},{"bytes":904,"kind":"copy","path":"portable/skills/service-readiness/references/status-policy.md","sha256":"0319ad5884b291b01433d559429dcdb5d265bc5715b3c7bff734afa257ebef5b","sourceInputs":["src/skills/service-readiness/references/status-policy.md","src/skills/service-readiness/SKILL.md"]},{"bytes":1344,"kind":"copy","path":"portable/skills/service-readiness/SKILL.md","sha256":"de9bebc358e0ba30d769d7e9bad6175251a858efe4e704941f9ef6dc830261f3","sourceInputs":["src/skills/service-readiness/SKILL.md"]}],"producer":{"name":"agent-bundle","version":"0.1.0"},"project":{"configDigest":"c6ec1f92b7f7f28c7eb485b9ad22b0fdda89ea63e58166a27b9969d0243cef89","configPath":"agent-bundle.config.ts","modelDigest":"8551c2c0a6630de6e3366155442b9919259fbf3331245219ad6e6dc4549069b3","packageName":"@agent-bundle-example/mcp-app","revision":"914a0ee2dcafedf9136a1c3a3885150f98313a6d4035e8c1e9f9e13a86083c13","sourceInputs":[{"executable":false,"path":"agent-bundle.config.ts","sha256":"c6ec1f92b7f7f28c7eb485b9ad22b0fdda89ea63e58166a27b9969d0243cef89"},{"executable":false,"path":"evals/fixtures/status/result.json","sha256":"f9a03542d74a4f7e3ecac0ea161b820f0dcbbdfc4c1db3889401064653bd9811"},{"executable":false,"path":"evals/graders/status-result.ts","sha256":"b846dd661ff5f9af9dd15df7a2208344c13c6153514c9435a585a0caa820ebaf"},{"executable":false,"path":"evals/status.eval.ts","sha256":"ad0f9f1e216aec4684b4b51e337387b893c978e827ae8c5edf2ea41dfdf82207"},{"executable":false,"path":"package.json","sha256":"29ef79c4d6f863920649fd6162611a6344b1e4fd8a068c64229aa321be1d9cc3"},{"executable":false,"path":"README.md","sha256":"35e3f3656ce34c5ed1181917ecebc40d10ec3f121630ade7ff7db7093e2db6df"},{"executable":false,"path":"rstest.browser-app.config.ts","sha256":"e2de9384badc7c4fb6b89ea5b54ed85fd3cacbe9e31162555362d0c89a318557"},{"executable":false,"path":"src/compiler-status-contract.ts","sha256":"ff8484b2ae613abb1cf2f76c70f558733563228570df1c05485a3a04ebffcd59"},{"executable":false,"path":"src/hooks/session-start.ts","sha256":"b856621ec280ed94a8e1dfa0fe065a1ff4d41690ff07be9e148c01b1180fd346"},{"executable":false,"path":"src/mcp/status.ts","sha256":"9116902d7041d30b4c3fcb412b2d83a793975fdac9632648e07dfc85da2a73c1"},{"executable":false,"path":"src/scripts/check-service-fixture.ts","sha256":"32967d447487049c62af2195612ec6f2b5de630753ea2c20b473faf93e804fba"},{"executable":false,"path":"src/skills/service-readiness/assets/readiness-report.md","sha256":"772e118b18070497c0f589bc4f9b37c71ade5ce59ba4a6904c65b2b724f8714b"},{"executable":false,"path":"src/skills/service-readiness/references/status-policy.md","sha256":"0319ad5884b291b01433d559429dcdb5d265bc5715b3c7bff734afa257ebef5b"},{"executable":false,"path":"src/skills/service-readiness/SKILL.md","sha256":"de9bebc358e0ba30d769d7e9bad6175251a858efe4e704941f9ef6dc830261f3"},{"executable":false,"path":"tests/browser-app/status-panel.browser.test.ts","sha256":"a49e632decebd56db42214afc3f1cba8729c24b594935e4b2468e3a2d4ad6695"},{"executable":false,"path":"views/status-panel.html","sha256":"75018093566d7bfdf16dfffcc072d4983e0c2ecd5f40f592e27e571cb3e5a868"},{"executable":false,"path":"views/status-panel.ts","sha256":"3bd3017d4f4d730293b15f386c5949b390bc8bba1ed2c5fd861efed477afefc8"}]},"runtime":{"node":"22.12.0"},"targets":[{"adapterRevision":"1.22.0","name":"claude","observedVersion":"2.1.250","schemas":[{"name":"hooks","revision":"2.1.250","sha256":"3c6f3e4391f3dca939d75bd0b200ea88e68db939a2cb885d46f0b143293efb84"},{"name":"lsp","revision":"2.1.250","sha256":"c81fd2f57c410f70f8e5c3f84483f5ec1b575ee02802b424977826f757dccd8e"},{"name":"marketplace","revision":"2.1.250","sha256":"4ffa94e8024966e8080b9d3b338c9612bdfa255802a8491b43f74f90427bc988"},{"name":"mcp","revision":"2.1.250","sha256":"76ccf02c7bfe2d57945ba18e84da8d655529bd68b4d692f72bce28238c99067e"},{"name":"monitors","revision":"2.1.250","sha256":"d45abdf7561e4316ba217ce9c2ac84f32e1049622b74abb081693b479a54b48d"},{"name":"plugin","revision":"2.1.250","sha256":"3c9943237da86fd08ae82f698cde36dbef2ecf742098c6961cedf481fe435c12"},{"name":"settings","revision":"2.1.250","sha256":"9e86d8c5e4053e8de0e468d349e2c3dde5834d22d6769372b88570e301700073"},{"name":"theme","revision":"2.1.250","sha256":"721aa9b0bc7c60cd9359343e5c7205ffbdfea82da312f601720c9dfaa2d8cf0d"}]},{"adapterRevision":"1.8.0","name":"codex","observedVersion":"0.147.0","schemas":[{"name":"app","revision":"0.147.0","sha256":"01c720a645e437bf0c4f8c26fd4cb5a13988e5649e4a8562ee23a1d4b7355c6a"},{"name":"hooks","revision":"0.147.0","sha256":"175b859eb8e85bd287d85ee840d97c3f5c2d0dda3223507a796d158e3770eeba"},{"name":"marketplace","revision":"0.147.0","sha256":"fbccce3ade39e1b077fcb440e60260de6e811e8c2d222b2ae0fe8fe47706b470"},{"name":"mcp","revision":"0.147.0","sha256":"75bd50f9fcb85c2e8d43bc132d61c172a02f28ea8bb77389816ae77b14a4257e"},{"name":"plugin","revision":"0.147.0","sha256":"4ad476545c96c83d899c4524dcccd4eb4fe7d3299c307878a0cd46a237f48d58"}]},{"adapterRevision":"1.6.0","name":"portable","observedVersion":"1.0.0","schemas":[{"name":"mcp","revision":"1.0.0","sha256":"6539175bfcdf43085855183e86da40ea94b166547a72b47ae9a0a390516d3acb"},{"name":"plugin","revision":"1.0.0","sha256":"0a4aad95ce337878ad38802ebf0daa3fde76abe3f65400c86bcbb1ec0b3ab883"}]}],"validation":{"artifact":{"status":"passed"},"source":{"status":"passed"},"targets":[{"name":"claude","status":"passed"},{"name":"codex","status":"passed"},{"name":"portable","status":"passed"}]}} diff --git a/examples/mcp-app/artifact/claude/.claude-plugin/marketplace.json b/examples/mcp-app/artifact/claude/.claude-plugin/marketplace.json deleted file mode 100644 index d24f68ca5..000000000 --- a/examples/mcp-app/artifact/claude/.claude-plugin/marketplace.json +++ /dev/null @@ -1 +0,0 @@ -{"description":"A unified service-readiness assistant with MCP, Skills, Hooks, scripts, and evaluation.","name":"mcp-app-example-marketplace","owner":{"name":"mcp-app-example"},"plugins":[{"description":"A unified service-readiness assistant with MCP, Skills, Hooks, scripts, and evaluation.","name":"mcp-app-example","source":"./","version":"1.0.0"}]} diff --git a/examples/mcp-app/artifact/claude/.claude-plugin/plugin.json b/examples/mcp-app/artifact/claude/.claude-plugin/plugin.json deleted file mode 100644 index 3a3e7a43d..000000000 --- a/examples/mcp-app/artifact/claude/.claude-plugin/plugin.json +++ /dev/null @@ -1 +0,0 @@ -{"author":{"name":"mcp-app-example"},"description":"A unified service-readiness assistant with MCP, Skills, Hooks, scripts, and evaluation.","hooks":"./hooks/hooks.json","name":"mcp-app-example","version":"1.0.0"} diff --git a/examples/mcp-app/artifact/claude/.mcp.json b/examples/mcp-app/artifact/claude/.mcp.json deleted file mode 100644 index a8c317b72..000000000 --- a/examples/mcp-app/artifact/claude/.mcp.json +++ /dev/null @@ -1 +0,0 @@ -{"mcpServers":{"status":{"args":["${CLAUDE_PLUGIN_ROOT}/mcp/mcp-status-073c1634.mjs"],"command":"node","env":{"AGENT_BUNDLE_PLUGIN_ROOT":"${CLAUDE_PLUGIN_ROOT}"},"type":"stdio"}}} diff --git a/examples/mcp-app/artifact/claude/INSTALL.md b/examples/mcp-app/artifact/claude/INSTALL.md deleted file mode 100644 index b69cfdbf3..000000000 --- a/examples/mcp-app/artifact/claude/INSTALL.md +++ /dev/null @@ -1,18 +0,0 @@ -# Install mcp-app-example - -A unified service-readiness assistant with MCP, Skills, Hooks, scripts, and evaluation. - -Version: `1.0.0` - -Run these commands from this bundle directory. - -## Claude Code - -Claude Code installs this bundle through its local marketplace contract: - -```sh -claude plugin marketplace add ./ -claude plugin install mcp-app-example@mcp-app-example-marketplace --scope user -``` - -Replace `user` with `project` or `local` when that Claude scope is intended. diff --git a/examples/mcp-app/artifact/claude/assets/evals/fixtures/status/result.json b/examples/mcp-app/artifact/claude/assets/evals/fixtures/status/result.json deleted file mode 100644 index a765aa4b5..000000000 --- a/examples/mcp-app/artifact/claude/assets/evals/fixtures/status/result.json +++ /dev/null @@ -1,9 +0,0 @@ -{ - "service": "compiler", - "status": "healthy", - "summary": "Compiler service is ready for release.", - "checks": [ - { "label": "Availability", "status": "passing" }, - { "label": "Build queue", "status": "passing" } - ] -} diff --git a/examples/mcp-app/artifact/claude/hooks/hooks.json b/examples/mcp-app/artifact/claude/hooks/hooks.json deleted file mode 100644 index 1afdaac5a..000000000 --- a/examples/mcp-app/artifact/claude/hooks/hooks.json +++ /dev/null @@ -1 +0,0 @@ -{"hooks":{"SessionStart":[{"hooks":[{"command":"node \"${CLAUDE_PLUGIN_ROOT}/hooks/session-start-session-start-7ab7e8a5.mjs\"","type":"command"}]}]}} diff --git a/examples/mcp-app/artifact/claude/hooks/session-start-session-start-7ab7e8a5.mjs b/examples/mcp-app/artifact/claude/hooks/session-start-session-start-7ab7e8a5.mjs deleted file mode 100644 index 60c3d473d..000000000 --- a/examples/mcp-app/artifact/claude/hooks/session-start-session-start-7ab7e8a5.mjs +++ /dev/null @@ -1,253 +0,0 @@ -// The require scope -var __webpack_require__ = {}; - -// webpack/runtime/define_property_getters -(() => { -__webpack_require__.d = (exports, getters, values) => { - var define = (defs, kind) => { - for(var key in defs) { - if(__webpack_require__.o(defs, key) && !__webpack_require__.o(exports, key)) { - Object.defineProperty(exports, key, { enumerable: true, [kind]: defs[key] }); - } - } - }; - define(getters, "get"); - define(values, "value"); -}; -})(); -// webpack/runtime/has_own_property -(() => { -__webpack_require__.o = (obj, prop) => (Object.prototype.hasOwnProperty.call(obj, prop)) -})(); -// webpack/runtime/make_namespace_object -(() => { -// define __esModule on exports -__webpack_require__.r = (exports) => { - if(typeof Symbol !== 'undefined' && Symbol.toStringTag) { - Object.defineProperty(exports, Symbol.toStringTag, { value: 'Module' }); - } - Object.defineProperty(exports, '__esModule', { value: true }); -}; -})(); - -// NAMESPACE OBJECT: ./src/hooks/session-start.ts -var session_start_namespaceObject = {}; -__webpack_require__.r(session_start_namespaceObject); -__webpack_require__.d(session_start_namespaceObject, { - "default": () => (session_start) }); - - -/* export default */ const session_start = ((event)=>({ - additionalContext: [ - `Service readiness session ${event.sessionId ?? 'is active'} from ${event.source ?? 'an unknown source'}.`, - `Use the service-readiness Skill, then run check-service-fixture from ${event.cwd ?? process.cwd()} before release review.`, - 'Use show-status for compiler or payments-api when live service evidence is needed.' - ].join(' '), - outcome: 'continue' - })); - - -const target = "claude"; -const canonicalEvent = "sessionStart"; -const nativeEvent = "SessionStart"; -const isRecord = (value)=>typeof value === "object" && value !== null && !Array.isArray(value); -const defined = (value)=>Object.fromEntries(Object.entries(value).filter(([, item])=>item !== undefined)); -const decodeClaudeNative = (nativeInput)=>({ - agentId: nativeInput.agent_id, - agentTranscriptPath: nativeInput.agent_transcript_path, - agentType: nativeInput.agent_type, - cwd: nativeInput.cwd, - effort: nativeInput.effort, - hookEventName: nativeInput.hook_event_name, - lastAssistantMessage: nativeInput.last_assistant_message, - model: nativeInput.model, - permissionMode: nativeInput.permission_mode, - promptId: nativeInput.prompt_id, - sessionId: nativeInput.session_id, - source: nativeInput.source, - stopHookActive: nativeInput.stop_hook_active, - toolInput: nativeInput.tool_input, - toolName: nativeInput.tool_name, - toolResponse: nativeInput.tool_response, - toolUseId: nativeInput.tool_use_id, - transcriptPath: nativeInput.transcript_path, - turnId: nativeInput.turn_id - }); -const encodeClaudeNative = (canonicalInput)=>defined({ - hook_event_name: nativeEvent, - agent_id: canonicalInput.agentId, - agent_transcript_path: canonicalInput.agentTranscriptPath, - agent_type: canonicalInput.agentType, - cwd: canonicalInput.cwd, - effort: canonicalInput.effort, - last_assistant_message: canonicalInput.lastAssistantMessage, - model: canonicalInput.model, - permission_mode: canonicalInput.permissionMode, - prompt_id: canonicalInput.promptId, - session_id: canonicalInput.sessionId, - source: canonicalInput.source, - stop_hook_active: canonicalInput.stopHookActive, - tool_input: canonicalInput.toolInput, - tool_name: canonicalInput.toolName, - tool_response: canonicalInput.toolResponse, - tool_use_id: canonicalInput.toolUseId, - transcript_path: canonicalInput.transcriptPath, - turn_id: canonicalInput.turnId - }); -const decodeNative = decodeClaudeNative; -const encodeNative = encodeClaudeNative; -const fail = (message)=>{ - throw new Error(`Agent Bundle hook error: ${message}`); -}; -const validateResult = (result)=>{ - if (result === undefined) return undefined; - if (!isRecord(result)) fail("handler must return void or a result object"); - const allowed = new Set([ - "outcome", - "reason", - "updatedInput", - "additionalContext" - ]); - for (const key of Object.keys(result))if (!allowed.has(key)) fail(`handler result has unsupported field ${key}`); - if (result.outcome !== undefined && ![ - "continue", - "deny", - "stop" - ].includes(result.outcome)) fail("handler result outcome is invalid"); - if (result.reason !== undefined && typeof result.reason !== "string") fail("handler result reason must be a string"); - if (result.additionalContext !== undefined && typeof result.additionalContext !== "string") fail("handler result additionalContext must be a string"); - if (result.updatedInput !== undefined && !isRecord(result.updatedInput)) fail("handler result updatedInput must be an object"); - const supportsDeniedReason = canonicalEvent === "beforeTool" || canonicalEvent === "stop" || canonicalEvent === "agentStop"; - if (result.reason !== undefined && !(result.outcome === "deny" && supportsDeniedReason)) fail("reason is only valid for a denied beforeTool, stop, or agentStop hook"); - if (result.outcome === "deny" && supportsDeniedReason && (typeof result.reason !== "string" || result.reason.trim().length === 0)) fail(`denied ${canonicalEvent} hook requires a nonempty reason`); - if ((canonicalEvent === "sessionStart" || canonicalEvent === "afterTool" || canonicalEvent === "agentStart") && (result.outcome === "deny" || result.outcome === "stop" || result.updatedInput !== undefined)) fail(`${canonicalEvent} cannot deny, stop, or replace input`); - if (canonicalEvent === "beforeTool" && (result.outcome === "stop" || result.outcome === "deny" && result.updatedInput !== undefined)) fail("beforeTool cannot stop or replace input while denying"); - if (canonicalEvent === "stop" && (result.outcome === "stop" || result.updatedInput !== undefined || result.additionalContext !== undefined)) fail("stop only accepts continue or deny with a reason"); - if (canonicalEvent === "agentStop" && (result.outcome === "stop" || result.updatedInput !== undefined)) fail("agentStop cannot stop the parent flow or replace input"); - if (canonicalEvent === "agentStop" && target === "codex" && 0) {} - return result; -}; -const encodeOutput = (result)=>{ - if (result === undefined) return undefined; - if (canonicalEvent === "stop" || canonicalEvent === "agentStop") { - if (result.outcome === "deny") return defined({ - decision: "block", - reason: result.reason - }); - if (canonicalEvent === "agentStop" && target === "claude" && result.additionalContext !== undefined) return { - hookSpecificOutput: { - additionalContext: result.additionalContext, - hookEventName: nativeEvent - } - }; - return undefined; - } - const output = defined({ - additionalContext: result.additionalContext, - hookEventName: nativeEvent, - permissionDecision: canonicalEvent === "beforeTool" ? result.outcome === "deny" ? "deny" : "allow" : undefined, - permissionDecisionReason: canonicalEvent === "beforeTool" && result.outcome === "deny" ? result.reason : undefined, - updatedInput: canonicalEvent === "beforeTool" && result.outcome !== "deny" ? result.updatedInput : undefined - }); - return Object.keys(output).length === 1 && output.hookEventName !== undefined ? undefined : { - hookSpecificOutput: output - }; -}; -const decodeOutput = (nativeOutput)=>{ - if (nativeOutput === undefined) return undefined; - if (canonicalEvent === "stop" || canonicalEvent === "agentStop") { - if (nativeOutput.decision === "block") return defined({ - outcome: "deny", - reason: nativeOutput.reason - }); - if (canonicalEvent === "agentStop" && target === "claude" && isRecord(nativeOutput.hookSpecificOutput)) return defined({ - additionalContext: nativeOutput.hookSpecificOutput.additionalContext, - outcome: "continue" - }); - return undefined; - } - const output = nativeOutput.hookSpecificOutput; - if (!isRecord(output)) fail("native hook output is malformed"); - return defined({ - additionalContext: output.additionalContext, - outcome: output.permissionDecision === "deny" ? "deny" : "continue", - reason: output.permissionDecisionReason, - updatedInput: output.updatedInput - }); -}; -const requireString = (input, field)=>{ - if (typeof input[field] !== "string") fail(`native ${field} must be a string`); -}; -const requireNullableString = (input, field)=>{ - if (input[field] !== null && typeof input[field] !== "string") fail(`native ${field} must be a string or null`); -}; -const validateNativeInput = (input)=>{ - requireString(input, "session_id"); - if (false) {} - else requireString(input, "transcript_path"); - requireString(input, "cwd"); - if (input.hook_event_name !== nativeEvent) fail(`native hook_event_name must equal ${nativeEvent}`); - if (input.prompt_id !== undefined) requireString(input, "prompt_id"); - if (input.permission_mode !== undefined) requireString(input, "permission_mode"); - if (input.model !== undefined) requireString(input, "model"); - if (canonicalEvent === "sessionStart") { - requireString(input, "source"); - return; - } - if (canonicalEvent === "beforeTool" || canonicalEvent === "afterTool") { - requireString(input, "tool_name"); - if (false) {} else if (!isRecord(input.tool_input)) fail(`native ${nativeEvent} tool_input must be an object`); - requireString(input, "tool_use_id"); - if (canonicalEvent === "afterTool") { - if (input.tool_response === undefined) fail("native PostToolUse tool_response is required"); - } - return; - } - if (canonicalEvent === "agentStart" || canonicalEvent === "agentStop") { - requireString(input, "agent_id"); - requireString(input, "agent_type"); - if (false) {} - if (canonicalEvent === "agentStart") return; - if (typeof input.stop_hook_active !== "boolean") fail("native SubagentStop stop_hook_active must be a boolean"); - requireNullableString(input, "agent_transcript_path"); - requireNullableString(input, "last_assistant_message"); - return; - } - if (typeof input.stop_hook_active !== "boolean") fail("native Stop stop_hook_active must be a boolean"); - if (false) {} - else requireString(input, "last_assistant_message"); -}; -const run = async ()=>{ - const handler = Reflect.get(session_start_namespaceObject, "default"); - if (typeof handler !== "function") fail("default export must be a function"); - let raw = ""; - for await (const chunk of process.stdin)raw += chunk; - if (raw.trim().length === 0) fail("stdin must contain exactly one JSON value"); - let input; - try { - input = JSON.parse(raw); - } catch { - fail("stdin must contain exactly one JSON value"); - } - if (!isRecord(input)) fail("stdin JSON value must be an object"); - const simulation = process.env.AGENT_BUNDLE_HOOK_SIMULATION === "1"; - const nativeInput = simulation ? encodeNative(input) : input; - validateNativeInput(nativeInput); - const event = decodeNative(nativeInput); - const result = validateResult(await handler(event, { - nativeEvent: nativeEvent, - nativeInput, - target: target - })); - const nativeOutput = encodeOutput(result); - const output = simulation ? decodeOutput(nativeOutput) : nativeOutput; - if (output !== undefined) process.stdout.write(JSON.stringify(output)); -}; -if (import.meta.main) { - await run().catch((error)=>{ - process.stderr.write(`${error instanceof Error ? error.message : String(error)}\n`); - process.exitCode = 1; - }); -} - -export {}; diff --git a/examples/mcp-app/artifact/claude/mcp/mcp-status-073c1634.mjs b/examples/mcp-app/artifact/claude/mcp/mcp-status-073c1634.mjs deleted file mode 100644 index 29189bf45..000000000 --- a/examples/mcp-app/artifact/claude/mcp/mcp-status-073c1634.mjs +++ /dev/null @@ -1,30761 +0,0 @@ -import node_process from "node:process"; - -// The require scope -var __webpack_require__ = {}; - -// webpack/runtime/define_property_getters -(() => { -__webpack_require__.d = (exports, getters, values) => { - var define = (defs, kind) => { - for(var key in defs) { - if(__webpack_require__.o(defs, key) && !__webpack_require__.o(exports, key)) { - Object.defineProperty(exports, key, { enumerable: true, [kind]: defs[key] }); - } - } - }; - define(getters, "get"); - define(values, "value"); -}; -})(); -// webpack/runtime/has_own_property -(() => { -__webpack_require__.o = (obj, prop) => (Object.prototype.hasOwnProperty.call(obj, prop)) -})(); -// webpack/runtime/make_namespace_object -(() => { -// define __esModule on exports -__webpack_require__.r = (exports) => { - if(typeof Symbol !== 'undefined' && Symbol.toStringTag) { - Object.defineProperty(exports, Symbol.toStringTag, { value: 'Module' }); - } - Object.defineProperty(exports, '__esModule', { value: true }); -}; -})(); - -// NAMESPACE OBJECT: ./src/mcp/status.ts -var status_namespaceObject = {}; -__webpack_require__.r(status_namespaceObject); -__webpack_require__.d(status_namespaceObject, { - createStatusServer: () => (createStatusServer), - "default": () => (mcp_status) }); - - -// NAMESPACE OBJECT: ../../node_modules/.pnpm/@modelcontextprotocol+server@2.0.0/node_modules/@modelcontextprotocol/server/dist/stdio.mjs -var stdio_namespaceObject = {}; -__webpack_require__.r(stdio_namespaceObject); -__webpack_require__.d(stdio_namespaceObject, { - StdioServerTransport: () => (stdio_StdioServerTransport) }); - - -//#region rolldown:runtime -var __create = Object.create; -var __defProp = Object.defineProperty; -var __getOwnPropDesc = Object.getOwnPropertyDescriptor; -var __getOwnPropNames = Object.getOwnPropertyNames; -var __getProtoOf = Object.getPrototypeOf; -var __hasOwnProp = Object.prototype.hasOwnProperty; -var __commonJSMin = (cb, mod) => () => (mod || cb((mod = { exports: {} }).exports, mod), mod.exports); -var __exportAll = (all, symbols) => { - let target = {}; - for (var name in all) { - __defProp(target, name, { - get: all[name], - enumerable: true - }); - } - if (symbols) { - __defProp(target, Symbol.toStringTag, { value: "Module" }); - } - return target; -}; -var __copyProps = (to, from, except, desc) => { - if (from && typeof from === "object" || typeof from === "function") { - for (var keys = __getOwnPropNames(from), i = 0, n = keys.length, key; i < n; i++) { - key = keys[i]; - if (!__hasOwnProp.call(to, key) && key !== except) { - __defProp(to, key, { - get: ((k) => from[k]).bind(null, key), - enumerable: !(desc = __getOwnPropDesc(from, key)) || desc.enumerable - }); - } - } - } - return to; -}; -var __toESM = (mod, isNodeMode, target) => (target = mod != null ? __create(__getProtoOf(mod)) : {}, __copyProps(isNodeMode || !mod || !mod.__esModule ? __defProp(target, "default", { - value: mod, - enumerable: true -}) : target, mod)); - -//#endregion - -//#region ../core-internal/src/validators/dialects.ts -/** -* Canonical `$schema` URIs per supported dialect (http + https variants, trailing-`#` stripped). -*/ -const DRAFT_2020_12_URIS = new Set(["https://json-schema.org/draft/2020-12/schema", "http://json-schema.org/draft/2020-12/schema"]); -const DRAFT_2019_09_URIS = new Set(["https://json-schema.org/draft/2019-09/schema", "http://json-schema.org/draft/2019-09/schema"]); -const DRAFT_07_URIS = new Set(["https://json-schema.org/draft-07/schema", "http://json-schema.org/draft-07/schema"]); -const DRAFT_06_URIS = new Set(["https://json-schema.org/draft-06/schema", "http://json-schema.org/draft-06/schema"]); -/** -* Whether a `$schema` value declares the 2019-09 dialect — the only supported dialect with -* `$recursiveRef`/`$recursiveAnchor`. Non-throwing (unlike {@linkcode declaredDialect}) so -* wire-layer callers can consult it for documents whose dialect may be unsupported. -*/ -function declares2019Dialect($schema) { - return typeof $schema === "string" && DRAFT_2019_09_URIS.has($schema.replace(/#$/, "")); -} -/** -* Classify a schema's declared `$schema` dialect. No `$schema` (or a non-string one) means -* 2020-12. Any other dialect throws a plain `Error` with a clear message rather than letting the -* engine crash on an opaque internal error or silently mis-validate; `remedy` names the calling -* provider's escape hatch in that message. -*/ -function declaredDialect(schema, remedy) { - if (!("$schema" in schema) || typeof schema.$schema !== "string") return "2020-12"; - const declared = schema.$schema.replace(/#$/, ""); - if (DRAFT_2020_12_URIS.has(declared)) return "2020-12"; - if (DRAFT_2019_09_URIS.has(declared)) return "2019-09"; - if (DRAFT_07_URIS.has(declared) || DRAFT_06_URIS.has(declared)) return "draft-7"; - throw new Error(`JSON Schema declares an unsupported dialect ("$schema": "${schema.$schema.slice(0, 200)}"). The default validator supports JSON Schema 2020-12, 2019-09, draft-07, and draft-06; ${remedy}`); -} - -//#endregion - -//# sourceMappingURL=dialects-DoSzNhcb.mjs.map - -// functions -function assertEqual(val) { - return val; -} -function assertNotEqual(val) { - return val; -} -function toZod() { - return (schema) => schema; -} -function assertIs(_arg) { } -function assertNever(_x) { - throw new Error("Unexpected value in exhaustive check"); -} -function assert(_) { } -function getEnumValues(entries) { - const numericValues = Object.values(entries).filter((v) => typeof v === "number"); - const values = Object.entries(entries) - .filter(([k, _]) => numericValues.indexOf(+k) === -1) - .map(([_, v]) => v); - return values; -} -function joinValues(array, separator = "|") { - return array.map((val) => stringifyPrimitive(val)).join(separator); -} -function jsonStringifyReplacer(_, value) { - if (typeof value === "bigint") - return value.toString(); - return value; -} -function util_cached(getter) { - const set = false; - return { - get value() { - if (!set) { - const value = getter(); - Object.defineProperty(this, "value", { value }); - return value; - } - throw new Error("cached value already set"); - }, - }; -} -function nullish(input) { - return input === null || input === undefined; -} -function cleanRegex(source) { - const start = source.startsWith("^") ? 1 : 0; - const end = source.endsWith("$") ? source.length - 1 : source.length; - return source.slice(start, end); -} -function floatSafeRemainder(val, step) { - const ratio = val / step; - const roundedRatio = Math.round(ratio); - // `val` and `step` each round to a double before the division rounds again, so a true decimal multiple's quotient can sit up to 1.5 of these scaled epsilons from the integer. A 1x tolerance therefore rejected 2.03 as a multiple of 0.07; 4x covers the worst case with margin. - const tolerance = 4 * Number.EPSILON * Math.max(Math.abs(ratio), 1); - if (Math.abs(ratio - roundedRatio) < tolerance) - return 0; - return ratio - roundedRatio; -} -const EVALUATING = /* @__PURE__*/ Symbol("evaluating"); -function defineLazy(object, key, getter) { - let value = undefined; - Object.defineProperty(object, key, { - get() { - if (value === EVALUATING) { - // Circular reference detected, return undefined to break the cycle - return undefined; - } - if (value === undefined) { - value = EVALUATING; - value = getter(); - } - return value; - }, - set(v) { - Object.defineProperty(object, key, { - value: v, - // configurable: true, - }); - // object[key] = v; - }, - configurable: true, - }); -} -function objectClone(obj) { - return Object.create(Object.getPrototypeOf(obj), Object.getOwnPropertyDescriptors(obj)); -} -function assignProp(target, prop, value) { - Object.defineProperty(target, prop, { - value, - writable: true, - enumerable: true, - configurable: true, - }); -} -function mergeDefs(...defs) { - const mergedDescriptors = {}; - for (const def of defs) { - const descriptors = Object.getOwnPropertyDescriptors(def); - Object.assign(mergedDescriptors, descriptors); - } - return Object.defineProperties({}, mergedDescriptors); -} -function cloneDef(schema) { - return mergeDefs(schema._zod.def); -} -function getElementAtPath(obj, path) { - if (!path) - return obj; - return path.reduce((acc, key) => acc?.[key], obj); -} -function promiseAllObject(promisesObj) { - const keys = Object.keys(promisesObj); - const promises = keys.map((key) => promisesObj[key]); - return Promise.all(promises).then((results) => { - const resolvedObj = {}; - for (let i = 0; i < keys.length; i++) { - resolvedObj[keys[i]] = results[i]; - } - return resolvedObj; - }); -} -function randomString(length = 10) { - const chars = "abcdefghijklmnopqrstuvwxyz"; - let str = ""; - for (let i = 0; i < length; i++) { - str += chars[Math.floor(Math.random() * chars.length)]; - } - return str; -} -function util_esc(str) { - return JSON.stringify(str); -} -function slugify(input) { - return input - .toLowerCase() - .trim() - .replace(/[^\w\s-]/g, "") - .replace(/[\s_-]+/g, "-") - .replace(/^-+|-+$/g, ""); -} -const captureStackTrace = ("captureStackTrace" in Error ? Error.captureStackTrace : (..._args) => { }); -function util_isObject(data) { - return typeof data === "object" && data !== null && !Array.isArray(data); -} -const util_allowsEval = /* @__PURE__*/ util_cached(() => { - // Skip the probe under `jitless`: strict CSPs report the caught `new Function` as a `securitypolicyviolation` even though the throw is swallowed. - if (globalConfig.jitless) { - return false; - } - // @ts-ignore - if (typeof navigator !== "undefined" && navigator?.userAgent?.includes("Cloudflare")) { - return false; - } - try { - const F = Function; - new F(""); - return true; - } - catch (_) { - return false; - } -}); -function isPlainObject(o) { - if (util_isObject(o) === false) - return false; - // modified constructor - const ctor = o.constructor; - if (ctor === undefined) - return true; - if (typeof ctor !== "function") - return true; - // modified prototype - const prot = ctor.prototype; - if (util_isObject(prot) === false) - return false; - // ctor doesn't have static `isPrototypeOf` - if (Object.prototype.hasOwnProperty.call(prot, "isPrototypeOf") === false) { - return false; - } - return true; -} -function shallowClone(o) { - if (isPlainObject(o)) - return { ...o }; - if (Array.isArray(o)) - return [...o]; - if (o instanceof Map) - return new Map(o); - if (o instanceof Set) - return new Set(o); - return o; -} -function numKeys(data) { - let keyCount = 0; - for (const key in data) { - if (Object.prototype.hasOwnProperty.call(data, key)) { - keyCount++; - } - } - return keyCount; -} -const getParsedType = (data) => { - const t = typeof data; - switch (t) { - case "undefined": - return "undefined"; - case "string": - return "string"; - case "number": - return Number.isNaN(data) ? "nan" : "number"; - case "boolean": - return "boolean"; - case "function": - return "function"; - case "bigint": - return "bigint"; - case "symbol": - return "symbol"; - case "object": - if (Array.isArray(data)) { - return "array"; - } - if (data === null) { - return "null"; - } - if (data.then && typeof data.then === "function" && data.catch && typeof data.catch === "function") { - return "promise"; - } - if (typeof Map !== "undefined" && data instanceof Map) { - return "map"; - } - if (typeof Set !== "undefined" && data instanceof Set) { - return "set"; - } - if (typeof Date !== "undefined" && data instanceof Date) { - return "date"; - } - // @ts-ignore - if (typeof File !== "undefined" && data instanceof File) { - return "file"; - } - return "object"; - default: - throw new Error(`Unknown data type: ${t}`); - } -}; -const propertyKeyTypes = /* @__PURE__*/ new Set(["string", "number", "symbol"]); -const primitiveTypes = /* @__PURE__*/ (/* unused pure expression or super */ null && (new Set([ - "string", - "number", - "bigint", - "boolean", - "symbol", - "undefined", -]))); -function escapeRegex(str) { - return str.replace(/[.*+?^${}()|[\]\\]/g, "\\$&"); -} -// zod-specific utils -function clone(inst, def, params) { - const cl = new inst._zod.constr(def ?? inst._zod.def); - if (!def || params?.parent) - cl._zod.parent = inst; - return cl; -} -function normalizeParams(_params) { - const params = _params; - if (!params) - return {}; - if (typeof params === "string") - return { error: () => params }; - if (params?.message !== undefined) { - if (params?.error !== undefined) - throw new Error("Cannot specify both `message` and `error` params"); - params.error = params.message; - } - delete params.message; - if (typeof params.error === "string") - return { ...params, error: () => params.error }; - return params; -} -function createTransparentProxy(getter) { - let target; - return new Proxy({}, { - get(_, prop, receiver) { - target ?? (target = getter()); - return Reflect.get(target, prop, receiver); - }, - set(_, prop, value, receiver) { - target ?? (target = getter()); - return Reflect.set(target, prop, value, receiver); - }, - has(_, prop) { - target ?? (target = getter()); - return Reflect.has(target, prop); - }, - deleteProperty(_, prop) { - target ?? (target = getter()); - return Reflect.deleteProperty(target, prop); - }, - ownKeys(_) { - target ?? (target = getter()); - return Reflect.ownKeys(target); - }, - getOwnPropertyDescriptor(_, prop) { - target ?? (target = getter()); - return Reflect.getOwnPropertyDescriptor(target, prop); - }, - defineProperty(_, prop, descriptor) { - target ?? (target = getter()); - return Reflect.defineProperty(target, prop, descriptor); - }, - }); -} -function stringifyPrimitive(value) { - if (typeof value === "bigint") - return value.toString() + "n"; - if (typeof value === "string") - return `"${value}"`; - return `${value}`; -} -function optionalKeys(shape) { - return Object.keys(shape).filter((k) => { - return shape[k]._zod.optin !== undefined && shape[k]._zod.optout === "optional"; - }); -} -// Wrapped in a `@__PURE__` IIFE: esbuild never tree-shakes a top-level initializer that contains a member access on `Number`, so the bare object literal survived into every bundle. -const NUMBER_FORMAT_RANGES = /*@__PURE__*/ (() => ({ - safeint: [Number.MIN_SAFE_INTEGER, Number.MAX_SAFE_INTEGER], - int32: [-2147483648, 2147483647], - uint32: [0, 4294967295], - float32: [-3.4028234663852886e38, 3.4028234663852886e38], - float64: [-Number.MAX_VALUE, Number.MAX_VALUE], -}))(); -const BIGINT_FORMAT_RANGES = { - int64: [/* @__PURE__*/ BigInt("-9223372036854775808"), /* @__PURE__*/ BigInt("9223372036854775807")], - uint64: [/* @__PURE__*/ BigInt(0), /* @__PURE__*/ BigInt("18446744073709551615")], -}; -function pick(schema, mask) { - const currDef = schema._zod.def; - const checks = currDef.checks; - const hasChecks = checks && checks.length > 0; - if (hasChecks) { - throw new Error(".pick() cannot be used on object schemas containing refinements"); - } - const def = mergeDefs(schema._zod.def, { - get shape() { - const newShape = {}; - // `for...in` skips symbols, so a symbol in the mask would select nothing - for (const key of Reflect.ownKeys(mask)) { - if (!Object.prototype.hasOwnProperty.call(currDef.shape, key)) { - throw new Error(`Unrecognized key: "${String(key)}"`); - } - if (!mask[key]) - continue; - assignProp(newShape, key, currDef.shape[key]); - } - assignProp(this, "shape", newShape); // self-caching - return newShape; - }, - checks: [], - }); - return clone(schema, def); -} -function omit(schema, mask) { - const currDef = schema._zod.def; - const checks = currDef.checks; - const hasChecks = checks && checks.length > 0; - if (hasChecks) { - throw new Error(".omit() cannot be used on object schemas containing refinements"); - } - const def = mergeDefs(schema._zod.def, { - get shape() { - const newShape = { ...schema._zod.def.shape }; - for (const key of Reflect.ownKeys(mask)) { - if (!Object.prototype.hasOwnProperty.call(currDef.shape, key)) { - throw new Error(`Unrecognized key: "${String(key)}"`); - } - if (!mask[key]) - continue; - delete newShape[key]; - } - assignProp(this, "shape", newShape); // self-caching - return newShape; - }, - checks: [], - }); - return clone(schema, def); -} -function extend(schema, shape) { - if (!isPlainObject(shape)) { - throw new Error("Invalid input to extend: expected a plain object"); - } - const checks = schema._zod.def.checks; - const hasChecks = checks && checks.length > 0; - if (hasChecks) { - // Only throw if new shape overlaps with existing shape. Use getOwnPropertyDescriptor to check key existence without accessing values - const existingShape = schema._zod.def.shape; - for (const key of Reflect.ownKeys(shape)) { - if (Object.getOwnPropertyDescriptor(existingShape, key) !== undefined) { - throw new Error("Cannot overwrite keys on object schemas containing refinements. Use `.safeExtend()` instead."); - } - } - } - const def = mergeDefs(schema._zod.def, { - get shape() { - const _shape = { ...schema._zod.def.shape, ...shape }; - assignProp(this, "shape", _shape); // self-caching - return _shape; - }, - }); - return clone(schema, def); -} -function safeExtend(schema, shape) { - if (!isPlainObject(shape)) { - throw new Error("Invalid input to safeExtend: expected a plain object"); - } - const def = mergeDefs(schema._zod.def, { - get shape() { - const _shape = { ...schema._zod.def.shape, ...shape }; - assignProp(this, "shape", _shape); // self-caching - return _shape; - }, - }); - return clone(schema, def); -} -function merge(a, b) { - if (!b?._zod?.def) { - throw new Error("Invalid input to merge: expected an object schema. To merge a plain shape, use `.extend()`."); - } - if (a._zod.def.checks?.length) { - throw new Error(".merge() cannot be used on object schemas containing refinements. Use .safeExtend() instead."); - } - const def = mergeDefs(a._zod.def, { - get shape() { - const _shape = { ...a._zod.def.shape, ...b._zod.def.shape }; - assignProp(this, "shape", _shape); // self-caching - return _shape; - }, - get catchall() { - return b._zod.def.catchall; - }, - checks: b._zod.def.checks ?? [], - }); - return clone(a, def); -} -function partial(Class, schema, mask, name = "partial") { - const currDef = schema._zod.def; - const checks = currDef.checks; - const hasChecks = checks && checks.length > 0; - if (hasChecks) { - throw new Error(`.${name}() cannot be used on object schemas containing refinements`); - } - const def = mergeDefs(schema._zod.def, { - get shape() { - const oldShape = schema._zod.def.shape; - const shape = { ...oldShape }; - if (mask) { - for (const key of Reflect.ownKeys(mask)) { - if (!Object.prototype.hasOwnProperty.call(oldShape, key)) { - throw new Error(`Unrecognized key: "${String(key)}"`); - } - if (!mask[key]) - continue; - // if (oldShape[key]!._zod.optin === "optional") continue; - shape[key] = Class - ? new Class({ - type: "optional", - innerType: oldShape[key], - }) - : oldShape[key]; - } - } - else { - // the spread copies symbol keys; `for...in` would not reach them - for (const key of Reflect.ownKeys(oldShape)) { - // if (oldShape[key]!._zod.optin === "optional") continue; - shape[key] = Class - ? new Class({ - type: "optional", - innerType: oldShape[key], - }) - : oldShape[key]; - } - } - assignProp(this, "shape", shape); // self-caching - return shape; - }, - checks: [], - }); - return clone(schema, def); -} -function util_required(Class, schema, mask) { - const def = mergeDefs(schema._zod.def, { - get shape() { - const oldShape = schema._zod.def.shape; - const shape = { ...oldShape }; - if (mask) { - for (const key of Reflect.ownKeys(mask)) { - if (!Object.prototype.hasOwnProperty.call(shape, key)) { - throw new Error(`Unrecognized key: "${String(key)}"`); - } - if (!mask[key]) - continue; - // overwrite with non-optional - shape[key] = new Class({ - type: "nonoptional", - innerType: oldShape[key], - }); - } - } - else { - for (const key of Reflect.ownKeys(oldShape)) { - // overwrite with non-optional - shape[key] = new Class({ - type: "nonoptional", - innerType: oldShape[key], - }); - } - } - assignProp(this, "shape", shape); // self-caching - return shape; - }, - }); - return clone(schema, def); -} -// invalid_type | too_big | too_small | invalid_format | not_multiple_of | unrecognized_keys | invalid_union | invalid_key | invalid_element | invalid_value | custom -function aborted(x, startIndex = 0) { - if (x.aborted === true) - return true; - for (let i = startIndex; i < x.issues.length; i++) { - if (x.issues[i]?.continue !== true) { - return true; - } - } - return false; -} -// Checks for explicit abort (continue === false), as opposed to implicit abort (continue === undefined). Used to respect `abort: true` in .refine() even for checks that have a `when` function. -function explicitlyAborted(x, startIndex = 0) { - if (x.aborted === true) - return true; - for (let i = startIndex; i < x.issues.length; i++) { - if (x.issues[i]?.continue === false) { - return true; - } - } - return false; -} -function prefixIssues(path, issues) { - return issues.map((iss) => { - var _a; - (_a = iss).path ?? (_a.path = []); - iss.path.unshift(path); - return iss; - }); -} -function unwrapMessage(message) { - return typeof message === "string" ? message : message?.message; -} -/* A check holds no link back to the schema it is attached to — the same check instance is shared by every clone of that schema — so the owner is stamped onto the issues a check just raised, at the only point where both are in scope. Runs on the failure path only; `start` is the issue count from before the check ran. */ -function attachSchema(issues, start, inst) { - var _a; - for (let i = start; i < issues.length; i++) { - (_a = issues[i]).schema ?? (_a.schema = inst); - } -} -function finalizeIssue(iss, ctx, config) { - var _a; - // A schema that raised an issue itself owns it outright, and outranks any stamp an enclosing check left in `attachSchema`. String formats and z.custom() are schema and check at once, so when they act as a check they defer to that stamp instead. - const traits = iss.inst?._zod?.traits; - if (traits?.has("$ZodType")) { - if (traits.has("$ZodCheck")) - (_a = iss).schema ?? (_a.schema = iss.inst); - else - iss.schema = iss.inst; - } - // Decreasing specificity, first map to return a message wins. `inst` is whatever raised the issue, so a check's own map outranks the owning schema's. - const schemaError = iss.schema !== iss.inst ? iss.schema?._zod.def?.error : undefined; - const message = iss.message - ? iss.message - : (unwrapMessage(iss.inst?._zod.def?.error?.(iss)) ?? - unwrapMessage(schemaError?.(iss)) ?? - unwrapMessage(ctx?.error?.(iss)) ?? - unwrapMessage(config.customError?.(iss)) ?? - unwrapMessage(config.localeError?.(iss)) ?? - "Invalid input"); - const { inst: _inst, schema: _schema, continue: _continue, input: _input, ...rest } = iss; - rest.path ?? (rest.path = []); - rest.message = message; - if (ctx?.reportInput) { - rest.input = _input; - } - return rest; -} -function getSizableOrigin(input) { - if (input instanceof Set) - return "set"; - if (input instanceof Map) - return "map"; - // @ts-ignore - if (input instanceof File) - return "file"; - return "unknown"; -} -const highSurrogate = /[\uD800-\uDBFF]/; -// Code points in `str`: a surrogate pair counts once, a lone surrogate as itself. Hand-rolled because the string iterator allocates and runs ~250x slower on this path; the regex probe exits ~50x quicker for a string with no astral characters. -function codePointLength(str) { - const units = str.length; - if (!highSurrogate.test(str)) - return units; - let count = units; - for (let i = 0; i < units - 1; i++) { - if ((str.charCodeAt(i) & 0xfc00) === 0xd800 && (str.charCodeAt(i + 1) & 0xfc00) === 0xdc00) { - count--; - i++; - } - } - return count; -} -function getLengthableOrigin(input) { - if (Array.isArray(input)) - return "array"; - if (typeof input === "string") - return "string"; - return "unknown"; -} -function parsedType(data) { - const t = typeof data; - switch (t) { - case "number": { - return Number.isNaN(data) ? "nan" : "number"; - } - case "object": { - if (data === null) { - return "null"; - } - if (Array.isArray(data)) { - return "array"; - } - const obj = data; - if (obj && Object.getPrototypeOf(obj) !== Object.prototype && "constructor" in obj && obj.constructor) { - return obj.constructor.name; - } - } - } - return t; -} -function util_issue(...args) { - const [iss, input, inst] = args; - if (typeof iss === "string") { - return { - message: iss, - code: "custom", - input, - inst, - }; - } - return { ...iss }; -} -function cleanEnum(obj) { - return Object.entries(obj) - .filter(([k, _]) => { - // return true if NaN, meaning it's not a number, thus a string key - return Number.isNaN(Number.parseInt(k, 10)); - }) - .map((el) => el[1]); -} -// Codec utility functions -function base64ToUint8Array(base64) { - const binaryString = atob(base64); - const bytes = new Uint8Array(binaryString.length); - for (let i = 0; i < binaryString.length; i++) { - bytes[i] = binaryString.charCodeAt(i); - } - return bytes; -} -function uint8ArrayToBase64(bytes) { - let binaryString = ""; - for (let i = 0; i < bytes.length; i++) { - binaryString += String.fromCharCode(bytes[i]); - } - return btoa(binaryString); -} -function base64urlToUint8Array(base64url) { - const base64 = base64url.replace(/-/g, "+").replace(/_/g, "/"); - const padding = "=".repeat((4 - (base64.length % 4)) % 4); - return base64ToUint8Array(base64 + padding); -} -function uint8ArrayToBase64url(bytes) { - return uint8ArrayToBase64(bytes).replace(/\+/g, "-").replace(/\//g, "_").replace(/=/g, ""); -} -function hexToUint8Array(hex) { - const cleanHex = hex.replace(/^0x/, ""); - if (cleanHex.length % 2 !== 0) { - throw new Error("Invalid hex string length"); - } - const bytes = new Uint8Array(cleanHex.length / 2); - for (let i = 0; i < cleanHex.length; i += 2) { - bytes[i / 2] = Number.parseInt(cleanHex.slice(i, i + 2), 16); - } - return bytes; -} -function uint8ArrayToHex(bytes) { - return Array.from(bytes) - .map((b) => b.toString(16).padStart(2, "0")) - .join(""); -} -// instanceof -class util_Class { - constructor(..._args) { } -} -////////// PROTOTYPE INSTALLERS ////////// -// -// Members live on the prototype and materialize per instance on first read, which keeps own-property count under the step where V8 stops using inline slots. Changing anything here means re-measuring runtime, memory and bundle size together — see "The three axes" in AGENTS.md. -/** - * Installs a trait's members on its prototype. Each value builds that member for the instance on first read; the built value shadows the accessor as an own property, so a detached `const { parse } = schema` keeps working. - * - * Call this from a `proto` initializer, which runs once per prototype — never per instance. - */ -function util_members(proto, table) { - for (const key in table) { - const desc = Object.getOwnPropertyDescriptor(table, key); - // a getter installs as written, so it stays live: `description` reads through to the registry on every access. not enumerable: an object literal's is, and a prototype member never was - if (desc.get) - Object.defineProperty(proto, key, { ...desc, enumerable: false }); - // a method materializes bound on first read, which is what keeps a detached member working: `const opt = schema.optional; opt()` - else - defineBound(proto, key, desc.value); - } -} -/** Shadows a prototype member with an own value, so a getter that builds from the instance runs once. */ -function util_own(inst, key, value, enumerable = true) { - Object.defineProperty(inst, key, { configurable: true, writable: true, enumerable, value }); - return value; -} -/** Like {@link own}, for a member that was never an own data property and has to stay out of `Object.keys`. */ -function hide(inst, key, value) { - return util_own(inst, key, value, false); -} -function defineBound(proto, key, fn) { - Object.defineProperty(proto, key, { - configurable: true, - get() { - // vitest's spyOn calls a prototype getter bare to find the function it wraps, so a nullish receiver answers the raw method - return this == null ? fn : util_own(this, key, fn.bind(this)); - }, - set(value) { - util_own(this, key, value); - }, - }); -} -/** Returns the prototype to install on, or `undefined` if this group is already installed on it. */ -function claim(inst, sentinel) { - const proto = Object.getPrototypeOf(inst); - // Runs on every construction, so `in` rather than the costlier `hasOwnProperty.call`. Sentinels are keys the group itself defines. - return sentinel in proto ? undefined : proto; -} -// The internals whose init chain is installing. A second call for the same one is a derived constructor overriding its base, so it must not construct another schema in between or the override is dropped. -let installing; -// Set while a getter is running, so a value that resolved through a recursion break is not memoized. One shared descriptor shadows the key for the duration, which costs no per-key allocation. -let broke = false; -const breaker = { - configurable: true, - get() { - broke = true; - return undefined; - }, -}; -/** - * Installs a lazily-derived internal on the `_zod` prototype of `inst`'s - * constructor, computed from the internals object itself and cached there on - * first read. One accessor per constructor rather than one per instance. - */ -function defineLazyInternal(inst, key, compute) { - const proto = Object.getPrototypeOf(inst._zod); - if (key in proto && installing !== inst._zod) { - // A repeat construction: everything is installed already. Cleared here so the reference is not held past the first construction of every type. - installing = undefined; - return; - } - installing = inst._zod; - Object.defineProperty(proto, key, { - configurable: true, - get() { - // Shadowed before computing so a re-entrant read from a recursive schema resolves to undefined instead of running the getter again. - Object.defineProperty(this, key, breaker); - const outer = broke; - broke = false; - try { - const value = compute(this); - // A result that resolved through a recursion break is recomputed once the graph is complete; everything else memoizes, undefined included. - if (broke) - delete this[key]; - else - Object.defineProperty(this, key, { configurable: true, writable: true, value }); - broke = broke || outer; - return value; - } - catch (err) { - // A compute that threw memoizes nothing, so a later read runs it again and fails the same way. The shadow goes with it, since leaving it installed would answer undefined for every later read. - delete this[key]; - broke = broke || outer; - throw err; - } - }, - set(value) { - Object.defineProperty(this, key, { configurable: true, writable: true, value }); - }, - }); -} -/** - * Installs `key` on `inst`'s prototype, computed by `make` on first read and cached there as an own - * data property. One accessor per constructor rather than one per instance, because an own accessor - * puts every instance after the first into v8 dictionary mode. The key doubles as the sentinel. - */ -function installLazyProp(inst, key, make, enumerable) { - const proto = claim(inst, key); - if (!proto) - return; - Object.defineProperty(proto, key, { - configurable: true, - get() { - // Shadowed before computing, so a re-entrant read from a self-referential shape resolves to undefined instead of running the getter again. A data property rather than an accessor: an own accessor is the dictionary-mode transition this exists to avoid. - const desc = { configurable: true, writable: true, enumerable, value: undefined }; - Object.defineProperty(this, key, desc); - // a compute that throws leaves the shadow behind, so later reads answer undefined instead of re-throwing; `defineLazy` did the same, and `defineLazyInternal`'s delete-on-catch would cost bytes in every bundle for a case only a throwing user getter reaches - desc.value = make(this); - Object.defineProperty(this, key, desc); - return desc.value; - }, - set(value) { - Object.defineProperty(this, key, { configurable: true, writable: true, enumerable, value }); - }, - }); -} -/** Marks the thunk `_catch` synthesises for a constant catch value. `Function.length` cannot tell that thunk from a user callback — rest and defaulted parameters both report arity 0 — and a user callback reads `ctx.error`, whose issues only finalize correctly against the caller's per-parse error map. Provenance can say what arity cannot. A plain string key rather than `Symbol.for`, whose call at module scope no bundler can prove pure — the same shape that anchored `urlCanParse` into every build. */ -const CONSTANT_CATCH = "~constantCatch"; -/** Wraps a constant catch value in a thunk tagged with {@link CONSTANT_CATCH}. */ -function constantCatch(value) { - const fn = () => value; - fn[CONSTANT_CATCH] = true; - return fn; -} - -var core_a; - -/** A special constant with type `never` */ -const NEVER = /*@__PURE__*/ Object.freeze({ - status: "aborted", -}); -/* Shared descriptor for installing `_zod`; defineProperty reads it - * synchronously, so reusing one object avoids a per-instance allocation. */ -const _zodDesc = { value: undefined, enumerable: false }; -// null where suppressing the capture would be unrecoverable: `parse()` puts the frames back with `captureStackTrace`, so without it the throw would lose its stack. also latched to null once `stackTraceLimit` proves unassignable, which a realm can do at any point by hardening Error -let _E = "captureStackTrace" in Error ? Error : null; -// v8 captures a stack trace inside the Error constructor, which dominates a failed parse; costs only the frames, and parse() restores those. the constructor must RUN: Object.create is cheaper and passes instanceof, but Error.isError and util.types.isNativeError check an internal slot -function newError(Definition) { - const E = _E; - if (E) { - const saved = E.stackTraceLimit; - if (typeof saved === "number") { - try { - E.stackTraceLimit = 0; - } - catch { - _E = null; - return new Definition(); - } - try { - return new Definition(); - } - finally { - E.stackTraceLimit = saved; - } - } - } - return new Definition(); -} -function $constructor(name, initializer, -/** This trait's members, installed once on every prototype that composes it. They cannot be declared in the initializer above: that runs per instance, and the prototype is shared. */ -proto, params) { - // Prototype for this constructor's `_zod` internals. Lazily-derived fields (`values`, `pattern`, `optin`, …) install here once rather than as an accessor on every instance. - const zodProto = {}; - // Assigning the fields in the constructor body is what gives instances in-object slots; building the object literally and reparenting it costs a second allocation and a generic property copy. - function Internals(def) { - this.def = def; - this.constr = _; - this.traits = new Set(); - } - Internals.prototype = zodProto; - const protoMembers = proto; - // One trait's members land on every prototype whose chain composes it, so the answer is per prototype rather than per trait. - const initialized = protoMembers && new WeakSet(); - function init(inst, def) { - if (!inst._zod) { - _zodDesc.value = new Internals(def); - try { - Object.defineProperty(inst, "_zod", _zodDesc); - } - finally { - // Cleared even on throw, so the shared descriptor never leaks one instance's internals into the next. - _zodDesc.value = undefined; - } - } - if (inst._zod.traits.has(name)) { - return; - } - inst._zod.traits.add(name); - initializer(inst, def); - if (initialized) { - // `super(def)` from a user subclass gives `this` a prototype the subclass owns, and installing there would overwrite whatever the subclass declared. `constr` built the instance, so its prototype is the one below the subclass's that should carry the members. A receiver whose chain never reaches that prototype installs on its own, which for a plain object handed straight to `init` means `Object.prototype` — unchanged from before. - const own = Object.getPrototypeOf(inst); - const ctorProto = inst._zod.constr.prototype; - let up = own; - while (up && up !== ctorProto) - up = Object.getPrototypeOf(up); - const target = up ?? own; - if (!initialized.has(target)) { - initialized.add(target); - util_members(target, protoMembers); - } - } - // support prototype modifications; for-in avoids the array allocation of Object.keys on the (usually empty) prototype - const proto = _.prototype; - for (const k in proto) { - if (!Object.prototype.hasOwnProperty.call(proto, k)) - continue; - if (!(k in inst)) { - inst[k] = proto[k].bind(inst); - } - } - } - // doesn't work if Parent has a constructor with arguments - const Parent = params?.Parent ?? Object; - class Definition extends Parent { - } - Object.defineProperty(Definition, "name", { value: name }); - function _(def) { - const inst = params?.Parent ? newError(Definition) : this; - init(inst, def); - const deferred = inst._zod.deferred; - if (deferred) { - for (const fn of deferred) { - fn(); - } - // Released: initializers run once, and the list would otherwise be retained for the schema's lifetime. - inst._zod.deferred = undefined; - } - // Global post-processor hook. Internal: installed by `import "zod/compile"` to enable AOT compilation for every constructed schema. Runs last, once the instance is fully built, because it hands the instance to compile(). The post-processor is expected to be reentrancy-guarded by its own implementation. - const pp = globalThis.__zod_globalConfig?.postProcessor; - if (pp) - pp(inst); - return inst; - } - Object.defineProperty(_, "init", { value: init }); - Object.defineProperty(_, Symbol.hasInstance, { - value: (inst) => { - if (params?.Parent && inst instanceof params.Parent) - return true; - return inst?._zod?.traits?.has(name); - }, - }); - Object.defineProperty(_, "name", { value: name }); - return _; -} -////////////////////////////// UTILITIES /////////////////////////////////////// -const $brand = /*@__PURE__*/ (/* unused pure expression or super */ null && (Symbol("zod_brand"))); -class $ZodAsyncError extends Error { - constructor() { - super(`Encountered Promise during synchronous parse. Use .parseAsync() instead.`); - } -} -class $ZodEncodeError extends Error { - constructor(name) { - super(`Encountered unidirectional transform during encode: ${name}`); - this.name = "ZodEncodeError"; - } -} -(core_a = globalThis).__zod_globalConfig ?? (core_a.__zod_globalConfig = {}); -const globalConfig = globalThis.__zod_globalConfig; -function core_config(newConfig) { - if (newConfig) - Object.assign(globalConfig, newConfig); - return globalConfig; -} - -class $ZodCyclicError extends Error { - constructor() { - super(`Cannot parse a reference cycle that closes through a transform`); - this.name = "ZodCyclicError"; - } -} -/** Keyed off the context object every schema in one parse call already shares. */ -const STATE = "~memo"; -const NO_ISSUES = []; -// Receivers prefix paths in place, so the cache and every hand-out need their own copies. -function cloneIssues(issues) { - return issues.map((iss) => (iss.path ? { ...iss, path: iss.path.slice() } : { ...iss })); -} -const recursive = /*@__PURE__*/ new WeakMap(); -/** Whether this schema's subtree contains a cycle, so one parse can re-enter it. */ -function isRecursive(inst, stack) { - const cached = recursive.get(inst); - if (cached !== undefined) - return cached; - // Relative to the walk in progress, so not cached. - if (stack.has(inst)) - return true; - stack.add(inst); - let result = false; - const check = (child) => { - if (!result && child?._zod && isRecursive(child, stack)) - result = true; - }; - const def = inst._zod.def; - const kind = def.type; - switch (kind) { - case "object": { - // `Reflect.ownKeys` rather than `Object.keys`, so a cycle through a declared symbol key is still seen - for (const key of Reflect.ownKeys(def.shape)) - check(def.shape[key]); - check(def.catchall); - break; - } - case "array": - check(def.element); - break; - case "tuple": - for (const el of def.items) - check(el); - check(def.rest); - break; - case "record": - case "map": - check(def.keyType); - check(def.valueType); - break; - case "set": - check(def.valueType); - break; - case "union": - for (const el of def.options) - check(el); - break; - case "intersection": - check(def.left); - check(def.right); - break; - case "optional": - case "nullable": - case "default": - case "prefault": - case "catch": - case "readonly": - case "nonoptional": - case "promise": - case "success": - check(def.innerType); - break; - case "pipe": - check(def.in); - check(def.out); - break; - case "function": - check(def.input); - check(def.output); - break; - // reading `_zod.innerType` resolves the getter once and caches it - case "lazy": - check(inst._zod.innerType); - break; - // a leaf by choice: `parts` are regex fragments, not data positions - case "template_literal": - // leaves - case "string": - case "number": - case "int": - case "boolean": - case "bigint": - case "symbol": - case "undefined": - case "null": - case "void": - case "never": - case "any": - case "unknown": - case "date": - case "nan": - case "enum": - case "literal": - case "file": - case "transform": - case "custom": - break; - default: { - // a new built-in kind becomes a compile error here - kind; - // a user-defined kind can still hold children, and only its author knows where, so fall back to scanning the def — skipping accessors, since reading one can run user code - for (const key in def) { - const desc = Object.getOwnPropertyDescriptor(def, key); - if (!desc || desc.get) - continue; - const value = desc.value; - if (!value || typeof value !== "object") - continue; - if (value._zod) - check(value); - else if (Array.isArray(value)) - for (const el of value) - check(el); - } - } - } - stack.delete(inst); - recursive.set(inst, result); - return result; -} -/** - * Whether one parse can re-enter this schema, i.e. its subtree contains a cycle. - * Exported for `z.compile`, which refuses to compile such a schema: cycle - * breaking is driven from here off state keyed on the parse context, and a - * generated fast path has no context to key on. - */ -function isRecursiveSchema(inst) { - return isRecursive(inst, new Set()); -} -function bucketFor(state, inst) { - let bucket = state.buckets.get(inst); - if (!bucket) { - bucket = new Map(); - state.buckets.set(inst, bucket); - } - return bucket; -} -// Set immediately before delegating to core and cleared immediately after, so `alloc` registers only for a visit this module is driving. -let handoff; -// Allocated but unfinished entries. `alloc` and the matching pop both happen in the synchronous part of a parse, so they nest even when children are async, and one stack serves every schema. -const memoizer_open = []; -const memoizer_memo = { - alloc(_inst, payload, empty) { - const bucket = handoff; - if (!bucket) - return empty; - handoff = undefined; - const entry = { value: empty, issues: null }; - bucket.set(payload.value, entry); - memoizer_open.push(entry); - return empty; - }, - guard(inst) { - var _a; - (_a = inst._zod).deferred ?? (_a.deferred = []); - inst._zod.deferred.push(() => { - const base = inst._zod.parse; - const wrapped = (payload, ctx) => { - // The value is a placeholder a back-edge is still waiting on, so the cycle closes through this transform. Its output can't exist in time to bind. - if (ctx.direction !== "backward" && isBackEdge(ctx, payload.value)) - throw new $ZodCyclicError(); - return base(payload, ctx); - }; - inst._zod.parse = wrapped; - if (inst._zod.run === base) - inst._zod.run = wrapped; - }); - }, - attach(inst) { - var _a; - let isRecursiveInst; - // `bucket` memoized for one parse; a recursive schema is re-entered many times and its bucket never changes - let lastCtx; - let lastBucket; - // Wraps `parse` in a deferred so it sees the container's final parse. Core's own deferred copies `parse` into `run` when there are no checks, and it ran first, so `run` is patched to match; with checks, `run` reads `parse` dynamically. - (_a = inst._zod).deferred ?? (_a.deferred = []); - inst._zod.deferred.push(() => { - const base = inst._zod.parse; - const wrapped = (payload, ctx) => { - if (isRecursiveInst === undefined) { - isRecursiveInst = isRecursive(inst, new Set()); - if (!isRecursiveInst) { - // Nothing here can ever fire, so take it back out. - inst._zod.parse = base; - if (inst._zod.run === wrapped) - inst._zod.run = base; - return base(payload, ctx); - } - } - const input = payload.value; - if (input === null || typeof input !== "object") - return base(payload, ctx); - let state = ctx[STATE]; - if (!state) { - state = { buckets: new Map(), backEdges: undefined }; - ctx[STATE] = state; - } - let bucket; - if (lastCtx === ctx) { - bucket = lastBucket; - } - else { - bucket = bucketFor(state, inst); - lastCtx = ctx; - lastBucket = bucket; - } - const hit = bucket.get(input); - if (hit) { - payload.value = hit.value; - if (hit.issues) { - if (hit.issues.length) - payload.issues.push(...cloneIssues(hit.issues)); - } - else { - // Still being parsed: its own checks cover it, so skip them here. - payload.memo = true; - state.backEdges ?? (state.backEdges = new Set()); - state.backEdges.add(hit.value); - } - return payload; - } - handoff = bucket; - const depth = memoizer_open.length; - const result = base(payload, ctx); - handoff = undefined; - // A container that rejected its input outright allocated nothing. - const entry = memoizer_open.length > depth ? memoizer_open.pop() : undefined; - // Both paths written out so the sync one allocates no closure. It runs once per node, and capturing here cost more than everything else combined. - if (result instanceof Promise) { - return result.then((r) => { - if (entry) - entry.issues = r.issues.length ? cloneIssues(r.issues) : NO_ISSUES; - return r; - }); - } - if (entry) - entry.issues = result.issues.length ? cloneIssues(result.issues) : NO_ISSUES; - return result; - }; - inst._zod.parse = wrapped; - if (inst._zod.run === base) - inst._zod.run = wrapped; - }); - }, -}; -/** The memoizer that gives containers cycle support. `zod` installs it by default; `zod/mini` opts in with `config({ memoizer: memoizer() })`. */ -function memoizer() { - return memoizer_memo; -} -/** Whether this value is a node a back-edge resolved to before it finished. */ -function isBackEdge(ctx, value) { - const backEdges = ctx[STATE]?.backEdges; - return backEdges !== undefined && value !== null && typeof value === "object" && backEdges.has(value); -} - - -/** - * @deprecated CUID v1 is deprecated by its authors due to information leakage - * (timestamps embedded in the id). Use {@link cuid2} instead. - * See https://github.com/paralleldrive/cuid. - */ -const cuid = /^[cC][0-9a-z]{6,}$/; -const cuid2 = /^[0-9a-z]+$/; -const ulid = /^[0-7][0-9A-HJKMNP-TV-Za-hjkmnp-tv-z]{25}$/; -const xid = /^[0-9a-vA-V]{20}$/; -const ksuid = /^[A-Za-z0-9]{27}$/; -const nanoid = /^[a-zA-Z0-9_-]{21}$/; -function nanoidOfLength(length) { - return new RegExp(`^[a-zA-Z0-9_-]{${length}}$`); -} -/** ISO 8601-1 duration regex. Does not support the 8601-2 extensions like negative durations or fractional/negative components. */ -const duration = /^P(?:(\d+W)|(?!.*W)(?=\d|T\d)(\d+Y)?(\d+M)?(\d+D)?(T(?=\d)(\d+H)?(\d+M)?(\d+([.,]\d+)?S)?)?)$/; -/** Implements ISO 8601-2 extensions like explicit +- prefixes, mixing weeks with other units, and fractional/negative components. */ -const extendedDuration = /^[-+]?P(?!$)(?:(?:[-+]?\d+Y)|(?:[-+]?\d+[.,]\d+Y$))?(?:(?:[-+]?\d+M)|(?:[-+]?\d+[.,]\d+M$))?(?:(?:[-+]?\d+W)|(?:[-+]?\d+[.,]\d+W$))?(?:(?:[-+]?\d+D)|(?:[-+]?\d+[.,]\d+D$))?(?:T(?=[\d+-])(?:(?:[-+]?\d+H)|(?:[-+]?\d+[.,]\d+H$))?(?:(?:[-+]?\d+M)|(?:[-+]?\d+[.,]\d+M$))?(?:[-+]?\d+(?:[.,]\d+)?S)?)??$/; -/** A regex for any UUID-like identifier: 8-4-4-4-12 hex pattern */ -const guid = /^([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})$/; -/** Returns a regex for validating an RFC 9562/4122 UUID. - * - * @param version Optionally specify a version 1-8. If no version is specified, all versions are supported. */ -const uuid = (version) => { - if (!version) - return /^([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)$/; - return new RegExp(`^([0-9a-fA-F]{8}-[0-9a-fA-F]{4}-${version}[0-9a-fA-F]{3}-[89abAB][0-9a-fA-F]{3}-[0-9a-fA-F]{12})$`); -}; -const uuid4 = /*@__PURE__*/ (/* unused pure expression or super */ null && (uuid(4))); -const uuid6 = /*@__PURE__*/ (/* unused pure expression or super */ null && (uuid(6))); -const uuid7 = /*@__PURE__*/ (/* unused pure expression or super */ null && (uuid(7))); -/** Practical email validation */ -const email = /^(?!\.)(?!.*\.\.)([A-Za-z0-9_'+\-\.]*)[A-Za-z0-9_+-]@([A-Za-z0-9][A-Za-z0-9\-]*\.)+[A-Za-z]{2,}$/; -/** Equivalent to the HTML5 input[type=email] validation implemented by browsers. Source: https://developer.mozilla.org/en-US/docs/Web/HTML/Element/input/email */ -const html5Email = /^[a-zA-Z0-9.!#$%&'*+/=?^_`{|}~-]+@[a-zA-Z0-9](?:[a-zA-Z0-9-]{0,61}[a-zA-Z0-9])?(?:\.[a-zA-Z0-9](?:[a-zA-Z0-9-]{0,61}[a-zA-Z0-9])?)*$/; -/** The classic emailregex.com regex for RFC 5322-compliant emails */ -const rfc5322Email = /^(([^<>()\[\]\\.,;:\s@"]+(\.[^<>()\[\]\\.,;:\s@"]+)*)|(".+"))@((\[[0-9]{1,3}\.[0-9]{1,3}\.[0-9]{1,3}\.[0-9]{1,3}])|(([a-zA-Z\-0-9]+\.)+[a-zA-Z]{2,}))$/; -/** A loose regex that allows Unicode characters, enforces length limits, and that's about it. */ -const unicodeEmail = /^[^\s@"]{1,64}@[^\s@]{1,255}$/u; -const idnEmail = (/* unused pure expression or super */ null && (unicodeEmail)); -const browserEmail = /^[a-zA-Z0-9.!#$%&'*+/=?^_`{|}~-]+@[a-zA-Z0-9](?:[a-zA-Z0-9-]{0,61}[a-zA-Z0-9])?(?:\.[a-zA-Z0-9](?:[a-zA-Z0-9-]{0,61}[a-zA-Z0-9])?)*$/; -// from https://thekevinscott.com/emojis-in-javascript/#writing-a-regular-expression -// Single character class, not an alternation: the two properties overlap (U+1F9B0-U+1F9B3), so `(A|B)+` backtracks exponentially on a failed match. -const _emoji = `^[\\p{Extended_Pictographic}\\p{Emoji_Component}]+$`; -function emoji() { - return new RegExp(_emoji, "u"); -} -const ipv4 = /^(?:(?: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])$/; -const regexes_ipv6 = /^(([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}|:))$/; -const mac = (delimiter) => { - const escapedDelim = util.escapeRegex(delimiter ?? ":"); - return new RegExp(`^(?:[0-9A-F]{2}${escapedDelim}){5}[0-9A-F]{2}$|^(?:[0-9a-f]{2}${escapedDelim}){5}[0-9a-f]{2}$`); -}; -const cidrv4 = /^((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])$/; -const cidrv6 = /^(([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}|:))\/(12[0-8]|1[01][0-9]|[1-9]?[0-9])$/; -// https://stackoverflow.com/questions/7860392/determine-if-string-is-in-base64-using-javascript -const regexes_base64 = /^$|^(?:[0-9a-zA-Z+/]{4})*(?:(?:[0-9a-zA-Z+/]{2}==)|(?:[0-9a-zA-Z+/]{3}=))?$/; -const regexes_base64url = /^[A-Za-z0-9_-]*$/; -// based on https://stackoverflow.com/questions/106179/regular-expression-to-match-dns-hostname-or-ip-address -// export const hostname: RegExp = /^([a-zA-Z0-9-]+\.)*[a-zA-Z0-9-]+$/; -const regexes_hostname = /^(?=.{1,253}\.?$)[a-zA-Z0-9](?:[a-zA-Z0-9-]{0,61}[a-zA-Z0-9])?(?:\.[a-zA-Z0-9](?:[-0-9a-zA-Z]{0,61}[0-9a-zA-Z])?)*\.?$/; -const domain = /^(?=.{1,253}$)([a-zA-Z0-9](?:[a-zA-Z0-9-]{0,61}[a-zA-Z0-9])?\.)+[a-zA-Z]{2,63}$/; -const httpProtocol = /^https?$/; -// https://blog.stevenlevithan.com/archives/validate-phone-number#r4-3 (regex sans spaces) E.164: leading digit must be 1-9; total digits (excluding '+') between 7-15 -const e164 = /^\+[1-9]\d{6,14}$/; -// Credit card shape: 12–19 digits, optionally separated by single spaces or single hyphens. ISO/IEC 7812 caps the PAN at 19 digits; 12 is the shortest issued length (Maestro). -const creditCard = /^\d(?:[ -]?\d){11,18}$/; -const dateSource = `(?:(?:\\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])))`; -/** Anchors a pattern source. The interpolation lives here rather than at the call site because - * esbuild will not drop a `@__PURE__` call whose own argument interpolates a variable, but it - * will drop `anchor(dateSource)`. Keeping it inline pinned `date` into every bundle. */ -function regexes_anchor(source) { - return new RegExp(`^${source}$`); -} -const regexes_date = /*@__PURE__*/ regexes_anchor(dateSource); -function timeSource(args) { - const hhmm = `(?:[01]\\d|2[0-3]):[0-5]\\d`; - const regex = typeof args.precision === "number" - ? args.precision === -1 - ? `${hhmm}` - : args.precision === 0 - ? `${hhmm}:[0-5]\\d` - : `${hhmm}:[0-5]\\d\\.\\d{${args.precision}}` - : args.seconds - ? `${hhmm}:[0-5]\\d(?:\\.\\d+)?` - : `${hhmm}(?::[0-5]\\d(?:\\.\\d+)?)?`; - return regex; -} -function regexes_time(args) { - return new RegExp(`^${timeSource(args)}$`); -} -// Adapted from https://stackoverflow.com/a/3143231 -function datetime(args) { - const opts = ["Z"]; - // if (args.offset) opts.push(`([+-]\\d{2}:\\d{2})`); - if (args.offset) - opts.push(`([+-](?:[01]\\d|2[0-3]):[0-5]\\d)`); - // RFC 3339 mandates seconds wherever the time carries a `Z` or an offset, so only the unqualified form `local` adds may omit them - const qualified = `${timeSource({ precision: args.precision, seconds: true })}(?:${opts.join("|")})`; - const timeRegex = args.local ? `${qualified}|${timeSource({ precision: args.precision })}` : qualified; - return new RegExp(`^${dateSource}T(?:${timeRegex})$`); -} -const regexes_string = (params) => { - const regex = params ? `[\\s\\S]{${params?.minimum ?? 0},${params?.maximum ?? ""}}` : `[\\s\\S]*`; - return new RegExp(`^${regex}$`); -}; -const bigint = /^-?\d+n?$/; -const integer = /^-?\d+$/; -const number = /^-?\d+(?:\.\d+)?$/; -const regexes_boolean = /^(?:true|false)$/i; -const _null = /^null$/i; - -const _undefined = /^undefined$/i; - -// regex for string with no uppercase letters -const lowercase = /^[^A-Z]*$/; -// regex for string with no lowercase letters -const uppercase = /^[^a-z]*$/; -// regex for hexadecimal strings (any length) -const regexes_hex = /^[0-9a-fA-F]*$/; -// Hash regexes for different algorithms and encodings -// Helper function to create base64 regex with exact length and padding -function fixedBase64(bodyLength, padding) { - return new RegExp(`^[A-Za-z0-9+/]{${bodyLength}}${padding}$`); -} -// Helper function to create base64url regex with exact length (no padding) -function fixedBase64url(length) { - return new RegExp(`^[A-Za-z0-9_-]{${length}}$`); -} -// MD5 (16 bytes): base64 = 24 chars total (22 + "==") -const md5_hex = /^[0-9a-fA-F]{32}$/; -const md5_base64 = /*@__PURE__*/ (/* unused pure expression or super */ null && (fixedBase64(22, "=="))); -const md5_base64url = /*@__PURE__*/ (/* unused pure expression or super */ null && (fixedBase64url(22))); -// SHA1 (20 bytes): base64 = 28 chars total (27 + "=") -const sha1_hex = /^[0-9a-fA-F]{40}$/; -const sha1_base64 = /*@__PURE__*/ (/* unused pure expression or super */ null && (fixedBase64(27, "="))); -const sha1_base64url = /*@__PURE__*/ (/* unused pure expression or super */ null && (fixedBase64url(27))); -// SHA256 (32 bytes): base64 = 44 chars total (43 + "=") -const sha256_hex = /^[0-9a-fA-F]{64}$/; -const sha256_base64 = /*@__PURE__*/ (/* unused pure expression or super */ null && (fixedBase64(43, "="))); -const sha256_base64url = /*@__PURE__*/ (/* unused pure expression or super */ null && (fixedBase64url(43))); -// SHA384 (48 bytes): base64 = 64 chars total (no padding) -const sha384_hex = /^[0-9a-fA-F]{96}$/; -const sha384_base64 = /*@__PURE__*/ (/* unused pure expression or super */ null && (fixedBase64(64, ""))); -const sha384_base64url = /*@__PURE__*/ (/* unused pure expression or super */ null && (fixedBase64url(64))); -// SHA512 (64 bytes): base64 = 88 chars total (86 + "==") -const sha512_hex = /^[0-9a-fA-F]{128}$/; -const sha512_base64 = /*@__PURE__*/ (/* unused pure expression or super */ null && (fixedBase64(86, "=="))); -const sha512_base64url = /*@__PURE__*/ (/* unused pure expression or super */ null && (fixedBase64url(86))); - -// import { $ZodType } from "./schemas.js"; - - - -const $ZodCheck = /*@__PURE__*/ $constructor("$ZodCheck", (inst, def) => { - var _a; - inst._zod ?? (inst._zod = {}); - inst._zod.def = def; - (_a = inst._zod).onattach ?? (_a.onattach = []); -}); -/** Default `when` for size-based checks: run only on non-nullish values with a `size`. */ -const _whenHasSize = (payload) => { - const val = payload.value; - return !util.nullish(val) && val.size !== undefined; -}; -/** Default `when` for length-based checks: run only on non-nullish values with a `length`. */ -const _whenHasLength = (payload) => { - const val = payload.value; - return !nullish(val) && val.length !== undefined; -}; -const numericOriginMap = { - number: "number", - bigint: "bigint", - object: "date", -}; -const $ZodCheckLessThan = /*@__PURE__*/ $constructor("$ZodCheckLessThan", (inst, def) => { - $ZodCheck.init(inst, def); - const origin = numericOriginMap[typeof def.value]; - inst._zod.onattach.push((inst) => { - const bag = inst._zod.bag; - const curr = (def.inclusive ? bag.maximum : bag.exclusiveMaximum) ?? Number.POSITIVE_INFINITY; - if (def.value < curr) { - if (def.inclusive) - bag.maximum = def.value; - else - bag.exclusiveMaximum = def.value; - } - }); - inst._zod.check = (payload) => { - if (def.inclusive ? payload.value <= def.value : payload.value < def.value) { - return; - } - payload.issues.push({ - origin: numericOriginMap[typeof payload.value] ?? origin, - code: "too_big", - maximum: typeof def.value === "object" ? def.value.getTime() : def.value, - input: payload.value, - inclusive: def.inclusive, - inst, - continue: !def.abort, - }); - }; -}); -const $ZodCheckGreaterThan = /*@__PURE__*/ $constructor("$ZodCheckGreaterThan", (inst, def) => { - $ZodCheck.init(inst, def); - const origin = numericOriginMap[typeof def.value]; - inst._zod.onattach.push((inst) => { - const bag = inst._zod.bag; - const curr = (def.inclusive ? bag.minimum : bag.exclusiveMinimum) ?? Number.NEGATIVE_INFINITY; - if (def.value > curr) { - if (def.inclusive) - bag.minimum = def.value; - else - bag.exclusiveMinimum = def.value; - } - }); - inst._zod.check = (payload) => { - if (def.inclusive ? payload.value >= def.value : payload.value > def.value) { - return; - } - payload.issues.push({ - origin: numericOriginMap[typeof payload.value] ?? origin, - code: "too_small", - minimum: typeof def.value === "object" ? def.value.getTime() : def.value, - input: payload.value, - inclusive: def.inclusive, - inst, - continue: !def.abort, - }); - }; -}); -const $ZodCheckMultipleOf = -/*@__PURE__*/ $constructor("$ZodCheckMultipleOf", (inst, def) => { - $ZodCheck.init(inst, def); - inst._zod.onattach.push((inst) => { - var _a; - (_a = inst._zod.bag).multipleOf ?? (_a.multipleOf = def.value); - }); - inst._zod.check = (payload) => { - if (typeof payload.value !== typeof def.value) - throw new Error("Cannot mix number and bigint in multiple_of check."); - const isMultiple = typeof payload.value === "bigint" - ? // `value % 0n` throws, and nothing is a multiple of zero — the number branch already fails this way via NaN - def.value !== BigInt(0) && payload.value % def.value === BigInt(0) - : floatSafeRemainder(payload.value, def.value) === 0; - if (isMultiple) - return; - payload.issues.push({ - origin: typeof payload.value, - code: "not_multiple_of", - divisor: def.value, - input: payload.value, - inst, - continue: !def.abort, - }); - }; -}); -const $ZodCheckNumberFormat = /*@__PURE__*/ $constructor("$ZodCheckNumberFormat", (inst, def) => { - $ZodCheck.init(inst, def); // no format checks - def.format = def.format || "float64"; - const isInt = def.format?.includes("int"); - const origin = isInt ? "int" : "number"; - const [minimum, maximum] = NUMBER_FORMAT_RANGES[def.format]; - inst._zod.onattach.push((inst) => { - const bag = inst._zod.bag; - bag.format = def.format; - bag.minimum = minimum; - bag.maximum = maximum; - if (isInt) - bag.pattern = integer; - }); - inst._zod.check = (payload) => { - const input = payload.value; - if (isInt) { - if (!Number.isInteger(input)) { - // invalid_format issue - // payload.issues.push({ - // expected: def.format, - // format: def.format, - // code: "invalid_format", - // input, - // inst, - // }); - // invalid_type issue - payload.issues.push({ - expected: origin, - format: def.format, - code: "invalid_type", - continue: false, - input, - inst, - }); - return; - // not_multiple_of issue - // payload.issues.push({ - // code: "not_multiple_of", - // origin: "number", - // input, - // inst, - // divisor: 1, - // }); - } - if (!Number.isSafeInteger(input)) { - if (input > 0) { - // too_big - payload.issues.push({ - input, - code: "too_big", - maximum: Number.MAX_SAFE_INTEGER, - note: "Integers must be within the safe integer range.", - inst, - origin, - inclusive: true, - continue: !def.abort, - }); - } - else { - // too_small - payload.issues.push({ - input, - code: "too_small", - minimum: Number.MIN_SAFE_INTEGER, - note: "Integers must be within the safe integer range.", - inst, - origin, - inclusive: true, - continue: !def.abort, - }); - } - return; - } - } - if (input < minimum) { - payload.issues.push({ - origin: "number", - input, - code: "too_small", - minimum, - inclusive: true, - inst, - continue: !def.abort, - }); - } - if (input > maximum) { - payload.issues.push({ - origin: "number", - input, - code: "too_big", - maximum, - inclusive: true, - inst, - continue: !def.abort, - }); - } - }; -}); -const $ZodCheckBigIntFormat = /*@__PURE__*/ (/* unused pure expression or super */ null && (core.$constructor("$ZodCheckBigIntFormat", (inst, def) => { - $ZodCheck.init(inst, def); // no format checks - const [minimum, maximum] = util.BIGINT_FORMAT_RANGES[def.format]; - inst._zod.onattach.push((inst) => { - const bag = inst._zod.bag; - bag.format = def.format; - bag.minimum = minimum; - bag.maximum = maximum; - }); - inst._zod.check = (payload) => { - const input = payload.value; - if (input < minimum) { - payload.issues.push({ - origin: "bigint", - input, - code: "too_small", - minimum: minimum, - inclusive: true, - inst, - continue: !def.abort, - }); - } - if (input > maximum) { - payload.issues.push({ - origin: "bigint", - input, - code: "too_big", - maximum, - inclusive: true, - inst, - continue: !def.abort, - }); - } - }; -}))); -const $ZodCheckMaxSize = /*@__PURE__*/ (/* unused pure expression or super */ null && (core.$constructor("$ZodCheckMaxSize", (inst, def) => { - var _a; - $ZodCheck.init(inst, def); - (_a = inst._zod.def).when ?? (_a.when = _whenHasSize); - inst._zod.onattach.push((inst) => { - const curr = (inst._zod.bag.maximum ?? Number.POSITIVE_INFINITY); - if (def.maximum < curr) - inst._zod.bag.maximum = def.maximum; - }); - inst._zod.check = (payload) => { - const input = payload.value; - const size = input.size; - if (size <= def.maximum) - return; - payload.issues.push({ - origin: util.getSizableOrigin(input), - code: "too_big", - maximum: def.maximum, - inclusive: true, - input, - inst, - continue: !def.abort, - }); - }; -}))); -const $ZodCheckMinSize = /*@__PURE__*/ (/* unused pure expression or super */ null && (core.$constructor("$ZodCheckMinSize", (inst, def) => { - var _a; - $ZodCheck.init(inst, def); - (_a = inst._zod.def).when ?? (_a.when = _whenHasSize); - inst._zod.onattach.push((inst) => { - const curr = (inst._zod.bag.minimum ?? Number.NEGATIVE_INFINITY); - if (def.minimum > curr) - inst._zod.bag.minimum = def.minimum; - }); - inst._zod.check = (payload) => { - const input = payload.value; - const size = input.size; - if (size >= def.minimum) - return; - payload.issues.push({ - origin: util.getSizableOrigin(input), - code: "too_small", - minimum: def.minimum, - inclusive: true, - input, - inst, - continue: !def.abort, - }); - }; -}))); -const $ZodCheckSizeEquals = /*@__PURE__*/ (/* unused pure expression or super */ null && (core.$constructor("$ZodCheckSizeEquals", (inst, def) => { - var _a; - $ZodCheck.init(inst, def); - (_a = inst._zod.def).when ?? (_a.when = _whenHasSize); - inst._zod.onattach.push((inst) => { - const bag = inst._zod.bag; - bag.minimum = def.size; - bag.maximum = def.size; - bag.size = def.size; - }); - inst._zod.check = (payload) => { - const input = payload.value; - const size = input.size; - if (size === def.size) - return; - const tooBig = size > def.size; - payload.issues.push({ - origin: util.getSizableOrigin(input), - ...(tooBig ? { code: "too_big", maximum: def.size } : { code: "too_small", minimum: def.size }), - inclusive: true, - exact: true, - input: payload.value, - inst, - continue: !def.abort, - }); - }; -}))); -const $ZodCheckMaxLength = /*@__PURE__*/ $constructor("$ZodCheckMaxLength", (inst, def) => { - var _a; - $ZodCheck.init(inst, def); - (_a = inst._zod.def).when ?? (_a.when = _whenHasLength); - inst._zod.onattach.push((inst) => { - const curr = (inst._zod.bag.maximum ?? Number.POSITIVE_INFINITY); - if (def.maximum < curr) - inst._zod.bag.maximum = def.maximum; - }); - inst._zod.check = (payload) => { - const input = payload.value; - const units = input.length; - // Strings are measured in Unicode code points, not UTF-16 units. A code point is at most two units, so a string that already fits in units fits in code points; only an overflow has to be counted. - const length = typeof input === "string" && units > def.maximum ? codePointLength(input) : units; - if (length <= def.maximum) - return; - const origin = getLengthableOrigin(input); - payload.issues.push({ - origin, - code: "too_big", - maximum: def.maximum, - inclusive: true, - input, - inst, - continue: !def.abort, - }); - }; -}); -const $ZodCheckMinLength = /*@__PURE__*/ $constructor("$ZodCheckMinLength", (inst, def) => { - var _a; - $ZodCheck.init(inst, def); - (_a = inst._zod.def).when ?? (_a.when = _whenHasLength); - inst._zod.onattach.push((inst) => { - const curr = (inst._zod.bag.minimum ?? Number.NEGATIVE_INFINITY); - if (def.minimum > curr) - inst._zod.bag.minimum = def.minimum; - }); - inst._zod.check = (payload) => { - const input = payload.value; - const units = input.length; - // A code point is one or two UTF-16 units, so fewer units than the floor can never reach it and twice the floor always clears it. Only in between is the exact count in doubt. - const length = typeof input === "string" && units >= def.minimum && units < def.minimum * 2 - ? codePointLength(input) - : units; - if (length >= def.minimum) - return; - const origin = getLengthableOrigin(input); - payload.issues.push({ - origin, - code: "too_small", - minimum: def.minimum, - inclusive: true, - input, - inst, - continue: !def.abort, - }); - }; -}); -const $ZodCheckLengthEquals = /*@__PURE__*/ $constructor("$ZodCheckLengthEquals", (inst, def) => { - var _a; - $ZodCheck.init(inst, def); - (_a = inst._zod.def).when ?? (_a.when = _whenHasLength); - inst._zod.onattach.push((inst) => { - const bag = inst._zod.bag; - bag.minimum = def.length; - bag.maximum = def.length; - bag.length = def.length; - }); - inst._zod.check = (payload) => { - const input = payload.value; - const units = input.length; - // A code point is one or two UTF-16 units, so outside `[length, length * 2]` units the target is missed either way — and missed in the same direction in both measures. - const length = typeof input === "string" && units >= def.length && units <= def.length * 2 - ? codePointLength(input) - : units; - if (length === def.length) - return; - const origin = getLengthableOrigin(input); - const tooBig = length > def.length; - payload.issues.push({ - origin, - ...(tooBig ? { code: "too_big", maximum: def.length } : { code: "too_small", minimum: def.length }), - inclusive: true, - exact: true, - input: payload.value, - inst, - continue: !def.abort, - }); - }; -}); -const $ZodCheckStringFormat = /*@__PURE__*/ $constructor("$ZodCheckStringFormat", (inst, def) => { - var _a, _b; - $ZodCheck.init(inst, def); - inst._zod.onattach.push((inst) => { - const bag = inst._zod.bag; - bag.format = def.format; - if (def.pattern) { - bag.patterns ?? (bag.patterns = new Set()); - bag.patterns.add(def.pattern); - } - }); - if (def.pattern) - (_a = inst._zod).check ?? (_a.check = (payload) => { - def.pattern.lastIndex = 0; - if (def.pattern.test(payload.value)) - return; - payload.issues.push({ - origin: "string", - code: "invalid_format", - format: def.format, - input: payload.value, - ...(def.pattern ? { pattern: def.pattern.toString() } : {}), - inst, - continue: !def.abort, - }); - }); - else - (_b = inst._zod).check ?? (_b.check = () => { }); -}); -const $ZodCheckRegex = /*@__PURE__*/ $constructor("$ZodCheckRegex", (inst, def) => { - $ZodCheckStringFormat.init(inst, def); - inst._zod.check = (payload) => { - def.pattern.lastIndex = 0; - if (def.pattern.test(payload.value)) - return; - payload.issues.push({ - origin: "string", - code: "invalid_format", - format: "regex", - input: payload.value, - pattern: def.pattern.toString(), - inst, - continue: !def.abort, - }); - }; -}); -const $ZodCheckLowerCase = /*@__PURE__*/ $constructor("$ZodCheckLowerCase", (inst, def) => { - def.pattern ?? (def.pattern = lowercase); - $ZodCheckStringFormat.init(inst, def); -}); -const $ZodCheckUpperCase = /*@__PURE__*/ $constructor("$ZodCheckUpperCase", (inst, def) => { - def.pattern ?? (def.pattern = uppercase); - $ZodCheckStringFormat.init(inst, def); -}); -const $ZodCheckIncludes = /*@__PURE__*/ $constructor("$ZodCheckIncludes", (inst, def) => { - $ZodCheck.init(inst, def); - const escapedRegex = escapeRegex(def.includes); - // `String.prototype.includes(sub, position)` matches `sub` at `position` - // OR LATER, so the pattern must allow at least `position` leading chars - // (`{N,}`), not exactly `position` chars (`{N}`). - const pattern = new RegExp(typeof def.position === "number" ? `^.{${def.position},}${escapedRegex}` : escapedRegex); - def.pattern = pattern; - inst._zod.onattach.push((inst) => { - const bag = inst._zod.bag; - bag.patterns ?? (bag.patterns = new Set()); - bag.patterns.add(pattern); - }); - inst._zod.check = (payload) => { - if (payload.value.includes(def.includes, def.position)) - return; - payload.issues.push({ - origin: "string", - code: "invalid_format", - format: "includes", - includes: def.includes, - input: payload.value, - inst, - continue: !def.abort, - }); - }; -}); -const $ZodCheckStartsWith = /*@__PURE__*/ $constructor("$ZodCheckStartsWith", (inst, def) => { - $ZodCheck.init(inst, def); - const pattern = new RegExp(`^${escapeRegex(def.prefix)}.*`); - def.pattern ?? (def.pattern = pattern); - inst._zod.onattach.push((inst) => { - const bag = inst._zod.bag; - bag.patterns ?? (bag.patterns = new Set()); - bag.patterns.add(pattern); - }); - inst._zod.check = (payload) => { - if (payload.value.startsWith(def.prefix)) - return; - payload.issues.push({ - origin: "string", - code: "invalid_format", - format: "starts_with", - prefix: def.prefix, - input: payload.value, - inst, - continue: !def.abort, - }); - }; -}); -const $ZodCheckEndsWith = /*@__PURE__*/ $constructor("$ZodCheckEndsWith", (inst, def) => { - $ZodCheck.init(inst, def); - const pattern = new RegExp(`.*${escapeRegex(def.suffix)}$`); - def.pattern ?? (def.pattern = pattern); - inst._zod.onattach.push((inst) => { - const bag = inst._zod.bag; - bag.patterns ?? (bag.patterns = new Set()); - bag.patterns.add(pattern); - }); - inst._zod.check = (payload) => { - if (payload.value.endsWith(def.suffix)) - return; - payload.issues.push({ - origin: "string", - code: "invalid_format", - format: "ends_with", - suffix: def.suffix, - input: payload.value, - inst, - continue: !def.abort, - }); - }; -}); -/////////////////////////////////// -///// $ZodCheckProperty ///// -/////////////////////////////////// -function handleCheckPropertyResult(result, payload, property) { - if (result.issues.length) { - payload.issues.push(...util.prefixIssues(property, result.issues)); - } -} -const $ZodCheckProperty = /*@__PURE__*/ (/* unused pure expression or super */ null && (core.$constructor("$ZodCheckProperty", (inst, def) => { - $ZodCheck.init(inst, def); - inst._zod.check = (payload) => { - const result = def.schema._zod.run({ - value: payload.value[def.property], - issues: [], - }, {}); - if (result instanceof Promise) { - return result.then((result) => handleCheckPropertyResult(result, payload, def.property)); - } - handleCheckPropertyResult(result, payload, def.property); - return; - }; -}))); -const $ZodCheckMimeType = /*@__PURE__*/ (/* unused pure expression or super */ null && (core.$constructor("$ZodCheckMimeType", (inst, def) => { - $ZodCheck.init(inst, def); - const mimeSet = new Set(def.mime); - inst._zod.onattach.push((inst) => { - inst._zod.bag.mime = def.mime; - }); - inst._zod.check = (payload) => { - if (mimeSet.has(payload.value.type)) - return; - payload.issues.push({ - code: "invalid_value", - values: def.mime, - input: payload.value.type, - inst, - continue: !def.abort, - }); - }; -}))); -const $ZodCheckOverwrite = /*@__PURE__*/ $constructor("$ZodCheckOverwrite", (inst, def) => { - $ZodCheck.init(inst, def); - inst._zod.check = (payload) => { - payload.value = def.tx(payload.value); - }; -}); - -class Doc { - constructor(args = [], closed = {}) { - this.content = []; - this.indent = 0; - this.args = args; - this.closed = closed; - } - indented(fn) { - this.indent += 1; - fn(this); - this.indent -= 1; - } - write(arg) { - if (typeof arg === "function") { - arg(this, { execution: "sync" }); - arg(this, { execution: "async" }); - return; - } - const content = arg; - const lines = content.split("\n").filter((x) => x); - const minIndent = Math.min(...lines.map((x) => x.length - x.trimStart().length)); - const dedented = lines.map((x) => x.slice(minIndent)).map((x) => " ".repeat(this.indent * 2) + x); - for (const line of dedented) { - this.content.push(line); - } - } - compile() { - const F = Function; - const content = this?.content ?? [``]; - const factory = new F(...Object.keys(this.closed), `return function (${this.args.join(", ")}) {\n${content.join("\n")}\n};`); - return factory(...Object.values(this.closed)); - } -} - - - -/* Computing the message eagerly is expensive (pretty-printed JSON of all - * issues), so defer it until first read. The accessor functions and - * descriptors are shared across instances to keep error construction - * cheap; the computed message is cached on the internals object. The - * setter preserves plain assignment semantics for consumers that - * overwrite `message`. */ -function _getMessage() { - const internals = this._zod; - internals.message ?? (internals.message = JSON.stringify(internals.def, jsonStringifyReplacer, 2)); - return internals.message; -} -function _setMessage(value) { - this._zod.message = value; -} -const _messageDesc = { - get: _getMessage, - set: _setMessage, - enumerable: true, - configurable: true, -}; -const errors_zodDesc = { value: undefined, enumerable: false }; -const _issuesDesc = { value: undefined, enumerable: false }; -/* Prototypes that already carry the lazy `toString`. Seeded with the - * intrinsics so that `init` on a foreign object — it accepts any object — - * can never install an accessor onto a prototype we do not own. */ -const _installedToString = /* @__PURE__ */ new WeakSet([Object.prototype, Error.prototype]); -const errors_initializer = (inst, def) => { - inst.name = "$ZodError"; - errors_zodDesc.value = inst._zod; - Object.defineProperty(inst, "_zod", errors_zodDesc); - _issuesDesc.value = def; - Object.defineProperty(inst, "issues", _issuesDesc); - // Clear the shared slots; a retained `value` pins the last error's issues. - errors_zodDesc.value = undefined; - _issuesDesc.value = undefined; - Object.defineProperty(inst, "message", _messageDesc); - /* `toString` lives as a non-enumerable lazy getter on the shared - * prototype; on first access it caches a per-instance closure so - * detached usage still works. */ - const proto = Object.getPrototypeOf(inst); - if (!_installedToString.has(proto)) { - _installedToString.add(proto); - Object.defineProperty(proto, "toString", { - configurable: true, - enumerable: false, - get() { - const value = () => this.message; - Object.defineProperty(this, "toString", { value, configurable: true, writable: true }); - return value; - }, - set(value) { - Object.defineProperty(this, "toString", { value, configurable: true, writable: true }); - }, - }); - } -}; -const $ZodError = $constructor("$ZodError", errors_initializer); -const $ZodRealError = $constructor("$ZodError", errors_initializer, undefined, { - Parent: Error, -}); -/** Get-or-create `obj[key]` as an own data property. A path segment naming an inherited member - * ("toString", "constructor") would otherwise read through to the prototype, and assigning - * "__proto__" would hit the setter instead of creating a key. */ -function errors_node(obj, key, make) { - if (!Object.prototype.hasOwnProperty.call(obj, key)) { - if (key === "__proto__") { - Object.defineProperty(obj, key, { value: make(), writable: true, enumerable: true, configurable: true }); - } - else { - obj[key] = make(); - } - } - return obj[key]; -} -function flattenError(error, mapper = (issue) => issue.message) { - const fieldErrors = {}; - const formErrors = []; - for (const sub of error.issues) { - if (sub.path.length > 0) { - errors_node(fieldErrors, sub.path[0], () => []).push(mapper(sub)); - } - else { - formErrors.push(mapper(sub)); - } - } - return { formErrors, fieldErrors }; -} -function formatError(error, mapper = (issue) => issue.message) { - const fieldErrors = { _errors: [] }; - const processError = (error, path = []) => { - for (const issue of error.issues) { - if (issue.code === "invalid_union" && issue.errors.length) { - issue.errors.map((issues) => processError({ issues }, [...path, ...issue.path])); - } - else if (issue.code === "invalid_key") { - processError({ issues: issue.issues }, [...path, ...issue.path]); - } - else if (issue.code === "invalid_element") { - processError({ issues: issue.issues }, [...path, ...issue.path]); - } - else { - const fullpath = [...path, ...issue.path]; - if (fullpath.length === 0) { - fieldErrors._errors.push(mapper(issue)); - } - else { - let curr = fieldErrors; - let i = 0; - while (i < fullpath.length) { - const el = fullpath[i]; - const terminal = i === fullpath.length - 1; - // `_errors` is reserved by this legacy format, so merge a matching path segment into the current node instead of treating its array as a child. - if (el === "_errors") { - if (terminal) - curr._errors.push(mapper(issue)); - i++; - continue; - } - // A path element may collide with an inherited property name such as - // "__proto__" or "constructor". Truthiness checks read the prototype - // (so no node is created, then ._errors.push throws), and bracket - // assignment of "__proto__" hits the setter instead of creating an - // own key. Guard the read with hasOwnProperty and create the node - // with defineProperty so any path element becomes a real own key. - if (!Object.prototype.hasOwnProperty.call(curr, el)) { - Object.defineProperty(curr, el, { - value: { _errors: [] }, - enumerable: true, - writable: true, - configurable: true, - }); - } - const node = curr[el]; - if (terminal) { - node._errors.push(mapper(issue)); - } - curr = node; - i++; - } - } - } - } - }; - processError(error); - return fieldErrors; -} -function treeifyError(error, mapper = (issue) => issue.message) { - const result = { errors: [] }; - const processError = (error, path = []) => { - var _a; - for (const issue of error.issues) { - if (issue.code === "invalid_union" && issue.errors.length) { - // regular union error - issue.errors.map((issues) => processError({ issues }, [...path, ...issue.path])); - } - else if (issue.code === "invalid_key") { - processError({ issues: issue.issues }, [...path, ...issue.path]); - } - else if (issue.code === "invalid_element") { - processError({ issues: issue.issues }, [...path, ...issue.path]); - } - else { - const fullpath = [...path, ...issue.path]; - if (fullpath.length === 0) { - result.errors.push(mapper(issue)); - continue; - } - let curr = result; - let i = 0; - while (i < fullpath.length) { - const el = fullpath[i]; - const terminal = i === fullpath.length - 1; - if (typeof el === "string") { - curr.properties ?? (curr.properties = {}); - // el may collide with an inherited property name ("__proto__", - // "constructor", ...); ??= reads the prototype so the node is never - // created and curr.errors.push throws. Guard with hasOwnProperty and - // create the node with defineProperty so "__proto__" becomes a real - // own key rather than invoking the prototype setter. - if (!Object.prototype.hasOwnProperty.call(curr.properties, el)) { - Object.defineProperty(curr.properties, el, { - value: { errors: [] }, - enumerable: true, - writable: true, - configurable: true, - }); - } - curr = curr.properties[el]; - } - else { - curr.items ?? (curr.items = []); - (_a = curr.items)[el] ?? (_a[el] = { errors: [] }); - curr = curr.items[el]; - } - if (terminal) { - curr.errors.push(mapper(issue)); - } - i++; - } - } - } - }; - processError(error); - return result; -} -/** Format a ZodError as a human-readable string in the following form. - * - * From - * - * ```ts - * ZodError { - * issues: [ - * { - * expected: 'string', - * code: 'invalid_type', - * path: [ 'username' ], - * message: 'Invalid input: expected string' - * }, - * { - * expected: 'number', - * code: 'invalid_type', - * path: [ 'favoriteNumbers', 1 ], - * message: 'Invalid input: expected number' - * } - * ]; - * } - * ``` - * - * to - * - * ``` - * username - * ✖ Expected number, received string at "username - * favoriteNumbers[0] - * ✖ Invalid input: expected number - * ``` - */ -function toDotPath(_path) { - const segs = []; - const path = _path.map((seg) => (typeof seg === "object" ? seg.key : seg)); - for (const seg of path) { - if (typeof seg === "number") - segs.push(`[${seg}]`); - else if (typeof seg === "symbol") - segs.push(`[${JSON.stringify(String(seg))}]`); - else if (/[^\w$]/.test(seg)) - segs.push(`[${JSON.stringify(seg)}]`); - else { - if (segs.length) - segs.push("."); - segs.push(seg); - } - } - return segs.join(""); -} -function prettifyError(error) { - const lines = []; - // sort by path length - const issues = [...error.issues].sort((a, b) => (a.path ?? []).length - (b.path ?? []).length); - // Process each issue - for (const issue of issues) { - lines.push(`✖ ${issue.message}`); - if (issue.path?.length) - lines.push(` → at ${toDotPath(issue.path)}`); - } - // Convert Map to formatted string - return lines.join("\n"); -} - - - - -// Always both keys, so the `_params` read site in `_parse` sees one object shape rather than two. -function finalizeParams(callee, params) { - return { callee: params?.callee ?? callee, Err: params?.Err }; -} -const parse_parse = (_Err) => { - const fn = (schema, value, _ctx, _params) => { - const ctx = _ctx ? { ..._ctx, async: false } : { async: false }; - const result = schema._zod.run({ value, issues: [] }, ctx); - if (result instanceof Promise) { - throw new $ZodAsyncError(); - } - if (result.issues.length) { - const e = new (_params?.Err ?? _Err)(result.issues.map((iss) => finalizeIssue(iss, ctx, core_config()))); - captureStackTrace(e, _params?.callee ?? fn); - throw e; - } - return result.value; - }; - return fn; -}; -const core_parse_parse = /* @__PURE__*/ parse_parse($ZodRealError); -const parse_parseAsync = (_Err) => { - const fn = async (schema, value, _ctx, params) => { - const ctx = _ctx ? { ..._ctx, async: true } : { async: true }; - let result = schema._zod.run({ value, issues: [] }, ctx); - if (result instanceof Promise) - result = await result; - if (result.issues.length) { - const e = new (params?.Err ?? _Err)(result.issues.map((iss) => finalizeIssue(iss, ctx, core_config()))); - captureStackTrace(e, params?.callee ?? fn); - throw e; - } - return result.value; - }; - return fn; -}; -const core_parse_parseAsync = /* @__PURE__*/ parse_parseAsync($ZodRealError); -const _safeParse = (_Err) => (schema, value, _ctx) => { - const ctx = _ctx ? { ..._ctx, async: false } : { async: false }; - const result = schema._zod.run({ value, issues: [] }, ctx); - if (result instanceof Promise) { - throw new $ZodAsyncError(); - } - return result.issues.length - ? { - success: false, - error: new (_Err ?? $ZodError)(result.issues.map((iss) => finalizeIssue(iss, ctx, core_config()))), - } - : { success: true, data: result.value }; -}; -const safeParse = /* @__PURE__*/ _safeParse($ZodRealError); -const _safeParseAsync = (_Err) => async (schema, value, _ctx) => { - const ctx = _ctx ? { ..._ctx, async: true } : { async: true }; - let result = schema._zod.run({ value, issues: [] }, ctx); - if (result instanceof Promise) - result = await result; - return result.issues.length - ? { - success: false, - error: new _Err(result.issues.map((iss) => finalizeIssue(iss, ctx, core_config()))), - } - : { success: true, data: result.value }; -}; -const safeParseAsync = /* @__PURE__*/ _safeParseAsync($ZodRealError); -// registry mirrors of the compiler's sentinels, so this module never imports the compiler -const COMPILE_INVALID = /* @__PURE__ */ (/* unused pure expression or super */ null && (Symbol.for("zod.compile.invalid"))); -const COMPILE_FALLBACK = /* @__PURE__ */ (/* unused pure expression or super */ null && (Symbol.for("zod.compile.fallback"))); -// Deliberately tiny, because v8 will not inline a body carrying the fallback's object literals and throw. Everything that is not the compiled happy path lives in validateFallback, and that split is worth ~35% on a compiled schema. -const parse_validate = ((schema, value, _ctx) => { - const validator = schema._zod.bag.validator; - if (validator !== undefined && validator(value) !== COMPILE_INVALID) - return true; - return validateFallback(schema, value, _ctx); -}); -function validateFallback(schema, value, _ctx) { - const ctx = _ctx ? { ..._ctx, async: false } : { async: false }; - const fallbackRun = schema._zod.bag.fallbackRun; - let result; - if (fallbackRun) { - // skip nested fast paths on the fallback, so user callbacks keep the at-most-twice bound - ctx[COMPILE_FALLBACK] = true; - result = fallbackRun({ value, issues: [] }, ctx); - } - else { - result = schema._zod.run({ value, issues: [] }, ctx); - } - if (result instanceof Promise) { - throw new core.$ZodAsyncError(); - } - return result.issues.length === 0; -} -// no fast path: the compiler keeps async parses on the runtime, because a promise-returning callback that is not declared async compiles to a throw -const parse_validateAsync = async (schema, value, _ctx) => { - const ctx = _ctx ? { ..._ctx, async: true } : { async: true }; - let result = schema._zod.run({ value, issues: [] }, ctx); - if (result instanceof Promise) - result = await result; - return result.issues.length === 0; -}; -const parse_encode = (_Err) => { - const parse = parse_parse(_Err); - const fn = (schema, value, _ctx, _params) => { - const ctx = _ctx ? { ..._ctx, direction: "backward" } : { direction: "backward" }; - return parse(schema, value, ctx, finalizeParams(fn, _params)); - }; - return fn; -}; -const encode = /* @__PURE__*/ parse_encode($ZodRealError); -const parse_decode = (_Err) => { - const parse = parse_parse(_Err); - const fn = (schema, value, _ctx, _params) => { - return parse(schema, value, _ctx, finalizeParams(fn, _params)); - }; - return fn; -}; -const decode = /* @__PURE__*/ parse_decode($ZodRealError); -const parse_encodeAsync = (_Err) => { - const parseAsync = parse_parseAsync(_Err); - const fn = async (schema, value, _ctx, _params) => { - const ctx = _ctx ? { ..._ctx, direction: "backward" } : { direction: "backward" }; - return (await parseAsync(schema, value, ctx, finalizeParams(fn, _params))); - }; - return fn; -}; -const encodeAsync = /* @__PURE__*/ parse_encodeAsync($ZodRealError); -const parse_decodeAsync = (_Err) => { - const parseAsync = parse_parseAsync(_Err); - const fn = async (schema, value, _ctx, _params) => { - return await parseAsync(schema, value, _ctx, finalizeParams(fn, _params)); - }; - return fn; -}; -const decodeAsync = /* @__PURE__*/ parse_decodeAsync($ZodRealError); -const _safeEncode = (_Err) => (schema, value, _ctx) => { - const ctx = _ctx ? { ..._ctx, direction: "backward" } : { direction: "backward" }; - return _safeParse(_Err)(schema, value, ctx); -}; -const safeEncode = /* @__PURE__*/ _safeEncode($ZodRealError); -const _safeDecode = (_Err) => (schema, value, _ctx) => { - return _safeParse(_Err)(schema, value, _ctx); -}; -const safeDecode = /* @__PURE__*/ _safeDecode($ZodRealError); -const _safeEncodeAsync = (_Err) => async (schema, value, _ctx) => { - const ctx = _ctx ? { ..._ctx, direction: "backward" } : { direction: "backward" }; - return _safeParseAsync(_Err)(schema, value, ctx); -}; -const safeEncodeAsync = /* @__PURE__*/ _safeEncodeAsync($ZodRealError); -const _safeDecodeAsync = (_Err) => async (schema, value, _ctx) => { - return _safeParseAsync(_Err)(schema, value, _ctx); -}; -const safeDecodeAsync = /* @__PURE__*/ _safeDecodeAsync($ZodRealError); - -const versions_version = { - major: 4, - minor: 5, - patch: 4, -}; - - - - - - - - -const $ZodType = /*@__PURE__*/ $constructor("$ZodType", (inst, def) => { - var _a; - inst ?? (inst = {}); - inst._zod.def = def; // set _def property - inst._zod.bag = inst._zod.bag || {}; // initialize _bag object - inst._zod.version = versions_version; - const defChecks = inst._zod.def.checks; - // if inst is itself a checks.$ZodCheck, run it as a check - const checks = inst._zod.traits.has("$ZodCheck") - ? [inst, ...(defChecks ?? [])] - : defChecks?.length - ? [...defChecks] - : []; - for (const ch of checks) { - for (const fn of ch._zod.onattach) { - fn(inst); - } - } - if (checks.length === 0) { - // deferred initializer inst._zod.parse is not yet defined - (_a = inst._zod).deferred ?? (_a.deferred = []); - inst._zod.deferred?.push(() => { - inst._zod.run = inst._zod.parse; - }); - } - else { - const runChecks = (payload, checks, ctx) => { - if (payload.memo) - return payload; - let isAborted = aborted(payload); - let asyncResult; - for (const ch of checks) { - if (ch._zod.def.when) { - if (explicitlyAborted(payload)) - continue; - const shouldRun = ch._zod.def.when(payload); - if (!shouldRun) - continue; - } - else if (isAborted) { - continue; - } - const currLen = payload.issues.length; - const _ = ch._zod.check(payload); - if (_ instanceof Promise && ctx?.async === false) { - throw new $ZodAsyncError(); - } - if (asyncResult || _ instanceof Promise) { - asyncResult = (asyncResult ?? Promise.resolve()).then(async () => { - await _; - const nextLen = payload.issues.length; - if (nextLen === currLen) - return; - attachSchema(payload.issues, currLen, inst); - if (!isAborted) - isAborted = aborted(payload, currLen); - }); - } - else { - const nextLen = payload.issues.length; - if (nextLen === currLen) - continue; - attachSchema(payload.issues, currLen, inst); - if (!isAborted) - isAborted = aborted(payload, currLen); - } - } - if (asyncResult) { - return asyncResult.then(() => { - return payload; - }); - } - return payload; - }; - const handleCanaryResult = (canary, payload, ctx) => { - // abort if the canary is aborted - if (aborted(canary)) { - canary.aborted = true; - return canary; - } - // run checks first, then - const checkResult = runChecks(payload, checks, ctx); - if (checkResult instanceof Promise) { - if (ctx.async === false) - throw new $ZodAsyncError(); - return checkResult.then((checkResult) => inst._zod.parse(checkResult, ctx)); - } - return inst._zod.parse(checkResult, ctx); - }; - inst._zod.run = (payload, ctx) => { - if (ctx.skipChecks) { - return inst._zod.parse(payload, ctx); - } - if (ctx.direction === "backward") { - // run canary initial pass (no checks) - const canary = inst._zod.parse({ value: payload.value, issues: [] }, { ...ctx, skipChecks: true }); - if (canary instanceof Promise) { - return canary.then((canary) => { - return handleCanaryResult(canary, payload, ctx); - }); - } - return handleCanaryResult(canary, payload, ctx); - } - // forward - const result = inst._zod.parse(payload, ctx); - if (result instanceof Promise) { - if (ctx.async === false) - throw new $ZodAsyncError(); - return result.then((result) => runChecks(result, checks, ctx)); - } - return runChecks(result, checks, ctx); - }; - } -}, { - // Wrappers extend this by installing a richer factory over it; reading it eagerly would defeat the laziness. - get "~standard"() { - return hide(this, "~standard", standardProps(this)); - }, - set "~standard"(value) { - util_own(this, "~standard", value); - }, -}); -/** The Standard Schema surface for `inst`. Shared so wrappers can extend it without forcing it. */ -const toStandardResult = (r) => r.success ? { value: r.data } : { issues: r.error?.issues }; -function standardProps(inst) { - return { - validate: (value) => { - try { - return toStandardResult(safeParse(inst, value)); - } - catch (_) { - return safeParseAsync(inst, value).then(toStandardResult); - } - }, - vendor: "zod", - version: 1, - }; -} - -const $ZodString = /*@__PURE__*/ $constructor("$ZodString", (inst, def) => { - $ZodType.init(inst, def); - inst._zod.pattern = [...(inst?._zod.bag?.patterns ?? [])].pop() ?? regexes_string(inst._zod.bag); - inst._zod.parse = (payload, _) => { - if (def.coerce) - try { - payload.value = String(payload.value); - } - catch (_) { } - if (typeof payload.value === "string") - return payload; - payload.issues.push({ - expected: "string", - code: "invalid_type", - input: payload.value, - inst, - }); - return payload; - }; -}); -const $ZodStringFormat = /*@__PURE__*/ $constructor("$ZodStringFormat", (inst, def) => { - // check initialization must come first - $ZodCheckStringFormat.init(inst, def); - $ZodString.init(inst, def); -}); -const $ZodGUID = /*@__PURE__*/ $constructor("$ZodGUID", (inst, def) => { - def.pattern ?? (def.pattern = guid); - $ZodStringFormat.init(inst, def); -}); -const $ZodUUID = /*@__PURE__*/ $constructor("$ZodUUID", (inst, def) => { - if (def.version) { - const versionMap = { - v1: 1, - v2: 2, - v3: 3, - v4: 4, - v5: 5, - v6: 6, - v7: 7, - v8: 8, - }; - const v = versionMap[def.version]; - if (v === undefined) - throw new Error(`Invalid UUID version: "${def.version}"`); - def.pattern ?? (def.pattern = uuid(v)); - } - else - def.pattern ?? (def.pattern = uuid()); - $ZodStringFormat.init(inst, def); -}); -const $ZodEmail = /*@__PURE__*/ $constructor("$ZodEmail", (inst, def) => { - def.pattern ?? (def.pattern = email); - $ZodStringFormat.init(inst, def); -}); -/** The `://` guard rejected the input before the URL constructor saw it. */ -const URL_BAD_FORMAT = 1; -/** The URL constructor rejected the input. */ -const URL_UNPARSEABLE = 2; -/** Parses a URL for `$ZodURL`, applying the one guard the URL constructor cannot express. Returns the parsed URL, or a code naming the stage that rejected it — the runtime needs that distinction to pick an issue note, and compiled code only needs to know it is not a URL. */ -function parseURLObject(trimmed, def) { - // When normalize is off, require :// for http/https URLs. This prevents strings like "http:example.com" or "https:/path" from being silently accepted - if (!def.normalize && def.protocol?.source === httpProtocol.source && !/^https?:\/\//i.test(trimmed)) { - return URL_BAD_FORMAT; - } - try { - // @ts-ignore - return new URL(trimmed); - } - catch { - return URL_UNPARSEABLE; - } -} -const asciiTabOrNewline = /[\t\n\r]/g; -/** The URL parser deletes every ASCII tab, LF and CR from its input before it parses, so `new URL("https://exa\nmple.com")` reports on `example.com`. Applying the same deletion to the returned value closes the half of that divergence which can move the host; the parser's other rewrite, stripping C0 controls at the edges, cannot. */ -function stripTabAndNewline(value) { - return value.replace(asciiTabOrNewline, ""); -} -function urlHostnameOk(url, hostname) { - hostname.lastIndex = 0; - return hostname.test(url.hostname); -} -function urlProtocolOk(url, protocol) { - protocol.lastIndex = 0; - return protocol.test(url.protocol.endsWith(":") ? url.protocol.slice(0, -1) : url.protocol); -} -const $ZodURL = /*@__PURE__*/ $constructor("$ZodURL", (inst, def) => { - $ZodStringFormat.init(inst, def); - inst._zod.check = (payload) => { - try { - // Trim whitespace from input - const trimmed = payload.value.trim(); - const url = parseURLObject(trimmed, def); - if (url === URL_BAD_FORMAT) { - payload.issues.push({ - code: "invalid_format", - format: "url", - note: "Invalid URL format", - input: payload.value, - inst, - continue: !def.abort, - }); - return; - } - if (url === URL_UNPARSEABLE) { - payload.issues.push({ - code: "invalid_format", - format: "url", - input: payload.value, - inst, - continue: !def.abort, - }); - return; - } - if (def.hostname && !urlHostnameOk(url, def.hostname)) { - payload.issues.push({ - code: "invalid_format", - format: "url", - note: "Invalid hostname", - pattern: def.hostname.source, - input: payload.value, - inst, - continue: !def.abort, - }); - } - if (def.protocol && !urlProtocolOk(url, def.protocol)) { - payload.issues.push({ - code: "invalid_format", - format: "url", - note: "Invalid protocol", - pattern: def.protocol.source, - input: payload.value, - inst, - continue: !def.abort, - }); - } - // Set the output value based on normalize flag - payload.value = def.normalize ? url.href : stripTabAndNewline(trimmed); - return; - } - catch (_) { - payload.issues.push({ - code: "invalid_format", - format: "url", - input: payload.value, - inst, - continue: !def.abort, - }); - } - }; -}); -const $ZodEmoji = /*@__PURE__*/ $constructor("$ZodEmoji", (inst, def) => { - def.pattern ?? (def.pattern = emoji()); - $ZodStringFormat.init(inst, def); -}); -const $ZodNanoID = /*@__PURE__*/ $constructor("$ZodNanoID", (inst, def) => { - if (def.length !== undefined && (!Number.isInteger(def.length) || def.length < 1)) - throw new Error(`Invalid nanoid length: ${def.length}`); - def.pattern ?? (def.pattern = def.length === undefined ? nanoid : nanoidOfLength(def.length)); - $ZodStringFormat.init(inst, def); -}); -/** - * @deprecated CUID v1 is deprecated by its authors due to information leakage - * (timestamps embedded in the id). Use {@link $ZodCUID2} instead. - * See https://github.com/paralleldrive/cuid. - */ -const $ZodCUID = /*@__PURE__*/ $constructor("$ZodCUID", (inst, def) => { - def.pattern ?? (def.pattern = cuid); - $ZodStringFormat.init(inst, def); -}); -const $ZodCUID2 = /*@__PURE__*/ $constructor("$ZodCUID2", (inst, def) => { - def.pattern ?? (def.pattern = cuid2); - $ZodStringFormat.init(inst, def); -}); -const $ZodULID = /*@__PURE__*/ $constructor("$ZodULID", (inst, def) => { - def.pattern ?? (def.pattern = ulid); - $ZodStringFormat.init(inst, def); -}); -const $ZodXID = /*@__PURE__*/ $constructor("$ZodXID", (inst, def) => { - def.pattern ?? (def.pattern = xid); - $ZodStringFormat.init(inst, def); -}); -const $ZodKSUID = /*@__PURE__*/ $constructor("$ZodKSUID", (inst, def) => { - def.pattern ?? (def.pattern = ksuid); - $ZodStringFormat.init(inst, def); -}); -const $ZodISODateTime = /*@__PURE__*/ $constructor("$ZodISODateTime", (inst, def) => { - def.pattern ?? (def.pattern = datetime(def)); - $ZodStringFormat.init(inst, def); - // these two drop the offset or seconds `date-time` requires — on the bag not the def, since `z.string().check(...)` lands the format on a different schema - if (def.local || def.precision === -1) { - inst._zod.bag.laxFormat = true; - inst._zod.onattach.push((s) => { - s._zod.bag.laxFormat = true; - }); - } -}); -const $ZodISODate = /*@__PURE__*/ $constructor("$ZodISODate", (inst, def) => { - def.pattern ?? (def.pattern = regexes_date); - $ZodStringFormat.init(inst, def); -}); -const $ZodISOTime = /*@__PURE__*/ $constructor("$ZodISOTime", (inst, def) => { - def.pattern ?? (def.pattern = regexes_time(def)); - $ZodStringFormat.init(inst, def); -}); -const $ZodISODuration = /*@__PURE__*/ $constructor("$ZodISODuration", (inst, def) => { - def.pattern ?? (def.pattern = duration); - $ZodStringFormat.init(inst, def); -}); -const $ZodIPv4 = /*@__PURE__*/ $constructor("$ZodIPv4", (inst, def) => { - def.pattern ?? (def.pattern = ipv4); - $ZodStringFormat.init(inst, def); - inst._zod.bag.format = `ipv4`; -}); -/** An IPv6 address is written with hex digits, colons and dots, and nothing else. The guard is what makes the check below an IPv6 check: `new URL("http://[...]")` parses an authority, not an address, so `@` and `\` re-delimit it and `"::@1\\"` validates against the host `0.0.0.1`. The URL parser also deletes ASCII tab, LF and CR rather than failing, which is how `"::1\n"` validated as `::1`. */ -const ipv6Alphabet = /^[0-9a-fA-F:.]+$/; -function isValidIPv6(value) { - if (!ipv6Alphabet.test(value)) - return false; - try { - // @ts-ignore - new URL(`http://[${value}]`); - return true; - } - catch { - return false; - } -} -const $ZodIPv6 = /*@__PURE__*/ $constructor("$ZodIPv6", (inst, def) => { - def.pattern ?? (def.pattern = regexes_ipv6); - $ZodStringFormat.init(inst, def); - inst._zod.bag.format = `ipv6`; - inst._zod.check = (payload) => { - if (!isValidIPv6(payload.value)) { - payload.issues.push({ - code: "invalid_format", - format: "ipv6", - input: payload.value, - inst, - continue: !def.abort, - }); - } - }; -}); -const $ZodMAC = /*@__PURE__*/ (/* unused pure expression or super */ null && (core.$constructor("$ZodMAC", (inst, def) => { - def.pattern ?? (def.pattern = regexes.mac(def.delimiter)); - $ZodStringFormat.init(inst, def); - inst._zod.bag.format = `mac`; -}))); -const $ZodCIDRv4 = /*@__PURE__*/ $constructor("$ZodCIDRv4", (inst, def) => { - def.pattern ?? (def.pattern = cidrv4); - $ZodStringFormat.init(inst, def); -}); -function isValidCIDRv6(value) { - const parts = value.split("/"); - if (parts.length !== 2) - return false; - const [address, prefix] = parts; - if (!prefix) - return false; - const prefixNum = Number(prefix); - if (`${prefixNum}` !== prefix) - return false; - if (prefixNum < 0 || prefixNum > 128) - return false; - return isValidIPv6(address); -} -const $ZodCIDRv6 = /*@__PURE__*/ $constructor("$ZodCIDRv6", (inst, def) => { - def.pattern ?? (def.pattern = cidrv6); // not used for validation - $ZodStringFormat.init(inst, def); - inst._zod.check = (payload) => { - if (!isValidCIDRv6(payload.value)) { - payload.issues.push({ - code: "invalid_format", - format: "cidrv6", - input: payload.value, - inst, - continue: !def.abort, - }); - } - }; -}); -////////////////////////////// ZodBase64 ////////////////////////////// -function isValidBase64(data) { - if (data === "") - return true; - // atob ignores whitespace, so reject it up front. - if (/\s/.test(data)) - return false; - if (data.length % 4 !== 0) - return false; - try { - // @ts-ignore - atob(data); - return true; - } - catch { - return false; - } -} -const $ZodBase64 = /*@__PURE__*/ $constructor("$ZodBase64", (inst, def) => { - def.pattern ?? (def.pattern = regexes_base64); - $ZodStringFormat.init(inst, def); - inst._zod.bag.contentEncoding = "base64"; - inst._zod.check = (payload) => { - if (isValidBase64(payload.value)) - return; - payload.issues.push({ - code: "invalid_format", - format: "base64", - input: payload.value, - inst, - continue: !def.abort, - }); - }; -}); -////////////////////////////// ZodBase64 ////////////////////////////// -function isValidBase64URL(data) { - if (!regexes_base64url.test(data)) - return false; - const base64 = data.replace(/[-_]/g, (c) => (c === "-" ? "+" : "/")); - const padded = base64.padEnd(Math.ceil(base64.length / 4) * 4, "="); - return isValidBase64(padded); -} -const $ZodBase64URL = /*@__PURE__*/ $constructor("$ZodBase64URL", (inst, def) => { - def.pattern ?? (def.pattern = regexes_base64url); - $ZodStringFormat.init(inst, def); - inst._zod.bag.contentEncoding = "base64url"; - inst._zod.check = (payload) => { - if (isValidBase64URL(payload.value)) - return; - payload.issues.push({ - code: "invalid_format", - format: "base64url", - input: payload.value, - inst, - continue: !def.abort, - }); - }; -}); -const $ZodE164 = /*@__PURE__*/ $constructor("$ZodE164", (inst, def) => { - def.pattern ?? (def.pattern = e164); - $ZodStringFormat.init(inst, def); -}); -////////////////////////////// ZodCreditCard ////////////////////////////// -const CC_SANITIZE = /[- ]/g; -/** Luhn checksum on a digit-only string. Adapted from valibot (MIT). */ -function isLuhnAlgo(digits) { - let length = digits.length; - let bit = 1; - let sum = 0; - while (length) { - const value = +digits[--length]; - bit ^= 1; - sum += bit ? [0, 2, 4, 6, 8, 1, 3, 5, 7, 9][value] : value; - } - return sum % 10 === 0; -} -function isValidCreditCard(input) { - if (!regexes.creditCard.test(input)) - return false; - return isLuhnAlgo(input.replace(CC_SANITIZE, "")); -} -const $ZodCreditCard = /*@__PURE__*/ (/* unused pure expression or super */ null && (core.$constructor("$ZodCreditCard", (inst, def) => { - // Shape only — the Luhn check below is not expressible as a pattern, so consumers of `pattern` (JSON Schema, template literals) get the length and separator rules alone. - def.pattern ?? (def.pattern = regexes.creditCard); - $ZodStringFormat.init(inst, def); - inst._zod.check = (payload) => { - if (isValidCreditCard(payload.value)) - return; - payload.issues.push({ - code: "invalid_format", - format: "credit_card", - input: payload.value, - inst, - continue: !def.abort, - }); - }; -}))); -////////////////////////////// ZodJWT ////////////////////////////// -function isValidJWT(token, algorithm = null) { - try { - const tokensParts = token.split("."); - if (tokensParts.length !== 3) - return false; - const [header] = tokensParts; - if (!header) - return false; - // @ts-ignore - const parsedHeader = JSON.parse(atob(header)); - if ("typ" in parsedHeader && parsedHeader?.typ !== "JWT") - return false; - if (!parsedHeader.alg) - return false; - if (algorithm && (!("alg" in parsedHeader) || parsedHeader.alg !== algorithm)) - return false; - return true; - } - catch { - return false; - } -} -const $ZodJWT = /*@__PURE__*/ $constructor("$ZodJWT", (inst, def) => { - $ZodStringFormat.init(inst, def); - inst._zod.check = (payload) => { - if (isValidJWT(payload.value, def.alg)) - return; - payload.issues.push({ - code: "invalid_format", - format: "jwt", - input: payload.value, - inst, - continue: !def.abort, - }); - }; -}); -const $ZodCustomStringFormat = /*@__PURE__*/ (/* unused pure expression or super */ null && (core.$constructor("$ZodCustomStringFormat", (inst, def) => { - $ZodStringFormat.init(inst, def); - inst._zod.check = (payload) => { - if (def.fn(payload.value)) - return; - payload.issues.push({ - code: "invalid_format", - format: def.format, - input: payload.value, - inst, - continue: !def.abort, - }); - }; -}))); -const $ZodNumber = /*@__PURE__*/ $constructor("$ZodNumber", (inst, def) => { - $ZodType.init(inst, def); - inst._zod.pattern = inst._zod.bag.pattern ?? number; - inst._zod.parse = (payload, _ctx) => { - if (def.coerce) - try { - payload.value = Number(payload.value); - } - catch (_) { } - const input = payload.value; - if (typeof input === "number" && !Number.isNaN(input) && Number.isFinite(input)) { - return payload; - } - const received = typeof input === "number" - ? Number.isNaN(input) - ? "NaN" - : !Number.isFinite(input) - ? String(input) - : undefined - : undefined; - payload.issues.push({ - expected: "number", - code: "invalid_type", - input, - inst, - ...(received ? { received } : {}), - }); - return payload; - }; -}); -const $ZodNumberFormat = /*@__PURE__*/ $constructor("$ZodNumberFormat", (inst, def) => { - $ZodCheckNumberFormat.init(inst, def); - $ZodNumber.init(inst, def); // no format checks -}); -const $ZodBoolean = /*@__PURE__*/ $constructor("$ZodBoolean", (inst, def) => { - $ZodType.init(inst, def); - inst._zod.pattern = regexes_boolean; - inst._zod.parse = (payload, _ctx) => { - if (def.coerce) - try { - payload.value = Boolean(payload.value); - } - catch (_) { } - const input = payload.value; - if (typeof input === "boolean") - return payload; - payload.issues.push({ - expected: "boolean", - code: "invalid_type", - input, - inst, - }); - return payload; - }; -}); -const $ZodBigInt = /*@__PURE__*/ (/* unused pure expression or super */ null && (core.$constructor("$ZodBigInt", (inst, def) => { - $ZodType.init(inst, def); - inst._zod.pattern = regexes.bigint; - inst._zod.parse = (payload, _ctx) => { - if (def.coerce) - try { - payload.value = BigInt(payload.value); - } - catch (_) { } - if (typeof payload.value === "bigint") - return payload; - payload.issues.push({ - expected: "bigint", - code: "invalid_type", - input: payload.value, - inst, - }); - return payload; - }; -}))); -const $ZodBigIntFormat = /*@__PURE__*/ (/* unused pure expression or super */ null && (core.$constructor("$ZodBigIntFormat", (inst, def) => { - checks.$ZodCheckBigIntFormat.init(inst, def); - $ZodBigInt.init(inst, def); // no format checks -}))); -const $ZodSymbol = /*@__PURE__*/ (/* unused pure expression or super */ null && (core.$constructor("$ZodSymbol", (inst, def) => { - $ZodType.init(inst, def); - inst._zod.parse = (payload, _ctx) => { - const input = payload.value; - if (typeof input === "symbol") - return payload; - payload.issues.push({ - expected: "symbol", - code: "invalid_type", - input, - inst, - }); - return payload; - }; -}))); -const $ZodUndefined = /*@__PURE__*/ (/* unused pure expression or super */ null && (core.$constructor("$ZodUndefined", (inst, def) => { - $ZodType.init(inst, def); - inst._zod.pattern = regexes.undefined; - inst._zod.values = new Set([undefined]); - inst._zod.parse = (payload, _ctx) => { - const input = payload.value; - if (typeof input === "undefined") - return payload; - payload.issues.push({ - expected: "undefined", - code: "invalid_type", - input, - inst, - }); - return payload; - }; -}))); -const $ZodNull = /*@__PURE__*/ $constructor("$ZodNull", (inst, def) => { - $ZodType.init(inst, def); - inst._zod.pattern = _null; - inst._zod.values = new Set([null]); - inst._zod.parse = (payload, _ctx) => { - const input = payload.value; - if (input === null) - return payload; - payload.issues.push({ - expected: "null", - code: "invalid_type", - input, - inst, - }); - return payload; - }; -}); -const $ZodAny = /*@__PURE__*/ $constructor("$ZodAny", (inst, def) => { - $ZodType.init(inst, def); - inst._zod.parse = (payload) => payload; -}); -const $ZodUnknown = /*@__PURE__*/ $constructor("$ZodUnknown", (inst, def) => { - $ZodType.init(inst, def); - inst._zod.parse = (payload) => payload; -}); -const $ZodNever = /*@__PURE__*/ $constructor("$ZodNever", (inst, def) => { - $ZodType.init(inst, def); - inst._zod.parse = (payload, _ctx) => { - payload.issues.push({ - expected: "never", - code: "invalid_type", - input: payload.value, - inst, - }); - return payload; - }; -}); -const $ZodVoid = /*@__PURE__*/ (/* unused pure expression or super */ null && (core.$constructor("$ZodVoid", (inst, def) => { - $ZodType.init(inst, def); - inst._zod.parse = (payload, _ctx) => { - const input = payload.value; - if (typeof input === "undefined") - return payload; - payload.issues.push({ - expected: "void", - code: "invalid_type", - input, - inst, - }); - return payload; - }; -}))); -const $ZodDate = /*@__PURE__*/ (/* unused pure expression or super */ null && (core.$constructor("$ZodDate", (inst, def) => { - $ZodType.init(inst, def); - inst._zod.parse = (payload, _ctx) => { - if (def.coerce) { - try { - payload.value = new Date(payload.value); - } - catch (_err) { } - } - const input = payload.value; - const isDate = input instanceof Date; - const isValidDate = isDate && !Number.isNaN(input.getTime()); - if (isValidDate) - return payload; - payload.issues.push({ - expected: "date", - code: "invalid_type", - input, - ...(isDate ? { received: "Invalid Date" } : {}), - inst, - }); - return payload; - }; -}))); -function handleArrayResult(result, final, index) { - if (result.issues.length) { - final.issues.push(...prefixIssues(index, result.issues)); - } - final.value[index] = result.value; -} -const $ZodArray = /*@__PURE__*/ $constructor("$ZodArray", (inst, def) => { - $ZodType.init(inst, def); - const memo = globalConfig.memoizer; - memo?.attach(inst); - inst._zod.parse = (payload, ctx) => { - const input = payload.value; - if (!Array.isArray(input)) { - payload.issues.push({ - expected: "array", - code: "invalid_type", - input, - inst, - }); - return payload; - } - payload.value = memo ? memo.alloc(inst, payload, Array(input.length), ctx) : Array(input.length); - const proms = []; - for (let i = 0; i < input.length; i++) { - const item = input[i]; - const result = def.element._zod.run({ - value: item, - issues: [], - }, ctx); - if (result instanceof Promise) { - proms.push(result.then((result) => handleArrayResult(result, payload, i))); - } - else { - handleArrayResult(result, payload, i); - } - } - if (proms.length) { - return Promise.all(proms).then(() => payload); - } - return payload; //handleArrayResultsAsync(parseResults, final); - }; -}); -function handlePropertyResult(result, final, key, input, optin, optout) { - const isPresent = key in input; - const isOptionalOut = optout === "optional"; - // The middle rung means "absence permitted, nothing supplied in its place", so an absent key contributes nothing — whatever the schema made of `undefined` is invented, not substituted. Only `optional` reaches this with a value: `defaulted` substitutes, and a schema that isn't optional-out has to keep the key. - if (!isPresent && isOptionalOut && optin === "optional") { - return; - } - if (result.issues.length) { - // For optional-in/out schemas, ignore errors on absent keys. - if (optin !== undefined && isOptionalOut && !isPresent) { - return; - } - final.issues.push(...prefixIssues(key, result.issues)); - } - if (!isPresent && optin === undefined) { - if (!result.issues.length) { - final.issues.push({ - code: "invalid_type", - expected: "nonoptional", - input: undefined, - path: [key], - }); - } - return; - } - if (result.value === undefined) { - if (isPresent) { - final.value[key] = undefined; - } - } - else { - final.value[key] = result.value; - } -} -// one shared instance; a fresh [] per schema cost 56 bytes retained -const NO_SYMBOL_KEYS = []; -function normalizeDef(def) { - const keys = Object.keys(def.shape); - const ownSymbols = Object.getOwnPropertySymbols(def.shape); - const symbolKeys = ownSymbols.length ? ownSymbols : NO_SYMBOL_KEYS; - // aliases `keys` when there are no symbols, so a string-only shape keeps one array - const allKeys = symbolKeys.length ? [...keys, ...symbolKeys] : keys; - for (const k of allKeys) { - if (!def.shape?.[k]?._zod?.traits?.has("$ZodType")) { - throw new Error(`Invalid element at key "${String(k)}": expected a Zod schema`); - } - } - const okeys = optionalKeys(def.shape); - return { - ...def, - allKeys, - symbolKeys, - // string-only: handleCatchall matches it against `for...in`, which never yields a symbol - keySet: new Set(keys), - numKeys: keys.length, - optionalKeys: new Set(okeys), - }; -} -function handleCatchall(proms, input, payload, ctx, def, inst) { - const unrecognized = []; - const keySet = def.keySet; - const _catchall = def.catchall._zod; - const t = _catchall.def.type; - const optin = _catchall.optin; - const optout = _catchall.optout; - for (const key in input) { - // Must precede the __proto__ branch: a declared key is not unrecognized, even though the shape loop deliberately strips __proto__ from the parsed output. - if (keySet.has(key)) - continue; - // Don't copy an undeclared __proto__ into the result; assignment to a plain {} would replace the result prototype. But in strict mode it is still an unknown key, so report it before skipping. - if (key === "__proto__") { - if (t === "never") - unrecognized.push(key); - continue; - } - if (t === "never") { - unrecognized.push(key); - continue; - } - const r = _catchall.run({ value: input[key], issues: [] }, ctx); - if (r instanceof Promise) { - proms.push(r.then((r) => handlePropertyResult(r, payload, key, input, optin, optout))); - } - else { - handlePropertyResult(r, payload, key, input, optin, optout); - } - } - if (unrecognized.length) { - payload.issues.push({ - code: "unrecognized_keys", - keys: unrecognized, - input, - inst, - // Describes the shape of the input, not the validity of the parsed value, so it never aborts. The parse still fails; the schema's own checks just get to run first, and an enclosing intersection can reconcile the key against a sibling operand. - continue: true, - }); - } - if (!proms.length) - return payload; - return Promise.all(proms).then(() => { - return payload; - }); -} -// Whichever object a def's `shape` currently answers from: the one the caller passed until the first read, the frozen copy after it. Keyed by def, so a def rebuilt by a builder is simply absent rather than inheriting the source's. Read its keys with `Object.keys`, which does not invoke them — that is what lets a discriminated union check its discriminator without resolving an option whose getters reference the union being constructed. -const propShapes = new WeakMap(); -const $ZodObject = /*@__PURE__*/ $constructor("$ZodObject", (inst, def) => { - // requires cast because technically $ZodObject doesn't extend - $ZodType.init(inst, def); - // const sh = def.shape; - const desc = Object.getOwnPropertyDescriptor(def, "shape"); - if (!desc?.get) { - const sh = def.shape; - propShapes.set(def, sh); - Object.defineProperty(def, "shape", { - get: () => { - const newSh = { ...sh }; - Object.defineProperty(def, "shape", { - value: newSh, - }); - propShapes.set(def, newSh); - return newSh; - }, - }); - } - const _normalized = util_cached(() => normalizeDef(def)); - defineLazyInternal(inst, "propValues", (zod) => { - const shape = zod.def.shape; - const propValues = {}; - for (const key in shape) { - const field = shape[key]._zod; - if (field.values) { - if (!Object.prototype.hasOwnProperty.call(propValues, key)) { - assignProp(propValues, key, new Set()); - } - for (const v of field.values) - propValues[key].add(v); - // An omittable slot reads back as undefined at a discriminator lookup, so it has to claim undefined: two options that can both omit the key are not discriminable on it. - if (field.optin !== undefined) - propValues[key].add(undefined); - } - } - return propValues; - }); - const isObject = util_isObject; - const catchall = def.catchall; - let value; - const memo = globalConfig.memoizer; - memo?.attach(inst); - inst._zod.parse = (payload, ctx) => { - value ?? (value = _normalized.value); - const input = payload.value; - if (!isObject(input)) { - payload.issues.push({ - expected: "object", - code: "invalid_type", - input, - inst, - }); - return payload; - } - payload.value = memo ? memo.alloc(inst, payload, {}, ctx) : {}; - const proms = []; - const shape = value.shape; - for (const key of value.allKeys) { - if (key === "__proto__") - continue; - const el = shape[key]; - const optin = el._zod.optin; - const optout = el._zod.optout; - const r = el._zod.run({ value: input[key], issues: [] }, ctx); - if (r instanceof Promise) { - proms.push(r.then((r) => handlePropertyResult(r, payload, key, input, optin, optout))); - } - else { - handlePropertyResult(r, payload, key, input, optin, optout); - } - } - if (!catchall) { - return proms.length ? Promise.all(proms).then(() => payload) : payload; - } - return handleCatchall(proms, input, payload, ctx, _normalized.value, inst); - }; -}); -const $ZodObjectJIT = /*@__PURE__*/ $constructor("$ZodObjectJIT", (inst, def) => { - // requires cast because technically $ZodObject doesn't extend - $ZodObject.init(inst, def); - const superParse = inst._zod.parse; - const _normalized = util_cached(() => normalizeDef(def)); - const memo = globalConfig.memoizer; - const generateFastpass = (shape) => { - const normalized = _normalized.value; - const syms = normalized.symbolKeys; - // a symbol has no source literal, so it is read as `syms[i]` off the closed-over scope - const doc = new Doc(["payload", "ctx"], { shape, inst, memo, syms }); - const parseStr = (k) => `shape[${k}]._zod.run({ value: input[${k}], issues: [] }, ctx)`; - // Prefixes in place, like util.prefixIssues does for every interpreted path. - const prefixStr = (id, k) => ` - for (let i = 0; i < ${id}.issues.length; i++) { - const iss = ${id}.issues[i]; - iss.path = iss.path ? [${k}, ...iss.path] : [${k}]; - payload.issues.push(iss); - }`; - doc.write(`const input = payload.value;`); - const ids = Object.create(null); - let counter = 0; - for (const key of normalized.allKeys) { - ids[key] = `key_${counter++}`; - } - // A: preserve key order { - doc.write(memo ? `const newResult = memo.alloc(inst, payload, {}, ctx);` : `const newResult = {};`); - for (const key of normalized.allKeys) { - if (key === "__proto__") - continue; - const id = ids[key]; - const k = typeof key === "symbol" ? `syms[${syms.indexOf(key)}]` : util_esc(key); - const isPresent = `${k} in input`; - const schema = shape[key]; - const optin = schema?._zod?.optin; - const isOptionalIn = optin !== undefined; - const isOptionalOut = schema?._zod?.optout === "optional"; - doc.write(`const ${id} = ${parseStr(k)};`); - if (isOptionalIn && isOptionalOut) { - // For optional-in/out schemas, ignore errors on absent keys — and, like the interpreted path, drop the value produced alongside them. The middle rung goes further: it permits absence without supplying anything in its place, so an absent key contributes nothing at all. - const assign = optin === "optional" ? `${id}_present` : `${id}.value !== undefined || ${id}_present`; - doc.write(` - const ${id}_present = ${isPresent}; - if (!${id}.issues.length || ${id}_present) { - if (${id}.issues.length) {${prefixStr(id, k)} - } - - if (${assign}) { - newResult[${k}] = ${id}.value; - } - } - - `); - } - else if (!isOptionalIn) { - doc.write(` - const ${id}_present = ${isPresent}; - if (${id}.issues.length) {${prefixStr(id, k)} - } - if (!${id}_present && !${id}.issues.length) { - payload.issues.push({ - code: "invalid_type", - expected: "nonoptional", - input: undefined, - path: [${k}] - }); - } - - if (${id}_present) { - newResult[${k}] = ${id}.value; - } - - `); - } - else { - doc.write(` - if (${id}.issues.length) {${prefixStr(id, k)} - } - - if (${id}.value === undefined) { - if (${isPresent}) { - newResult[${k}] = undefined; - } - } else { - newResult[${k}] = ${id}.value; - } - - `); - } - } - doc.write(`payload.value = newResult;`); - doc.write(`return payload;`); - // closing `shape` in is what pays: turbofan specializes the parser against that one shape object, so every `shape[k]._zod.run` folds to a known callee. as a parameter it stays a generic load and measures 13% slower even with the forwarding frame gone - return doc.compile(); - }; - let fastpass; - const isObject = util_isObject; - const jit = !globalConfig.jitless; - const allowsEval = util_allowsEval; - const fastEnabled = jit && allowsEval.value; // && !def.catchall; - const catchall = def.catchall; - let value; - inst._zod.parse = (payload, ctx) => { - value ?? (value = _normalized.value); - const input = payload.value; - if (!isObject(input)) { - payload.issues.push({ - expected: "object", - code: "invalid_type", - input, - inst, - }); - return payload; - } - if (jit && fastEnabled && ctx?.async === false && ctx.jitless !== true) { - // always synchronous - if (!fastpass) - fastpass = generateFastpass(def.shape); - payload = fastpass(payload, ctx); - if (!catchall) - return payload; - return handleCatchall([], input, payload, ctx, value, inst); - } - return superParse(payload, ctx); - }; -}); -function handleUnionResults(results, final, inst, ctx) { - for (const result of results) { - if (result.issues.length === 0) { - final.value = result.value; - return final; - } - } - const nonaborted = results.filter((r) => !aborted(r)); - if (nonaborted.length === 1) { - final.value = nonaborted[0].value; - return nonaborted[0]; - } - final.issues.push({ - code: "invalid_union", - input: final.value, - inst, - errors: results.map((result) => result.issues.map((iss) => finalizeIssue(iss, ctx, core_config()))), - }); - return final; -} -const $ZodUnion = /*@__PURE__*/ $constructor("$ZodUnion", (inst, def) => { - $ZodType.init(inst, def); - defineLazyInternal(inst, "optin", (zod) => zod.def.options.some((o) => o._zod.optin === "defaulted") - ? "defaulted" - : zod.def.options.some((o) => o._zod.optin !== undefined) - ? "optional" - : undefined); - defineLazyInternal(inst, "optout", (zod) => zod.def.options.some((o) => o._zod.optout === "optional") ? "optional" : undefined); - defineLazyInternal(inst, "values", (zod) => { - if (zod.def.options.every((o) => o._zod.values)) { - return new Set(zod.def.options.flatMap((option) => Array.from(option._zod.values))); - } - return undefined; - }); - defineLazyInternal(inst, "pattern", (zod) => { - if (zod.def.options.every((o) => o._zod.pattern)) { - const patterns = zod.def.options.map((o) => o._zod.pattern); - return new RegExp(`^(${patterns.map((p) => cleanRegex(p.source)).join("|")})$`); - } - return undefined; - }); - const first = def.options.length === 1 ? def.options[0]._zod.run : null; - inst._zod.parse = (payload, ctx) => { - if (first) { - return first(payload, ctx); - } - let async = false; - const results = []; - for (const option of def.options) { - const result = option._zod.run({ - value: payload.value, - issues: [], - }, ctx); - if (result instanceof Promise) { - results.push(result); - async = true; - } - else { - if (result.issues.length === 0) - return result; - results.push(result); - } - } - if (!async) - return handleUnionResults(results, payload, inst, ctx); - return Promise.all(results).then((results) => { - return handleUnionResults(results, payload, inst, ctx); - }); - }; -}); -function handleExclusiveUnionResults(results, final, inst, ctx) { - const matches = []; - for (let i = 0; i < results.length; i++) { - if (results[i].issues.length === 0) - matches.push(i); - } - if (matches.length === 1) { - final.value = results[matches[0]].value; - return final; - } - if (matches.length === 0) { - // No matches - same as regular union - final.issues.push({ - code: "invalid_union", - input: final.value, - inst, - errors: results.map((result) => result.issues.map((iss) => util.finalizeIssue(iss, ctx, core.config()))), - }); - } - else { - // Multiple matches - exclusive union failure - final.issues.push({ - code: "invalid_union", - input: final.value, - inst, - errors: [], - inclusive: false, - matches, - }); - } - return final; -} -const $ZodXor = /*@__PURE__*/ (/* unused pure expression or super */ null && (core.$constructor("$ZodXor", (inst, def) => { - $ZodUnion.init(inst, def); - def.inclusive = false; - const first = def.options.length === 1 ? def.options[0]._zod.run : null; - inst._zod.parse = (payload, ctx) => { - if (first) { - return first(payload, ctx); - } - let async = false; - const results = []; - for (const option of def.options) { - const result = option._zod.run({ - value: payload.value, - issues: [], - }, ctx); - if (result instanceof Promise) { - results.push(result); - async = true; - } - else { - results.push(result); - } - } - if (!async) - return handleExclusiveUnionResults(results, payload, inst, ctx); - return Promise.all(results).then((results) => { - return handleExclusiveUnionResults(results, payload, inst, ctx); - }); - }; -}))); -/** Returns the option of `union` whose discriminator claims `value`. */ -function getDiscriminatedOption(union, value) { - const internals = union._zod; - let map = internals.bag.optionsMap; - if (!map) { - map = new Map(); - const { options, discriminator } = internals.def; - for (const option of options) { - // First declaration wins, matching the order the parse path resolves a duplicate in. - for (const v of option._zod.propValues?.[discriminator] ?? []) - if (!map.has(v)) - map.set(v, option); - } - internals.bag.optionsMap = map; - } - return map.get(value); -} -const $ZodDiscriminatedUnion = -/*@__PURE__*/ -$constructor("$ZodDiscriminatedUnion", (inst, def) => { - def.inclusive = false; - $ZodUnion.init(inst, def); - const _super = inst._zod.parse; - defineLazyInternal(inst, "propValues", (zod) => { - const propValues = {}; - for (const option of zod.def.options) { - const pv = option._zod.propValues; - if (!pv || Object.keys(pv).length === 0) - throw new Error(`Invalid discriminated union option at index "${zod.def.options.indexOf(option)}"`); - for (const [k, v] of Object.entries(pv)) { - if (!Object.prototype.hasOwnProperty.call(propValues, k)) { - assignProp(propValues, k, new Set()); - } - for (const val of v) { - propValues[k].add(val); - } - } - } - return propValues; - }); - // Checked now rather than in the lookup map below, so an option that lacks the discriminator fails at the `discriminatedUnion` call instead of on the first object parsed. Options whose shape cannot be enumerated without resolving it — pipes, lazies, and objects rebuilt by a builder such as `.extend()` — are left to the map. - def.options.forEach((option, i) => { - const propShape = propShapes.get(option._zod.def); - if (propShape && !Object.prototype.hasOwnProperty.call(propShape, def.discriminator)) { - throw new Error(`Invalid discriminated union option at index "${i}"`); - } - }); - const disc = util_cached(() => { - const opts = def.options; - const map = new Map(); - for (const o of opts) { - const values = o._zod.propValues?.[def.discriminator]; - if (!values || values.size === 0) - throw new Error(`Invalid discriminated union option at index "${def.options.indexOf(o)}"`); - for (const v of values) { - if (map.has(v)) { - throw new Error(`Duplicate discriminator value "${String(v)}"`); - } - map.set(v, o); - } - } - return map; - }); - inst._zod.parse = (payload, ctx) => { - const input = payload.value; - if (!util_isObject(input)) { - payload.issues.push({ - code: "invalid_type", - expected: "object", - input, - inst, - }); - return payload; - } - const opt = disc.value.get(input?.[def.discriminator]); - if (opt) { - return opt._zod.run(payload, ctx); - } - // Fall back to union matching when the fast discriminator path fails: - // - explicitly enabled via unionFallback, or - // - during backward direction (encode), since codec-based discriminators have different values in forward vs backward directions - if (def.unionFallback || ctx.direction === "backward") { - return _super(payload, ctx); - } - // no matching discriminator - payload.issues.push({ - code: "invalid_union", - errors: [], - note: "No matching discriminator", - discriminator: def.discriminator, - options: Array.from(disc.value.keys()), - input, - path: [def.discriminator], - inst, - }); - return payload; - }; -}); -const $ZodIntersection = /*@__PURE__*/ $constructor("$ZodIntersection", (inst, def) => { - $ZodType.init(inst, def); - inst._zod.parse = (payload, ctx) => { - const input = payload.value; - const left = def.left._zod.run({ value: input, issues: [] }, ctx); - const right = def.right._zod.run({ value: input, issues: [] }, ctx); - const async = left instanceof Promise || right instanceof Promise; - if (async) { - return Promise.all([left, right]).then(([left, right]) => { - return handleIntersectionResults(payload, left, right); - }); - } - return handleIntersectionResults(payload, left, right); - }; -}); -function schemas_mergeValues(a, b) { - // const aType = parse.t(a); - // const bType = parse.t(b); - if (a === b) { - return { valid: true, data: a }; - } - if (a instanceof Date && b instanceof Date && +a === +b) { - return { valid: true, data: a }; - } - if (isPlainObject(a) && isPlainObject(b)) { - const bKeys = Object.keys(b); - const sharedKeys = Object.keys(a).filter((key) => bKeys.indexOf(key) !== -1); - const newObj = { ...a, ...b }; - if (Object.prototype.hasOwnProperty.call(newObj, "__proto__")) - delete newObj.__proto__; - for (const key of sharedKeys) { - if (key === "__proto__") - continue; - const sharedValue = schemas_mergeValues(a[key], b[key]); - if (!sharedValue.valid) { - return { - valid: false, - mergeErrorPath: [key, ...sharedValue.mergeErrorPath], - }; - } - newObj[key] = sharedValue.data; - } - return { valid: true, data: newObj }; - } - if (Array.isArray(a) && Array.isArray(b)) { - if (a.length !== b.length) { - return { valid: false, mergeErrorPath: [] }; - } - const newArray = []; - for (let index = 0; index < a.length; index++) { - const itemA = a[index]; - const itemB = b[index]; - const sharedValue = schemas_mergeValues(itemA, itemB); - if (!sharedValue.valid) { - return { - valid: false, - mergeErrorPath: [index, ...sharedValue.mergeErrorPath], - }; - } - newArray.push(sharedValue.data); - } - return { valid: true, data: newArray }; - } - return { valid: false, mergeErrorPath: [] }; -} -function handleIntersectionResults(result, left, right) { - // Track which side(s) reject each key. A key rejection is reported only when BOTH sides reject it, so a key owned by one branch survives the other's key schema. strictObject reports these as unrecognized_keys; a record with an open key schema reports one invalid_key per key. - const unrecKeys = new Map(); - let unrecIssue; - const keyIssues = new Map(); - const collect = (iss, side) => { - let keys; - if (iss.code === "unrecognized_keys" && !iss.path?.length) { - unrecIssue ?? (unrecIssue = iss); - keys = iss.keys; - } - else if (iss.code === "invalid_key" && iss.origin === "record" && iss.path?.length === 1) { - const k = String(iss.path[0]); - if (!keyIssues.has(k)) - keyIssues.set(k, iss); - keys = [k]; - } - else { - return false; - } - for (const k of keys) { - if (!unrecKeys.has(k)) - unrecKeys.set(k, {}); - unrecKeys.get(k)[side] = true; - } - return true; - }; - for (const iss of left.issues) { - if (!collect(iss, "l")) - result.issues.push(iss); - } - for (const iss of right.issues) { - if (!collect(iss, "r")) - result.issues.push(iss); - } - // Report only keys rejected by BOTH sides - const bothKeys = [...unrecKeys].filter(([, f]) => f.l && f.r).map(([k]) => k); - if (bothKeys.length) { - const aggregated = unrecIssue ? bothKeys.filter((k) => unrecIssue.keys.includes(k)) : []; - if (aggregated.length) - result.issues.push({ ...unrecIssue, keys: aggregated }); - for (const k of bothKeys) { - if (!aggregated.includes(k) && keyIssues.has(k)) - result.issues.push(keyIssues.get(k)); - } - } - const merged = schemas_mergeValues(left.value, right.value); - if (!merged.valid) { - if (aborted(result)) - return result; - throw new Error(`Unmergable intersection. Error path: ` + `${JSON.stringify(merged.mergeErrorPath)}`); - } - result.value = merged.data; - return result; -} -const $ZodTuple = /*@__PURE__*/ (/* unused pure expression or super */ null && (core.$constructor("$ZodTuple", (inst, def) => { - $ZodType.init(inst, def); - const items = def.items; - const memo = core.globalConfig.memoizer; - memo?.attach(inst); - inst._zod.parse = (payload, ctx) => { - const input = payload.value; - if (!Array.isArray(input)) { - payload.issues.push({ - input, - inst, - expected: "tuple", - code: "invalid_type", - }); - return payload; - } - payload.value = memo ? memo.alloc(inst, payload, [], ctx) : []; - const proms = []; - const optinStart = getTupleOptStart(items, "optin"); - const optoutStart = getTupleOptStart(items, "optout"); - if (!def.rest) { - if (input.length < optinStart) { - payload.issues.push({ - code: "too_small", - minimum: optinStart, - inclusive: true, - input, - inst, - origin: "array", - }); - return payload; - } - if (input.length > items.length) { - payload.issues.push({ - code: "too_big", - maximum: items.length, - inclusive: true, - input, - inst, - origin: "array", - }); - } - } - // Run every item in parallel, collecting results into an indexed array. The post-processing in `handleTupleResults` walks them in order so it can decide whether an absent optional-output error can truncate the tail or must be reported to preserve required output. - const itemResults = new Array(items.length); - for (let i = 0; i < items.length; i++) { - const r = items[i]._zod.run({ value: input[i], issues: [] }, ctx); - if (r instanceof Promise) { - proms.push(r.then((rr) => { - itemResults[i] = rr; - })); - } - else { - itemResults[i] = r; - } - } - if (def.rest) { - let i = items.length - 1; - const rest = input.slice(items.length); - for (const el of rest) { - i++; - const result = def.rest._zod.run({ value: el, issues: [] }, ctx); - if (result instanceof Promise) { - proms.push(result.then((r) => handleTupleResult(r, payload, i))); - } - else { - handleTupleResult(result, payload, i); - } - } - } - if (proms.length) { - return Promise.all(proms).then(() => handleTupleResults(itemResults, payload, items, input, optoutStart)); - } - return handleTupleResults(itemResults, payload, items, input, optoutStart); - }; -}))); -function getTupleOptStart(items, key) { - for (let i = items.length - 1; i >= 0; i--) { - // optin is a three-rung ladder so any rung above `undefined` permits an absent slot; optout stays two-valued. - const omittable = key === "optin" ? items[i]._zod.optin !== undefined : items[i]._zod.optout === "optional"; - if (!omittable) - return i + 1; - } - return 0; -} -function handleTupleResult(result, final, index) { - if (result.issues.length) { - final.issues.push(...util.prefixIssues(index, result.issues)); - } - final.value[index] = result.value; -} -function handleTupleResults(itemResults, final, items, input, optoutStart) { - // Walk results in order. Mirror $ZodObject's swallow-on-absent-optional rule, but only after `optoutStart`: the first index where the output tuple tail can be absent. - for (let i = 0; i < items.length; i++) { - const r = itemResults[i]; - const isPresent = i < input.length; - // The array analog of `handlePropertyResult`'s absent-key early return: the middle rung permits absence without supplying anything in its place, so the tail truncates here instead of materializing whatever the item made of `undefined`. - if (!isPresent && i >= optoutStart && items[i]._zod.optin === "optional") { - final.value.length = i; - break; - } - if (r.issues.length) { - if (!isPresent && i >= optoutStart) { - final.value.length = i; - break; - } - final.issues.push(...util.prefixIssues(i, r.issues)); - } - final.value[i] = r.value; - } - // Drop trailing slots that produced `undefined` for absent input - // (the array analog of an absent optional key on an object). The - // `i >= input.length` floor is critical: an explicit `undefined` - // *inside* the input must be preserved even when the schema is - // optional-out (e.g. `z.string().or(z.undefined())` accepting an - // explicit undefined value). - for (let i = final.value.length - 1; i >= input.length; i--) { - if (items[i]._zod.optout === "optional" && final.value[i] === undefined) { - final.value.length = i; - } - else { - break; - } - } - return final; -} -const $ZodRecord = /*@__PURE__*/ $constructor("$ZodRecord", (inst, def) => { - $ZodType.init(inst, def); - const memo = globalConfig.memoizer; - memo?.attach(inst); - inst._zod.parse = (payload, ctx) => { - const input = payload.value; - if (!isPlainObject(input)) { - payload.issues.push({ - expected: "record", - code: "invalid_type", - input, - inst, - }); - return payload; - } - const proms = []; - const values = def.keyType._zod.values; - if (values && !def.partial) { - payload.value = memo ? memo.alloc(inst, payload, {}, ctx) : {}; - const recordKeys = new Set(); - for (const key of values) { - if (typeof key === "string" || typeof key === "number" || typeof key === "symbol") { - recordKeys.add(typeof key === "number" ? key.toString() : key); - // A declared __proto__ is stripped but is not an unrecognized key. - if (key === "__proto__") - continue; - const keyResult = def.keyType._zod.run({ value: key, issues: [] }, ctx); - if (keyResult instanceof Promise) { - throw new Error("Async schemas not supported in object keys currently"); - } - if (keyResult.issues.length) { - payload.issues.push({ - code: "invalid_key", - origin: "record", - issues: keyResult.issues.map((iss) => finalizeIssue(iss, ctx, core_config())), - input: key, - path: [key], - inst, - }); - continue; - } - const outKey = keyResult.value; - if (outKey === "__proto__") - continue; - const result = def.valueType._zod.run({ value: input[key], issues: [] }, ctx); - if (result instanceof Promise) { - proms.push(result.then((result) => { - if (result.issues.length) { - payload.issues.push(...prefixIssues(key, result.issues)); - } - payload.value[outKey] = result.value; - })); - } - else { - if (result.issues.length) { - payload.issues.push(...prefixIssues(key, result.issues)); - } - payload.value[outKey] = result.value; - } - } - } - let unrecognized; - for (const key in input) { - if (!recordKeys.has(key)) { - if (def.mode === "loose") { - // skip __proto__ so it can't replace the result prototype via the assignment setter on the plain {} we build into - if (key === "__proto__") - continue; - payload.value[key] = input[key]; - } - else { - unrecognized = unrecognized ?? []; - unrecognized.push(key); - } - } - } - if (unrecognized && unrecognized.length > 0) { - payload.issues.push({ - code: "unrecognized_keys", - input, - inst, - keys: unrecognized, - continue: true, - }); - } - } - else { - payload.value = memo ? memo.alloc(inst, payload, {}, ctx) : {}; - // An enumerable key schema declares which keys the record owns, so a key outside the set is unrecognized. A non-enumerable one (regex, refine) is a constraint every key must satisfy, so a failing key is invalid. Only the former is reconcilable against the other side of an intersection. - let unrecognized; - // Reflect.ownKeys for Symbol-key support; filter non-enumerable to match z.object() - for (const key of Reflect.ownKeys(input)) { - if (key === "__proto__") - continue; - if (!Object.prototype.propertyIsEnumerable.call(input, key)) - continue; - let keyResult = def.keyType._zod.run({ value: key, issues: [] }, ctx); - if (keyResult instanceof Promise) { - throw new Error("Async schemas not supported in object keys currently"); - } - // Numeric string fallback: if key is a numeric string and failed, retry with Number(key). This handles z.number(), z.literal([1, 2, 3]), and unions containing numeric literals - const checkNumericKey = typeof key === "string" && number.test(key) && keyResult.issues.length; - if (checkNumericKey) { - const retryResult = def.keyType._zod.run({ value: Number(key), issues: [] }, ctx); - if (retryResult instanceof Promise) { - throw new Error("Async schemas not supported in object keys currently"); - } - if (retryResult.issues.length === 0) { - keyResult = retryResult; - } - } - if (keyResult.issues.length) { - if (def.mode === "loose") { - // Pass through unchanged - payload.value[key] = input[key]; - } - else if (values) { - unrecognized = unrecognized ?? []; - unrecognized.push(key); - } - else { - // Default "strict" behavior: error on invalid key - payload.issues.push({ - code: "invalid_key", - origin: "record", - issues: keyResult.issues.map((iss) => finalizeIssue(iss, ctx, core_config())), - input: key, - path: [key], - inst, - }); - } - continue; - } - // the guard above tests the raw input key, but the key schema can normalize an ordinary key into __proto__; re-check the key we actually write under - const outKey = keyResult.value; - if (outKey === "__proto__") - continue; - const result = def.valueType._zod.run({ value: input[key], issues: [] }, ctx); - if (result instanceof Promise) { - proms.push(result.then((result) => { - if (result.issues.length) { - payload.issues.push(...prefixIssues(key, result.issues)); - } - payload.value[outKey] = result.value; - })); - } - else { - if (result.issues.length) { - payload.issues.push(...prefixIssues(key, result.issues)); - } - payload.value[outKey] = result.value; - } - } - if (unrecognized && unrecognized.length > 0) { - payload.issues.push({ - code: "unrecognized_keys", - input, - inst, - keys: unrecognized, - continue: true, - }); - } - } - if (proms.length) { - return Promise.all(proms).then(() => payload); - } - return payload; - }; -}); -const $ZodMap = /*@__PURE__*/ (/* unused pure expression or super */ null && (core.$constructor("$ZodMap", (inst, def) => { - $ZodType.init(inst, def); - const memo = core.globalConfig.memoizer; - memo?.attach(inst); - inst._zod.parse = (payload, ctx) => { - const input = payload.value; - if (!(input instanceof Map)) { - payload.issues.push({ - expected: "map", - code: "invalid_type", - input, - inst, - }); - return payload; - } - const proms = []; - payload.value = memo ? memo.alloc(inst, payload, new Map(), ctx) : new Map(); - for (const [key, value] of input) { - const keyResult = def.keyType._zod.run({ value: key, issues: [] }, ctx); - const valueResult = def.valueType._zod.run({ value: value, issues: [] }, ctx); - if (keyResult instanceof Promise || valueResult instanceof Promise) { - proms.push(Promise.all([keyResult, valueResult]).then(([keyResult, valueResult]) => { - handleMapResult(keyResult, valueResult, payload, key, input, inst, ctx); - })); - } - else { - handleMapResult(keyResult, valueResult, payload, key, input, inst, ctx); - } - } - if (proms.length) - return Promise.all(proms).then(() => payload); - return payload; - }; -}))); -function handleMapResult(keyResult, valueResult, final, key, input, inst, ctx) { - if (keyResult.issues.length) { - if (util.propertyKeyTypes.has(typeof key)) { - final.issues.push(...util.prefixIssues(key, keyResult.issues)); - } - else { - final.issues.push({ - code: "invalid_key", - origin: "map", - input, - inst, - issues: keyResult.issues.map((iss) => util.finalizeIssue(iss, ctx, core.config())), - }); - } - } - if (valueResult.issues.length) { - if (util.propertyKeyTypes.has(typeof key)) { - final.issues.push(...util.prefixIssues(key, valueResult.issues)); - } - else { - final.issues.push({ - origin: "map", - code: "invalid_element", - input, - inst, - key: key, - issues: valueResult.issues.map((iss) => util.finalizeIssue(iss, ctx, core.config())), - }); - } - } - final.value.set(keyResult.value, valueResult.value); -} -const $ZodSet = /*@__PURE__*/ (/* unused pure expression or super */ null && (core.$constructor("$ZodSet", (inst, def) => { - $ZodType.init(inst, def); - const memo = core.globalConfig.memoizer; - memo?.attach(inst); - inst._zod.parse = (payload, ctx) => { - const input = payload.value; - if (!(input instanceof Set)) { - payload.issues.push({ - input, - inst, - expected: "set", - code: "invalid_type", - }); - return payload; - } - const proms = []; - payload.value = memo ? memo.alloc(inst, payload, new Set(), ctx) : new Set(); - for (const item of input) { - const result = def.valueType._zod.run({ value: item, issues: [] }, ctx); - if (result instanceof Promise) { - proms.push(result.then((result) => handleSetResult(result, payload))); - } - else - handleSetResult(result, payload); - } - if (proms.length) - return Promise.all(proms).then(() => payload); - return payload; - }; -}))); -function handleSetResult(result, final) { - if (result.issues.length) { - final.issues.push(...result.issues); - } - final.value.add(result.value); -} -const $ZodEnum = /*@__PURE__*/ $constructor("$ZodEnum", (inst, def) => { - $ZodType.init(inst, def); - const values = getEnumValues(def.entries); - const valuesSet = new Set(values); - inst._zod.values = valuesSet; - const patternValues = values.filter((k) => propertyKeyTypes.has(typeof k)); - // unmatchable fallback, RE2-safe: an empty alternation would compile to /^()$/, which matches "" - inst._zod.pattern = new RegExp(patternValues.length ? `^(${patternValues.map((o) => escapeRegex(o.toString())).join("|")})$` : "^[^\\s\\S]$"); - inst._zod.parse = (payload, _ctx) => { - const input = payload.value; - if (valuesSet.has(input)) { - return payload; - } - payload.issues.push({ - code: "invalid_value", - values, - input, - inst, - }); - return payload; - }; -}); -const $ZodLiteral = /*@__PURE__*/ $constructor("$ZodLiteral", (inst, def) => { - $ZodType.init(inst, def); - const values = new Set(def.values); - inst._zod.values = values; - // unmatchable fallback, RE2-safe: an empty alternation would compile to /^()$/, which matches "" - inst._zod.pattern = new RegExp(def.values.length - ? `^(${def.values - .map((o) => (typeof o === "string" ? escapeRegex(o) : o ? escapeRegex(o.toString()) : String(o))) - .join("|")})$` - : "^[^\\s\\S]$"); - inst._zod.parse = (payload, _ctx) => { - const input = payload.value; - if (values.has(input)) { - return payload; - } - payload.issues.push({ - code: "invalid_value", - values: def.values, - input, - inst, - }); - return payload; - }; -}); -const $ZodFile = /*@__PURE__*/ (/* unused pure expression or super */ null && (core.$constructor("$ZodFile", (inst, def) => { - $ZodType.init(inst, def); - inst._zod.parse = (payload, _ctx) => { - const input = payload.value; - // @ts-ignore - if (input instanceof File) - return payload; - payload.issues.push({ - expected: "file", - code: "invalid_type", - input, - inst, - }); - return payload; - }; -}))); -const $ZodTransform = /*@__PURE__*/ $constructor("$ZodTransform", (inst, def) => { - $ZodType.init(inst, def); - inst._zod.optin = "optional"; - globalConfig.memoizer?.guard(inst); - inst._zod.parse = (payload, ctx) => { - if (ctx.direction === "backward") { - throw new $ZodEncodeError(inst.constructor.name); - } - const _out = def.transform(payload.value, payload); - if (ctx.async) { - const output = _out instanceof Promise ? _out : Promise.resolve(_out); - return output.then((output) => { - payload.value = output; - return payload; - }); - } - if (_out instanceof Promise) { - throw new $ZodAsyncError(); - } - payload.value = _out; - return payload; - }; -}); -function handleOptionalResult(payload, result) { - // A substituting schema that still failed has no usable answer; yield undefined. Its issues are simply dropped: it ran on a payload of its own, so there is no shared array to truncate and nothing of the caller's to lose with it. - payload.value = result.issues.length ? undefined : result.value; - return payload; -} -const $ZodOptional = /*@__PURE__*/ $constructor("$ZodOptional", (inst, def) => { - $ZodType.init(inst, def); - // .optional() propagates absence rather than substituting for it, so a defaulted inner keeps its rung. - defineLazyInternal(inst, "optin", (zod) => zod.def.innerType._zod.optin === "defaulted" ? "defaulted" : "optional"); - inst._zod.optout = "optional"; - defineLazyInternal(inst, "values", (zod) => { - const values = zod.def.innerType._zod.values; - return values ? new Set([...values, undefined]) : undefined; - }); - defineLazyInternal(inst, "pattern", (zod) => { - const pattern = zod.def.innerType._zod.pattern; - return pattern ? new RegExp(`^(${cleanRegex(pattern.source)})?$`) : undefined; - }); - inst._zod.parse = (payload, ctx) => { - if (payload.value === undefined) { - // Only the top rung substitutes a value for absence; everything else leaves it intact, which is what .optional() means. - if (def.innerType._zod.optin !== "defaulted") - return payload; - // Its own payload, for the same reason $ZodCatch gets one: a pipe forwards an unrecognized key through the caller's issues array, and this must not read that as the substituting schema failing and drop it. - const result = def.innerType._zod.run({ value: payload.value, issues: [] }, ctx); - if (result instanceof Promise) - return result.then((result) => handleOptionalResult(payload, result)); - return handleOptionalResult(payload, result); - } - return def.innerType._zod.run(payload, ctx); - }; -}); -const $ZodExactOptional = /*@__PURE__*/ $constructor("$ZodExactOptional", (inst, def) => { - // Call parent init - inherits optin/optout = "optional" - $ZodOptional.init(inst, def); - // Override values/pattern to NOT add undefined - defineLazyInternal(inst, "values", (zod) => zod.def.innerType._zod.values); - defineLazyInternal(inst, "pattern", (zod) => zod.def.innerType._zod.pattern); - // Override parse to just delegate (no undefined handling) - inst._zod.parse = (payload, ctx) => { - return def.innerType._zod.run(payload, ctx); - }; -}); -const $ZodNullable = /*@__PURE__*/ $constructor("$ZodNullable", (inst, def) => { - $ZodType.init(inst, def); - defineLazyInternal(inst, "optin", (zod) => zod.def.innerType._zod.optin); - defineLazyInternal(inst, "optout", (zod) => zod.def.innerType._zod.optout); - defineLazyInternal(inst, "pattern", (zod) => { - const pattern = zod.def.innerType._zod.pattern; - return pattern ? new RegExp(`^(${cleanRegex(pattern.source)}|null)$`) : undefined; - }); - defineLazyInternal(inst, "values", (zod) => { - return zod.def.innerType._zod.values ? new Set([...zod.def.innerType._zod.values, null]) : undefined; - }); - inst._zod.parse = (payload, ctx) => { - // Forward direction (decode): allow null to pass through - if (payload.value === null) - return payload; - return def.innerType._zod.run(payload, ctx); - }; -}); -const $ZodDefault = /*@__PURE__*/ $constructor("$ZodDefault", (inst, def) => { - $ZodType.init(inst, def); - // inst._zod.qin = "true"; - inst._zod.optin = "defaulted"; - defineLazyInternal(inst, "values", (zod) => zod.def.innerType._zod.values); - inst._zod.parse = (payload, ctx) => { - if (ctx.direction === "backward") { - return def.innerType._zod.run(payload, ctx); - } - // Forward direction (decode): apply defaults for undefined input - if (payload.value === undefined) { - payload.value = def.defaultValue; - /** - * $ZodDefault returns the default value immediately in forward direction. - * It doesn't pass the default value into the validator ("prefault"). There's no reason to pass the default value through validation. The validity of the default is enforced by TypeScript statically. Otherwise, it's the responsibility of the user to ensure the default is valid. In the case of pipes with divergent in/out types, you can specify the default on the `in` schema of your ZodPipe to set a "prefault" for the pipe. */ - return payload; - } - // Forward direction: continue with default handling - const result = def.innerType._zod.run(payload, ctx); - if (result instanceof Promise) { - return result.then((result) => handleDefaultResult(result, def)); - } - return handleDefaultResult(result, def); - }; -}); -function handleDefaultResult(payload, def) { - if (payload.value === undefined) { - payload.value = def.defaultValue; - } - return payload; -} -const $ZodPrefault = /*@__PURE__*/ $constructor("$ZodPrefault", (inst, def) => { - $ZodType.init(inst, def); - inst._zod.optin = "defaulted"; - defineLazyInternal(inst, "values", (zod) => zod.def.innerType._zod.values); - inst._zod.parse = (payload, ctx) => { - if (ctx.direction === "backward") { - return def.innerType._zod.run(payload, ctx); - } - // Forward direction (decode): apply prefault for undefined input - if (payload.value === undefined) { - payload.value = def.defaultValue; - } - return def.innerType._zod.run(payload, ctx); - }; -}); -const $ZodNonOptional = /*@__PURE__*/ $constructor("$ZodNonOptional", (inst, def) => { - $ZodType.init(inst, def); - defineLazyInternal(inst, "values", (zod) => { - const v = zod.def.innerType._zod.values; - return v ? new Set([...v].filter((x) => x !== undefined)) : undefined; - }); - inst._zod.parse = (payload, ctx) => { - const result = def.innerType._zod.run(payload, ctx); - if (result instanceof Promise) { - return result.then((result) => handleNonOptionalResult(result, inst)); - } - return handleNonOptionalResult(result, inst); - }; -}); -function handleNonOptionalResult(payload, inst) { - if (!payload.issues.length && payload.value === undefined) { - payload.issues.push({ - code: "invalid_type", - expected: "nonoptional", - input: payload.value, - inst, - }); - } - return payload; -} -const $ZodSuccess = /*@__PURE__*/ (/* unused pure expression or super */ null && (core.$constructor("$ZodSuccess", (inst, def) => { - $ZodType.init(inst, def); - inst._zod.parse = (payload, ctx) => { - if (ctx.direction === "backward") { - throw new core.$ZodEncodeError("ZodSuccess"); - } - const result = def.innerType._zod.run(payload, ctx); - if (result instanceof Promise) { - return result.then((result) => { - payload.value = result.issues.length === 0; - return payload; - }); - } - payload.value = result.issues.length === 0; - return payload; - }; -}))); -function handleCatchResult(payload, result, def, ctx) { - if (!result.issues.length) { - payload.value = result.value; - // The value carries up, so the flag describing it has to carry with it: a back-edge into a node still being parsed must not be frozen by an enclosing readonly, and its checks belong to the node itself. Guarded so the ordinary case adds no own property. - if (result.memo) - payload.memo = true; - return payload; - } - // Spread the inner's own payload, not ours: `value` has to stay the input the catch was handed, and the inner ran on a payload of its own so its issues are already private to this call. - payload.value = def.catchValue({ - ...result, - value: payload.value, - error: { - issues: result.issues.map((iss) => finalizeIssue(iss, ctx, core_config())), - }, - input: payload.value, - }); - return payload; -} -const $ZodCatch = /*@__PURE__*/ $constructor("$ZodCatch", (inst, def) => { - $ZodType.init(inst, def); - defineLazyInternal(inst, "optin", (zod) => zod.def.innerType._zod.optin === "defaulted" ? "defaulted" : "optional"); - defineLazyInternal(inst, "optout", (zod) => zod.def.innerType._zod.optout); - defineLazyInternal(inst, "values", (zod) => zod.def.innerType._zod.values); - inst._zod.parse = (payload, ctx) => { - if (ctx.direction === "backward") { - return def.innerType._zod.run(payload, ctx); - } - // Forward direction (decode): apply catch logic - const result = def.innerType._zod.run({ value: payload.value, issues: [] }, ctx); - if (result instanceof Promise) { - return result.then((result) => handleCatchResult(payload, result, def, ctx)); - } - return handleCatchResult(payload, result, def, ctx); - }; -}); -const $ZodNaN = /*@__PURE__*/ (/* unused pure expression or super */ null && (core.$constructor("$ZodNaN", (inst, def) => { - $ZodType.init(inst, def); - inst._zod.parse = (payload, _ctx) => { - if (typeof payload.value !== "number" || !Number.isNaN(payload.value)) { - payload.issues.push({ - input: payload.value, - inst, - expected: "nan", - code: "invalid_type", - }); - return payload; - } - return payload; - }; -}))); -const $ZodPipe = /*@__PURE__*/ $constructor("$ZodPipe", (inst, def) => { - $ZodType.init(inst, def); - defineLazyInternal(inst, "values", (zod) => zod.def.in._zod.values); - defineLazyInternal(inst, "optin", (zod) => zod.def.in._zod.optin); - defineLazyInternal(inst, "optout", (zod) => zod.def.out._zod.optout); - defineLazyInternal(inst, "propValues", (zod) => zod.def.in._zod.propValues); - inst._zod.parse = (payload, ctx) => { - if (ctx.direction === "backward") { - const right = def.out._zod.run(payload, ctx); - if (right instanceof Promise) { - return right.then((right) => handlePipeResult(right, def.in, ctx)); - } - return handlePipeResult(right, def.in, ctx); - } - const left = def.in._zod.run(payload, ctx); - if (left instanceof Promise) { - return left.then((left) => handlePipeResult(left, def.out, ctx)); - } - return handlePipeResult(left, def.out, ctx); - }; -}); -function handlePipeResult(left, next, ctx) { - // Any issue stops the pipe, so a failing refinement never feeds its transform. An unrecognized key is the exception: it describes the input's extra properties, not the value being piped, and an enclosing intersection may yet reconcile it. - if (left.issues.some((iss) => iss.code !== "unrecognized_keys")) { - // prevent further checks - left.aborted = true; - return left; - } - return next._zod.run({ value: left.value, issues: left.issues }, ctx); -} -const $ZodCodec = /*@__PURE__*/ (/* unused pure expression or super */ null && (core.$constructor("$ZodCodec", (inst, def) => { - $ZodType.init(inst, def); - util.defineLazyInternal(inst, "values", (zod) => zod.def.in._zod.values); - util.defineLazyInternal(inst, "optin", (zod) => zod.def.in._zod.optin); - util.defineLazyInternal(inst, "optout", (zod) => zod.def.out._zod.optout); - util.defineLazyInternal(inst, "propValues", (zod) => zod.def.in._zod.propValues); - inst._zod.parse = (payload, ctx) => { - const direction = ctx.direction || "forward"; - if (direction === "forward") { - const left = def.in._zod.run(payload, ctx); - if (left instanceof Promise) { - return left.then((left) => handleCodecAResult(left, def, ctx)); - } - return handleCodecAResult(left, def, ctx); - } - else { - const right = def.out._zod.run(payload, ctx); - if (right instanceof Promise) { - return right.then((right) => handleCodecAResult(right, def, ctx)); - } - return handleCodecAResult(right, def, ctx); - } - }; -}))); -function handleCodecAResult(result, def, ctx) { - if (result.issues.length) { - // prevent further checks - result.aborted = true; - return result; - } - const direction = ctx.direction || "forward"; - if (direction === "forward") { - const transformed = def.transform(result.value, result); - if (transformed instanceof Promise) { - return transformed.then((value) => handleCodecTxResult(result, value, def.out, ctx)); - } - return handleCodecTxResult(result, transformed, def.out, ctx); - } - else { - const transformed = def.reverseTransform(result.value, result); - if (transformed instanceof Promise) { - return transformed.then((value) => handleCodecTxResult(result, value, def.in, ctx)); - } - return handleCodecTxResult(result, transformed, def.in, ctx); - } -} -function handleCodecTxResult(left, value, nextSchema, ctx) { - // Check if transform added any issues - if (left.issues.length) { - left.aborted = true; - return left; - } - return nextSchema._zod.run({ value, issues: left.issues }, ctx); -} -const $ZodPreprocess = /*@__PURE__*/ $constructor("$ZodPreprocess", (inst, def) => { - $ZodPipe.init(inst, def); -}); -const $ZodReadonly = /*@__PURE__*/ $constructor("$ZodReadonly", (inst, def) => { - $ZodType.init(inst, def); - defineLazyInternal(inst, "propValues", (zod) => zod.def.innerType._zod.propValues); - defineLazyInternal(inst, "values", (zod) => zod.def.innerType._zod.values); - defineLazyInternal(inst, "optin", (zod) => zod.def.innerType?._zod?.optin); - defineLazyInternal(inst, "optout", (zod) => zod.def.innerType?._zod?.optout); - inst._zod.parse = (payload, ctx) => { - if (ctx.direction === "backward") { - return def.innerType._zod.run(payload, ctx); - } - const result = def.innerType._zod.run(payload, ctx); - if (result instanceof Promise) { - return result.then(handleReadonlyResult); - } - return handleReadonlyResult(result); - }; -}); -function handleReadonlyResult(payload) { - // A repeat visit hands back a node that is still being built; freezing it here would make the rest of its keys fail to assign. - if (!payload.memo) - payload.value = Object.freeze(payload.value); - return payload; -} -const $ZodTemplateLiteral = /*@__PURE__*/ (/* unused pure expression or super */ null && (core.$constructor("$ZodTemplateLiteral", (inst, def) => { - $ZodType.init(inst, def); - const regexParts = []; - for (const part of def.parts) { - if (typeof part === "object" && part !== null) { - // is Zod schema - if (!part._zod.pattern) { - // if (!source) - throw new Error(`Invalid template literal part, no pattern found: ${[...part._zod.traits].shift()}`); - } - const source = part._zod.pattern instanceof RegExp ? part._zod.pattern.source : part._zod.pattern; - if (!source) - throw new Error(`Invalid template literal part: ${part._zod.traits}`); - const start = source.startsWith("^") ? 1 : 0; - const end = source.endsWith("$") ? source.length - 1 : source.length; - regexParts.push(source.slice(start, end)); - } - else if (part === null || util.primitiveTypes.has(typeof part)) { - regexParts.push(util.escapeRegex(`${part}`)); - } - else { - throw new Error(`Invalid template literal part: ${part}`); - } - } - inst._zod.pattern = new RegExp(`^${regexParts.join("")}$`); - inst._zod.parse = (payload, _ctx) => { - if (typeof payload.value !== "string") { - payload.issues.push({ - input: payload.value, - inst, - expected: "string", - code: "invalid_type", - }); - return payload; - } - inst._zod.pattern.lastIndex = 0; - if (!inst._zod.pattern.test(payload.value)) { - payload.issues.push({ - input: payload.value, - inst, - code: "invalid_format", - format: def.format ?? "template_literal", - pattern: inst._zod.pattern.source, - }); - return payload; - } - return payload; - }; -}))); -const $ZodFunction = /*@__PURE__*/ (/* unused pure expression or super */ null && (core.$constructor("$ZodFunction", (inst, def) => { - $ZodType.init(inst, def); - // Defined, not assigned: the classic prototype exposes `_def` as a getter with no setter. - Object.defineProperty(inst, "_def", { value: def }); - inst._zod.def = def; - inst.implement = (func) => { - if (typeof func !== "function") { - throw new Error("implement() must be called with a function"); - } - // Defined inline so the closure stays anonymous: binding it to a `const` first names it, which costs 256 bytes per implemented function. - return Object.defineProperty(function (...args) { - const parsedArgs = inst._def.input ? parse(inst._def.input, args) : args; - const result = Reflect.apply(func, this, parsedArgs); - if (inst._def.output) { - return parse(inst._def.output, result); - } - return result; - }, "_zod", { value: inst._zod, enumerable: false }); - }; - inst.implementAsync = (func) => { - if (typeof func !== "function") { - throw new Error("implementAsync() must be called with a function"); - } - return Object.defineProperty(async function (...args) { - const parsedArgs = inst._def.input ? await parseAsync(inst._def.input, args) : args; - const result = await Reflect.apply(func, this, parsedArgs); - if (inst._def.output) { - return await parseAsync(inst._def.output, result); - } - return result; - }, "_zod", { value: inst._zod, enumerable: false }); - }; - inst._zod.parse = (payload, _ctx) => { - if (typeof payload.value !== "function") { - payload.issues.push({ - code: "invalid_type", - expected: "function", - input: payload.value, - inst, - }); - return payload; - } - // Check if output is a promise type to determine if we should use async implementation - const hasPromiseOutput = inst._def.output && inst._def.output._zod.def.type === "promise"; - if (hasPromiseOutput) { - payload.value = inst.implementAsync(payload.value); - } - else { - payload.value = inst.implement(payload.value); - } - return payload; - }; - inst.input = (...args) => { - const F = inst.constructor; - if (Array.isArray(args[0])) { - return new F({ - type: "function", - input: new $ZodTuple({ - type: "tuple", - items: args[0], - rest: args[1], - }), - output: inst._def.output, - }); - } - return new F({ - type: "function", - input: args[0], - output: inst._def.output, - }); - }; - inst.output = (output) => { - const F = inst.constructor; - return new F({ - type: "function", - input: inst._def.input, - output, - }); - }; - return inst; -}))); -const $ZodPromise = /*@__PURE__*/ (/* unused pure expression or super */ null && (core.$constructor("$ZodPromise", (inst, def) => { - $ZodType.init(inst, def); - inst._zod.parse = (payload, ctx) => { - return Promise.resolve(payload.value).then((inner) => def.innerType._zod.run({ value: inner, issues: [] }, ctx)); - }; -}))); -const $ZodLazy = /*@__PURE__*/ $constructor("$ZodLazy", (inst, def) => { - $ZodType.init(inst, def); - // Cache the resolved inner type on the shared `def` so all clones of this lazy (e.g. via `.describe()`/`.meta()`) share the same inner instance, preserving identity for cycle detection on recursive schemas. - defineLazy(inst._zod, "innerType", () => { - const d = def; - if (!d._cachedInner) - d._cachedInner = def.getter(); - return d._cachedInner; - }); - defineLazyInternal(inst, "pattern", (zod) => zod.innerType?._zod?.pattern); - defineLazyInternal(inst, "propValues", (zod) => zod.innerType?._zod?.propValues); - defineLazyInternal(inst, "optin", (zod) => zod.innerType?._zod?.optin ?? undefined); - defineLazyInternal(inst, "optout", (zod) => zod.innerType?._zod?.optout ?? undefined); - inst._zod.parse = (payload, ctx) => { - const inner = inst._zod.innerType; - return inner._zod.run(payload, ctx); - }; -}); -const $ZodCustom = /*@__PURE__*/ $constructor("$ZodCustom", (inst, def) => { - $ZodCheck.init(inst, def); - $ZodType.init(inst, def); - inst._zod.parse = (payload, _) => { - return payload; - }; - inst._zod.check = (payload) => { - const input = payload.value; - const r = def.fn(input); - if (r instanceof Promise) { - return r.then((r) => handleRefineResult(r, payload, input, inst)); - } - handleRefineResult(r, payload, input, inst); - return; - }; -}); -function handleRefineResult(result, payload, input, inst) { - if (!result) { - const _iss = { - code: "custom", - input, - inst, // incorporates params.error into issue reporting - path: [...(inst._zod.def.path ?? [])], // incorporates params.error into issue reporting - continue: !inst._zod.def.abort, - // params: inst._zod.def.params, - }; - if (inst._zod.def.params) - _iss.params = inst._zod.def.params; - payload.issues.push(util_issue(_iss)); - } -} - -var registries_a; -const $output = /*@__PURE__*/ (/* unused pure expression or super */ null && (Symbol("ZodOutput"))); -const $input = /*@__PURE__*/ (/* unused pure expression or super */ null && (Symbol("ZodInput"))); -class $ZodRegistry { - constructor() { - this._map = new WeakMap(); - this._idmap = new Map(); - } - add(schema, ..._meta) { - const meta = _meta[0]; - this._map.set(schema, meta); - if (meta && typeof meta === "object" && "id" in meta) { - this._idmap.set(meta.id, schema); - } - return this; - } - clear() { - this._map = new WeakMap(); - this._idmap = new Map(); - return this; - } - remove(schema) { - const meta = this._map.get(schema); - if (meta && typeof meta === "object" && "id" in meta) { - this._idmap.delete(meta.id); - } - this._map.delete(schema); - return this; - } - get(schema) { - // return this._map.get(schema) as any; - // inherit metadata - const p = schema._zod.parent; - if (p) { - const pm = { ...(this.get(p) ?? {}) }; - delete pm.id; // do not inherit id - const f = { ...pm, ...this._map.get(schema) }; - return Object.keys(f).length ? f : undefined; - } - return this._map.get(schema); - } - has(schema) { - return this._map.has(schema); - } -} -// registries -function registries_registry() { - return new $ZodRegistry(); -} -(registries_a = globalThis).__zod_globalRegistry ?? (registries_a.__zod_globalRegistry = registries_registry()); -const globalRegistry = globalThis.__zod_globalRegistry; - - - - - -// @__NO_SIDE_EFFECTS__ -function _string(Class, params) { - return new Class({ - type: "string", - ...normalizeParams(params), - }); -} -// @__NO_SIDE_EFFECTS__ -function _coercedString(Class, params) { - return new Class({ - type: "string", - coerce: true, - ...util.normalizeParams(params), - }); -} -// @__NO_SIDE_EFFECTS__ -function _email(Class, params) { - return new Class({ - type: "string", - format: "email", - check: "string_format", - abort: false, - ...normalizeParams(params), - }); -} -// @__NO_SIDE_EFFECTS__ -function _guid(Class, params) { - return new Class({ - type: "string", - format: "guid", - check: "string_format", - abort: false, - ...normalizeParams(params), - }); -} -// @__NO_SIDE_EFFECTS__ -function _uuid(Class, params) { - return new Class({ - type: "string", - format: "uuid", - check: "string_format", - abort: false, - ...normalizeParams(params), - }); -} -// @__NO_SIDE_EFFECTS__ -function _uuidv4(Class, params) { - return new Class({ - type: "string", - format: "uuid", - check: "string_format", - abort: false, - version: "v4", - ...normalizeParams(params), - }); -} -// @__NO_SIDE_EFFECTS__ -function _uuidv6(Class, params) { - return new Class({ - type: "string", - format: "uuid", - check: "string_format", - abort: false, - version: "v6", - ...normalizeParams(params), - }); -} -// @__NO_SIDE_EFFECTS__ -function _uuidv7(Class, params) { - return new Class({ - type: "string", - format: "uuid", - check: "string_format", - abort: false, - version: "v7", - ...normalizeParams(params), - }); -} -// @__NO_SIDE_EFFECTS__ -function _url(Class, params) { - return new Class({ - type: "string", - format: "url", - check: "string_format", - abort: false, - ...normalizeParams(params), - }); -} -// @__NO_SIDE_EFFECTS__ -function api_emoji(Class, params) { - return new Class({ - type: "string", - format: "emoji", - check: "string_format", - abort: false, - ...normalizeParams(params), - }); -} -// @__NO_SIDE_EFFECTS__ -function _nanoid(Class, params) { - return new Class({ - type: "string", - format: "nanoid", - check: "string_format", - abort: false, - ...normalizeParams(params), - }); -} -/** - * @deprecated CUID v1 is deprecated by its authors due to information leakage - * (timestamps embedded in the id). Use {@link _cuid2} instead. - * See https://github.com/paralleldrive/cuid. - */ -// @__NO_SIDE_EFFECTS__ -function _cuid(Class, params) { - return new Class({ - type: "string", - format: "cuid", - check: "string_format", - abort: false, - ...normalizeParams(params), - }); -} -// @__NO_SIDE_EFFECTS__ -function _cuid2(Class, params) { - return new Class({ - type: "string", - format: "cuid2", - check: "string_format", - abort: false, - ...normalizeParams(params), - }); -} -// @__NO_SIDE_EFFECTS__ -function _ulid(Class, params) { - return new Class({ - type: "string", - format: "ulid", - check: "string_format", - abort: false, - ...normalizeParams(params), - }); -} -// @__NO_SIDE_EFFECTS__ -function _xid(Class, params) { - return new Class({ - type: "string", - format: "xid", - check: "string_format", - abort: false, - ...normalizeParams(params), - }); -} -// @__NO_SIDE_EFFECTS__ -function _ksuid(Class, params) { - return new Class({ - type: "string", - format: "ksuid", - check: "string_format", - abort: false, - ...normalizeParams(params), - }); -} -// @__NO_SIDE_EFFECTS__ -function _ipv4(Class, params) { - return new Class({ - type: "string", - format: "ipv4", - check: "string_format", - abort: false, - ...normalizeParams(params), - }); -} -// @__NO_SIDE_EFFECTS__ -function _ipv6(Class, params) { - return new Class({ - type: "string", - format: "ipv6", - check: "string_format", - abort: false, - ...normalizeParams(params), - }); -} -// @__NO_SIDE_EFFECTS__ -function _mac(Class, params) { - return new Class({ - type: "string", - format: "mac", - check: "string_format", - abort: false, - ...util.normalizeParams(params), - }); -} -// @__NO_SIDE_EFFECTS__ -function _cidrv4(Class, params) { - return new Class({ - type: "string", - format: "cidrv4", - check: "string_format", - abort: false, - ...normalizeParams(params), - }); -} -// @__NO_SIDE_EFFECTS__ -function _cidrv6(Class, params) { - return new Class({ - type: "string", - format: "cidrv6", - check: "string_format", - abort: false, - ...normalizeParams(params), - }); -} -// @__NO_SIDE_EFFECTS__ -function _base64(Class, params) { - return new Class({ - type: "string", - format: "base64", - check: "string_format", - abort: false, - ...normalizeParams(params), - }); -} -// @__NO_SIDE_EFFECTS__ -function _base64url(Class, params) { - return new Class({ - type: "string", - format: "base64url", - check: "string_format", - abort: false, - ...normalizeParams(params), - }); -} -// @__NO_SIDE_EFFECTS__ -function _e164(Class, params) { - return new Class({ - type: "string", - format: "e164", - check: "string_format", - abort: false, - ...normalizeParams(params), - }); -} -// @__NO_SIDE_EFFECTS__ -function _creditCard(Class, params) { - return new Class({ - type: "string", - format: "credit_card", - check: "string_format", - abort: false, - ...util.normalizeParams(params), - }); -} -// @__NO_SIDE_EFFECTS__ -function _jwt(Class, params) { - return new Class({ - type: "string", - format: "jwt", - check: "string_format", - abort: false, - ...normalizeParams(params), - }); -} -const TimePrecision = (/* unused pure expression or super */ null && ({ - Any: null, - Minute: -1, - Second: 0, - Millisecond: 3, - Microsecond: 6, -})); -// @__NO_SIDE_EFFECTS__ -function _isoDateTime(Class, params) { - return new Class({ - type: "string", - format: "datetime", - check: "string_format", - offset: false, - local: false, - precision: null, - ...normalizeParams(params), - }); -} -// @__NO_SIDE_EFFECTS__ -function _isoDate(Class, params) { - return new Class({ - type: "string", - format: "date", - check: "string_format", - ...normalizeParams(params), - }); -} -// @__NO_SIDE_EFFECTS__ -function _isoTime(Class, params) { - return new Class({ - type: "string", - format: "time", - check: "string_format", - precision: null, - ...normalizeParams(params), - }); -} -// @__NO_SIDE_EFFECTS__ -function _isoDuration(Class, params) { - return new Class({ - type: "string", - format: "duration", - check: "string_format", - ...normalizeParams(params), - }); -} -// @__NO_SIDE_EFFECTS__ -function _number(Class, params) { - return new Class({ - type: "number", - checks: [], - ...normalizeParams(params), - }); -} -// @__NO_SIDE_EFFECTS__ -function _coercedNumber(Class, params) { - return new Class({ - type: "number", - coerce: true, - checks: [], - ...normalizeParams(params), - }); -} -// @__NO_SIDE_EFFECTS__ -function _int(Class, params) { - return new Class({ - type: "number", - check: "number_format", - abort: false, - format: "safeint", - ...normalizeParams(params), - }); -} -// @__NO_SIDE_EFFECTS__ -function _float32(Class, params) { - return new Class({ - type: "number", - check: "number_format", - abort: false, - format: "float32", - ...util.normalizeParams(params), - }); -} -// @__NO_SIDE_EFFECTS__ -function _float64(Class, params) { - return new Class({ - type: "number", - check: "number_format", - abort: false, - format: "float64", - ...util.normalizeParams(params), - }); -} -// @__NO_SIDE_EFFECTS__ -function _int32(Class, params) { - return new Class({ - type: "number", - check: "number_format", - abort: false, - format: "int32", - ...util.normalizeParams(params), - }); -} -// @__NO_SIDE_EFFECTS__ -function _uint32(Class, params) { - return new Class({ - type: "number", - check: "number_format", - abort: false, - format: "uint32", - ...util.normalizeParams(params), - }); -} -// @__NO_SIDE_EFFECTS__ -function _boolean(Class, params) { - return new Class({ - type: "boolean", - ...normalizeParams(params), - }); -} -// @__NO_SIDE_EFFECTS__ -function _coercedBoolean(Class, params) { - return new Class({ - type: "boolean", - coerce: true, - ...util.normalizeParams(params), - }); -} -// @__NO_SIDE_EFFECTS__ -function _bigint(Class, params) { - return new Class({ - type: "bigint", - ...util.normalizeParams(params), - }); -} -// @__NO_SIDE_EFFECTS__ -function _coercedBigint(Class, params) { - return new Class({ - type: "bigint", - coerce: true, - ...util.normalizeParams(params), - }); -} -// @__NO_SIDE_EFFECTS__ -function _int64(Class, params) { - return new Class({ - type: "bigint", - check: "bigint_format", - abort: false, - format: "int64", - ...util.normalizeParams(params), - }); -} -// @__NO_SIDE_EFFECTS__ -function _uint64(Class, params) { - return new Class({ - type: "bigint", - check: "bigint_format", - abort: false, - format: "uint64", - ...util.normalizeParams(params), - }); -} -// @__NO_SIDE_EFFECTS__ -function _symbol(Class, params) { - return new Class({ - type: "symbol", - ...util.normalizeParams(params), - }); -} -// @__NO_SIDE_EFFECTS__ -function api_undefined(Class, params) { - return new Class({ - type: "undefined", - ...util.normalizeParams(params), - }); -} -// @__NO_SIDE_EFFECTS__ -function api_null(Class, params) { - return new Class({ - type: "null", - ...normalizeParams(params), - }); -} -// @__NO_SIDE_EFFECTS__ -function _any(Class) { - return new Class({ - type: "any", - }); -} -// @__NO_SIDE_EFFECTS__ -function _unknown(Class) { - return new Class({ - type: "unknown", - }); -} -// @__NO_SIDE_EFFECTS__ -function _never(Class, params) { - return new Class({ - type: "never", - ...normalizeParams(params), - }); -} -// @__NO_SIDE_EFFECTS__ -function _void(Class, params) { - return new Class({ - type: "void", - ...util.normalizeParams(params), - }); -} -// @__NO_SIDE_EFFECTS__ -function _date(Class, params) { - return new Class({ - type: "date", - ...util.normalizeParams(params), - }); -} -// @__NO_SIDE_EFFECTS__ -function _coercedDate(Class, params) { - return new Class({ - type: "date", - coerce: true, - ...util.normalizeParams(params), - }); -} -// @__NO_SIDE_EFFECTS__ -function _nan(Class, params) { - return new Class({ - type: "nan", - ...util.normalizeParams(params), - }); -} -// @__NO_SIDE_EFFECTS__ -function _lt(value, params) { - return new $ZodCheckLessThan({ - check: "less_than", - ...normalizeParams(params), - value, - inclusive: false, - }); -} -// @__NO_SIDE_EFFECTS__ -function _lte(value, params) { - return new $ZodCheckLessThan({ - check: "less_than", - ...normalizeParams(params), - value, - inclusive: true, - }); -} - -// @__NO_SIDE_EFFECTS__ -function _gt(value, params) { - return new $ZodCheckGreaterThan({ - check: "greater_than", - ...normalizeParams(params), - value, - inclusive: false, - }); -} -// @__NO_SIDE_EFFECTS__ -function _gte(value, params) { - return new $ZodCheckGreaterThan({ - check: "greater_than", - ...normalizeParams(params), - value, - inclusive: true, - }); -} - -// @__NO_SIDE_EFFECTS__ -function _positive(params) { - return _gt(0, params); -} -// negative -// @__NO_SIDE_EFFECTS__ -function _negative(params) { - return _lt(0, params); -} -// nonpositive -// @__NO_SIDE_EFFECTS__ -function _nonpositive(params) { - return _lte(0, params); -} -// nonnegative -// @__NO_SIDE_EFFECTS__ -function _nonnegative(params) { - return _gte(0, params); -} -// @__NO_SIDE_EFFECTS__ -function _multipleOf(value, params) { - return new $ZodCheckMultipleOf({ - check: "multiple_of", - ...normalizeParams(params), - value, - }); -} -// @__NO_SIDE_EFFECTS__ -function _maxSize(maximum, params) { - return new checks.$ZodCheckMaxSize({ - check: "max_size", - ...util.normalizeParams(params), - maximum, - }); -} -// @__NO_SIDE_EFFECTS__ -function _minSize(minimum, params) { - return new checks.$ZodCheckMinSize({ - check: "min_size", - ...util.normalizeParams(params), - minimum, - }); -} -// @__NO_SIDE_EFFECTS__ -function _size(size, params) { - return new checks.$ZodCheckSizeEquals({ - check: "size_equals", - ...util.normalizeParams(params), - size, - }); -} -// @__NO_SIDE_EFFECTS__ -function _maxLength(maximum, params) { - const ch = new $ZodCheckMaxLength({ - check: "max_length", - ...normalizeParams(params), - maximum, - }); - return ch; -} -// @__NO_SIDE_EFFECTS__ -function _minLength(minimum, params) { - return new $ZodCheckMinLength({ - check: "min_length", - ...normalizeParams(params), - minimum, - }); -} -// @__NO_SIDE_EFFECTS__ -function _length(length, params) { - return new $ZodCheckLengthEquals({ - check: "length_equals", - ...normalizeParams(params), - length, - }); -} -// @__NO_SIDE_EFFECTS__ -function _regex(pattern, params) { - return new $ZodCheckRegex({ - check: "string_format", - format: "regex", - ...normalizeParams(params), - pattern, - }); -} -// @__NO_SIDE_EFFECTS__ -function _lowercase(params) { - return new $ZodCheckLowerCase({ - check: "string_format", - format: "lowercase", - ...normalizeParams(params), - }); -} -// @__NO_SIDE_EFFECTS__ -function _uppercase(params) { - return new $ZodCheckUpperCase({ - check: "string_format", - format: "uppercase", - ...normalizeParams(params), - }); -} -// @__NO_SIDE_EFFECTS__ -function _includes(includes, params) { - return new $ZodCheckIncludes({ - check: "string_format", - format: "includes", - ...normalizeParams(params), - includes, - }); -} -// @__NO_SIDE_EFFECTS__ -function _startsWith(prefix, params) { - return new $ZodCheckStartsWith({ - check: "string_format", - format: "starts_with", - ...normalizeParams(params), - prefix, - }); -} -// @__NO_SIDE_EFFECTS__ -function _endsWith(suffix, params) { - return new $ZodCheckEndsWith({ - check: "string_format", - format: "ends_with", - ...normalizeParams(params), - suffix, - }); -} -// @__NO_SIDE_EFFECTS__ -function _property(property, schema, params) { - return new checks.$ZodCheckProperty({ - check: "property", - property, - schema, - ...util.normalizeParams(params), - }); -} -// @__NO_SIDE_EFFECTS__ -function _properties(shape) { - return Object.entries(shape).map(([property, schema]) => new checks.$ZodCheckProperty({ check: "property", property, schema })); -} -// @__NO_SIDE_EFFECTS__ -function _mime(types, params) { - return new checks.$ZodCheckMimeType({ - check: "mime_type", - mime: types, - ...util.normalizeParams(params), - }); -} -// @__NO_SIDE_EFFECTS__ -function _overwrite(tx) { - return new $ZodCheckOverwrite({ - check: "overwrite", - tx, - }); -} -// normalize -// @__NO_SIDE_EFFECTS__ -function _normalize(form) { - return _overwrite((input) => input.normalize(form)); -} -// trim -// @__NO_SIDE_EFFECTS__ -function _trim() { - return _overwrite((input) => input.trim()); -} -// toLowerCase -// @__NO_SIDE_EFFECTS__ -function _toLowerCase() { - return _overwrite((input) => input.toLowerCase()); -} -// toUpperCase -// @__NO_SIDE_EFFECTS__ -function _toUpperCase() { - return _overwrite((input) => input.toUpperCase()); -} -// slugify -// @__NO_SIDE_EFFECTS__ -function _slugify() { - return _overwrite((input) => slugify(input)); -} -// @__NO_SIDE_EFFECTS__ -function _array(Class, element, params) { - return new Class({ - type: "array", - element, - // get element() { - // return element; - // }, - ...normalizeParams(params), - }); -} -// @__NO_SIDE_EFFECTS__ -function _union(Class, options, params) { - return new Class({ - type: "union", - options, - ...util.normalizeParams(params), - }); -} -function _xor(Class, options, params) { - return new Class({ - type: "union", - options, - inclusive: false, - ...util.normalizeParams(params), - }); -} -// @__NO_SIDE_EFFECTS__ -function _discriminatedUnion(Class, discriminator, options, params) { - return new Class({ - type: "union", - options: options, - discriminator, - ...util.normalizeParams(params), - }); -} -// @__NO_SIDE_EFFECTS__ -function _intersection(Class, left, right) { - return new Class({ - type: "intersection", - left, - right, - }); -} -// export function _tuple( -// Class: util.SchemaClass, -// items: [], -// params?: string | $ZodTupleParams -// ): schemas.$ZodTuple<[], null>; -// @__NO_SIDE_EFFECTS__ -function _tuple(Class, items, _paramsOrRest, _params) { - const hasRest = _paramsOrRest instanceof schemas.$ZodType; - const params = hasRest ? _params : _paramsOrRest; - const rest = hasRest ? _paramsOrRest : null; - return new Class({ - type: "tuple", - items, - rest, - ...util.normalizeParams(params), - }); -} -// @__NO_SIDE_EFFECTS__ -function _record(Class, keyType, valueType, params) { - return new Class({ - type: "record", - keyType, - valueType, - ...util.normalizeParams(params), - }); -} -// @__NO_SIDE_EFFECTS__ -function _map(Class, keyType, valueType, params) { - return new Class({ - type: "map", - keyType, - valueType, - ...util.normalizeParams(params), - }); -} -// @__NO_SIDE_EFFECTS__ -function _set(Class, valueType, params) { - return new Class({ - type: "set", - valueType, - ...util.normalizeParams(params), - }); -} -// @__NO_SIDE_EFFECTS__ -function _enum(Class, values, params) { - const entries = Array.isArray(values) ? Object.fromEntries(values.map((v) => [v, v])) : values; - // if (Array.isArray(values)) { - // for (const value of values) { - // entries[value] = value; - // } - // } else { - // Object.assign(entries, values); - // } - // const entries: util.EnumLike = {}; - // for (const val of values) { - // entries[val] = val; - // } - return new Class({ - type: "enum", - entries, - ...util.normalizeParams(params), - }); -} -// @__NO_SIDE_EFFECTS__ -/** @deprecated This API has been merged into `z.enum()`. Use `z.enum()` instead. - * - * ```ts - * enum Colors { red, green, blue } - * z.enum(Colors); - * ``` - */ -function _nativeEnum(Class, entries, params) { - return new Class({ - type: "enum", - entries, - ...util.normalizeParams(params), - }); -} -// @__NO_SIDE_EFFECTS__ -function _literal(Class, value, params) { - return new Class({ - type: "literal", - values: Array.isArray(value) ? value : [value], - ...util.normalizeParams(params), - }); -} -// @__NO_SIDE_EFFECTS__ -function _file(Class, params) { - return new Class({ - type: "file", - ...util.normalizeParams(params), - }); -} -// @__NO_SIDE_EFFECTS__ -function _transform(Class, fn) { - return new Class({ - type: "transform", - transform: fn, - }); -} -// @__NO_SIDE_EFFECTS__ -function _optional(Class, innerType) { - return new Class({ - type: "optional", - innerType, - }); -} -// @__NO_SIDE_EFFECTS__ -function _nullable(Class, innerType) { - return new Class({ - type: "nullable", - innerType, - }); -} -// @__NO_SIDE_EFFECTS__ -function _default(Class, innerType, defaultValue) { - return new Class({ - type: "default", - innerType, - get defaultValue() { - return typeof defaultValue === "function" ? defaultValue() : util.shallowClone(defaultValue); - }, - }); -} -// @__NO_SIDE_EFFECTS__ -function _nonoptional(Class, innerType, params) { - return new Class({ - type: "nonoptional", - innerType, - ...util.normalizeParams(params), - }); -} -// @__NO_SIDE_EFFECTS__ -function _success(Class, innerType) { - return new Class({ - type: "success", - innerType, - }); -} -// @__NO_SIDE_EFFECTS__ -function _catch(Class, innerType, catchValue) { - return new Class({ - type: "catch", - innerType, - catchValue: (typeof catchValue === "function" ? catchValue : util.constantCatch(catchValue)), - }); -} -// @__NO_SIDE_EFFECTS__ -function _pipe(Class, in_, out) { - return new Class({ - type: "pipe", - in: in_, - out, - }); -} -// @__NO_SIDE_EFFECTS__ -function _readonly(Class, innerType) { - return new Class({ - type: "readonly", - innerType, - }); -} -// @__NO_SIDE_EFFECTS__ -function _templateLiteral(Class, parts, params) { - return new Class({ - type: "template_literal", - parts, - ...util.normalizeParams(params), - }); -} -// @__NO_SIDE_EFFECTS__ -function _lazy(Class, getter) { - return new Class({ - type: "lazy", - getter, - }); -} -// @__NO_SIDE_EFFECTS__ -function _promise(Class, innerType) { - return new Class({ - type: "promise", - innerType, - }); -} -// @__NO_SIDE_EFFECTS__ -function _custom(Class, fn, _params) { - const norm = util.normalizeParams(_params); - norm.abort ?? (norm.abort = true); // default to abort:false - const schema = new Class({ - type: "custom", - check: "custom", - fn: fn, - ...norm, - }); - return schema; -} -// same as _custom but defaults to abort:false -// @__NO_SIDE_EFFECTS__ -function _refine(Class, fn, _params) { - const schema = new Class({ - type: "custom", - check: "custom", - fn: fn, - ...normalizeParams(_params), - }); - return schema; -} -// @__NO_SIDE_EFFECTS__ -function _superRefine(fn, params) { - const ch = _check((payload) => { - payload.addIssue = (issue) => { - if (typeof issue === "string") { - payload.issues.push(util_issue(issue, payload.value, ch._zod.def)); - } - else { - // for Zod 3 backwards compatibility - const _issue = issue; - if (_issue.fatal) - _issue.continue = false; - _issue.code ?? (_issue.code = "custom"); - if (!("input" in _issue)) - _issue.input = payload.value; - _issue.inst ?? (_issue.inst = ch); - _issue.continue ?? (_issue.continue = !ch._zod.def.abort); // abort is always undefined, so this is always true... - payload.issues.push(util_issue(_issue)); - } - }; - return fn(payload.value, payload); - }, params); - return ch; -} -// @__NO_SIDE_EFFECTS__ -function _check(fn, params) { - const ch = new $ZodCheck({ - check: "custom", - ...normalizeParams(params), - }); - ch._zod.check = fn; - return ch; -} -// @__NO_SIDE_EFFECTS__ -function describe(description) { - const ch = new $ZodCheck({ check: "describe" }); - ch._zod.onattach = [ - (inst) => { - const existing = globalRegistry.get(inst) ?? {}; - globalRegistry.add(inst, { ...existing, description }); - }, - ]; - ch._zod.check = () => { }; // no-op check - return ch; -} -// @__NO_SIDE_EFFECTS__ -function api_meta(metadata) { - const ch = new $ZodCheck({ check: "meta" }); - ch._zod.onattach = [ - (inst) => { - const existing = globalRegistry.get(inst) ?? {}; - globalRegistry.add(inst, { ...existing, ...metadata }); - }, - ]; - ch._zod.check = () => { }; // no-op check - return ch; -} -// @__NO_SIDE_EFFECTS__ -function _stringbool(Classes, _params) { - const params = util.normalizeParams(_params); - let truthyArray = params.truthy ?? ["true", "1", "yes", "on", "y", "enabled"]; - let falsyArray = params.falsy ?? ["false", "0", "no", "off", "n", "disabled"]; - if (params.case !== "sensitive") { - truthyArray = truthyArray.map((v) => (typeof v === "string" ? v.toLowerCase() : v)); - falsyArray = falsyArray.map((v) => (typeof v === "string" ? v.toLowerCase() : v)); - } - const truthySet = new Set(truthyArray); - const falsySet = new Set(falsyArray); - const _Codec = Classes.Codec ?? schemas.$ZodCodec; - const _Boolean = Classes.Boolean ?? schemas.$ZodBoolean; - const _String = Classes.String ?? schemas.$ZodString; - const stringSchema = new _String({ type: "string", error: params.error }); - const booleanSchema = new _Boolean({ type: "boolean", error: params.error }); - const codec = new _Codec({ - type: "pipe", - in: stringSchema, - out: booleanSchema, - transform: ((input, payload) => { - let data = input; - if (params.case !== "sensitive") - data = data.toLowerCase(); - if (truthySet.has(data)) { - return true; - } - else if (falsySet.has(data)) { - return false; - } - else { - payload.issues.push({ - code: "invalid_value", - expected: "stringbool", - values: [...truthySet, ...falsySet], - input: payload.value, - inst: codec, - continue: false, - }); - return {}; - } - }), - reverseTransform: ((input, _payload) => { - if (input === true) { - return truthyArray[0] || "true"; - } - else { - return falsyArray[0] || "false"; - } - }), - error: params.error, - }); - codec._zod.bag.truthy = truthyArray; - codec._zod.bag.falsy = falsyArray; - codec._zod.bag.case = params.case ?? "insensitive"; - return codec; -} -// @__NO_SIDE_EFFECTS__ -function _stringFormat(Class, format, fnOrRegex, _params = {}) { - const params = util.normalizeParams(_params); - const def = { - check: "string_format", - type: "string", - format, - fn: typeof fnOrRegex === "function" ? fnOrRegex : (val) => fnOrRegex.test(val), - ...params, - }; - if (fnOrRegex instanceof RegExp) { - def.pattern = fnOrRegex; - } - const inst = new Class(def); - return inst; -} - - - -function assignProps(target, ...sources) { - for (const source of sources) { - for (const key of Reflect.ownKeys(source)) { - if (Object.prototype.propertyIsEnumerable.call(source, key)) { - assignProp(target, key, source[key]); - } - } - } - return target; -} -// function initializeContext(inputs: JSONSchemaGeneratorParams): ToJSONSchemaContext { -// return { -// processor: inputs.processor, -// metadataRegistry: inputs.metadata ?? globalRegistry, -// target: inputs.target ?? "draft-2020-12", -// unrepresentable: inputs.unrepresentable ?? "throw", -// }; -// } -function initializeContext(params) { - // Normalize target: convert old non-hyphenated versions to hyphenated versions - let target = params?.target ?? "draft-2020-12"; - if (target === "draft-4") - target = "draft-04"; - if (target === "draft-7") - target = "draft-07"; - return { - processors: params.processors ?? {}, - metadataRegistry: params?.metadata ?? globalRegistry, - target, - unrepresentable: params?.unrepresentable ?? "throw", - override: params?.override ?? (() => { }), - io: params?.io ?? "output", - counter: 0, - seen: new Map(), - sharedDefsExtractedFor: undefined, - sharedEmitDoneFor: undefined, - cycles: params?.cycles ?? "ref", - reused: params?.reused ?? "inline", - intersections: [], - deferred: [], - external: params?.external ?? undefined, - }; -} -/** - * Applies the `unrepresentable` setting at a site that has no JSON Schema equivalent. Throws - * `message` unless the setting (or the handler's return value) says otherwise. Returns `true` if a - * custom JSON Schema was written into `json`, in which case the caller must not write its own. - */ -function handleUnrepresentable(schema, ctx, json, params, message) { - const result = typeof ctx.unrepresentable === "function" - ? ctx.unrepresentable({ zodSchema: schema, path: params.path, message }) - : ctx.unrepresentable; - if (result === "any") - return false; - if (result === undefined || result === "throw") - throw new Error(message); - Object.assign(json, result); - return true; -} -function to_json_schema_process(schema, ctx, _params = { path: [], schemaPath: [] }) { - var _a; - const def = schema._zod.def; - // check for schema in seens - const seen = ctx.seen.get(schema); - if (seen) { - seen.count++; - // check if cycle - const isCycle = _params.schemaPath.includes(schema); - if (isCycle) { - seen.cycle = _params.path; - } - return seen.schema; - } - // initialize - const result = { schema: {}, count: 1, cycle: undefined, path: _params.path }; - ctx.seen.set(schema, result); - ctx.sharedDefsExtractedFor = undefined; - ctx.sharedEmitDoneFor = undefined; - // custom method overrides default behavior - const overrideSchema = schema._zod.toJSONSchema?.(); - if (overrideSchema) { - result.schema = overrideSchema; - } - else { - const params = { - ..._params, - schemaPath: [..._params.schemaPath, schema], - path: _params.path, - }; - if (schema._zod.processJSONSchema) { - schema._zod.processJSONSchema(ctx, result.schema, params); - } - else { - const _json = result.schema; - const processor = ctx.processors[def.type]; - if (!processor) { - throw new Error(`[toJSONSchema]: Non-representable type encountered: ${def.type}`); - } - processor(schema, ctx, _json, params); - } - const parent = schema._zod.parent; - if (parent) { - // Also set ref if processor didn't (for inheritance) - if (!result.ref) - result.ref = parent; - to_json_schema_process(parent, ctx, params); - ctx.seen.get(parent).isParent = true; - } - } - // metadata - const meta = ctx.metadataRegistry.get(schema); - if (meta) - assignProps(result.schema, meta); - if (ctx.io === "input" && isTransforming(schema)) { - // examples/defaults only apply to output type of pipe - delete result.schema.examples; - delete result.schema.default; - } - // set prefault as default - if (ctx.io === "input" && "_prefault" in result.schema) - (_a = result.schema).default ?? (_a.default = result.schema._prefault); - delete result.schema._prefault; - // pulling fresh from ctx.seen in case it was overwritten - const _result = ctx.seen.get(schema); - return _result.schema; -} -// Escape a reference token for use in a JSON Pointer fragment (RFC 6901): `~` becomes `~0` and `/` becomes `~1`. The `~` replacement must run first. -function encodeJSONPointerSegment(segment) { - return segment.replace(/~/g, "~0").replace(/\//g, "~1"); -} -function extractDefs(ctx, schema -// params: EmitParams -) { - // iterate over seen map; - const root = ctx.seen.get(schema); - if (!root) - throw new Error("Unprocessed schema. This is a bug in Zod."); - // With `external` set, every registered schema resolves through the external branch of `makeURI`, so the root branch below produces the same ref the external branch would — this pass is identical whichever schema it is called with, and only needs to run once. - if (ctx.external && ctx.sharedDefsExtractedFor === ctx.external) - return; - // Track ids to detect duplicates across different schemas - const idToSchema = new Map(); - for (const entry of ctx.seen.entries()) { - const id = ctx.metadataRegistry.get(entry[0])?.id; - if (id) { - const existing = idToSchema.get(id); - if (existing && existing !== entry[0]) { - throw new Error(`Duplicate schema id "${id}" detected during JSON Schema conversion. Two different schemas cannot share the same id when converted together.`); - } - idToSchema.set(id, entry[0]); - } - } - // returns a ref to the schema defId will be empty if the ref points to an external schema (or #) - const makeURI = (entry) => { - // comparing the seen objects because sometimes multiple schemas map to the same seen object. e.g. lazy - // external is configured - const defsSegment = ctx.target === "draft-2020-12" ? "$defs" : "definitions"; - if (ctx.external) { - const externalId = ctx.external.registry.get(entry[0])?.id; // ?? "__shared";// `__schema${ctx.counter++}`; - // check if schema is in the external registry - const uriGenerator = ctx.external.uri ?? ((id) => id); - if (externalId) { - return { ref: uriGenerator(externalId) }; - } - // otherwise, add to __shared - const id = entry[1].defId ?? entry[1].schema.id ?? `schema${ctx.counter++}`; - entry[1].defId = id; // set defId so it will be reused if needed - return { defId: id, ref: `${uriGenerator("__shared")}#/${defsSegment}/${encodeJSONPointerSegment(id)}` }; - } - const uriPrefix = `#`; - const defUriPrefix = `${uriPrefix}/${defsSegment}/`; - // an id-less root has nowhere to be extracted to, so it stays inline and self-references as `#` - if (entry[1] === root && !entry[1].schema.id) { - return { ref: uriPrefix }; - } - // self-contained schema - const defId = entry[1].schema.id ?? `__schema${ctx.counter++}`; - return { defId, ref: defUriPrefix + encodeJSONPointerSegment(defId) }; - }; - // stored cached version in `def` property remove all properties, set $ref - const extractToDef = (entry) => { - // if the schema is already a reference, do not extract it - if (entry[1].schema.$ref) { - return; - } - const seen = entry[1]; - const { ref, defId } = makeURI(entry); - seen.def = { ...seen.schema }; - // defId won't be set if the schema is a reference to an external schema or if the schema is the root schema - if (defId) - seen.defId = defId; - // wipe away all properties except $ref - const schema = seen.schema; - for (const key in schema) { - delete schema[key]; - } - schema.$ref = ref; - }; - // throw on cycles - // break cycles - if (ctx.cycles === "throw") { - for (const entry of ctx.seen.entries()) { - const seen = entry[1]; - if (seen.cycle) { - throw new Error("Cycle detected: " + - `#/${seen.cycle?.join("/")}/` + - '\n\nSet the `cycles` parameter to `"ref"` to resolve cyclical schemas with defs.'); - } - } - } - // extract schemas into $defs - for (const entry of ctx.seen.entries()) { - const seen = entry[1]; - // convert root schema to # $ref - if (schema === entry[0]) { - extractToDef(entry); // this has special handling for the root schema - continue; - } - // extract schemas that are in the external registry - if (ctx.external) { - const ext = ctx.external.registry.get(entry[0])?.id; - if (schema !== entry[0] && ext) { - extractToDef(entry); - continue; - } - } - // extract schemas with `id` meta - const id = ctx.metadataRegistry.get(entry[0])?.id; - if (id) { - extractToDef(entry); - continue; - } - // break cycles - if (seen.cycle) { - // any - extractToDef(entry); - continue; - } - // extract reused schemas - if (seen.count > 1) { - if (ctx.reused === "ref") { - extractToDef(entry); - // biome-ignore lint: - continue; - } - } - } - if (ctx.external) - ctx.sharedDefsExtractedFor = ctx.external; -} -/** Rewrites `anyOf: [{type: "a"}, {type: "b"}]` to `type: ["a", "b"]`, which every JSON Schema draft treats as equivalent and most consumers render far better for the nullable case. Only branches that are a bare type assertion qualify — anything carrying a constraint, `$ref`, `const` or metadata is left alone. Runs after `flattenRef`, so a branch an override decorated or `$defs` extraction turned into a `$ref` is no longer bare and correctly stays in `anyOf`. `oneOf` is excluded: `integer` and `number` overlap, so "exactly one" and "at least one" are not the same there. OpenAPI 3.0 is excluded: its `type` must be a single string. */ -function compactTypeUnion(schema) { - const options = schema.anyOf; - if (!Array.isArray(options) || options.length === 0 || schema.type !== undefined) - return; - const types = []; - for (const option of options) { - if (!option || typeof option !== "object") - return; - // A branch that is itself a compactible union folds into this one — nested `anyOf` and a flat `type` array say the same thing. Compacting it first also makes the result independent of the order this pass walks the seen map in. - compactTypeUnion(option); - const keys = Object.keys(option); - if (keys.length !== 1 || keys[0] !== "type") - return; - const type = option.type; - for (const member of Array.isArray(type) ? type : [type]) { - if (typeof member !== "string") - return; - if (!types.includes(member)) - types.push(member); - } - } - delete schema.anyOf; - // A `type` array must be non-empty and unique (metaschema); a single member is spelled as a bare string. - schema.type = types.length === 1 ? types[0] : types; -} -/** Keywords `foldIntersection` knows how to combine. Anything else — `$ref`, `patternProperties`, - * an annotation like `description` — makes a member unfoldable, so a constraint this does not - * understand leaves the `allOf` alone instead of being silently dropped or misattributed. */ -const FOLDABLE_KEYS = new Set(["type", "properties", "required", "additionalProperties"]); -const UNION_KEYS = ["oneOf", "anyOf"]; -/** A member's constraint on a key it does not declare itself. A `catchall` states one; `false`, an absent `additionalProperties`, and the empty schema a loose object emits state nothing. */ -function undeclaredConstraint(member) { - const extra = member.additionalProperties; - if (extra === undefined || extra === false || typeof extra !== "object" || extra === null) - return null; - return Object.keys(extra).length ? extra : null; -} -/** Combines object members into the single object they describe together, or returns `null` if any of them carries a keyword outside {@link FOLDABLE_KEYS}. */ -function foldObjects(members) { - const objects = []; - for (const member of members) { - // A boolean subschema is legal JSON Schema and carries no keywords to fold. - if (typeof member !== "object" || member.type !== "object") - return null; - for (const key in member) { - if (!FOLDABLE_KEYS.has(key)) - return null; - } - objects.push(member); - } - const properties = {}; - const required = new Set(); - for (const object of objects) { - for (const key in object.properties) { - // `in` would report a `__proto__` key as already present via the prototype chain and skip it. - if (Object.prototype.hasOwnProperty.call(properties, key)) - continue; - // Every member constrains this key: the ones that declare it say how, and a `catchall` member constrains it too even though it does not name it. The key has to satisfy all of them, which is the same intersection one level down. - const parts = []; - for (const other of objects) { - const part = other.properties?.[key] ?? undeclaredConstraint(other); - if (part === null || part === undefined) - continue; - if (!parts.some((seen) => JSON.stringify(seen) === JSON.stringify(part))) - parts.push(part); - } - const merged = parts.length === 1 - ? parts[0] - : (foldObjects(parts) ?? { allOf: parts }); - assignProp(properties, key, merged); - } - for (const key of object.required ?? []) - required.add(key); - } - const folded = { type: "object", properties }; - if (required.size) - folded.required = [...required]; - // A key no member declares is rejected only when every member rejects it, so the fold is closed only when every member is. Otherwise it carries whatever the `catchall` members demand of such a key. - if (objects.every((object) => object.additionalProperties === false)) { - folded.additionalProperties = false; - } - else { - const constraints = []; - for (const object of objects) { - const constraint = undeclaredConstraint(object); - if (constraint && !constraints.some((seen) => JSON.stringify(seen) === JSON.stringify(constraint))) - constraints.push(constraint); - } - if (constraints.length === 1) - folded.additionalProperties = constraints[0]; - else if (constraints.length > 1) - folded.additionalProperties = { allOf: constraints }; - } - return folded; -} -/** `additionalProperties` in an `allOf` member sees only that member's own `properties`, so two - * closed object members reject each other's keys and the schema validates nothing. Zod's parser - * pools the key sets instead — `handleIntersectionResults` reports a key as unrecognized only when - * *every* side rejects it — so the emitted schema has to pool them too, and folding the members - * into one object is the encoding that says so on every target. - * - * This runs from `finalize`, after `extractDefs`, which is what keeps it clear of the `$ref` - * machinery: a member extracted into `$defs` is already a `$ref` by now and declines to fold, so it - * keeps its reference and its own closedness rather than being inlined as a stale copy. */ -function foldIntersection(json) { - const allOf = json.allOf; - if (!Array.isArray(allOf) || allOf.length < 2) - return; - // An `override` runs before this pass and may have written object keywords onto the intersection itself. Those are deliberate, so decline rather than overwrite them. - for (const key of FOLDABLE_KEYS) - if (key in json) - return; - // An intersection distributes over a union: `A & (X | Y)` is `(A & X) | (A & Y)`. Only the first union is distributed over; a second one stays among the members every branch folds against, where it fails the object check and declines the whole intersection rather than multiplying out. - const unions = allOf.filter((m) => UNION_KEYS.some((k) => Array.isArray(m[k]))); - let folded = null; - if (!unions.length) { - folded = foldObjects(allOf); - } - else { - const union = unions[0]; - const keyword = UNION_KEYS.find((k) => Array.isArray(union[k])); - if (Object.keys(union).length !== 1) - return; - const rest = allOf.filter((m) => m !== union); - const branches = union[keyword].map((branch) => foldObjects([...rest, branch])); - if (branches.some((b) => !b)) - return; - folded = { [keyword]: branches }; - } - if (!folded) - return; - delete json.allOf; - assignProps(json, folded); -} -function finalize(ctx, schema) { - const root = ctx.seen.get(schema); - if (!root) - throw new Error("Unprocessed schema. This is a bug in Zod."); - // flatten refs - inherit properties from parent schemas - const flattenRef = (zodSchema) => { - const seen = ctx.seen.get(zodSchema); - // already processed - if (seen.ref === null) - return; - const schema = seen.def ?? seen.schema; - const _cached = { ...schema }; - const ref = seen.ref; - seen.ref = null; // prevent infinite recursion - if (ref) { - flattenRef(ref); - const refSeen = ctx.seen.get(ref); - const refSchema = refSeen.schema; - // merge referenced schema into current - if (refSchema.$ref && (ctx.target === "draft-07" || ctx.target === "draft-04" || ctx.target === "openapi-3.0")) { - // older drafts can't combine $ref with other properties - schema.allOf = schema.allOf ?? []; - schema.allOf.push(refSchema); - } - else { - assignProps(schema, refSchema); - } - // restore child's own properties (child wins) - assignProps(schema, _cached); - const isParentRef = zodSchema._zod.parent === ref; - // For parent chain, child is a refinement - remove parent-only properties - if (isParentRef) { - for (const key in schema) { - if (key === "$ref" || key === "allOf") - continue; - if (!(key in _cached)) { - delete schema[key]; - } - } - } - // When ref was extracted to $defs, remove properties that match the definition - if (refSchema.$ref && refSeen.def) { - for (const key in schema) { - if (key === "$ref" || key === "allOf") - continue; - if (key in refSeen.def && JSON.stringify(schema[key]) === JSON.stringify(refSeen.def[key])) { - delete schema[key]; - } - } - } - } - // If parent was extracted (has $ref), propagate $ref to this schema. This handles cases like: readonly().meta({id}).describe() where processor sets ref to innerType but parent should be referenced - const parent = zodSchema._zod.parent; - if (parent && parent !== ref) { - // Ensure parent is processed first so its def has inherited properties - flattenRef(parent); - const parentSeen = ctx.seen.get(parent); - if (parentSeen?.schema.$ref) { - schema.$ref = parentSeen.schema.$ref; - // De-duplicate with parent's definition - if (parentSeen.def) { - for (const key in schema) { - if (key === "$ref" || key === "allOf") - continue; - if (key in parentSeen.def && JSON.stringify(schema[key]) === JSON.stringify(parentSeen.def[key])) { - delete schema[key]; - } - } - } - } - } - // execute overrides - ctx.override({ - zodSchema: zodSchema, - jsonSchema: schema, - path: seen.path ?? [], - }); - }; - // Flattening walks the whole map and clears each `ref` as it goes, so a second call over the same map is a no-op scan. Skip it outright once it has run for a registry conversion. - if (!ctx.external || ctx.sharedEmitDoneFor !== ctx.external) { - for (const entry of [...ctx.seen.entries()].reverse()) { - flattenRef(entry[0]); - } - if (ctx.target !== "openapi-3.0") { - for (const entry of ctx.seen.entries()) { - compactTypeUnion(entry[1].def ?? entry[1].schema); - } - } - for (const rewrite of ctx.deferred) - rewrite(); - // After flattening, every member that was extracted is a `$ref`, so the fold sees the final shape. A schema that inherits an intersection — through `z.lazy`, or any `ref` chain — holds the same `allOf` array, so fold by array identity to catch every copy. - if (ctx.intersections.length) { - const carriers = new Map(); - for (const seen of ctx.seen.values()) { - for (const json of [seen.schema, seen.def]) { - const allOf = json?.allOf; - if (!Array.isArray(allOf)) - continue; - const existing = carriers.get(allOf); - if (existing) - existing.push(json); - else - carriers.set(allOf, [json]); - } - } - for (const allOf of ctx.intersections) { - for (const json of carriers.get(allOf) ?? []) - foldIntersection(json); - } - } - } - const result = {}; - if (ctx.target === "draft-2020-12") { - result.$schema = "https://json-schema.org/draft/2020-12/schema"; - } - else if (ctx.target === "draft-07") { - result.$schema = "http://json-schema.org/draft-07/schema#"; - } - else if (ctx.target === "draft-04") { - result.$schema = "http://json-schema.org/draft-04/schema#"; - } - else if (ctx.target === "openapi-3.0") { - // OpenAPI 3.0 schema objects should not include a $schema property - } - else { - // Arbitrary string values are allowed but won't have a $schema property set - } - if (ctx.external?.uri) { - const id = ctx.external.registry.get(schema)?.id; - if (!id) - throw new Error("Schema is missing an `id` property"); - result.$id = ctx.external.uri(id); - } - // when the root was extracted into $defs, `root.schema` is the `$ref` wrapper and `root.def` is the body that now lives under $defs - assignProps(result, root.defId ? root.schema : (root.def ?? root.schema)); - // The `id` in `.meta()` is a Zod-specific registration tag used to extract schemas into $defs — it is not user-facing JSON Schema metadata. Strip it from the output body where it would otherwise leak. The id is preserved implicitly via the $defs key (and via $ref paths). - const rootMetaId = ctx.metadataRegistry.get(schema)?.id; - if (rootMetaId !== undefined && result.id === rootMetaId) - delete result.id; - // build defs object. With `external`, `defs` is the shared object every schema writes into, so the same entries are reassigned on every call. Without it, `defs` is fresh per call and must be rebuilt. - const defs = ctx.external?.defs ?? {}; - if (!ctx.external || ctx.sharedEmitDoneFor !== ctx.external) { - for (const entry of ctx.seen.entries()) { - const seen = entry[1]; - if (seen.def && seen.defId) { - if (seen.def.id === seen.defId) - delete seen.def.id; - assignProp(defs, seen.defId, seen.def); - } - } - } - if (ctx.external) - ctx.sharedEmitDoneFor = ctx.external; - // set definitions in result - if (ctx.external) { - } - else { - if (Object.keys(defs).length > 0) { - if (ctx.target === "draft-2020-12") { - result.$defs = defs; - } - else { - result.definitions = defs; - } - } - } - try { - // this "finalizes" this schema and ensures all cycles are removed each call to finalize() is functionally independent though the seen map is shared - const finalized = JSON.parse(JSON.stringify(result)); - Object.defineProperty(finalized, "~standard", { - value: { - ...schema["~standard"], - jsonSchema: { - input: createStandardJSONSchemaMethod(schema, "input", ctx.processors), - output: createStandardJSONSchemaMethod(schema, "output", ctx.processors), - }, - }, - enumerable: false, - writable: false, - }); - return finalized; - } - catch (_err) { - throw new Error("Error converting schema to JSON."); - } -} -function isTransforming(_schema, _ctx) { - const ctx = _ctx ?? { seen: new Set() }; - if (ctx.seen.has(_schema)) - return false; - ctx.seen.add(_schema); - const def = _schema._zod.def; - if (def.type === "transform") - return true; - if (def.type === "array") - return isTransforming(def.element, ctx); - if (def.type === "set") - return isTransforming(def.valueType, ctx); - if (def.type === "lazy") - return isTransforming(def.getter(), ctx); - if (def.type === "promise" || - def.type === "optional" || - def.type === "nonoptional" || - def.type === "nullable" || - def.type === "readonly" || - def.type === "default" || - def.type === "prefault" || - def.type === "catch") { - return isTransforming(def.innerType, ctx); - } - if (def.type === "intersection") { - return isTransforming(def.left, ctx) || isTransforming(def.right, ctx); - } - if (def.type === "record" || def.type === "map") { - return isTransforming(def.keyType, ctx) || isTransforming(def.valueType, ctx); - } - if (def.type === "pipe") { - if (_schema._zod.traits.has("$ZodCodec")) - return true; - return isTransforming(def.in, ctx) || isTransforming(def.out, ctx); - } - if (def.type === "object") { - for (const key in def.shape) { - if (isTransforming(def.shape[key], ctx)) - return true; - } - return false; - } - if (def.type === "union") { - for (const option of def.options) { - if (isTransforming(option, ctx)) - return true; - } - return false; - } - if (def.type === "tuple") { - for (const item of def.items) { - if (isTransforming(item, ctx)) - return true; - } - if (def.rest && isTransforming(def.rest, ctx)) - return true; - return false; - } - return false; -} -/** - * Creates a toJSONSchema method for a schema instance. - * This encapsulates the logic of initializing context, processing, extracting defs, and finalizing. - */ -const createToJSONSchemaMethod = (schema, processors = {}) => (params) => { - const ctx = initializeContext({ ...params, processors }); - to_json_schema_process(schema, ctx); - extractDefs(ctx, schema); - return finalize(ctx, schema); -}; -const createStandardJSONSchemaMethod = (schema, io, processors = {}) => (params) => { - const { libraryOptions, target } = params ?? {}; - const ctx = initializeContext({ ...(libraryOptions ?? {}), target, io, processors }); - to_json_schema_process(schema, ctx); - extractDefs(ctx, schema); - return finalize(ctx, schema); -}; - - - - -const formatMap = { - guid: "uuid", - url: "uri", - datetime: "date-time", - json_string: "json-string", - regex: "", // do not set -}; -// ==================== SIMPLE TYPE PROCESSORS ==================== -const stringProcessor = (schema, ctx, _json, _params) => { - const json = _json; - json.type = "string"; - const { minimum, maximum, format, patterns, contentEncoding, laxFormat } = schema._zod - .bag; - if (typeof minimum === "number") - json.minLength = minimum; - if (typeof maximum === "number") - json.maxLength = maximum; - // custom pattern overrides format - if (format) { - json.format = formatMap[format] ?? format; - if (json.format === "") - delete json.format; // empty format is not valid - // `z.iso.time()` is never full-time, and `laxFormat` carries the datetime shapes that also accept what their keyword forbids - if (format === "time" || laxFormat) { - delete json.format; - } - } - if (contentEncoding) - json.contentEncoding = contentEncoding; - if (patterns && patterns.size > 0) { - const patternList = [...patterns]; - if (patternList.length === 1) - json.pattern = patternList[0].source; - else if (patternList.length > 1) { - json.allOf = [ - ...patternList.map((regex) => ({ - ...(ctx.target === "draft-07" || ctx.target === "draft-04" || ctx.target === "openapi-3.0" - ? { type: "string" } - : {}), - pattern: regex.source, - })), - ]; - } - } -}; -const numberProcessor = (schema, ctx, _json, params) => { - const json = _json; - const { minimum, maximum, format, multipleOf, exclusiveMaximum, exclusiveMinimum } = schema._zod.bag; - if (typeof format === "string" && format.includes("int")) - json.type = "integer"; - else - json.type = "number"; - // when both minimum and exclusiveMinimum exist, pick the more restrictive one - const exMin = typeof exclusiveMinimum === "number" && exclusiveMinimum >= (minimum ?? Number.NEGATIVE_INFINITY); - const exMax = typeof exclusiveMaximum === "number" && exclusiveMaximum <= (maximum ?? Number.POSITIVE_INFINITY); - const legacy = ctx.target === "draft-04" || ctx.target === "openapi-3.0"; - if (exMin) { - if (legacy) { - json.minimum = exclusiveMinimum; - json.exclusiveMinimum = true; - } - else { - json.exclusiveMinimum = exclusiveMinimum; - } - } - else if (typeof minimum === "number") { - json.minimum = minimum; - } - if (exMax) { - if (legacy) { - json.maximum = exclusiveMaximum; - json.exclusiveMaximum = true; - } - else { - json.exclusiveMaximum = exclusiveMaximum; - } - } - else if (typeof maximum === "number") { - json.maximum = maximum; - } - if (typeof multipleOf === "number") { - // JSON Schema requires a divisor strictly greater than zero, and a non-finite one does not survive JSON at all. A negative divisor accepts exactly what its absolute value accepts, so it still maps; zero, NaN and Infinity have no keyword form. - if (Number.isFinite(multipleOf) && multipleOf !== 0) - json.multipleOf = Math.abs(multipleOf); - else - handleUnrepresentable(schema, ctx, json, params, `A multipleOf divisor of ${multipleOf} cannot be represented in JSON Schema`); - } -}; -const booleanProcessor = (_schema, _ctx, json, _params) => { - json.type = "boolean"; -}; -const bigintProcessor = (schema, ctx, json, params) => { - handleUnrepresentable(schema, ctx, json, params, "BigInt cannot be represented in JSON Schema"); -}; -const symbolProcessor = (schema, ctx, json, params) => { - handleUnrepresentable(schema, ctx, json, params, "Symbols cannot be represented in JSON Schema"); -}; -const nullProcessor = (_schema, ctx, json, _params) => { - if (ctx.target === "openapi-3.0") { - json.type = "string"; - json.nullable = true; - json.enum = [null]; - } - else { - json.type = "null"; - } -}; -const undefinedProcessor = (schema, ctx, json, params) => { - handleUnrepresentable(schema, ctx, json, params, "Undefined cannot be represented in JSON Schema"); -}; -const voidProcessor = (schema, ctx, json, params) => { - handleUnrepresentable(schema, ctx, json, params, "Void cannot be represented in JSON Schema"); -}; -const neverProcessor = (_schema, _ctx, json, _params) => { - json.not = {}; -}; -const anyProcessor = (_schema, _ctx, _json, _params) => { - // empty schema accepts anything -}; -const unknownProcessor = (_schema, _ctx, _json, _params) => { - // empty schema accepts anything -}; -const dateProcessor = (schema, ctx, json, params) => { - handleUnrepresentable(schema, ctx, json, params, "Date cannot be represented in JSON Schema"); -}; -const enumProcessor = (schema, _ctx, json, _params) => { - const def = schema._zod.def; - const values = getEnumValues(def.entries); - // an empty enum accepts nothing, same as z.never() - if (values.length === 0) { - json.not = {}; - return; - } - // Number enums can have both string and number values - if (values.every((v) => typeof v === "number")) - json.type = "number"; - if (values.every((v) => typeof v === "string")) - json.type = "string"; - json.enum = values; -}; -const literalProcessor = (schema, ctx, json, params) => { - const def = schema._zod.def; - // a literal with no values accepts nothing, same as z.never() - if (def.values.length === 0) { - json.not = {}; - return; - } - const vals = []; - for (const val of def.values) { - if (val === undefined) { - // a custom schema replaces the whole literal, so there is nothing left to accumulate - if (handleUnrepresentable(schema, ctx, json, params, "Literal `undefined` cannot be represented in JSON Schema")) - return; - // otherwise do not add to vals - } - else if (typeof val === "bigint") { - if (handleUnrepresentable(schema, ctx, json, params, "BigInt literals cannot be represented in JSON Schema")) - return; - vals.push(Number(val)); - } - else { - vals.push(val); - } - } - if (vals.length === 0) { - // do nothing (an undefined literal was stripped) - } - else if (vals.length === 1) { - const val = vals[0]; - json.type = val === null ? "null" : typeof val; - if (ctx.target === "draft-04" || ctx.target === "openapi-3.0") { - json.enum = [val]; - } - else { - json.const = val; - } - } - else { - if (vals.every((v) => typeof v === "number")) - json.type = "number"; - if (vals.every((v) => typeof v === "string")) - json.type = "string"; - if (vals.every((v) => typeof v === "boolean")) - json.type = "boolean"; - if (vals.every((v) => v === null)) - json.type = "null"; - json.enum = vals; - } -}; -const nanProcessor = (schema, ctx, json, params) => { - handleUnrepresentable(schema, ctx, json, params, "NaN cannot be represented in JSON Schema"); -}; -const templateLiteralProcessor = (schema, _ctx, json, _params) => { - const _json = json; - const pattern = schema._zod.pattern; - if (!pattern) - throw new Error("Pattern not found in template literal"); - _json.type = "string"; - _json.pattern = pattern.source; -}; -const fileProcessor = (schema, _ctx, json, _params) => { - const _json = json; - const file = { - type: "string", - format: "binary", - contentEncoding: "binary", - }; - const { minimum, maximum, mime } = schema._zod.bag; - if (minimum !== undefined) - file.minLength = minimum; - if (maximum !== undefined) - file.maxLength = maximum; - if (mime) { - if (mime.length === 1) { - file.contentMediaType = mime[0]; - Object.assign(_json, file); - } - else { - Object.assign(_json, file); // shared props at root - _json.anyOf = mime.map((m) => ({ contentMediaType: m })); // only contentMediaType differs - } - } - else { - Object.assign(_json, file); - } -}; -const successProcessor = (_schema, _ctx, json, _params) => { - json.type = "boolean"; -}; -const customProcessor = (schema, ctx, json, params) => { - handleUnrepresentable(schema, ctx, json, params, "Custom types cannot be represented in JSON Schema"); -}; -const functionProcessor = (schema, ctx, json, params) => { - handleUnrepresentable(schema, ctx, json, params, "Function types cannot be represented in JSON Schema"); -}; -const transformProcessor = (schema, ctx, json, params) => { - handleUnrepresentable(schema, ctx, json, params, "Transforms cannot be represented in JSON Schema"); -}; -const mapProcessor = (schema, ctx, json, params) => { - handleUnrepresentable(schema, ctx, json, params, "Map cannot be represented in JSON Schema"); -}; -const setProcessor = (schema, ctx, json, params) => { - handleUnrepresentable(schema, ctx, json, params, "Set cannot be represented in JSON Schema"); -}; -// ==================== COMPOSITE TYPE PROCESSORS ==================== -const arrayProcessor = (schema, ctx, _json, params) => { - const json = _json; - const def = schema._zod.def; - const { minimum, maximum } = schema._zod.bag; - if (typeof minimum === "number") - json.minItems = minimum; - if (typeof maximum === "number") - json.maxItems = maximum; - json.type = "array"; - json.items = to_json_schema_process(def.element, ctx, { - ...params, - path: [...params.path, "items"], - }); -}; -// Transform and catch set `optin = "optional"` at runtime so the parser lets them observe an -// absent key, but their declared input type stays required. An input JSON Schema describes the -// declared type, so resolve past them to the schema that actually carries the optionality. -// Used by both `objectProcessor` (for `required`) and `tupleProcessor` (for `minItems`); see -// wiki/optionality.md, "The JSON Schema emitter reads the *static* value". -function inputOptin(schema) { - const def = schema._zod.def; - if (def.type === "pipe" && def.in._zod.traits.has("$ZodTransform")) { - return inputOptin(def.out); - } - if (def.type === "catch") { - return inputOptin(def.innerType); - } - return schema._zod.optin; -} -const objectProcessor = (schema, ctx, _json, params) => { - const json = _json; - const def = schema._zod.def; - const shape = def.shape; - // dropping it while still emitting `additionalProperties: false` would emit a schema that rejects data this one requires - const symbolKeys = Object.getOwnPropertySymbols(shape); - if (symbolKeys.length && - handleUnrepresentable(schema, ctx, json, params, "Symbol keys cannot be represented in JSON Schema")) { - return; - } - json.type = "object"; - json.properties = {}; - for (const key in shape) { - // assignProp so a __proto__ key becomes an own property instead of hitting the inherited setter on the plain {} we build into - assignProp(json.properties, key, to_json_schema_process(shape[key], ctx, { - ...params, - path: [...params.path, "properties", key], - })); - } - // required keys - const allKeys = new Set(Object.keys(shape)); - const requiredKeys = new Set([...allKeys].filter((key) => { - const field = def.shape[key]; - if (ctx.io === "input") { - return inputOptin(field) === undefined; - } - else { - return field._zod.optout === undefined; - } - })); - if (requiredKeys.size > 0) { - json.required = Array.from(requiredKeys); - } - // catchall - if (def.catchall?._zod.def.type === "never") { - // strict - json.additionalProperties = false; - } - else if (!def.catchall) { - // regular - if (ctx.io === "output") - json.additionalProperties = false; - } - else if (def.catchall) { - json.additionalProperties = to_json_schema_process(def.catchall, ctx, { - ...params, - path: [...params.path, "additionalProperties"], - }); - } -}; -const unionProcessor = (schema, ctx, json, params) => { - const def = schema._zod.def; - // Exclusive unions (inclusive === false) use oneOf (exactly one match) instead of anyOf (one or more matches). This includes both z.xor() and discriminated unions - const isExclusive = def.inclusive === false; - const options = def.options.map((x, i) => to_json_schema_process(x, ctx, { - ...params, - path: [...params.path, isExclusive ? "oneOf" : "anyOf", i], - })); - if (isExclusive) { - json.oneOf = options; - } - else { - json.anyOf = options; - } -}; -const intersectionProcessor = (schema, ctx, json, params) => { - const def = schema._zod.def; - const a = to_json_schema_process(def.left, ctx, { - ...params, - path: [...params.path, "allOf", 0], - }); - const b = to_json_schema_process(def.right, ctx, { - ...params, - path: [...params.path, "allOf", 1], - }); - const isSimpleIntersection = (val) => "allOf" in val && Object.keys(val).length === 1; - const allOf = [ - ...(isSimpleIntersection(a) ? a.allOf : [a]), - ...(isSimpleIntersection(b) ? b.allOf : [b]), - ]; - json.allOf = allOf; - // Recorded innermost first, so a nested intersection has already folded by the time this one is considered. The array is the handle rather than the schema, because a wrapper that inherits this schema shares the same array; `finalize` folds every object holding it. See `foldIntersection`. - ctx.intersections.push(allOf); -}; -const tupleProcessor = (schema, ctx, _json, params) => { - const json = _json; - const def = schema._zod.def; - json.type = "array"; - const prefixPath = ctx.target === "draft-2020-12" ? "prefixItems" : "items"; - const restPath = ctx.target === "draft-2020-12" ? "items" : ctx.target === "openapi-3.0" ? "items" : "additionalItems"; - const prefixItems = def.items.map((x, i) => to_json_schema_process(x, ctx, { - ...params, - path: [...params.path, prefixPath, i], - })); - const rest = def.rest - ? to_json_schema_process(def.rest, ctx, { - ...params, - path: [...params.path, restPath, ...(ctx.target === "openapi-3.0" ? [def.items.length] : [])], - }) - : null; - let minItems = def.items.length; - while (minItems > 0) { - const item = def.items[minItems - 1]; - const optional = ctx.io === "input" ? inputOptin(item) !== undefined : item._zod.optout === "optional"; - if (!optional) - break; - minItems--; - } - const maxItems = def.items.length; - const isClosed = !def.rest; - if (ctx.target === "draft-2020-12") { - json.prefixItems = prefixItems; - if (isClosed) { - json.items = false; - } - else if (rest) { - json.items = rest; - } - if (minItems > 0) - json.minItems = minItems; - if (isClosed) - json.maxItems = maxItems; - } - else if (ctx.target === "openapi-3.0") { - json.items = { - anyOf: prefixItems, - }; - if (rest) { - json.items.anyOf.push(rest); - } - if (minItems > 0) - json.minItems = minItems; - if (isClosed) - json.maxItems = maxItems; - } - else { - json.items = prefixItems; - if (isClosed) { - json.additionalItems = false; - } - else if (rest) { - json.additionalItems = rest; - } - if (minItems > 0) - json.minItems = minItems; - if (isClosed) - json.maxItems = maxItems; - } - // explicit user-defined length checks take precedence - const { minimum, maximum } = schema._zod.bag; - if (typeof minimum === "number") - json.minItems = minimum; - if (typeof maximum === "number") - json.maxItems = maximum; -}; -/** JSON object keys are always strings, so a numeric record key schema is re-expressed over the - * numeric-string form the record parser matches. Deferred to `finalize`, after the flatten: a key - * behind a wrapper only carries its own `type` before then, and a union key only has its branches. - * - * A numeric bound cannot apply to a property name, so `minimum` and its siblings are dropped rather - * than carried over: keeping them beside `type: "string"` reproduces the match-nothing schema this - * exists to fix. A key that carries one therefore emits wider than the record parses — `z.record(z.number().min(5), V)` - * accepts `"3"` — which is the deliberate trade, since throwing on it would reject an ordinary schema - * outright. */ -function stringifyKeyNames(bySchema, json, visited) { - // an extracted key that rewrites cannot go on sharing its definition — the string form a key position needs is not the number form every other reference wants — so it inlines. One that does not rewrite keeps the `$ref`. - if (json.$ref) { - // a recursive key holds its own reference inside its definition, so a node already on the path is left alone rather than resolved again - if (visited.has(json)) - return json; - visited.add(json); - const def = bySchema.get(json)?.def; - if (!def) - return json; - const inlined = stringifyKeyNames(bySchema, def, visited); - return inlined === def ? json : inlined; - } - for (const keyword of ["anyOf", "oneOf"]) { - const branches = json[keyword]; - if (!Array.isArray(branches)) - continue; - const mapped = branches.map((branch) => stringifyKeyNames(bySchema, branch, visited)); - // rebuilding regardless would detach a key that had nothing to re-express, dropping its `$ref` and leaking the internal `id` - if (mapped.some((branch, i) => branch !== branches[i])) - json = { ...json, [keyword]: mapped }; - } - // a member that already admits a string leaves the key unconstrained, so the node's own type re-expresses only when every member is numeric - const types = Array.isArray(json.type) ? json.type : [json.type]; - const numericType = !types.includes("string") && types.some((t) => t === "number" || t === "integer"); - // a heterogeneous key carries no type at all, so its numeric members are caught here instead - const values = json.enum ?? (json.const !== undefined ? [json.const] : undefined); - if (!numericType && !values?.some((v) => typeof v === "number")) - return json; - const { minimum, maximum, exclusiveMinimum, exclusiveMaximum, multipleOf, format, id, ...rest } = json; - if (rest.enum) - rest.enum = rest.enum.map((v) => (typeof v === "number" ? String(v) : v)); - else if (typeof rest.const === "number") - rest.const = String(rest.const); - // a heterogeneous key keeps its absent type: the stringified members already say what a key may be - if (!numericType) - return rest; - rest.type = "string"; - if (!values) - rest.pattern = (types.includes("number") ? number : integer).source; - return rest; -} -/** Every record of one conversion, so the carriers are found in a single pass rather than once per record. */ -const pendingRecords = new WeakMap(); -function rewriteKeyNames(ctx) { - // an extracted key is resolved by the object `extractToDef` left in its place, so the map is built once rather than searched per reference. `_zod.toJSONSchema` can hand the same object to two schemas, so the first entry carrying a body wins, as a search would have found it. - const bySchema = new Map(); - for (const entry of ctx.seen.values()) { - if (entry.def && !bySchema.has(entry.schema)) - bySchema.set(entry.schema, entry); - } - const rewrites = new Map(); - for (const record of pendingRecords.get(ctx) ?? []) { - const seen = ctx.seen.get(record); - const names = (seen?.def ?? seen?.schema)?.propertyNames; - if (!names || names === true || rewrites.has(names)) - continue; - const rewritten = stringifyKeyNames(bySchema, names, new Set()); - if (rewritten !== names) - rewrites.set(names, rewritten); - } - if (!rewrites.size) - return; - // the flatten has already copied each record's own properties onto every wrapper by reference, and an extracted body is another such copy, so every carrier holding a rewritten key is updated together - for (const entry of ctx.seen.values()) { - for (const carrier of [entry.schema, entry.def]) { - const rewritten = carrier && rewrites.get(carrier.propertyNames); - if (rewritten) - carrier.propertyNames = rewritten; - } - } -} -const recordProcessor = (schema, ctx, _json, params) => { - const json = _json; - const def = schema._zod.def; - json.type = "object"; - // For looseRecord with regex patterns, use patternProperties. This correctly represents "only validate keys matching the pattern" semantics and composes well with allOf (intersections) - const keyType = def.keyType; - const keyBag = keyType._zod.bag; - const patterns = keyBag?.patterns; - if (def.mode === "loose" && patterns && patterns.size > 0) { - // Use patternProperties for looseRecord with regex patterns - const valueSchema = to_json_schema_process(def.valueType, ctx, { - ...params, - path: [...params.path, "patternProperties", "*"], - }); - json.patternProperties = {}; - for (const pattern of patterns) { - assignProp(json.patternProperties, pattern.source, valueSchema); - } - } - else { - // Default behavior: use propertyNames + additionalProperties - if (ctx.target === "draft-07" || ctx.target === "draft-2020-12") { - json.propertyNames = to_json_schema_process(def.keyType, ctx, { - ...params, - path: [...params.path, "propertyNames"], - }); - let pending = pendingRecords.get(ctx); - if (!pending) { - pending = []; - pendingRecords.set(ctx, pending); - ctx.deferred.push(() => rewriteKeyNames(ctx)); - } - pending.push(schema); - } - json.additionalProperties = to_json_schema_process(def.valueType, ctx, { - ...params, - path: [...params.path, "additionalProperties"], - }); - } - // Add required for keys with discrete values (enum, literal, etc.) - const keyValues = keyType._zod.values; - // Every key shares one value schema, so an optional-in value makes the whole key set omittable on input. Output keeps them: the exhaustive branch assigns every key, even one whose value came back undefined. - const omittableOnInput = ctx.io === "input" && inputOptin(def.valueType) !== undefined; - if (keyValues && !def.partial && !omittableOnInput) { - const validKeyValues = [...keyValues].filter((v) => typeof v === "string" || typeof v === "number"); - if (validKeyValues.length > 0) { - json.required = validKeyValues.map(String); - } - } -}; -const nullableProcessor = (schema, ctx, json, params) => { - const def = schema._zod.def; - const inner = to_json_schema_process(def.innerType, ctx, params); - const seen = ctx.seen.get(schema); - if (ctx.target === "openapi-3.0") { - seen.ref = def.innerType; - json.nullable = true; - } - else { - json.anyOf = [inner, { type: "null" }]; - } -}; -const nonoptionalProcessor = (schema, ctx, _json, params) => { - const def = schema._zod.def; - to_json_schema_process(def.innerType, ctx, params); - const seen = ctx.seen.get(schema); - seen.ref = def.innerType; -}; -/** Round-trips a default value through JSON so the emitted schema is guaranteed to be valid JSON. - * A BigInt has no reliable encoding, so it goes through `unrepresentable` like any other - * unrepresentable value. Returns a sentinel when the caller must not write a default of its own. */ -const UNREPRESENTABLE_DEFAULT = Symbol(); -function serializeDefaultValue(value, schema, ctx, json, params) { - let unrepresentable = false; - const serialized = JSON.stringify(value, (_, val) => { - if (typeof val !== "bigint") - return val; - unrepresentable = true; - return null; - }); - if (!unrepresentable) - return JSON.parse(serialized); - handleUnrepresentable(schema, ctx, json, params, "BigInt defaults cannot be represented in JSON Schema"); - return UNREPRESENTABLE_DEFAULT; -} -const defaultProcessor = (schema, ctx, json, params) => { - const def = schema._zod.def; - to_json_schema_process(def.innerType, ctx, params); - const seen = ctx.seen.get(schema); - seen.ref = def.innerType; - const value = serializeDefaultValue(def.defaultValue, schema, ctx, json, params); - if (value !== UNREPRESENTABLE_DEFAULT) - json.default = value; -}; -const prefaultProcessor = (schema, ctx, json, params) => { - const def = schema._zod.def; - to_json_schema_process(def.innerType, ctx, params); - const seen = ctx.seen.get(schema); - seen.ref = def.innerType; - if (ctx.io !== "input") - return; - const value = serializeDefaultValue(def.defaultValue, schema, ctx, json, params); - if (value !== UNREPRESENTABLE_DEFAULT) - json._prefault = value; -}; -const catchProcessor = (schema, ctx, json, params) => { - const def = schema._zod.def; - to_json_schema_process(def.innerType, ctx, params); - const seen = ctx.seen.get(schema); - seen.ref = def.innerType; - let catchValue; - try { - catchValue = def.catchValue(undefined); - } - catch { - handleUnrepresentable(schema, ctx, json, params, "Dynamic catch values are not supported in JSON Schema"); - return; - } - json.default = catchValue; -}; -const pipeProcessor = (schema, ctx, _json, params) => { - const def = schema._zod.def; - const inIsTransform = def.in._zod.traits.has("$ZodTransform"); - const innerType = ctx.io === "input" ? (inIsTransform ? def.out : def.in) : def.out; - to_json_schema_process(innerType, ctx, params); - const seen = ctx.seen.get(schema); - seen.ref = innerType; -}; -const readonlyProcessor = (schema, ctx, json, params) => { - const def = schema._zod.def; - to_json_schema_process(def.innerType, ctx, params); - const seen = ctx.seen.get(schema); - seen.ref = def.innerType; - json.readOnly = true; -}; -const promiseProcessor = (schema, ctx, _json, params) => { - const def = schema._zod.def; - to_json_schema_process(def.innerType, ctx, params); - const seen = ctx.seen.get(schema); - seen.ref = def.innerType; -}; -const optionalProcessor = (schema, ctx, _json, params) => { - const def = schema._zod.def; - to_json_schema_process(def.innerType, ctx, params); - const seen = ctx.seen.get(schema); - seen.ref = def.innerType; -}; -const lazyProcessor = (schema, ctx, _json, params) => { - const innerType = schema._zod.innerType; - to_json_schema_process(innerType, ctx, params); - const seen = ctx.seen.get(schema); - seen.ref = innerType; -}; -// ==================== ALL PROCESSORS ==================== -const allProcessors = { - string: stringProcessor, - number: numberProcessor, - boolean: booleanProcessor, - bigint: bigintProcessor, - symbol: symbolProcessor, - null: nullProcessor, - undefined: undefinedProcessor, - void: voidProcessor, - never: neverProcessor, - any: anyProcessor, - unknown: unknownProcessor, - date: dateProcessor, - enum: enumProcessor, - literal: literalProcessor, - nan: nanProcessor, - template_literal: templateLiteralProcessor, - file: fileProcessor, - success: successProcessor, - custom: customProcessor, - function: functionProcessor, - transform: transformProcessor, - map: mapProcessor, - set: setProcessor, - array: arrayProcessor, - object: objectProcessor, - union: unionProcessor, - intersection: intersectionProcessor, - tuple: tupleProcessor, - record: recordProcessor, - nullable: nullableProcessor, - nonoptional: nonoptionalProcessor, - default: defaultProcessor, - prefault: prefaultProcessor, - catch: catchProcessor, - pipe: pipeProcessor, - readonly: readonlyProcessor, - promise: promiseProcessor, - optional: optionalProcessor, - lazy: lazyProcessor, -}; -function toJSONSchema(input, params) { - if ("_idmap" in input) { - // Registry case - const registry = input; - const ctx = initializeContext({ ...params, processors: allProcessors }); - const defs = {}; - // First pass: process all schemas to build the seen map - for (const entry of registry._idmap.entries()) { - const [_, schema] = entry; - to_json_schema_process(schema, ctx); - } - const schemas = {}; - const external = { - registry, - uri: params?.uri, - defs, - }; - // Update the context with external configuration - ctx.external = external; - // Second pass: emit each schema - for (const entry of registry._idmap.entries()) { - const [key, schema] = entry; - extractDefs(ctx, schema); - assignProp(schemas, key, finalize(ctx, schema)); - } - if (Object.keys(defs).length > 0) { - const defsSegment = ctx.target === "draft-2020-12" ? "$defs" : "definitions"; - schemas.__shared = { - [defsSegment]: defs, - }; - } - return { schemas }; - } - // Single schema case - const ctx = initializeContext({ ...params, processors: allProcessors }); - to_json_schema_process(input, ctx); - extractDefs(ctx, input); - return finalize(ctx, input); -} - - -const en_error = () => { - const Sizable = { - string: { unit: "characters", verb: "to have" }, - file: { unit: "bytes", verb: "to have" }, - array: { unit: "items", verb: "to have" }, - set: { unit: "items", verb: "to have" }, - map: { unit: "entries", verb: "to have" }, - }; - function getSizing(origin) { - return Sizable[origin] ?? null; - } - const FormatDictionary = { - 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", - credit_card: "credit card number", - jwt: "JWT", - template_literal: "input", - }; - // type names: missing keys = do not translate (use raw value via ?? fallback) - const TypeDictionary = { - // Compatibility: "nan" -> "NaN" for display - nan: "NaN", - // All other type names omitted - they fall back to raw values via ?? operator - }; - function getTypeName(type, input) { - if (type === "number" && typeof input === "number" && !Number.isFinite(input)) { - return String(input); - } - return TypeDictionary[type] ?? type; - } - return (issue) => { - switch (issue.code) { - case "invalid_type": { - const expected = getTypeName(issue.expected); - const receivedType = parsedType(issue.input); - const received = getTypeName(receivedType, issue.input); - return `Invalid input: expected ${expected}, received ${received}`; - } - case "invalid_value": - if (issue.values.length === 1) - return `Invalid input: expected ${stringifyPrimitive(issue.values[0])}`; - return `Invalid option: expected one of ${joinValues(issue.values, "|")}`; - case "too_big": { - const adj = issue.exact ? "exactly " : issue.inclusive ? "<=" : "<"; - const sizing = getSizing(issue.origin); - if (sizing) - return `Too big: expected ${issue.origin ?? "value"} to have ${adj}${issue.maximum.toString()} ${sizing.unit ?? "elements"}`; - return `Too big: expected ${issue.origin ?? "value"} to be ${adj}${issue.maximum.toString()}`; - } - case "too_small": { - const adj = issue.exact ? "exactly " : issue.inclusive ? ">=" : ">"; - const sizing = getSizing(issue.origin); - if (sizing) { - return `Too small: expected ${issue.origin} to have ${adj}${issue.minimum.toString()} ${sizing.unit}`; - } - return `Too small: expected ${issue.origin} to be ${adj}${issue.minimum.toString()}`; - } - case "invalid_format": { - const _issue = issue; - if (_issue.format === "starts_with") { - return `Invalid string: must start with "${_issue.prefix}"`; - } - if (_issue.format === "ends_with") - return `Invalid string: must end with "${_issue.suffix}"`; - if (_issue.format === "includes") - return `Invalid string: must include "${_issue.includes}"`; - if (_issue.format === "regex") - return `Invalid string: must match pattern ${_issue.pattern}`; - return `Invalid ${FormatDictionary[_issue.format] ?? issue.format}`; - } - case "not_multiple_of": - return `Invalid number: must be a multiple of ${issue.divisor}`; - case "unrecognized_keys": - return `Unrecognized key${issue.keys.length > 1 ? "s" : ""}: ${joinValues(issue.keys, ", ")}`; - case "invalid_key": - return `Invalid key in ${issue.origin}`; - case "invalid_union": - if (issue.options && Array.isArray(issue.options) && issue.options.length > 0) { - const opts = issue.options.map((o) => `'${o}'`).join(" | "); - return `Invalid discriminator value. Expected ${opts}`; - } - if (issue.inclusive === false) { - return "Invalid input: more than one option matched"; - } - return "Invalid input"; - case "invalid_element": - return `Invalid value in ${issue.origin}`; - default: - return `Invalid input`; - } - }; -}; -/* export default */ function en() { - return { - localeError: en_error(), - }; -} - - - - -/* Prototypes that already carry the lazy helper methods. Seeded with the - * intrinsics so that `init` on a foreign object — it accepts any object — - * can never install an accessor onto a prototype we do not own. */ -const _installedErrorProtos = /* @__PURE__ */ new WeakSet([Object.prototype, Error.prototype]); -/* Helper methods live as non-enumerable lazy getters on the shared - * prototype instead of own properties on every instance. On first - * access the getter allocates the per-instance closure and caches it - * as a non-enumerable own property, so detached usage still works and - * the allocation only happens for methods actually touched. */ -function _lazyMethod(proto, key, make) { - Object.defineProperty(proto, key, { - configurable: true, - enumerable: false, - get() { - const value = make(this); - Object.defineProperty(this, key, { value, configurable: true, writable: true }); - return value; - }, - set(value) { - Object.defineProperty(this, key, { value, configurable: true, writable: true }); - }, - }); -} -const classic_errors_initializer = (inst, issues) => { - $ZodError.init(inst, issues); - inst.name = "ZodError"; - const proto = Object.getPrototypeOf(inst); - if (_installedErrorProtos.has(proto)) - return; - _installedErrorProtos.add(proto); - _lazyMethod(proto, "format", (self) => (mapper) => formatError(self, mapper)); - _lazyMethod(proto, "flatten", (self) => (mapper) => flattenError(self, mapper)); - _lazyMethod(proto, "addIssue", (self) => (issue) => { - self.issues.push(issue); - self.message = JSON.stringify(self.issues, jsonStringifyReplacer, 2); - }); - _lazyMethod(proto, "addIssues", (self) => (issues) => { - self.issues.push(...issues); - self.message = JSON.stringify(self.issues, jsonStringifyReplacer, 2); - }); - Object.defineProperty(proto, "isEmpty", { - configurable: true, - enumerable: false, - get() { - return this.issues.length === 0; - }, - }); -}; -const ZodError = /*@__PURE__*/ (/* unused pure expression or super */ null && (core.$constructor("ZodError", classic_errors_initializer))); -const ZodRealError = /*@__PURE__*/ $constructor("ZodError", classic_errors_initializer, undefined, { - Parent: Error, -}); -// /** @deprecated Use `z.core.$ZodErrorMapCtx` instead. */ -// export type ErrorMapCtx = core.$ZodErrorMapCtx; - - - -const classic_parse_parse = /* @__PURE__ */ parse_parse(ZodRealError); -const classic_parse_parseAsync = /* @__PURE__ */ parse_parseAsync(ZodRealError); -const parse_safeParse = /* @__PURE__ */ _safeParse(ZodRealError); -const parse_safeParseAsync = /* @__PURE__ */ _safeParseAsync(ZodRealError); - -// Codec functions -const classic_parse_encode = /* @__PURE__ */ parse_encode(ZodRealError); -const classic_parse_decode = /* @__PURE__ */ parse_decode(ZodRealError); -const classic_parse_encodeAsync = /* @__PURE__ */ parse_encodeAsync(ZodRealError); -const classic_parse_decodeAsync = /* @__PURE__ */ parse_decodeAsync(ZodRealError); -const parse_safeEncode = /* @__PURE__ */ _safeEncode(ZodRealError); -const parse_safeDecode = /* @__PURE__ */ _safeDecode(ZodRealError); -const parse_safeEncodeAsync = /* @__PURE__ */ _safeEncodeAsync(ZodRealError); -const parse_safeDecodeAsync = /* @__PURE__ */ _safeDecodeAsync(ZodRealError); - - - - - - - - -// Register English as the default locale on first ZodType construction. Hooked into the `ZodType` `$constructor` (rather than a top-level `config(en())` in `external.ts`) so bundlers honoring `sideEffects: false` can't tree-shake it out — see #5953, #5725. An explicit `z.config(z.locales.xx())` call wins regardless of order, since this only sets the default when none is present. -function _ensureDefaultLocale() { - if (!globalConfig.localeError) - core_config(en()); -} -// the default memoizer is read by the core container init, which runs before `ZodType.init`, so each container calls this first -function _ensureDefaultMemoizer() { - if (!globalConfig.memoizer) - core_config({ memoizer: memoizer() }); -} -const ZodType = /*@__PURE__*/ $constructor("ZodType", (inst, def) => { - _ensureDefaultLocale(); - $ZodType.init(inst, def); - inst.def = def; - inst.type = def.type; - return inst; -}, { - check(...chks) { - const def = this.def; - return this.clone(mergeDefs(def, { - checks: [ - ...(def.checks ?? []), - ...chks.map((ch) => typeof ch === "function" ? { _zod: { check: ch, def: { check: "custom" }, onattach: [] } } : ch), - ], - }), { parent: true }); - }, - with(...chks) { - return this.check(...chks); - }, - clone(def, params) { - return clone(this, def, params); - }, - brand() { - return this; - }, - register(reg, meta) { - reg.add(this, meta); - return this; - }, - refine(check, params) { - return this.check(refine(check, params)); - }, - superRefine(refinement, params) { - return this.check(superRefine(refinement, params)); - }, - overwrite(fn) { - return this.check(_overwrite(fn)); - }, - optional() { - return schemas_optional(this); - }, - exactOptional() { - return exactOptional(this); - }, - nullable() { - return nullable(this); - }, - nullish() { - return schemas_optional(nullable(this)); - }, - nonoptional(params) { - return nonoptional(this, params); - }, - array() { - return schemas_array(this); - }, - or(arg) { - return schemas_union([this, arg]); - }, - and(arg) { - return intersection(this, arg); - }, - transform(tx) { - return pipe(this, transform(tx)); - }, - default(d) { - return schemas_default(this, d); - }, - prefault(d) { - return prefault(this, d); - }, - catch(params) { - return schemas_catch(this, params); - }, - pipe(target) { - return pipe(this, target); - }, - readonly() { - return readonly(this); - }, - describe(description) { - const cl = this.clone(); - globalRegistry.add(cl, { description }); - return cl; - }, - meta(...args) { - // overloaded: meta() returns the registered metadata, meta(data) returns a clone with `data` registered. The mapped type picks up the second overload, so we accept variadic any-args and return `any` to satisfy both at runtime. - if (args.length === 0) - return globalRegistry.get(this); - const cl = this.clone(); - globalRegistry.add(cl, args[0]); - return cl; - }, - isOptional() { - return this.safeParse(undefined).success; - }, - isNullable() { - return this.safeParse(null).success; - }, - apply(fn, ...args) { - return args.length === 0 ? fn(this) : fn(this, ...args); - }, - // Overrides core's `~standard` to add `jsonSchema`. Must stay a prototype entry: redefining it per instance demotes instances to dictionary mode. - get "~standard"() { - return hide(this, "~standard", { - ...standardProps(this), - jsonSchema: { - input: createStandardJSONSchemaMethod(this, "input"), - output: createStandardJSONSchemaMethod(this, "output"), - }, - }); - }, - set "~standard"(value) { - util_own(this, "~standard", value); - }, - parse: function _parse(data, params) { - return classic_parse_parse(this, data, params, { callee: _parse }); - }, - parseAsync: async function _parseAsync(data, params) { - return await classic_parse_parseAsync(this, data, params, { callee: _parseAsync }); - }, - safeParse(data, params) { - return parse_safeParse(this, data, params); - }, - async safeParseAsync(data, params) { - return parse_safeParseAsync(this, data, params); - }, - // `spa` is an alias: same function object as `safeParseAsync`, as before. - get spa() { - return this?.safeParseAsync; - }, - set spa(value) { - util_own(this, "spa", value); - }, - encode: function _encode(data, params) { - return classic_parse_encode(this, data, params, { callee: _encode }); - }, - decode: function _decode(data, params) { - return classic_parse_decode(this, data, params, { callee: _decode }); - }, - encodeAsync: async function _encodeAsync(data, params) { - return await classic_parse_encodeAsync(this, data, params, { callee: _encodeAsync }); - }, - decodeAsync: async function _decodeAsync(data, params) { - return await classic_parse_decodeAsync(this, data, params, { callee: _decodeAsync }); - }, - safeEncode(data, params) { - return parse_safeEncode(this, data, params); - }, - safeDecode(data, params) { - return parse_safeDecode(this, data, params); - }, - async safeEncodeAsync(data, params) { - return parse_safeEncodeAsync(this, data, params); - }, - async safeDecodeAsync(data, params) { - return parse_safeDecodeAsync(this, data, params); - }, - toJSONSchema(params) { - return createToJSONSchemaMethod(this, {})(params); - }, - // Reads through to the registry on every access, so it must not cache. - get description() { - return globalRegistry.get(this)?.description; - }, - // No setter: `schema._def = x` throws, as it did when `_def` was a non-writable own property. - get _def() { - return this._zod.def; - }, -}); -/** @internal */ -const _ZodString = /*@__PURE__*/ $constructor("_ZodString", (inst, def) => { - $ZodString.init(inst, def); - ZodType.init(inst, def); - inst._zod.processJSONSchema = (ctx, json, params) => stringProcessor(inst, ctx, json, params); - const bag = inst._zod.bag; - inst.format = bag.format ?? null; - inst.minLength = bag.minimum ?? null; - inst.maxLength = bag.maximum ?? null; -}, { - regex(...args) { - return this.check(_regex(...args)); - }, - includes(...args) { - return this.check(_includes(...args)); - }, - startsWith(...args) { - return this.check(_startsWith(...args)); - }, - endsWith(...args) { - return this.check(_endsWith(...args)); - }, - min(...args) { - return this.check(_minLength(...args)); - }, - max(...args) { - return this.check(_maxLength(...args)); - }, - length(...args) { - return this.check(_length(...args)); - }, - nonempty(...args) { - return this.check(_minLength(1, ...args)); - }, - lowercase(params) { - return this.check(_lowercase(params)); - }, - uppercase(params) { - return this.check(_uppercase(params)); - }, - trim() { - return this.check(_trim()); - }, - normalize(...args) { - return this.check(_normalize(...args)); - }, - toLowerCase() { - return this.check(_toLowerCase()); - }, - toUpperCase() { - return this.check(_toUpperCase()); - }, - slugify() { - return this.check(_slugify()); - }, -}); -const ZodString = /*@__PURE__*/ $constructor("ZodString", (inst, def) => { - $ZodString.init(inst, def); - _ZodString.init(inst, def); -}, { - email(params) { - return this.check(_email(ZodEmail, params)); - }, - url(params) { - return this.check(_url(ZodURL, params)); - }, - jwt(params) { - return this.check(_jwt(ZodJWT, params)); - }, - emoji(params) { - return this.check(api_emoji(ZodEmoji, params)); - }, - guid(params) { - return this.check(_guid(ZodGUID, params)); - }, - uuid(params) { - return this.check(_uuid(ZodUUID, params)); - }, - uuidv4(params) { - return this.check(_uuidv4(ZodUUID, params)); - }, - uuidv6(params) { - return this.check(_uuidv6(ZodUUID, params)); - }, - uuidv7(params) { - return this.check(_uuidv7(ZodUUID, params)); - }, - nanoid(params) { - return this.check(_nanoid(ZodNanoID, params)); - }, - cuid(params) { - return this.check(_cuid(ZodCUID, params)); - }, - cuid2(params) { - return this.check(_cuid2(ZodCUID2, params)); - }, - ulid(params) { - return this.check(_ulid(ZodULID, params)); - }, - base64(params) { - return this.check(_base64(ZodBase64, params)); - }, - base64url(params) { - return this.check(_base64url(ZodBase64URL, params)); - }, - xid(params) { - return this.check(_xid(ZodXID, params)); - }, - ksuid(params) { - return this.check(_ksuid(ZodKSUID, params)); - }, - ipv4(params) { - return this.check(_ipv4(ZodIPv4, params)); - }, - ipv6(params) { - return this.check(_ipv6(ZodIPv6, params)); - }, - cidrv4(params) { - return this.check(_cidrv4(ZodCIDRv4, params)); - }, - cidrv6(params) { - return this.check(_cidrv6(ZodCIDRv6, params)); - }, - e164(params) { - return this.check(_e164(ZodE164, params)); - }, - datetime(params) { - return this.check(_isoDateTime(ZodISODateTime, params)); - }, - date(params) { - return this.check(_isoDate(ZodISODate, params)); - }, - time(params) { - return this.check(_isoTime(schemas_ZodISOTime, params)); - }, - duration(params) { - return this.check(_isoDuration(schemas_ZodISODuration, params)); - }, -}); -function schemas_string(params) { - return _string(ZodString, params); -} -const ZodStringFormat = /*@__PURE__*/ $constructor("ZodStringFormat", (inst, def) => { - $ZodStringFormat.init(inst, def); - _ZodString.init(inst, def); -}); -const ZodISODateTime = /*@__PURE__*/ $constructor("ZodISODateTime", (inst, def) => { - $ZodISODateTime.init(inst, def); - ZodStringFormat.init(inst, def); -}); -const ZodISODate = /*@__PURE__*/ $constructor("ZodISODate", (inst, def) => { - $ZodISODate.init(inst, def); - ZodStringFormat.init(inst, def); -}); -const schemas_ZodISOTime = /*@__PURE__*/ $constructor("ZodISOTime", (inst, def) => { - $ZodISOTime.init(inst, def); - ZodStringFormat.init(inst, def); -}); -const schemas_ZodISODuration = /*@__PURE__*/ $constructor("ZodISODuration", (inst, def) => { - $ZodISODuration.init(inst, def); - ZodStringFormat.init(inst, def); -}); -const ZodEmail = /*@__PURE__*/ $constructor("ZodEmail", (inst, def) => { - // ZodStringFormat.init(inst, def); - $ZodEmail.init(inst, def); - ZodStringFormat.init(inst, def); -}); -function schemas_email(params) { - return _email(ZodEmail, params); -} -const ZodGUID = /*@__PURE__*/ $constructor("ZodGUID", (inst, def) => { - // ZodStringFormat.init(inst, def); - $ZodGUID.init(inst, def); - ZodStringFormat.init(inst, def); -}); -function schemas_guid(params) { - return core._guid(ZodGUID, params); -} -const ZodUUID = /*@__PURE__*/ $constructor("ZodUUID", (inst, def) => { - // ZodStringFormat.init(inst, def); - $ZodUUID.init(inst, def); - ZodStringFormat.init(inst, def); -}); -function schemas_uuid(params) { - return core._uuid(ZodUUID, params); -} -function uuidv4(params) { - return core._uuidv4(ZodUUID, params); -} -// ZodUUIDv6 -function uuidv6(params) { - return core._uuidv6(ZodUUID, params); -} -// ZodUUIDv7 -function uuidv7(params) { - return core._uuidv7(ZodUUID, params); -} -const ZodURL = /*@__PURE__*/ $constructor("ZodURL", (inst, def) => { - // ZodStringFormat.init(inst, def); - $ZodURL.init(inst, def); - ZodStringFormat.init(inst, def); -}); -function schemas_url(params) { - return _url(ZodURL, params); -} -function httpUrl(params) { - return core._url(ZodURL, { - protocol: core.regexes.httpProtocol, - hostname: core.regexes.domain, - ...util.normalizeParams(params), - }); -} -const ZodEmoji = /*@__PURE__*/ $constructor("ZodEmoji", (inst, def) => { - // ZodStringFormat.init(inst, def); - $ZodEmoji.init(inst, def); - ZodStringFormat.init(inst, def); -}); -function schemas_emoji(params) { - return core._emoji(ZodEmoji, params); -} -const ZodNanoID = /*@__PURE__*/ $constructor("ZodNanoID", (inst, def) => { - // ZodStringFormat.init(inst, def); - $ZodNanoID.init(inst, def); - ZodStringFormat.init(inst, def); -}); -function schemas_nanoid(params) { - return core._nanoid(ZodNanoID, params); -} -/** - * @deprecated CUID v1 is deprecated by its authors due to information leakage - * (timestamps embedded in the id). Use {@link ZodCUID2} instead. - * See https://github.com/paralleldrive/cuid. - */ -const ZodCUID = /*@__PURE__*/ $constructor("ZodCUID", (inst, def) => { - // ZodStringFormat.init(inst, def); - $ZodCUID.init(inst, def); - ZodStringFormat.init(inst, def); -}); -/** - * Validates a CUID v1 string. - * - * @deprecated CUID v1 is deprecated by its authors due to information leakage - * (timestamps embedded in the id). Use {@link cuid2 | `z.cuid2()`} instead. - * See https://github.com/paralleldrive/cuid. - */ -function schemas_cuid(params) { - return core._cuid(ZodCUID, params); -} -const ZodCUID2 = /*@__PURE__*/ $constructor("ZodCUID2", (inst, def) => { - // ZodStringFormat.init(inst, def); - $ZodCUID2.init(inst, def); - ZodStringFormat.init(inst, def); -}); -function schemas_cuid2(params) { - return core._cuid2(ZodCUID2, params); -} -const ZodULID = /*@__PURE__*/ $constructor("ZodULID", (inst, def) => { - // ZodStringFormat.init(inst, def); - $ZodULID.init(inst, def); - ZodStringFormat.init(inst, def); -}); -function schemas_ulid(params) { - return core._ulid(ZodULID, params); -} -const ZodXID = /*@__PURE__*/ $constructor("ZodXID", (inst, def) => { - // ZodStringFormat.init(inst, def); - $ZodXID.init(inst, def); - ZodStringFormat.init(inst, def); -}); -function schemas_xid(params) { - return core._xid(ZodXID, params); -} -const ZodKSUID = /*@__PURE__*/ $constructor("ZodKSUID", (inst, def) => { - // ZodStringFormat.init(inst, def); - $ZodKSUID.init(inst, def); - ZodStringFormat.init(inst, def); -}); -function schemas_ksuid(params) { - return core._ksuid(ZodKSUID, params); -} -const ZodIPv4 = /*@__PURE__*/ $constructor("ZodIPv4", (inst, def) => { - // ZodStringFormat.init(inst, def); - $ZodIPv4.init(inst, def); - ZodStringFormat.init(inst, def); -}); -function schemas_ipv4(params) { - return core._ipv4(ZodIPv4, params); -} -const ZodMAC = /*@__PURE__*/ (/* unused pure expression or super */ null && (core.$constructor("ZodMAC", (inst, def) => { - // ZodStringFormat.init(inst, def); - core.$ZodMAC.init(inst, def); - ZodStringFormat.init(inst, def); -}))); -function schemas_mac(params) { - return core._mac(ZodMAC, params); -} -const ZodIPv6 = /*@__PURE__*/ $constructor("ZodIPv6", (inst, def) => { - // ZodStringFormat.init(inst, def); - $ZodIPv6.init(inst, def); - ZodStringFormat.init(inst, def); -}); -function schemas_ipv6(params) { - return core._ipv6(ZodIPv6, params); -} -const ZodCIDRv4 = /*@__PURE__*/ $constructor("ZodCIDRv4", (inst, def) => { - $ZodCIDRv4.init(inst, def); - ZodStringFormat.init(inst, def); -}); -function schemas_cidrv4(params) { - return core._cidrv4(ZodCIDRv4, params); -} -const ZodCIDRv6 = /*@__PURE__*/ $constructor("ZodCIDRv6", (inst, def) => { - $ZodCIDRv6.init(inst, def); - ZodStringFormat.init(inst, def); -}); -function schemas_cidrv6(params) { - return core._cidrv6(ZodCIDRv6, params); -} -const ZodBase64 = /*@__PURE__*/ $constructor("ZodBase64", (inst, def) => { - // ZodStringFormat.init(inst, def); - $ZodBase64.init(inst, def); - ZodStringFormat.init(inst, def); -}); -function schemas_base64(params) { - return core._base64(ZodBase64, params); -} -const ZodBase64URL = /*@__PURE__*/ $constructor("ZodBase64URL", (inst, def) => { - // ZodStringFormat.init(inst, def); - $ZodBase64URL.init(inst, def); - ZodStringFormat.init(inst, def); -}); -function schemas_base64url(params) { - return core._base64url(ZodBase64URL, params); -} -const ZodE164 = /*@__PURE__*/ $constructor("ZodE164", (inst, def) => { - // ZodStringFormat.init(inst, def); - $ZodE164.init(inst, def); - ZodStringFormat.init(inst, def); -}); -function schemas_e164(params) { - return core._e164(ZodE164, params); -} -const ZodCreditCard = /*@__PURE__*/ (/* unused pure expression or super */ null && (core.$constructor("ZodCreditCard", (inst, def) => { - core.$ZodCreditCard.init(inst, def); - ZodStringFormat.init(inst, def); -}))); -function schemas_creditCard(params) { - return core._creditCard(ZodCreditCard, params); -} -const ZodJWT = /*@__PURE__*/ $constructor("ZodJWT", (inst, def) => { - // ZodStringFormat.init(inst, def); - $ZodJWT.init(inst, def); - ZodStringFormat.init(inst, def); -}); -function jwt(params) { - return core._jwt(ZodJWT, params); -} -const ZodCustomStringFormat = /*@__PURE__*/ (/* unused pure expression or super */ null && (core.$constructor("ZodCustomStringFormat", (inst, def) => { - // ZodStringFormat.init(inst, def); - core.$ZodCustomStringFormat.init(inst, def); - ZodStringFormat.init(inst, def); -}))); -function stringFormat(format, fnOrRegex, _params = {}) { - return core._stringFormat(ZodCustomStringFormat, format, fnOrRegex, _params); -} -function schemas_hostname(_params) { - return core._stringFormat(ZodCustomStringFormat, "hostname", core.regexes.hostname, _params); -} -function schemas_hex(_params) { - return core._stringFormat(ZodCustomStringFormat, "hex", core.regexes.hex, _params); -} -function schemas_hash(alg, params) { - const enc = params?.enc ?? "hex"; - const format = `${alg}_${enc}`; - const regex = core.regexes[format]; - if (!regex) - throw new Error(`Unrecognized hash format: ${format}`); - return core._stringFormat(ZodCustomStringFormat, format, regex, params); -} -const ZodNumber = /*@__PURE__*/ $constructor("ZodNumber", (inst, def) => { - $ZodNumber.init(inst, def); - ZodType.init(inst, def); - inst._zod.processJSONSchema = (ctx, json, params) => numberProcessor(inst, ctx, json, params); - const bag = inst._zod.bag; - inst.minValue = - Math.max(bag.minimum ?? Number.NEGATIVE_INFINITY, bag.exclusiveMinimum ?? Number.NEGATIVE_INFINITY) ?? null; - inst.maxValue = - Math.min(bag.maximum ?? Number.POSITIVE_INFINITY, bag.exclusiveMaximum ?? Number.POSITIVE_INFINITY) ?? null; - inst.isInt = (bag.format ?? "").includes("int") || Number.isSafeInteger(bag.multipleOf ?? 0.5); - inst.isFinite = true; - inst.format = bag.format ?? null; -}, { - gt(value, params) { - return this.check(_gt(value, params)); - }, - gte(value, params) { - return this.check(_gte(value, params)); - }, - min(value, params) { - return this.check(_gte(value, params)); - }, - lt(value, params) { - return this.check(_lt(value, params)); - }, - lte(value, params) { - return this.check(_lte(value, params)); - }, - max(value, params) { - return this.check(_lte(value, params)); - }, - int(params) { - return this.check(schemas_int(params)); - }, - safe(params) { - return this.check(schemas_int(params)); - }, - positive(params) { - return this.check(_gt(0, params)); - }, - nonnegative(params) { - return this.check(_gte(0, params)); - }, - negative(params) { - return this.check(_lt(0, params)); - }, - nonpositive(params) { - return this.check(_lte(0, params)); - }, - multipleOf(value, params) { - return this.check(_multipleOf(value, params)); - }, - step(value, params) { - return this.check(_multipleOf(value, params)); - }, - finite() { - return this; - }, -}); -function schemas_number(params) { - return _number(ZodNumber, params); -} -const ZodNumberFormat = /*@__PURE__*/ $constructor("ZodNumberFormat", (inst, def) => { - $ZodNumberFormat.init(inst, def); - ZodNumber.init(inst, def); -}); -function schemas_int(params) { - return _int(ZodNumberFormat, params); -} -function float32(params) { - return core._float32(ZodNumberFormat, params); -} -function float64(params) { - return core._float64(ZodNumberFormat, params); -} -function int32(params) { - return core._int32(ZodNumberFormat, params); -} -function uint32(params) { - return core._uint32(ZodNumberFormat, params); -} -const ZodBoolean = /*@__PURE__*/ $constructor("ZodBoolean", (inst, def) => { - $ZodBoolean.init(inst, def); - ZodType.init(inst, def); - inst._zod.processJSONSchema = (ctx, json, params) => booleanProcessor(inst, ctx, json, params); -}); -function schemas_boolean(params) { - return _boolean(ZodBoolean, params); -} -const ZodBigInt = /*@__PURE__*/ (/* unused pure expression or super */ null && (core.$constructor("ZodBigInt", (inst, def) => { - core.$ZodBigInt.init(inst, def); - ZodType.init(inst, def); - inst._zod.processJSONSchema = (ctx, json, params) => processors.bigintProcessor(inst, ctx, json, params); - const bag = inst._zod.bag; - inst.minValue = bag.minimum ?? null; - inst.maxValue = bag.maximum ?? null; - inst.format = bag.format ?? null; -}, { - gte(value, params) { - return this.check(checks.gte(value, params)); - }, - min(value, params) { - return this.check(checks.gte(value, params)); - }, - gt(value, params) { - return this.check(checks.gt(value, params)); - }, - lt(value, params) { - return this.check(checks.lt(value, params)); - }, - lte(value, params) { - return this.check(checks.lte(value, params)); - }, - max(value, params) { - return this.check(checks.lte(value, params)); - }, - positive(params) { - return this.check(checks.gt(BigInt(0), params)); - }, - negative(params) { - return this.check(checks.lt(BigInt(0), params)); - }, - nonpositive(params) { - return this.check(checks.lte(BigInt(0), params)); - }, - nonnegative(params) { - return this.check(checks.gte(BigInt(0), params)); - }, - multipleOf(value, params) { - return this.check(checks.multipleOf(value, params)); - }, -}))); -function schemas_bigint(params) { - return core._bigint(ZodBigInt, params); -} -const ZodBigIntFormat = /*@__PURE__*/ (/* unused pure expression or super */ null && (core.$constructor("ZodBigIntFormat", (inst, def) => { - core.$ZodBigIntFormat.init(inst, def); - ZodBigInt.init(inst, def); -}))); -function int64(params) { - return core._int64(ZodBigIntFormat, params); -} -function uint64(params) { - return core._uint64(ZodBigIntFormat, params); -} -const ZodSymbol = /*@__PURE__*/ (/* unused pure expression or super */ null && (core.$constructor("ZodSymbol", (inst, def) => { - core.$ZodSymbol.init(inst, def); - ZodType.init(inst, def); - inst._zod.processJSONSchema = (ctx, json, params) => processors.symbolProcessor(inst, ctx, json, params); -}))); -function symbol(params) { - return core._symbol(ZodSymbol, params); -} -const ZodUndefined = /*@__PURE__*/ (/* unused pure expression or super */ null && (core.$constructor("ZodUndefined", (inst, def) => { - core.$ZodUndefined.init(inst, def); - ZodType.init(inst, def); - inst._zod.processJSONSchema = (ctx, json, params) => processors.undefinedProcessor(inst, ctx, json, params); -}))); -function schemas_undefined(params) { - return core._undefined(ZodUndefined, params); -} - -const ZodNull = /*@__PURE__*/ $constructor("ZodNull", (inst, def) => { - $ZodNull.init(inst, def); - ZodType.init(inst, def); - inst._zod.processJSONSchema = (ctx, json, params) => nullProcessor(inst, ctx, json, params); -}); -function schemas_null(params) { - return api_null(ZodNull, params); -} - -const ZodAny = /*@__PURE__*/ $constructor("ZodAny", (inst, def) => { - $ZodAny.init(inst, def); - ZodType.init(inst, def); - inst._zod.processJSONSchema = (ctx, json, params) => anyProcessor(inst, ctx, json, params); -}); -function any() { - return _any(ZodAny); -} -const ZodUnknown = /*@__PURE__*/ $constructor("ZodUnknown", (inst, def) => { - $ZodUnknown.init(inst, def); - ZodType.init(inst, def); - inst._zod.processJSONSchema = (ctx, json, params) => unknownProcessor(inst, ctx, json, params); -}); -function unknown() { - return _unknown(ZodUnknown); -} -const ZodNever = /*@__PURE__*/ $constructor("ZodNever", (inst, def) => { - $ZodNever.init(inst, def); - ZodType.init(inst, def); - inst._zod.processJSONSchema = (ctx, json, params) => neverProcessor(inst, ctx, json, params); -}); -function never(params) { - return _never(ZodNever, params); -} -const ZodVoid = /*@__PURE__*/ (/* unused pure expression or super */ null && (core.$constructor("ZodVoid", (inst, def) => { - core.$ZodVoid.init(inst, def); - ZodType.init(inst, def); - inst._zod.processJSONSchema = (ctx, json, params) => processors.voidProcessor(inst, ctx, json, params); -}))); -function schemas_void(params) { - return core._void(ZodVoid, params); -} - -const ZodDate = /*@__PURE__*/ (/* unused pure expression or super */ null && (core.$constructor("ZodDate", (inst, def) => { - core.$ZodDate.init(inst, def); - ZodType.init(inst, def); - inst._zod.processJSONSchema = (ctx, json, params) => processors.dateProcessor(inst, ctx, json, params); - inst.min = (value, params) => inst.check(checks.gte(value, params)); - inst.max = (value, params) => inst.check(checks.lte(value, params)); - const c = inst._zod.bag; - inst.minDate = c.minimum ? new Date(c.minimum) : null; - inst.maxDate = c.maximum ? new Date(c.maximum) : null; -}))); -function schemas_date(params) { - return core._date(ZodDate, params); -} -const ZodArray = /*@__PURE__*/ $constructor("ZodArray", (inst, def) => { - _ensureDefaultMemoizer(); - $ZodArray.init(inst, def); - ZodType.init(inst, def); - inst._zod.processJSONSchema = (ctx, json, params) => arrayProcessor(inst, ctx, json, params); - inst.element = def.element; -}, { - min(n, params) { - return this.check(_minLength(n, params)); - }, - nonempty(params) { - return this.check(_minLength(1, params)); - }, - max(n, params) { - return this.check(_maxLength(n, params)); - }, - length(n, params) { - return this.check(_length(n, params)); - }, - unwrap() { - return this.element; - }, -}); -function schemas_array(element, params) { - return _array(ZodArray, element, params); -} -// .keyof -function keyof(schema) { - const shape = schema._zod.def.shape; - return schemas_enum(Object.keys(shape)); -} -const ZodObject = /*@__PURE__*/ $constructor("ZodObject", (inst, def) => { - _ensureDefaultMemoizer(); - $ZodObjectJIT.init(inst, def); - ZodType.init(inst, def); - inst._zod.processJSONSchema = (ctx, json, params) => objectProcessor(inst, ctx, json, params); - installLazyProp(inst, "shape", (self) => self._zod.def.shape, false); -}, { - keyof() { - return schemas_enum(Object.keys(this._zod.def.shape)); - }, - catchall(catchall) { - return this.clone({ ...this._zod.def, catchall: catchall }); - }, - passthrough() { - return this.clone({ ...this._zod.def, catchall: unknown() }); - }, - loose() { - return this.clone({ ...this._zod.def, catchall: unknown() }); - }, - strict() { - return this.clone({ ...this._zod.def, catchall: never() }); - }, - strip() { - return this.clone({ ...this._zod.def, catchall: undefined }); - }, - extend(incoming) { - return extend(this, incoming); - }, - safeExtend(incoming) { - return safeExtend(this, incoming); - }, - merge(other) { - return merge(this, other); - }, - pick(mask) { - return pick(this, mask); - }, - omit(mask) { - return omit(this, mask); - }, - partial(...args) { - return partial(ZodOptional, this, args[0]); - }, - exactPartial(...args) { - return partial(ZodExactOptional, this, args[0], "exactPartial"); - }, - required(...args) { - return util_required(ZodNonOptional, this, args[0]); - }, -}); -function schemas_object(shape, params) { - const def = { - type: "object", - shape: shape ?? {}, - ...normalizeParams(params), - }; - return new ZodObject(def); -} -// strictObject -function strictObject(shape, params) { - return new ZodObject({ - type: "object", - shape, - catchall: never(), - ...util.normalizeParams(params), - }); -} -// looseObject -function looseObject(shape, params) { - return new ZodObject({ - type: "object", - shape, - catchall: unknown(), - ...normalizeParams(params), - }); -} -const ZodUnion = /*@__PURE__*/ $constructor("ZodUnion", (inst, def) => { - $ZodUnion.init(inst, def); - ZodType.init(inst, def); - inst._zod.processJSONSchema = (ctx, json, params) => unionProcessor(inst, ctx, json, params); - inst.options = def.options; -}); -function schemas_union(options, params) { - return new ZodUnion({ - type: "union", - options: options, - ...normalizeParams(params), - }); -} -const ZodXor = /*@__PURE__*/ (/* unused pure expression or super */ null && (core.$constructor("ZodXor", (inst, def) => { - ZodUnion.init(inst, def); - core.$ZodXor.init(inst, def); - inst._zod.processJSONSchema = (ctx, json, params) => processors.unionProcessor(inst, ctx, json, params); - inst.options = def.options; -}))); -/** Creates an exclusive union (XOR) where exactly one option must match. - * Unlike regular unions that succeed when any option matches, xor fails if - * zero or more than one option matches the input. */ -function xor(options, params) { - return new ZodXor({ - type: "union", - options: options, - inclusive: false, - ...util.normalizeParams(params), - }); -} -const ZodDiscriminatedUnion = /*@__PURE__*/ $constructor("ZodDiscriminatedUnion", (inst, def) => { - ZodUnion.init(inst, def); - $ZodDiscriminatedUnion.init(inst, def); -}); -function discriminatedUnion(discriminator, options, params) { - // const [options, params] = args; - return new ZodDiscriminatedUnion({ - type: "union", - options: options, - discriminator, - ...normalizeParams(params), - }); -} -const ZodIntersection = /*@__PURE__*/ $constructor("ZodIntersection", (inst, def) => { - $ZodIntersection.init(inst, def); - ZodType.init(inst, def); - inst._zod.processJSONSchema = (ctx, json, params) => intersectionProcessor(inst, ctx, json, params); -}); -function intersection(left, right) { - return new ZodIntersection({ - type: "intersection", - left: left, - right: right, - }); -} -const ZodTuple = /*@__PURE__*/ (/* unused pure expression or super */ null && (core.$constructor("ZodTuple", (inst, def) => { - _ensureDefaultMemoizer(); - core.$ZodTuple.init(inst, def); - ZodType.init(inst, def); - inst._zod.processJSONSchema = (ctx, json, params) => processors.tupleProcessor(inst, ctx, json, params); -}, { - rest(rest) { - return this.clone({ - ...this._zod.def, - rest: rest, - }); - }, - partial() { - const def = this._zod.def; - // a refinement was authored against the full arity; partialing would run it on a shorter array - if (def.checks?.length) - throw new Error(".partial() cannot be used on tuple schemas containing refinements"); - return this.clone({ - ...def, - items: def.items.map((item) => new ZodOptional({ type: "optional", innerType: item })), - }); - }, -}))); -function tuple(items, _paramsOrRest, _params) { - const hasRest = _paramsOrRest instanceof core.$ZodType; - const params = hasRest ? _params : _paramsOrRest; - const rest = hasRest ? _paramsOrRest : null; - return new ZodTuple({ - type: "tuple", - items: items, - rest, - ...util.normalizeParams(params), - }); -} -const ZodRecord = /*@__PURE__*/ $constructor("ZodRecord", (inst, def) => { - _ensureDefaultMemoizer(); - $ZodRecord.init(inst, def); - ZodType.init(inst, def); - inst._zod.processJSONSchema = (ctx, json, params) => recordProcessor(inst, ctx, json, params); - inst.keyType = def.keyType; - inst.valueType = def.valueType; -}); -function schemas_record(keyType, valueType, params) { - // v3-compat: z.record(valueType, params?) — defaults keyType to z.string() - if (!valueType || !valueType._zod) { - return new ZodRecord({ - type: "record", - keyType: schemas_string(), - valueType: keyType, - ...normalizeParams(valueType), - }); - } - return new ZodRecord({ - type: "record", - keyType, - valueType: valueType, - ...normalizeParams(params), - }); -} -// type alksjf = core.output; -function partialRecord(keyType, valueType, params) { - return new ZodRecord({ - type: "record", - keyType, - valueType: valueType, - ...util.normalizeParams(params), - partial: true, - }); -} -function looseRecord(keyType, valueType, params) { - return new ZodRecord({ - type: "record", - keyType, - valueType: valueType, - mode: "loose", - ...util.normalizeParams(params), - }); -} -const ZodMap = /*@__PURE__*/ (/* unused pure expression or super */ null && (core.$constructor("ZodMap", (inst, def) => { - _ensureDefaultMemoizer(); - core.$ZodMap.init(inst, def); - ZodType.init(inst, def); - inst._zod.processJSONSchema = (ctx, json, params) => processors.mapProcessor(inst, ctx, json, params); - inst.keyType = def.keyType; - inst.valueType = def.valueType; - inst.min = (...args) => inst.check(core._minSize(...args)); - inst.nonempty = (params) => inst.check(core._minSize(1, params)); - inst.max = (...args) => inst.check(core._maxSize(...args)); - inst.size = (...args) => inst.check(core._size(...args)); -}))); -function schemas_map(keyType, valueType, params) { - return new ZodMap({ - type: "map", - keyType: keyType, - valueType: valueType, - ...util.normalizeParams(params), - }); -} -const ZodSet = /*@__PURE__*/ (/* unused pure expression or super */ null && (core.$constructor("ZodSet", (inst, def) => { - _ensureDefaultMemoizer(); - core.$ZodSet.init(inst, def); - ZodType.init(inst, def); - inst._zod.processJSONSchema = (ctx, json, params) => processors.setProcessor(inst, ctx, json, params); - inst.min = (...args) => inst.check(core._minSize(...args)); - inst.nonempty = (params) => inst.check(core._minSize(1, params)); - inst.max = (...args) => inst.check(core._maxSize(...args)); - inst.size = (...args) => inst.check(core._size(...args)); -}))); -function schemas_set(valueType, params) { - return new ZodSet({ - type: "set", - valueType: valueType, - ...util.normalizeParams(params), - }); -} -const ZodEnum = /*@__PURE__*/ $constructor("ZodEnum", (inst, def) => { - $ZodEnum.init(inst, def); - ZodType.init(inst, def); - inst._zod.processJSONSchema = (ctx, json, params) => enumProcessor(inst, ctx, json, params); - inst.enum = def.entries; - inst.options = Object.values(def.entries); - const keys = new Set(Object.keys(def.entries)); - inst.extract = (values, params) => { - const newEntries = {}; - for (const value of values) { - if (keys.has(value)) { - newEntries[value] = def.entries[value]; - } - else - throw new Error(`Key ${value} not found in enum`); - } - return new ZodEnum({ - ...def, - checks: [], - ...normalizeParams(params), - entries: newEntries, - }); - }; - inst.exclude = (values, params) => { - const newEntries = { ...def.entries }; - for (const value of values) { - if (keys.has(value)) { - delete newEntries[value]; - } - else - throw new Error(`Key ${value} not found in enum`); - } - return new ZodEnum({ - ...def, - checks: [], - ...normalizeParams(params), - entries: newEntries, - }); - }; -}); -function schemas_enum(values, params) { - const entries = Array.isArray(values) ? Object.fromEntries(values.map((v) => [v, v])) : values; - return new ZodEnum({ - type: "enum", - entries, - ...normalizeParams(params), - }); -} - -/** @deprecated This API has been merged into `z.enum()`. Use `z.enum()` instead. - * - * ```ts - * enum Colors { red, green, blue } - * z.enum(Colors); - * ``` - */ -function nativeEnum(entries, params) { - return new ZodEnum({ - type: "enum", - entries, - ...util.normalizeParams(params), - }); -} -const ZodLiteral = /*@__PURE__*/ $constructor("ZodLiteral", (inst, def) => { - $ZodLiteral.init(inst, def); - ZodType.init(inst, def); - inst._zod.processJSONSchema = (ctx, json, params) => literalProcessor(inst, ctx, json, params); - inst.values = new Set(def.values); - Object.defineProperty(inst, "value", { - get() { - if (def.values.length > 1) { - throw new Error("This schema contains multiple valid literal values. Use `.values` instead."); - } - return def.values[0]; - }, - }); -}); -function literal(value, params) { - return new ZodLiteral({ - type: "literal", - values: Array.isArray(value) ? value : [value], - ...normalizeParams(params), - }); -} -const ZodFile = /*@__PURE__*/ (/* unused pure expression or super */ null && (core.$constructor("ZodFile", (inst, def) => { - core.$ZodFile.init(inst, def); - ZodType.init(inst, def); - inst._zod.processJSONSchema = (ctx, json, params) => processors.fileProcessor(inst, ctx, json, params); - inst.min = (size, params) => inst.check(core._minSize(size, params)); - inst.max = (size, params) => inst.check(core._maxSize(size, params)); - inst.mime = (types, params) => inst.check(core._mime(Array.isArray(types) ? types : [types], params)); -}))); -function schemas_file(params) { - return core._file(ZodFile, params); -} -const ZodTransform = /*@__PURE__*/ $constructor("ZodTransform", (inst, def) => { - _ensureDefaultMemoizer(); - $ZodTransform.init(inst, def); - ZodType.init(inst, def); - inst._zod.processJSONSchema = (ctx, json, params) => transformProcessor(inst, ctx, json, params); - inst._zod.parse = (payload, _ctx) => { - if (_ctx.direction === "backward") { - throw new $ZodEncodeError(inst.constructor.name); - } - payload.addIssue = (issue) => { - if (typeof issue === "string") { - payload.issues.push(util_issue(issue, payload.value, def)); - } - else { - // for Zod 3 backwards compatibility - const _issue = issue; - if (_issue.fatal) - _issue.continue = false; - _issue.code ?? (_issue.code = "custom"); - if (!("input" in _issue)) - _issue.input = payload.value; - _issue.inst ?? (_issue.inst = inst); - // _issue.continue ??= true; - payload.issues.push(util_issue(_issue)); - } - }; - const output = def.transform(payload.value, payload); - if (output instanceof Promise) { - return output.then((output) => { - payload.value = output; - return payload; - }); - } - payload.value = output; - return payload; - }; -}); -function transform(fn) { - return new ZodTransform({ - type: "transform", - transform: fn, - }); -} -const ZodOptional = /*@__PURE__*/ $constructor("ZodOptional", (inst, def) => { - $ZodOptional.init(inst, def); - ZodType.init(inst, def); - inst._zod.processJSONSchema = (ctx, json, params) => optionalProcessor(inst, ctx, json, params); - inst.unwrap = () => inst._zod.def.innerType; -}); -function schemas_optional(innerType) { - return new ZodOptional({ - type: "optional", - innerType: innerType, - }); -} -const ZodExactOptional = /*@__PURE__*/ $constructor("ZodExactOptional", (inst, def) => { - $ZodExactOptional.init(inst, def); - ZodType.init(inst, def); - inst._zod.processJSONSchema = (ctx, json, params) => optionalProcessor(inst, ctx, json, params); - inst.unwrap = () => inst._zod.def.innerType; -}); -function exactOptional(innerType) { - return new ZodExactOptional({ - type: "optional", - innerType: innerType, - }); -} -const ZodNullable = /*@__PURE__*/ $constructor("ZodNullable", (inst, def) => { - $ZodNullable.init(inst, def); - ZodType.init(inst, def); - inst._zod.processJSONSchema = (ctx, json, params) => nullableProcessor(inst, ctx, json, params); - inst.unwrap = () => inst._zod.def.innerType; -}); -function nullable(innerType) { - return new ZodNullable({ - type: "nullable", - innerType: innerType, - }); -} -// nullish -function schemas_nullish(innerType) { - return schemas_optional(nullable(innerType)); -} -const ZodDefault = /*@__PURE__*/ $constructor("ZodDefault", (inst, def) => { - $ZodDefault.init(inst, def); - ZodType.init(inst, def); - inst._zod.processJSONSchema = (ctx, json, params) => defaultProcessor(inst, ctx, json, params); - inst.unwrap = () => inst._zod.def.innerType; - inst.removeDefault = inst.unwrap; -}); -function schemas_default(innerType, defaultValue) { - return new ZodDefault({ - type: "default", - innerType: innerType, - get defaultValue() { - return typeof defaultValue === "function" ? defaultValue() : shallowClone(defaultValue); - }, - }); -} -const ZodPrefault = /*@__PURE__*/ $constructor("ZodPrefault", (inst, def) => { - $ZodPrefault.init(inst, def); - ZodType.init(inst, def); - inst._zod.processJSONSchema = (ctx, json, params) => prefaultProcessor(inst, ctx, json, params); - inst.unwrap = () => inst._zod.def.innerType; -}); -function prefault(innerType, defaultValue) { - return new ZodPrefault({ - type: "prefault", - innerType: innerType, - get defaultValue() { - return typeof defaultValue === "function" ? defaultValue() : shallowClone(defaultValue); - }, - }); -} -const ZodNonOptional = /*@__PURE__*/ $constructor("ZodNonOptional", (inst, def) => { - $ZodNonOptional.init(inst, def); - ZodType.init(inst, def); - inst._zod.processJSONSchema = (ctx, json, params) => nonoptionalProcessor(inst, ctx, json, params); - inst.unwrap = () => inst._zod.def.innerType; -}); -function nonoptional(innerType, params) { - return new ZodNonOptional({ - type: "nonoptional", - innerType: innerType, - ...normalizeParams(params), - }); -} -const ZodSuccess = /*@__PURE__*/ (/* unused pure expression or super */ null && (core.$constructor("ZodSuccess", (inst, def) => { - core.$ZodSuccess.init(inst, def); - ZodType.init(inst, def); - inst._zod.processJSONSchema = (ctx, json, params) => processors.successProcessor(inst, ctx, json, params); - inst.unwrap = () => inst._zod.def.innerType; -}))); -function success(innerType) { - return new ZodSuccess({ - type: "success", - innerType: innerType, - }); -} -const ZodCatch = /*@__PURE__*/ $constructor("ZodCatch", (inst, def) => { - $ZodCatch.init(inst, def); - ZodType.init(inst, def); - inst._zod.processJSONSchema = (ctx, json, params) => catchProcessor(inst, ctx, json, params); - inst.unwrap = () => inst._zod.def.innerType; - inst.removeCatch = inst.unwrap; -}); -function schemas_catch(innerType, catchValue) { - return new ZodCatch({ - type: "catch", - innerType: innerType, - catchValue: (typeof catchValue === "function" ? catchValue : constantCatch(catchValue)), - }); -} - -const ZodNaN = /*@__PURE__*/ (/* unused pure expression or super */ null && (core.$constructor("ZodNaN", (inst, def) => { - core.$ZodNaN.init(inst, def); - ZodType.init(inst, def); - inst._zod.processJSONSchema = (ctx, json, params) => processors.nanProcessor(inst, ctx, json, params); -}))); -function nan(params) { - return core._nan(ZodNaN, params); -} -const ZodPipe = /*@__PURE__*/ $constructor("ZodPipe", (inst, def) => { - $ZodPipe.init(inst, def); - ZodType.init(inst, def); - inst._zod.processJSONSchema = (ctx, json, params) => pipeProcessor(inst, ctx, json, params); - inst.in = def.in; - inst.out = def.out; -}); -function pipe(in_, out) { - return new ZodPipe({ - type: "pipe", - in: in_, - out: out, - // ...util.normalizeParams(params), - }); -} -const ZodCodec = /*@__PURE__*/ (/* unused pure expression or super */ null && (core.$constructor("ZodCodec", (inst, def) => { - ZodPipe.init(inst, def); - core.$ZodCodec.init(inst, def); -}))); -function schemas_codec(in_, out, params) { - return new ZodCodec({ - type: "pipe", - in: in_, - out: out, - transform: params.decode, - reverseTransform: params.encode, - }); -} -function invertCodec(codec) { - const def = codec._zod.def; - return new ZodCodec({ - type: "pipe", - in: def.out, - out: def.in, - transform: def.reverseTransform, - reverseTransform: def.transform, - }); -} -const ZodPreprocess = /*@__PURE__*/ $constructor("ZodPreprocess", (inst, def) => { - ZodPipe.init(inst, def); - $ZodPreprocess.init(inst, def); -}); -const ZodReadonly = /*@__PURE__*/ $constructor("ZodReadonly", (inst, def) => { - $ZodReadonly.init(inst, def); - ZodType.init(inst, def); - inst._zod.processJSONSchema = (ctx, json, params) => readonlyProcessor(inst, ctx, json, params); - inst.unwrap = () => inst._zod.def.innerType; -}); -function readonly(innerType) { - return new ZodReadonly({ - type: "readonly", - innerType: innerType, - }); -} -const ZodTemplateLiteral = /*@__PURE__*/ (/* unused pure expression or super */ null && (core.$constructor("ZodTemplateLiteral", (inst, def) => { - core.$ZodTemplateLiteral.init(inst, def); - ZodType.init(inst, def); - inst._zod.processJSONSchema = (ctx, json, params) => processors.templateLiteralProcessor(inst, ctx, json, params); -}))); -function templateLiteral(parts, params) { - return new ZodTemplateLiteral({ - type: "template_literal", - parts, - ...util.normalizeParams(params), - }); -} -const ZodLazy = /*@__PURE__*/ $constructor("ZodLazy", (inst, def) => { - $ZodLazy.init(inst, def); - ZodType.init(inst, def); - inst._zod.processJSONSchema = (ctx, json, params) => lazyProcessor(inst, ctx, json, params); - inst.unwrap = () => inst._zod.def.getter(); -}); -function lazy(getter) { - return new ZodLazy({ - type: "lazy", - getter: getter, - }); -} -const ZodPromise = /*@__PURE__*/ (/* unused pure expression or super */ null && (core.$constructor("ZodPromise", (inst, def) => { - core.$ZodPromise.init(inst, def); - ZodType.init(inst, def); - inst._zod.processJSONSchema = (ctx, json, params) => processors.promiseProcessor(inst, ctx, json, params); - inst.unwrap = () => inst._zod.def.innerType; -}))); -function schemas_promise(innerType) { - return new ZodPromise({ - type: "promise", - innerType: innerType, - }); -} -const ZodFunction = /*@__PURE__*/ (/* unused pure expression or super */ null && (core.$constructor("ZodFunction", (inst, def) => { - core.$ZodFunction.init(inst, def); - ZodType.init(inst, def); - inst._zod.processJSONSchema = (ctx, json, params) => processors.functionProcessor(inst, ctx, json, params); -}))); -function _function(params) { - return new ZodFunction({ - type: "function", - input: Array.isArray(params?.input) ? tuple(params?.input) : (params?.input ?? schemas_array(unknown())), - output: params?.output ?? unknown(), - }); -} - -const ZodCustom = /*@__PURE__*/ $constructor("ZodCustom", (inst, def) => { - $ZodCustom.init(inst, def); - ZodType.init(inst, def); - inst._zod.processJSONSchema = (ctx, json, params) => customProcessor(inst, ctx, json, params); -}); -// custom checks -function schemas_check(fn) { - const ch = new core.$ZodCheck({ - check: "custom", - // ...util.normalizeParams(params), - }); - ch._zod.check = fn; - return ch; -} -function custom(fn, _params) { - return core._custom(ZodCustom, fn ?? (() => true), _params); -} -function refine(fn, _params = {}) { - return _refine(ZodCustom, fn, _params); -} -// superRefine -function superRefine(fn, params) { - return _superRefine(fn, params); -} -// Re-export describe and meta from core -const schemas_describe = describe; -const schemas_meta = api_meta; -function _instanceof(cls, params = {}) { - const inst = new ZodCustom({ - type: "custom", - check: "custom", - fn: (data) => data instanceof cls, - abort: true, - ...util.normalizeParams(params), - }); - inst._zod.bag.Class = cls; - // Override check to emit invalid_type instead of custom - inst._zod.check = (payload) => { - if (!(payload.value instanceof cls)) { - payload.issues.push({ - code: "invalid_type", - expected: cls.name, - input: payload.value, - inst, - path: [...(inst._zod.def.path ?? [])], - }); - } - }; - return inst; -} - -// stringbool -const stringbool = (...args) => core._stringbool({ - Codec: ZodCodec, - Boolean: ZodBoolean, - String: ZodString, -}, ...args); -function schemas_json(params) { - const jsonSchema = lazy(() => { - return schemas_union([schemas_string(params), schemas_number(), schemas_boolean(), schemas_null(), schemas_array(jsonSchema), schemas_record(schemas_string(), jsonSchema)]); - }); - return jsonSchema; -} -// preprocess -function preprocess(fn, schema) { - return new ZodPreprocess({ - type: "pipe", - in: transform(fn), - out: schema, - }); -} - - - - -function iso_datetime(params) { - return _isoDateTime(ZodISODateTime, params); -} -function iso_date(params) { - return _isoDate(ZodISODate, params); -} -function iso_time(params) { - return core._isoTime(ZodISOTime, params); -} -function iso_duration(params) { - return core._isoDuration(ZodISODuration, params); -} - -// Zod 3 compat layer - -/** @deprecated Use the raw string literal codes instead, e.g. "invalid_type". */ -const ZodIssueCode = { - 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", -}; - -/** @deprecated Use `z.config(params)` instead. */ -function setErrorMap(map) { - core.config({ - customError: map, - }); -} -/** @deprecated Use `z.config()` instead. */ -function getErrorMap() { - return core.config().customError; -} -/** @deprecated Do not use. Stub definition, only included for zod-to-json-schema compatibility. */ -var compat_ZodFirstPartyTypeKind; -(function (ZodFirstPartyTypeKind) { -})(compat_ZodFirstPartyTypeKind || (compat_ZodFirstPartyTypeKind = {})); - - - -function coerce_string(params) { - return core._coercedString(schemas.ZodString, params); -} -function coerce_number(params) { - return _coercedNumber(ZodNumber, params); -} -function coerce_boolean(params) { - return core._coercedBoolean(schemas.ZodBoolean, params); -} -function coerce_bigint(params) { - return core._coercedBigint(schemas.ZodBigInt, params); -} -function coerce_date(params) { - return core._coercedDate(schemas.ZodDate, params); -} - - - -//#region src/constants.ts -const LATEST_PROTOCOL_VERSION = "2025-11-25"; -const auth_CUe6YdwF_DEFAULT_NEGOTIATED_PROTOCOL_VERSION = "2025-03-26"; -const auth_CUe6YdwF_SUPPORTED_PROTOCOL_VERSIONS = [ - LATEST_PROTOCOL_VERSION, - "2025-06-18", - "2025-03-26", - "2024-11-05", - "2024-10-07" -]; -/** -* `_meta` key associating a message with a 2025-11-25 task. -* -* @deprecated 2025-11-25 wire vocabulary with no SDK runtime; kept importable for interoperability only. -*/ -const RELATED_TASK_META_KEY = "io.modelcontextprotocol/related-task"; -/** -* `_meta` key carrying the MCP protocol version governing a request. -* -* For the HTTP transport, the value must match the `MCP-Protocol-Version` header. -*/ -const auth_CUe6YdwF_PROTOCOL_VERSION_META_KEY = "io.modelcontextprotocol/protocolVersion"; -/** -* `_meta` key identifying the client software making a request. -* -* Clients SHOULD include it on every request; the value is self-reported and -* intended for display, logging, and debugging — servers should not rely on -* it for behavior or security decisions. -*/ -const auth_CUe6YdwF_CLIENT_INFO_META_KEY = "io.modelcontextprotocol/clientInfo"; -/** -* `_meta` key identifying the server software producing a response. -* -* Servers SHOULD include it on every response; the value is self-reported and -* intended for display, logging, and debugging — clients should not rely on -* it for behavior or security decisions. -*/ -const auth_CUe6YdwF_SERVER_INFO_META_KEY = "io.modelcontextprotocol/serverInfo"; -/** -* `_meta` key carrying the client's capabilities for a request. -* -* Capabilities are declared per request rather than once at initialization; -* servers must not infer capabilities from prior requests. -*/ -const auth_CUe6YdwF_CLIENT_CAPABILITIES_META_KEY = "io.modelcontextprotocol/clientCapabilities"; -/** -* `_meta` key carrying the JSON-RPC ID of the `subscriptions/listen` request -* that opened the stream a notification was delivered on. -* -* Stamped by the server on every notification delivered via a -* `subscriptions/listen` stream (including the leading -* `notifications/subscriptions/acknowledged`); on stdio, where all messages -* share one channel, clients use it to correlate notifications with their -* originating subscription. The value is the listen request's JSON-RPC ID -* verbatim. -*/ -const auth_CUe6YdwF_SUBSCRIPTION_ID_META_KEY = "io.modelcontextprotocol/subscriptionId"; -/** -* `_meta` key carrying the desired log level for a request. -* -* When absent, the server must not send `notifications/message` notifications -* for the request. -* -* @deprecated Deprecated as of protocol version 2026-07-28 (SEP-2577); remains -* in the specification for at least twelve months. -*/ -const LOG_LEVEL_META_KEY = "io.modelcontextprotocol/logLevel"; -/** -* `_meta` key carrying W3C Trace Context for distributed tracing (SEP-414). -* -* When present, the value MUST follow the W3C `traceparent` header format, -* e.g. `00-4bf92f3577b34da6a3ce929d0e0e4736-00f067aa0ba902b7-01`. -* -* @see https://www.w3.org/TR/trace-context/#traceparent-header -*/ -const TRACEPARENT_META_KEY = "traceparent"; -/** -* `_meta` key carrying vendor-specific trace state for distributed tracing (SEP-414). -* -* When present, the value MUST follow the W3C `tracestate` header format, -* e.g. `vendor1=value1,vendor2=value2`. -* -* @see https://www.w3.org/TR/trace-context/#tracestate-header -*/ -const TRACESTATE_META_KEY = "tracestate"; -/** -* `_meta` key carrying cross-cutting propagation values for distributed tracing (SEP-414). -* -* When present, the value MUST follow the W3C Baggage header format, -* e.g. `userId=alice,serverRegion=us-east-1`. -* -* @see https://www.w3.org/TR/baggage/ -*/ -const BAGGAGE_META_KEY = "baggage"; -const JSONRPC_VERSION = "2.0"; -const PARSE_ERROR = (/* unused pure expression or super */ null && (-32700)); -const INVALID_REQUEST = (/* unused pure expression or super */ null && (-32600)); -const METHOD_NOT_FOUND = (/* unused pure expression or super */ null && (-32601)); -const INVALID_PARAMS = (/* unused pure expression or super */ null && (-32602)); -const INTERNAL_ERROR = (/* unused pure expression or super */ null && (-32603)); - -//#endregion -//#region src/schemas.ts -const JSONValueSchema = lazy(() => schemas_union([ - schemas_string(), - schemas_number(), - schemas_boolean(), - schemas_null(), - schemas_record(schemas_string(), JSONValueSchema), - schemas_array(JSONValueSchema) -])); -const JSONObjectSchema = schemas_record(schemas_string(), JSONValueSchema); -const JSONArraySchema = schemas_array(JSONValueSchema); -/** -* A progress token, used to associate progress notifications with the original request. -*/ -const ProgressTokenSchema = schemas_union([schemas_string(), schemas_number().int()]); -/** -* An opaque token used to represent a cursor for pagination. -*/ -const CursorSchema = schemas_string(); -/** @deprecated 2025-11-25 wire vocabulary with no SDK runtime; kept importable for interoperability only. */ -const TaskMetadataSchema = schemas_object({ ttl: schemas_number().optional() }); -/** -* Metadata for associating messages with a task. -* Include this in the `_meta` field under the key `io.modelcontextprotocol/related-task`. -* -* @deprecated 2025-11-25 wire vocabulary with no SDK runtime; kept importable for interoperability only. -*/ -const RelatedTaskMetadataSchema = schemas_object({ taskId: schemas_string() }); -const RequestMetaSchema = looseObject({ - progressToken: ProgressTokenSchema.optional(), - [RELATED_TASK_META_KEY]: RelatedTaskMetadataSchema.optional() -}); -/** -* Common params for any request. -*/ -const BaseRequestParamsSchema = schemas_object({ _meta: RequestMetaSchema.optional() }); -/** -* Common params for any task-augmented request. -* -* @deprecated 2025-11-25 wire vocabulary with no SDK runtime; kept importable for interoperability only. -*/ -const auth_CUe6YdwF_TaskAugmentedRequestParamsSchema = BaseRequestParamsSchema.extend({ task: TaskMetadataSchema.optional() }); -const RequestSchema = schemas_object({ - method: schemas_string(), - params: BaseRequestParamsSchema.loose().optional() -}); -const NotificationsParamsSchema = schemas_object({ _meta: RequestMetaSchema.optional() }); -const NotificationSchema = schemas_object({ - method: schemas_string(), - params: NotificationsParamsSchema.loose().optional() -}); -/** -* The contents of a result's `_meta` field (the 2026-07-28 `ResultMetaObject`). -* Loose — implementation-specific keys pass through. -* -* The serverInfo key identifies the server software producing the response -* (servers SHOULD include it on every response; the value is self-reported -* and intended for display, logging, and debugging). The getter defers the -* `ImplementationSchema` reference, which is declared later in this file. -*/ -const ResultMetaObjectSchema = looseObject({ get [auth_CUe6YdwF_SERVER_INFO_META_KEY]() { - return ImplementationSchema.optional().catch(void 0); -} }); -const ResultSchema = looseObject({ _meta: ResultMetaObjectSchema.optional() }); -/** -* A uniquely identifying ID for a request in JSON-RPC. -*/ -const RequestIdSchema = schemas_union([schemas_string(), schemas_number().int()]); -/** -* A request that expects a response. -*/ -const JSONRPCRequestSchema = schemas_object({ - jsonrpc: literal(JSONRPC_VERSION), - id: RequestIdSchema, - ...RequestSchema.shape -}).strict(); -/** -* A notification which does not expect a response. -*/ -const JSONRPCNotificationSchema = schemas_object({ - jsonrpc: literal(JSONRPC_VERSION), - ...NotificationSchema.shape -}).strict(); -/** -* A successful (non-error) response to a request. -*/ -const JSONRPCResultResponseSchema = schemas_object({ - jsonrpc: literal(JSONRPC_VERSION), - id: RequestIdSchema, - result: ResultSchema -}).strict(); -/** -* A response to a request that indicates an error occurred. -*/ -const JSONRPCErrorResponseSchema = schemas_object({ - jsonrpc: literal(JSONRPC_VERSION), - id: RequestIdSchema.optional(), - error: schemas_object({ - code: schemas_number().int(), - message: schemas_string(), - data: unknown().optional() - }) -}).strict(); -const auth_CUe6YdwF_JSONRPCMessageSchema = schemas_union([ - JSONRPCRequestSchema, - JSONRPCNotificationSchema, - JSONRPCResultResponseSchema, - JSONRPCErrorResponseSchema -]); -const auth_CUe6YdwF_JSONRPCResponseSchema = schemas_union([JSONRPCResultResponseSchema, JSONRPCErrorResponseSchema]); -/** -* A response that indicates success but carries no data. -*/ -const EmptyResultSchema = ResultSchema.strict(); -const CancelledNotificationParamsSchema = NotificationsParamsSchema.extend({ - requestId: RequestIdSchema.optional(), - reason: schemas_string().optional() -}); -/** -* This notification can be sent by either side to indicate that it is cancelling a previously-issued request. -* -* The request SHOULD still be in-flight, but due to communication latency, it is always possible that this notification MAY arrive after the request has already finished. -* -* This notification indicates that the result will be unused, so any associated processing SHOULD cease. -* -* A client MUST NOT attempt to cancel its {@linkcode InitializeRequest | initialize} request. -*/ -const CancelledNotificationSchema = NotificationSchema.extend({ - method: literal("notifications/cancelled"), - params: CancelledNotificationParamsSchema -}); -/** -* Icon schema for use in {@link Tool | tools}, {@link Prompt | prompts}, {@link Resource | resources}, and {@link Implementation | implementations}. -*/ -const IconSchema = schemas_object({ - src: schemas_string(), - mimeType: schemas_string().optional(), - sizes: schemas_array(schemas_string()).optional(), - theme: schemas_enum(["light", "dark"]).optional() -}); -/** -* Base schema to add `icons` property. -* -*/ -const IconsSchema = schemas_object({ icons: schemas_array(IconSchema).optional() }); -/** -* Base metadata interface for common properties across {@link Resource | resources}, {@link Tool | tools}, {@link Prompt | prompts}, and {@link Implementation | implementations}. -*/ -const BaseMetadataSchema = schemas_object({ - name: schemas_string(), - title: schemas_string().optional() -}); -/** -* Describes the name and version of an MCP implementation. -*/ -const ImplementationSchema = BaseMetadataSchema.extend({ - ...BaseMetadataSchema.shape, - ...IconsSchema.shape, - version: schemas_string(), - websiteUrl: schemas_string().optional(), - description: schemas_string().optional() -}); -const auth_CUe6YdwF_FormElicitationCapabilitySchema = intersection(schemas_object({ applyDefaults: schemas_boolean().optional() }), JSONObjectSchema); -const auth_CUe6YdwF_ElicitationCapabilitySchema = preprocess((value) => { - if (value && typeof value === "object" && !Array.isArray(value) && Object.keys(value).length === 0) return { form: {} }; - return value; -}, intersection(schemas_object({ - form: auth_CUe6YdwF_FormElicitationCapabilitySchema.optional(), - url: JSONObjectSchema.optional() -}), JSONObjectSchema.optional())); -/** -* Task capabilities for clients, indicating which request types support task creation. -* -* @deprecated 2025-11-25 wire vocabulary with no SDK runtime; kept importable for interoperability only. -*/ -const ClientTasksCapabilitySchema = looseObject({ - list: JSONObjectSchema.optional(), - cancel: JSONObjectSchema.optional(), - requests: looseObject({ - sampling: looseObject({ createMessage: JSONObjectSchema.optional() }).optional(), - elicitation: looseObject({ create: JSONObjectSchema.optional() }).optional() - }).optional() -}); -/** -* Task capabilities for servers, indicating which request types support task creation. -* -* @deprecated 2025-11-25 wire vocabulary with no SDK runtime; kept importable for interoperability only. -*/ -const ServerTasksCapabilitySchema = looseObject({ - list: JSONObjectSchema.optional(), - cancel: JSONObjectSchema.optional(), - requests: looseObject({ tools: looseObject({ call: JSONObjectSchema.optional() }).optional() }).optional() -}); -/** -* Capabilities a client may support. Known capabilities are defined here, in this schema, but this is not a closed set: any client can define its own, additional capabilities. -*/ -const ClientCapabilitiesSchema = schemas_object({ - experimental: schemas_record(schemas_string(), JSONObjectSchema).optional(), - sampling: schemas_object({ - context: JSONObjectSchema.optional(), - tools: JSONObjectSchema.optional() - }).optional(), - elicitation: auth_CUe6YdwF_ElicitationCapabilitySchema.optional(), - roots: schemas_object({ listChanged: schemas_boolean().optional() }).optional(), - tasks: ClientTasksCapabilitySchema.optional(), - extensions: schemas_record(schemas_string(), JSONObjectSchema).optional() -}); -const InitializeRequestParamsSchema = BaseRequestParamsSchema.extend({ - protocolVersion: schemas_string(), - capabilities: ClientCapabilitiesSchema, - clientInfo: ImplementationSchema -}); -/** -* This request is sent from the client to the server when it first connects, asking it to begin initialization. -*/ -const auth_CUe6YdwF_InitializeRequestSchema = RequestSchema.extend({ - method: literal("initialize"), - params: InitializeRequestParamsSchema -}); -/** -* Capabilities that a server may support. Known capabilities are defined here, in this schema, but this is not a closed set: any server can define its own, additional capabilities. -*/ -const ServerCapabilitiesSchema = schemas_object({ - experimental: schemas_record(schemas_string(), JSONObjectSchema).optional(), - logging: JSONObjectSchema.optional(), - completions: JSONObjectSchema.optional(), - prompts: schemas_object({ listChanged: schemas_boolean().optional() }).optional(), - resources: schemas_object({ - subscribe: schemas_boolean().optional(), - listChanged: schemas_boolean().optional() - }).optional(), - tools: schemas_object({ listChanged: schemas_boolean().optional() }).optional(), - tasks: ServerTasksCapabilitySchema.optional(), - extensions: schemas_record(schemas_string(), JSONObjectSchema).optional() -}); -/** -* After receiving an initialize request from the client, the server sends this response. -*/ -const InitializeResultSchema = ResultSchema.extend({ - protocolVersion: schemas_string(), - capabilities: ServerCapabilitiesSchema, - serverInfo: ImplementationSchema, - instructions: schemas_string().optional() -}); -/** -* This notification is sent from the client to the server after initialization has finished. -*/ -const auth_CUe6YdwF_InitializedNotificationSchema = NotificationSchema.extend({ - method: literal("notifications/initialized"), - params: NotificationsParamsSchema.optional() -}); -/** -* A request from the client asking the server to advertise its supported protocol -* versions, capabilities, and other metadata (protocol revision 2026-07-28). Servers -* MUST implement `server/discover`. Clients MAY call it but are not required to — -* version negotiation can also happen inline via the per-request `_meta` envelope. -*/ -const DiscoverRequestSchema = RequestSchema.extend({ - method: literal("server/discover"), - params: BaseRequestParamsSchema.optional() -}); -/** -* The result returned by the server for a `server/discover` request. -*/ -const DiscoverResultSchema = ResultSchema.extend({ - supportedVersions: schemas_array(schemas_string()), - capabilities: ServerCapabilitiesSchema, - instructions: schemas_string().optional() -}); -/** -* A ping, issued by either the server or the client, to check that the other party is still alive. The receiver must promptly respond, or else may be disconnected. -*/ -const PingRequestSchema = RequestSchema.extend({ - method: literal("ping"), - params: BaseRequestParamsSchema.optional() -}); -const ProgressSchema = schemas_object({ - progress: schemas_number(), - total: schemas_optional(schemas_number()), - message: schemas_optional(schemas_string()) -}); -const ProgressNotificationParamsSchema = schemas_object({ - ...NotificationsParamsSchema.shape, - ...ProgressSchema.shape, - progressToken: ProgressTokenSchema -}); -/** -* An out-of-band notification used to inform the receiver of a progress update for a long-running request. -* -* @category notifications/progress -*/ -const ProgressNotificationSchema = NotificationSchema.extend({ - method: literal("notifications/progress"), - params: ProgressNotificationParamsSchema -}); -const PaginatedRequestParamsSchema = BaseRequestParamsSchema.extend({ cursor: CursorSchema.optional() }); -const PaginatedRequestSchema = RequestSchema.extend({ params: PaginatedRequestParamsSchema.optional() }); -const PaginatedResultSchema = ResultSchema.extend({ nextCursor: CursorSchema.optional() }); -/** -* The contents of a specific resource or sub-resource. -*/ -const ResourceContentsSchema = schemas_object({ - uri: schemas_string(), - mimeType: schemas_optional(schemas_string()), - _meta: schemas_record(schemas_string(), unknown()).optional() -}); -const TextResourceContentsSchema = ResourceContentsSchema.extend({ text: schemas_string() }); -/** -* A Zod schema for validating Base64 strings that is more performant and -* robust for very large inputs than the default regex-based check. It avoids -* stack overflows by using the native `atob` function for validation. -*/ -const auth_CUe6YdwF_Base64Schema = schemas_string().refine((val) => { - try { - atob(val); - return true; - } catch { - return false; - } -}, { message: "Invalid Base64 string" }); -const BlobResourceContentsSchema = ResourceContentsSchema.extend({ blob: auth_CUe6YdwF_Base64Schema }); -/** -* The sender or recipient of messages and data in a conversation. -*/ -const RoleSchema = schemas_enum(["user", "assistant"]); -/** -* Optional annotations providing clients additional context about a resource. -*/ -const AnnotationsSchema = schemas_object({ - audience: schemas_array(RoleSchema).optional(), - priority: schemas_number().min(0).max(1).optional(), - lastModified: iso_datetime({ offset: true }).optional() -}); -/** -* A known resource that the server is capable of reading. -*/ -const ResourceSchema = schemas_object({ - ...BaseMetadataSchema.shape, - ...IconsSchema.shape, - uri: schemas_string(), - description: schemas_optional(schemas_string()), - mimeType: schemas_optional(schemas_string()), - size: schemas_optional(schemas_number()), - annotations: AnnotationsSchema.optional(), - _meta: schemas_optional(looseObject({})) -}); -/** -* A template description for resources available on the server. -*/ -const ResourceTemplateSchema = schemas_object({ - ...BaseMetadataSchema.shape, - ...IconsSchema.shape, - uriTemplate: schemas_string(), - description: schemas_optional(schemas_string()), - mimeType: schemas_optional(schemas_string()), - annotations: AnnotationsSchema.optional(), - _meta: schemas_optional(looseObject({})) -}); -/** -* Sent from the client to request a list of resources the server has. -*/ -const ListResourcesRequestSchema = PaginatedRequestSchema.extend({ method: literal("resources/list") }); -/** -* The server's response to a {@linkcode ListResourcesRequest | resources/list} request from the client. -*/ -const ListResourcesResultSchema = PaginatedResultSchema.extend({ resources: schemas_array(ResourceSchema) }); -/** -* Sent from the client to request a list of resource templates the server has. -*/ -const ListResourceTemplatesRequestSchema = PaginatedRequestSchema.extend({ method: literal("resources/templates/list") }); -/** -* The server's response to a {@linkcode ListResourceTemplatesRequest | resources/templates/list} request from the client. -*/ -const ListResourceTemplatesResultSchema = PaginatedResultSchema.extend({ resourceTemplates: schemas_array(ResourceTemplateSchema) }); -const ResourceRequestParamsSchema = BaseRequestParamsSchema.extend({ uri: schemas_string() }); -/** -* Parameters for a {@linkcode ReadResourceRequest | resources/read} request. -*/ -const ReadResourceRequestParamsSchema = ResourceRequestParamsSchema; -/** -* Sent from the client to the server, to read a specific resource URI. -*/ -const ReadResourceRequestSchema = RequestSchema.extend({ - method: literal("resources/read"), - params: ReadResourceRequestParamsSchema -}); -/** -* The server's response to a {@linkcode ReadResourceRequest | resources/read} request from the client. -*/ -const ReadResourceResultSchema = ResultSchema.extend({ contents: schemas_array(schemas_union([TextResourceContentsSchema, BlobResourceContentsSchema])) }); -/** -* An optional notification from the server to the client, informing it that the list of resources it can read from has changed. This may be issued by servers without any previous subscription from the client. -*/ -const ResourceListChangedNotificationSchema = NotificationSchema.extend({ - method: literal("notifications/resources/list_changed"), - params: NotificationsParamsSchema.optional() -}); -const SubscribeRequestParamsSchema = ResourceRequestParamsSchema; -/** -* Sent from the client to request `resources/updated` notifications from the server whenever a particular resource changes. -*/ -const SubscribeRequestSchema = RequestSchema.extend({ - method: literal("resources/subscribe"), - params: SubscribeRequestParamsSchema -}); -const UnsubscribeRequestParamsSchema = ResourceRequestParamsSchema; -/** -* Sent from the client to request cancellation of {@linkcode ResourceUpdatedNotification | resources/updated} notifications from the server. This should follow a previous {@linkcode SubscribeRequest | resources/subscribe} request. -*/ -const UnsubscribeRequestSchema = RequestSchema.extend({ - method: literal("resources/unsubscribe"), - params: UnsubscribeRequestParamsSchema -}); -/** -* The set of notification types a client opts in to on a `subscriptions/listen` -* request. Each type is opt-in; the server MUST NOT send a notification type -* the client has not explicitly requested here. -*/ -const SubscriptionFilterSchema = schemas_object({ - toolsListChanged: schemas_boolean().optional(), - promptsListChanged: schemas_boolean().optional(), - resourcesListChanged: schemas_boolean().optional(), - resourceSubscriptions: schemas_array(schemas_string()).optional() -}); -const SubscriptionsListenRequestParamsSchema = BaseRequestParamsSchema.extend({ notifications: SubscriptionFilterSchema }); -/** -* Sent from the client to open a long-lived channel for receiving notifications -* outside the context of a specific request (protocol revision 2026-07-28). -* Replaces the previous HTTP GET endpoint and `resources/subscribe`. -*/ -const SubscriptionsListenRequestSchema = RequestSchema.extend({ - method: literal("subscriptions/listen"), - params: SubscriptionsListenRequestParamsSchema -}); -const SubscriptionsAcknowledgedNotificationParamsSchema = NotificationsParamsSchema.extend({ notifications: SubscriptionFilterSchema }); -/** -* Sent by the server as the first message on a `subscriptions/listen` stream -* to acknowledge that the subscription has been established and report which -* notification types it agreed to honor (protocol revision 2026-07-28). -*/ -const SubscriptionsAcknowledgedNotificationSchema = NotificationSchema.extend({ - method: literal("notifications/subscriptions/acknowledged"), - params: SubscriptionsAcknowledgedNotificationParamsSchema -}); -/** -* `_meta` for a {@linkcode SubscriptionsListenResult}: the listen request's -* JSON-RPC ID under the canonical subscription-id key (mirroring the same key -* on every notification delivered on the stream). Extends -* {@linkcode ResultMetaObjectSchema}, so the optional serverInfo key is typed -* here too. -*/ -const SubscriptionsListenResultMetaSchema = ResultMetaObjectSchema.extend({ [auth_CUe6YdwF_SUBSCRIPTION_ID_META_KEY]: RequestIdSchema }); -/** -* The response to a `subscriptions/listen` request, signalling that the -* subscription has ended gracefully (for example, during server shutdown). -* Because the listen stream is long-lived, this result is sent only when the -* server tears the subscription down; an abrupt transport close carries no -* response. The result body is otherwise empty. -*/ -const SubscriptionsListenResultSchema = ResultSchema.extend({ _meta: SubscriptionsListenResultMetaSchema }); -/** -* Parameters for a {@linkcode ResourceUpdatedNotification | notifications/resources/updated} notification. -*/ -const ResourceUpdatedNotificationParamsSchema = NotificationsParamsSchema.extend({ uri: schemas_string() }); -/** -* A notification from the server to the client, informing it that a resource has changed and may need to be read again. This should only be sent if the client previously sent a {@linkcode SubscribeRequest | resources/subscribe} request. -*/ -const ResourceUpdatedNotificationSchema = NotificationSchema.extend({ - method: literal("notifications/resources/updated"), - params: ResourceUpdatedNotificationParamsSchema -}); -/** -* Describes an argument that a prompt can accept. -*/ -const PromptArgumentSchema = schemas_object({ - name: schemas_string(), - description: schemas_optional(schemas_string()), - required: schemas_optional(schemas_boolean()) -}); -/** -* A prompt or prompt template that the server offers. -*/ -const PromptSchema = schemas_object({ - ...BaseMetadataSchema.shape, - ...IconsSchema.shape, - description: schemas_optional(schemas_string()), - arguments: schemas_optional(schemas_array(PromptArgumentSchema)), - _meta: schemas_optional(looseObject({})) -}); -/** -* Sent from the client to request a list of prompts and prompt templates the server has. -*/ -const ListPromptsRequestSchema = PaginatedRequestSchema.extend({ method: literal("prompts/list") }); -/** -* The server's response to a {@linkcode ListPromptsRequest | prompts/list} request from the client. -*/ -const ListPromptsResultSchema = PaginatedResultSchema.extend({ prompts: schemas_array(PromptSchema) }); -/** -* Parameters for a {@linkcode GetPromptRequest | prompts/get} request. -*/ -const GetPromptRequestParamsSchema = BaseRequestParamsSchema.extend({ - name: schemas_string(), - arguments: schemas_record(schemas_string(), schemas_string()).optional() -}); -/** -* Used by the client to get a prompt provided by the server. -*/ -const GetPromptRequestSchema = RequestSchema.extend({ - method: literal("prompts/get"), - params: GetPromptRequestParamsSchema -}); -/** -* Text provided to or from an LLM. -*/ -const TextContentSchema = schemas_object({ - type: literal("text"), - text: schemas_string(), - annotations: AnnotationsSchema.optional(), - _meta: schemas_record(schemas_string(), unknown()).optional() -}); -/** -* An image provided to or from an LLM. -*/ -const ImageContentSchema = schemas_object({ - type: literal("image"), - data: auth_CUe6YdwF_Base64Schema, - mimeType: schemas_string(), - annotations: AnnotationsSchema.optional(), - _meta: schemas_record(schemas_string(), unknown()).optional() -}); -/** -* Audio content provided to or from an LLM. -*/ -const AudioContentSchema = schemas_object({ - type: literal("audio"), - data: auth_CUe6YdwF_Base64Schema, - mimeType: schemas_string(), - annotations: AnnotationsSchema.optional(), - _meta: schemas_record(schemas_string(), unknown()).optional() -}); -/** -* A tool call request from an assistant (LLM). -* Represents the assistant's request to use a tool. -* -* @deprecated Deprecated as of protocol version 2026-07-28 (SEP-2577); remains -* in the specification for at least twelve months. Migrate to calling LLM -* provider APIs directly. -*/ -const ToolUseContentSchema = schemas_object({ - type: literal("tool_use"), - name: schemas_string(), - id: schemas_string(), - input: schemas_record(schemas_string(), unknown()), - _meta: schemas_record(schemas_string(), unknown()).optional() -}); -/** -* The contents of a resource, embedded into a prompt or tool call result. -*/ -const EmbeddedResourceSchema = schemas_object({ - type: literal("resource"), - resource: schemas_union([TextResourceContentsSchema, BlobResourceContentsSchema]), - annotations: AnnotationsSchema.optional(), - _meta: schemas_record(schemas_string(), unknown()).optional() -}); -/** -* A resource that the server is capable of reading, included in a prompt or tool call result. -* -* Note: resource links returned by tools are not guaranteed to appear in the results of {@linkcode ListResourcesRequest | resources/list} requests. -*/ -const ResourceLinkSchema = ResourceSchema.extend({ type: literal("resource_link") }); -/** -* A content block that can be used in prompts and tool results. -*/ -const ContentBlockSchema = schemas_union([ - TextContentSchema, - ImageContentSchema, - AudioContentSchema, - ResourceLinkSchema, - EmbeddedResourceSchema -]); -/** -* Describes a message returned as part of a prompt. -*/ -const PromptMessageSchema = schemas_object({ - role: RoleSchema, - content: ContentBlockSchema -}); -/** -* The server's response to a {@linkcode GetPromptRequest | prompts/get} request from the client. -*/ -const GetPromptResultSchema = ResultSchema.extend({ - description: schemas_string().optional(), - messages: schemas_array(PromptMessageSchema) -}); -/** -* An optional notification from the server to the client, informing it that the list of prompts it offers has changed. This may be issued by servers without any previous subscription from the client. -*/ -const PromptListChangedNotificationSchema = NotificationSchema.extend({ - method: literal("notifications/prompts/list_changed"), - params: NotificationsParamsSchema.optional() -}); -/** -* Additional properties describing a `Tool` to clients. -* -* NOTE: all properties in {@linkcode ToolAnnotations} are **hints**. -* They are not guaranteed to provide a faithful description of -* tool behavior (including descriptive properties like `title`). -* -* Clients should never make tool use decisions based on `ToolAnnotations` -* received from untrusted servers. -*/ -const ToolAnnotationsSchema = schemas_object({ - title: schemas_string().optional(), - readOnlyHint: schemas_boolean().optional(), - destructiveHint: schemas_boolean().optional(), - idempotentHint: schemas_boolean().optional(), - openWorldHint: schemas_boolean().optional() -}); -/** -* Execution-related properties for a tool. -*/ -const ToolExecutionSchema = schemas_object({ taskSupport: schemas_enum([ - "required", - "optional", - "forbidden" -]).optional() }); -/** -* Definition for a tool the client can call. -*/ -const ToolSchema = schemas_object({ - ...BaseMetadataSchema.shape, - ...IconsSchema.shape, - description: schemas_string().optional(), - inputSchema: schemas_object({ - type: literal("object"), - properties: schemas_record(schemas_string(), JSONValueSchema).optional(), - required: schemas_array(schemas_string()).optional() - }).catchall(unknown()), - outputSchema: looseObject({ $schema: schemas_string().optional() }).optional(), - annotations: ToolAnnotationsSchema.optional(), - execution: ToolExecutionSchema.optional(), - _meta: schemas_record(schemas_string(), unknown()).optional() -}); -/** -* Sent from the client to request a list of tools the server has. -*/ -const ListToolsRequestSchema = PaginatedRequestSchema.extend({ method: literal("tools/list") }); -/** -* The server's response to a {@linkcode ListToolsRequest | tools/list} request from the client. -*/ -const ListToolsResultSchema = PaginatedResultSchema.extend({ tools: schemas_array(ToolSchema) }); -/** -* The server's response to a tool call. -*/ -const auth_CUe6YdwF_CallToolResultSchema = ResultSchema.extend({ - content: schemas_array(ContentBlockSchema).default([]), - structuredContent: unknown().optional(), - isError: schemas_boolean().optional() -}); -/** -* {@linkcode CallToolResultSchema} extended with backwards compatibility to protocol version 2024-10-07. -*/ -const CompatibilityCallToolResultSchema = auth_CUe6YdwF_CallToolResultSchema.or(ResultSchema.extend({ toolResult: unknown() })); -/** -* Parameters for a `tools/call` request. -*/ -const CallToolRequestParamsSchema = auth_CUe6YdwF_TaskAugmentedRequestParamsSchema.extend({ - name: schemas_string(), - arguments: schemas_record(schemas_string(), unknown()).optional() -}); -/** -* Used by the client to invoke a tool provided by the server. -*/ -const CallToolRequestSchema = RequestSchema.extend({ - method: literal("tools/call"), - params: CallToolRequestParamsSchema -}); -/** -* An optional notification from the server to the client, informing it that the list of tools it offers has changed. This may be issued by servers without any previous subscription from the client. -*/ -const ToolListChangedNotificationSchema = NotificationSchema.extend({ - method: literal("notifications/tools/list_changed"), - params: NotificationsParamsSchema.optional() -}); -/** -* Base schema for list changed subscription options (without callback). -* Used internally for Zod validation of `autoRefresh` and `debounceMs`. -*/ -const ListChangedOptionsBaseSchema = schemas_object({ - autoRefresh: schemas_boolean().default(true), - debounceMs: schemas_number().int().nonnegative().default(300) -}); -/** -* The severity of a log message. -* -* @deprecated Deprecated as of protocol version 2026-07-28 (SEP-2577); remains -* in the specification for at least twelve months. Migrate to stderr logging -* (STDIO servers) or OpenTelemetry. -*/ -const LoggingLevelSchema = schemas_enum([ - "debug", - "info", - "notice", - "warning", - "error", - "critical", - "alert", - "emergency" -]); -/** -* Parameters for a `logging/setLevel` request. -* -* @deprecated Deprecated as of protocol version 2026-07-28 (SEP-2577); remains -* in the specification for at least twelve months. Migrate to stderr logging -* (STDIO servers) or OpenTelemetry. -*/ -const SetLevelRequestParamsSchema = BaseRequestParamsSchema.extend({ level: LoggingLevelSchema }); -/** -* A request from the client to the server, to enable or adjust logging. -* -* @deprecated Deprecated as of protocol version 2026-07-28 (SEP-2577); remains -* in the specification for at least twelve months. Migrate to stderr logging -* (STDIO servers) or OpenTelemetry. -*/ -const SetLevelRequestSchema = RequestSchema.extend({ - method: literal("logging/setLevel"), - params: SetLevelRequestParamsSchema -}); -/** -* Parameters for a `notifications/message` notification. -* -* @deprecated Deprecated as of protocol version 2026-07-28 (SEP-2577); remains -* in the specification for at least twelve months. Migrate to stderr logging -* (STDIO servers) or OpenTelemetry. -*/ -const LoggingMessageNotificationParamsSchema = NotificationsParamsSchema.extend({ - level: LoggingLevelSchema, - logger: schemas_string().optional(), - data: unknown() -}); -/** -* Notification of a log message passed from server to client. If no `logging/setLevel` request has been sent from the client, the server MAY decide which messages to send automatically. -* -* @deprecated Deprecated as of protocol version 2026-07-28 (SEP-2577); remains -* in the specification for at least twelve months. Migrate to stderr logging -* (STDIO servers) or OpenTelemetry. -*/ -const LoggingMessageNotificationSchema = NotificationSchema.extend({ - method: literal("notifications/message"), - params: LoggingMessageNotificationParamsSchema -}); -/** -* Hints to use for model selection. -* -* @deprecated Deprecated as of protocol version 2026-07-28 (SEP-2577); remains -* in the specification for at least twelve months. Migrate to calling LLM -* provider APIs directly. -*/ -const ModelHintSchema = schemas_object({ name: schemas_string().optional() }); -/** -* The server's preferences for model selection, requested of the client during sampling. -* -* @deprecated Deprecated as of protocol version 2026-07-28 (SEP-2577); remains -* in the specification for at least twelve months. Migrate to calling LLM -* provider APIs directly. -*/ -const ModelPreferencesSchema = schemas_object({ - hints: schemas_array(ModelHintSchema).optional(), - costPriority: schemas_number().min(0).max(1).optional(), - speedPriority: schemas_number().min(0).max(1).optional(), - intelligencePriority: schemas_number().min(0).max(1).optional() -}); -/** -* Controls tool usage behavior in sampling requests. -* -* @deprecated Deprecated as of protocol version 2026-07-28 (SEP-2577); remains -* in the specification for at least twelve months. Migrate to calling LLM -* provider APIs directly. -*/ -const ToolChoiceSchema = schemas_object({ mode: schemas_enum([ - "auto", - "required", - "none" -]).optional() }); -/** -* The result of a tool execution, provided by the user (server). -* Represents the outcome of invoking a tool requested via `ToolUseContent`. -* -* @deprecated Deprecated as of protocol version 2026-07-28 (SEP-2577); remains -* in the specification for at least twelve months. Migrate to calling LLM -* provider APIs directly. -*/ -const ToolResultContentSchema = schemas_object({ - type: literal("tool_result"), - toolUseId: schemas_string().describe("The unique identifier for the corresponding tool call."), - content: schemas_array(ContentBlockSchema), - structuredContent: unknown().optional(), - isError: schemas_boolean().optional(), - _meta: schemas_record(schemas_string(), unknown()).optional() -}); -/** -* Basic content types for sampling responses (without tool use). -* Used for backwards-compatible {@linkcode CreateMessageResult} when tools are not used. -* -* @deprecated Deprecated as of protocol version 2026-07-28 (SEP-2577); remains -* in the specification for at least twelve months. Migrate to calling LLM -* provider APIs directly. -*/ -const SamplingContentSchema = discriminatedUnion("type", [ - TextContentSchema, - ImageContentSchema, - AudioContentSchema -]); -/** -* Content block types allowed in sampling messages. -* This includes text, image, audio, tool use requests, and tool results. -* -* @deprecated Deprecated as of protocol version 2026-07-28 (SEP-2577); remains -* in the specification for at least twelve months. Migrate to calling LLM -* provider APIs directly. -*/ -const SamplingMessageContentBlockSchema = discriminatedUnion("type", [ - TextContentSchema, - ImageContentSchema, - AudioContentSchema, - ToolUseContentSchema, - ToolResultContentSchema -]); -/** -* Describes a message issued to or received from an LLM API. -* -* @deprecated Deprecated as of protocol version 2026-07-28 (SEP-2577); remains -* in the specification for at least twelve months. Migrate to calling LLM -* provider APIs directly. -*/ -const SamplingMessageSchema = schemas_object({ - role: RoleSchema, - content: schemas_union([SamplingMessageContentBlockSchema, schemas_array(SamplingMessageContentBlockSchema)]), - _meta: schemas_record(schemas_string(), unknown()).optional() -}); -/** -* Parameters for a `sampling/createMessage` request. -* -* @deprecated Deprecated as of protocol version 2026-07-28 (SEP-2577); remains -* in the specification for at least twelve months. Migrate to calling LLM -* provider APIs directly. -*/ -const CreateMessageRequestParamsSchema = auth_CUe6YdwF_TaskAugmentedRequestParamsSchema.extend({ - messages: schemas_array(SamplingMessageSchema), - modelPreferences: ModelPreferencesSchema.optional(), - systemPrompt: schemas_string().optional(), - includeContext: schemas_enum([ - "none", - "thisServer", - "allServers" - ]).optional(), - temperature: schemas_number().optional(), - maxTokens: schemas_number().int(), - stopSequences: schemas_array(schemas_string()).optional(), - metadata: JSONObjectSchema.optional(), - tools: schemas_array(ToolSchema).optional(), - toolChoice: ToolChoiceSchema.optional() -}); -/** -* A request from the server to sample an LLM via the client. The client has full discretion over which model to select. The client should also inform the user before beginning sampling, to allow them to inspect the request (human in the loop) and decide whether to approve it. -* -* @deprecated Deprecated as of protocol version 2026-07-28 (SEP-2577); remains -* in the specification for at least twelve months. Migrate to calling LLM -* provider APIs directly. -*/ -const CreateMessageRequestSchema = RequestSchema.extend({ - method: literal("sampling/createMessage"), - params: CreateMessageRequestParamsSchema -}); -/** -* The client's response to a `sampling/create_message` request from the server. -* This is the backwards-compatible version that returns single content (no arrays). -* Used when the request does not include tools. -* -* @deprecated Deprecated as of protocol version 2026-07-28 (SEP-2577); remains -* in the specification for at least twelve months. Migrate to calling LLM -* provider APIs directly. -*/ -const CreateMessageResultSchema = ResultSchema.extend({ - model: schemas_string(), - stopReason: schemas_optional(schemas_enum([ - "endTurn", - "stopSequence", - "maxTokens" - ]).or(schemas_string())), - role: RoleSchema, - content: SamplingContentSchema -}); -/** -* The client's response to a `sampling/create_message` request when tools were provided. -* This version supports array content for tool use flows. -* -* @deprecated Deprecated as of protocol version 2026-07-28 (SEP-2577); remains -* in the specification for at least twelve months. Migrate to calling LLM -* provider APIs directly. -*/ -const CreateMessageResultWithToolsSchema = ResultSchema.extend({ - model: schemas_string(), - stopReason: schemas_optional(schemas_enum([ - "endTurn", - "stopSequence", - "maxTokens", - "toolUse" - ]).or(schemas_string())), - role: RoleSchema, - content: schemas_union([SamplingMessageContentBlockSchema, schemas_array(SamplingMessageContentBlockSchema)]) -}); -/** -* Primitive schema definition for boolean fields. -*/ -const BooleanSchemaSchema = schemas_object({ - type: literal("boolean"), - title: schemas_string().optional(), - description: schemas_string().optional(), - default: schemas_boolean().optional() -}); -/** -* Primitive schema definition for string fields. -*/ -const StringSchemaSchema = schemas_object({ - type: literal("string"), - title: schemas_string().optional(), - description: schemas_string().optional(), - minLength: schemas_number().optional(), - maxLength: schemas_number().optional(), - format: schemas_enum([ - "email", - "uri", - "date", - "date-time" - ]).optional(), - default: schemas_string().optional() -}); -/** -* Primitive schema definition for number fields. -*/ -const NumberSchemaSchema = schemas_object({ - type: schemas_enum(["number", "integer"]), - title: schemas_string().optional(), - description: schemas_string().optional(), - minimum: schemas_number().optional(), - maximum: schemas_number().optional(), - default: schemas_number().optional() -}); -/** -* Schema for single-selection enumeration without display titles for options. -*/ -const UntitledSingleSelectEnumSchemaSchema = schemas_object({ - type: literal("string"), - title: schemas_string().optional(), - description: schemas_string().optional(), - enum: schemas_array(schemas_string()), - default: schemas_string().optional() -}); -/** -* Schema for single-selection enumeration with display titles for each option. -*/ -const TitledSingleSelectEnumSchemaSchema = schemas_object({ - type: literal("string"), - title: schemas_string().optional(), - description: schemas_string().optional(), - oneOf: schemas_array(schemas_object({ - const: schemas_string(), - title: schemas_string() - })), - default: schemas_string().optional() -}); -/** -* Use {@linkcode TitledSingleSelectEnumSchema} instead. -* This interface will be removed in a future version. -*/ -const LegacyTitledEnumSchemaSchema = schemas_object({ - type: literal("string"), - title: schemas_string().optional(), - description: schemas_string().optional(), - enum: schemas_array(schemas_string()), - enumNames: schemas_array(schemas_string()).optional(), - default: schemas_string().optional() -}); -const SingleSelectEnumSchemaSchema = schemas_union([UntitledSingleSelectEnumSchemaSchema, TitledSingleSelectEnumSchemaSchema]); -/** -* Schema for multiple-selection enumeration without display titles for options. -*/ -const UntitledMultiSelectEnumSchemaSchema = schemas_object({ - type: literal("array"), - title: schemas_string().optional(), - description: schemas_string().optional(), - minItems: schemas_number().optional(), - maxItems: schemas_number().optional(), - items: schemas_object({ - type: literal("string"), - enum: schemas_array(schemas_string()) - }), - default: schemas_array(schemas_string()).optional() -}); -/** -* Schema for multiple-selection enumeration with display titles for each option. -*/ -const TitledMultiSelectEnumSchemaSchema = schemas_object({ - type: literal("array"), - title: schemas_string().optional(), - description: schemas_string().optional(), - minItems: schemas_number().optional(), - maxItems: schemas_number().optional(), - items: schemas_object({ anyOf: schemas_array(schemas_object({ - const: schemas_string(), - title: schemas_string() - })) }), - default: schemas_array(schemas_string()).optional() -}); -/** -* Combined schema for multiple-selection enumeration -*/ -const MultiSelectEnumSchemaSchema = schemas_union([UntitledMultiSelectEnumSchemaSchema, TitledMultiSelectEnumSchemaSchema]); -/** -* Primitive schema definition for enum fields. -*/ -const EnumSchemaSchema = schemas_union([ - LegacyTitledEnumSchemaSchema, - SingleSelectEnumSchemaSchema, - MultiSelectEnumSchemaSchema -]); -/** -* Union of all primitive schema definitions. -*/ -const PrimitiveSchemaDefinitionSchema = schemas_union([ - EnumSchemaSchema, - BooleanSchemaSchema, - StringSchemaSchema, - NumberSchemaSchema -]); -/** -* Parameters for an `elicitation/create` request for form-based elicitation. -*/ -const ElicitRequestFormParamsSchema = auth_CUe6YdwF_TaskAugmentedRequestParamsSchema.extend({ - mode: literal("form").optional(), - message: schemas_string(), - requestedSchema: schemas_object({ - type: literal("object"), - properties: schemas_record(schemas_string(), PrimitiveSchemaDefinitionSchema), - required: schemas_array(schemas_string()).optional() - }).catchall(unknown()) -}); -/** -* Parameters for an {@linkcode ElicitRequest | elicitation/create} request for URL-based elicitation. -*/ -const ElicitRequestURLParamsSchema = auth_CUe6YdwF_TaskAugmentedRequestParamsSchema.extend({ - mode: literal("url"), - message: schemas_string(), - elicitationId: schemas_string(), - url: schemas_string().url() -}); -/** -* The parameters for a request to elicit additional information from the user via the client. -*/ -const ElicitRequestParamsSchema = schemas_union([ElicitRequestFormParamsSchema, ElicitRequestURLParamsSchema]); -/** -* A request from the server to elicit user input via the client. -* The client should present the message and form fields to the user (form mode) -* or navigate to a URL (URL mode). -*/ -const ElicitRequestSchema = RequestSchema.extend({ - method: literal("elicitation/create"), - params: ElicitRequestParamsSchema -}); -/** -* Parameters for a {@linkcode ElicitationCompleteNotification | notifications/elicitation/complete} notification. -* -* @deprecated Removed from the spec by #2891 (2026-07-28). The client learns the outcome -* of an out-of-band interaction by retrying the original request; no server-initiated -* completion signal exists in the 2026-07-28 revision. Kept here for the 2025-era flow -* only. The 2026-07-28 wire codec excludes this notification. -* @category notifications/elicitation/complete -*/ -const ElicitationCompleteNotificationParamsSchema = NotificationsParamsSchema.extend({ elicitationId: schemas_string() }); -/** -* A notification from the server to the client, informing it of a completion of an out-of-band elicitation request. -* -* @deprecated Removed from the spec by #2891 (2026-07-28). The client learns the outcome -* of an out-of-band interaction by retrying the original request; no server-initiated -* completion signal exists in the 2026-07-28 revision. Kept here for the 2025-era flow -* only. The 2026-07-28 wire codec excludes this notification. -* @category notifications/elicitation/complete -*/ -const ElicitationCompleteNotificationSchema = NotificationSchema.extend({ - method: literal("notifications/elicitation/complete"), - params: ElicitationCompleteNotificationParamsSchema -}); -/** -* The client's response to an {@linkcode ElicitRequest | elicitation/create} request from the server. -*/ -const ElicitResultSchema = ResultSchema.extend({ - action: schemas_enum([ - "accept", - "decline", - "cancel" - ]), - content: preprocess((val) => val === null ? void 0 : val, schemas_record(schemas_string(), schemas_union([ - schemas_string(), - schemas_number(), - schemas_boolean(), - schemas_array(schemas_string()) - ])).optional()) -}); -/** -* A reference to a resource or resource template definition. -*/ -const ResourceTemplateReferenceSchema = schemas_object({ - type: literal("ref/resource"), - uri: schemas_string() -}); -/** -* Identifies a prompt. -*/ -const PromptReferenceSchema = schemas_object({ - type: literal("ref/prompt"), - name: schemas_string() -}); -/** -* Parameters for a {@linkcode CompleteRequest | completion/complete} request. -*/ -const CompleteRequestParamsSchema = BaseRequestParamsSchema.extend({ - ref: schemas_union([PromptReferenceSchema, ResourceTemplateReferenceSchema]), - argument: schemas_object({ - name: schemas_string(), - value: schemas_string() - }), - context: schemas_object({ arguments: schemas_record(schemas_string(), schemas_string()).optional() }).optional() -}); -/** -* A request from the client to the server, to ask for completion options. -*/ -const CompleteRequestSchema = RequestSchema.extend({ - method: literal("completion/complete"), - params: CompleteRequestParamsSchema -}); -/** -* The server's response to a {@linkcode CompleteRequest | completion/complete} request -*/ -const CompleteResultSchema = ResultSchema.extend({ completion: looseObject({ - values: schemas_array(schemas_string()).max(100), - total: schemas_optional(schemas_number().int()), - hasMore: schemas_optional(schemas_boolean()) -}) }); -/** -* Represents a root directory or file that the server can operate on. -* -* @deprecated Deprecated as of protocol version 2026-07-28 (SEP-2577); remains -* in the specification for at least twelve months. Migrate to passing paths via -* tool parameters, resource URIs, or configuration. -*/ -const RootSchema = schemas_object({ - uri: schemas_string().startsWith("file://"), - name: schemas_string().optional(), - _meta: schemas_record(schemas_string(), unknown()).optional() -}); -/** -* Sent from the server to request a list of root URIs from the client. -* -* @deprecated Deprecated as of protocol version 2026-07-28 (SEP-2577); remains -* in the specification for at least twelve months. Migrate to passing paths via -* tool parameters, resource URIs, or configuration. -*/ -const ListRootsRequestSchema = RequestSchema.extend({ - method: literal("roots/list"), - params: BaseRequestParamsSchema.optional() -}); -/** -* The client's response to a `roots/list` request from the server. -* -* @deprecated Deprecated as of protocol version 2026-07-28 (SEP-2577); remains -* in the specification for at least twelve months. Migrate to passing paths via -* tool parameters, resource URIs, or configuration. -*/ -const ListRootsResultSchema = ResultSchema.extend({ roots: schemas_array(RootSchema) }); -/** -* A notification from the client to the server, informing it that the list of roots has changed. -* -* @deprecated Deprecated as of protocol version 2026-07-28 (SEP-2577); remains -* in the specification for at least twelve months. Migrate to passing paths via -* tool parameters, resource URIs, or configuration. -*/ -const RootsListChangedNotificationSchema = NotificationSchema.extend({ - method: literal("notifications/roots/list_changed"), - params: NotificationsParamsSchema.optional() -}); -/** -* Task creation parameters, used to ask that the server create a task to represent a request. -* -* @deprecated 2025-11-25 wire vocabulary with no SDK runtime; kept importable for interoperability only. -*/ -const TaskCreationParamsSchema = looseObject({ - ttl: schemas_number().optional(), - pollInterval: schemas_number().optional() -}); -/** -* The status of a task. -* -* @deprecated 2025-11-25 wire vocabulary with no SDK runtime; kept importable for interoperability only. -*/ -const TaskStatusSchema = schemas_enum([ - "working", - "input_required", - "completed", - "failed", - "cancelled" -]); -/** -* A pollable state object associated with a request. -* -* @deprecated 2025-11-25 wire vocabulary with no SDK runtime; kept importable for interoperability only. -*/ -const TaskSchema = schemas_object({ - taskId: schemas_string(), - status: TaskStatusSchema, - ttl: schemas_union([schemas_number(), schemas_null()]), - createdAt: schemas_string(), - lastUpdatedAt: schemas_string(), - pollInterval: schemas_optional(schemas_number()), - statusMessage: schemas_optional(schemas_string()) -}); -/** -* Result returned when a task is created, containing the task data wrapped in a `task` field. -* -* @deprecated 2025-11-25 wire vocabulary with no SDK runtime; kept importable for interoperability only. -*/ -const CreateTaskResultSchema = ResultSchema.extend({ task: TaskSchema }); -/** -* Parameters for task status notification. -* -* @deprecated 2025-11-25 wire vocabulary with no SDK runtime; kept importable for interoperability only. -*/ -const TaskStatusNotificationParamsSchema = NotificationsParamsSchema.merge(TaskSchema); -/** -* A notification sent when a task's status changes. -* -* @deprecated 2025-11-25 wire vocabulary with no SDK runtime; kept importable for interoperability only. -*/ -const TaskStatusNotificationSchema = NotificationSchema.extend({ - method: literal("notifications/tasks/status"), - params: TaskStatusNotificationParamsSchema -}); -/** -* A request to get the state of a specific task. -* -* @deprecated 2025-11-25 wire vocabulary with no SDK runtime; kept importable for interoperability only. -*/ -const GetTaskRequestSchema = RequestSchema.extend({ - method: literal("tasks/get"), - params: BaseRequestParamsSchema.extend({ taskId: schemas_string() }) -}); -/** -* The response to a {@linkcode GetTaskRequest | tasks/get} request. -* -* @deprecated 2025-11-25 wire vocabulary with no SDK runtime; kept importable for interoperability only. -*/ -const GetTaskResultSchema = ResultSchema.merge(TaskSchema); -/** -* A request to get the result of a specific task. -* -* @deprecated 2025-11-25 wire vocabulary with no SDK runtime; kept importable for interoperability only. -*/ -const GetTaskPayloadRequestSchema = RequestSchema.extend({ - method: literal("tasks/result"), - params: BaseRequestParamsSchema.extend({ taskId: schemas_string() }) -}); -/** -* The response to a `tasks/result` request. -* The structure matches the result type of the original request. -* For example, a {@linkcode CallToolRequest | tools/call} task would return the `CallToolResult` structure. -* -* -* @deprecated 2025-11-25 wire vocabulary with no SDK runtime; kept importable for interoperability only. -*/ -const GetTaskPayloadResultSchema = ResultSchema.loose(); -/** -* A request to list tasks. -* -* @deprecated 2025-11-25 wire vocabulary with no SDK runtime; kept importable for interoperability only. -*/ -const ListTasksRequestSchema = PaginatedRequestSchema.extend({ method: literal("tasks/list") }); -/** -* The response to a {@linkcode ListTasksRequest | tasks/list} request. -* -* @deprecated 2025-11-25 wire vocabulary with no SDK runtime; kept importable for interoperability only. -*/ -const ListTasksResultSchema = PaginatedResultSchema.extend({ tasks: schemas_array(TaskSchema) }); -/** -* A request to cancel a specific task. -* -* @deprecated 2025-11-25 wire vocabulary with no SDK runtime; kept importable for interoperability only. -*/ -const CancelTaskRequestSchema = RequestSchema.extend({ - method: literal("tasks/cancel"), - params: BaseRequestParamsSchema.extend({ taskId: schemas_string() }) -}); -/** -* The response to a {@linkcode CancelTaskRequest | tasks/cancel} request. -* -* @deprecated 2025-11-25 wire vocabulary with no SDK runtime; kept importable for interoperability only. -*/ -const CancelTaskResultSchema = ResultSchema.merge(TaskSchema); -const ClientRequestSchema = schemas_union([ - PingRequestSchema, - auth_CUe6YdwF_InitializeRequestSchema, - DiscoverRequestSchema, - CompleteRequestSchema, - SetLevelRequestSchema, - GetPromptRequestSchema, - ListPromptsRequestSchema, - ListResourcesRequestSchema, - ListResourceTemplatesRequestSchema, - ReadResourceRequestSchema, - SubscribeRequestSchema, - UnsubscribeRequestSchema, - SubscriptionsListenRequestSchema, - CallToolRequestSchema, - ListToolsRequestSchema -]); -const ClientNotificationSchema = schemas_union([ - CancelledNotificationSchema, - ProgressNotificationSchema, - auth_CUe6YdwF_InitializedNotificationSchema, - RootsListChangedNotificationSchema -]); -const ClientResultSchema = schemas_union([ - EmptyResultSchema, - CreateMessageResultSchema, - CreateMessageResultWithToolsSchema, - ElicitResultSchema, - ListRootsResultSchema -]); -const ServerRequestSchema = schemas_union([ - PingRequestSchema, - CreateMessageRequestSchema, - ElicitRequestSchema, - ListRootsRequestSchema -]); -const ServerNotificationSchema = schemas_union([ - CancelledNotificationSchema, - ProgressNotificationSchema, - LoggingMessageNotificationSchema, - ResourceUpdatedNotificationSchema, - ResourceListChangedNotificationSchema, - ToolListChangedNotificationSchema, - PromptListChangedNotificationSchema, - SubscriptionsAcknowledgedNotificationSchema, - ElicitationCompleteNotificationSchema -]); -const ServerResultSchema = schemas_union([ - EmptyResultSchema, - InitializeResultSchema, - DiscoverResultSchema, - CompleteResultSchema, - GetPromptResultSchema, - ListPromptsResultSchema, - ListResourcesResultSchema, - ListResourceTemplatesResultSchema, - ReadResourceResultSchema, - auth_CUe6YdwF_CallToolResultSchema, - ListToolsResultSchema, - SubscriptionsListenResultSchema -]); - -//#endregion -//#region src/auth.ts -/** -* Reusable URL validation that disallows `javascript:` scheme -*/ -const SafeUrlSchema = schemas_url().superRefine((val, ctx) => { - if (!URL.canParse(val)) { - ctx.addIssue({ - code: ZodIssueCode.custom, - message: "URL must be parseable", - fatal: true - }); - return NEVER; - } -}).refine((url) => { - const u = new URL(url); - return u.protocol !== "javascript:" && u.protocol !== "data:" && u.protocol !== "vbscript:"; -}, { message: "URL cannot use javascript:, data:, or vbscript: scheme" }); -/** -* RFC 9728 OAuth Protected Resource Metadata -*/ -const OAuthProtectedResourceMetadataSchema = looseObject({ - resource: schemas_string().url(), - authorization_servers: schemas_array(SafeUrlSchema).optional(), - jwks_uri: schemas_string().url().optional(), - scopes_supported: schemas_array(schemas_string()).optional(), - bearer_methods_supported: schemas_array(schemas_string()).optional(), - resource_signing_alg_values_supported: schemas_array(schemas_string()).optional(), - resource_name: schemas_string().optional(), - resource_documentation: schemas_string().optional(), - resource_policy_uri: schemas_string().url().optional(), - resource_tos_uri: schemas_string().url().optional(), - tls_client_certificate_bound_access_tokens: schemas_boolean().optional(), - authorization_details_types_supported: schemas_array(schemas_string()).optional(), - dpop_signing_alg_values_supported: schemas_array(schemas_string()).optional(), - dpop_bound_access_tokens_required: schemas_boolean().optional() -}); -/** -* RFC 8414 OAuth 2.0 Authorization Server Metadata -*/ -const OAuthMetadataSchema = looseObject({ - issuer: schemas_string(), - authorization_endpoint: SafeUrlSchema, - token_endpoint: SafeUrlSchema, - registration_endpoint: SafeUrlSchema.optional(), - scopes_supported: schemas_array(schemas_string()).optional(), - response_types_supported: schemas_array(schemas_string()), - response_modes_supported: schemas_array(schemas_string()).optional(), - grant_types_supported: schemas_array(schemas_string()).optional(), - token_endpoint_auth_methods_supported: schemas_array(schemas_string()).optional(), - token_endpoint_auth_signing_alg_values_supported: schemas_array(schemas_string()).optional(), - service_documentation: SafeUrlSchema.optional(), - revocation_endpoint: SafeUrlSchema.optional(), - revocation_endpoint_auth_methods_supported: schemas_array(schemas_string()).optional(), - revocation_endpoint_auth_signing_alg_values_supported: schemas_array(schemas_string()).optional(), - introspection_endpoint: schemas_string().optional(), - introspection_endpoint_auth_methods_supported: schemas_array(schemas_string()).optional(), - introspection_endpoint_auth_signing_alg_values_supported: schemas_array(schemas_string()).optional(), - code_challenge_methods_supported: schemas_array(schemas_string()).optional(), - client_id_metadata_document_supported: schemas_boolean().optional(), - authorization_response_iss_parameter_supported: schemas_boolean().optional().catch(void 0) -}); -/** -* OpenID Connect Discovery 1.0 Provider Metadata -* -* @see https://openid.net/specs/openid-connect-discovery-1_0.html#ProviderMetadata -*/ -const OpenIdProviderMetadataSchema = looseObject({ - issuer: schemas_string(), - authorization_endpoint: SafeUrlSchema, - token_endpoint: SafeUrlSchema, - userinfo_endpoint: SafeUrlSchema.optional(), - jwks_uri: SafeUrlSchema, - registration_endpoint: SafeUrlSchema.optional(), - scopes_supported: schemas_array(schemas_string()).optional(), - response_types_supported: schemas_array(schemas_string()), - response_modes_supported: schemas_array(schemas_string()).optional(), - grant_types_supported: schemas_array(schemas_string()).optional(), - acr_values_supported: schemas_array(schemas_string()).optional(), - subject_types_supported: schemas_array(schemas_string()), - id_token_signing_alg_values_supported: schemas_array(schemas_string()), - id_token_encryption_alg_values_supported: schemas_array(schemas_string()).optional(), - id_token_encryption_enc_values_supported: schemas_array(schemas_string()).optional(), - userinfo_signing_alg_values_supported: schemas_array(schemas_string()).optional(), - userinfo_encryption_alg_values_supported: schemas_array(schemas_string()).optional(), - userinfo_encryption_enc_values_supported: schemas_array(schemas_string()).optional(), - request_object_signing_alg_values_supported: schemas_array(schemas_string()).optional(), - request_object_encryption_alg_values_supported: schemas_array(schemas_string()).optional(), - request_object_encryption_enc_values_supported: schemas_array(schemas_string()).optional(), - token_endpoint_auth_methods_supported: schemas_array(schemas_string()).optional(), - token_endpoint_auth_signing_alg_values_supported: schemas_array(schemas_string()).optional(), - display_values_supported: schemas_array(schemas_string()).optional(), - claim_types_supported: schemas_array(schemas_string()).optional(), - claims_supported: schemas_array(schemas_string()).optional(), - service_documentation: schemas_string().optional(), - claims_locales_supported: schemas_array(schemas_string()).optional(), - ui_locales_supported: schemas_array(schemas_string()).optional(), - claims_parameter_supported: schemas_boolean().optional(), - request_parameter_supported: schemas_boolean().optional(), - request_uri_parameter_supported: schemas_boolean().optional(), - require_request_uri_registration: schemas_boolean().optional(), - op_policy_uri: SafeUrlSchema.optional(), - op_tos_uri: SafeUrlSchema.optional(), - client_id_metadata_document_supported: schemas_boolean().optional(), - authorization_response_iss_parameter_supported: schemas_boolean().optional().catch(void 0) -}); -/** -* OpenID Connect Discovery metadata that may include OAuth 2.0 fields -* This schema represents the real-world scenario where OIDC providers -* return a mix of OpenID Connect and OAuth 2.0 metadata fields -*/ -const OpenIdProviderDiscoveryMetadataSchema = schemas_object({ - ...OpenIdProviderMetadataSchema.shape, - ...OAuthMetadataSchema.pick({ code_challenge_methods_supported: true }).shape -}); -/** -* OAuth 2.1 token response -*/ -const OAuthTokensSchema = schemas_object({ - access_token: schemas_string(), - id_token: schemas_string().optional(), - token_type: schemas_string(), - expires_in: coerce_number().optional(), - scope: schemas_string().optional(), - refresh_token: schemas_string().optional() -}).strip(); -/** -* RFC 8693 §2.2.1 Token Exchange response for ID-JAG tokens. -* -* `token_type` is intentionally optional: per RFC 8693 §2.2.1 it is informational when -* the issued token is not an access token, and per RFC 6749 §5.1 it is case-insensitive, -* so strict checking rejects conformant IdPs. -*/ -const IdJagTokenExchangeResponseSchema = schemas_object({ - issued_token_type: literal("urn:ietf:params:oauth:token-type:id-jag"), - access_token: schemas_string(), - token_type: schemas_string().optional(), - expires_in: schemas_number().optional(), - scope: schemas_string().optional() -}).strip(); -/** -* OAuth 2.1 error response -*/ -const OAuthErrorResponseSchema = schemas_object({ - error: schemas_string(), - error_description: schemas_string().optional(), - error_uri: schemas_string().optional() -}); -/** -* Optional version of {@linkcode SafeUrlSchema} that allows empty string for backward compatibility on `tos_uri` and `logo_uri` -*/ -const OptionalSafeUrlSchema = SafeUrlSchema.optional().or(literal("").transform(() => void 0)); -/** -* RFC 7591 OAuth 2.0 Dynamic Client Registration metadata -*/ -const OAuthClientMetadataSchema = schemas_object({ - redirect_uris: schemas_array(SafeUrlSchema), - token_endpoint_auth_method: schemas_string().optional(), - grant_types: schemas_array(schemas_string()).optional(), - response_types: schemas_array(schemas_string()).optional(), - application_type: schemas_string().optional(), - client_name: schemas_string().optional(), - client_uri: SafeUrlSchema.optional(), - logo_uri: OptionalSafeUrlSchema, - scope: schemas_string().optional(), - contacts: schemas_array(schemas_string()).optional(), - tos_uri: OptionalSafeUrlSchema, - policy_uri: schemas_string().optional(), - jwks_uri: SafeUrlSchema.optional(), - jwks: any().optional(), - software_id: schemas_string().optional(), - software_version: schemas_string().optional(), - software_statement: schemas_string().optional() -}).strip(); -/** -* RFC 7591 OAuth 2.0 Dynamic Client Registration client information -*/ -const OAuthClientInformationSchema = schemas_object({ - client_id: schemas_string(), - client_secret: schemas_string().optional(), - client_id_issued_at: schemas_number().optional(), - client_secret_expires_at: schemas_number().optional() -}).strip(); -/** -* RFC 7591 OAuth 2.0 Dynamic Client Registration full response (client information plus metadata) -*/ -const OAuthClientInformationFullSchema = OAuthClientMetadataSchema.merge(OAuthClientInformationSchema); -/** -* RFC 7591 OAuth 2.0 Dynamic Client Registration error response -*/ -const OAuthClientRegistrationErrorSchema = schemas_object({ - error: schemas_string(), - error_description: schemas_string().optional() -}).strip(); -/** -* RFC 7009 OAuth 2.0 Token Revocation request -*/ -const OAuthTokenRevocationRequestSchema = schemas_object({ - token: schemas_string(), - token_type_hint: schemas_string().optional() -}).strip(); - -//#endregion - -//# sourceMappingURL=auth-CUe6YdwF.mjs.map - - - - - - - - -//#region ../core-internal/src/errors/crossBundleBrand.ts -/** -* Cross-bundle `instanceof` support for the SDK error classes. -* -* `@modelcontextprotocol/client` and `@modelcontextprotocol/server` each bundle their -* own copy of `core-internal`, so an error constructed by one package fails a -* prototype-identity `instanceof` against the same class re-exported by the other — -* exactly the check a dual-role process (gateway, host, in-process test) writes. -* -* Instead of prototype identity, branded classes stamp every instance with the brand -* strings of its class chain under a registry symbol (`Symbol.for`, shared across -* bundles and realms), and resolve `instanceof` via `Symbol.hasInstance` against the -* brand set. Ordinary prototype-based `instanceof` is kept as a fallback so behavior -* is unchanged for anything unbranded. -* -* A class participates by defining an **own** `mcpBrand` static (via a `static {}` -* block, so nothing reaches the declaration files — a declared `protected static` -* field would make the constructor types nominally incompatible across the bundled -* copies) and (for hierarchy roots) installing {@linkcode brandedHasInstance} as -* `Symbol.hasInstance`. User-defined subclasses that do not declare their own brand -* keep plain prototype semantics — a foreign base-class instance never satisfies -* `instanceof UserSubclass`. -* -* Prior art — the same stamp-and-hook shape ships at scale elsewhere: Node core -* (stream.Writable since 2017, Console via a marker symbol, diagnostics_channel), -* undici's whole error hierarchy (vendored into Node as fetch), googleapis/gaxios -* (GaxiosError, Symbol.for marker), AWS SDK v3's ServiceException (which pairs a -* Symbol.hasInstance override with a static isInstance guard, as we do), and zod v4 -* (Symbol.hasInstance on every schema class for cross-version interop). -* -* Contract notes: -* - Participation criterion: **every error class exported from a public package that -* callers are documented to `instanceof` must be branded.** The per-package -* errorBrandConformance tests walk the export surfaces and fail naming any -* exported Error subclass that has not opted in. -* - Brands assert **identity, not shape**: brand strings are version-less, so an -* instance from one SDK version matches the class of another. Members added to a -* branded class in a later version may be absent on a matched instance — read -* fields defensively, and treat branded classes as additive-only. The escape -* hatch when a release must break a branded class's read contract: change that -* class's brand string in the same release, which cleanly severs cross-version -* matching for that class. The per-package brand pins make the rename -* deliberate: errorSurfacePins.test.ts owns the core-internal brands, and each -* package's errorBrandConformance test pins its package-local ones. -* - Cross-bundle matching requires **both** copies to be at or after the release -* that introduced branding; against an older copy, behavior degrades to plain -* prototype `instanceof` in both directions. -* - A consumer re-bundling the SDK with property mangling (`mangle.props`) would -* break the brand statics; default esbuild/webpack/terser settings do not. -*/ -/** Registry symbol — identical across bundled copies and realms. */ -const BRANDS = Symbol.for("mcp.sdk.errorBrands"); -/** -* Stamp `instance` with the brand of every class in `ctor`'s chain that declares an -* own `mcpBrand`. Call once from the hierarchy root's constructor with `new.target` — -* subclasses inherit the stamping without touching their constructors. -* -* Constructor-time only: never stamp arbitrary objects. A stamped non-instance would -* satisfy `instanceof` while lacking the prototype members (getters like `.status`) -* that callers reach for after the check. -*/ -function stampErrorBrands(instance, ctor) { - const brands = /* @__PURE__ */ new Set(); - let current = ctor; - while (typeof current === "function") { - const brand = current.mcpBrand; - if (Object.prototype.hasOwnProperty.call(current, "mcpBrand") && typeof brand === "string") brands.add(brand); - current = Object.getPrototypeOf(current); - } - if (brands.size === 0) return; - Object.defineProperty(instance, BRANDS, { - value: brands, - enumerable: false, - configurable: true - }); -} -/** -* `Symbol.hasInstance` implementation for branded hierarchy roots. Matches when the -* value carries the **own** brand of the class being tested against (cross-bundle -* path), falling back to ordinary prototype-based `instanceof` otherwise. -*/ -function brandedHasInstance(cls, value) { - try { - if (typeof value === "object" && value !== null && Object.prototype.hasOwnProperty.call(cls, "mcpBrand") && typeof cls.mcpBrand === "string" && Object.prototype.hasOwnProperty.call(value, BRANDS)) { - const carried = value[BRANDS]; - if (carried && typeof carried.has === "function" && carried.has(cls.mcpBrand)) return true; - } - } catch {} - return Function.prototype[Symbol.hasInstance].call(cls, value); -} - -//#endregion -//#region ../core-internal/src/auth/errors.ts -/** -* OAuth error codes as defined by {@link https://datatracker.ietf.org/doc/html/rfc6749#section-5.2 | RFC 6749} -* and extensions. -*/ -let src_CX2iR2pK_OAuthErrorCode = /* @__PURE__ */ (/* unused pure expression or super */ null && (function(OAuthErrorCode$1) { - /** - * The request is missing a required parameter, includes an invalid parameter value, - * includes a parameter more than once, or is otherwise malformed. - */ - OAuthErrorCode$1["InvalidRequest"] = "invalid_request"; - /** - * Client authentication failed (e.g., unknown client, no client authentication included, - * or unsupported authentication method). - */ - OAuthErrorCode$1["InvalidClient"] = "invalid_client"; - /** - * The provided authorization grant or refresh token is invalid, expired, revoked, - * does not match the redirection URI used in the authorization request, or was issued to another client. - */ - OAuthErrorCode$1["InvalidGrant"] = "invalid_grant"; - /** - * The authenticated client is not authorized to use this authorization grant type. - */ - OAuthErrorCode$1["UnauthorizedClient"] = "unauthorized_client"; - /** - * The authorization grant type is not supported by the authorization server. - */ - OAuthErrorCode$1["UnsupportedGrantType"] = "unsupported_grant_type"; - /** - * The requested scope is invalid, unknown, malformed, or exceeds the scope granted by the resource owner. - */ - OAuthErrorCode$1["InvalidScope"] = "invalid_scope"; - /** - * The resource owner or authorization server denied the request. - */ - OAuthErrorCode$1["AccessDenied"] = "access_denied"; - /** - * The authorization server encountered an unexpected condition that prevented it from fulfilling the request. - */ - OAuthErrorCode$1["ServerError"] = "server_error"; - /** - * The authorization server is currently unable to handle the request due to temporary overloading or maintenance. - */ - OAuthErrorCode$1["TemporarilyUnavailable"] = "temporarily_unavailable"; - /** - * The authorization server does not support obtaining an authorization code using this method. - */ - OAuthErrorCode$1["UnsupportedResponseType"] = "unsupported_response_type"; - /** - * The authorization server does not support the requested token type. - */ - OAuthErrorCode$1["UnsupportedTokenType"] = "unsupported_token_type"; - /** - * The access token provided is expired, revoked, malformed, or invalid for other reasons. - */ - OAuthErrorCode$1["InvalidToken"] = "invalid_token"; - /** - * The HTTP method used is not allowed for this endpoint. (Custom, non-standard error) - */ - OAuthErrorCode$1["MethodNotAllowed"] = "method_not_allowed"; - /** - * Rate limit exceeded. (Custom, non-standard error based on RFC 6585) - */ - OAuthErrorCode$1["TooManyRequests"] = "too_many_requests"; - /** - * The client metadata is invalid. (Custom error for dynamic client registration - RFC 7591) - */ - OAuthErrorCode$1["InvalidClientMetadata"] = "invalid_client_metadata"; - /** - * The value of one or more redirection URIs is invalid. (Dynamic client registration - RFC 7591 §3.2.2) - */ - OAuthErrorCode$1["InvalidRedirectUri"] = "invalid_redirect_uri"; - /** - * The request requires higher privileges than provided by the access token. - */ - OAuthErrorCode$1["InsufficientScope"] = "insufficient_scope"; - /** - * The requested resource is invalid, missing, unknown, or malformed. (Custom error for resource indicators - RFC 8707) - */ - OAuthErrorCode$1["InvalidTarget"] = "invalid_target"; - return OAuthErrorCode$1; -}({}))); -/** -* OAuth error class for all OAuth-related errors. -*/ -var src_CX2iR2pK_OAuthError = class OAuthError extends Error { - static { - Object.defineProperty(this, "mcpBrand", { value: "mcp.OAuthError" }); - } - static [Symbol.hasInstance](value) { - return brandedHasInstance(this, value); - } - /** - * Brand-based type guard: equivalent to `value instanceof this`, as an - * explicit static predicate (the axios/AWS-SDK `isInstance` style). Reads - * the caller's own brand via `this`, so every branded subclass gets a - * correctly-scoped guard by inheritance. Must be invoked on the class — - * in callback position write `v => SdkError.isInstance(v)`, not - * `.filter(SdkError.isInstance)` (detached calls throw rather than - * silently matching nothing). - */ - static isInstance(value) { - 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 brandedHasInstance(this, value); - } - constructor(code, message, errorUri) { - super(message); - this.code = code; - this.errorUri = errorUri; - this.name = "OAuthError"; - stampErrorBrands(this, new.target); - } - /** - * Converts the error to a standard OAuth error response object. - */ - toResponseObject() { - const response = { - error: this.code, - error_description: this.message - }; - if (this.errorUri) response.error_uri = this.errorUri; - return response; - } - /** - * Creates an {@linkcode OAuthError} from an OAuth error response. - */ - static fromResponse(response) { - return new OAuthError(response.error, response.error_description ?? response.error, response.error_uri); - } -}; - -//#endregion -//#region ../core-internal/src/errors/sdkErrors.ts -/** -* Error codes for SDK errors (local errors that never cross the wire). -* Unlike {@linkcode ProtocolErrorCode} which uses numeric JSON-RPC codes, `SdkErrorCode` uses -* descriptive string values for better developer experience. -* -* These errors are thrown locally by the SDK and are never serialized as -* JSON-RPC error responses. -*/ -let src_CX2iR2pK_SdkErrorCode = /* @__PURE__ */ function(SdkErrorCode$1) { - /** Transport is not connected */ - SdkErrorCode$1["NotConnected"] = "NOT_CONNECTED"; - /** Transport is already connected */ - SdkErrorCode$1["AlreadyConnected"] = "ALREADY_CONNECTED"; - /** Protocol is not initialized */ - SdkErrorCode$1["NotInitialized"] = "NOT_INITIALIZED"; - /** Required capability is not supported by the remote side */ - SdkErrorCode$1["CapabilityNotSupported"] = "CAPABILITY_NOT_SUPPORTED"; - /** Request timed out waiting for response */ - SdkErrorCode$1["RequestTimeout"] = "REQUEST_TIMEOUT"; - /** Connection was closed */ - SdkErrorCode$1["ConnectionClosed"] = "CONNECTION_CLOSED"; - /** Failed to send message */ - SdkErrorCode$1["SendFailed"] = "SEND_FAILED"; - /** Response result failed local schema validation */ - SdkErrorCode$1["InvalidResult"] = "INVALID_RESULT"; - /** - * The response carried a `resultType` discriminator (protocol revision - * 2026-07-28) naming a result kind this client cannot consume yet, e.g. - * `input_required`. The kind is carried in `data.resultType`. - */ - SdkErrorCode$1["UnsupportedResultType"] = "UNSUPPORTED_RESULT_TYPE"; - /** - * The multi-round-trip auto-fulfilment driver exhausted its round cap - * (`inputRequired.maxRounds`) without the server returning a complete - * result. `data.rounds` carries the cap that was hit and - * `data.lastResult` carries the last `input_required` payload received - * (`{ inputRequests, requestState? }`), so callers can inspect or resume - * the flow manually. - */ - SdkErrorCode$1["InputRequiredRoundsExceeded"] = "INPUT_REQUIRED_ROUNDS_EXCEEDED"; - /** - * The auto-aggregating no-`cursor` `listTools()` / `listPrompts()` / - * `listResources()` / `listResourceTemplates()` walk hit the - * `ClientOptions.listMaxPages` cap without the server's pagination - * converging. `data.method` carries the list verb and - * `data.listMaxPages` the cap that was hit; raise the cap or fall back to - * explicit per-page `{ cursor }` calls. - */ - SdkErrorCode$1["ListPaginationExceeded"] = "LIST_PAGINATION_EXCEEDED"; - /** - * The spec method being sent does not exist on the negotiated protocol - * version's wire era (e.g. `tasks/get` toward a 2026-07-28 peer, or - * `server/discover` toward a 2025-era peer). Raised locally, before - * anything reaches the transport. The method and era are carried in - * `data.method` / `data.era`. - */ - SdkErrorCode$1["MethodNotSupportedByProtocolVersion"] = "METHOD_NOT_SUPPORTED_BY_PROTOCOL_VERSION"; - /** - * Protocol-era negotiation at connect time failed without producing either a - * usable modern (2026-07-28+) era or a definitive legacy fallback signal — - * e.g. the negotiation mode forbids falling back (`pin`), the probe hit a - * network failure, or the server answered the probe with a 5xx (a typed - * connect error, never an era verdict). - * - * Negotiation-phase only: this code is never used once an era is - * established. Auth walls never carry it: a 401/403 rejecting the probe - * uses {@linkcode ClientHttpAuthentication} / {@linkcode ClientHttpForbidden} - * instead, so era-recovery flows keyed on this code (e.g. cached-verdict - * gateways) can never persist a verdict for an unauthorized exchange. - */ - SdkErrorCode$1["EraNegotiationFailed"] = "ERA_NEGOTIATION_FAILED"; - SdkErrorCode$1["ClientHttpNotImplemented"] = "CLIENT_HTTP_NOT_IMPLEMENTED"; - /** - * HTTP 401 authentication failure: the transport's re-auth retry still got - * 401 (`Server returned 401 after re-authentication`), or the version - * negotiation probe was rejected 401 with no `authProvider` configured - * (`Version negotiation failed: the server requires authorization (HTTP 401)`). - * Carried on an {@linkcode SdkHttpError} with `status: 401`. - */ - SdkErrorCode$1["ClientHttpAuthentication"] = "CLIENT_HTTP_AUTHENTICATION"; - /** - * HTTP 403 denial: the step-up re-authorization retry limit was reached, - * or the version negotiation probe was rejected 403 - * (`Version negotiation failed: the server denied access (HTTP 403)`). - * Carried on an {@linkcode SdkHttpError} with `status: 403`. - */ - SdkErrorCode$1["ClientHttpForbidden"] = "CLIENT_HTTP_FORBIDDEN"; - SdkErrorCode$1["ClientHttpUnexpectedContent"] = "CLIENT_HTTP_UNEXPECTED_CONTENT"; - SdkErrorCode$1["ClientHttpFailedToOpenStream"] = "CLIENT_HTTP_FAILED_TO_OPEN_STREAM"; - SdkErrorCode$1["ClientHttpFailedToTerminateSession"] = "CLIENT_HTTP_FAILED_TO_TERMINATE_SESSION"; - return SdkErrorCode$1; -}({}); -/** -* SDK errors are local errors that never cross the wire. -* They are distinct from {@linkcode ProtocolError} which represents JSON-RPC protocol errors -* that are serialized and sent as error responses. -* -* @example -* ```ts source="./sdkErrors.examples.ts#SdkError_basicUsage" -* try { -* // Throwing an SDK error -* throw new SdkError(SdkErrorCode.NotConnected, 'Transport is not connected'); -* } catch (error) { -* // Checking error type by code -* if (error instanceof SdkError && error.code === SdkErrorCode.RequestTimeout) { -* // Handle timeout -* } -* } -* ``` -*/ -var src_CX2iR2pK_SdkError = class extends Error { - static { - Object.defineProperty(this, "mcpBrand", { value: "mcp.SdkError" }); - } - static [Symbol.hasInstance](value) { - return brandedHasInstance(this, value); - } - /** - * Brand-based type guard: equivalent to `value instanceof this`, as an - * explicit static predicate (the axios/AWS-SDK `isInstance` style). Reads - * the caller's own brand via `this`, so every branded subclass gets a - * correctly-scoped guard by inheritance. Must be invoked on the class — - * in callback position write `v => SdkError.isInstance(v)`, not - * `.filter(SdkError.isInstance)` (detached calls throw rather than - * silently matching nothing). - */ - static isInstance(value) { - 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 brandedHasInstance(this, value); - } - constructor(code, message, data) { - super(message); - this.code = code; - this.data = data; - this.name = "SdkError"; - stampErrorBrands(this, new.target); - } -}; -/** -* An {@linkcode SdkError} subclass for HTTP transport failures. -* -* Thrown by the streamable HTTP transport when the server responds with a -* non-OK status code. Narrows {@linkcode SdkError.data | data} to -* {@linkcode SdkHttpErrorData} so consumers can inspect the HTTP status -* without unsafe casting. -* -* @example -* ```ts source="./sdkErrors.examples.ts#SdkHttpError_basicUsage" -* if (error instanceof SdkHttpError) { -* console.log(error.status); // number -* console.log(error.statusText); // string | undefined -* } -* ``` -*/ -var SdkHttpError = class extends src_CX2iR2pK_SdkError { - static { - Object.defineProperty(this, "mcpBrand", { value: "mcp.SdkHttpError" }); - } - constructor(code, message, data) { - super(code, message, data); - this.name = "SdkHttpError"; - } - get status() { - return this.data.status; - } - get statusText() { - return this.data.statusText; - } -}; - -//#endregion -//#region ../core-internal/src/shared/authUtils.ts -/** -* Utilities for handling OAuth resource URIs. -*/ -/** -* Converts a server URL to a resource URL by removing the fragment. -* {@link https://datatracker.ietf.org/doc/html/rfc8707#section-2 | RFC 8707 section 2} -* states that resource URIs "MUST NOT include a fragment component". -* Keeps everything else unchanged (scheme, domain, port, path, query). -*/ -function resourceUrlFromServerUrl(url) { - const resourceURL = typeof url === "string" ? new URL(url) : new URL(url.href); - resourceURL.hash = ""; - return resourceURL; -} -/** -* Checks if a requested resource URL matches a configured resource URL. -* A requested resource matches if it has the same scheme, domain, port, -* and its path starts with the configured resource's path. -* -* @param options - The options object -* @param options.requestedResource - The resource URL being requested -* @param options.configuredResource - The resource URL that has been configured -* @returns true if the requested resource matches the configured resource, false otherwise -*/ -function checkResourceAllowed({ requestedResource, configuredResource }) { - const requested = typeof requestedResource === "string" ? new URL(requestedResource) : new URL(requestedResource.href); - const configured = typeof configuredResource === "string" ? new URL(configuredResource) : new URL(configuredResource.href); - if (requested.origin !== configured.origin) return false; - if (requested.pathname.length < configured.pathname.length) return false; - const requestedPath = requested.pathname.endsWith("/") ? requested.pathname : requested.pathname + "/"; - const configuredPath = configured.pathname.endsWith("/") ? configured.pathname : configured.pathname + "/"; - return requestedPath.startsWith(configuredPath); -} - -//#endregion -//#region ../core-internal/src/shared/clientCapabilityRequirements.ts -/** -* Inbound request methods whose processing structurally requires a client -* capability, keyed by method, valued by the capabilities required. -* -* Currently empty: none of the request methods served on the 2026-07-28 -* registry unconditionally requires a client capability. Entries appear here -* when such methods exist — for example requests whose handling embeds -* elicitation or sampling input requests (the input-request engine), or -* opt-in subscription delivery. Handler-conditional requirements (a specific -* tool that needs sampling) are not expressible as a static method table and -* are enforced at the point the requirement arises instead. -*/ -const REQUIRED_CLIENT_CAPABILITIES_BY_METHOD = (/* unused pure expression or super */ null && ({})); -/** -* The client capabilities a request method structurally requires, or -* `undefined` when the method has no static requirement. -*/ -function src_CX2iR2pK_requiredClientCapabilitiesForRequest(method) { - return Object.hasOwn(REQUIRED_CLIENT_CAPABILITIES_BY_METHOD, method) ? REQUIRED_CLIENT_CAPABILITIES_BY_METHOD[method] : void 0; -} -function isPlainObject$7(value) { - return value !== null && typeof value === "object" && !Array.isArray(value); -} -/** -* Whether a required nested member counts as declared even though it is not -* spelled out: a bare `elicitation: {}` declaration (no mode sub-capability at -* all) is read as form support — the pre-mode (2025) meaning of a bare -* declaration — so an `elicitation.form` requirement treats it as satisfied. -* Declaring any mode explicitly (for example `elicitation: { url: {} }`) -* removes the implication. -*/ -function isImpliedCapabilityMember(capability, member, declaredValue) { - return capability === "elicitation" && member === "form" && declaredValue["form"] === void 0 && declaredValue["url"] === void 0; -} -/** -* The client capabilities an embedded multi-round-trip input request requires -* (call site 2 — the outbound input-request leg): a server MUST NOT send an -* `inputRequests` kind the request's declared client capabilities do not -* cover. Returns `undefined` for entries whose method is not one of the -* embedded input-request kinds (those are a server bug handled separately, -* not a capability question). -* -* The requirement is mode-aware where the capability is: URL-mode elicitation -* requires `elicitation.url`; form-mode (or mode-omitted) elicitation requires -* `elicitation.form` (modes are sub-capabilities, and a server MUST NOT send a -* mode the client did not declare); sampling with `tools`/`toolChoice` -* requires `sampling.tools`. A bare `elicitation: {}` declaration satisfies -* the form requirement — see {@linkcode missingClientCapabilities}. -*/ -function requiredClientCapabilitiesForInputRequest(entry) { - switch (entry.method) { - case "elicitation/create": - if (entry.params?.["mode"] === "url") return { elicitation: { url: {} } }; - return { elicitation: { form: {} } }; - case "sampling/createMessage": { - const params = entry.params; - if (params !== void 0 && (params["tools"] !== void 0 || params["toolChoice"] !== void 0)) return { sampling: { tools: {} } }; - return { sampling: {} }; - } - case "roots/list": return { roots: {} }; - default: return; - } -} -/** -* Computes the subset of `required` client capabilities the client did not -* declare. Returns `undefined` when every required capability is declared; -* otherwise returns an object in the `ClientCapabilities` shape containing -* exactly the missing capabilities (suitable for -* `data.requiredCapabilities` on the `-32021` error). -* -* A capability counts as declared when its top-level key is present on the -* declared capabilities; when the requirement names nested members (for -* example `elicitation: { url: {} }`), each named member must also be present -* under the declared capability. One lenient reading applies: a bare -* `elicitation: {}` declaration (no mode sub-capability at all) counts as -* declaring `elicitation.form` — the pre-mode (2025) meaning of a bare -* declaration. An absent or empty `declared` value means -* nothing is declared — every required capability is missing (the structural -* clean-refusal posture for sessions with no per-request capability view). -*/ -function src_CX2iR2pK_missingClientCapabilities(required, declared) { - const missing = {}; - for (const [capability, requirement] of Object.entries(required)) { - if (requirement === void 0) continue; - const declaredValue = declared === void 0 ? void 0 : declared[capability]; - if (declaredValue === void 0) { - missing[capability] = requirement; - continue; - } - if (isPlainObject$7(requirement) && isPlainObject$7(declaredValue)) { - const missingMembers = {}; - for (const [member, memberRequirement] of Object.entries(requirement)) if (memberRequirement !== void 0 && declaredValue[member] === void 0 && !isImpliedCapabilityMember(capability, member, declaredValue)) missingMembers[member] = memberRequirement; - if (Object.keys(missingMembers).length > 0) missing[capability] = missingMembers; - } - } - return Object.keys(missing).length > 0 ? missing : void 0; -} - -//#endregion -//#region ../core-internal/src/shared/protocolEras.ts -/** -* The first protocol revision of the modern (2026-07-28) era. Revision identifiers -* are ISO dates, so lexicographic comparison orders them chronologically. -*/ -const FIRST_MODERN_PROTOCOL_VERSION = "2026-07-28"; -/** -* Modern-era protocol revisions this SDK can negotiate via `server/discover`. -* Deliberately separate from {@linkcode SUPPORTED_PROTOCOL_VERSIONS} (the legacy -* `initialize` list), so adding a revision here can never leak a modern version -* string into a 2025-era handshake. Internal — not part of the public API surface. -*/ -const src_CX2iR2pK_SUPPORTED_MODERN_PROTOCOL_VERSIONS = (/* unused pure expression or super */ null && ([FIRST_MODERN_PROTOCOL_VERSION])); -/** Whether the given protocol revision belongs to the modern (2026-07-28+) era. */ -function isModernProtocolVersion(version) { - return version >= FIRST_MODERN_PROTOCOL_VERSION; -} -/** The legacy-era (pre-2026-07-28) subset of a supported-versions list, in the list's own preference order. */ -function legacyProtocolVersions(versions) { - return versions.filter((version) => !isModernProtocolVersion(version)); -} -/** The modern-era (2026-07-28+) subset of a supported-versions list, in the list's own preference order. */ -function modernProtocolVersions(versions) { - return versions.filter((version) => isModernProtocolVersion(version)); -} - -//#endregion -//#region ../core-internal/src/wire/textFallback.ts -/** -* SEP-2106 §4.3 TextContent auto-append, era-agnostic, called from BOTH -* codecs' {@link WireCodec.projectCallToolResult}: when `structuredContent` -* is a non-object value (array/primitive/`null`) and the handler authored no -* `type:'text'` block, append `{type:'text', text: JSON.stringify(value)}`. -* Object-shaped (or absent) `structuredContent` returns the same reference. -* -* Leaf module: imported by both era codec modules, so it must NOT import from -* `./codec.js` (which value-imports the rev codecs at top level — that would -* make a runtime cycle and a TDZ hazard for entries that evaluate a rev codec -* module first). -*/ -function appendTextFallbackForNonObject(result) { - const sc = result.structuredContent; - if (sc === void 0) return result; - if (!(typeof sc !== "object" || sc === null || Array.isArray(sc))) return result; - if (result.content?.some((c) => c.type === "text") ?? false) return result; - return { - ...result, - content: [...result.content ?? [], { - type: "text", - text: JSON.stringify(sc) - }] - }; -} - -//#endregion -//#region ../core-internal/src/wire/resultFamilies.ts -/** -* Result-family keys that must never default into a `{content: []}` tools/call -* success. Shared by the 2025 wire-seam schema and server normalization. -* Leaf module (like `textFallback.ts`): imported by registry/server paths, so -* it must NOT import from `./codec.js` — that would close a runtime cycle. -*/ -const TOOL_RESULT_FOREIGN_FAMILY_KEYS = [ - "task", - "inputRequests", - "requestState" -]; -/** -* Single owner of the v1-parity ruling: a plain-object tool result without `content` (and -* without foreign-family keys) gains `content: []`. Shared by the 2025 wire seam and server-side handler normalization. -*/ -function normalizeContentlessToolResult(value) { - if (value === null || typeof value !== "object" || Array.isArray(value) || value.content !== void 0 || TOOL_RESULT_FOREIGN_FAMILY_KEYS.some((key) => key in value)) return value; - return { - ...value, - content: [] - }; -} - -//#endregion -//#region ../core-internal/src/wire/rev2025-11-25/buildSchemas.ts -/** -* Complete frozen 2025-11-25 wire schemas. Self-contained — no imports from -* the public/neutral types/schemas.ts. The neutral layer is the public-API -* superset and is free to evolve (e.g., SEP-2106 widening); this file is the -* 2025 wire-parse contract (Q10-L2 byte-identity) and is BEHAVIOR-FROZEN. -* -* This is the era's complete frozen wire-parse contract — both the 2025-only -* delta (the deprecated task family, the era role unions) AND frozen copies of -* every era-shared shape (Tool, CallToolResult, Initialize*, ContentBlock, -* prompts/resources/completion/elicitation, …). The 2026-era codec -* (`wire/rev2026-07-28/`) is symmetrically self-contained in the same way. -* -* The 2025-only delta (the task message surface, restored types-only by #2248 -* for interop with task-capable 2025 peers) is parsed ONLY through this era's -* registry; the deprecated Task* schemas also live (marked `@deprecated`) in -* the neutral schema layer so the public types stay nameable without a -* cross-layer import — nameability is constant, runtime availability is -* version-keyed — but appear in no API signature. Q1 increment 2 — deletions -* are physical: the -* 2026-era REGISTRY has no Task* methods (its frozen building-block copies do -* carry the deprecated Task* sub-schemas by composition — soft contamination, -* tracked for anchor-exactness adjudication). -* -* The only cross-layer dependency is `import type { JSONObject, JSONValue }` -* from the neutral types barrel — pure structural type aliases with no parse -* behavior. No runtime schema is shared with the neutral layer. -*/ -function build$1() { - const JSONValueSchema$1 = lazy(() => schemas_union([ - schemas_string(), - schemas_number(), - schemas_boolean(), - schemas_null(), - schemas_record(schemas_string(), JSONValueSchema$1), - schemas_array(JSONValueSchema$1) - ])); - const JSONObjectSchema$1 = schemas_record(schemas_string(), JSONValueSchema$1); - /** - * A progress token, used to associate progress notifications with the original request. - */ - const ProgressTokenSchema$1 = schemas_union([schemas_string(), schemas_number().int()]); - /** - * An opaque token used to represent a cursor for pagination. - */ - const CursorSchema$1 = schemas_string(); - /** @deprecated 2025-11-25 wire vocabulary with no SDK runtime; kept importable for interoperability only. */ - const TaskMetadataSchema$1 = schemas_object({ ttl: schemas_number().optional() }); - /** - * Metadata for associating messages with a task. - * Include this in the `_meta` field under the key `io.modelcontextprotocol/related-task`. - * - * @deprecated 2025-11-25 wire vocabulary with no SDK runtime; kept importable for interoperability only. - */ - const RelatedTaskMetadataSchema$1 = schemas_object({ taskId: schemas_string() }); - const RequestMetaSchema$1 = looseObject({ - progressToken: ProgressTokenSchema$1.optional(), - "io.modelcontextprotocol/related-task": RelatedTaskMetadataSchema$1.optional() - }); - /** - * Common params for any request. - */ - const BaseRequestParamsSchema$1 = schemas_object({ _meta: RequestMetaSchema$1.optional() }); - /** - * Common params for any task-augmented request. - * - * @deprecated 2025-11-25 wire vocabulary with no SDK runtime; kept importable for interoperability only. - */ - const TaskAugmentedRequestParamsSchema$1 = BaseRequestParamsSchema$1.extend({ task: TaskMetadataSchema$1.optional() }); - const RequestSchema$1 = schemas_object({ - method: schemas_string(), - params: BaseRequestParamsSchema$1.loose().optional() - }); - const NotificationsParamsSchema$1 = schemas_object({ _meta: RequestMetaSchema$1.optional() }); - const NotificationSchema$1 = schemas_object({ - method: schemas_string(), - params: NotificationsParamsSchema$1.loose().optional() - }); - const ResultSchema$1 = looseObject({ _meta: RequestMetaSchema$1.optional() }); - /** - * A uniquely identifying ID for a request in JSON-RPC. - */ - const RequestIdSchema$1 = schemas_union([schemas_string(), schemas_number().int()]); - /** - * A response that indicates success but carries no data. - */ - const EmptyResultSchema$1 = ResultSchema$1.strict(); - const CancelledNotificationParamsSchema$1 = NotificationsParamsSchema$1.extend({ - requestId: RequestIdSchema$1.optional(), - reason: schemas_string().optional() - }); - /** - * This notification can be sent by either side to indicate that it is cancelling a previously-issued request. - * - * The request SHOULD still be in-flight, but due to communication latency, it is always possible that this notification MAY arrive after the request has already finished. - * - * This notification indicates that the result will be unused, so any associated processing SHOULD cease. - * - * A client MUST NOT attempt to cancel its {@linkcode InitializeRequest | initialize} request. - */ - const CancelledNotificationSchema$1 = NotificationSchema$1.extend({ - method: literal("notifications/cancelled"), - params: CancelledNotificationParamsSchema$1 - }); - /** - * Icon schema for use in {@link Tool | tools}, {@link Prompt | prompts}, {@link Resource | resources}, and {@link Implementation | implementations}. - */ - const IconSchema$1 = schemas_object({ - src: schemas_string(), - mimeType: schemas_string().optional(), - sizes: schemas_array(schemas_string()).optional(), - theme: schemas_enum(["light", "dark"]).optional() - }); - /** - * Base schema to add `icons` property. - * - */ - const IconsSchema$1 = schemas_object({ icons: schemas_array(IconSchema$1).optional() }); - /** - * Base metadata interface for common properties across {@link Resource | resources}, {@link Tool | tools}, {@link Prompt | prompts}, and {@link Implementation | implementations}. - */ - const BaseMetadataSchema$1 = schemas_object({ - name: schemas_string(), - title: schemas_string().optional() - }); - /** - * Describes the name and version of an MCP implementation. - */ - const ImplementationSchema$1 = BaseMetadataSchema$1.extend({ - ...BaseMetadataSchema$1.shape, - ...IconsSchema$1.shape, - version: schemas_string(), - websiteUrl: schemas_string().optional(), - description: schemas_string().optional() - }); - const FormElicitationCapabilitySchema = intersection(schemas_object({ applyDefaults: schemas_boolean().optional() }), JSONObjectSchema$1); - const ElicitationCapabilitySchema = preprocess((value) => { - if (value && typeof value === "object" && !Array.isArray(value) && Object.keys(value).length === 0) return { form: {} }; - return value; - }, intersection(schemas_object({ - form: FormElicitationCapabilitySchema.optional(), - url: JSONObjectSchema$1.optional() - }), JSONObjectSchema$1.optional())); - /** - * Task capabilities for clients, indicating which request types support task creation. - * - * @deprecated 2025-11-25 wire vocabulary with no SDK runtime; kept importable for interoperability only. - */ - const ClientTasksCapabilitySchema$1 = looseObject({ - list: JSONObjectSchema$1.optional(), - cancel: JSONObjectSchema$1.optional(), - requests: looseObject({ - sampling: looseObject({ createMessage: JSONObjectSchema$1.optional() }).optional(), - elicitation: looseObject({ create: JSONObjectSchema$1.optional() }).optional() - }).optional() - }); - /** - * Task capabilities for servers, indicating which request types support task creation. - * - * @deprecated 2025-11-25 wire vocabulary with no SDK runtime; kept importable for interoperability only. - */ - const ServerTasksCapabilitySchema$1 = looseObject({ - list: JSONObjectSchema$1.optional(), - cancel: JSONObjectSchema$1.optional(), - requests: looseObject({ tools: looseObject({ call: JSONObjectSchema$1.optional() }).optional() }).optional() - }); - /** - * Capabilities a client may support. Known capabilities are defined here, in this schema, but this is not a closed set: any client can define its own, additional capabilities. - */ - const ClientCapabilitiesSchema$1 = schemas_object({ - experimental: schemas_record(schemas_string(), JSONObjectSchema$1).optional(), - sampling: schemas_object({ - context: JSONObjectSchema$1.optional(), - tools: JSONObjectSchema$1.optional() - }).optional(), - elicitation: ElicitationCapabilitySchema.optional(), - roots: schemas_object({ listChanged: schemas_boolean().optional() }).optional(), - tasks: ClientTasksCapabilitySchema$1.optional(), - extensions: schemas_record(schemas_string(), JSONObjectSchema$1).optional() - }); - const InitializeRequestParamsSchema$1 = BaseRequestParamsSchema$1.extend({ - protocolVersion: schemas_string(), - capabilities: ClientCapabilitiesSchema$1, - clientInfo: ImplementationSchema$1 - }); - /** - * This request is sent from the client to the server when it first connects, asking it to begin initialization. - */ - const InitializeRequestSchema$1 = RequestSchema$1.extend({ - method: literal("initialize"), - params: InitializeRequestParamsSchema$1 - }); - /** - * Capabilities that a server may support. Known capabilities are defined here, in this schema, but this is not a closed set: any server can define its own, additional capabilities. - */ - const ServerCapabilitiesSchema$1 = schemas_object({ - experimental: schemas_record(schemas_string(), JSONObjectSchema$1).optional(), - logging: JSONObjectSchema$1.optional(), - completions: JSONObjectSchema$1.optional(), - prompts: schemas_object({ listChanged: schemas_boolean().optional() }).optional(), - resources: schemas_object({ - subscribe: schemas_boolean().optional(), - listChanged: schemas_boolean().optional() - }).optional(), - tools: schemas_object({ listChanged: schemas_boolean().optional() }).optional(), - tasks: ServerTasksCapabilitySchema$1.optional(), - extensions: schemas_record(schemas_string(), JSONObjectSchema$1).optional() - }); - /** - * After receiving an initialize request from the client, the server sends this response. - */ - const InitializeResultSchema$1 = ResultSchema$1.extend({ - protocolVersion: schemas_string(), - capabilities: ServerCapabilitiesSchema$1, - serverInfo: ImplementationSchema$1, - instructions: schemas_string().optional() - }); - /** - * This notification is sent from the client to the server after initialization has finished. - */ - const InitializedNotificationSchema$1 = NotificationSchema$1.extend({ - method: literal("notifications/initialized"), - params: NotificationsParamsSchema$1.optional() - }); - /** - * A ping, issued by either the server or the client, to check that the other party is still alive. The receiver must promptly respond, or else may be disconnected. - */ - const PingRequestSchema$1 = RequestSchema$1.extend({ - method: literal("ping"), - params: BaseRequestParamsSchema$1.optional() - }); - const ProgressSchema$1 = schemas_object({ - progress: schemas_number(), - total: schemas_optional(schemas_number()), - message: schemas_optional(schemas_string()) - }); - const ProgressNotificationParamsSchema$1 = schemas_object({ - ...NotificationsParamsSchema$1.shape, - ...ProgressSchema$1.shape, - progressToken: ProgressTokenSchema$1 - }); - /** - * An out-of-band notification used to inform the receiver of a progress update for a long-running request. - * - * @category notifications/progress - */ - const ProgressNotificationSchema$1 = NotificationSchema$1.extend({ - method: literal("notifications/progress"), - params: ProgressNotificationParamsSchema$1 - }); - const PaginatedRequestParamsSchema$1 = BaseRequestParamsSchema$1.extend({ cursor: CursorSchema$1.optional() }); - const PaginatedRequestSchema$1 = RequestSchema$1.extend({ params: PaginatedRequestParamsSchema$1.optional() }); - const PaginatedResultSchema$1 = ResultSchema$1.extend({ nextCursor: CursorSchema$1.optional() }); - /** - * The contents of a specific resource or sub-resource. - */ - const ResourceContentsSchema$1 = schemas_object({ - uri: schemas_string(), - mimeType: schemas_optional(schemas_string()), - _meta: schemas_record(schemas_string(), unknown()).optional() - }); - const TextResourceContentsSchema$1 = ResourceContentsSchema$1.extend({ text: schemas_string() }); - /** - * A Zod schema for validating Base64 strings that is more performant and - * robust for very large inputs than the default regex-based check. It avoids - * stack overflows by using the native `atob` function for validation. - */ - const Base64Schema = schemas_string().refine((val) => { - try { - atob(val); - return true; - } catch { - return false; - } - }, { message: "Invalid Base64 string" }); - const BlobResourceContentsSchema$1 = ResourceContentsSchema$1.extend({ blob: Base64Schema }); - /** - * The sender or recipient of messages and data in a conversation. - */ - const RoleSchema$1 = schemas_enum(["user", "assistant"]); - /** - * Optional annotations providing clients additional context about a resource. - */ - const AnnotationsSchema$1 = schemas_object({ - audience: schemas_array(RoleSchema$1).optional(), - priority: schemas_number().min(0).max(1).optional(), - lastModified: iso_datetime({ offset: true }).optional() - }); - /** - * A known resource that the server is capable of reading. - */ - const ResourceSchema$1 = schemas_object({ - ...BaseMetadataSchema$1.shape, - ...IconsSchema$1.shape, - uri: schemas_string(), - description: schemas_optional(schemas_string()), - mimeType: schemas_optional(schemas_string()), - size: schemas_optional(schemas_number()), - annotations: AnnotationsSchema$1.optional(), - _meta: schemas_optional(looseObject({})) - }); - /** - * A template description for resources available on the server. - */ - const ResourceTemplateSchema$1 = schemas_object({ - ...BaseMetadataSchema$1.shape, - ...IconsSchema$1.shape, - uriTemplate: schemas_string(), - description: schemas_optional(schemas_string()), - mimeType: schemas_optional(schemas_string()), - annotations: AnnotationsSchema$1.optional(), - _meta: schemas_optional(looseObject({})) - }); - /** - * Sent from the client to request a list of resources the server has. - */ - const ListResourcesRequestSchema$1 = PaginatedRequestSchema$1.extend({ method: literal("resources/list") }); - /** - * The server's response to a {@linkcode ListResourcesRequest | resources/list} request from the client. - */ - const ListResourcesResultSchema$1 = PaginatedResultSchema$1.extend({ resources: schemas_array(ResourceSchema$1) }); - /** - * Sent from the client to request a list of resource templates the server has. - */ - const ListResourceTemplatesRequestSchema$1 = PaginatedRequestSchema$1.extend({ method: literal("resources/templates/list") }); - /** - * The server's response to a {@linkcode ListResourceTemplatesRequest | resources/templates/list} request from the client. - */ - const ListResourceTemplatesResultSchema$1 = PaginatedResultSchema$1.extend({ resourceTemplates: schemas_array(ResourceTemplateSchema$1) }); - const ResourceRequestParamsSchema$1 = BaseRequestParamsSchema$1.extend({ uri: schemas_string() }); - /** - * Parameters for a {@linkcode ReadResourceRequest | resources/read} request. - */ - const ReadResourceRequestParamsSchema$1 = ResourceRequestParamsSchema$1; - /** - * Sent from the client to the server, to read a specific resource URI. - */ - const ReadResourceRequestSchema$1 = RequestSchema$1.extend({ - method: literal("resources/read"), - params: ReadResourceRequestParamsSchema$1 - }); - /** - * The server's response to a {@linkcode ReadResourceRequest | resources/read} request from the client. - */ - const ReadResourceResultSchema$1 = ResultSchema$1.extend({ contents: schemas_array(schemas_union([TextResourceContentsSchema$1, BlobResourceContentsSchema$1])) }); - /** - * An optional notification from the server to the client, informing it that the list of resources it can read from has changed. This may be issued by servers without any previous subscription from the client. - */ - const ResourceListChangedNotificationSchema$1 = NotificationSchema$1.extend({ - method: literal("notifications/resources/list_changed"), - params: NotificationsParamsSchema$1.optional() - }); - const SubscribeRequestParamsSchema$1 = ResourceRequestParamsSchema$1; - /** - * Sent from the client to request `resources/updated` notifications from the server whenever a particular resource changes. - */ - const SubscribeRequestSchema$1 = RequestSchema$1.extend({ - method: literal("resources/subscribe"), - params: SubscribeRequestParamsSchema$1 - }); - const UnsubscribeRequestParamsSchema$1 = ResourceRequestParamsSchema$1; - /** - * Sent from the client to request cancellation of {@linkcode ResourceUpdatedNotification | resources/updated} notifications from the server. This should follow a previous {@linkcode SubscribeRequest | resources/subscribe} request. - */ - const UnsubscribeRequestSchema$1 = RequestSchema$1.extend({ - method: literal("resources/unsubscribe"), - params: UnsubscribeRequestParamsSchema$1 - }); - /** - * Parameters for a {@linkcode ResourceUpdatedNotification | notifications/resources/updated} notification. - */ - const ResourceUpdatedNotificationParamsSchema$1 = NotificationsParamsSchema$1.extend({ uri: schemas_string() }); - /** - * A notification from the server to the client, informing it that a resource has changed and may need to be read again. This should only be sent if the client previously sent a {@linkcode SubscribeRequest | resources/subscribe} request. - */ - const ResourceUpdatedNotificationSchema$1 = NotificationSchema$1.extend({ - method: literal("notifications/resources/updated"), - params: ResourceUpdatedNotificationParamsSchema$1 - }); - /** - * Describes an argument that a prompt can accept. - */ - const PromptArgumentSchema$1 = schemas_object({ - name: schemas_string(), - description: schemas_optional(schemas_string()), - required: schemas_optional(schemas_boolean()) - }); - /** - * A prompt or prompt template that the server offers. - */ - const PromptSchema$1 = schemas_object({ - ...BaseMetadataSchema$1.shape, - ...IconsSchema$1.shape, - description: schemas_optional(schemas_string()), - arguments: schemas_optional(schemas_array(PromptArgumentSchema$1)), - _meta: schemas_optional(looseObject({})) - }); - /** - * Sent from the client to request a list of prompts and prompt templates the server has. - */ - const ListPromptsRequestSchema$1 = PaginatedRequestSchema$1.extend({ method: literal("prompts/list") }); - /** - * The server's response to a {@linkcode ListPromptsRequest | prompts/list} request from the client. - */ - const ListPromptsResultSchema$1 = PaginatedResultSchema$1.extend({ prompts: schemas_array(PromptSchema$1) }); - /** - * Parameters for a {@linkcode GetPromptRequest | prompts/get} request. - */ - const GetPromptRequestParamsSchema$1 = BaseRequestParamsSchema$1.extend({ - name: schemas_string(), - arguments: schemas_record(schemas_string(), schemas_string()).optional() - }); - /** - * Used by the client to get a prompt provided by the server. - */ - const GetPromptRequestSchema$1 = RequestSchema$1.extend({ - method: literal("prompts/get"), - params: GetPromptRequestParamsSchema$1 - }); - /** - * Text provided to or from an LLM. - */ - const TextContentSchema$1 = schemas_object({ - type: literal("text"), - text: schemas_string(), - annotations: AnnotationsSchema$1.optional(), - _meta: schemas_record(schemas_string(), unknown()).optional() - }); - /** - * An image provided to or from an LLM. - */ - const ImageContentSchema$1 = schemas_object({ - type: literal("image"), - data: Base64Schema, - mimeType: schemas_string(), - annotations: AnnotationsSchema$1.optional(), - _meta: schemas_record(schemas_string(), unknown()).optional() - }); - /** - * Audio content provided to or from an LLM. - */ - const AudioContentSchema$1 = schemas_object({ - type: literal("audio"), - data: Base64Schema, - mimeType: schemas_string(), - annotations: AnnotationsSchema$1.optional(), - _meta: schemas_record(schemas_string(), unknown()).optional() - }); - /** - * A tool call request from an assistant (LLM). - * Represents the assistant's request to use a tool. - * - * @deprecated Deprecated as of protocol version 2026-07-28 (SEP-2577); remains - * in the specification for at least twelve months. Migrate to calling LLM - * provider APIs directly. - */ - const ToolUseContentSchema$1 = schemas_object({ - type: literal("tool_use"), - name: schemas_string(), - id: schemas_string(), - input: schemas_record(schemas_string(), unknown()), - _meta: schemas_record(schemas_string(), unknown()).optional() - }); - /** - * The contents of a resource, embedded into a prompt or tool call result. - */ - const EmbeddedResourceSchema$1 = schemas_object({ - type: literal("resource"), - resource: schemas_union([TextResourceContentsSchema$1, BlobResourceContentsSchema$1]), - annotations: AnnotationsSchema$1.optional(), - _meta: schemas_record(schemas_string(), unknown()).optional() - }); - /** - * A resource that the server is capable of reading, included in a prompt or tool call result. - * - * Note: resource links returned by tools are not guaranteed to appear in the results of {@linkcode ListResourcesRequest | resources/list} requests. - */ - const ResourceLinkSchema$1 = ResourceSchema$1.extend({ type: literal("resource_link") }); - /** - * A content block that can be used in prompts and tool results. - */ - const ContentBlockSchema$1 = schemas_union([ - TextContentSchema$1, - ImageContentSchema$1, - AudioContentSchema$1, - ResourceLinkSchema$1, - EmbeddedResourceSchema$1 - ]); - /** - * Describes a message returned as part of a prompt. - */ - const PromptMessageSchema$1 = schemas_object({ - role: RoleSchema$1, - content: ContentBlockSchema$1 - }); - /** - * The server's response to a {@linkcode GetPromptRequest | prompts/get} request from the client. - */ - const GetPromptResultSchema$1 = ResultSchema$1.extend({ - description: schemas_string().optional(), - messages: schemas_array(PromptMessageSchema$1) - }); - /** - * An optional notification from the server to the client, informing it that the list of prompts it offers has changed. This may be issued by servers without any previous subscription from the client. - */ - const PromptListChangedNotificationSchema$1 = NotificationSchema$1.extend({ - method: literal("notifications/prompts/list_changed"), - params: NotificationsParamsSchema$1.optional() - }); - /** - * Additional properties describing a `Tool` to clients. - * - * NOTE: all properties in {@linkcode ToolAnnotations} are **hints**. - * They are not guaranteed to provide a faithful description of - * tool behavior (including descriptive properties like `title`). - * - * Clients should never make tool use decisions based on `ToolAnnotations` - * received from untrusted servers. - */ - const ToolAnnotationsSchema$1 = schemas_object({ - title: schemas_string().optional(), - readOnlyHint: schemas_boolean().optional(), - destructiveHint: schemas_boolean().optional(), - idempotentHint: schemas_boolean().optional(), - openWorldHint: schemas_boolean().optional() - }); - /** - * Execution-related properties for a tool. - */ - const ToolExecutionSchema$1 = schemas_object({ taskSupport: schemas_enum([ - "required", - "optional", - "forbidden" - ]).optional() }); - /** - * Definition for a tool the client can call. - */ - const ToolSchema$1 = schemas_object({ - ...BaseMetadataSchema$1.shape, - ...IconsSchema$1.shape, - description: schemas_string().optional(), - inputSchema: schemas_object({ - type: literal("object"), - properties: schemas_record(schemas_string(), JSONValueSchema$1).optional(), - required: schemas_array(schemas_string()).optional() - }).catchall(unknown()), - outputSchema: schemas_object({ - type: literal("object"), - properties: schemas_record(schemas_string(), JSONValueSchema$1).optional(), - required: schemas_array(schemas_string()).optional() - }).catchall(unknown()).optional(), - annotations: ToolAnnotationsSchema$1.optional(), - execution: ToolExecutionSchema$1.optional(), - _meta: schemas_record(schemas_string(), unknown()).optional() - }); - /** - * Sent from the client to request a list of tools the server has. - */ - const ListToolsRequestSchema$1 = PaginatedRequestSchema$1.extend({ method: literal("tools/list") }); - /** - * The server's response to a {@linkcode ListToolsRequest | tools/list} request from the client. - */ - const ListToolsResultSchema$1 = PaginatedResultSchema$1.extend({ tools: schemas_array(ToolSchema$1) }); - /** - * The server's response to a tool call. - */ - const CallToolResultSchema$1 = ResultSchema$1.extend({ - content: schemas_array(ContentBlockSchema$1), - structuredContent: schemas_record(schemas_string(), unknown()).optional(), - isError: schemas_boolean().optional() - }); - /** - * Parameters for a `tools/call` request. - */ - const CallToolRequestParamsSchema$1 = TaskAugmentedRequestParamsSchema$1.extend({ - name: schemas_string(), - arguments: schemas_record(schemas_string(), unknown()).optional() - }); - /** - * Used by the client to invoke a tool provided by the server. - */ - const CallToolRequestSchema$1 = RequestSchema$1.extend({ - method: literal("tools/call"), - params: CallToolRequestParamsSchema$1 - }); - /** - * An optional notification from the server to the client, informing it that the list of tools it offers has changed. This may be issued by servers without any previous subscription from the client. - */ - const ToolListChangedNotificationSchema$1 = NotificationSchema$1.extend({ - method: literal("notifications/tools/list_changed"), - params: NotificationsParamsSchema$1.optional() - }); - /** - * The severity of a log message. - * - * @deprecated Deprecated as of protocol version 2026-07-28 (SEP-2577); remains - * in the specification for at least twelve months. Migrate to stderr logging - * (STDIO servers) or OpenTelemetry. - */ - const LoggingLevelSchema$1 = schemas_enum([ - "debug", - "info", - "notice", - "warning", - "error", - "critical", - "alert", - "emergency" - ]); - /** - * Parameters for a `logging/setLevel` request. - * - * @deprecated Deprecated as of protocol version 2026-07-28 (SEP-2577); remains - * in the specification for at least twelve months. Migrate to stderr logging - * (STDIO servers) or OpenTelemetry. - */ - const SetLevelRequestParamsSchema$1 = BaseRequestParamsSchema$1.extend({ level: LoggingLevelSchema$1 }); - /** - * A request from the client to the server, to enable or adjust logging. - * - * @deprecated Deprecated as of protocol version 2026-07-28 (SEP-2577); remains - * in the specification for at least twelve months. Migrate to stderr logging - * (STDIO servers) or OpenTelemetry. - */ - const SetLevelRequestSchema$1 = RequestSchema$1.extend({ - method: literal("logging/setLevel"), - params: SetLevelRequestParamsSchema$1 - }); - /** - * Parameters for a `notifications/message` notification. - * - * @deprecated Deprecated as of protocol version 2026-07-28 (SEP-2577); remains - * in the specification for at least twelve months. Migrate to stderr logging - * (STDIO servers) or OpenTelemetry. - */ - const LoggingMessageNotificationParamsSchema$1 = NotificationsParamsSchema$1.extend({ - level: LoggingLevelSchema$1, - logger: schemas_string().optional(), - data: unknown() - }); - /** - * Notification of a log message passed from server to client. If no `logging/setLevel` request has been sent from the client, the server MAY decide which messages to send automatically. - * - * @deprecated Deprecated as of protocol version 2026-07-28 (SEP-2577); remains - * in the specification for at least twelve months. Migrate to stderr logging - * (STDIO servers) or OpenTelemetry. - */ - const LoggingMessageNotificationSchema$1 = NotificationSchema$1.extend({ - method: literal("notifications/message"), - params: LoggingMessageNotificationParamsSchema$1 - }); - /** - * Hints to use for model selection. - * - * @deprecated Deprecated as of protocol version 2026-07-28 (SEP-2577); remains - * in the specification for at least twelve months. Migrate to calling LLM - * provider APIs directly. - */ - const ModelHintSchema$1 = schemas_object({ name: schemas_string().optional() }); - /** - * The server's preferences for model selection, requested of the client during sampling. - * - * @deprecated Deprecated as of protocol version 2026-07-28 (SEP-2577); remains - * in the specification for at least twelve months. Migrate to calling LLM - * provider APIs directly. - */ - const ModelPreferencesSchema$1 = schemas_object({ - hints: schemas_array(ModelHintSchema$1).optional(), - costPriority: schemas_number().min(0).max(1).optional(), - speedPriority: schemas_number().min(0).max(1).optional(), - intelligencePriority: schemas_number().min(0).max(1).optional() - }); - /** - * Controls tool usage behavior in sampling requests. - * - * @deprecated Deprecated as of protocol version 2026-07-28 (SEP-2577); remains - * in the specification for at least twelve months. Migrate to calling LLM - * provider APIs directly. - */ - const ToolChoiceSchema$1 = schemas_object({ mode: schemas_enum([ - "auto", - "required", - "none" - ]).optional() }); - /** - * The result of a tool execution, provided by the user (server). - * Represents the outcome of invoking a tool requested via `ToolUseContent`. - * - * @deprecated Deprecated as of protocol version 2026-07-28 (SEP-2577); remains - * in the specification for at least twelve months. Migrate to calling LLM - * provider APIs directly. - */ - const ToolResultContentSchema$1 = schemas_object({ - type: literal("tool_result"), - toolUseId: schemas_string().describe("The unique identifier for the corresponding tool call."), - content: schemas_array(ContentBlockSchema$1), - structuredContent: schemas_object({}).loose().optional(), - isError: schemas_boolean().optional(), - _meta: schemas_record(schemas_string(), unknown()).optional() - }); - /** - * Basic content types for sampling responses (without tool use). - * Used for backwards-compatible {@linkcode CreateMessageResult} when tools are not used. - * - * @deprecated Deprecated as of protocol version 2026-07-28 (SEP-2577); remains - * in the specification for at least twelve months. Migrate to calling LLM - * provider APIs directly. - */ - const SamplingContentSchema$1 = discriminatedUnion("type", [ - TextContentSchema$1, - ImageContentSchema$1, - AudioContentSchema$1 - ]); - /** - * Content block types allowed in sampling messages. - * This includes text, image, audio, tool use requests, and tool results. - * - * @deprecated Deprecated as of protocol version 2026-07-28 (SEP-2577); remains - * in the specification for at least twelve months. Migrate to calling LLM - * provider APIs directly. - */ - const SamplingMessageContentBlockSchema$1 = discriminatedUnion("type", [ - TextContentSchema$1, - ImageContentSchema$1, - AudioContentSchema$1, - ToolUseContentSchema$1, - ToolResultContentSchema$1 - ]); - /** - * Describes a message issued to or received from an LLM API. - * - * @deprecated Deprecated as of protocol version 2026-07-28 (SEP-2577); remains - * in the specification for at least twelve months. Migrate to calling LLM - * provider APIs directly. - */ - const SamplingMessageSchema$1 = schemas_object({ - role: RoleSchema$1, - content: schemas_union([SamplingMessageContentBlockSchema$1, schemas_array(SamplingMessageContentBlockSchema$1)]), - _meta: schemas_record(schemas_string(), unknown()).optional() - }); - /** - * Parameters for a `sampling/createMessage` request. - * - * @deprecated Deprecated as of protocol version 2026-07-28 (SEP-2577); remains - * in the specification for at least twelve months. Migrate to calling LLM - * provider APIs directly. - */ - const CreateMessageRequestParamsSchema$1 = TaskAugmentedRequestParamsSchema$1.extend({ - messages: schemas_array(SamplingMessageSchema$1), - modelPreferences: ModelPreferencesSchema$1.optional(), - systemPrompt: schemas_string().optional(), - includeContext: schemas_enum([ - "none", - "thisServer", - "allServers" - ]).optional(), - temperature: schemas_number().optional(), - maxTokens: schemas_number().int(), - stopSequences: schemas_array(schemas_string()).optional(), - metadata: JSONObjectSchema$1.optional(), - tools: schemas_array(ToolSchema$1).optional(), - toolChoice: ToolChoiceSchema$1.optional() - }); - /** - * A request from the server to sample an LLM via the client. The client has full discretion over which model to select. The client should also inform the user before beginning sampling, to allow them to inspect the request (human in the loop) and decide whether to approve it. - * - * @deprecated Deprecated as of protocol version 2026-07-28 (SEP-2577); remains - * in the specification for at least twelve months. Migrate to calling LLM - * provider APIs directly. - */ - const CreateMessageRequestSchema$1 = RequestSchema$1.extend({ - method: literal("sampling/createMessage"), - params: CreateMessageRequestParamsSchema$1 - }); - /** - * The client's response to a `sampling/create_message` request from the server. - * This is the backwards-compatible version that returns single content (no arrays). - * Used when the request does not include tools. - * - * @deprecated Deprecated as of protocol version 2026-07-28 (SEP-2577); remains - * in the specification for at least twelve months. Migrate to calling LLM - * provider APIs directly. - */ - const CreateMessageResultSchema$1 = ResultSchema$1.extend({ - model: schemas_string(), - stopReason: schemas_optional(schemas_enum([ - "endTurn", - "stopSequence", - "maxTokens" - ]).or(schemas_string())), - role: RoleSchema$1, - content: SamplingContentSchema$1 - }); - /** - * The client's response to a `sampling/create_message` request when tools were provided. - * This version supports array content for tool use flows. - * - * @deprecated Deprecated as of protocol version 2026-07-28 (SEP-2577); remains - * in the specification for at least twelve months. Migrate to calling LLM - * provider APIs directly. - */ - const CreateMessageResultWithToolsSchema$1 = ResultSchema$1.extend({ - model: schemas_string(), - stopReason: schemas_optional(schemas_enum([ - "endTurn", - "stopSequence", - "maxTokens", - "toolUse" - ]).or(schemas_string())), - role: RoleSchema$1, - content: schemas_union([SamplingMessageContentBlockSchema$1, schemas_array(SamplingMessageContentBlockSchema$1)]) - }); - /** - * Primitive schema definition for boolean fields. - */ - const BooleanSchemaSchema$1 = schemas_object({ - type: literal("boolean"), - title: schemas_string().optional(), - description: schemas_string().optional(), - default: schemas_boolean().optional() - }); - /** - * Primitive schema definition for string fields. - */ - const StringSchemaSchema$1 = schemas_object({ - type: literal("string"), - title: schemas_string().optional(), - description: schemas_string().optional(), - minLength: schemas_number().optional(), - maxLength: schemas_number().optional(), - format: schemas_enum([ - "email", - "uri", - "date", - "date-time" - ]).optional(), - default: schemas_string().optional() - }); - /** - * Primitive schema definition for number fields. - */ - const NumberSchemaSchema$1 = schemas_object({ - type: schemas_enum(["number", "integer"]), - title: schemas_string().optional(), - description: schemas_string().optional(), - minimum: schemas_number().optional(), - maximum: schemas_number().optional(), - default: schemas_number().optional() - }); - /** - * Schema for single-selection enumeration without display titles for options. - */ - const UntitledSingleSelectEnumSchemaSchema$1 = schemas_object({ - type: literal("string"), - title: schemas_string().optional(), - description: schemas_string().optional(), - enum: schemas_array(schemas_string()), - default: schemas_string().optional() - }); - /** - * Schema for single-selection enumeration with display titles for each option. - */ - const TitledSingleSelectEnumSchemaSchema$1 = schemas_object({ - type: literal("string"), - title: schemas_string().optional(), - description: schemas_string().optional(), - oneOf: schemas_array(schemas_object({ - const: schemas_string(), - title: schemas_string() - })), - default: schemas_string().optional() - }); - /** - * Use {@linkcode TitledSingleSelectEnumSchema} instead. - * This interface will be removed in a future version. - */ - const LegacyTitledEnumSchemaSchema$1 = schemas_object({ - type: literal("string"), - title: schemas_string().optional(), - description: schemas_string().optional(), - enum: schemas_array(schemas_string()), - enumNames: schemas_array(schemas_string()).optional(), - default: schemas_string().optional() - }); - const SingleSelectEnumSchemaSchema$1 = schemas_union([UntitledSingleSelectEnumSchemaSchema$1, TitledSingleSelectEnumSchemaSchema$1]); - /** - * Schema for multiple-selection enumeration without display titles for options. - */ - const UntitledMultiSelectEnumSchemaSchema$1 = schemas_object({ - type: literal("array"), - title: schemas_string().optional(), - description: schemas_string().optional(), - minItems: schemas_number().optional(), - maxItems: schemas_number().optional(), - items: schemas_object({ - type: literal("string"), - enum: schemas_array(schemas_string()) - }), - default: schemas_array(schemas_string()).optional() - }); - /** - * Schema for multiple-selection enumeration with display titles for each option. - */ - const TitledMultiSelectEnumSchemaSchema$1 = schemas_object({ - type: literal("array"), - title: schemas_string().optional(), - description: schemas_string().optional(), - minItems: schemas_number().optional(), - maxItems: schemas_number().optional(), - items: schemas_object({ anyOf: schemas_array(schemas_object({ - const: schemas_string(), - title: schemas_string() - })) }), - default: schemas_array(schemas_string()).optional() - }); - /** - * Combined schema for multiple-selection enumeration - */ - const MultiSelectEnumSchemaSchema$1 = schemas_union([UntitledMultiSelectEnumSchemaSchema$1, TitledMultiSelectEnumSchemaSchema$1]); - /** - * Primitive schema definition for enum fields. - */ - const EnumSchemaSchema$1 = schemas_union([ - LegacyTitledEnumSchemaSchema$1, - SingleSelectEnumSchemaSchema$1, - MultiSelectEnumSchemaSchema$1 - ]); - /** - * Union of all primitive schema definitions. - */ - const PrimitiveSchemaDefinitionSchema$1 = schemas_union([ - EnumSchemaSchema$1, - BooleanSchemaSchema$1, - StringSchemaSchema$1, - NumberSchemaSchema$1 - ]); - /** - * Parameters for an `elicitation/create` request for form-based elicitation. - */ - const ElicitRequestFormParamsSchema$1 = TaskAugmentedRequestParamsSchema$1.extend({ - mode: literal("form").optional(), - message: schemas_string(), - requestedSchema: schemas_object({ - type: literal("object"), - properties: schemas_record(schemas_string(), PrimitiveSchemaDefinitionSchema$1), - required: schemas_array(schemas_string()).optional() - }).catchall(unknown()) - }); - /** - * Parameters for an {@linkcode ElicitRequest | elicitation/create} request for URL-based elicitation. - */ - const ElicitRequestURLParamsSchema$1 = TaskAugmentedRequestParamsSchema$1.extend({ - mode: literal("url"), - message: schemas_string(), - elicitationId: schemas_string(), - url: schemas_string().url() - }); - /** - * The parameters for a request to elicit additional information from the user via the client. - */ - const ElicitRequestParamsSchema$1 = schemas_union([ElicitRequestFormParamsSchema$1, ElicitRequestURLParamsSchema$1]); - /** - * A request from the server to elicit user input via the client. - * The client should present the message and form fields to the user (form mode) - * or navigate to a URL (URL mode). - */ - const ElicitRequestSchema$1 = RequestSchema$1.extend({ - method: literal("elicitation/create"), - params: ElicitRequestParamsSchema$1 - }); - /** - * Parameters for a {@linkcode ElicitationCompleteNotification | notifications/elicitation/complete} notification. - * - * @category notifications/elicitation/complete - */ - const ElicitationCompleteNotificationParamsSchema$1 = NotificationsParamsSchema$1.extend({ elicitationId: schemas_string() }); - /** - * A notification from the server to the client, informing it of a completion of an out-of-band elicitation request. - * - * @category notifications/elicitation/complete - */ - const ElicitationCompleteNotificationSchema$1 = NotificationSchema$1.extend({ - method: literal("notifications/elicitation/complete"), - params: ElicitationCompleteNotificationParamsSchema$1 - }); - /** - * The client's response to an {@linkcode ElicitRequest | elicitation/create} request from the server. - */ - const ElicitResultSchema$1 = ResultSchema$1.extend({ - action: schemas_enum([ - "accept", - "decline", - "cancel" - ]), - content: preprocess((val) => val === null ? void 0 : val, schemas_record(schemas_string(), schemas_union([ - schemas_string(), - schemas_number(), - schemas_boolean(), - schemas_array(schemas_string()) - ])).optional()) - }); - /** - * A reference to a resource or resource template definition. - */ - const ResourceTemplateReferenceSchema$1 = schemas_object({ - type: literal("ref/resource"), - uri: schemas_string() - }); - /** - * Identifies a prompt. - */ - const PromptReferenceSchema$1 = schemas_object({ - type: literal("ref/prompt"), - name: schemas_string() - }); - /** - * Parameters for a {@linkcode CompleteRequest | completion/complete} request. - */ - const CompleteRequestParamsSchema$1 = BaseRequestParamsSchema$1.extend({ - ref: schemas_union([PromptReferenceSchema$1, ResourceTemplateReferenceSchema$1]), - argument: schemas_object({ - name: schemas_string(), - value: schemas_string() - }), - context: schemas_object({ arguments: schemas_record(schemas_string(), schemas_string()).optional() }).optional() - }); - /** - * A request from the client to the server, to ask for completion options. - */ - const CompleteRequestSchema$1 = RequestSchema$1.extend({ - method: literal("completion/complete"), - params: CompleteRequestParamsSchema$1 - }); - /** - * The server's response to a {@linkcode CompleteRequest | completion/complete} request - */ - const CompleteResultSchema$1 = ResultSchema$1.extend({ completion: looseObject({ - values: schemas_array(schemas_string()).max(100), - total: schemas_optional(schemas_number().int()), - hasMore: schemas_optional(schemas_boolean()) - }) }); - /** - * Represents a root directory or file that the server can operate on. - * - * @deprecated Deprecated as of protocol version 2026-07-28 (SEP-2577); remains - * in the specification for at least twelve months. Migrate to passing paths via - * tool parameters, resource URIs, or configuration. - */ - const RootSchema$1 = schemas_object({ - uri: schemas_string().startsWith("file://"), - name: schemas_string().optional(), - _meta: schemas_record(schemas_string(), unknown()).optional() - }); - /** - * Sent from the server to request a list of root URIs from the client. - * - * @deprecated Deprecated as of protocol version 2026-07-28 (SEP-2577); remains - * in the specification for at least twelve months. Migrate to passing paths via - * tool parameters, resource URIs, or configuration. - */ - const ListRootsRequestSchema$1 = RequestSchema$1.extend({ - method: literal("roots/list"), - params: BaseRequestParamsSchema$1.optional() - }); - /** - * The client's response to a `roots/list` request from the server. - * - * @deprecated Deprecated as of protocol version 2026-07-28 (SEP-2577); remains - * in the specification for at least twelve months. Migrate to passing paths via - * tool parameters, resource URIs, or configuration. - */ - const ListRootsResultSchema$1 = ResultSchema$1.extend({ roots: schemas_array(RootSchema$1) }); - /** - * A notification from the client to the server, informing it that the list of roots has changed. - * - * @deprecated Deprecated as of protocol version 2026-07-28 (SEP-2577); remains - * in the specification for at least twelve months. Migrate to passing paths via - * tool parameters, resource URIs, or configuration. - */ - const RootsListChangedNotificationSchema$1 = NotificationSchema$1.extend({ - method: literal("notifications/roots/list_changed"), - params: NotificationsParamsSchema$1.optional() - }); - /** - * Task creation parameters, used to ask that the server create a task to represent a request. - * - * @deprecated 2025-11-25 wire vocabulary with no SDK runtime; kept importable for interoperability only. - */ - const TaskCreationParamsSchema$1 = looseObject({ - ttl: schemas_number().optional(), - pollInterval: schemas_number().optional() - }); - /** - * The status of a task. - * - * @deprecated 2025-11-25 wire vocabulary with no SDK runtime; kept importable for interoperability only. - */ - const TaskStatusSchema$1 = schemas_enum([ - "working", - "input_required", - "completed", - "failed", - "cancelled" - ]); - /** - * A pollable state object associated with a request. - * - * @deprecated 2025-11-25 wire vocabulary with no SDK runtime; kept importable for interoperability only. - */ - const TaskSchema$1 = schemas_object({ - taskId: schemas_string(), - status: TaskStatusSchema$1, - ttl: schemas_union([schemas_number(), schemas_null()]), - createdAt: schemas_string(), - lastUpdatedAt: schemas_string(), - pollInterval: schemas_optional(schemas_number()), - statusMessage: schemas_optional(schemas_string()) - }); - /** - * Result returned when a task is created, containing the task data wrapped in a `task` field. - * - * @deprecated 2025-11-25 wire vocabulary with no SDK runtime; kept importable for interoperability only. - */ - const CreateTaskResultSchema$1 = ResultSchema$1.extend({ task: TaskSchema$1 }); - /** - * Parameters for task status notification. - * - * @deprecated 2025-11-25 wire vocabulary with no SDK runtime; kept importable for interoperability only. - */ - const TaskStatusNotificationParamsSchema$1 = NotificationsParamsSchema$1.merge(TaskSchema$1); - /** - * A notification sent when a task's status changes. - * - * @deprecated 2025-11-25 wire vocabulary with no SDK runtime; kept importable for interoperability only. - */ - const TaskStatusNotificationSchema$1 = NotificationSchema$1.extend({ - method: literal("notifications/tasks/status"), - params: TaskStatusNotificationParamsSchema$1 - }); - /** - * A request to get the state of a specific task. - * - * @deprecated 2025-11-25 wire vocabulary with no SDK runtime; kept importable for interoperability only. - */ - const GetTaskRequestSchema$1 = RequestSchema$1.extend({ - method: literal("tasks/get"), - params: BaseRequestParamsSchema$1.extend({ taskId: schemas_string() }) - }); - /** - * The response to a {@linkcode GetTaskRequest | tasks/get} request. - * - * @deprecated 2025-11-25 wire vocabulary with no SDK runtime; kept importable for interoperability only. - */ - const GetTaskResultSchema$1 = ResultSchema$1.merge(TaskSchema$1); - /** - * A request to get the result of a specific task. - * - * @deprecated 2025-11-25 wire vocabulary with no SDK runtime; kept importable for interoperability only. - */ - const GetTaskPayloadRequestSchema$1 = RequestSchema$1.extend({ - method: literal("tasks/result"), - params: BaseRequestParamsSchema$1.extend({ taskId: schemas_string() }) - }); - /** - * The response to a `tasks/result` request. - * The structure matches the result type of the original request. - * For example, a {@linkcode CallToolRequest | tools/call} task would return the `CallToolResult` structure. - * - * - * @deprecated 2025-11-25 wire vocabulary with no SDK runtime; kept importable for interoperability only. - */ - const GetTaskPayloadResultSchema$1 = ResultSchema$1.loose(); - /** - * A request to list tasks. - * - * @deprecated 2025-11-25 wire vocabulary with no SDK runtime; kept importable for interoperability only. - */ - const ListTasksRequestSchema$1 = PaginatedRequestSchema$1.extend({ method: literal("tasks/list") }); - /** - * The response to a {@linkcode ListTasksRequest | tasks/list} request. - * - * @deprecated 2025-11-25 wire vocabulary with no SDK runtime; kept importable for interoperability only. - */ - const ListTasksResultSchema$1 = PaginatedResultSchema$1.extend({ tasks: schemas_array(TaskSchema$1) }); - /** - * A request to cancel a specific task. - * - * @deprecated 2025-11-25 wire vocabulary with no SDK runtime; kept importable for interoperability only. - */ - const CancelTaskRequestSchema$1 = RequestSchema$1.extend({ - method: literal("tasks/cancel"), - params: BaseRequestParamsSchema$1.extend({ taskId: schemas_string() }) - }); - return { - JSONValueSchema: JSONValueSchema$1, - JSONObjectSchema: JSONObjectSchema$1, - ProgressTokenSchema: ProgressTokenSchema$1, - CursorSchema: CursorSchema$1, - TaskMetadataSchema: TaskMetadataSchema$1, - RelatedTaskMetadataSchema: RelatedTaskMetadataSchema$1, - RequestMetaSchema: RequestMetaSchema$1, - BaseRequestParamsSchema: BaseRequestParamsSchema$1, - TaskAugmentedRequestParamsSchema: TaskAugmentedRequestParamsSchema$1, - RequestSchema: RequestSchema$1, - NotificationsParamsSchema: NotificationsParamsSchema$1, - NotificationSchema: NotificationSchema$1, - ResultSchema: ResultSchema$1, - RequestIdSchema: RequestIdSchema$1, - EmptyResultSchema: EmptyResultSchema$1, - CancelledNotificationParamsSchema: CancelledNotificationParamsSchema$1, - CancelledNotificationSchema: CancelledNotificationSchema$1, - IconSchema: IconSchema$1, - IconsSchema: IconsSchema$1, - BaseMetadataSchema: BaseMetadataSchema$1, - ImplementationSchema: ImplementationSchema$1, - ClientTasksCapabilitySchema: ClientTasksCapabilitySchema$1, - ServerTasksCapabilitySchema: ServerTasksCapabilitySchema$1, - ClientCapabilitiesSchema: ClientCapabilitiesSchema$1, - InitializeRequestParamsSchema: InitializeRequestParamsSchema$1, - InitializeRequestSchema: InitializeRequestSchema$1, - ServerCapabilitiesSchema: ServerCapabilitiesSchema$1, - InitializeResultSchema: InitializeResultSchema$1, - InitializedNotificationSchema: InitializedNotificationSchema$1, - PingRequestSchema: PingRequestSchema$1, - ProgressSchema: ProgressSchema$1, - ProgressNotificationParamsSchema: ProgressNotificationParamsSchema$1, - ProgressNotificationSchema: ProgressNotificationSchema$1, - PaginatedRequestParamsSchema: PaginatedRequestParamsSchema$1, - PaginatedRequestSchema: PaginatedRequestSchema$1, - PaginatedResultSchema: PaginatedResultSchema$1, - ResourceContentsSchema: ResourceContentsSchema$1, - TextResourceContentsSchema: TextResourceContentsSchema$1, - BlobResourceContentsSchema: BlobResourceContentsSchema$1, - RoleSchema: RoleSchema$1, - AnnotationsSchema: AnnotationsSchema$1, - ResourceSchema: ResourceSchema$1, - ResourceTemplateSchema: ResourceTemplateSchema$1, - ListResourcesRequestSchema: ListResourcesRequestSchema$1, - ListResourcesResultSchema: ListResourcesResultSchema$1, - ListResourceTemplatesRequestSchema: ListResourceTemplatesRequestSchema$1, - ListResourceTemplatesResultSchema: ListResourceTemplatesResultSchema$1, - ResourceRequestParamsSchema: ResourceRequestParamsSchema$1, - ReadResourceRequestParamsSchema: ReadResourceRequestParamsSchema$1, - ReadResourceRequestSchema: ReadResourceRequestSchema$1, - ReadResourceResultSchema: ReadResourceResultSchema$1, - ResourceListChangedNotificationSchema: ResourceListChangedNotificationSchema$1, - SubscribeRequestParamsSchema: SubscribeRequestParamsSchema$1, - SubscribeRequestSchema: SubscribeRequestSchema$1, - UnsubscribeRequestParamsSchema: UnsubscribeRequestParamsSchema$1, - UnsubscribeRequestSchema: UnsubscribeRequestSchema$1, - ResourceUpdatedNotificationParamsSchema: ResourceUpdatedNotificationParamsSchema$1, - ResourceUpdatedNotificationSchema: ResourceUpdatedNotificationSchema$1, - PromptArgumentSchema: PromptArgumentSchema$1, - PromptSchema: PromptSchema$1, - ListPromptsRequestSchema: ListPromptsRequestSchema$1, - ListPromptsResultSchema: ListPromptsResultSchema$1, - GetPromptRequestParamsSchema: GetPromptRequestParamsSchema$1, - GetPromptRequestSchema: GetPromptRequestSchema$1, - TextContentSchema: TextContentSchema$1, - ImageContentSchema: ImageContentSchema$1, - AudioContentSchema: AudioContentSchema$1, - ToolUseContentSchema: ToolUseContentSchema$1, - EmbeddedResourceSchema: EmbeddedResourceSchema$1, - ResourceLinkSchema: ResourceLinkSchema$1, - ContentBlockSchema: ContentBlockSchema$1, - PromptMessageSchema: PromptMessageSchema$1, - GetPromptResultSchema: GetPromptResultSchema$1, - PromptListChangedNotificationSchema: PromptListChangedNotificationSchema$1, - ToolAnnotationsSchema: ToolAnnotationsSchema$1, - ToolExecutionSchema: ToolExecutionSchema$1, - ToolSchema: ToolSchema$1, - ListToolsRequestSchema: ListToolsRequestSchema$1, - ListToolsResultSchema: ListToolsResultSchema$1, - CallToolResultSchema: CallToolResultSchema$1, - CallToolRequestParamsSchema: CallToolRequestParamsSchema$1, - CallToolRequestSchema: CallToolRequestSchema$1, - ToolListChangedNotificationSchema: ToolListChangedNotificationSchema$1, - LoggingLevelSchema: LoggingLevelSchema$1, - SetLevelRequestParamsSchema: SetLevelRequestParamsSchema$1, - SetLevelRequestSchema: SetLevelRequestSchema$1, - LoggingMessageNotificationParamsSchema: LoggingMessageNotificationParamsSchema$1, - LoggingMessageNotificationSchema: LoggingMessageNotificationSchema$1, - ModelHintSchema: ModelHintSchema$1, - ModelPreferencesSchema: ModelPreferencesSchema$1, - ToolChoiceSchema: ToolChoiceSchema$1, - ToolResultContentSchema: ToolResultContentSchema$1, - SamplingContentSchema: SamplingContentSchema$1, - SamplingMessageContentBlockSchema: SamplingMessageContentBlockSchema$1, - SamplingMessageSchema: SamplingMessageSchema$1, - CreateMessageRequestParamsSchema: CreateMessageRequestParamsSchema$1, - CreateMessageRequestSchema: CreateMessageRequestSchema$1, - CreateMessageResultSchema: CreateMessageResultSchema$1, - CreateMessageResultWithToolsSchema: CreateMessageResultWithToolsSchema$1, - BooleanSchemaSchema: BooleanSchemaSchema$1, - StringSchemaSchema: StringSchemaSchema$1, - NumberSchemaSchema: NumberSchemaSchema$1, - UntitledSingleSelectEnumSchemaSchema: UntitledSingleSelectEnumSchemaSchema$1, - TitledSingleSelectEnumSchemaSchema: TitledSingleSelectEnumSchemaSchema$1, - LegacyTitledEnumSchemaSchema: LegacyTitledEnumSchemaSchema$1, - SingleSelectEnumSchemaSchema: SingleSelectEnumSchemaSchema$1, - UntitledMultiSelectEnumSchemaSchema: UntitledMultiSelectEnumSchemaSchema$1, - TitledMultiSelectEnumSchemaSchema: TitledMultiSelectEnumSchemaSchema$1, - MultiSelectEnumSchemaSchema: MultiSelectEnumSchemaSchema$1, - EnumSchemaSchema: EnumSchemaSchema$1, - PrimitiveSchemaDefinitionSchema: PrimitiveSchemaDefinitionSchema$1, - ElicitRequestFormParamsSchema: ElicitRequestFormParamsSchema$1, - ElicitRequestURLParamsSchema: ElicitRequestURLParamsSchema$1, - ElicitRequestParamsSchema: ElicitRequestParamsSchema$1, - ElicitRequestSchema: ElicitRequestSchema$1, - ElicitationCompleteNotificationParamsSchema: ElicitationCompleteNotificationParamsSchema$1, - ElicitationCompleteNotificationSchema: ElicitationCompleteNotificationSchema$1, - ElicitResultSchema: ElicitResultSchema$1, - ResourceTemplateReferenceSchema: ResourceTemplateReferenceSchema$1, - PromptReferenceSchema: PromptReferenceSchema$1, - CompleteRequestParamsSchema: CompleteRequestParamsSchema$1, - CompleteRequestSchema: CompleteRequestSchema$1, - CompleteResultSchema: CompleteResultSchema$1, - RootSchema: RootSchema$1, - ListRootsRequestSchema: ListRootsRequestSchema$1, - ListRootsResultSchema: ListRootsResultSchema$1, - RootsListChangedNotificationSchema: RootsListChangedNotificationSchema$1, - TaskCreationParamsSchema: TaskCreationParamsSchema$1, - TaskStatusSchema: TaskStatusSchema$1, - TaskSchema: TaskSchema$1, - CreateTaskResultSchema: CreateTaskResultSchema$1, - TaskStatusNotificationParamsSchema: TaskStatusNotificationParamsSchema$1, - TaskStatusNotificationSchema: TaskStatusNotificationSchema$1, - GetTaskRequestSchema: GetTaskRequestSchema$1, - GetTaskResultSchema: GetTaskResultSchema$1, - GetTaskPayloadRequestSchema: GetTaskPayloadRequestSchema$1, - GetTaskPayloadResultSchema: GetTaskPayloadResultSchema$1, - ListTasksRequestSchema: ListTasksRequestSchema$1, - ListTasksResultSchema: ListTasksResultSchema$1, - CancelTaskRequestSchema: CancelTaskRequestSchema$1, - CancelTaskResultSchema: ResultSchema$1.merge(TaskSchema$1), - ClientRequestSchema: schemas_union([ - PingRequestSchema$1, - InitializeRequestSchema$1, - CompleteRequestSchema$1, - SetLevelRequestSchema$1, - GetPromptRequestSchema$1, - ListPromptsRequestSchema$1, - ListResourcesRequestSchema$1, - ListResourceTemplatesRequestSchema$1, - ReadResourceRequestSchema$1, - SubscribeRequestSchema$1, - UnsubscribeRequestSchema$1, - CallToolRequestSchema$1, - ListToolsRequestSchema$1, - GetTaskRequestSchema$1, - GetTaskPayloadRequestSchema$1, - ListTasksRequestSchema$1, - CancelTaskRequestSchema$1 - ]), - ClientNotificationSchema: schemas_union([ - CancelledNotificationSchema$1, - ProgressNotificationSchema$1, - InitializedNotificationSchema$1, - RootsListChangedNotificationSchema$1, - TaskStatusNotificationSchema$1 - ]), - ClientResultSchema: schemas_union([ - EmptyResultSchema$1, - CreateMessageResultSchema$1, - CreateMessageResultWithToolsSchema$1, - ElicitResultSchema$1, - ListRootsResultSchema$1, - GetTaskResultSchema$1, - ListTasksResultSchema$1, - CreateTaskResultSchema$1 - ]), - ServerRequestSchema: schemas_union([ - PingRequestSchema$1, - CreateMessageRequestSchema$1, - ElicitRequestSchema$1, - ListRootsRequestSchema$1, - GetTaskRequestSchema$1, - GetTaskPayloadRequestSchema$1, - ListTasksRequestSchema$1, - CancelTaskRequestSchema$1 - ]), - ServerNotificationSchema: schemas_union([ - CancelledNotificationSchema$1, - ProgressNotificationSchema$1, - LoggingMessageNotificationSchema$1, - ResourceUpdatedNotificationSchema$1, - ResourceListChangedNotificationSchema$1, - ToolListChangedNotificationSchema$1, - PromptListChangedNotificationSchema$1, - TaskStatusNotificationSchema$1, - ElicitationCompleteNotificationSchema$1 - ]), - ServerResultSchema: schemas_union([ - EmptyResultSchema$1, - InitializeResultSchema$1, - CompleteResultSchema$1, - GetPromptResultSchema$1, - ListPromptsResultSchema$1, - ListResourcesResultSchema$1, - ListResourceTemplatesResultSchema$1, - ReadResourceResultSchema$1, - CallToolResultSchema$1, - ListToolsResultSchema$1, - GetTaskResultSchema$1, - ListTasksResultSchema$1, - CreateTaskResultSchema$1 - ]), - CallToolResultWireSchema: unknown().superRefine((value, ctx) => { - if (typeof value !== "object" || value === null || Array.isArray(value) || value.content !== void 0) return; - for (const key of TOOL_RESULT_FOREIGN_FAMILY_KEYS) if (key in value) { - ctx.addIssue({ - code: "custom", - message: `content is required when the body carries '${key}' — another result family cannot default into an empty tools/call success` - }); - return; - } - }).transform(normalizeContentlessToolResult).pipe(CallToolResultSchema$1) - }; -} -let memo$1; -/** -* Builds the era wire-schema set on first call and returns the same object -* thereafter. Module evaluation stays construction-free so importing the -* era codec/registry costs nothing until the first validation actually -* needs a schema; the registry, the codec, and the eager `schemas.ts` -* shim all pull through this memo, so reference identity holds across -* every consumer. -*/ -function buildSchemas2025() { - return memo$1 ??= build$1(); -} - -//#endregion -//#region ../core-internal/src/wire/rev2025-11-25/legacyWrap.ts -/** -* SEP-2106 legacy `outputSchema` wrap helpers (2025-era projection only). -* -* The neutral / 2026-07-28 model lets a tool's `outputSchema` carry any JSON -* Schema root. The 2025-11-25 wire shape requires `type:'object'` at the root, -* so when an era-blind handler advertises a non-object root, the 2025 codec's -* `encodeResult('tools/list', …)` projects it down to -* `{type:'object', properties:{result:}, required:['result']}`, and -* `projectCallToolResult` wraps the matching `structuredContent` as -* `{result:}`. The 2026 codec's projections are the identity. -* -* These helpers are wire-layer property — they exist so the projection can -* live behind {@link WireCodec.encodeResult} / {@link WireCodec.projectCallToolResult} -* and never be re-derived in shared/ or server-side code. -*/ -/** -* Whether a JSON Schema's root is non-object: either an explicit non-object -* `type`, or a typeless root such as `{anyOf:[…]}`. Object-shaped typeless -* roots that the schema-conversion layer can prove are objects are stamped -* `type:'object'` upstream, so they reach this predicate as object roots. -*/ -function isNonObjectJsonSchemaRoot(json) { - return json["type"] !== "object"; -} -/** -* Keyword-position keys whose values are instance data (not subschemas). A -* `{$ref:…}` appearing inside one is a literal value, not a JSON Pointer to -* rewrite. Only consulted when the current object is in keyword position — -* a PROPERTY named `default`/`const` (under `properties`/`$defs`/…) is a name -* position whose value IS a subschema and is recursed into. -*/ -const REF_REWRITE_DATA_POSITION_KEYS = new Set([ - "const", - "enum", - "default", - "examples" -]); -/** -* Keyword-position keys whose value is a name→subschema map. Entries inside -* such a map are in NAME position: their keys are author-chosen property -* names (which may collide with JSON Schema keywords), their values are -* subschemas to recurse into. -*/ -const REF_REWRITE_NAME_MAP_KEYS = new Set([ - "properties", - "patternProperties", - "$defs", - "definitions", - "dependentSchemas", - "dependencies" -]); -/** -* Whether a subtree's `$id` establishes a new resolution base. A fragment-only -* `$id` (`"#item"`, the draft-07/06 spelling of 2020-12's `$anchor`) does not -* change the RFC 3986 base URI — same-document pointers inside still resolve -* against the document root and must be rewritten. -*/ -function establishesNewBase(id) { - return id !== void 0 && !(typeof id === "string" && id.startsWith("#")); -} -/** -* Wrap a non-object output schema in the 2025-era envelope: -* `{type:'object', properties:{result:}, required:['result']}`. -* -* Same-document `$ref` / `$dynamicRef` JSON Pointers inside the natural schema -* (e.g. `#/properties/foo` produced by zod for de-duplicated/recursive types) -* are rewritten to account for the new `#/properties/result` root: bare `#` → -* `#/properties/result`, `#/…` → `#/properties/result/…`. Cross-document refs -* (anything not starting with `#`) are left untouched. -* -* The rewrite is position-aware: data-valued keywords -* (`const`/`enum`/`default`/`examples`) in keyword position are NOT descended -* into; the same names appearing as property names under -* `properties`/`patternProperties`/`$defs`/`definitions`/`dependentSchemas`/ -* `dependencies` ARE descended into (they're subschemas). The rewrite is also -* `$id`-scoped: if the natural root carries a base-establishing `$id` no -* pointer is rewritten (same-document refs inside resolve against the embedded -* `$id` base, not the wrapper root), and any subtree that establishes its own -* `$id` is left untouched for the same reason. Fragment-only `$id` (`"#item"`, -* draft-07's anchor spelling) does not establish a base and IS descended into. -*/ -function wrapOutputSchemaForLegacy(natural) { - const $schema = typeof natural["$schema"] === "string" ? natural["$schema"] : void 0; - if (establishesNewBase(natural["$id"])) return { - ...$schema !== void 0 && { $schema }, - type: "object", - properties: { result: natural }, - required: ["result"] - }; - const convertRecursiveRefs = declares2019Dialect(natural["$schema"]) && natural["$recursiveAnchor"] !== true; - const rewriteRefs = (node, parentIsNameMap) => { - if (Array.isArray(node)) return node.map((item) => rewriteRefs(item, false)); - if (node === null || typeof node !== "object") return node; - if (!parentIsNameMap && establishesNewBase(node["$id"])) return node; - const out = {}; - let convertedRecursion = false; - for (const [k, v] of Object.entries(node)) if (parentIsNameMap) out[k] = rewriteRefs(v, false); - else if ((k === "$ref" || k === "$dynamicRef") && typeof v === "string") out[k] = v === "#" ? "#/properties/result" : v.startsWith("#/") ? `#/properties/result${v.slice(1)}` : v; - else if (k === "$recursiveRef" && v === "#" && convertRecursiveRefs) convertedRecursion = true; - else if (REF_REWRITE_DATA_POSITION_KEYS.has(k)) out[k] = v; - else if (REF_REWRITE_NAME_MAP_KEYS.has(k)) out[k] = rewriteRefs(v, true); - else out[k] = rewriteRefs(v, false); - if (convertedRecursion) if ("$ref" in out) out["allOf"] = [...Array.isArray(out["allOf"]) ? out["allOf"] : [], { $ref: "#/properties/result" }]; - else out["$ref"] = "#/properties/result"; - return out; - }; - return { - ...$schema !== void 0 && { $schema }, - type: "object", - properties: { result: rewriteRefs(natural, false) }, - required: ["result"] - }; -} - -//#endregion -//#region ../core-internal/src/wire/rev2025-11-25/registry.ts -const requestMethodKeys$1 = { - 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 -}; -const notificationMethodKeys$1 = { - "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 -}; -const resultMethodKeys = { - 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 -}; -let maps$1; -function registryMaps() { - if (maps$1) return maps$1; - const s = buildSchemas2025(); - maps$1 = { - requestSchemas: { - ping: s.PingRequestSchema, - initialize: s.InitializeRequestSchema, - "completion/complete": s.CompleteRequestSchema, - "logging/setLevel": s.SetLevelRequestSchema, - "prompts/get": s.GetPromptRequestSchema, - "prompts/list": s.ListPromptsRequestSchema, - "resources/list": s.ListResourcesRequestSchema, - "resources/templates/list": s.ListResourceTemplatesRequestSchema, - "resources/read": s.ReadResourceRequestSchema, - "resources/subscribe": s.SubscribeRequestSchema, - "resources/unsubscribe": s.UnsubscribeRequestSchema, - "tools/call": s.CallToolRequestSchema, - "tools/list": s.ListToolsRequestSchema, - "tasks/get": s.GetTaskRequestSchema, - "tasks/result": s.GetTaskPayloadRequestSchema, - "tasks/list": s.ListTasksRequestSchema, - "tasks/cancel": s.CancelTaskRequestSchema, - "sampling/createMessage": s.CreateMessageRequestSchema, - "elicitation/create": s.ElicitRequestSchema, - "roots/list": s.ListRootsRequestSchema - }, - notificationSchemas: { - "notifications/cancelled": s.CancelledNotificationSchema, - "notifications/progress": s.ProgressNotificationSchema, - "notifications/initialized": s.InitializedNotificationSchema, - "notifications/roots/list_changed": s.RootsListChangedNotificationSchema, - "notifications/tasks/status": s.TaskStatusNotificationSchema, - "notifications/message": s.LoggingMessageNotificationSchema, - "notifications/resources/updated": s.ResourceUpdatedNotificationSchema, - "notifications/resources/list_changed": s.ResourceListChangedNotificationSchema, - "notifications/tools/list_changed": s.ToolListChangedNotificationSchema, - "notifications/prompts/list_changed": s.PromptListChangedNotificationSchema, - "notifications/elicitation/complete": s.ElicitationCompleteNotificationSchema - }, - resultSchemas: { - ping: s.EmptyResultSchema, - initialize: s.InitializeResultSchema, - "completion/complete": s.CompleteResultSchema, - "logging/setLevel": s.EmptyResultSchema, - "prompts/get": s.GetPromptResultSchema, - "prompts/list": s.ListPromptsResultSchema, - "resources/list": s.ListResourcesResultSchema, - "resources/templates/list": s.ListResourceTemplatesResultSchema, - "resources/read": s.ReadResourceResultSchema, - "resources/subscribe": s.EmptyResultSchema, - "resources/unsubscribe": s.EmptyResultSchema, - "tools/call": s.CallToolResultWireSchema, - "tools/list": s.ListToolsResultSchema, - "sampling/createMessage": s.CreateMessageResultWithToolsSchema, - "elicitation/create": s.ElicitResultSchema, - "roots/list": s.ListRootsResultSchema - } - }; - return maps$1; -} -/** -* Forces the lazy registry maps (and, through them, the era's schema memo). -* Warm-up hook for `preloadSchemas()` — no-op once the maps exist. -*/ -function warmRegistryMaps2025() { - registryMaps(); -} -/** The 2025-era request-method set (registry membership = the deletion story). */ -function hasRequestMethod2025(method) { - return Object.prototype.hasOwnProperty.call(requestMethodKeys$1, method); -} -/** The 2025-era notification-method set. */ -function hasNotificationMethod2025(method) { - return Object.prototype.hasOwnProperty.call(notificationMethodKeys$1, method); -} -/** Result-map membership: exactly the era's typed-method subset (no task entries, no 2026-only methods). */ -function hasResultMethod(method) { - return Object.prototype.hasOwnProperty.call(resultMethodKeys, method); -} -function getResultSchema(method) { - return hasResultMethod(method) ? registryMaps().resultSchemas[method] : void 0; -} -function getRequestSchema(method) { - return hasRequestMethod2025(method) ? registryMaps().requestSchemas[method] : void 0; -} -function getNotificationSchema(method) { - return hasNotificationMethod2025(method) ? registryMaps().notificationSchemas[method] : void 0; -} -/** Registry method lists (for the spec-method universe and the CI registry-diff oracle). */ -const rev2025RequestMethods = Object.keys(requestMethodKeys$1); -const rev2025NotificationMethods = Object.keys(notificationMethodKeys$1); - -//#endregion -//#region ../core-internal/src/wire/rev2025-11-25/codec.ts -function isPlainObject$6(value) { - return value !== null && typeof value === "object" && !Array.isArray(value); -} -/** Tri-state wrap of an optional Zod schema lookup (the function-only contract). */ -function triState$1(schema, raw) { - if (schema === void 0) return { - ok: false, - reason: "not-in-era" - }; - const parsed = schema.safeParse(raw); - return parsed.success ? { - ok: true, - value: parsed.data - } : { - ok: false, - reason: "invalid", - message: String(parsed.error) - }; -} -const NOT_IN_ERA$1 = { - ok: false, - reason: "not-in-era" -}; -/** Whether a `tools/list` entry advertises a non-object `outputSchema` root that needs the SEP-2106 legacy wrap. */ -function toolNeedsLegacyWrap(t) { - return isPlainObject$6(t) && isPlainObject$6(t["outputSchema"]) && isNonObjectJsonSchemaRoot(t["outputSchema"]); -} -/** The wire→neutral trust boundary: a decoded 2025-era wire result is adopted as the neutral `Result` here (the module's single deliberate assertion). */ -function toNeutralResult(value) { - return value; -} -const rev2025Codec = { - era: "2025-11-25", - hasRequestMethod: hasRequestMethod2025, - hasNotificationMethod: hasNotificationMethod2025, - validateRequest: (method, raw) => triState$1(getRequestSchema(method), raw), - validateResult: (method, raw) => triState$1(getResultSchema(method), raw), - validateNotification: (method, raw) => triState$1(getNotificationSchema(method), raw), - hasInputRequestMethod: () => false, - validateInputRequest: () => NOT_IN_ERA$1, - validateInputResponse: () => NOT_IN_ERA$1, - samplingResultVariant: ((hasTools, raw) => { - const s = buildSchemas2025(); - return triState$1(hasTools ? s.CreateMessageResultWithToolsSchema : s.CreateMessageResultSchema, raw); - }), - outboundEnvelope: (_material) => void 0, - validateEnvelopeMeta: (_meta) => [], - projectCallToolResult(result, advertisedOutputSchema) { - const withText = appendTextFallbackForNonObject(result); - const sc = withText.structuredContent; - if (sc === void 0) return withText; - const valueIsNonObject = typeof sc !== "object" || sc === null || Array.isArray(sc); - const schemaWrapped = advertisedOutputSchema !== void 0 && isNonObjectJsonSchemaRoot(advertisedOutputSchema); - if (!valueIsNonObject && !schemaWrapped) return withText; - return { - ...withText, - structuredContent: { result: sc } - }; - }, - decodeResult(_method, raw) { - if (isPlainObject$6(raw) && "resultType" in raw) { - const stripped = { ...raw }; - delete stripped["resultType"]; - return { - kind: "complete", - result: toNeutralResult(stripped) - }; - } - return { - kind: "complete", - result: toNeutralResult(raw) - }; - }, - encodeResult(method, result) { - if (method !== "tools/list") return result; - const tools = result.tools; - if (!Array.isArray(tools) || !tools.some((t) => toolNeedsLegacyWrap(t))) return result; - return { - ...result, - tools: tools.map((t) => toolNeedsLegacyWrap(t) ? { - ...t, - outputSchema: wrapOutputSchemaForLegacy(t.outputSchema) - } : t) - }; - }, - encodeErrorCode: (code) => code === -32002 ? -32602 : code, - checkInboundEnvelope: (_material) => void 0 -}; - -//#endregion -//#region ../core-internal/src/wire/rev2026-07-28/buildSchemas.ts -/** -* 2026-era wire schemas (protocol revision 2026-07-28). -* -* Fully self-contained — no runtime imports from types/schemas.ts. The -* neutral types/schemas.ts layer is the public-API superset and is free to -* evolve; this file is the 2026 wire-parse contract and is BEHAVIOR-FROZEN -* against the 2026-07-28 anchor. Every era-shared building block (content -* blocks, resources, prompts, capabilities, notifications, …) that the wire -* shapes compose is a frozen LOCAL copy — verbatim from the neutral layer at -* the point this revision was sealed, dependencies first. The only cross-layer -* dependency is `import type { JSONObject, JSONValue }` from the neutral types -* barrel — pure structural type aliases with no parse behavior. -* -* This module is the only place the per-request `_meta` envelope is modeled. -* The envelope is wire-only vocabulary: the protocol layer lifts it off -* inbound requests before any handler runs and surfaces it at -* `ctx.mcpReq.envelope`; the 2026-era codec enforces its requiredness at -* dispatch time (`checkInboundEnvelope`) - the former neutral-schema JSDoc -* deferral ("enforced per request at dispatch time, not here") is now -* discharged by that codec step. -* -* No 2025-era traffic ever touches this module, so requiredness here is -* bare and spec-exact (the shared-schema `.catch` hazards do not apply). -* -* SPEC-CURRENCY RE-SEAL (2026-07-17): the 2026-07-28 revision was re-sealed -* upstream by spec PR #3002 (commit 71e30695, merged 2026-07-15 — after the -* previous anchor pin f68d864a): the envelope's `clientInfo` demoted from -* required to SHOULD, and `DiscoverResult.serverInfo` moved from the result -* body to the new `ResultMetaObject` key -* `_meta['io.modelcontextprotocol/serverInfo']` (optional on every result). -* The shapes below are the re-sealed anchor, exactly — no pre-#3002 shape is -* modeled anywhere (per ruling: the final revision is the only 2026-07-28). -*/ -function build() { - const JSONValueSchema$1 = lazy(() => schemas_union([ - schemas_string(), - schemas_number(), - schemas_boolean(), - schemas_null(), - schemas_record(schemas_string(), JSONValueSchema$1), - schemas_array(JSONValueSchema$1) - ])); - const JSONObjectSchema$1 = schemas_record(schemas_string(), JSONValueSchema$1); - /** - * A progress token, used to associate progress notifications with the original request. - */ - const ProgressTokenSchema$1 = schemas_union([schemas_string(), schemas_number().int()]); - /** - * An opaque token used to represent a cursor for pagination. - */ - const CursorSchema$1 = schemas_string(); - /** - * A uniquely identifying ID for a request in JSON-RPC. - */ - const RequestIdSchema$1 = schemas_union([schemas_string(), schemas_number().int()]); - /** - * The sender or recipient of messages and data in a conversation. - */ - const RoleSchema$1 = schemas_enum(["user", "assistant"]); - /** - * The severity of a log message. - */ - const LoggingLevelSchema$1 = schemas_enum([ - "debug", - "info", - "notice", - "warning", - "error", - "critical", - "alert", - "emergency" - ]); - /** - * A Zod schema for validating Base64 strings that is more performant and - * robust for very large inputs than the default regex-based check. It avoids - * stack overflows by using the native `atob` function for validation. - */ - const Base64Schema = schemas_string().refine((val) => { - try { - atob(val); - return true; - } catch { - return false; - } - }, { message: "Invalid Base64 string" }); - /** @deprecated 2025-11-25 wire vocabulary with no SDK runtime; kept importable for interoperability only. */ - const TaskMetadataSchema$1 = schemas_object({ ttl: schemas_number().optional() }); - /** @deprecated 2025-11-25 wire vocabulary with no SDK runtime; kept importable for interoperability only. */ - const RelatedTaskMetadataSchema$1 = schemas_object({ taskId: schemas_string() }); - const RequestMetaSchema$1 = looseObject({ - progressToken: ProgressTokenSchema$1.optional(), - "io.modelcontextprotocol/related-task": RelatedTaskMetadataSchema$1.optional() - }); - const BaseRequestParamsSchema$1 = schemas_object({ _meta: RequestMetaSchema$1.optional() }); - /** @deprecated 2025-11-25 wire vocabulary with no SDK runtime; kept importable for interoperability only. */ - const TaskAugmentedRequestParamsSchema$1 = BaseRequestParamsSchema$1.extend({ task: TaskMetadataSchema$1.optional() }); - const NotificationsParamsSchema$1 = schemas_object({ _meta: RequestMetaSchema$1.optional() }); - const NotificationSchema$1 = schemas_object({ - method: schemas_string(), - params: NotificationsParamsSchema$1.loose().optional() - }); - const IconSchema$1 = schemas_object({ - src: schemas_string(), - mimeType: schemas_string().optional(), - sizes: schemas_array(schemas_string()).optional(), - theme: schemas_enum(["light", "dark"]).optional() - }); - const IconsSchema$1 = schemas_object({ icons: schemas_array(IconSchema$1).optional() }); - const BaseMetadataSchema$1 = schemas_object({ - name: schemas_string(), - title: schemas_string().optional() - }); - const ImplementationSchema$1 = BaseMetadataSchema$1.extend({ - ...BaseMetadataSchema$1.shape, - ...IconsSchema$1.shape, - version: schemas_string(), - websiteUrl: schemas_string().optional(), - description: schemas_string().optional() - }); - const FormElicitationCapabilitySchema = intersection(schemas_object({ applyDefaults: schemas_boolean().optional() }), JSONObjectSchema$1); - const ElicitationCapabilitySchema = preprocess((value) => { - if (value && typeof value === "object" && !Array.isArray(value) && Object.keys(value).length === 0) return { form: {} }; - return value; - }, intersection(schemas_object({ - form: FormElicitationCapabilitySchema.optional(), - url: JSONObjectSchema$1.optional() - }), JSONObjectSchema$1.optional())); - /** @deprecated 2025-11-25 wire vocabulary with no SDK runtime; kept importable for interoperability only. */ - const ClientTasksCapabilitySchema$1 = looseObject({ - list: JSONObjectSchema$1.optional(), - cancel: JSONObjectSchema$1.optional(), - requests: looseObject({ - sampling: looseObject({ createMessage: JSONObjectSchema$1.optional() }).optional(), - elicitation: looseObject({ create: JSONObjectSchema$1.optional() }).optional() - }).optional() - }); - /** @deprecated 2025-11-25 wire vocabulary with no SDK runtime; kept importable for interoperability only. */ - const ServerTasksCapabilitySchema$1 = looseObject({ - list: JSONObjectSchema$1.optional(), - cancel: JSONObjectSchema$1.optional(), - requests: looseObject({ tools: looseObject({ call: JSONObjectSchema$1.optional() }).optional() }).optional() - }); - const ClientCapabilitiesSchema$1 = schemas_object({ - experimental: schemas_record(schemas_string(), JSONObjectSchema$1).optional(), - sampling: schemas_object({ - context: JSONObjectSchema$1.optional(), - tools: JSONObjectSchema$1.optional() - }).optional(), - elicitation: ElicitationCapabilitySchema.optional(), - roots: schemas_object({ listChanged: schemas_boolean().optional() }).optional(), - tasks: ClientTasksCapabilitySchema$1.optional(), - extensions: schemas_record(schemas_string(), JSONObjectSchema$1).optional() - }); - const ServerCapabilitiesSchema$1 = schemas_object({ - experimental: schemas_record(schemas_string(), JSONObjectSchema$1).optional(), - logging: JSONObjectSchema$1.optional(), - completions: JSONObjectSchema$1.optional(), - prompts: schemas_object({ listChanged: schemas_boolean().optional() }).optional(), - resources: schemas_object({ - subscribe: schemas_boolean().optional(), - listChanged: schemas_boolean().optional() - }).optional(), - tools: schemas_object({ listChanged: schemas_boolean().optional() }).optional(), - tasks: ServerTasksCapabilitySchema$1.optional(), - extensions: schemas_record(schemas_string(), JSONObjectSchema$1).optional() - }); - const ProgressSchema$1 = schemas_object({ - progress: schemas_number(), - total: schemas_optional(schemas_number()), - message: schemas_optional(schemas_string()) - }); - const ProgressNotificationParamsSchema$1 = schemas_object({ - ...NotificationsParamsSchema$1.shape, - ...ProgressSchema$1.shape, - progressToken: ProgressTokenSchema$1 - }); - const ProgressNotificationSchema$1 = NotificationSchema$1.extend({ - method: literal("notifications/progress"), - params: ProgressNotificationParamsSchema$1 - }); - const LoggingMessageNotificationParamsSchema$1 = NotificationsParamsSchema$1.extend({ - level: LoggingLevelSchema$1, - logger: schemas_string().optional(), - data: unknown() - }); - const LoggingMessageNotificationSchema$1 = NotificationSchema$1.extend({ - method: literal("notifications/message"), - params: LoggingMessageNotificationParamsSchema$1 - }); - const ResourceContentsSchema$1 = schemas_object({ - uri: schemas_string(), - mimeType: schemas_optional(schemas_string()), - _meta: schemas_record(schemas_string(), unknown()).optional() - }); - const TextResourceContentsSchema$1 = ResourceContentsSchema$1.extend({ text: schemas_string() }); - const BlobResourceContentsSchema$1 = ResourceContentsSchema$1.extend({ blob: Base64Schema }); - const AnnotationsSchema$1 = schemas_object({ - audience: schemas_array(RoleSchema$1).optional(), - priority: schemas_number().min(0).max(1).optional(), - lastModified: iso_datetime({ offset: true }).optional() - }); - const ResourceSchema$1 = schemas_object({ - ...BaseMetadataSchema$1.shape, - ...IconsSchema$1.shape, - uri: schemas_string(), - description: schemas_optional(schemas_string()), - mimeType: schemas_optional(schemas_string()), - size: schemas_optional(schemas_number()), - annotations: AnnotationsSchema$1.optional(), - _meta: schemas_optional(looseObject({})) - }); - const ResourceTemplateSchema$1 = schemas_object({ - ...BaseMetadataSchema$1.shape, - ...IconsSchema$1.shape, - uriTemplate: schemas_string(), - description: schemas_optional(schemas_string()), - mimeType: schemas_optional(schemas_string()), - annotations: AnnotationsSchema$1.optional(), - _meta: schemas_optional(looseObject({})) - }); - const ResourceListChangedNotificationSchema$1 = NotificationSchema$1.extend({ - method: literal("notifications/resources/list_changed"), - params: NotificationsParamsSchema$1.optional() - }); - const ResourceUpdatedNotificationParamsSchema$1 = NotificationsParamsSchema$1.extend({ uri: schemas_string() }); - const ResourceUpdatedNotificationSchema$1 = NotificationSchema$1.extend({ - method: literal("notifications/resources/updated"), - params: ResourceUpdatedNotificationParamsSchema$1 - }); - const PromptArgumentSchema$1 = schemas_object({ - name: schemas_string(), - description: schemas_optional(schemas_string()), - required: schemas_optional(schemas_boolean()) - }); - const PromptSchema$1 = schemas_object({ - ...BaseMetadataSchema$1.shape, - ...IconsSchema$1.shape, - description: schemas_optional(schemas_string()), - arguments: schemas_optional(schemas_array(PromptArgumentSchema$1)), - _meta: schemas_optional(looseObject({})) - }); - const PromptListChangedNotificationSchema$1 = NotificationSchema$1.extend({ - method: literal("notifications/prompts/list_changed"), - params: NotificationsParamsSchema$1.optional() - }); - const TextContentSchema$1 = schemas_object({ - type: literal("text"), - text: schemas_string(), - annotations: AnnotationsSchema$1.optional(), - _meta: schemas_record(schemas_string(), unknown()).optional() - }); - const ImageContentSchema$1 = schemas_object({ - type: literal("image"), - data: Base64Schema, - mimeType: schemas_string(), - annotations: AnnotationsSchema$1.optional(), - _meta: schemas_record(schemas_string(), unknown()).optional() - }); - const AudioContentSchema$1 = schemas_object({ - type: literal("audio"), - data: Base64Schema, - mimeType: schemas_string(), - annotations: AnnotationsSchema$1.optional(), - _meta: schemas_record(schemas_string(), unknown()).optional() - }); - const ToolUseContentSchema$1 = schemas_object({ - type: literal("tool_use"), - name: schemas_string(), - id: schemas_string(), - input: schemas_record(schemas_string(), unknown()), - _meta: schemas_record(schemas_string(), unknown()).optional() - }); - const EmbeddedResourceSchema$1 = schemas_object({ - type: literal("resource"), - resource: schemas_union([TextResourceContentsSchema$1, BlobResourceContentsSchema$1]), - annotations: AnnotationsSchema$1.optional(), - _meta: schemas_record(schemas_string(), unknown()).optional() - }); - const ResourceLinkSchema$1 = ResourceSchema$1.extend({ type: literal("resource_link") }); - const ContentBlockSchema$1 = schemas_union([ - TextContentSchema$1, - ImageContentSchema$1, - AudioContentSchema$1, - ResourceLinkSchema$1, - EmbeddedResourceSchema$1 - ]); - const PromptMessageSchema$1 = schemas_object({ - role: RoleSchema$1, - content: ContentBlockSchema$1 - }); - const ToolAnnotationsSchema$1 = schemas_object({ - title: schemas_string().optional(), - readOnlyHint: schemas_boolean().optional(), - destructiveHint: schemas_boolean().optional(), - idempotentHint: schemas_boolean().optional(), - openWorldHint: schemas_boolean().optional() - }); - const ToolListChangedNotificationSchema$1 = NotificationSchema$1.extend({ - method: literal("notifications/tools/list_changed"), - params: NotificationsParamsSchema$1.optional() - }); - const ModelHintSchema$1 = schemas_object({ name: schemas_string().optional() }); - const ModelPreferencesSchema$1 = schemas_object({ - hints: schemas_array(ModelHintSchema$1).optional(), - costPriority: schemas_number().min(0).max(1).optional(), - speedPriority: schemas_number().min(0).max(1).optional(), - intelligencePriority: schemas_number().min(0).max(1).optional() - }); - const ToolChoiceSchema$1 = schemas_object({ mode: schemas_enum([ - "auto", - "required", - "none" - ]).optional() }); - const BooleanSchemaSchema$1 = schemas_object({ - type: literal("boolean"), - title: schemas_string().optional(), - description: schemas_string().optional(), - default: schemas_boolean().optional() - }); - const StringSchemaSchema$1 = schemas_object({ - type: literal("string"), - title: schemas_string().optional(), - description: schemas_string().optional(), - minLength: schemas_number().optional(), - maxLength: schemas_number().optional(), - format: schemas_enum([ - "email", - "uri", - "date", - "date-time" - ]).optional(), - default: schemas_string().optional() - }); - const NumberSchemaSchema$1 = schemas_object({ - type: schemas_enum(["number", "integer"]), - title: schemas_string().optional(), - description: schemas_string().optional(), - minimum: schemas_number().optional(), - maximum: schemas_number().optional(), - default: schemas_number().optional() - }); - const UntitledSingleSelectEnumSchemaSchema$1 = schemas_object({ - type: literal("string"), - title: schemas_string().optional(), - description: schemas_string().optional(), - enum: schemas_array(schemas_string()), - default: schemas_string().optional() - }); - const TitledSingleSelectEnumSchemaSchema$1 = schemas_object({ - type: literal("string"), - title: schemas_string().optional(), - description: schemas_string().optional(), - oneOf: schemas_array(schemas_object({ - const: schemas_string(), - title: schemas_string() - })), - default: schemas_string().optional() - }); - const LegacyTitledEnumSchemaSchema$1 = schemas_object({ - type: literal("string"), - title: schemas_string().optional(), - description: schemas_string().optional(), - enum: schemas_array(schemas_string()), - enumNames: schemas_array(schemas_string()).optional(), - default: schemas_string().optional() - }); - const SingleSelectEnumSchemaSchema$1 = schemas_union([UntitledSingleSelectEnumSchemaSchema$1, TitledSingleSelectEnumSchemaSchema$1]); - const UntitledMultiSelectEnumSchemaSchema$1 = schemas_object({ - type: literal("array"), - title: schemas_string().optional(), - description: schemas_string().optional(), - minItems: schemas_number().optional(), - maxItems: schemas_number().optional(), - items: schemas_object({ - type: literal("string"), - enum: schemas_array(schemas_string()) - }), - default: schemas_array(schemas_string()).optional() - }); - const TitledMultiSelectEnumSchemaSchema$1 = schemas_object({ - type: literal("array"), - title: schemas_string().optional(), - description: schemas_string().optional(), - minItems: schemas_number().optional(), - maxItems: schemas_number().optional(), - items: schemas_object({ anyOf: schemas_array(schemas_object({ - const: schemas_string(), - title: schemas_string() - })) }), - default: schemas_array(schemas_string()).optional() - }); - const MultiSelectEnumSchemaSchema$1 = schemas_union([UntitledMultiSelectEnumSchemaSchema$1, TitledMultiSelectEnumSchemaSchema$1]); - const EnumSchemaSchema$1 = schemas_union([ - LegacyTitledEnumSchemaSchema$1, - SingleSelectEnumSchemaSchema$1, - MultiSelectEnumSchemaSchema$1 - ]); - const PrimitiveSchemaDefinitionSchema$1 = schemas_union([ - EnumSchemaSchema$1, - BooleanSchemaSchema$1, - StringSchemaSchema$1, - NumberSchemaSchema$1 - ]); - const ElicitRequestFormParamsSchema$1 = TaskAugmentedRequestParamsSchema$1.extend({ - mode: literal("form").optional(), - message: schemas_string(), - requestedSchema: schemas_object({ - type: literal("object"), - properties: schemas_record(schemas_string(), PrimitiveSchemaDefinitionSchema$1), - required: schemas_array(schemas_string()).optional() - }).catchall(unknown()) - }); - const ResourceTemplateReferenceSchema$1 = schemas_object({ - type: literal("ref/resource"), - uri: schemas_string() - }); - const PromptReferenceSchema$1 = schemas_object({ - type: literal("ref/prompt"), - name: schemas_string() - }); - const RootSchema$1 = schemas_object({ - uri: schemas_string().startsWith("file://"), - name: schemas_string().optional(), - _meta: schemas_record(schemas_string(), unknown()).optional() - }); - const sharedClientCapabilityShape = ClientCapabilitiesSchema$1.shape; - const ClientCapabilities2026Schema = schemas_object({ - experimental: sharedClientCapabilityShape.experimental, - sampling: sharedClientCapabilityShape.sampling, - elicitation: sharedClientCapabilityShape.elicitation, - roots: sharedClientCapabilityShape.roots, - extensions: sharedClientCapabilityShape.extensions - }); - const sharedServerCapabilityShape = ServerCapabilitiesSchema$1.shape; - const ServerCapabilities2026Schema = schemas_object({ - experimental: sharedServerCapabilityShape.experimental, - logging: sharedServerCapabilityShape.logging, - completions: sharedServerCapabilityShape.completions, - prompts: sharedServerCapabilityShape.prompts, - resources: sharedServerCapabilityShape.resources, - tools: sharedServerCapabilityShape.tools, - extensions: sharedServerCapabilityShape.extensions - }); - /** - * The per-request `_meta` envelope carried by every request under protocol revision - * 2026-07-28: the protocol version governing the request, the client implementation - * info, and the client's capabilities — declared per request rather than once at - * initialization — plus the optional log-level opt-in. - * - * This schema models the complete envelope on its own (loose: foreign keys - * pass through - the lift extracts exactly the reserved keys, so enforcement - * never sees extension material). Requiredness is enforced per request at - * dispatch time by the 2026-era codec's `checkInboundEnvelope` step. - */ - const RequestMetaEnvelopeSchema = looseObject({ - progressToken: ProgressTokenSchema$1.optional(), - [auth_CUe6YdwF_PROTOCOL_VERSION_META_KEY]: schemas_string(), - [auth_CUe6YdwF_CLIENT_INFO_META_KEY]: ImplementationSchema$1.optional(), - [auth_CUe6YdwF_CLIENT_CAPABILITIES_META_KEY]: ClientCapabilities2026Schema, - [LOG_LEVEL_META_KEY]: LoggingLevelSchema$1.optional() - }); - /** 2026-era Tool: anchor-exact — no `execution` (deleted vocabulary). */ - const ToolSchema$1 = schemas_object({ - ...BaseMetadataSchema$1.shape, - ...IconsSchema$1.shape, - description: schemas_string().optional(), - inputSchema: looseObject({ - $schema: schemas_string().optional(), - type: literal("object") - }), - outputSchema: looseObject({ $schema: schemas_string().optional() }).optional(), - annotations: ToolAnnotationsSchema$1.optional(), - _meta: schemas_record(schemas_string(), unknown()).optional() - }); - /** 2026-era ToolResultContent (anchor-exact: `structuredContent?: unknown`). */ - const ToolResultContentSchema$1 = schemas_object({ - type: literal("tool_result"), - toolUseId: schemas_string(), - content: schemas_array(ContentBlockSchema$1), - structuredContent: unknown().optional(), - isError: schemas_boolean().optional(), - _meta: schemas_record(schemas_string(), unknown()).optional() - }); - /** 2026-era sampling content union (composes the forked tool-result shape). */ - const SamplingMessageContentBlockSchema$1 = schemas_union([ - TextContentSchema$1, - ImageContentSchema$1, - AudioContentSchema$1, - ToolUseContentSchema$1, - ToolResultContentSchema$1 - ]); - /** 2026-era SamplingMessage (anchor-exact: single block or array). */ - const SamplingMessageSchema$1 = schemas_object({ - role: RoleSchema$1, - content: schemas_union([SamplingMessageContentBlockSchema$1, schemas_array(SamplingMessageContentBlockSchema$1)]), - _meta: schemas_record(schemas_string(), unknown()).optional() - }); - /** Open union per the anchor: 'complete' | 'input_required' | string. */ - const ResultTypeSchema = schemas_string(); - /** - * Result `_meta` (anchor `ResultMetaObject`, added by spec PR #3002): - * loose, with the serverInfo key typed when present; the outbound stamp - * is the encode contract's `stampServerInfoMeta` step. - */ - const ResultMetaSchema = looseObject({ [auth_CUe6YdwF_SERVER_INFO_META_KEY]: ImplementationSchema$1.optional().catch(void 0) }); - const wireMeta = ResultMetaSchema.optional(); - function wireResult(shape) { - return looseObject({ - _meta: wireMeta, - resultType: ResultTypeSchema.default("complete"), - ...shape - }); - } - const ResultSchema$1 = wireResult({}); - const PaginatedResultSchema$1 = wireResult({ nextCursor: CursorSchema$1.optional() }); - const CallToolResultSchema$1 = wireResult({ - content: schemas_array(ContentBlockSchema$1), - structuredContent: unknown().optional(), - isError: schemas_boolean().optional() - }); - const ListToolsResultSchema$1 = wireResult({ - ttlMs: schemas_number().int().min(0), - cacheScope: schemas_enum(["public", "private"]), - tools: schemas_array(ToolSchema$1), - nextCursor: CursorSchema$1.optional() - }); - const ListPromptsResultSchema$1 = wireResult({ - ttlMs: schemas_number().int().min(0), - cacheScope: schemas_enum(["public", "private"]), - prompts: schemas_array(PromptSchema$1), - nextCursor: CursorSchema$1.optional() - }); - const GetPromptResultSchema$1 = wireResult({ - description: schemas_string().optional(), - messages: schemas_array(PromptMessageSchema$1) - }); - const ListResourcesResultSchema$1 = wireResult({ - ttlMs: schemas_number().int().min(0), - cacheScope: schemas_enum(["public", "private"]), - resources: schemas_array(ResourceSchema$1), - nextCursor: CursorSchema$1.optional() - }); - const ListResourceTemplatesResultSchema$1 = wireResult({ - ttlMs: schemas_number().int().min(0), - cacheScope: schemas_enum(["public", "private"]), - resourceTemplates: schemas_array(ResourceTemplateSchema$1), - nextCursor: CursorSchema$1.optional() - }); - const ReadResourceResultSchema$1 = wireResult({ - ttlMs: schemas_number().int().min(0), - cacheScope: schemas_enum(["public", "private"]), - contents: schemas_array(schemas_union([TextResourceContentsSchema$1, BlobResourceContentsSchema$1])) - }); - const CompleteResultSchema$1 = wireResult({ completion: schemas_object({ - values: schemas_array(schemas_string()).max(100), - total: schemas_number().int().optional(), - hasMore: schemas_boolean().optional() - }).loose() }); - /** CacheableResult (SEP-2549): ttlMs and cacheScope REQUIRED per the anchor. */ - const CacheableResultSchema = wireResult({ - ttlMs: schemas_number().int().min(0), - cacheScope: schemas_enum(["public", "private"]) - }); - const DiscoverResultSchema$1 = wireResult({ - ttlMs: schemas_number().int().min(0).catch(0), - cacheScope: schemas_enum(["public", "private"]).catch("private"), - supportedVersions: schemas_array(schemas_string()), - capabilities: ServerCapabilities2026Schema, - instructions: schemas_string().optional() - }); - /** 2026-era CreateMessageRequestParams (anchor-exact: forked SamplingMessage/Tool, no task augmentation). */ - const CreateMessageRequestParamsSchema$1 = schemas_object({ - messages: schemas_array(SamplingMessageSchema$1), - modelPreferences: ModelPreferencesSchema$1.optional(), - systemPrompt: schemas_string().optional(), - includeContext: schemas_enum([ - "none", - "thisServer", - "allServers" - ]).optional(), - temperature: schemas_number().optional(), - maxTokens: schemas_number().int(), - stopSequences: schemas_array(schemas_string()).optional(), - metadata: JSONObjectSchema$1.optional(), - tools: schemas_array(ToolSchema$1).optional(), - toolChoice: ToolChoiceSchema$1.optional() - }); - /** 2026-era embedded sampling request (de-JSON-RPC'd). */ - const CreateMessageRequestSchema$1 = schemas_object({ - method: literal("sampling/createMessage"), - params: CreateMessageRequestParamsSchema$1 - }); - /** - * 2026-era embedded roots listing request (de-JSON-RPC'd). Embedded input - * requests do NOT carry the per-request `_meta` envelope on this revision — - * the anchor declares a bare optional `_meta` on `params`. - */ - const ListRootsRequestSchema$1 = schemas_object({ - method: literal("roots/list"), - params: schemas_object({ _meta: schemas_record(schemas_string(), unknown()).optional() }).optional() - }); - /** 2026-era embedded sampling response (anchor-exact: extends the forked SamplingMessage). */ - const CreateMessageResultSchema$1 = schemas_object({ - ...SamplingMessageSchema$1.shape, - model: schemas_string(), - stopReason: schemas_string().optional() - }); - /** 2026-era embedded roots listing response (anchor-exact: bare `roots` array). */ - const ListRootsResultSchema$1 = schemas_object({ roots: schemas_array(RootSchema$1) }); - /** 2026-era embedded elicitation response (anchor-exact: bare result, restricted content value types). */ - const ElicitResultSchema$1 = schemas_object({ - action: schemas_enum([ - "accept", - "decline", - "cancel" - ]), - content: schemas_record(schemas_string(), schemas_union([ - schemas_string(), - schemas_number(), - schemas_boolean(), - schemas_array(schemas_string()) - ])).optional() - }); - /** - * 2026-era URL-mode elicitation params (anchor-exact fork): the draft removed - * `elicitationId` (and the `notifications/elicitation/complete` channel it - * keyed) — the shared schema keeps the field because it is required on the - * frozen 2025-11-25 revision. - */ - const ElicitRequestURLParamsSchema$1 = schemas_object({ - mode: literal("url"), - message: schemas_string(), - url: schemas_string().url() - }); - /** 2026-era elicitation params (form mode is revision-identical; URL mode is the fork above). */ - const ElicitRequestParamsSchema$1 = schemas_union([ElicitRequestFormParamsSchema$1, ElicitRequestURLParamsSchema$1]); - /** 2026-era embedded elicitation request (de-JSON-RPC'd; see the URL-mode fork above). */ - const ElicitRequestSchema$1 = schemas_object({ - method: literal("elicitation/create"), - params: ElicitRequestParamsSchema$1 - }); - /** A single embedded input request (one of the three demoted server→client requests). */ - const InputRequestSchema = schemas_union([ - CreateMessageRequestSchema$1, - ListRootsRequestSchema$1, - ElicitRequestSchema$1 - ]); - /** A single embedded input response — the BARE result union (never a `{method, result}` wrapper). */ - const InputResponseSchema = schemas_union([ - CreateMessageResultSchema$1, - ListRootsResultSchema$1, - ElicitResultSchema$1 - ]); - /** Map of embedded input requests, keyed by server-assigned identifiers. */ - const InputRequestsSchema = schemas_record(schemas_string(), InputRequestSchema); - /** Map of embedded input responses, keyed by the corresponding request identifiers. */ - const InputResponsesSchema = schemas_record(schemas_string(), InputResponseSchema); - /** - * The wire InputRequiredResult: `resultType: 'input_required'` plus at least - * one of `inputRequests` / `requestState` (the at-least-one rule is enforced - * at the server seam, not by this parse shape). - */ - const InputRequiredResultSchema = wireResult({ - inputRequests: InputRequestsSchema.optional(), - requestState: schemas_string().optional() - }); - /** The retry-channel members carried by client-initiated requests on this revision. */ - const retryParamsShape = { - inputResponses: InputResponsesSchema.optional(), - requestState: schemas_string().optional() - }; - /** Anchor InputResponseRequestParams: the retry channel on top of the required request `_meta` envelope. */ - const InputResponseRequestParamsSchema = schemas_object({ - _meta: RequestMetaEnvelopeSchema, - ...retryParamsShape - }); - /** Post-lift request `_meta` (progressToken + extension keys; loose). */ - const DispatchRequestMetaSchema = looseObject({ progressToken: ProgressTokenSchema$1.optional() }); - function wireRequest(method, paramsShape) { - return schemas_object({ - method: literal(method), - params: schemas_object({ - _meta: RequestMetaEnvelopeSchema, - ...paramsShape - }) - }); - } - function dispatchRequest(method, paramsShape) { - return schemas_object({ - method: literal(method), - params: schemas_object({ - _meta: DispatchRequestMetaSchema.optional(), - ...paramsShape - }).optional() - }); - } - const callToolParamsShape = { - name: schemas_string(), - arguments: schemas_record(schemas_string(), unknown()).optional(), - ...retryParamsShape - }; - const paginatedParamsShape = { cursor: CursorSchema$1.optional() }; - const CallToolRequestSchema$1 = wireRequest("tools/call", callToolParamsShape); - const ListToolsRequestSchema$1 = wireRequest("tools/list", paginatedParamsShape); - const ListPromptsRequestSchema$1 = wireRequest("prompts/list", paginatedParamsShape); - const GetPromptRequestSchema$1 = wireRequest("prompts/get", { - name: schemas_string(), - arguments: schemas_record(schemas_string(), schemas_string()).optional(), - ...retryParamsShape - }); - const ListResourcesRequestSchema$1 = wireRequest("resources/list", paginatedParamsShape); - const ListResourceTemplatesRequestSchema$1 = wireRequest("resources/templates/list", paginatedParamsShape); - const ReadResourceRequestSchema$1 = wireRequest("resources/read", { - uri: schemas_string(), - ...retryParamsShape - }); - const completeParamsShape = { - ref: schemas_union([PromptReferenceSchema$1, ResourceTemplateReferenceSchema$1]), - argument: schemas_object({ - name: schemas_string(), - value: schemas_string() - }), - context: schemas_object({ arguments: schemas_record(schemas_string(), schemas_string()).optional() }).optional() - }; - const CompleteRequestSchema$1 = wireRequest("completion/complete", completeParamsShape); - const DiscoverRequestSchema$1 = wireRequest("server/discover", {}); - /** Anchor SubscriptionFilter (2026-only). */ - const SubscriptionFilterSchema$1 = schemas_object({ - toolsListChanged: schemas_boolean().optional(), - promptsListChanged: schemas_boolean().optional(), - resourcesListChanged: schemas_boolean().optional(), - resourceSubscriptions: schemas_array(schemas_string()).optional() - }); - const subscriptionsListenParamsShape = { notifications: SubscriptionFilterSchema$1 }; - const SubscriptionsListenRequestSchema$1 = wireRequest("subscriptions/listen", subscriptionsListenParamsShape); - /** - * Anchor SubscriptionsListenResultMeta — required subscriptionId stamp on - * the graceful-close result. Extends `ResultMetaObject` since spec PR - * #3002 (composed, so the serverInfo key and its leniency stay single-sourced). - */ - const SubscriptionsListenResultMetaSchema$1 = ResultMetaSchema.extend({ "io.modelcontextprotocol/subscriptionId": RequestIdSchema$1 }); - /** - * Anchor SubscriptionsListenResult (2026-only). The empty `subscriptions/listen` - * response signalling that the subscription has ended gracefully (server - * shutdown). An abrupt transport close carries no response — the client treats - * stream-close-without-result as a disconnect. - */ - const SubscriptionsListenResultSchema$1 = looseObject({ - _meta: SubscriptionsListenResultMetaSchema$1, - resultType: ResultTypeSchema.default("complete") - }); - /** Dispatch (post-lift) request schemas, keyed by method — registry-internal. */ - const dispatchRequestSchemas = { - "tools/call": dispatchRequest("tools/call", callToolParamsShape), - "tools/list": dispatchRequest("tools/list", paginatedParamsShape), - "prompts/get": dispatchRequest("prompts/get", { - name: schemas_string(), - arguments: schemas_record(schemas_string(), schemas_string()).optional() - }), - "prompts/list": dispatchRequest("prompts/list", paginatedParamsShape), - "resources/list": dispatchRequest("resources/list", paginatedParamsShape), - "resources/templates/list": dispatchRequest("resources/templates/list", paginatedParamsShape), - "resources/read": dispatchRequest("resources/read", { uri: schemas_string() }), - "completion/complete": dispatchRequest("completion/complete", completeParamsShape), - "server/discover": dispatchRequest("server/discover", {}), - "subscriptions/listen": dispatchRequest("subscriptions/listen", subscriptionsListenParamsShape) - }; - /** Dispatch (post-lift) result schemas, keyed by method — what the funnel - * validates AFTER `decodeResult` consumed `resultType`. */ - function liftedResult(shape) { - return looseObject({ - _meta: wireMeta, - ...shape - }); - } - const dispatchResultSchemas = { - "tools/call": liftedResult({ - content: schemas_array(ContentBlockSchema$1), - structuredContent: unknown().optional(), - isError: schemas_boolean().optional() - }), - "tools/list": liftedResult({ - ttlMs: schemas_number().int().min(0), - cacheScope: schemas_enum(["public", "private"]), - tools: schemas_array(ToolSchema$1), - nextCursor: CursorSchema$1.optional() - }), - "prompts/get": liftedResult({ - description: schemas_string().optional(), - messages: schemas_array(PromptMessageSchema$1) - }), - "prompts/list": liftedResult({ - ttlMs: schemas_number().int().min(0), - cacheScope: schemas_enum(["public", "private"]), - prompts: schemas_array(PromptSchema$1), - nextCursor: CursorSchema$1.optional() - }), - "resources/list": liftedResult({ - ttlMs: schemas_number().int().min(0), - cacheScope: schemas_enum(["public", "private"]), - resources: schemas_array(ResourceSchema$1), - nextCursor: CursorSchema$1.optional() - }), - "resources/templates/list": liftedResult({ - ttlMs: schemas_number().int().min(0), - cacheScope: schemas_enum(["public", "private"]), - resourceTemplates: schemas_array(ResourceTemplateSchema$1), - nextCursor: CursorSchema$1.optional() - }), - "resources/read": liftedResult({ - ttlMs: schemas_number().int().min(0), - cacheScope: schemas_enum(["public", "private"]), - contents: schemas_array(schemas_union([TextResourceContentsSchema$1, BlobResourceContentsSchema$1])) - }), - "completion/complete": liftedResult({ completion: schemas_object({ - values: schemas_array(schemas_string()).max(100), - total: schemas_number().int().optional(), - hasMore: schemas_boolean().optional() - }).loose() }), - "server/discover": liftedResult({ - ttlMs: schemas_number().int().min(0).catch(0), - cacheScope: schemas_enum(["public", "private"]).catch("private"), - supportedVersions: schemas_array(schemas_string()), - capabilities: ServerCapabilities2026Schema, - instructions: schemas_string().optional() - }), - "subscriptions/listen": liftedResult({}) - }; - /** - * Notification `_meta` (anchor `NotificationMetaObject`): loose, with the - * subscriptions/listen demux key typed when present. Only the anchor-exact - * SHAPE is modeled here — listen delivery itself (filter gating, demux, - * teardown) is #14 scope and not implemented by this module. - */ - const NotificationMetaSchema = looseObject({ "io.modelcontextprotocol/subscriptionId": RequestIdSchema$1.optional() }); - /** Anchor SubscriptionsAcknowledgedNotification (2026-only). */ - const SubscriptionsAcknowledgedNotificationSchema$1 = schemas_object({ - method: literal("notifications/subscriptions/acknowledged"), - params: schemas_object({ - _meta: NotificationMetaSchema.optional(), - notifications: SubscriptionFilterSchema$1 - }) - }); - /** - * 2026-era `notifications/cancelled` params (anchor-exact fork): `requestId` - * is REQUIRED on this revision — the shared schema keeps it optional because - * the frozen 2025-11-25 shape declares it optional (task cancellation goes - * through `tasks/cancel` there). Requiredness is bare because no 2025-era - * traffic touches this module. - */ - const CancelledNotificationParamsSchema$1 = schemas_object({ - _meta: NotificationMetaSchema.optional(), - requestId: RequestIdSchema$1, - reason: schemas_string().optional() - }); - /** 2026-era `notifications/cancelled` (see the params fork above). */ - const CancelledNotificationSchema$1 = schemas_object({ - method: literal("notifications/cancelled"), - params: CancelledNotificationParamsSchema$1 - }); - const notificationSchemas2026 = { - "notifications/cancelled": CancelledNotificationSchema$1, - "notifications/progress": ProgressNotificationSchema$1, - "notifications/message": LoggingMessageNotificationSchema$1, - "notifications/resources/updated": ResourceUpdatedNotificationSchema$1, - "notifications/resources/list_changed": ResourceListChangedNotificationSchema$1, - "notifications/tools/list_changed": ToolListChangedNotificationSchema$1, - "notifications/prompts/list_changed": PromptListChangedNotificationSchema$1, - "notifications/subscriptions/acknowledged": SubscriptionsAcknowledgedNotificationSchema$1 - }; - const wireResultResponse = (result) => schemas_object({ - jsonrpc: literal("2.0"), - id: schemas_union([schemas_string(), schemas_number().int()]), - result - }).strict(); - return { - JSONValueSchema: JSONValueSchema$1, - JSONObjectSchema: JSONObjectSchema$1, - ProgressTokenSchema: ProgressTokenSchema$1, - CursorSchema: CursorSchema$1, - RequestIdSchema: RequestIdSchema$1, - RoleSchema: RoleSchema$1, - LoggingLevelSchema: LoggingLevelSchema$1, - TaskMetadataSchema: TaskMetadataSchema$1, - RelatedTaskMetadataSchema: RelatedTaskMetadataSchema$1, - RequestMetaSchema: RequestMetaSchema$1, - BaseRequestParamsSchema: BaseRequestParamsSchema$1, - TaskAugmentedRequestParamsSchema: TaskAugmentedRequestParamsSchema$1, - NotificationsParamsSchema: NotificationsParamsSchema$1, - NotificationSchema: NotificationSchema$1, - IconSchema: IconSchema$1, - IconsSchema: IconsSchema$1, - BaseMetadataSchema: BaseMetadataSchema$1, - ImplementationSchema: ImplementationSchema$1, - ClientTasksCapabilitySchema: ClientTasksCapabilitySchema$1, - ServerTasksCapabilitySchema: ServerTasksCapabilitySchema$1, - ClientCapabilitiesSchema: ClientCapabilitiesSchema$1, - ServerCapabilitiesSchema: ServerCapabilitiesSchema$1, - ProgressSchema: ProgressSchema$1, - ProgressNotificationParamsSchema: ProgressNotificationParamsSchema$1, - ProgressNotificationSchema: ProgressNotificationSchema$1, - LoggingMessageNotificationParamsSchema: LoggingMessageNotificationParamsSchema$1, - LoggingMessageNotificationSchema: LoggingMessageNotificationSchema$1, - ResourceContentsSchema: ResourceContentsSchema$1, - TextResourceContentsSchema: TextResourceContentsSchema$1, - BlobResourceContentsSchema: BlobResourceContentsSchema$1, - AnnotationsSchema: AnnotationsSchema$1, - ResourceSchema: ResourceSchema$1, - ResourceTemplateSchema: ResourceTemplateSchema$1, - ResourceListChangedNotificationSchema: ResourceListChangedNotificationSchema$1, - ResourceUpdatedNotificationParamsSchema: ResourceUpdatedNotificationParamsSchema$1, - ResourceUpdatedNotificationSchema: ResourceUpdatedNotificationSchema$1, - PromptArgumentSchema: PromptArgumentSchema$1, - PromptSchema: PromptSchema$1, - PromptListChangedNotificationSchema: PromptListChangedNotificationSchema$1, - TextContentSchema: TextContentSchema$1, - ImageContentSchema: ImageContentSchema$1, - AudioContentSchema: AudioContentSchema$1, - ToolUseContentSchema: ToolUseContentSchema$1, - EmbeddedResourceSchema: EmbeddedResourceSchema$1, - ResourceLinkSchema: ResourceLinkSchema$1, - ContentBlockSchema: ContentBlockSchema$1, - PromptMessageSchema: PromptMessageSchema$1, - ToolAnnotationsSchema: ToolAnnotationsSchema$1, - ToolListChangedNotificationSchema: ToolListChangedNotificationSchema$1, - ModelHintSchema: ModelHintSchema$1, - ModelPreferencesSchema: ModelPreferencesSchema$1, - ToolChoiceSchema: ToolChoiceSchema$1, - BooleanSchemaSchema: BooleanSchemaSchema$1, - StringSchemaSchema: StringSchemaSchema$1, - NumberSchemaSchema: NumberSchemaSchema$1, - UntitledSingleSelectEnumSchemaSchema: UntitledSingleSelectEnumSchemaSchema$1, - TitledSingleSelectEnumSchemaSchema: TitledSingleSelectEnumSchemaSchema$1, - LegacyTitledEnumSchemaSchema: LegacyTitledEnumSchemaSchema$1, - SingleSelectEnumSchemaSchema: SingleSelectEnumSchemaSchema$1, - UntitledMultiSelectEnumSchemaSchema: UntitledMultiSelectEnumSchemaSchema$1, - TitledMultiSelectEnumSchemaSchema: TitledMultiSelectEnumSchemaSchema$1, - MultiSelectEnumSchemaSchema: MultiSelectEnumSchemaSchema$1, - EnumSchemaSchema: EnumSchemaSchema$1, - PrimitiveSchemaDefinitionSchema: PrimitiveSchemaDefinitionSchema$1, - ElicitRequestFormParamsSchema: ElicitRequestFormParamsSchema$1, - ResourceTemplateReferenceSchema: ResourceTemplateReferenceSchema$1, - PromptReferenceSchema: PromptReferenceSchema$1, - RootSchema: RootSchema$1, - ClientCapabilities2026Schema, - ServerCapabilities2026Schema, - RequestMetaEnvelopeSchema, - ToolSchema: ToolSchema$1, - ToolResultContentSchema: ToolResultContentSchema$1, - SamplingMessageContentBlockSchema: SamplingMessageContentBlockSchema$1, - SamplingMessageSchema: SamplingMessageSchema$1, - ResultTypeSchema, - ResultMetaSchema, - ResultSchema: ResultSchema$1, - PaginatedResultSchema: PaginatedResultSchema$1, - CallToolResultSchema: CallToolResultSchema$1, - ListToolsResultSchema: ListToolsResultSchema$1, - ListPromptsResultSchema: ListPromptsResultSchema$1, - GetPromptResultSchema: GetPromptResultSchema$1, - ListResourcesResultSchema: ListResourcesResultSchema$1, - ListResourceTemplatesResultSchema: ListResourceTemplatesResultSchema$1, - ReadResourceResultSchema: ReadResourceResultSchema$1, - CompleteResultSchema: CompleteResultSchema$1, - CacheableResultSchema, - DiscoverResultSchema: DiscoverResultSchema$1, - CreateMessageRequestParamsSchema: CreateMessageRequestParamsSchema$1, - CreateMessageRequestSchema: CreateMessageRequestSchema$1, - ListRootsRequestSchema: ListRootsRequestSchema$1, - CreateMessageResultSchema: CreateMessageResultSchema$1, - ListRootsResultSchema: ListRootsResultSchema$1, - ElicitResultSchema: ElicitResultSchema$1, - ElicitRequestURLParamsSchema: ElicitRequestURLParamsSchema$1, - ElicitRequestParamsSchema: ElicitRequestParamsSchema$1, - ElicitRequestSchema: ElicitRequestSchema$1, - InputRequestSchema, - InputResponseSchema, - InputRequestsSchema, - InputResponsesSchema, - InputRequiredResultSchema, - InputResponseRequestParamsSchema, - CallToolRequestSchema: CallToolRequestSchema$1, - ListToolsRequestSchema: ListToolsRequestSchema$1, - ListPromptsRequestSchema: ListPromptsRequestSchema$1, - GetPromptRequestSchema: GetPromptRequestSchema$1, - ListResourcesRequestSchema: ListResourcesRequestSchema$1, - ListResourceTemplatesRequestSchema: ListResourceTemplatesRequestSchema$1, - ReadResourceRequestSchema: ReadResourceRequestSchema$1, - CompleteRequestSchema: CompleteRequestSchema$1, - DiscoverRequestSchema: DiscoverRequestSchema$1, - SubscriptionFilterSchema: SubscriptionFilterSchema$1, - SubscriptionsListenRequestSchema: SubscriptionsListenRequestSchema$1, - SubscriptionsListenResultMetaSchema: SubscriptionsListenResultMetaSchema$1, - SubscriptionsListenResultSchema: SubscriptionsListenResultSchema$1, - dispatchRequestSchemas, - dispatchResultSchemas, - NotificationMetaSchema, - SubscriptionsAcknowledgedNotificationSchema: SubscriptionsAcknowledgedNotificationSchema$1, - CancelledNotificationParamsSchema: CancelledNotificationParamsSchema$1, - CancelledNotificationSchema: CancelledNotificationSchema$1, - notificationSchemas2026, - JSONRPCResultResponseSchema: wireResultResponse(ResultSchema$1), - CallToolResultResponseSchema: wireResultResponse(schemas_union([CallToolResultSchema$1, InputRequiredResultSchema])), - ListToolsResultResponseSchema: wireResultResponse(ListToolsResultSchema$1), - ListPromptsResultResponseSchema: wireResultResponse(ListPromptsResultSchema$1), - GetPromptResultResponseSchema: wireResultResponse(schemas_union([GetPromptResultSchema$1, InputRequiredResultSchema])), - ListResourcesResultResponseSchema: wireResultResponse(ListResourcesResultSchema$1), - ListResourceTemplatesResultResponseSchema: wireResultResponse(ListResourceTemplatesResultSchema$1), - ReadResourceResultResponseSchema: wireResultResponse(schemas_union([ReadResourceResultSchema$1, InputRequiredResultSchema])), - CompleteResultResponseSchema: wireResultResponse(CompleteResultSchema$1), - DiscoverResultResponseSchema: wireResultResponse(DiscoverResultSchema$1) - }; -} -let src_CX2iR2pK_memo; -/** -* Builds the era wire-schema set on first call and returns the same object -* thereafter. Module evaluation stays construction-free so importing the -* era codec/registry costs nothing until the first validation actually -* needs a schema; the registry, the codec, and the eager `schemas.ts` -* shim all pull through this memo, so reference identity holds across -* every consumer. -*/ -function buildSchemas2026() { - return src_CX2iR2pK_memo ??= build(); -} - -//#endregion -//#region ../core-internal/src/shared/resultCacheHints.ts -/** -* The operations whose results are cacheable on the 2026-07-28 revision (the -* `CacheableResult` extenders). This list is closed: no other operation's -* result ever receives cache fields from the SDK. -*/ -const CACHEABLE_RESULT_METHODS = [ - "tools/list", - "prompts/list", - "resources/list", - "resources/templates/list", - "resources/read", - "server/discover" -]; -/** Whether the given method's result is cacheable on the 2026-07-28 revision. */ -function isCacheableResultMethod(method) { - return CACHEABLE_RESULT_METHODS.includes(method); -} -/** -* The symbol-keyed carrier for a configured cache hint on a result object. -* Symbol properties are invisible to JSON serialization, so the carrier can be -* attached era-blind: only the 2026-era encode seam consumes it. -*/ -const RESULT_CACHE_HINT_FALLBACK = Symbol("modelcontextprotocol.resultCacheHintFallback"); -/** -* Attaches a configured cache hint to a result as the encode-time fallback. -* Returns the result unchanged when there is nothing to attach. When a more -* specific hint is already attached, the two hints are combined per field -* (most-specific-author-wins for each of `ttlMs` and `cacheScope`): the -* per-registration hint attached by the feature layer keeps every field it -* sets, and the server-level per-operation hint only fills the fields the -* more specific hint leaves unset. -*/ -function attachCacheHintFallback(result, hint) { - if (hint === void 0) return result; - const attached = result[RESULT_CACHE_HINT_FALLBACK]; - if (attached === void 0) return { - ...result, - [RESULT_CACHE_HINT_FALLBACK]: hint - }; - const merged = {}; - const ttlMs = attached.ttlMs ?? hint.ttlMs; - if (ttlMs !== void 0) merged.ttlMs = ttlMs; - const cacheScope = attached.cacheScope ?? hint.cacheScope; - if (cacheScope !== void 0) merged.cacheScope = cacheScope; - return { - ...result, - [RESULT_CACHE_HINT_FALLBACK]: merged - }; -} -/** Reads the configured cache-hint fallback attached to a result, if any. */ -function cacheHintFallbackOf(result) { - return result[RESULT_CACHE_HINT_FALLBACK]; -} -/** -* Whether a value is a valid `ttlMs`: a non-negative safe integer. Safe -* integers are required because the wire schemas validate `ttlMs` as an -* integer within `Number.MIN_SAFE_INTEGER`/`Number.MAX_SAFE_INTEGER`; a value -* outside that range is treated as invalid here so it falls through to the -* next author instead of being emitted and rejected downstream. -*/ -function isValidCacheTtlMs(value) { - return typeof value === "number" && Number.isSafeInteger(value) && value >= 0; -} -/** Whether a value is a valid `cacheScope`. */ -function isValidCacheScope(value) { - return value === "public" || value === "private"; -} -/** -* Validates a configured cache hint at configuration time. Throws a -* `RangeError` naming the offending field, so misconfiguration fails at -* startup/registration rather than silently degrading at encode time. -*/ -function assertValidCacheHint(hint, context) { - if (hint.ttlMs !== void 0 && !isValidCacheTtlMs(hint.ttlMs)) throw new RangeError(`Invalid cache hint for ${context}: ttlMs must be a non-negative safe integer (got ${String(hint.ttlMs)})`); - if (hint.cacheScope !== void 0 && !isValidCacheScope(hint.cacheScope)) throw new RangeError(`Invalid cache hint for ${context}: cacheScope must be 'public' or 'private' (got ${String(hint.cacheScope)})`); -} - -//#endregion -//#region ../core-internal/src/types/enums.ts -/** -* Error codes for protocol errors that cross the wire as JSON-RPC error responses. -* These follow the JSON-RPC specification and MCP-specific extensions. -*/ -let src_CX2iR2pK_ProtocolErrorCode = /* @__PURE__ */ function(ProtocolErrorCode$1) { - ProtocolErrorCode$1[ProtocolErrorCode$1["ParseError"] = -32700] = "ParseError"; - ProtocolErrorCode$1[ProtocolErrorCode$1["InvalidRequest"] = -32600] = "InvalidRequest"; - ProtocolErrorCode$1[ProtocolErrorCode$1["MethodNotFound"] = -32601] = "MethodNotFound"; - ProtocolErrorCode$1[ProtocolErrorCode$1["InvalidParams"] = -32602] = "InvalidParams"; - ProtocolErrorCode$1[ProtocolErrorCode$1["InternalError"] = -32603] = "InternalError"; - /** - * Resource not found. - * - * Receive-tolerated only: the SDK never EMITS `-32002` — `resources/read` - * misses answer `-32602` (Invalid Params) on every protocol revision per - * the 2026-07-28 spec MUST, and a handler-thrown `-32002` is mapped to - * `-32602` at the era encode seam. The member stays importable so clients - * can recognise `-32002` from peers built on earlier SDK releases (the - * spec's "clients SHOULD also accept `-32002`" backwards-compatibility - * clause). Throw `ResourceNotFoundError` instead. - */ - ProtocolErrorCode$1[ProtocolErrorCode$1["ResourceNotFound"] = -32002] = "ResourceNotFound"; - /** - * Processing the request requires a capability the client did not declare - * in the request's `clientCapabilities` (protocol revision 2026-07-28). - */ - ProtocolErrorCode$1[ProtocolErrorCode$1["MissingRequiredClientCapability"] = -32021] = "MissingRequiredClientCapability"; - /** - * The request's protocol version is unknown to the server or unsupported - * by it (protocol revision 2026-07-28). - */ - ProtocolErrorCode$1[ProtocolErrorCode$1["UnsupportedProtocolVersion"] = -32022] = "UnsupportedProtocolVersion"; - ProtocolErrorCode$1[ProtocolErrorCode$1["UrlElicitationRequired"] = -32042] = "UrlElicitationRequired"; - return ProtocolErrorCode$1; -}({}); - -//#endregion -//#region ../core-internal/src/types/errors.ts -/** -* Protocol errors are JSON-RPC errors that cross the wire as error responses. -* They use numeric error codes from the {@linkcode ProtocolErrorCode} enum. -* -* `instanceof` on this class (and its subclasses) is brand-matched, so it works -* across separately bundled copies of the SDK — e.g. an error constructed by -* `@modelcontextprotocol/client` matches the class re-exported by -* `@modelcontextprotocol/server` in the same process. -*/ -var src_CX2iR2pK_ProtocolError = class ProtocolError extends Error { - static { - Object.defineProperty(this, "mcpBrand", { value: "mcp.ProtocolError" }); - } - static [Symbol.hasInstance](value) { - return brandedHasInstance(this, value); - } - /** - * Brand-based type guard: equivalent to `value instanceof this`, as an - * explicit static predicate (the axios/AWS-SDK `isInstance` style). Reads - * the caller's own brand via `this`, so every branded subclass gets a - * correctly-scoped guard by inheritance. Must be invoked on the class — - * in callback position write `v => SdkError.isInstance(v)`, not - * `.filter(SdkError.isInstance)` (detached calls throw rather than - * silently matching nothing). - */ - static isInstance(value) { - 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 brandedHasInstance(this, value); - } - constructor(code, message, data) { - super(message); - this.code = code; - this.data = data; - this.name = "ProtocolError"; - stampErrorBrands(this, new.target); - } - /** - * Factory method to create the appropriate error type based on the error code and data - */ - static fromError(code, message, data) { - if (code === src_CX2iR2pK_ProtocolErrorCode.UrlElicitationRequired && data) { - const errorData = data; - if (errorData.elicitations) return new UrlElicitationRequiredError(errorData.elicitations, message); - } - if (code === src_CX2iR2pK_ProtocolErrorCode.UnsupportedProtocolVersion && data) { - const errorData = data; - if (Array.isArray(errorData.supported) && typeof errorData.requested === "string") return new src_CX2iR2pK_UnsupportedProtocolVersionError({ - supported: errorData.supported, - requested: errorData.requested - }, message); - } - if (code === src_CX2iR2pK_ProtocolErrorCode.InvalidParams || code === src_CX2iR2pK_ProtocolErrorCode.ResourceNotFound) { - const errorData = data; - if (typeof errorData?.uri === "string" && (code === src_CX2iR2pK_ProtocolErrorCode.ResourceNotFound || Object.keys(errorData).length === 1)) return new ResourceNotFoundError(errorData.uri, message); - } - if (code === src_CX2iR2pK_ProtocolErrorCode.MissingRequiredClientCapability && data) { - const errorData = data; - if (errorData.requiredCapabilities !== null && typeof errorData.requiredCapabilities === "object" && !Array.isArray(errorData.requiredCapabilities)) return new src_CX2iR2pK_MissingRequiredClientCapabilityError({ requiredCapabilities: errorData.requiredCapabilities }, message); - } - return new ProtocolError(code, message, data); - } -}; -/** -* Error type for a `resources/read` miss: the requested resource does not -* exist. The wire code is `-32602` (Invalid Params) on every protocol -* revision — the spec MUST for revision 2026-07-28, and the value the v1.x -* SDK has always emitted on earlier revisions. The error data echoes the -* requested URI. -* -* Recognise this error by checking `error.data` is exactly `{ uri: string }` -* (a `-32602` whose data carries `uri` and nothing else is resource-not-found; -* any other `-32602` is an ordinary Invalid Params). For backwards compatibility, clients should also -* accept `-32002` as resource not found — earlier SDK builds emitted that -* code, and {@linkcode ProtocolError.fromError} reconstructs this class for -* either code **when `error.data` carries `uri`** (a bare `-32002` without -* `data.uri` stays a generic {@linkcode ProtocolError}). `instanceof` checks -* are brand-matched and work across separately bundled copies of the SDK. -*/ -var ResourceNotFoundError = class extends src_CX2iR2pK_ProtocolError { - static { - Object.defineProperty(this, "mcpBrand", { value: "mcp.ResourceNotFoundError" }); - } - constructor(uri, message = `Resource not found: ${uri}`) { - super(src_CX2iR2pK_ProtocolErrorCode.InvalidParams, message, { uri }); - } - /** The URI that was requested and not found. */ - get uri() { - return this.data.uri; - } -}; -/** -* Specialized error type when a tool requires a URL mode elicitation. -* This makes it nicer for the client to handle since there is specific data to work with instead of just a code to check against. -*/ -var UrlElicitationRequiredError = class extends src_CX2iR2pK_ProtocolError { - static { - Object.defineProperty(this, "mcpBrand", { value: "mcp.UrlElicitationRequiredError" }); - } - constructor(elicitations, message = `URL elicitation${elicitations.length > 1 ? "s" : ""} required`) { - super(src_CX2iR2pK_ProtocolErrorCode.UrlElicitationRequired, message, { elicitations }); - } - get elicitations() { - return this.data?.elicitations ?? []; - } -}; -/** -* Error type for the `-32022` UnsupportedProtocolVersion protocol error (protocol -* revision 2026-07-28): the request's protocol version is unknown to the server or -* unsupported by it. -* -* The error data lists the protocol versions the receiver supports (`supported`), -* so the sender can choose a mutually supported version and retry, and echoes the -* version that was requested (`requested`). -*/ -var src_CX2iR2pK_UnsupportedProtocolVersionError = class extends src_CX2iR2pK_ProtocolError { - static { - Object.defineProperty(this, "mcpBrand", { value: "mcp.UnsupportedProtocolVersionError" }); - } - constructor(data, message = `Unsupported protocol version: ${data.requested}`) { - super(src_CX2iR2pK_ProtocolErrorCode.UnsupportedProtocolVersion, message, data); - } - /** - * Protocol versions the receiver supports. - */ - get supported() { - return this.data.supported; - } - /** - * The protocol version that was requested. - */ - get requested() { - return this.data.requested; - } -}; -/** -* Error type for the `-32021` MissingRequiredClientCapability protocol error -* (protocol revision 2026-07-28): processing the request requires a capability -* the client did not declare in the request's `clientCapabilities`. -* -* The error data lists the missing capabilities (`requiredCapabilities`) in -* the `ClientCapabilities` shape, so the client can see exactly what it would -* have to declare for the request to be served. On HTTP, the response status -* is `400 Bad Request`. -* -* Recognize this error by its code and `data.requiredCapabilities`, or by -* `instanceof` — checks are brand-matched and work across separately bundled -* copies of the SDK. -*/ -var src_CX2iR2pK_MissingRequiredClientCapabilityError = class extends src_CX2iR2pK_ProtocolError { - static { - Object.defineProperty(this, "mcpBrand", { value: "mcp.MissingRequiredClientCapabilityError" }); - } - constructor(data, message = `Missing required client capabilities: ${Object.keys(data.requiredCapabilities).join(", ")}`) { - super(src_CX2iR2pK_ProtocolErrorCode.MissingRequiredClientCapability, message, data); - } - /** - * The capabilities the server requires from the client to process the - * request (only the missing capabilities are listed). - */ - get requiredCapabilities() { - return this.data.requiredCapabilities; - } -}; - -//#endregion -//#region ../core-internal/src/wire/rev2026-07-28/encodeContract.ts -/** The default cache policy when neither the handler nor configuration provides one. */ -const DEFAULT_CACHE_TTL_MS = 0; -const DEFAULT_CACHE_SCOPE = "private"; -/** -* Request methods whose spec result vocabulary goes beyond `'complete'` on the -* 2026-07-28 revision: their results may be `input_required` (multi -* round-trip requests), so a handler-provided `resultType` passes through the -* stamp untouched. `subscriptions/listen` is NOT in this set: it never emits -* a JSON-RPC result — termination is stream close (HTTP) or -* `notifications/cancelled` (stdio) per the spec. -*/ -const EXTENDED_RESULT_TYPE_METHODS = [ - "tools/call", - "prompts/get", - "resources/read" -]; -/** -* Step 1 of the encode contract: ensure the outbound result carries the -* required `resultType` discriminator. -* -* - No handler-provided value → stamp `'complete'`. -* - Handler-provided `'complete'` → kept as-is. -* - Handler-provided non-`'complete'` value on a method whose vocabulary -* allows it ({@linkcode EXTENDED_RESULT_TYPE_METHODS}) → passes through. -* The value is forwarded verbatim — the wire vocabulary is an open union and -* the SDK does not validate the string, so emitting a `resultType` the -* negotiated revision does not define is the handler author's -* responsibility. -* - Handler-provided non-`'complete'` value on any other method → internal -* error (loud): the value would be mis-typed on the wire, and silently -* rewriting it would hide a server bug. -*/ -function stampResultType(method, result) { - const provided = result["resultType"]; - if (provided === void 0) return { - ...result, - resultType: "complete" - }; - if (provided === "complete") return result; - if (EXTENDED_RESULT_TYPE_METHODS.includes(method)) return result; - throw new src_CX2iR2pK_ProtocolError(src_CX2iR2pK_ProtocolErrorCode.InternalError, `Handler for ${method} returned resultType '${String(provided)}', but results of ${method} only support 'complete' on protocol revision 2026-07-28`); -} -/** -* Step 2 of the encode contract: fill the required `ttlMs`/`cacheScope` fields -* on cacheable results. -* -* Applies only when the (post-stamp) `resultType` is `'complete'` and the -* method is one of the cacheable operations; everything else is returned -* untouched apart from removing the configured-hint carrier. Field resolution -* is per field, most specific author first: a valid handler-returned value, -* then the configured cache hint attached by the server layer, then the -* defaults. Handler-returned values are validated at encode time (`ttlMs` -* must be a non-negative integer, `cacheScope` must be `'public'` or -* `'private'`); invalid values are ignored rather than emitted. -*/ -function fillCacheFields(method, result) { - const fallback = cacheHintFallbackOf(result); - if (result["resultType"] !== "complete" || !isCacheableResultMethod(method)) return fallback === void 0 ? result : stripCacheHintFallback(result); - const provided = result; - const ttlMs = isValidCacheTtlMs(provided["ttlMs"]) ? provided["ttlMs"] : resolveTtlMs(fallback); - const cacheScope = isValidCacheScope(provided["cacheScope"]) ? provided["cacheScope"] : resolveCacheScope(fallback); - const filled = { - ...provided, - ttlMs, - cacheScope - }; - delete filled[RESULT_CACHE_HINT_FALLBACK]; - return filled; -} -function isPlainObject$5(value) { - return value !== null && typeof value === "object" && !Array.isArray(value); -} -/** -* Step 3 of the encode contract: stamp the server's identity into the -* result's `_meta` under `io.modelcontextprotocol/serverInfo` (spec PR #3002: -* servers SHOULD include it on every response). -* -* - No `serverInfo` supplied (a client instance, or a hand-constructed -* protocol object) → identity function. -* - The result's `_meta` already carries the key → kept as-is (the handler -* is the more specific author; mirrors the cache-fill resolution order). -* - A present-but-non-object `_meta` (a dynamic-caller bug) → kept as-is: -* the stamp never rewrites handler material, and the malformed value fails -* loudly at the peer instead of being silently replaced here. -* - Otherwise → the key is added, preserving any other `_meta` entries. -* -* Runs for every result regardless of `resultType`: the anchor types -* `Result._meta` as `ResultMetaObject` on all results, `input_required` -* included. -*/ -function stampServerInfoMeta(result, serverInfo) { - if (serverInfo === void 0) return result; - const meta = result["_meta"]; - if (meta === void 0) return { - ...result, - _meta: { [auth_CUe6YdwF_SERVER_INFO_META_KEY]: serverInfo } - }; - if (!isPlainObject$5(meta)) return result; - if (meta[auth_CUe6YdwF_SERVER_INFO_META_KEY] !== void 0) return result; - return { - ...result, - _meta: { - ...meta, - [auth_CUe6YdwF_SERVER_INFO_META_KEY]: serverInfo - } - }; -} -function resolveTtlMs(fallback) { - return fallback !== void 0 && isValidCacheTtlMs(fallback.ttlMs) ? fallback.ttlMs : DEFAULT_CACHE_TTL_MS; -} -function resolveCacheScope(fallback) { - return fallback !== void 0 && isValidCacheScope(fallback.cacheScope) ? fallback.cacheScope : DEFAULT_CACHE_SCOPE; -} -function stripCacheHintFallback(result) { - const copy = { ...result }; - delete copy[RESULT_CACHE_HINT_FALLBACK]; - return copy; -} - -//#endregion -//#region ../core-internal/src/wire/rev2026-07-28/inputRequired.ts -/** -* In-band input-request vocabulary of the 2026-07-28 revision (SEP-2322 -* multi round-trip requests), dispatch view. -* -* The three former server→client wire requests (`elicitation/create`, -* `sampling/createMessage`, `roots/list`) are NOT wire request methods on -* this revision — they are demoted to de-JSON-RPC'd payloads embedded in an -* `input_required` result. The multi-round-trip driver dispatches those -* embedded payloads to the client's registered handlers through the normal -* handler machinery, and these are the schemas that dispatch parses them -* with: lenient where the anchor's wire-true artifacts are strict (an -* embedded request never carries the per-request `_meta` envelope), exact -* where the vocabulary forks (the sampling shapes compose the forked -* SamplingMessage/Tool payloads). -* -* Registry membership is intentionally NOT granted here — these methods stay -* absent from the 2026-era request registry (a peer sending one as a wire -* request still gets −32601 by absence). Only the codec's -* `inputRequestSchema`/`inputResponseSchema` accessors expose them. -*/ -/** The embedded input-request methods of the 2026-07-28 revision. */ -const INPUT_REQUEST_METHODS_2026 = [ - "elicitation/create", - "sampling/createMessage", - "roots/list" -]; -let maps; -function inputSchemaMaps() { - if (maps) return maps; - const s = buildSchemas2026(); - maps = { - request: { - "elicitation/create": schemas_object({ - method: literal("elicitation/create"), - params: s.ElicitRequestParamsSchema - }), - "sampling/createMessage": schemas_object({ - method: literal("sampling/createMessage"), - params: s.CreateMessageRequestParamsSchema - }), - "roots/list": schemas_object({ - method: literal("roots/list"), - params: looseObject({}).optional() - }) - }, - response: { - "elicitation/create": s.ElicitResultSchema, - "sampling/createMessage": s.CreateMessageResultSchema, - "roots/list": s.ListRootsResultSchema - } - }; - return maps; -} -/** -* Forces the lazy embedded-request maps (and, through them, the era's schema -* memo). Warm-up hook for `preloadSchemas()` — no-op once the maps exist. -*/ -function warmInputSchemaMaps2026() { - inputSchemaMaps(); -} -function isInputRequestMethod2026(method) { - return INPUT_REQUEST_METHODS_2026.includes(method); -} -function getInputRequestSchema2026(method) { - return isInputRequestMethod2026(method) ? inputSchemaMaps().request[method] : void 0; -} -function getInputResponseSchema2026(method) { - return isInputRequestMethod2026(method) ? inputSchemaMaps().response[method] : void 0; -} - -//#endregion -//#region ../core-internal/src/wire/rev2026-07-28/registry.ts -const requestMethodKeys = { - "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 -}; -const notificationMethodKeys = { - "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 -}; -/** The 2026-era request-method set (registry membership = the deletion story). */ -function hasRequestMethod2026(method) { - return Object.prototype.hasOwnProperty.call(requestMethodKeys, method); -} -/** The 2026-era notification-method set. */ -function hasNotificationMethod2026(method) { - return Object.prototype.hasOwnProperty.call(notificationMethodKeys, method); -} -/** Result-map membership (same key set as the request map on this era). */ -function hasResultMethod2026(method) { - return Object.prototype.hasOwnProperty.call(requestMethodKeys, method); -} -function getRequestSchema2026(method) { - return hasRequestMethod2026(method) ? buildSchemas2026().dispatchRequestSchemas[method] : void 0; -} -function getResultSchema2026(method) { - return hasResultMethod2026(method) ? buildSchemas2026().dispatchResultSchemas[method] : void 0; -} -function getNotificationSchema2026(method) { - return hasNotificationMethod2026(method) ? buildSchemas2026().notificationSchemas2026[method] : void 0; -} -/** Registry method lists (for the spec-method universe and the CI registry-diff oracle). */ -const rev2026RequestMethods = Object.keys(requestMethodKeys); -const rev2026NotificationMethods = Object.keys(notificationMethodKeys); - -//#endregion -//#region ../core-internal/src/wire/rev2026-07-28/codec.ts -function isPlainObject$4(value) { - return value !== null && typeof value === "object" && !Array.isArray(value); -} -/** Tri-state wrap of an optional Zod schema lookup (the function-only contract). */ -function triState(schema, raw) { - if (schema === void 0) return { - ok: false, - reason: "not-in-era" - }; - const parsed = schema.safeParse(raw); - return parsed.success ? { - ok: true, - value: parsed.data - } : { - ok: false, - reason: "invalid", - message: String(parsed.error) - }; -} -const NOT_IN_ERA = { - ok: false, - reason: "not-in-era" -}; -/** -* The reserved `_meta` keys an envelope must carry on this era (in reporting -* order). `clientInfo` is NOT here: spec PR #3002 demoted it to SHOULD, so a -* request without it is accepted (a present-but-malformed value still fails -* the envelope schema parse below). -*/ -const REQUIRED_ENVELOPE_KEYS = [auth_CUe6YdwF_PROTOCOL_VERSION_META_KEY, auth_CUe6YdwF_CLIENT_CAPABILITIES_META_KEY]; -/** Strip the known deleted-field set from an outbound result (Q1-SD3 iii). */ -function enforceDeletedFields(method, result) { - let next = result; - let copied = false; - const copy = () => { - if (!copied) { - next = { ...next }; - copied = true; - } - return next; - }; - const tools = result.tools; - if (method === "tools/list" && Array.isArray(tools) && tools.some((tool) => isPlainObject$4(tool) && "execution" in tool)) copy().tools = tools.map((tool) => { - if (!isPlainObject$4(tool) || !("execution" in tool)) return tool; - const rest = { ...tool }; - delete rest["execution"]; - return rest; - }); - const capabilities = result.capabilities; - if (isPlainObject$4(capabilities) && "tasks" in capabilities) { - const rest = { ...capabilities }; - delete rest["tasks"]; - copy().capabilities = rest; - } - return next; -} -const rev2026Codec = { - era: "2026-07-28", - hasRequestMethod: hasRequestMethod2026, - hasNotificationMethod: hasNotificationMethod2026, - hasInputRequestMethod: (method) => getInputRequestSchema2026(method) !== void 0, - validateRequest: (method, raw) => triState(getRequestSchema2026(method), raw), - validateResult: (method, raw) => triState(getResultSchema2026(method), raw), - validateNotification: (method, raw) => triState(getNotificationSchema2026(method), raw), - validateInputRequest: (method, raw) => triState(getInputRequestSchema2026(method), raw), - validateInputResponse: (method, raw) => triState(getInputResponseSchema2026(method), raw), - samplingResultVariant: () => NOT_IN_ERA, - outboundEnvelope(material) { - return { - [auth_CUe6YdwF_PROTOCOL_VERSION_META_KEY]: material.protocolVersion, - [auth_CUe6YdwF_CLIENT_INFO_META_KEY]: material.clientInfo, - [auth_CUe6YdwF_CLIENT_CAPABILITIES_META_KEY]: material.clientCapabilities, - ...material.logLevel !== void 0 && { [LOG_LEVEL_META_KEY]: material.logLevel } - }; - }, - validateEnvelopeMeta(meta) { - const issues = []; - for (const key of REQUIRED_ENVELOPE_KEYS) if (!(key in meta)) issues.push({ - key, - problem: "missing" - }); - const parsed = buildSchemas2026().RequestMetaEnvelopeSchema.safeParse(meta); - if (!parsed.success) for (const issue of parsed.error.issues) { - const path = issue.path.map(String); - const key = path.length > 0 ? path.join(".") : "_meta"; - if (path.length === 1 && issues.some((existing) => existing.key === key && existing.problem === "missing")) continue; - issues.push({ - key, - problem: issue.message - }); - } - return issues; - }, - projectCallToolResult: (result) => appendTextFallbackForNonObject(result), - inputRequestSchema: getInputRequestSchema2026, - decodeResult(method, raw) { - if (!isPlainObject$4(raw)) return { - kind: "invalid", - error: new src_CX2iR2pK_SdkError(src_CX2iR2pK_SdkErrorCode.InvalidResult, `Invalid result for ${method}: not an object`, { method }) - }; - const rawResultType = raw["resultType"]; - if (rawResultType === void 0) return { - kind: "invalid", - error: new src_CX2iR2pK_SdkError(src_CX2iR2pK_SdkErrorCode.InvalidResult, `Invalid result for ${method}: missing required resultType — servers implementing protocol revision 2026-07-28 MUST include it (the absent-means-complete bridge applies only to earlier-revision servers)`, { - method, - violation: "missing-resultType" - }) - }; - if (typeof rawResultType !== "string") return { - kind: "invalid", - error: new src_CX2iR2pK_SdkError(src_CX2iR2pK_SdkErrorCode.InvalidResult, `Invalid result for ${method}: non-string resultType`, { - method, - resultType: rawResultType - }) - }; - if (rawResultType === "input_required") { - const rawInputRequests = raw["inputRequests"]; - const inputRequests = isPlainObject$4(rawInputRequests) ? rawInputRequests : {}; - const requestState = raw["requestState"]; - if (Object.keys(inputRequests).length === 0 && typeof requestState !== "string") return { - kind: "invalid", - error: new src_CX2iR2pK_SdkError(src_CX2iR2pK_SdkErrorCode.InvalidResult, `Invalid result for ${method}: input_required carries neither inputRequests nor requestState (every input_required result must include at least one of the two)`, { - method, - violation: "input-required-missing-both" - }) - }; - return { - kind: "input_required", - inputRequests, - ...typeof requestState === "string" && { requestState } - }; - } - if (rawResultType !== "complete") return { - kind: "invalid", - error: new src_CX2iR2pK_SdkError(src_CX2iR2pK_SdkErrorCode.UnsupportedResultType, `Unsupported result type '${rawResultType}' for ${method}`, { - resultType: rawResultType, - method - }) - }; - const wireResultSchemas = getWireResultSchemas(); - const wireSchema = Object.hasOwn(wireResultSchemas, method) ? wireResultSchemas[method] : void 0; - if (wireSchema !== void 0) { - const parsed = wireSchema.safeParse(raw); - if (!parsed.success) return { - kind: "invalid", - error: new src_CX2iR2pK_SdkError(src_CX2iR2pK_SdkErrorCode.InvalidResult, `Invalid result for ${method}: ${parsed.error}`, { method }) - }; - } - const lifted = { ...raw }; - delete lifted["resultType"]; - return { - kind: "complete", - result: lifted - }; - }, - encodeResult(method, result, serverInfo) { - return stampServerInfoMeta(fillCacheFields(method, stampResultType(method, enforceDeletedFields(method, result))), serverInfo); - }, - encodeErrorCode: (code) => code === -32002 ? -32602 : code, - checkInboundEnvelope(material) { - if (material.envelope === void 0) return "Request is missing the required _meta envelope for protocol revision 2026-07-28 (io.modelcontextprotocol/protocolVersion, io.modelcontextprotocol/clientCapabilities)"; - const parsed = buildSchemas2026().RequestMetaEnvelopeSchema.safeParse(material.envelope); - if (!parsed.success) return `Invalid _meta envelope for protocol revision 2026-07-28: ${parsed.error.issues.map((issue) => issue.message).join("; ")}`; - } -}; -/** Wire-true result wrappers consulted by decode step 2, keyed by method — -* built once through the era's schema memo on the first decode. */ -let wireResultSchemasMemo; -function getWireResultSchemas() { - if (wireResultSchemasMemo) return wireResultSchemasMemo; - const s = buildSchemas2026(); - wireResultSchemasMemo = { - "tools/call": s.CallToolResultSchema, - "tools/list": s.ListToolsResultSchema, - "prompts/get": s.GetPromptResultSchema, - "prompts/list": s.ListPromptsResultSchema, - "resources/list": s.ListResourcesResultSchema, - "resources/templates/list": s.ListResourceTemplatesResultSchema, - "resources/read": s.ReadResourceResultSchema, - "completion/complete": s.CompleteResultSchema, - "server/discover": s.DiscoverResultSchema - }; - return wireResultSchemasMemo; -} -/** -* Forces the lazy wire-result wrapper map (and, through it, the era's schema -* memo). Warm-up hook for `preloadSchemas()` — no-op once the map exists. -*/ -function warmWireResultSchemas2026() { - getWireResultSchemas(); -} - -//#endregion -//#region ../core-internal/src/wire/codec.ts -/** -* The modern wire revision literal. Internal only — deliberately NOT a public -* constant (G-D2-4: no public modern-version constant ships before era-aware -* list semantics exist). -*/ -const src_CX2iR2pK_MODERN_WIRE_REVISION = "2026-07-28"; -/** -* Era resolution, many-to-one (Q1-SD1): every modern-era revision -* (`>= 2026-07-28`) → the 2026-era codec; every legacy revision (the five -* `SUPPORTED_PROTOCOL_VERSIONS`) and `undefined`/unknown → the 2025-era -* codec (the DV-13 default posture — hand-constructed instances and -* unclassified traffic are legacy-era). This is the same era predicate the -* rest of the SDK uses ({@link isModernProtocolVersion}); a pinned modern -* revision other than the literal '2026-07-28' must still resolve modern. -*/ -function src_CX2iR2pK_codecForVersion(version) { - return version !== void 0 && isModernProtocolVersion(version) ? rev2026Codec : rev2025Codec; -} -/** -* The wire era an edge classification names (Q2 — produced at the -* transport/entry edge; this layer only CONSUMES it). The dispatch funnel no -* longer resolves a codec FROM the classification: era is instance state, and -* a classified inbound message is VALIDATED against the instance era — a -* mismatch is an entry/routing error, never a per-message era switch. The -* exact `revision` wins over the coarse era flag when both are present. -*/ -function classifiedWireEra(classification) { - if (classification.revision !== void 0) return src_CX2iR2pK_codecForVersion(classification.revision).era; - return classification.era === "modern" ? rev2026Codec.era : rev2025Codec.era; -} -/** -* The derived spec-method universe: the union of every codec registry. A -* method in this set is era-gated at dispatch and send time; a method outside -* it is a consumer-owned extension method (era-blind, schema-explicit). -* Derived from the registries — never hand-curated (the LEGACY_ONLY_METHODS -* table class is exactly what registry membership replaces). -*/ -function isSpecRequestMethod(method) { - return ALL_CODECS.some((codec) => codec.hasRequestMethod(method)); -} -function isSpecNotificationMethod(method) { - return ALL_CODECS.some((codec) => codec.hasNotificationMethod(method)); -} -const ALL_CODECS = [rev2025Codec, rev2026Codec]; - -//#endregion -//#region ../core-internal/src/shared/envelope.ts -/** -* Per-request `_meta` envelope claim helpers (protocol revision 2026-07-28). -* -* Pure, value-returning helpers used by the inbound HTTP classifier -* (`classifyInboundRequest`): claim detection and envelope validation with -* self-identifying issues. The envelope schema itself stays the wire layer's -* single source of truth (`RequestMetaEnvelopeSchema`); this module only maps -* its outcomes into the shapes the validation ladder emits. -* -* Claim detection is deliberately narrow: a message claims the 2026-07-28 -* envelope mechanism if and only if the reserved protocol-version `_meta` key -* is present in `params._meta`. Other reserved keys (client info, client -* capabilities, log level), a bare `progressToken`, or unrelated keys under -* the `io.modelcontextprotocol/` prefix do NOT constitute a claim on their -* own — but once the claim key is present, a malformed envelope is a -* validation error, never a silent fall back to legacy handling. -* -* The wire-exact envelope schema, the required-key set, and the per-key issue -* mapping live in the wire layer (the 2026-era codec's `validateEnvelopeMeta`). -* This module never reaches into a per-revision wire module directly. -*/ -function isPlainObject$3(value) { - return value !== null && typeof value === "object" && !Array.isArray(value); -} -/** The `_meta` object of a message's params, when present. */ -function src_CX2iR2pK_requestMetaOf(params) { - if (!isPlainObject$3(params)) return void 0; - const meta = params["_meta"]; - return isPlainObject$3(meta) ? meta : void 0; -} -/** -* Whether a message's params carry the per-request envelope claim: the -* reserved protocol-version `_meta` key is present (regardless of whether the -* rest of the envelope is valid — validation is a separate, later step). -*/ -function src_CX2iR2pK_hasEnvelopeClaim(params) { - const meta = src_CX2iR2pK_requestMetaOf(params); - return meta !== void 0 && PROTOCOL_VERSION_META_KEY in meta; -} -/** -* The protocol version named by a message's envelope claim, when the claim is -* present and carries a string value. A present claim with a non-string value -* still counts as a claim ({@linkcode hasEnvelopeClaim}); it surfaces as a -* validation issue instead of a version. -*/ -function src_CX2iR2pK_envelopeClaimVersion(params) { - const value = src_CX2iR2pK_requestMetaOf(params)?.[PROTOCOL_VERSION_META_KEY]; - return typeof value === "string" ? value : void 0; -} -/** -* Validates a request's `_meta` object as a 2026-07-28 per-request envelope -* and reports problems as self-identifying issues (which key, what problem). -* -* Returns an empty array when the envelope is valid. Missing required keys are -* reported first (as `problem: 'missing'`), then schema violations inside -* present keys, in a stable order. -*/ -function src_CX2iR2pK_validateEnvelopeMeta(meta) { - return src_CX2iR2pK_codecForVersion(src_CX2iR2pK_MODERN_WIRE_REVISION).validateEnvelopeMeta(meta); -} - -//#endregion -//#region ../core-internal/src/types/schemas.ts -var schemas_exports = /* @__PURE__ */ __exportAll({ - AnnotationsSchema: () => AnnotationsSchema, - AudioContentSchema: () => AudioContentSchema, - BaseMetadataSchema: () => BaseMetadataSchema, - BaseRequestParamsSchema: () => BaseRequestParamsSchema, - BlobResourceContentsSchema: () => BlobResourceContentsSchema, - BooleanSchemaSchema: () => BooleanSchemaSchema, - CallToolRequestParamsSchema: () => CallToolRequestParamsSchema, - CallToolRequestSchema: () => CallToolRequestSchema, - CallToolResultSchema: () => auth_CUe6YdwF_CallToolResultSchema, - CancelTaskRequestSchema: () => CancelTaskRequestSchema, - CancelTaskResultSchema: () => CancelTaskResultSchema, - CancelledNotificationParamsSchema: () => CancelledNotificationParamsSchema, - CancelledNotificationSchema: () => CancelledNotificationSchema, - ClientCapabilitiesSchema: () => ClientCapabilitiesSchema, - ClientNotificationSchema: () => ClientNotificationSchema, - ClientRequestSchema: () => ClientRequestSchema, - ClientResultSchema: () => ClientResultSchema, - ClientTasksCapabilitySchema: () => ClientTasksCapabilitySchema, - CompatibilityCallToolResultSchema: () => CompatibilityCallToolResultSchema, - CompleteRequestParamsSchema: () => CompleteRequestParamsSchema, - CompleteRequestSchema: () => CompleteRequestSchema, - CompleteResultSchema: () => CompleteResultSchema, - ContentBlockSchema: () => ContentBlockSchema, - CreateMessageRequestParamsSchema: () => CreateMessageRequestParamsSchema, - CreateMessageRequestSchema: () => CreateMessageRequestSchema, - CreateMessageResultSchema: () => CreateMessageResultSchema, - CreateMessageResultWithToolsSchema: () => CreateMessageResultWithToolsSchema, - CreateTaskResultSchema: () => CreateTaskResultSchema, - CursorSchema: () => CursorSchema, - DiscoverRequestSchema: () => DiscoverRequestSchema, - DiscoverResultSchema: () => DiscoverResultSchema, - ElicitRequestFormParamsSchema: () => ElicitRequestFormParamsSchema, - ElicitRequestParamsSchema: () => ElicitRequestParamsSchema, - ElicitRequestSchema: () => ElicitRequestSchema, - ElicitRequestURLParamsSchema: () => ElicitRequestURLParamsSchema, - ElicitResultSchema: () => ElicitResultSchema, - ElicitationCompleteNotificationParamsSchema: () => ElicitationCompleteNotificationParamsSchema, - ElicitationCompleteNotificationSchema: () => ElicitationCompleteNotificationSchema, - EmbeddedResourceSchema: () => EmbeddedResourceSchema, - EmptyResultSchema: () => EmptyResultSchema, - EnumSchemaSchema: () => EnumSchemaSchema, - GetPromptRequestParamsSchema: () => GetPromptRequestParamsSchema, - GetPromptRequestSchema: () => GetPromptRequestSchema, - GetPromptResultSchema: () => GetPromptResultSchema, - GetTaskPayloadRequestSchema: () => GetTaskPayloadRequestSchema, - GetTaskPayloadResultSchema: () => GetTaskPayloadResultSchema, - GetTaskRequestSchema: () => GetTaskRequestSchema, - GetTaskResultSchema: () => GetTaskResultSchema, - IconSchema: () => IconSchema, - IconsSchema: () => IconsSchema, - ImageContentSchema: () => ImageContentSchema, - ImplementationSchema: () => ImplementationSchema, - InitializeRequestParamsSchema: () => InitializeRequestParamsSchema, - InitializeRequestSchema: () => auth_CUe6YdwF_InitializeRequestSchema, - InitializeResultSchema: () => InitializeResultSchema, - InitializedNotificationSchema: () => auth_CUe6YdwF_InitializedNotificationSchema, - JSONArraySchema: () => JSONArraySchema, - JSONObjectSchema: () => JSONObjectSchema, - JSONRPCErrorResponseSchema: () => JSONRPCErrorResponseSchema, - JSONRPCMessageSchema: () => auth_CUe6YdwF_JSONRPCMessageSchema, - JSONRPCNotificationSchema: () => JSONRPCNotificationSchema, - JSONRPCRequestSchema: () => JSONRPCRequestSchema, - JSONRPCResponseSchema: () => auth_CUe6YdwF_JSONRPCResponseSchema, - JSONRPCResultResponseSchema: () => JSONRPCResultResponseSchema, - JSONValueSchema: () => JSONValueSchema, - LegacyTitledEnumSchemaSchema: () => LegacyTitledEnumSchemaSchema, - ListChangedOptionsBaseSchema: () => ListChangedOptionsBaseSchema, - ListPromptsRequestSchema: () => ListPromptsRequestSchema, - ListPromptsResultSchema: () => ListPromptsResultSchema, - ListResourceTemplatesRequestSchema: () => ListResourceTemplatesRequestSchema, - ListResourceTemplatesResultSchema: () => ListResourceTemplatesResultSchema, - ListResourcesRequestSchema: () => ListResourcesRequestSchema, - ListResourcesResultSchema: () => ListResourcesResultSchema, - ListRootsRequestSchema: () => ListRootsRequestSchema, - ListRootsResultSchema: () => ListRootsResultSchema, - ListTasksRequestSchema: () => ListTasksRequestSchema, - ListTasksResultSchema: () => ListTasksResultSchema, - ListToolsRequestSchema: () => ListToolsRequestSchema, - ListToolsResultSchema: () => ListToolsResultSchema, - LoggingLevelSchema: () => LoggingLevelSchema, - LoggingMessageNotificationParamsSchema: () => LoggingMessageNotificationParamsSchema, - LoggingMessageNotificationSchema: () => LoggingMessageNotificationSchema, - ModelHintSchema: () => ModelHintSchema, - ModelPreferencesSchema: () => ModelPreferencesSchema, - MultiSelectEnumSchemaSchema: () => MultiSelectEnumSchemaSchema, - NotificationSchema: () => NotificationSchema, - NotificationsParamsSchema: () => NotificationsParamsSchema, - NumberSchemaSchema: () => NumberSchemaSchema, - PaginatedRequestParamsSchema: () => PaginatedRequestParamsSchema, - PaginatedRequestSchema: () => PaginatedRequestSchema, - PaginatedResultSchema: () => PaginatedResultSchema, - PingRequestSchema: () => PingRequestSchema, - PrimitiveSchemaDefinitionSchema: () => PrimitiveSchemaDefinitionSchema, - ProgressNotificationParamsSchema: () => ProgressNotificationParamsSchema, - ProgressNotificationSchema: () => ProgressNotificationSchema, - ProgressSchema: () => ProgressSchema, - ProgressTokenSchema: () => ProgressTokenSchema, - PromptArgumentSchema: () => PromptArgumentSchema, - PromptListChangedNotificationSchema: () => PromptListChangedNotificationSchema, - PromptMessageSchema: () => PromptMessageSchema, - PromptReferenceSchema: () => PromptReferenceSchema, - PromptSchema: () => PromptSchema, - ReadResourceRequestParamsSchema: () => ReadResourceRequestParamsSchema, - ReadResourceRequestSchema: () => ReadResourceRequestSchema, - ReadResourceResultSchema: () => ReadResourceResultSchema, - RelatedTaskMetadataSchema: () => RelatedTaskMetadataSchema, - RequestIdSchema: () => RequestIdSchema, - RequestMetaSchema: () => RequestMetaSchema, - RequestSchema: () => RequestSchema, - ResourceContentsSchema: () => ResourceContentsSchema, - ResourceLinkSchema: () => ResourceLinkSchema, - ResourceListChangedNotificationSchema: () => ResourceListChangedNotificationSchema, - ResourceRequestParamsSchema: () => ResourceRequestParamsSchema, - ResourceSchema: () => ResourceSchema, - ResourceTemplateReferenceSchema: () => ResourceTemplateReferenceSchema, - ResourceTemplateSchema: () => ResourceTemplateSchema, - ResourceUpdatedNotificationParamsSchema: () => ResourceUpdatedNotificationParamsSchema, - ResourceUpdatedNotificationSchema: () => ResourceUpdatedNotificationSchema, - ResultMetaObjectSchema: () => ResultMetaObjectSchema, - ResultSchema: () => ResultSchema, - RoleSchema: () => RoleSchema, - RootSchema: () => RootSchema, - RootsListChangedNotificationSchema: () => RootsListChangedNotificationSchema, - SamplingContentSchema: () => SamplingContentSchema, - SamplingMessageContentBlockSchema: () => SamplingMessageContentBlockSchema, - SamplingMessageSchema: () => SamplingMessageSchema, - ServerCapabilitiesSchema: () => ServerCapabilitiesSchema, - ServerNotificationSchema: () => ServerNotificationSchema, - ServerRequestSchema: () => ServerRequestSchema, - ServerResultSchema: () => ServerResultSchema, - ServerTasksCapabilitySchema: () => ServerTasksCapabilitySchema, - SetLevelRequestParamsSchema: () => SetLevelRequestParamsSchema, - SetLevelRequestSchema: () => SetLevelRequestSchema, - SingleSelectEnumSchemaSchema: () => SingleSelectEnumSchemaSchema, - StringSchemaSchema: () => StringSchemaSchema, - SubscribeRequestParamsSchema: () => SubscribeRequestParamsSchema, - SubscribeRequestSchema: () => SubscribeRequestSchema, - SubscriptionFilterSchema: () => SubscriptionFilterSchema, - SubscriptionsAcknowledgedNotificationParamsSchema: () => SubscriptionsAcknowledgedNotificationParamsSchema, - SubscriptionsAcknowledgedNotificationSchema: () => SubscriptionsAcknowledgedNotificationSchema, - SubscriptionsListenRequestParamsSchema: () => SubscriptionsListenRequestParamsSchema, - SubscriptionsListenRequestSchema: () => SubscriptionsListenRequestSchema, - SubscriptionsListenResultMetaSchema: () => SubscriptionsListenResultMetaSchema, - SubscriptionsListenResultSchema: () => SubscriptionsListenResultSchema, - TaskAugmentedRequestParamsSchema: () => auth_CUe6YdwF_TaskAugmentedRequestParamsSchema, - TaskCreationParamsSchema: () => TaskCreationParamsSchema, - TaskMetadataSchema: () => TaskMetadataSchema, - TaskSchema: () => TaskSchema, - TaskStatusNotificationParamsSchema: () => TaskStatusNotificationParamsSchema, - TaskStatusNotificationSchema: () => TaskStatusNotificationSchema, - TaskStatusSchema: () => TaskStatusSchema, - TextContentSchema: () => TextContentSchema, - TextResourceContentsSchema: () => TextResourceContentsSchema, - TitledMultiSelectEnumSchemaSchema: () => TitledMultiSelectEnumSchemaSchema, - TitledSingleSelectEnumSchemaSchema: () => TitledSingleSelectEnumSchemaSchema, - ToolAnnotationsSchema: () => ToolAnnotationsSchema, - ToolChoiceSchema: () => ToolChoiceSchema, - ToolExecutionSchema: () => ToolExecutionSchema, - ToolListChangedNotificationSchema: () => ToolListChangedNotificationSchema, - ToolResultContentSchema: () => ToolResultContentSchema, - ToolSchema: () => ToolSchema, - ToolUseContentSchema: () => ToolUseContentSchema, - UnsubscribeRequestParamsSchema: () => UnsubscribeRequestParamsSchema, - UnsubscribeRequestSchema: () => UnsubscribeRequestSchema, - UntitledMultiSelectEnumSchemaSchema: () => UntitledMultiSelectEnumSchemaSchema, - UntitledSingleSelectEnumSchemaSchema: () => UntitledSingleSelectEnumSchemaSchema -}); - -//#endregion -//#region ../core-internal/src/types/guards.ts -/** -* Validates and parses an unknown value as a JSON-RPC message. -* -* Use this to validate incoming messages in custom transport implementations. -* Throws if the value does not conform to the JSON-RPC message schema. -* -* @param value - The value to validate (typically a parsed JSON object). -* @returns The validated {@linkcode JSONRPCMessage}. -* @throws If validation fails. -*/ -function parseJSONRPCMessage(value) { - return JSONRPCMessageSchema.parse(value); -} -const src_CX2iR2pK_isJSONRPCRequest = (value) => JSONRPCRequestSchema.safeParse(value).success; -const src_CX2iR2pK_isJSONRPCNotification = (value) => JSONRPCNotificationSchema.safeParse(value).success; -/** -* Checks if a value is a valid {@linkcode JSONRPCResultResponse}. -* @param value - The value to check. -* -* @returns True if the value is a valid {@linkcode JSONRPCResultResponse}, false otherwise. -*/ -const src_CX2iR2pK_isJSONRPCResultResponse = (value) => JSONRPCResultResponseSchema.safeParse(value).success; -/** -* Checks if a value is a valid {@linkcode JSONRPCErrorResponse}. -* @param value - The value to check. -* -* @returns True if the value is a valid {@linkcode JSONRPCErrorResponse}, false otherwise. -*/ -const src_CX2iR2pK_isJSONRPCErrorResponse = (value) => JSONRPCErrorResponseSchema.safeParse(value).success; -/** -* Checks if a value is a valid {@linkcode JSONRPCResponse} (either a result or error response). -* @param value - The value to check. -* -* @returns True if the value is a valid {@linkcode JSONRPCResponse}, false otherwise. -*/ -const isJSONRPCResponse = (value) => JSONRPCResponseSchema.safeParse(value).success; -/** -* Checks if a value is a valid {@linkcode CallToolResult}. -* -* This is a consumer-side VALUE check against the neutral model, not a wire -* validator: a raw wire object that additionally carries wire-only members -* (e.g. `resultType`) still passes through the loose index signature. Use a -* transport-level parse to validate raw wire traffic. -* -* @param value - The value to check. -* -* @returns True if the value is a valid {@linkcode CallToolResult}, false otherwise. -*/ -const isCallToolResult = (value) => { - if (typeof value !== "object" || value === null || value.content === void 0) return false; - return CallToolResultSchema.safeParse(value).success; -}; -/** -* Checks whether a value is an input-required result (protocol revision -* 2026-07-28): the multi-round-trip return shape discriminated by -* `resultType: 'input_required'`. -* -* This is a discriminator check, not a full validator — the at-least-one rule -* (`inputRequests` or `requestState`) is enforced by the `inputRequired()` -* builder and re-checked by the server seam for hand-built values. -* -* @param value - The value to check. -* @returns True if the value carries the `input_required` discriminator. -*/ -const isInputRequiredResult = (value) => typeof value === "object" && value !== null && !Array.isArray(value) && value.resultType === "input_required"; -/** -* Checks if a value is a valid {@linkcode TaskAugmentedRequestParams}. -* @param value - The value to check. -* -* @returns True if the value is a valid {@linkcode TaskAugmentedRequestParams}, false otherwise. -* -* @deprecated Recognizes 2025-11-25 task wire vocabulary, which has no SDK -* runtime; kept importable for interoperability only. -*/ -const isTaskAugmentedRequestParams = (value) => TaskAugmentedRequestParamsSchema.safeParse(value).success; -const src_CX2iR2pK_isInitializeRequest = (value) => InitializeRequestSchema.safeParse(value).success; -const isInitializedNotification = (value) => InitializedNotificationSchema.safeParse(value).success; -function assertCompleteRequestPrompt(request) { - if (request.params.ref.type !== "ref/prompt") throw new TypeError(`Expected CompleteRequestPrompt, but got ${request.params.ref.type}`); -} -function assertCompleteRequestResourceTemplate(request) { - if (request.params.ref.type !== "ref/resource") throw new TypeError(`Expected CompleteRequestResourceTemplate, but got ${request.params.ref.type}`); -} - -//#endregion -//#region ../core-internal/src/shared/mcpParamHeaders.ts -/** The fixed prefix every custom-parameter header carries. */ -const MCP_PARAM_HEADER_PREFIX = "Mcp-Param-"; -/** The schema-extension property name a tool's `inputSchema` carries. */ -const X_MCP_HEADER_KEY = "x-mcp-header"; -/** -* RFC 9110 §5.1 `token` syntax (`1*tchar`). Rejects empty, space, control -* characters (including CR/LF), and the listed delimiters. -*/ -const RFC9110_TOKEN = /^[!#$%&'*+\-.^_`|~0-9A-Za-z]+$/; -/** -* JSON Schema `type` values the spec admits on an `x-mcp-header` property. -* -* The spec text names `integer`, `string`, `boolean` and explicitly excludes -* `number`. The published conformance referee at the pinned release ships its -* `http-custom-headers` scenario with two `type: "number"` `x-mcp-header` -* parameters and expects the client to mirror them, so `number` is accepted -* here so that the conformance gate passes; the discrepancy is tracked -* upstream. Everything else (`object`, `array`, `null`, absent) is rejected. -*/ -const PERMITTED_X_MCP_HEADER_TYPES = new Set([ - "string", - "integer", - "boolean", - "number" -]); -/** -* Scan a tool's JSON-serialized `inputSchema` for `x-mcp-header` declarations -* and validate every constraint the spec places on them. Returns either the -* collected declarations (possibly empty) or the first violated constraint. -* -* The walk descends through `properties` at any depth (the spec's "any nesting -* depth" clause). The static-reachability MUST is enforced as a structural -* sweep: every position the chain MUST NOT pass through (`items`/ -* `additionalProperties`, `oneOf`/`anyOf`/`allOf`/`not`, `if`/`then`/`else`, -* `$defs`, `$ref` targets within `$defs`) is visited too, and an -* `x-mcp-header` found anywhere on that path invalidates the schema — "an -* annotation anywhere else makes the tool definition invalid". -*/ -function src_CX2iR2pK_scanXMcpHeaderDeclarations(inputSchema) { - const declarations = []; - const seenLower = /* @__PURE__ */ new Map(); - const visit = (node, path, reachable) => { - if (node === null || typeof node !== "object") return void 0; - const schema = node; - if (X_MCP_HEADER_KEY in schema) { - if (!reachable || path.length === 0) return `${pathName(path)}: x-mcp-header is only permitted on properties statically reachable via a chain of 'properties' keys (not under items, additionalProperties, oneOf/anyOf/allOf/not, if/then/else, or $ref)`; - const raw = schema[X_MCP_HEADER_KEY]; - if (typeof raw !== "string" || raw.length === 0) return `${pathName(path)}: x-mcp-header MUST be a non-empty string`; - if (!RFC9110_TOKEN.test(raw)) return `${pathName(path)}: x-mcp-header '${raw}' is not a valid RFC 9110 token (no spaces, control characters or HTTP delimiters)`; - const type = typeof schema.type === "string" ? schema.type : void 0; - if (type === void 0 || !PERMITTED_X_MCP_HEADER_TYPES.has(type)) return `${pathName(path)}: x-mcp-header is only permitted on primitive-typed properties (string, integer, boolean); got ${type ?? ""}`; - const lower = raw.toLowerCase(); - const prior = seenLower.get(lower); - if (prior !== void 0) return `x-mcp-header '${raw}' is not case-insensitively unique (also declared as '${prior}')`; - seenLower.set(lower, raw); - declarations.push({ - path, - headerName: raw, - type - }); - } - const properties = schema.properties; - if (properties !== null && typeof properties === "object") for (const [key, child] of Object.entries(properties)) { - const fault$1 = visit(child, [...path, key], reachable); - if (fault$1 !== void 0) return fault$1; - } - for (const k of NON_REACHABLE_SUBSCHEMA_KEYWORDS) { - const sub = schema[k]; - if (sub === void 0) continue; - const branches = Array.isArray(sub) ? sub : sub !== null && typeof sub === "object" && OBJECT_VALUED_SUBSCHEMA_KEYWORDS.has(k) ? Object.values(sub) : [sub]; - for (const branch of branches) { - const fault$1 = visit(branch, [...path, `<${k}>`], false); - if (fault$1 !== void 0) return fault$1; - } - } - }; - const fault = visit(inputSchema, [], true); - return fault === void 0 ? { - valid: true, - declarations - } : { - valid: false, - reason: fault - }; -} -/** -* JSON Schema keywords whose subschemas the SEP-2243 static-reachability -* constraint excludes from the `properties`-only chain. An `x-mcp-header` -* found under any of these invalidates the tool definition. -*/ -const NON_REACHABLE_SUBSCHEMA_KEYWORDS = [ - "items", - "prefixItems", - "contains", - "additionalProperties", - "unevaluatedProperties", - "unevaluatedItems", - "propertyNames", - "patternProperties", - "dependentSchemas", - "oneOf", - "anyOf", - "allOf", - "not", - "if", - "then", - "else", - "$defs", - "definitions" -]; -/** -* Subschema-carrying keywords whose value is a `name → subschema` object -* (not a single subschema or array of subschemas). The visit branches over -* `Object.values()` for these. -*/ -const OBJECT_VALUED_SUBSCHEMA_KEYWORDS = new Set([ - "patternProperties", - "dependentSchemas", - "$defs", - "definitions" -]); -function pathName(path) { - return path.length === 0 ? "" : path.join("."); -} -const BASE64_SENTINEL_PREFIX = "=?base64?"; -const BASE64_SENTINEL_SUFFIX = "?="; -const BASE64_CANONICAL = /^(?:[A-Za-z0-9+/]{4})*(?:[A-Za-z0-9+/]{2}==|[A-Za-z0-9+/]{3}=)?$/; -const CANONICAL_DECIMAL = /^-?\d+(\.\d+)?$/; -/** -* Convert a primitive argument value to its string representation per the -* spec's type-conversion rules: strings pass through, integers and numbers -* become their decimal string, booleans become lowercase `'true'` / `'false'`. -* Non-finite numbers and integers outside the safe range are refused (the -* caller treats `undefined` as "do not emit a header for this value"). -*/ -function mcpParamPrimitiveToString(value) { - if (typeof value === "string") return value; - if (typeof value === "boolean") return value ? "true" : "false"; - if (typeof value === "number") { - if (!Number.isFinite(value)) return void 0; - if (Number.isInteger(value) && !Number.isSafeInteger(value)) return void 0; - return String(value); - } -} -function base64ToUtf8(b64) { - const bin = atob(b64); - const bytes = new Uint8Array(bin.length); - for (let i = 0; i < bin.length; i++) bytes[i] = bin.codePointAt(i); - return new TextDecoder("utf-8", { fatal: true }).decode(bytes); -} -/** -* Decode an `Mcp-Param-*` header value: when it carries the Base64 sentinel, -* the payload is decoded as UTF-8; otherwise the value is returned as-is. -* Returns `undefined` when the sentinel is present but the payload is not -* canonical Base64 (or not valid UTF-8) — the spec requires servers to reject -* such values. -*/ -function decodeMcpParamValue(value) { - if (!(value.startsWith(BASE64_SENTINEL_PREFIX) && value.endsWith(BASE64_SENTINEL_SUFFIX))) return value; - const b64 = value.slice(9, value.length - 2); - if (!BASE64_CANONICAL.test(b64)) return void 0; - try { - return base64ToUtf8(b64); - } catch { - return; - } -} -function valueAtPath(root, path) { - let node = root; - for (const key of path) { - if (node === null || typeof node !== "object") return void 0; - node = node[key]; - } - return node; -} -/** -* The header/body comparison the server performs at tool-resolution time. -* -* For each `x-mcp-header` declaration on the named tool: when the body -* `arguments` carries a value, the matching `Mcp-Param-{Name}` header MUST be -* present and decode to an equal value; when the body value is `null` or -* absent the server MUST NOT expect the header (a present header is ignored). -* A sentinel-carrying header whose payload is not canonical Base64 / valid -* UTF-8 is rejected as invalid characters. -* -* Integer-typed declarations are compared numerically (the spec's SHOULD — -* `42.0` and `42` are equal); everything else is compared as decoded strings. -* -* Returns `undefined` when every check passes, or an -* {@linkcode InboundLadderRejection} carrying the same `-32020` -* (`HeaderMismatch`) shape the inbound classifier emits for the -* standard-header cross-checks — `400 Bad Request` with the disagreeing pair -* in `data.mismatch`. -*/ -function src_CX2iR2pK_validateMcpParamHeaders(declarations, args, headers) { - for (const decl of declarations) { - const headerKey = `${MCP_PARAM_HEADER_PREFIX}${decl.headerName}`; - const headerValue = headers.get(headerKey); - const bodyRaw = valueAtPath(args, decl.path); - if (bodyRaw === void 0 || bodyRaw === null) continue; - const bodyString = mcpParamPrimitiveToString(bodyRaw); - if (bodyString === void 0) continue; - if (headerValue === null) return paramHeaderMismatchRejection("param-header-missing", headerKey, `the body carries ${pathName(decl.path)}=${JSON.stringify(bodyRaw)} but the ${headerKey} header is absent`); - const decoded = decodeMcpParamValue(headerValue); - if (decoded === void 0) return paramHeaderMismatchRejection("param-header-invalid-encoding", headerKey, `the ${headerKey} header carries an invalid Base64 sentinel value`); - if (!((decl.type === "integer" || decl.type === "number") && CANONICAL_DECIMAL.test(decoded) && typeof bodyRaw === "number" ? Number(decoded) === bodyRaw : decoded === bodyString)) return paramHeaderMismatchRejection("param-header-mismatch", headerKey, `the ${headerKey} header decodes to ${JSON.stringify(decoded)} but the body carries ${pathName(decl.path)}=${JSON.stringify(bodyRaw)}`); - } -} -/** -* Build the `-32020` (`HeaderMismatch`) rejection for an `Mcp-Param-*` -* disagreement. Same shape as the inbound classifier's standard-header -* cross-check mismatch (HTTP `400`, `data.mismatch` naming the disagreeing -* pair, `settled: true`); only the rung differs because this check runs at the -* pre-dispatch step against a known tool's schema rather than at the edge. -*/ -function paramHeaderMismatchRejection(cell, header, body) { - return { - kind: "reject", - rung: "param-header-validation", - cell, - httpStatus: 400, - code: HEADER_MISMATCH_ERROR_CODE, - message: `Bad Request: the request headers and body disagree: ${body}`, - data: { mismatch: { - header, - body - } }, - settled: true - }; -} - -//#endregion -//#region ../core-internal/src/shared/inboundClassification.ts -/** -* Inbound HTTP request classification and the inbound validation ladder -* (protocol revision 2026-07-28). -* -* `classifyInboundRequest` is the body-primary era predicate for an HTTP -* entry that serves both protocol eras on one endpoint. It is evaluated -* exactly once, at the entry boundary, on the already-parsed request body: -* -* - `initialize` is a legacy-era request by definition (the modern era has no -* `initialize` handshake) — unless it carries a valid envelope claim naming -* a modern revision, in which case the claim wins and the request is -* classified like any other enveloped request (the modern era then answers -* it with method-not-found, exactly like every other method it does not -* define). -* - A request whose `params._meta` carries the reserved protocol-version key -* claims the per-request envelope mechanism and classifies into the era the -* named revision belongs to (a malformed envelope behind a present claim is -* a validation error, never a silent fall back to legacy handling). -* - A request without a claim is legacy-era traffic. -* - The `MCP-Protocol-Version` header is a cross-check only: it never -* upgrades or downgrades a body-derived classification, and a disagreement -* between header and body is an explicit ladder outcome. -* - Notifications carry no envelope claim of their own under the current -* spec, so for notification POSTs without a body claim the modern header is -* determinative; the `Mcp-Method` header is validated against the body when -* the message classifies modern and is never enforced on legacy traffic. -* A notification that does carry a claim is treated body-primary like a -* request, and a malformed claim is rejected the same way a request's -* malformed claim is — never silently resolved against the header. -* The notification-POST header cross-checks here are an SDK-defensive -* posture, not a spec requirement: the spec leaves header rules for posted -* notifications undefined (core client notifications do not occur over -* Streamable HTTP); applying the request rules symmetrically is what an -* ecosystem custom-notification POST expects, and the −32020 cells stay -* passing for them. -* - `GET`/`DELETE` (and any other non-`POST` method) are body-less 2025-era -* session operations: the modern era is `POST`-only, so they are routed to -* legacy serving when it is configured and rejected otherwise. -* - Array (batch) bodies are classified element-wise: an array containing a -* modern-claiming or invalid element is rejected, an all-legacy array is -* legacy traffic unchanged, and a single-element array is still an array. -* -* The classifier returns plain values (it never throws and never touches a -* transport): a routing outcome (`legacy`/`modern`) or a ladder rejection -* carrying the JSON-RPC error to emit and the HTTP status to emit it with. -* Legacy routing outcomes deliberately carry NO `MessageClassification` — -* legacy and hand-wired traffic is never classified, which keeps its -* dispatch behavior byte-identical to today's. -* -* Error codes for the modern-path rejection cells follow the published -* conformance suite (and the spec text it asserts): -* -* - A header/body cross-check mismatch (the `MCP-Protocol-Version` header -* disagreeing with the body, or the `Mcp-Method` header disagreeing with the -* body method) is rejected with `-32020` (`HeaderMismatch`) on HTTP 400. -* - A request whose protocol-version header names a modern revision but whose -* body carries no `_meta` envelope claim — including an envelope present but -* missing the required protocol-version key — is rejected with `-32602` -* (invalid params) naming the missing key(s), on HTTP 400. -* -* Should a future spec revision or conformance release change these -* assignments, the affected cells are re-derived against that release; the -* `settled` flag on {@linkcode InboundLadderRejection} stays available to mark -* a cell provisional again while such a change is in flight. -*/ -/** -* The error code emitted for header/body cross-check mismatches: the -* `MCP-Protocol-Version` header disagreeing with the body's envelope claim (or -* with the body's classification), and the `Mcp-Method` header disagreeing -* with the body method. -* -* `-32020` is the draft schema's `HEADER_MISMATCH` constant (the SEP-2243 -* `HeaderMismatch` code; the spec requires HTTP 400 for it), as also asserted -* by the published conformance suite for header-validation failures. It has no -* {@linkcode ProtocolErrorCode} member because it is not part of the 2025-era -* wire vocabulary; the validation ladder is its only emitter. -*/ -const HEADER_MISMATCH_ERROR_CODE = -32020; -/** -* The inbound validation ladder, expressed as data rather than control flow. -* -* The edge rungs are evaluated by {@linkcode classifyInboundRequest}; the -* dispatch rungs are evaluated by the protocol layer once the classified -* message is injected into a per-request server instance (the era registry -* gate, the envelope requiredness check, and per-method params validation). -* The client-capability rung is evaluated by the HTTP entry itself, -* pre-dispatch, on the validated envelope the classifier produced — see that -* rung's rationale for the ordering caveat. The order is the precedence: a -* request that fails several rungs is answered by the earliest one. -*/ -const INBOUND_VALIDATION_LADDER = [ - { - 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: [src_CX2iR2pK_ProtocolErrorCode.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: [HEADER_MISMATCH_ERROR_CODE, src_CX2iR2pK_ProtocolErrorCode.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: [src_CX2iR2pK_ProtocolErrorCode.InvalidParams], - conformance: ["server-stateless"], - rationale: "A present envelope claim with a malformed envelope — and a missing envelope on a request whose protocol-version header names a modern revision — 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: [src_CX2iR2pK_ProtocolErrorCode.MethodNotFound], - conformance: ["server-stateless"], - rationale: "Method existence outranks parameter validity: a method absent from the negotiated revision’s 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: [src_CX2iR2pK_ProtocolErrorCode.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: [HEADER_MISMATCH_ERROR_CODE], - conformance: ["http-header-validation"], - rationale: "SEP-2243 standard `Mcp-Method` / `Mcp-Name` headers — presence, sentinel decoding, and `Mcp-Name` ↔ body cross-check — are validated by the HTTP entry on a modern-classified request after the supported-revision gate and before dispatch. The classifier’s 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–6) are consulted." - }, - { - rung: "client-capabilities", - order: 8, - evaluatedAt: "pre-dispatch", - codes: [src_CX2iR2pK_ProtocolErrorCode.MissingRequiredClientCapability], - conformance: ["server-stateless"], - rationale: "The capability requirement is checked by the HTTP entry, pre-dispatch, against the validated envelope the classifier produced — 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: [HEADER_MISMATCH_ERROR_CODE], - conformance: ["http-custom-header-server-validation"], - rationale: "SEP-2243 `Mcp-Param-*` headers are validated against the named tool’s `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." - } -]; -/** -* HTTP status for ladder-originated JSON-RPC error codes. -* -* Keyed on origin, not on the bare code: this table only applies to errors -* the ladder (or a pre-handler protocol gate) produced. Errors produced by -* request handlers — whatever their code — stay in-band on HTTP 200, and are -* never mapped to an HTTP status by this table; in particular `-32603` and -* domain-specific codes never become a blanket 500. The single exception is -* `MissingRequiredClientCapability` (-32021) — see -* {@linkcode httpStatusForErrorCode}. -* -* `-32602` (invalid params) deliberately has NO entry: the only invalid-params -* rejection that maps to HTTP 400 is the classifier's own envelope rung -* short-circuit, which carries its HTTP status directly. A dispatch- or -* handler-produced invalid-params error is always in-band. -*/ -const src_CX2iR2pK_LADDER_ERROR_HTTP_STATUS = { - [src_CX2iR2pK_ProtocolErrorCode.ParseError]: 400, - [src_CX2iR2pK_ProtocolErrorCode.InvalidRequest]: 400, - [src_CX2iR2pK_ProtocolErrorCode.MethodNotFound]: 404, - [src_CX2iR2pK_ProtocolErrorCode.UnsupportedProtocolVersion]: 400, - [src_CX2iR2pK_ProtocolErrorCode.MissingRequiredClientCapability]: 400, - [HEADER_MISMATCH_ERROR_CODE]: 400 -}; -/** -* The HTTP status to answer a JSON-RPC error with, keyed on the error's -* origin. `in-band` errors (anything produced by a request handler) are -* HTTP 200 — the JSON-RPC error response is the payload, not an HTTP -* failure — with ONE exception: `MissingRequiredClientCapability` (-32021), -* whose 400 the spec mandates on the error itself with no origin condition, -* and which the SDK genuinely produces after dispatch (the `input_required` -* capability gate). A handler relaying some downstream peer's `-32020`/`-32022` -* is NOT that peer's spec error and stays in-band like every other handler -* code. `ladder` errors map through {@linkcode LADDER_ERROR_HTTP_STATUS}. -* -* The per-request transport intentionally does NOT delegate to this function: -* its `?? 400` ladder fallback is only correct for entry-gate codes known to -* the table, and would wrongly map dispatch-window errors outside it (a -* window `-32602` must stay in-band on 200). The transport indexes the table -* directly; keep the two in agreement when editing either. -*/ -function src_CX2iR2pK_httpStatusForErrorCode(code, origin) { - if (origin === "in-band") return code === src_CX2iR2pK_ProtocolErrorCode.MissingRequiredClientCapability ? 400 : 200; - return src_CX2iR2pK_LADDER_ERROR_HTTP_STATUS[code] ?? 400; -} -function src_CX2iR2pK_rejection(rung, cell, httpStatus, error, settled) { - return { - kind: "reject", - rung, - cell, - httpStatus, - code: error.code, - message: error.message, - ...error.data !== void 0 && { data: error.data }, - settled - }; -} -function crossCheckMismatch(cell, header, body, rung = "era-classification") { - return src_CX2iR2pK_rejection(rung, cell, 400, new src_CX2iR2pK_ProtocolError(HEADER_MISMATCH_ERROR_CODE, `Bad Request: the request headers and body disagree: ${body}`, { mismatch: { - header, - body - } }), true); -} -/** -* The methods whose body carries a `params.name` / `params.uri` value the -* `Mcp-Name` header must mirror, and which body field supplies it (SEP-2243 -* § Standard Request Headers, `Required For` column). -*/ -const MCP_NAME_HEADER_SOURCE = (/* unused pure expression or super */ null && ({ - "tools/call": "name", - "prompts/get": "name", - "resources/read": "uri" -})); -/** Strip RFC 9110 optional whitespace (SP / HTAB) around a field value in linear time. */ -function stripHttpOws(value) { - let start = 0; - while (start < value.length) { - const code = value.codePointAt(start); - if (code !== 9 && code !== 32) break; - start += 1; - } - let end = value.length; - while (end > start) { - const code = value.codePointAt(end - 1); - if (code !== 9 && code !== 32) break; - end -= 1; - } - return start === 0 && end === value.length ? value : value.slice(start, end); -} -/** -* SEP-2243 standard-header server-side validation, evaluated by the HTTP -* entry on a modern-classified request immediately after -* {@linkcode classifyInboundRequest} returns a modern route. -* -* Returns the `-32020` (`HeaderMismatch`) ladder rejection (HTTP `400`, -* `standard-header-validation` rung — the same shape -* {@linkcode classifyInboundRequest} already emits on the edge -* `era-classification` rung for the `MCP-Protocol-Version` and -* `Mcp-Method` *mismatch* cells) when: -* -* - the required `Mcp-Method` header is absent; -* - the required `Mcp-Name` header is absent on a `tools/call`, -* `prompts/get`, or `resources/read` request whose body carries the -* `params.name` / `params.uri` value the header mirrors; -* - the `Mcp-Name` header carries an invalid `=?base64?…?=` sentinel; or -* - the (decoded) `Mcp-Name` value disagrees with the body's -* `params.name` / `params.uri`. -* -* Returns `undefined` (pass) for notifications (the spec table reads -* "All requests"), for methods that have no `Mcp-Name` source, and when the -* headers agree with the body. Never enforced on legacy traffic — the entry -* only calls this on a modern route. -* -* Kept separate from {@linkcode classifyInboundRequest} so that a body-only -* call to the classifier (no headers passed) keeps routing a modern request -* unchanged: the classifier remains a pure body-primary router, and this -* function is the presence/`Mcp-Name` half of the standard-header rung the -* entry layers on top. -*/ -function src_CX2iR2pK_validateStandardRequestHeaders(request, route) { - if (route.messageKind !== "request") return; - const method = route.message.method; - if (request.mcpMethodHeader === void 0) return crossCheckMismatch("method-header-missing", "(missing)", `the body names method ${method} but the required Mcp-Method header is absent`, "standard-header-validation"); - const sourceField = Object.hasOwn(MCP_NAME_HEADER_SOURCE, method) ? MCP_NAME_HEADER_SOURCE[method] : void 0; - if (sourceField === void 0) return; - const sourceValue = route.message.params?.[sourceField]; - const bodyValue = typeof sourceValue === "string" ? sourceValue : void 0; - if (request.mcpNameHeader === void 0) { - if (bodyValue === void 0) return; - return crossCheckMismatch("name-header-missing", "(missing)", `the body carries params.${sourceField}="${bodyValue}" but the required Mcp-Name header is absent`, "standard-header-validation"); - } - const normalizedNameHeader = stripHttpOws(request.mcpNameHeader); - const decoded = decodeMcpParamValue(normalizedNameHeader); - if (decoded === void 0) return crossCheckMismatch("name-header-invalid-encoding", normalizedNameHeader, "the Mcp-Name header carries an invalid Base64 sentinel value", "standard-header-validation"); - if (bodyValue !== void 0 && decoded !== bodyValue) return crossCheckMismatch("name-header-mismatch", normalizedNameHeader, `the body carries params.${sourceField}="${bodyValue}" but the Mcp-Name header names "${decoded}"`, "standard-header-validation"); -} -function isPlainObject$2(value) { - return value !== null && typeof value === "object" && !Array.isArray(value); -} -function classificationForClaim(claimedVersion) { - if (claimedVersion === void 0) return { era: "modern" }; - return { - era: isModernProtocolVersion(claimedVersion) ? "modern" : "legacy", - revision: claimedVersion - }; -} -/** -* Whether a request's params carry a per-request envelope claim that is both -* well-formed and names a modern protocol revision. -* -* Used by the `initialize` precedence rule: only such a claim overrides the -* `initialize` ⇒ legacy-handshake classification — a request carrying a valid -* modern envelope is a modern request regardless of its method name, and the -* modern era then answers `initialize` exactly like any other method it does -* not define (method-not-found). A malformed claim, or one naming a pre-2026 -* revision, keeps the legacy-handshake routing unchanged. -* -* Exported on the core internal barrel for the stdio serving entry, which -* applies the same precedence rule to a connection's opening message; not -* public API. -*/ -function src_CX2iR2pK_carriesValidModernEnvelopeClaim(params) { - if (!src_CX2iR2pK_hasEnvelopeClaim(params)) return false; - const claimedVersion = src_CX2iR2pK_envelopeClaimVersion(params); - if (claimedVersion === void 0 || !isModernProtocolVersion(claimedVersion)) return false; - const meta = src_CX2iR2pK_requestMetaOf(params); - return meta !== void 0 && src_CX2iR2pK_validateEnvelopeMeta(meta).length === 0; -} -function classifyBatch(body) { - if (body.length === 0) return src_CX2iR2pK_rejection("jsonrpc-shape", "empty-batch", 400, new src_CX2iR2pK_ProtocolError(src_CX2iR2pK_ProtocolErrorCode.InvalidRequest, "Bad Request: empty JSON-RPC batch"), true); - for (const element of body) { - if (src_CX2iR2pK_hasEnvelopeClaim(isPlainObject$2(element) ? element["params"] : void 0)) return src_CX2iR2pK_rejection("jsonrpc-shape", "batch-with-modern-element", 400, new src_CX2iR2pK_ProtocolError(src_CX2iR2pK_ProtocolErrorCode.InvalidRequest, "Bad Request: JSON-RPC batches may not contain requests for protocol revision 2026-07-28 or later"), true); - if (!(src_CX2iR2pK_isJSONRPCRequest(element) || src_CX2iR2pK_isJSONRPCNotification(element) || src_CX2iR2pK_isJSONRPCResultResponse(element) || src_CX2iR2pK_isJSONRPCErrorResponse(element))) return src_CX2iR2pK_rejection("jsonrpc-shape", "batch-with-invalid-element", 400, new src_CX2iR2pK_ProtocolError(src_CX2iR2pK_ProtocolErrorCode.InvalidRequest, "Bad Request: JSON-RPC batch contains an invalid message"), true); - } - return { - kind: "legacy", - reason: "batch" - }; -} -function classifyRequestBody(request, body) { - const params = body.params; - const method = body.method; - const headerVersion = request.protocolVersionHeader; - const headerNamesModern = headerVersion !== void 0 && isModernProtocolVersion(headerVersion); - if (method === "initialize" && !src_CX2iR2pK_carriesValidModernEnvelopeClaim(params)) { - if (headerNamesModern) return crossCheckMismatch("initialize-with-modern-header", headerVersion, "an initialize request (legacy handshake) was sent with a modern MCP-Protocol-Version header"); - const requestedVersion = isPlainObject$2(params) && typeof params["protocolVersion"] === "string" ? params["protocolVersion"] : void 0; - return { - kind: "legacy", - reason: "initialize", - ...requestedVersion !== void 0 && { requestedVersion } - }; - } - if (src_CX2iR2pK_hasEnvelopeClaim(params)) { - const meta = src_CX2iR2pK_requestMetaOf(params); - const firstIssue = (meta === void 0 ? [] : src_CX2iR2pK_validateEnvelopeMeta(meta))[0]; - if (firstIssue !== void 0) return src_CX2iR2pK_rejection("envelope", "envelope-invalid", 400, new src_CX2iR2pK_ProtocolError(src_CX2iR2pK_ProtocolErrorCode.InvalidParams, `Invalid _meta envelope for protocol revision 2026-07-28: ${firstIssue.key}: ${firstIssue.problem}`, { envelope: firstIssue }), true); - const claimedVersion = src_CX2iR2pK_envelopeClaimVersion(params); - if (headerVersion !== void 0 && claimedVersion !== void 0 && headerVersion !== claimedVersion) return crossCheckMismatch("header-body-version-mismatch", headerVersion, `the body envelope names protocol version ${claimedVersion} but the MCP-Protocol-Version header names ${headerVersion}`); - if (request.mcpMethodHeader !== void 0 && request.mcpMethodHeader !== method) return crossCheckMismatch("method-header-mismatch", request.mcpMethodHeader, `the body names method ${method} but the Mcp-Method header names ${request.mcpMethodHeader}`); - return { - kind: "modern", - messageKind: "request", - message: body, - classification: classificationForClaim(claimedVersion) - }; - } - if (headerNamesModern) { - const meta = src_CX2iR2pK_requestMetaOf(params); - const missingFromEnvelope = src_CX2iR2pK_validateEnvelopeMeta(meta ?? {}).filter((issue) => issue.problem === "missing").map((issue) => issue.key); - const missing = meta === void 0 ? ["_meta"] : missingFromEnvelope.length > 0 ? missingFromEnvelope : [PROTOCOL_VERSION_META_KEY]; - return src_CX2iR2pK_rejection("envelope", "modern-header-without-claim", 400, new src_CX2iR2pK_ProtocolError(src_CX2iR2pK_ProtocolErrorCode.InvalidParams, `Invalid params: the MCP-Protocol-Version header names protocol revision ${headerVersion}, but the request is missing the required per-request envelope key(s): ${missing.join(", ")}`, { envelope: { missing } }), true); - } - return { - kind: "legacy", - reason: "no-claim", - ...headerVersion !== void 0 && { requestedVersion: headerVersion } - }; -} -function classifyNotificationBody(request, body) { - const params = body.params; - const method = body.method; - const headerVersion = request.protocolVersionHeader; - const headerNamesModern = headerVersion !== void 0 && isModernProtocolVersion(headerVersion); - if (src_CX2iR2pK_hasEnvelopeClaim(params)) { - const claimedVersion = src_CX2iR2pK_envelopeClaimVersion(params); - if (claimedVersion === void 0) { - const meta = src_CX2iR2pK_requestMetaOf(params); - const claimIssue = (meta === void 0 ? [] : src_CX2iR2pK_validateEnvelopeMeta(meta)).find((issue) => issue.key === PROTOCOL_VERSION_META_KEY) ?? { - key: PROTOCOL_VERSION_META_KEY, - problem: "expected a protocol version string" - }; - return src_CX2iR2pK_rejection("envelope", "notification-envelope-invalid", 400, new src_CX2iR2pK_ProtocolError(src_CX2iR2pK_ProtocolErrorCode.InvalidParams, `Invalid _meta envelope for protocol revision 2026-07-28: ${claimIssue.key}: ${claimIssue.problem}`, { envelope: claimIssue }), true); - } - if (headerVersion !== void 0 && headerVersion !== claimedVersion) return crossCheckMismatch("notification-header-body-version-mismatch", headerVersion, `the notification envelope names protocol version ${claimedVersion} but the MCP-Protocol-Version header names ${headerVersion}`); - const classification = classificationForClaim(claimedVersion); - if (classification.era === "modern" && request.mcpMethodHeader !== void 0 && request.mcpMethodHeader !== method) return crossCheckMismatch("notification-method-header-mismatch", request.mcpMethodHeader, `the notification body names method ${method} but the Mcp-Method header names ${request.mcpMethodHeader}`); - return { - kind: "modern", - messageKind: "notification", - message: body, - classification - }; - } - if (headerNamesModern) { - if (request.mcpMethodHeader !== void 0 && request.mcpMethodHeader !== method) return crossCheckMismatch("notification-method-header-mismatch", request.mcpMethodHeader, `the notification body names method ${method} but the Mcp-Method header names ${request.mcpMethodHeader}`); - return { - kind: "modern", - messageKind: "notification", - message: body, - classification: { - era: "modern", - revision: headerVersion - } - }; - } - return { - kind: "legacy", - reason: "notification", - ...headerVersion !== void 0 && { requestedVersion: headerVersion } - }; -} -/** -* Classifies one inbound HTTP request for dual-era serving. -* -* The body-primary predicate, evaluated once at the entry boundary: see the -* module documentation for the rules. Returns a routing outcome (`legacy` or -* `modern`) or a ladder rejection; it never throws. -*/ -function src_CX2iR2pK_classifyInboundRequest(request) { - request = { - ...request, - ...request.protocolVersionHeader !== void 0 && { protocolVersionHeader: stripHttpOws(request.protocolVersionHeader) }, - ...request.mcpMethodHeader !== void 0 && { mcpMethodHeader: stripHttpOws(request.mcpMethodHeader) }, - ...request.mcpNameHeader !== void 0 && { mcpNameHeader: stripHttpOws(request.mcpNameHeader) } - }; - if (request.httpMethod.toUpperCase() !== "POST") return { - kind: "legacy", - reason: "http-method" - }; - const body = request.body; - if (Array.isArray(body)) return classifyBatch(body); - if (src_CX2iR2pK_isJSONRPCResultResponse(body) || src_CX2iR2pK_isJSONRPCErrorResponse(body)) return { - kind: "legacy", - reason: "response" - }; - if (isPlainObject$2(body) && src_CX2iR2pK_isJSONRPCRequest(body)) return classifyRequestBody(request, body); - if (isPlainObject$2(body) && src_CX2iR2pK_isJSONRPCNotification(body)) return classifyNotificationBody(request, body); - return src_CX2iR2pK_rejection("jsonrpc-shape", "invalid-json-rpc-body", 400, new src_CX2iR2pK_ProtocolError(src_CX2iR2pK_ProtocolErrorCode.InvalidRequest, "Bad Request: the request body is not a valid JSON-RPC message"), true); -} -/** -* The rejection a modern-only endpoint (no legacy serving configured) -* answers a legacy-classified request with. -* -* - Envelope-less requests (including `initialize`) are answered with the -* unsupported-protocol-version error carrying the endpoint's supported -* versions and echoing the version the request named (when it named one — -* `requested` is omitted rather than fabricated when the request named no -* version at all), so a legacy client can discover what the endpoint serves -* from the error alone. -* - Posted responses and batch arrays are invalid requests on the modern era. -* - Non-`POST` methods are not allowed. -* - Legacy-classified notifications return `undefined`: the caller answers -* 202 with no body and does not dispatch the notification (accept-and-drop). -*/ -function src_CX2iR2pK_modernOnlyStrictRejection(route, supportedVersions) { - switch (route.reason) { - case "http-method": return src_CX2iR2pK_rejection("http-method", "modern-only-method-not-allowed", 405, new src_CX2iR2pK_ProtocolError(-32e3, "Method not allowed."), true); - case "batch": return src_CX2iR2pK_rejection("jsonrpc-shape", "modern-only-batch-not-supported", 400, new src_CX2iR2pK_ProtocolError(src_CX2iR2pK_ProtocolErrorCode.InvalidRequest, "Bad Request: JSON-RPC batches are not supported by this endpoint"), true); - case "response": return src_CX2iR2pK_rejection("jsonrpc-shape", "modern-only-response-post", 400, new src_CX2iR2pK_ProtocolError(src_CX2iR2pK_ProtocolErrorCode.InvalidRequest, "Bad Request: JSON-RPC responses cannot be posted to this endpoint"), true); - case "notification": return; - case "initialize": - case "no-claim": { - const requested = route.requestedVersion; - return src_CX2iR2pK_rejection("era-classification", "modern-only-missing-envelope", 400, requested === void 0 ? new src_CX2iR2pK_ProtocolError(src_CX2iR2pK_ProtocolErrorCode.UnsupportedProtocolVersion, "Unsupported protocol version: the request did not name a protocol version", { supported: [...supportedVersions] }) : new src_CX2iR2pK_UnsupportedProtocolVersionError({ - supported: [...supportedVersions], - requested - }), true); - } - } -} - -//#endregion -//#region ../core-internal/src/util/schema.ts -/** -* Internal Zod schema utilities for protocol handling. -* These are used internally by the SDK for protocol message validation. -*/ -/** -* Parses data against a Zod schema (synchronous). -* Returns a discriminated union with success/error. -*/ -function parseSchema(schema, data) { - return parse_safeParse(schema, data); -} -/** -* Union of the declared shape keys across several Zod object schemas. -*/ -function shapeKeys(schemas) { - return new Set(schemas.flatMap((schema) => Object.keys(schema.shape))); -} - -//#endregion -//#region ../core-internal/src/util/standardSchema.ts -/** -* Standard Schema utilities for user-provided schemas. -* Supports Zod v4, Valibot, ArkType, and other Standard Schema implementations. -* @see https://standardschema.dev -*/ -function isStandardSchema(schema) { - if (schema == null) return false; - const schemaType = typeof schema; - if (schemaType !== "object" && schemaType !== "function") return false; - if (!("~standard" in schema)) return false; - return typeof schema["~standard"]?.validate === "function"; -} -let warnedZodFallback = false; -/** JSON Schema draft targeted by every conversion; shared so pattern references above stay in lockstep. */ -const JSON_SCHEMA_CONVERSION_TARGET = "draft-2020-12"; -/** -* Converts a StandardSchema to JSON Schema for use as an MCP tool/prompt schema. -* -* MCP requires `type: "object"` at the root of tool `inputSchema` and prompt -* argument schemas; `outputSchema` may have any JSON Schema root (SEP-2106). -* Zod's discriminated unions emit `{oneOf: [...]}` without a top-level `type`, -* so for `io: 'input'` this function defaults `type` to `"object"` when absent -* and throws on an explicit non-object `type` (e.g. `z.string()`). For -* `io: 'output'` a non-object root is returned as-is; the `"object"` default is -* applied only when the root is provably object-shaped. -*/ -function standardSchemaToJsonSchema(schema, io = "input") { - const std = schema["~standard"]; - let result; - if (std.jsonSchema) result = std.jsonSchema[io]({ target: JSON_SCHEMA_CONVERSION_TARGET }); - else if (std.vendor === "zod") { - if (!("_zod" in schema)) 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()."); - if (!warnedZodFallback) { - warnedZodFallback = true; - 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."); - } - result = toJSONSchema(schema, { - target: JSON_SCHEMA_CONVERSION_TARGET, - io - }); - } else throw new Error(`Schema library "${std.vendor}" does not implement StandardJSONSchemaV1 (\`~standard.jsonSchema\`). Upgrade to a version that does, or wrap your JSON Schema with fromJsonSchema().`); - if (io === "output") { - if (result.type !== void 0) return result; - return isProvablyObjectShapedRoot(result) ? { - type: "object", - ...result - } : result; - } - if (result.type !== void 0 && result.type !== "object") throw new Error(`MCP tool and prompt schemas must describe objects (got type: ${JSON.stringify(result.type)}). Wrap your schema in z.object({...}) or equivalent.`); - return { - type: "object", - ...result - }; -} -/** -* A typeless JSON Schema root is "provably object-shaped" when either it carries object keywords -* directly (`properties`/`patternProperties`/`additionalProperties`/`required`), or it is a -* composition (`oneOf`/`anyOf`/`allOf`) whose every member is itself `type:'object'` or recursively -* provably object-shaped (e.g. a nested `discriminatedUnion`). `$ref` is not followed. Used to -* decide whether stamping `type:'object'` is safe (redundant-but-valid) versus self-contradictory. -*/ -function isProvablyObjectShapedRoot(schema) { - if ("properties" in schema || "patternProperties" in schema || "additionalProperties" in schema || "required" in schema) return true; - for (const key of [ - "oneOf", - "anyOf", - "allOf" - ]) { - const members = schema[key]; - if (Array.isArray(members) && members.length > 0) return members.every((m) => m !== null && typeof m === "object" && (m.type === "object" || isProvablyObjectShapedRoot(m))); - } - return false; -} -function formatIssue(issue) { - if (!issue.path?.length) return issue.message; - return `${issue.path.map((p) => String(typeof p === "object" ? p.key : p)).join(".")}: ${issue.message}`; -} -async function validateStandardSchema(schema, data) { - const result = await schema["~standard"].validate(data); - if (result.issues && result.issues.length > 0) return { - success: false, - error: result.issues.map((i) => formatIssue(i)).join(", ") - }; - return { - success: true, - data: result.value - }; -} -function zodEmittedPattern(schema) { - const jsonSchema = toJSONSchema(schema, { - target: JSON_SCHEMA_CONVERSION_TARGET, - io: "input" - }); - return typeof jsonSchema.pattern === "string" ? jsonSchema.pattern : void 0; -} -const DATETIME_FRACTION_DIGITS = /\\\.\\d\{(\d+)\}/; -function datetimeReferenceSchemas(pattern) { - const fractionDigits = DATETIME_FRACTION_DIGITS.exec(pattern); - const precisions = [ - void 0, - -1, - 0 - ]; - if (fractionDigits) precisions.push(Number(fractionDigits[1])); - return [false, true].flatMap((local) => [false, true].flatMap((offset) => precisions.map((precision) => iso_datetime({ - local, - offset, - precision - })))); -} -function referencePatternsForFormat(format, pattern) { - let referenceSchemas; - switch (format) { - case "email": - referenceSchemas = [schemas_email()]; - break; - case "uri": - referenceSchemas = [schemas_url()]; - break; - case "date": - referenceSchemas = [iso_date()]; - break; - case "date-time": - referenceSchemas = datetimeReferenceSchemas(pattern); - break; - } - return new Set(referenceSchemas.map((schema) => zodEmittedPattern(schema)).filter((emitted) => emitted !== void 0)); -} -/** Whether `pattern` is the library's own realization of `format` (droppable) rather than a user customization. */ -function isLibraryFormatPattern(format, pattern, vendor) { - if (vendor !== "zod") return true; - return referencePatternsForFormat(format, pattern).has(pattern); -} -function promptArgumentsFromStandardSchema(schema) { - const jsonSchema = standardSchemaToJsonSchema(schema, "input"); - const properties = jsonSchema.properties || {}; - const required = jsonSchema.required || []; - return Object.entries(properties).map(([name, prop]) => ({ - name, - description: prop?.description, - required: required.includes(name) - })); -} - -//#endregion -//#region ../core-internal/src/shared/elicitation.ts -function isJsonObject(value) { - return typeof value === "object" && value !== null && !Array.isArray(value); -} -function convertStandardElicitationSchema(schema) { - try { - return standardSchemaToJsonSchema(schema, "input"); - } catch (error) { - const detail = error instanceof Error ? error.message : String(error); - throw new src_CX2iR2pK_ProtocolError(src_CX2iR2pK_ProtocolErrorCode.InvalidParams, `Elicitation requestedSchema must describe an object with flat primitive properties: ${detail}`); - } -} -const ANNOTATION_ONLY_JSON_SCHEMA_KEYWORDS = new Set([ - "$comment", - "deprecated", - "description", - "examples", - "readOnly", - "title", - "writeOnly" -]); -function isAnnotationOnlyJsonSchemaKeyword(key) { - return ANNOTATION_ONLY_JSON_SCHEMA_KEYWORDS.has(key) || key.startsWith("x-"); -} -const ROOT_KEYS = new Set(["$schema", ...Object.keys(ElicitRequestFormParamsSchema.shape.requestedSchema.shape)]); -const PROPERTY_KEYS_BY_TYPE = { - string: shapeKeys([ - StringSchemaSchema, - UntitledSingleSelectEnumSchemaSchema, - TitledSingleSelectEnumSchemaSchema, - LegacyTitledEnumSchemaSchema - ]), - number: shapeKeys([NumberSchemaSchema]), - integer: shapeKeys([NumberSchemaSchema]), - boolean: shapeKeys([BooleanSchemaSchema]), - array: shapeKeys([UntitledMultiSelectEnumSchemaSchema, TitledMultiSelectEnumSchemaSchema]) -}; -const SUPPORTED_STRING_FORMATS = new Set(StringSchemaSchema.shape.format.unwrap().options); -/** Walks one property node: keeps grammar keys, drops the library format pattern, rejects unknown constraints. */ -function walkProperty(node, path, vendor, unsupported) { - if (!isJsonObject(node)) return node; - const allowedKeys = typeof node.type === "string" && Object.hasOwn(PROPERTY_KEYS_BY_TYPE, node.type) ? PROPERTY_KEYS_BY_TYPE[node.type] : void 0; - if (allowedKeys === void 0) return node; - const pruned = {}; - for (const [key, value] of Object.entries(node)) if (allowedKeys.has(key) || isAnnotationOnlyJsonSchemaKeyword(key)) pruned[key] = value; - else if (key === "pattern" && node.type === "string" && typeof node.format === "string") { - if (!SUPPORTED_STRING_FORMATS.has(node.format)) pruned[key] = value; - else if (typeof value !== "string" || !isLibraryFormatPattern(node.format, value, vendor)) unsupported.push(`${path}.${key}`); - } else unsupported.push(`${path}.${key}`); - return pruned; -} -/** Walks the schema root: keeps the spec root keys, drops annotations, rejects the rest. */ -function walkRequestedSchema(converted, vendor) { - const pruned = {}; - const unsupported = []; - for (const [key, value] of Object.entries(converted)) if (key === "properties" && isJsonObject(value)) pruned[key] = Object.fromEntries(Object.entries(value).map(([name, node]) => [name, walkProperty(node, `properties.${name}`, vendor, unsupported)])); - else if (ROOT_KEYS.has(key)) pruned[key] = value; - else if (!isAnnotationOnlyJsonSchemaKeyword(key)) unsupported.push(key); - if (unsupported.length > 0) throw new src_CX2iR2pK_ProtocolError(src_CX2iR2pK_ProtocolErrorCode.InvalidParams, `Elicitation requestedSchema contains unsupported JSON Schema constraint(s) after Standard Schema conversion: ${unsupported.join(", ")}`); - return pruned; -} -/** Names the properties that fail value validation, instead of surfacing a raw union dump. */ -function describeUnsupportedProperties(pruned, fallback) { - if (!isJsonObject(pruned.properties)) return fallback; - const offenders = Object.entries(pruned.properties).filter(([, node]) => !parseSchema(PrimitiveSchemaDefinitionSchema, node).success).map(([name]) => `properties.${name}`); - return offenders.length > 0 ? offenders.join(", ") : fallback; -} -function findDroppedConstraintPaths(original, parsed, path = "") { - if (Array.isArray(original) && Array.isArray(parsed)) return original.flatMap((item, index) => findDroppedConstraintPaths(item, parsed[index], `${path}[${index}]`)); - if (!isJsonObject(original) || !isJsonObject(parsed)) return []; - return Object.entries(original).flatMap(([key, value]) => { - const childPath = path ? `${path}.${key}` : key; - if (!Object.prototype.hasOwnProperty.call(parsed, key)) return isAnnotationOnlyJsonSchemaKeyword(key) ? [] : [childPath]; - return findDroppedConstraintPaths(value, parsed[key], childPath); - }); -} -/** Converts an authoring-friendly elicitation input into its wire-ready form. */ -function normalizeElicitInputParams(input) { - if (!isStandardSchema(input.requestedSchema)) return { - ...input, - mode: "form", - requestedSchema: input.requestedSchema - }; - const vendor = input.requestedSchema["~standard"].vendor; - const pruned = walkRequestedSchema(convertStandardElicitationSchema(input.requestedSchema), vendor); - const parsed = parseSchema(ElicitRequestFormParamsSchema.shape.requestedSchema, pruned); - if (!parsed.success) throw new src_CX2iR2pK_ProtocolError(src_CX2iR2pK_ProtocolErrorCode.InvalidParams, `Elicitation requestedSchema only supports flat primitive properties (string, number, integer, boolean, and string enums): ${describeUnsupportedProperties(pruned, parsed.error.message)}`); - const droppedConstraints = findDroppedConstraintPaths(pruned, parsed.data); - if (droppedConstraints.length > 0) throw new src_CX2iR2pK_ProtocolError(src_CX2iR2pK_ProtocolErrorCode.InvalidParams, `Elicitation requestedSchema contains unsupported JSON Schema constraint(s) after Standard Schema conversion: ${droppedConstraints.join(", ")}`); - const danglingRequired = (parsed.data.required ?? []).filter((key) => !Object.prototype.hasOwnProperty.call(parsed.data.properties, key)); - if (danglingRequired.length > 0) throw new src_CX2iR2pK_ProtocolError(src_CX2iR2pK_ProtocolErrorCode.InvalidParams, `Elicitation requestedSchema lists required properties that are not defined in properties: ${danglingRequired.join(", ")}`); - return { - ...input, - mode: "form", - requestedSchema: parsed.data - }; -} - -//#endregion -//#region ../core-internal/src/shared/inputRequired.ts -/** -* Authoring helpers for multi-round-trip requests (protocol revision -* 2026-07-28). -* -* A handler for one of the multi-round-trip methods (`tools/call`, -* `prompts/get`, `resources/read`) requests additional client input by -* returning an {@linkcode InputRequiredResult} instead of a final result. The -* helpers here build that return value and its embedded requests as NEUTRAL -* values; only the 2026-07-28 wire codec maps them to/from the wire. The -* 2025-era codec has no input-required vocabulary — on a 2025-era request the -* server's legacy shim (on by default) fulfils the embedded requests as real -* server→client requests and re-enters the handler, so the same return shape -* serves both eras; `ServerOptions.inputRequired.legacyShim: false` restores -* the pre-shim loud failure. -* -* There is no nominal brand: `resultType: 'input_required'` is the -* discriminator, and hand-built result literals are equally legal — the -* server seam re-checks the at-least-one rule for them. -*/ -function buildInputRequired(spec) { - const hasInputRequests = spec.inputRequests !== void 0 && Object.keys(spec.inputRequests).length > 0; - const hasRequestState = typeof spec.requestState === "string"; - if (!hasInputRequests && !hasRequestState) 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", - ...spec.inputRequests !== void 0 && { inputRequests: spec.inputRequests }, - ...spec.requestState !== void 0 && { requestState: spec.requestState } - }; -} -/** -* Builder for the input-required return value of multi-round-trip handlers, -* with per-kind constructors for the embedded requests -* (`inputRequired.elicit`, `inputRequired.elicitUrl`, -* `inputRequired.createMessage`, `inputRequired.listRoots`). -* -* @example Write-once tool requesting confirmation -* ```ts -* server.registerTool('deploy', { inputSchema: z.object({ env: z.string() }) }, async ({ env }, ctx) => { -* const confirmed = acceptedContent<{ confirm: boolean }>(ctx.mcpReq.inputResponses, 'confirm'); -* if (!confirmed) { -* return inputRequired({ -* inputRequests: { -* confirm: inputRequired.elicit({ -* message: `Deploy to ${env}?`, -* requestedSchema: { type: 'object', properties: { confirm: { type: 'boolean' } }, required: ['confirm'] } -* }) -* } -* }); -* } -* return { content: [{ type: 'text', text: `deployed to ${env}` }] }; -* }); -* ``` -*/ -const inputRequired = Object.assign(buildInputRequired, { - elicit(params) { - try { - return { - method: "elicitation/create", - params: normalizeElicitInputParams(params) - }; - } catch (error) { - throw error instanceof src_CX2iR2pK_ProtocolError ? new TypeError(error.message, { cause: error }) : error; - } - }, - elicitUrl(params) { - return { - method: "elicitation/create", - params: { - ...params, - mode: "url" - } - }; - }, - createMessage(params) { - return { - method: "sampling/createMessage", - params - }; - }, - listRoots() { - return { method: "roots/list" }; - } -}); -function acceptedContent(responses, key, schema) { - const view = inputResponse(responses, key); - if (view.kind !== "elicit" || view.action !== "accept" || view.content === void 0) return void 0; - if (schema === void 0) return view.content; - const outcome = schema["~standard"].validate(view.content); - if (outcome instanceof Promise) throw new TypeError("acceptedContent(responses, key, schema) requires a synchronously-validating schema"); - return outcome.issues === void 0 ? outcome.value : void 0; -} -/** -* Reads one entry of a retried request's `inputResponses` -* (`ctx.mcpReq.inputResponses`) as a discriminated view, covering -* decline/cancel detection and the non-elicitation response kinds that -* {@linkcode acceptedContent} does not surface. -* -* The values arrive from the client and are not re-validated here — treat -* them as untrusted input (validate elicitation content with the -* schema-aware {@linkcode acceptedContent} overload where it matters). -*/ -function inputResponse(responses, key) { - if (responses === void 0 || typeof responses !== "object" || responses === null) return { kind: "missing" }; - const entry = responses[key]; - if (entry === null || typeof entry !== "object" || Array.isArray(entry)) return { kind: "missing" }; - const candidate = entry; - if (candidate["action"] === "accept" || candidate["action"] === "decline" || candidate["action"] === "cancel") { - const content = candidate["content"]; - return { - kind: "elicit", - action: candidate["action"], - ...content !== null && typeof content === "object" && !Array.isArray(content) && { content } - }; - } - if (Array.isArray(candidate["roots"])) return { - kind: "roots", - roots: candidate["roots"] - }; - if (typeof candidate["role"] === "string" && candidate["content"] !== void 0) return { - kind: "sampling", - result: candidate - }; - return { kind: "missing" }; -} - -//#endregion -//#region ../core-internal/src/shared/inputRequiredDriver.ts -/** -* The multi-round-trip auto-fulfilment driver (protocol revision 2026-07-28). -* -* When a request to one of the multi-round-trip methods comes back as -* `input_required`, the driver fulfils the embedded input requests by -* dispatching them to the client's already-registered handlers (elicitation, -* sampling, roots — one generic engine, no per-feature API), then retries the -* original request with the collected `inputResponses` and a byte-exact echo -* of `requestState`, on a fresh request id, until the server returns a -* complete result or the round cap is exhausted. -* -* The driver is a LAYER OVER THE MANUAL PATH: each retry is issued with the -* same primitive a manual caller uses (`allowInputRequired` semantics — the -* retry hands back the next `input_required` payload instead of recursing), -* so the loop, the cap, and the pacing live in one place and disabling -* auto-fulfilment (`inputRequired.autoFulfill: false`) simply skips this -* module. Timeouts ride the EXISTING knobs: the per-leg `timeout` applies to -* every wire leg unchanged, and `maxTotalTimeout` bounds the whole flow by -* shrinking the budget passed to each leg — no new timer system. -*/ -/** -* Fixed pacing applied before retrying a requestState-only (load-shedding) -* leg — a leg that carries no embedded input requests, so nothing slows the -* loop down naturally. Counted in the same round cap. -*/ -const REQUEST_STATE_ONLY_LEG_PACING_MS = 250; -/** -* The message both multi-round-trip loops emit when the round cap is -* exhausted — the client driver as a typed error, the server-side legacy -* shim as its per-family failure. One formatter so the texts cannot drift -* (hosts and models read the tool-result copy verbatim). -*/ -function inputRequiredRoundsExceededMessage(method, maxRounds) { - return `Multi-round-trip request '${method}' still required input after ${maxRounds} rounds (inputRequired.maxRounds)`; -} -/** -* Abortable delay: resolves after `ms`, or rejects with the signal's reason -* (wrapped in an `SdkError` when it isn't already one) if the signal aborts -* first. Aborting after resolution is a no-op. Shared with the server-side -* legacy shim (the pacing semantics must match per era). -*/ -function sleep(ms, signal) { - return new Promise((resolve, reject) => { - if (signal?.aborted) { - reject(signal.reason instanceof src_CX2iR2pK_SdkError ? signal.reason : new src_CX2iR2pK_SdkError(src_CX2iR2pK_SdkErrorCode.RequestTimeout, String(signal.reason))); - return; - } - const timer = setTimeout(() => { - signal?.removeEventListener("abort", onAbort); - resolve(); - }, ms); - const onAbort = () => { - clearTimeout(timer); - reject(signal?.reason instanceof src_CX2iR2pK_SdkError ? signal.reason : new src_CX2iR2pK_SdkError(src_CX2iR2pK_SdkErrorCode.RequestTimeout, String(signal?.reason))); - }; - signal?.addEventListener("abort", onAbort, { once: true }); - }); -} -/** -* A per-round abort linked to the caller's signal: the embedded sibling -* dispatches share it, so the first failure (or a caller abort) cancels the -* others instead of leaving them running. Shared with the server-side legacy -* shim (the abort-linkage semantics must match per era). -*/ -function linkedRoundAbort(outer) { - const controller = new AbortController(); - const onOuterAbort = () => controller.abort(outer?.reason); - outer?.addEventListener("abort", onOuterAbort, { once: true }); - if (outer?.aborted) controller.abort(outer.reason); - return { - signal: controller.signal, - abort: (reason) => controller.abort(reason), - dispose: () => outer?.removeEventListener("abort", onOuterAbort) - }; -} - -//#endregion -//#region ../core-internal/src/types/specTypeSchema.ts -/** -* Explicit allowlist of protocol Zod schemas that correspond to a public spec type in `types.ts`. -* -* This intentionally excludes internal helper schemas exported from `schemas.ts` that have no -* matching public type (e.g. `ListChangedOptionsBaseSchema`, `BaseRequestParamsSchema`, -* `NotificationsParamsSchema`, `ClientTasksCapabilitySchema`, `ServerTasksCapabilitySchema`). -* Keeping the list explicit means new public spec types must be added here deliberately, and -* internals never leak into `SpecTypeName`. -* -* `ResourceTemplateSchema` is included; its public type is exported as `ResourceTemplateType` -* (the bare name collides with the server package's `ResourceTemplate` class), so -* `SpecTypes['ResourceTemplate']` is structurally equal to `ResourceTemplateType` rather than to -* a type literally named `ResourceTemplate`. -*/ -const SPEC_SCHEMA_KEYS = [ - "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" -]; -const authSchemas = { - IdJagTokenExchangeResponseSchema: IdJagTokenExchangeResponseSchema, - OAuthClientInformationFullSchema: OAuthClientInformationFullSchema, - OAuthClientInformationSchema: OAuthClientInformationSchema, - OAuthClientMetadataSchema: OAuthClientMetadataSchema, - OAuthClientRegistrationErrorSchema: OAuthClientRegistrationErrorSchema, - OAuthErrorResponseSchema: OAuthErrorResponseSchema, - OAuthMetadataSchema: OAuthMetadataSchema, - OAuthProtectedResourceMetadataSchema: OAuthProtectedResourceMetadataSchema, - OAuthTokenRevocationRequestSchema: OAuthTokenRevocationRequestSchema, - OAuthTokensSchema: OAuthTokensSchema, - OpenIdProviderDiscoveryMetadataSchema: OpenIdProviderDiscoveryMetadataSchema, - OpenIdProviderMetadataSchema: OpenIdProviderMetadataSchema -}; -const _specTypeSchemas = {}; -const _isSpecType = {}; -function register(key, schema) { - const name = key.slice(0, -6); - _specTypeSchemas[name] = schema; - _isSpecType[name] = (v) => schema.safeParse(v).success; -} -for (const key of SPEC_SCHEMA_KEYS) register(key, schemas_exports[key]); -for (const [key, schema] of Object.entries(authSchemas)) register(key, schema); -/** -* Runtime validators for every MCP spec type, keyed by type name. -* -* Use this when you need to validate a spec-defined shape at a boundary the SDK does not own, for -* example an extension's custom-method payload that embeds a `CallToolResult`, or a value read from -* storage that should be a `Tool`. -* -* Each entry implements the Standard Schema interface, so it composes with any -* Standard-Schema-aware library. For a simple boolean check, use {@linkcode isSpecType} instead. -* -* @example -* ```ts source="./specTypeSchema.examples.ts#specTypeSchemas_basicUsage" -* const result = specTypeSchemas.CallToolResult['~standard'].validate(untrusted); -* if (result.issues === undefined) { -* // result.value is CallToolResult -* } -* ``` -*/ -const specTypeSchemas = Object.freeze(_specTypeSchemas); -/** -* Type predicates for every MCP spec type, keyed by type name. -* -* Returns `true` if the value satisfies the schema's input type (`z.input<>`, before defaults and -* transforms are applied), and narrows to that input type. For schemas with `.default()` or -* `.preprocess()`, this may accept values that do not structurally match the named output type; -* for example `isSpecType.CallToolResult({})` is `true` because `content` has a default. Use -* `specTypeSchemas.X['~standard'].validate(value)` when you need the validated output value. -* -* Each guard is a standalone function, so it can be passed directly as a callback. -* -* @example -* ```ts source="./specTypeSchema.examples.ts#isSpecType_basicUsage" -* if (isSpecType.ContentBlock(value)) { -* // value is ContentBlock -* } -* -* const blocks = mixed.filter(isSpecType.ContentBlock); -* ``` -*/ -const isSpecType = Object.freeze(_isSpecType); - -//#endregion -//#region ../core-internal/src/wire/bootstrap.ts -function bootstrapOutboundCodec(method) { - switch (method) { - case "initialize": - case "notifications/initialized": return src_CX2iR2pK_codecForVersion(void 0); - case "server/discover": return src_CX2iR2pK_codecForVersion(src_CX2iR2pK_MODERN_WIRE_REVISION); - default: return; - } -} - -//#endregion -//#region ../core-internal/src/shared/protocol.ts -/** -* The default request timeout, in milliseconds. -*/ -const DEFAULT_REQUEST_TIMEOUT_MSEC = 6e4; -/** -* The reserved per-request `_meta` envelope keys (protocol revision -* 2026-07-28). The protocol layer lifts these out of inbound `_meta` before -* handlers run and surfaces them at `ctx.mcpReq.envelope` — they are -* wire-level bookkeeping, not handler material. -*/ -const RESERVED_ENVELOPE_META_KEYS = [ - auth_CUe6YdwF_PROTOCOL_VERSION_META_KEY, - auth_CUe6YdwF_CLIENT_INFO_META_KEY, - auth_CUe6YdwF_CLIENT_CAPABILITIES_META_KEY, - LOG_LEVEL_META_KEY -]; -/** -* Top-level params members carrying multi-round-trip driver material -* (protocol revision 2026-07-28). The spec reserves these names on -* client-initiated REQUESTS only — notification params keep them untouched -* (a vendor notification may legitimately use the same names). -*/ -const RETRY_PARAMS_KEYS = ["inputResponses", "requestState"]; -/** -* Lift wire-only material out of an inbound message so handlers see exactly -* the 2025-era shape, and surface it for the protocol layer (requests: via -* `ctx.mcpReq`). What counts as wire-only depends on the message kind: the -* reserved envelope `_meta` keys are reserved on every message, while the -* multi-round-trip retry fields (`inputResponses`/`requestState`) are -* reserved on client-initiated requests only — so notifications get only the -* envelope lift, and their top-level params stay untouched. Messages without -* wire-only material are returned unchanged (same reference). -*/ -function liftWireOnlyMaterial(message, kind) { - const params = message.params; - if (!isPlainObject$1(params)) return { - message, - lifted: {} - }; - const meta = params._meta; - const envelopeKeys = isPlainObject$1(meta) ? RESERVED_ENVELOPE_META_KEYS.filter((key) => key in meta) : []; - const retryKeys = kind === "request" ? RETRY_PARAMS_KEYS.filter((key) => key in params) : []; - if (envelopeKeys.length === 0 && retryKeys.length === 0) return { - message, - lifted: {} - }; - const lifted = {}; - const nextParams = { ...params }; - if (envelopeKeys.length > 0 && isPlainObject$1(meta)) { - const envelope = {}; - const nextMeta = { ...meta }; - for (const key of envelopeKeys) { - envelope[key] = meta[key]; - delete nextMeta[key]; - } - lifted.envelope = envelope; - if (Object.keys(nextMeta).length > 0) nextParams._meta = nextMeta; - else delete nextParams._meta; - } - for (const key of retryKeys) { - if (key === "inputResponses") lifted.inputResponses = nextParams[key]; - if (key === "requestState") lifted.requestState = nextParams[key]; - delete nextParams[key]; - } - return { - message: { - ...message, - params: nextParams - }, - lifted - }; -} -/** -* Standard Schema adapter over the era codec's `validateResult` function (the -* function-only WireCodec contract exposes no schema objects). Used by the -* spec-method `request()` overload so the request funnel keeps a single -* `StandardSchemaV1`-shaped validation seam for both spec and explicit-schema -* paths. -* -* Returns `undefined` when the method has no result entry on this era's -* registry — the caller maps that to the synchronous "pass a result schema" -* TypeError, exactly matching the pre-function-only behavior the -* typedMapAlignment suite pins (the result map deliberately excludes the -* `tasks/*` methods, so the spec-method overload refuses them up front). -*/ -function codecResultValidator(codec, method) { - const probe = codec.validateResult(method, void 0); - if (!probe.ok && probe.reason === "not-in-era") return void 0; - return { "~standard": { - version: 1, - vendor: "mcp-wire-codec", - validate(value) { - const outcome = codec.validateResult(method, value); - if (outcome.ok) return { value: outcome.value }; - return { issues: [{ message: outcome.reason === "invalid" ? outcome.message : `not-in-era: ${method}` }] }; - } - } }; -} -/** -* Builds the `ctx.mcpReq.requestState` accessor for a resolved value. The -* `as T` below is the one place {@linkcode RequestStateAccessor}'s -* caller-asserted typing is implemented — no implementation can produce an -* arbitrary `T` from a runtime value honestly. -*/ -function requestStateAccessor(value) { - return () => value; -} -/** Shared no-state accessor: the common case allocates nothing per request. */ -const NO_REQUEST_STATE = requestStateAccessor(void 0); -/** -* Returns a context whose `requestState` accessor reads the given value — -* how the server seam hands a verify hook's decoded payload (or the legacy -* shim's per-round echo) to the handler without mutating the original -* context. -*/ -function withRequestStateValue(ctx, value) { - return { - ...ctx, - mcpReq: { - ...ctx.mcpReq, - requestState: requestStateAccessor(value) - } - }; -} -let writeNegotiatedProtocolVersion; -/** -* Package-internal write channel for a {@linkcode Protocol} instance's -* negotiated protocol version, for callers outside the class hierarchy: -* tests and the (future) modern-era server entry that marks a factory -* instance modern at binding time. Exported on the core internal barrel -* only — never public API. -*/ -function src_CX2iR2pK_setNegotiatedProtocolVersion(instance, version) { - writeNegotiatedProtocolVersion(instance, version); -} -/** -* Implements MCP protocol framing on top of a pluggable transport, including -* features like request/response linking, notifications, and progress. -* -* `Protocol` is abstract; `Client` and `Server` are the concrete role-specific -* implementations most code should use. -*/ -var Protocol = class { - _transport; - _requestMessageId = 0; - _requestHandlers = /* @__PURE__ */ new Map(); - _requestHandlerAbortControllers = /* @__PURE__ */ new Map(); - _notificationHandlers = /* @__PURE__ */ new Map(); - _responseHandlers = /* @__PURE__ */ new Map(); - _progressHandlers = /* @__PURE__ */ new Map(); - _timeoutInfo = /* @__PURE__ */ new Map(); - _pendingDebouncedNotifications = /* @__PURE__ */ new Set(); - /** - * The protocol version negotiated for the current connection (`undefined` - * before negotiation completes), which determines the wire era this - * instance speaks. Set by the SDK's negotiation and initialize paths - * (`Client.connect`, `Server._oninitialize`). - */ - _negotiatedProtocolVersion; - static { - writeNegotiatedProtocolVersion = (instance, version) => { - instance._negotiatedProtocolVersion = version; - }; - } - _supportedProtocolVersions; - /** - * Callback for when the connection is closed for any reason. - * - * This is invoked when {@linkcode Protocol.close | close()} is called as well. - */ - onclose; - /** - * Callback for when an error occurs. - * - * Note that errors are not necessarily fatal; they are used for reporting any kind of exceptional condition out of band. - */ - onerror; - /** - * A handler to invoke for any request types that do not have their own handler installed. - */ - fallbackRequestHandler; - /** - * A handler to invoke for any notification types that do not have their own handler installed. - */ - fallbackNotificationHandler; - constructor(_options) { - this._options = _options; - this._supportedProtocolVersions = _options?.supportedProtocolVersions ?? auth_CUe6YdwF_SUPPORTED_PROTOCOL_VERSIONS; - this.setNotificationHandler("notifications/cancelled", (notification) => { - this._oncancel(notification); - }); - this.setNotificationHandler("notifications/progress", (notification) => { - this._onprogress(notification); - }); - this.setRequestHandler("ping", (_request) => ({})); - } - /** - * Drop consult for inbound messages whose transport did not classify them - * at the edge — long-lived channels such as stdio, where a role class may - * need to decline traffic the negotiated era has no answer for (the - * client-side inbound-request drop on modern-era connections: the - * 2026-07-28 era has no server→client request channel, and on stdio the - * client must never write JSON-RPC responses). - * - * Consulted ONLY when the transport supplied no - * {@linkcode MessageExtraInfo.classification}: edge-classified traffic - * never reaches the hook. Returning `'drop'` discards the message without - * writing any response (requests are surfaced via `onerror`). The base - * implementation returns `undefined`: unclassified traffic keeps today's - * dispatch path unchanged. Era selection never happens here — era is - * instance state, owned by the serving entry that constructed and - * connected the instance. - */ - _shouldDropInbound(_message) {} - /** - * The per-request `_meta` envelope this instance attaches to every outgoing - * request and notification, when one applies. The base implementation - * returns `undefined` (no envelope — the 2025-era posture, so legacy-era - * outbound traffic is byte-identical to a build without this seam). - * `Client` overrides it on a connection that negotiated a modern (2026-07-28+) - * era to return the reserved protocol-version / client-info / - * client-capabilities keys. User-supplied `_meta` keys take precedence over - * the auto-attached ones. - */ - _outboundMetaEnvelope() {} - /** - * Attach this instance's outbound `_meta` envelope (when one is configured) - * to a request or notification. A no-op when the seam returns `undefined` - * — the message returns by reference, so the legacy-era wire stays - * byte-identical. User-supplied `_meta` keys are spread last so they win - * over the auto-attached envelope keys. - */ - _envelopeOutbound(message) { - const envelope = this._outboundMetaEnvelope(); - if (envelope === void 0) return message; - const params = message.params ?? {}; - return { - ...message, - params: { - ...params, - _meta: { - ...envelope, - ...params._meta - } - } - }; - } - /** - * Extension point for non-`complete` decoded results in the response - * funnel: a result the wire codec discriminated into a kind other than - * `'complete'` or `'invalid'` is handed here for the role class to - * resolve. The base default surfaces it as a typed - * {@linkcode SdkErrorCode.UnsupportedResultType} error (no retry). - * - * Intended consumers (named so the seam stays accountable): - * - the `Client`'s multi-round-trip auto-fulfilment engine, which fulfils - * `'input_required'` results through the registered - * elicitation/sampling/roots handlers and retries via `flow.retry`; - * - a future client-side terminal-result handler for - * `subscriptions/listen`, when the spec defines one. - * - * `Server` instances never receive `input_required` responses on their - * outbound legs and leave the base behavior in place. - */ - _resolveNonCompleteResult(decoded, flow) { - return Promise.reject(new src_CX2iR2pK_SdkError(src_CX2iR2pK_SdkErrorCode.UnsupportedResultType, `Unsupported result type '${decoded.kind}' for ${flow.request.method}`, { - resultType: decoded.kind, - method: flow.request.method - })); - } - /** - * Protected accessor for a registered request handler. Used by role - * classes that dispatch synthesized requests through the same stored - * handler chain (e.g. the `Client` fulfilling an embedded multi-round-trip - * input request). - */ - _getRequestHandler(method) { - return this._requestHandlers.get(method); - } - async _oncancel(notification) { - if (!notification.params.requestId) return; - this._requestHandlerAbortControllers.get(notification.params.requestId)?.abort(notification.params.reason); - } - _setupTimeout(messageId, timeout, maxTotalTimeout, onTimeout, resetTimeoutOnProgress = false) { - this._timeoutInfo.set(messageId, { - timeoutId: setTimeout(onTimeout, timeout), - startTime: Date.now(), - timeout, - maxTotalTimeout, - resetTimeoutOnProgress, - onTimeout - }); - } - _resetTimeout(messageId) { - const info = this._timeoutInfo.get(messageId); - if (!info) return false; - const totalElapsed = Date.now() - info.startTime; - if (info.maxTotalTimeout && totalElapsed >= info.maxTotalTimeout) { - this._timeoutInfo.delete(messageId); - throw new src_CX2iR2pK_SdkError(src_CX2iR2pK_SdkErrorCode.RequestTimeout, "Maximum total timeout exceeded", { - maxTotalTimeout: info.maxTotalTimeout, - totalElapsed - }); - } - clearTimeout(info.timeoutId); - info.timeoutId = setTimeout(info.onTimeout, info.timeout); - return true; - } - _cleanupTimeout(messageId) { - const info = this._timeoutInfo.get(messageId); - if (info) { - clearTimeout(info.timeoutId); - this._timeoutInfo.delete(messageId); - } - } - /** - * Attaches to the given transport, starts it, and starts listening for messages. - * - * The caller assumes ownership of the {@linkcode Transport}, replacing any callbacks that have already been set, and expects that it is the only user of the {@linkcode Transport} instance going forward. - */ - async connect(transport) { - this._transport = transport; - const _onclose = this.transport?.onclose; - this._transport.onclose = () => { - try { - _onclose?.(); - } finally { - this._onclose(); - } - }; - const _onerror = this.transport?.onerror; - this._transport.onerror = (error) => { - _onerror?.(error); - this._onerror(error); - }; - const _onmessage = this._transport?.onmessage; - this._transport.onmessage = (message, extra) => { - _onmessage?.(message, extra); - if (src_CX2iR2pK_isJSONRPCResultResponse(message) || src_CX2iR2pK_isJSONRPCErrorResponse(message)) this._onresponse(message); - else if (src_CX2iR2pK_isJSONRPCRequest(message)) this._onrequest(message, extra); - else if (src_CX2iR2pK_isJSONRPCNotification(message)) this._onnotification(message, extra); - else this._onerror(/* @__PURE__ */ new Error(`Unknown message type: ${JSON.stringify(message)}`)); - }; - transport.setSupportedProtocolVersions?.(this._supportedProtocolVersions); - await this._transport.start(); - } - /** - * Transport-close hook. Subclass overrides MUST call `super._onclose()` - * after their own cleanup — base teardown (response-handler settlement, - * timeout clearing, in-flight request abort) does not run otherwise. - */ - _onclose() { - const responseHandlers = this._responseHandlers; - this._responseHandlers = /* @__PURE__ */ new Map(); - this._progressHandlers.clear(); - this._pendingDebouncedNotifications.clear(); - for (const info of this._timeoutInfo.values()) clearTimeout(info.timeoutId); - this._timeoutInfo.clear(); - const requestHandlerAbortControllers = this._requestHandlerAbortControllers; - this._requestHandlerAbortControllers = /* @__PURE__ */ new Map(); - const error = new src_CX2iR2pK_SdkError(src_CX2iR2pK_SdkErrorCode.ConnectionClosed, "Connection closed"); - this._transport = void 0; - try { - this.onclose?.(); - } finally { - for (const handler of responseHandlers.values()) handler(error); - for (const controller of requestHandlerAbortControllers.values()) controller.abort(error); - } - } - _onerror(error) { - this.onerror?.(error); - } - /** - * Inbound-notification dispatch. Subclass overrides MUST delegate - * unmatched traffic to `super._onnotification(rawNotification, extra)` — - * an override that consumes only what it owns and falls through to base - * dispatch for everything else. - */ - _onnotification(rawNotification, extra) { - const { message: notification } = liftWireOnlyMaterial(rawNotification, "notification"); - const codec = this._negotiatedWireCodec(); - if (extra?.classification === void 0 && this._shouldDropInbound(rawNotification) === "drop") return; - if (extra?.classification !== void 0) { - const classified = classifiedWireEra(extra.classification); - if (classified !== codec.era) { - this._onerror(/* @__PURE__ */ new Error(`Era mismatch on inbound notification '${notification.method}': classified as ${classified} but this instance serves ${codec.era}`)); - return; - } - } - if (isSpecNotificationMethod(notification.method) && !codec.hasNotificationMethod(notification.method)) return; - const handler = this._notificationHandlers.get(notification.method); - const fallback = this.fallbackNotificationHandler; - if (handler === void 0 && fallback === void 0) return; - Promise.resolve().then(() => handler === void 0 ? fallback(notification) : handler(notification, codec)).catch((error) => this._onerror(/* @__PURE__ */ new Error(`Uncaught error in notification handler: ${error}`))); - } - _onrequest(rawRequest, extra) { - const { message: request, lifted } = liftWireOnlyMaterial(rawRequest, "request"); - const codec = this._negotiatedWireCodec(); - if (extra?.classification === void 0 && this._shouldDropInbound(rawRequest) === "drop") { - this._onerror(/* @__PURE__ */ new Error(`Dropped inbound request '${rawRequest.method}': not servable on this connection's protocol era`)); - return; - } - const capturedTransport = this._transport; - const sendErrorResponse = (code, message, data) => { - const errorResponse = { - jsonrpc: "2.0", - id: request.id, - error: { - code, - message, - ...data !== void 0 && { data } - } - }; - capturedTransport?.send(errorResponse).catch((error) => this._onerror(/* @__PURE__ */ new Error(`Failed to send an error response: ${error}`))); - }; - if (extra?.classification !== void 0) { - const classified = classifiedWireEra(extra.classification); - if (classified !== codec.era) { - this._onerror(/* @__PURE__ */ new Error(`Era mismatch on inbound request '${request.method}': classified as ${classified} but this instance serves ${codec.era}`)); - const requested = extra.classification.revision ?? classified; - sendErrorResponse(src_CX2iR2pK_ProtocolErrorCode.UnsupportedProtocolVersion, `Unsupported protocol version: ${requested}`, { - supported: this._supportedProtocolVersions, - requested - }); - return; - } - } - if (isSpecRequestMethod(request.method) && !codec.hasRequestMethod(request.method)) { - sendErrorResponse(src_CX2iR2pK_ProtocolErrorCode.MethodNotFound, "Method not found"); - return; - } - const handler = this._requestHandlers.get(request.method) ?? this.fallbackRequestHandler; - if (handler === void 0) { - sendErrorResponse(src_CX2iR2pK_ProtocolErrorCode.MethodNotFound, "Method not found"); - return; - } - const envelopeError = codec.checkInboundEnvelope(lifted); - if (envelopeError !== void 0) { - sendErrorResponse(src_CX2iR2pK_ProtocolErrorCode.InvalidParams, envelopeError); - return; - } - const sendNotification = (notification, options) => this._notificationViaCodec(this._resolveOutboundCodec(notification.method), notification, { - ...options, - relatedRequestId: request.id - }); - const sendRequest = (r, resultSchema, options) => this._requestWithSchemaViaCodec(this._resolveOutboundCodec(r.method), r, resultSchema, { - ...options, - relatedRequestId: request.id - }); - const abortController = new AbortController(); - this._requestHandlerAbortControllers.set(request.id, abortController); - const partitionedInputResponses = lifted.inputResponses === void 0 ? void 0 : partitionInputResponses(lifted.inputResponses); - const baseCtx = { - sessionId: capturedTransport?.sessionId, - mcpReq: { - id: request.id, - method: request.method, - _meta: request.params?._meta, - ...lifted.envelope !== void 0 && { envelope: lifted.envelope }, - ...partitionedInputResponses !== void 0 && { inputResponses: partitionedInputResponses.accepted }, - ...partitionedInputResponses !== void 0 && partitionedInputResponses.droppedKeys.length > 0 && { droppedInputResponseKeys: partitionedInputResponses.droppedKeys }, - requestState: lifted.requestState === void 0 ? NO_REQUEST_STATE : requestStateAccessor(lifted.requestState), - signal: abortController.signal, - send: ((r, schemaOrOptions, maybeOptions) => { - const sendCodec = this._resolveOutboundCodec(r.method); - this._assertOutboundRequestInEra(sendCodec, r.method); - if (isStandardSchema(schemaOrOptions)) return sendRequest(r, schemaOrOptions, maybeOptions); - const validate = codecResultValidator(sendCodec, r.method); - if (validate === void 0) throw new TypeError(`'${r.method}' is not a spec method; pass a result schema as the second argument to ctx.mcpReq.send().`); - return sendRequest(r, validate, schemaOrOptions); - }), - notify: sendNotification - }, - http: extra?.authInfo ? { authInfo: extra.authInfo } : void 0 - }; - const ctx = this.buildContext(baseCtx, extra); - Promise.resolve().then(() => handler(request, ctx)).then(async (result) => { - if (abortController.signal.aborted) return; - let encoded; - try { - encoded = codec.encodeResult(request.method, result, this._outboundServerInfo()); - } catch (error) { - this._onerror(/* @__PURE__ */ new Error(`Failed to encode result for ${request.method}: ${error}`)); - sendErrorResponse(src_CX2iR2pK_ProtocolErrorCode.InternalError, "Internal error"); - return; - } - const response = { - result: encoded, - jsonrpc: "2.0", - id: request.id - }; - await capturedTransport?.send(response); - }, async (error) => { - if (abortController.signal.aborted) return; - const thrownCode = Number.isSafeInteger(error["code"]) ? error["code"] : src_CX2iR2pK_ProtocolErrorCode.InternalError; - const errorResponse = { - jsonrpc: "2.0", - id: request.id, - error: { - code: codec.encodeErrorCode(thrownCode), - message: error.message ?? "Internal error", - ...error["data"] !== void 0 && { data: error["data"] } - } - }; - await capturedTransport?.send(errorResponse); - }).catch((error) => this._onerror(/* @__PURE__ */ new Error(`Failed to send response: ${error}`))).finally(() => { - if (this._requestHandlerAbortControllers.get(request.id) === abortController) this._requestHandlerAbortControllers.delete(request.id); - }); - } - _onprogress(notification) { - const { progressToken, ...params } = notification.params; - const messageId = Number(progressToken); - const handler = this._progressHandlers.get(messageId); - if (!handler) { - this._onerror(/* @__PURE__ */ new Error(`Received a progress notification for an unknown token: ${JSON.stringify(notification)}`)); - return; - } - const responseHandler = this._responseHandlers.get(messageId); - const timeoutInfo = this._timeoutInfo.get(messageId); - if (timeoutInfo && responseHandler && timeoutInfo.resetTimeoutOnProgress) try { - this._resetTimeout(messageId); - } catch (error) { - this._responseHandlers.delete(messageId); - this._progressHandlers.delete(messageId); - this._cleanupTimeout(messageId); - responseHandler(error); - return; - } - handler(params); - } - /** - * Inbound-response dispatch. Subclass overrides MUST delegate unmatched - * traffic to `super._onresponse(response)` — an override that consumes - * only what it owns and falls through to base dispatch for everything - * else. - */ - _onresponse(response) { - const messageId = Number(response.id); - const handler = this._responseHandlers.get(messageId); - if (handler === void 0) { - this._onerror(/* @__PURE__ */ new Error(`Received a response for an unknown message ID: ${JSON.stringify(response)}`)); - return; - } - this._responseHandlers.delete(messageId); - this._cleanupTimeout(messageId); - this._progressHandlers.delete(messageId); - if (src_CX2iR2pK_isJSONRPCResultResponse(response)) handler(response); - else handler(src_CX2iR2pK_ProtocolError.fromError(response.error.code, response.error.message, response.error.data)); - } - get transport() { - return this._transport; - } - /** - * Closes the connection. - */ - async close() { - await this._transport?.close(); - } - request(request, schemaOrOptions, maybeOptions) { - const codec = this._resolveOutboundCodec(request.method); - this._assertOutboundRequestInEra(codec, request.method); - if (isStandardSchema(schemaOrOptions)) return this._requestWithSchemaViaCodec(codec, request, schemaOrOptions, maybeOptions); - const validate = codecResultValidator(codec, request.method); - if (validate === void 0) throw new TypeError(`'${request.method}' is not a spec method; pass a result schema as the second argument to request().`); - return this._requestWithSchemaViaCodec(codec, request, validate, schemaOrOptions); - } - /** - * The wire codec for this instance's negotiated era — the phase-2 truth: - * everything an established connection sends and receives resolves - * through it. Legacy until a version has been negotiated. - */ - _negotiatedWireCodec() { - return src_CX2iR2pK_codecForVersion(this._negotiatedProtocolVersion); - } - /** - * Protected accessor for the instance's negotiated wire codec, for role - * classes (Client/Server/McpServer) routing era-dependent behavior - * through the codec's function-only surface — `samplingResultVariant`, - * `outboundEnvelope`, `projectCallToolResult` — instead of branching on - * the protocol version themselves. - */ - _wireCodec() { - return this._negotiatedWireCodec(); - } - /** - * Outbound codec resolution: while the negotiated version is still unset - * (the negotiation window), lifecycle messages are bootstrap-pinned BY - * METHOD — they self-identify their era (`initialize` IS the legacy - * handshake, `server/discover` IS the modern probe). Once a version has - * been negotiated, the instance era is authoritative for everything — a - * negotiated session never re-routes a method onto the other era. - */ - _resolveOutboundCodec(method) { - if (this._negotiatedProtocolVersion === void 0) { - const pinned = bootstrapOutboundCodec(method); - if (pinned) return pinned; - } - return this._negotiatedWireCodec(); - } - /** - * Era gate for outbound requests — deletions are physical in BOTH - * directions: sending a spec method that the resolved era does not define - * dies locally with a typed error before anything reaches the transport. - * Methods outside the spec universe are consumer-owned extension methods - * and stay era-blind. - */ - _assertOutboundRequestInEra(codec, method) { - if (isSpecRequestMethod(method) && !codec.hasRequestMethod(method)) throw new src_CX2iR2pK_SdkError(src_CX2iR2pK_SdkErrorCode.MethodNotSupportedByProtocolVersion, `Method '${method}' is not supported by the negotiated protocol version (wire era ${codec.era})`, { - method, - era: codec.era - }); - } - /** - * Sends a request and waits for a response, using the provided schema for - * validation instead of the era registry's method-keyed entry. - * - * This is the internal implementation used by SDK methods whose result - * schema cannot be expressed as a method-keyed registry entry — the one - * surviving case is `server.createMessage`, whose result schema depends - * on the REQUEST params (tools vs no tools) — and by callers passing - * explicit compatibility schemas. Spec methods are still era-gated here: - * an explicit schema never smuggles a deleted method onto the wire. - */ - _requestWithSchema(request, resultSchema, options) { - const codec = this._resolveOutboundCodec(request.method); - this._assertOutboundRequestInEra(codec, request.method); - return this._requestWithSchemaViaCodec(codec, request, resultSchema, options); - } - /** - * The request funnel proper, keyed by the resolved era codec: the codec - * owns result decoding (raw-first `resultType` discrimination — V-1 — - * and the era's lift posture) before the schema validation step. - */ - _requestWithSchemaViaCodec(codec, request, resultSchema, options) { - const { relatedRequestId, resumptionToken, onresumptiontoken, headers } = options ?? {}; - const flowStartedAt = Date.now(); - let onAbort; - let cleanupMessageId; - return new Promise((resolve, reject) => { - const earlyReject = (error) => { - reject(error); - }; - if (!this._transport) { - earlyReject(/* @__PURE__ */ new Error("Not connected")); - return; - } - if (this._options?.enforceStrictCapabilities === true) try { - this.assertCapabilityForMethod(request.method); - } catch (error) { - earlyReject(error); - return; - } - if (options?.signal?.aborted) { - const reason = options.signal.reason; - throw reason instanceof src_CX2iR2pK_SdkError ? reason : new src_CX2iR2pK_SdkError(src_CX2iR2pK_SdkErrorCode.RequestTimeout, String(reason)); - } - const requestAbort = codec.era === src_CX2iR2pK_MODERN_WIRE_REVISION && this._transport.hasPerRequestStream === true ? new AbortController() : void 0; - const messageId = this._requestMessageId++; - cleanupMessageId = messageId; - const jsonrpcRequest = { - ...request, - jsonrpc: "2.0", - id: messageId - }; - if (options?.onprogress) { - this._progressHandlers.set(messageId, options.onprogress); - jsonrpcRequest.params = { - ...request.params, - _meta: { - ...request.params?._meta, - progressToken: messageId - } - }; - } - const outbound = this._envelopeOutbound(jsonrpcRequest); - let responseReceived = false; - const cancel = (reason) => { - if (responseReceived) return; - this._progressHandlers.delete(messageId); - if (requestAbort === void 0) this._transport?.send(this._envelopeOutbound({ - jsonrpc: "2.0", - method: "notifications/cancelled", - params: { - requestId: messageId, - reason: String(reason) - } - }), { - relatedRequestId, - resumptionToken, - onresumptiontoken - }).catch((error) => this._onerror(/* @__PURE__ */ new Error(`Failed to send cancellation: ${error}`))); - else requestAbort.abort(); - reject(reason instanceof src_CX2iR2pK_SdkError ? reason : new src_CX2iR2pK_SdkError(src_CX2iR2pK_SdkErrorCode.RequestTimeout, String(reason))); - }; - this._responseHandlers.set(messageId, (response) => { - if (options?.signal?.aborted) return; - responseReceived = true; - if (response instanceof Error) return reject(response); - let decoded; - try { - decoded = codec.decodeResult(request.method, response.result); - } catch (error) { - return reject(error instanceof Error ? error : new Error(String(error))); - } - if (decoded.kind === "invalid") return reject(decoded.error); - if (decoded.kind === "input_required") { - if (options?.allowInputRequired === true) return resolve(manualInputRequiredValue(decoded)); - const flow = { - codec, - request, - resultSchema, - options, - flowStartedAt, - retry: (params, legOptions) => this._requestWithSchemaViaCodec(codec, params === void 0 ? { method: request.method } : { - method: request.method, - params - }, resultSchema, legOptions) - }; - return resolve(this._resolveNonCompleteResult(decoded, flow)); - } - const result = decoded.result; - validateStandardSchema(resultSchema, result).then((parseResult) => { - if (parseResult.success) resolve(parseResult.data); - else reject(new src_CX2iR2pK_SdkError(src_CX2iR2pK_SdkErrorCode.InvalidResult, `Invalid result for ${request.method}: ${parseResult.error}`)); - }, reject); - }); - onAbort = () => cancel(options?.signal?.reason); - options?.signal?.addEventListener("abort", onAbort, { once: true }); - const timeout = options?.timeout ?? DEFAULT_REQUEST_TIMEOUT_MSEC; - const timeoutHandler = () => cancel(new src_CX2iR2pK_SdkError(src_CX2iR2pK_SdkErrorCode.RequestTimeout, "Request timed out", { timeout })); - this._setupTimeout(messageId, timeout, options?.maxTotalTimeout, timeoutHandler, options?.resetTimeoutOnProgress ?? false); - this._transport.send(outbound, { - relatedRequestId, - resumptionToken, - onresumptiontoken, - headers, - requestSignal: requestAbort?.signal - }).catch((error) => { - this._progressHandlers.delete(messageId); - reject(error); - }); - }).finally(() => { - if (onAbort) options?.signal?.removeEventListener("abort", onAbort); - if (cleanupMessageId !== void 0) { - this._responseHandlers.delete(cleanupMessageId); - this._cleanupTimeout(cleanupMessageId); - } - }); - } - /** - * Emits a notification, which is a one-way message that does not expect a response. - */ - async notification(notification, options) { - return this._notificationViaCodec(this._resolveOutboundCodec(notification.method), notification, options); - } - /** - * The notification funnel proper, keyed by the resolved era codec — - * direct sends and related notifications (`ctx.mcpReq.notify`) alike - * resolve through the instance's negotiated era at send time. - */ - async _notificationViaCodec(codec, notification, options) { - if (!this._transport) throw new src_CX2iR2pK_SdkError(src_CX2iR2pK_SdkErrorCode.NotConnected, "Not connected"); - if (isSpecNotificationMethod(notification.method) && !codec.hasNotificationMethod(notification.method)) throw new src_CX2iR2pK_SdkError(src_CX2iR2pK_SdkErrorCode.MethodNotSupportedByProtocolVersion, `Notification '${notification.method}' is not supported by the negotiated protocol version (wire era ${codec.era})`, { - method: notification.method, - era: codec.era - }); - this.assertNotificationCapability(notification.method); - const jsonrpcNotification = this._envelopeOutbound({ - jsonrpc: "2.0", - ...notification - }); - if ((this._options?.debouncedNotificationMethods ?? []).includes(notification.method) && !notification.params && !options?.relatedRequestId) { - if (this._pendingDebouncedNotifications.has(notification.method)) return; - this._pendingDebouncedNotifications.add(notification.method); - Promise.resolve().then(() => { - this._pendingDebouncedNotifications.delete(notification.method); - if (!this._transport) return; - this._transport?.send(jsonrpcNotification, options).catch((error) => this._onerror(error)); - }); - return; - } - await this._transport.send(jsonrpcNotification, options); - } - setRequestHandler(method, schemasOrHandler, maybeHandler) { - this.assertRequestHandlerCapability(method); - let stored; - if (typeof schemasOrHandler === "function") { - if (!isSpecRequestMethod(method)) throw new TypeError(`'${method}' is not a spec request method; pass schemas as the second argument to setRequestHandler().`); - stored = (request, ctx) => { - const dispatchCodec = this._negotiatedWireCodec(); - let outcome = dispatchCodec.validateRequest(method, request); - if (!outcome.ok && outcome.reason === "not-in-era") outcome = dispatchCodec.validateInputRequest(method, request); - if (!outcome.ok) { - if (outcome.reason === "not-in-era") throw new src_CX2iR2pK_ProtocolError(src_CX2iR2pK_ProtocolErrorCode.InternalError, `No wire schema for ${method} in the resolved era`); - throw new Error(outcome.message); - } - return Promise.resolve(schemasOrHandler(outcome.value, ctx)); - }; - } else if (maybeHandler) stored = async (request, ctx) => { - const parsed = await validateStandardSchema(schemasOrHandler.params, { ...request.params }); - if (!parsed.success) throw new src_CX2iR2pK_ProtocolError(src_CX2iR2pK_ProtocolErrorCode.InvalidParams, `Invalid params for ${method}: ${parsed.error}`); - return maybeHandler(parsed.data, ctx); - }; - else throw new TypeError("setRequestHandler: handler is required"); - this._requestHandlers.set(method, this._wrapHandler(method, stored)); - } - /** - * Hook for subclasses to wrap a registered request handler with role-specific - * validation or behavior (e.g. `Server` validates `tools/call` results, `Client` - * validates `elicitation/create` mode and result). Runs for both the 2-arg and - * 3-arg registration paths. The default implementation is identity. - * - * Subclasses overriding this hook avoid redeclaring `setRequestHandler`'s overload set. - */ - _wrapHandler(_method, handler) { - return handler; - } - /** - * Hook for subclasses to supply the implementation identity the 2026-era - * encode seam stamps into outbound result `_meta` under - * `io.modelcontextprotocol/serverInfo` (spec PR #3002: servers SHOULD - * identify themselves on every response). The default is `undefined` — no - * stamp. Only `Server` overrides this: the key identifies the software - * producing a response, and the 2025-era codec never stamps anything - * regardless (the never-stamp guarantee). - */ - _outboundServerInfo() {} - /** - * Removes the request handler for the given method. - */ - removeRequestHandler(method) { - this._requestHandlers.delete(method); - } - /** - * Asserts that a request handler has not already been set for the given method, in preparation for a new one being automatically installed. - */ - assertCanSetRequestHandler(method) { - if (this._requestHandlers.has(method)) throw new Error(`A request handler for ${method} already exists, which would be overridden`); - } - setNotificationHandler(method, schemasOrHandler, maybeHandler) { - if (typeof schemasOrHandler === "function") { - if (!isSpecNotificationMethod(method)) throw new TypeError(`'${method}' is not a spec notification method; pass schemas as the second argument to setNotificationHandler().`); - this._notificationHandlers.set(method, (notification, codec) => { - const outcome = codec.validateNotification(method, notification); - if (!outcome.ok) { - if (outcome.reason === "not-in-era") throw new src_CX2iR2pK_ProtocolError(src_CX2iR2pK_ProtocolErrorCode.InternalError, `No wire schema for ${method} in the resolved era`); - throw new Error(outcome.message); - } - return Promise.resolve(schemasOrHandler(outcome.value)); - }); - return; - } - if (!maybeHandler) throw new TypeError("setNotificationHandler: handler is required"); - this._notificationHandlers.set(method, async (notification) => { - const parsed = await validateStandardSchema(schemasOrHandler.params, { ...notification.params }); - if (!parsed.success) throw new src_CX2iR2pK_ProtocolError(src_CX2iR2pK_ProtocolErrorCode.InvalidParams, `Invalid params for notification ${method}: ${parsed.error}`); - await maybeHandler(parsed.data, notification); - }); - } - /** - * Removes the notification handler for the given method. - */ - removeNotificationHandler(method) { - this._notificationHandlers.delete(method); - } -}; -function isPlainObject$1(value) { - return value !== null && typeof value === "object" && !Array.isArray(value); -} -function mergeCapabilities(base, additional) { - const result = { ...base }; - for (const key in additional) { - const k = key; - const addValue = additional[k]; - if (addValue === void 0) continue; - const baseValue = result[k]; - result[k] = isPlainObject$1(baseValue) && isPlainObject$1(addValue) ? { - ...baseValue, - ...addValue - } : addValue; - } - return result; -} - -//#endregion -//#region ../core-internal/src/shared/inputRequiredEngine.ts -function src_CX2iR2pK_isPlainObject(value) { - return typeof value === "object" && value !== null && !Array.isArray(value); -} -/** -* Splits a retried request's `inputResponses` map into the BARE response -* entries the spec defines and everything else. The spec's embedded responses -* are the bare result objects (an `ElicitResult`, `CreateMessageResult`, or -* `ListRootsResult`); a wrapped `{method, result}` envelope (a shape some -* peers emit) is never accepted as a response — its key is recorded so the -* handler can re-issue the corresponding input request. -*/ -function partitionInputResponses(inputResponses) { - const accepted = {}; - const droppedKeys = []; - if (!src_CX2iR2pK_isPlainObject(inputResponses)) return { - accepted, - droppedKeys - }; - for (const [key, entry] of Object.entries(inputResponses)) { - if (!src_CX2iR2pK_isPlainObject(entry) || "method" in entry || "result" in entry) { - droppedKeys.push(key); - continue; - } - accepted[key] = entry; - } - return { - accepted, - droppedKeys - }; -} -/** -* Builds the manual-mode {@linkcode InputRequiredResult} value from the -* codec's decoded payload — what an `allowInputRequired: true` caller -* receives instead of the auto-fulfilled complete result. -*/ -function manualInputRequiredValue(decoded) { - return { - resultType: "input_required", - inputRequests: decoded.inputRequests, - ...decoded.requestState !== void 0 && { requestState: decoded.requestState } - }; -} - -//#endregion -//#region ../../node_modules/.pnpm/content-type@1.0.5/node_modules/content-type/index.js -/*! -* content-type -* Copyright(c) 2015 Douglas Christopher Wilson -* MIT Licensed -*/ -var require_content_type = /* @__PURE__ */ __commonJSMin(((exports) => { - /** - * RegExp to match *( ";" parameter ) in RFC 7231 sec 3.1.1.1 - * - * parameter = token "=" ( token / quoted-string ) - * token = 1*tchar - * tchar = "!" / "#" / "$" / "%" / "&" / "'" / "*" - * / "+" / "-" / "." / "^" / "_" / "`" / "|" / "~" - * / DIGIT / ALPHA - * ; any VCHAR, except delimiters - * quoted-string = DQUOTE *( qdtext / quoted-pair ) DQUOTE - * qdtext = HTAB / SP / %x21 / %x23-5B / %x5D-7E / obs-text - * obs-text = %x80-FF - * quoted-pair = "\" ( HTAB / SP / VCHAR / obs-text ) - */ - var PARAM_REGEXP = /; *([!#$%&'*+.^_`|~0-9A-Za-z-]+) *= *("(?:[\u000b\u0020\u0021\u0023-\u005b\u005d-\u007e\u0080-\u00ff]|\\[\u000b\u0020-\u00ff])*"|[!#$%&'*+.^_`|~0-9A-Za-z-]+) */g; - /** - * RegExp to match quoted-pair in RFC 7230 sec 3.2.6 - * - * quoted-pair = "\" ( HTAB / SP / VCHAR / obs-text ) - * obs-text = %x80-FF - */ - var QESC_REGEXP = /\\([\u000b\u0020-\u00ff])/g; - /** - * RegExp to match type in RFC 7231 sec 3.1.1.1 - * - * media-type = type "/" subtype - * type = token - * subtype = token - */ - var TYPE_REGEXP = /^[!#$%&'*+.^_`|~0-9A-Za-z-]+\/[!#$%&'*+.^_`|~0-9A-Za-z-]+$/; - exports.parse = parse; - /** - * Parse media type to object. - * - * @param {string|object} string - * @return {Object} - * @public - */ - function parse(string) { - if (!string) throw new TypeError("argument string is required"); - var header = typeof string === "object" ? getcontenttype(string) : string; - if (typeof header !== "string") throw new TypeError("argument string is required to be a string"); - var index = header.indexOf(";"); - var type = index !== -1 ? header.slice(0, index).trim() : header.trim(); - if (!TYPE_REGEXP.test(type)) throw new TypeError("invalid media type"); - var obj = new ContentType(type.toLowerCase()); - if (index !== -1) { - var key; - var match; - var value; - PARAM_REGEXP.lastIndex = index; - while (match = PARAM_REGEXP.exec(header)) { - if (match.index !== index) throw new TypeError("invalid parameter format"); - index += match[0].length; - key = match[1].toLowerCase(); - value = match[2]; - if (value.charCodeAt(0) === 34) { - value = value.slice(1, -1); - if (value.indexOf("\\") !== -1) value = value.replace(QESC_REGEXP, "$1"); - } - obj.parameters[key] = value; - } - if (index !== header.length) throw new TypeError("invalid parameter format"); - } - return obj; - } - /** - * Get content-type from req/res objects. - * - * @param {object} - * @return {Object} - * @private - */ - function getcontenttype(obj) { - var header; - if (typeof obj.getHeader === "function") header = obj.getHeader("content-type"); - else if (typeof obj.headers === "object") header = obj.headers && obj.headers["content-type"]; - if (typeof header !== "string") throw new TypeError("content-type header is missing from object"); - return header; - } - /** - * Class to represent a content type. - * @private - */ - function ContentType(type) { - this.parameters = Object.create(null); - this.type = type; - } -})); - -//#endregion -//#region ../core-internal/src/shared/mediaType.ts -var import_content_type = /* @__PURE__ */ __toESM(require_content_type(), 1); -/** -* Extracts the media type (the lowercased `type/subtype` pair, without -* parameters) from a raw `Content-Type` header value, or `undefined` when the -* header is missing or empty. -* -* Content-Type comparisons must use the parsed media type, never a substring -* search of the raw header: a value like `text/plain; a=application/json` -* contains the substring `application/json` but its media type is -* `text/plain`, and case variants or parameters make naive string comparison -* wrong in both directions. -* -* "Essence" is the WHATWG MIME Sniffing standard's term for the bare -* `type/subtype` pair (https://mimesniff.spec.whatwg.org/#mime-type-essence); -* the Fetch standard's request classification is defined against it -* (https://fetch.spec.whatwg.org/#cors-safelisted-request-header). -* -* Parsing is RFC 9110 (`content-type` package) first. When the parameter -* section is malformed (`application/json;`, `application/json; charset=`), -* browsers and most HTTP stacks still derive the media type from the segment -* before the first `;` — the fallback matches that widely-implemented -* behavior, so a header whose media type is unambiguous is not rejected for -* a sloppy parameter section. -*/ -function src_CX2iR2pK_mediaTypeEssence(header) { - if (!header) return; - try { - return import_content_type.parse(header).type; - } catch { - const essence = (header.split(";", 1)[0] ?? "").trim().toLowerCase(); - if (essence === "" || header.slice(essence.length).includes(",")) return; - return essence; - } -} -/** -* Whether a raw `Content-Type` header value denotes `application/json`. -* Parameters (for example `charset=utf-8`) are allowed and ignored; malformed -* parameter sections do not reject a header whose media type is unambiguously -* `application/json` (see `mediaTypeEssence` for the exact grammar). -*/ -function src_CX2iR2pK_isJsonContentType(header) { - if (header === "application/json") return true; - return src_CX2iR2pK_mediaTypeEssence(header) === "application/json"; -} - -//#endregion -//#region ../core-internal/src/shared/metadataUtils.ts -/** -* Utilities for working with {@linkcode BaseMetadata} objects. -*/ -/** -* Gets the display name for an object with {@linkcode BaseMetadata}. -* For tools, the precedence is: `title` → {@linkcode index.ToolAnnotations | annotations}.`title` → `name` -* For other objects: `title` → `name` -* This implements the spec requirement: "if no title is provided, name should be used for display purposes" -*/ -function getDisplayName(metadata) { - if (metadata.title !== void 0 && metadata.title !== "") return metadata.title; - if ("annotations" in metadata && metadata.annotations?.title) return metadata.annotations.title; - return metadata.name; -} - -//#endregion -//#region ../core-internal/src/shared/stdio.ts -const STDIO_DEFAULT_MAX_BUFFER_SIZE = 10 * 1024 * 1024; -/** -* Buffers a continuous stdio stream into discrete JSON-RPC messages. -*/ -var ReadBuffer = class { - _buffer; - _maxBufferSize; - constructor(options) { - this._maxBufferSize = options?.maxBufferSize ?? STDIO_DEFAULT_MAX_BUFFER_SIZE; - } - append(chunk) { - if ((this._buffer?.length ?? 0) + chunk.length > this._maxBufferSize) { - this.clear(); - throw new Error(`ReadBuffer exceeded maximum size of ${this._maxBufferSize} bytes`); - } - this._buffer = this._buffer ? Buffer.concat([this._buffer, chunk]) : chunk; - } - readMessage() { - while (this._buffer) { - const index = this._buffer.indexOf("\n"); - if (index === -1) return null; - const line = this._buffer.toString("utf8", 0, index).replace(/\r$/, ""); - this._buffer = this._buffer.subarray(index + 1); - try { - return deserializeMessage(line); - } catch (error) { - if (error instanceof SyntaxError) continue; - throw error; - } - } - return null; - } - clear() { - this._buffer = void 0; - } -}; -function deserializeMessage(line) { - return auth_CUe6YdwF_JSONRPCMessageSchema.parse(JSON.parse(line)); -} -function serializeMessage(message) { - return JSON.stringify(message) + "\n"; -} - -//#endregion -//#region ../core-internal/src/shared/toolNameValidation.ts -/** -* Tool name validation utilities according to SEP: Specify Format for Tool Names -* -* Tool names SHOULD be between 1 and 128 characters in length (inclusive). -* Tool names are case-sensitive. -* Allowed characters: uppercase and lowercase ASCII letters (`A-Z`, `a-z`), digits -* (`0-9`), underscore (`_`), dash (`-`), and dot (`.`). -* Tool names SHOULD NOT contain spaces, commas, or other special characters. -* -* @see {@link https://github.com/modelcontextprotocol/modelcontextprotocol/issues/986 | SEP-986: Specify Format for Tool Names} -*/ -/** -* Regular expression for valid tool names according to SEP-986 specification -*/ -const TOOL_NAME_REGEX = /^[A-Za-z0-9._-]{1,128}$/; -/** -* Validates a tool name according to the SEP specification -* @param name - The tool name to validate -* @returns An object containing validation result and any warnings -*/ -function validateToolName(name) { - const warnings = []; - if (name.length === 0) return { - isValid: false, - warnings: ["Tool name cannot be empty"] - }; - if (name.length > 128) return { - isValid: false, - warnings: [`Tool name exceeds maximum length of 128 characters (current: ${name.length})`] - }; - if (name.includes(" ")) warnings.push("Tool name contains spaces, which may cause parsing issues"); - if (name.includes(",")) warnings.push("Tool name contains commas, which may cause parsing issues"); - if (name.startsWith("-") || name.endsWith("-")) warnings.push("Tool name starts or ends with a dash, which may cause parsing issues in some contexts"); - if (name.startsWith(".") || name.endsWith(".")) warnings.push("Tool name starts or ends with a dot, which may cause parsing issues in some contexts"); - if (!TOOL_NAME_REGEX.test(name)) { - const invalidChars = [...name].filter((char) => !/[A-Za-z0-9._-]/.test(char)).filter((char, index, arr) => arr.indexOf(char) === index); - warnings.push(`Tool name contains invalid characters: ${invalidChars.map((c) => `"${c}"`).join(", ")}`, "Allowed characters are: A-Z, a-z, 0-9, underscore (_), dash (-), and dot (.)"); - return { - isValid: false, - warnings - }; - } - return { - isValid: true, - warnings - }; -} -/** -* Issues warnings for non-conforming tool names -* @param name - The tool name that triggered the warnings -* @param warnings - Array of warning messages -*/ -function issueToolNameWarning(name, warnings) { - if (warnings.length > 0) { - console.warn(`Tool name validation warning for "${name}":`); - for (const warning of warnings) console.warn(` - ${warning}`); - console.warn("Tool registration will proceed, but this may cause compatibility issues."); - console.warn("Consider updating the tool name to conform to the MCP tool naming standard."); - console.warn("See SEP: Specify Format for Tool Names (https://github.com/modelcontextprotocol/modelcontextprotocol/issues/986) for more details."); - } -} -/** -* Validates a tool name and issues warnings for non-conforming names -* @param name - The tool name to validate -* @returns `true` if the name is valid, `false` otherwise -*/ -function validateAndWarnToolName(name) { - const result = validateToolName(name); - issueToolNameWarning(name, result.warnings); - return result.isValid; -} - -//#endregion -//#region ../core-internal/src/shared/transport.ts -/** -* Normalizes `HeadersInit` to a plain `Record` for manipulation. -* Handles `Headers` objects, arrays of tuples, and plain objects. -*/ -function normalizeHeaders(headers) { - if (!headers) return {}; - if (headers instanceof Headers) return Object.fromEntries(headers.entries()); - if (Array.isArray(headers)) return Object.fromEntries(headers); - return { ...headers }; -} -/** -* Creates a fetch function that includes base `RequestInit` options. -* This ensures requests inherit settings like credentials, mode, headers, etc. from the base init. -* -* @param baseFetch - The base fetch function to wrap (defaults to global `fetch`) -* @param baseInit - The base `RequestInit` to merge with each request -* @returns A wrapped fetch function that merges base options with call-specific options -*/ -function createFetchWithInit(baseFetch = fetch, baseInit) { - if (!baseInit) return baseFetch; - return async (url, init) => { - return baseFetch(url, { - ...baseInit, - ...init, - headers: init?.headers ? { - ...normalizeHeaders(baseInit.headers), - ...normalizeHeaders(init.headers) - } : baseInit.headers - }); - }; -} - -//#endregion -//#region ../core-internal/src/shared/uriTemplate.ts -const MAX_TEMPLATE_LENGTH = 1e6; -const MAX_VARIABLE_LENGTH = 1e6; -const MAX_TEMPLATE_EXPRESSIONS = 1e4; -const MAX_REGEX_LENGTH = 1e6; -var src_CX2iR2pK_UriTemplate = class UriTemplate { - /** - * Returns true if the given string contains any URI template expressions. - * A template expression is a sequence of characters enclosed in curly braces, - * like `{foo}` or `{?bar}`. - */ - static isTemplate(str) { - return /\{[^}\s]+\}/.test(str); - } - static validateLength(str, max, context) { - if (str.length > max) throw new Error(`${context} exceeds maximum length of ${max} characters (got ${str.length})`); - } - template; - parts; - get variableNames() { - return this.parts.flatMap((part) => typeof part === "string" ? [] : part.names); - } - constructor(template) { - UriTemplate.validateLength(template, MAX_TEMPLATE_LENGTH, "Template"); - this.template = template; - this.parts = this.parse(template); - } - toString() { - return this.template; - } - parse(template) { - const parts = []; - let currentText = ""; - let i = 0; - let expressionCount = 0; - while (i < template.length) if (template[i] === "{") { - if (currentText) { - parts.push(currentText); - currentText = ""; - } - const end = template.indexOf("}", i); - if (end === -1) throw new Error("Unclosed template expression"); - expressionCount++; - if (expressionCount > MAX_TEMPLATE_EXPRESSIONS) throw new Error(`Template contains too many expressions (max ${MAX_TEMPLATE_EXPRESSIONS})`); - const expr = template.slice(i + 1, end); - const operator = this.getOperator(expr); - const exploded = expr.includes("*"); - const names = this.getNames(expr); - const name = names[0]; - for (const name$1 of names) UriTemplate.validateLength(name$1, MAX_VARIABLE_LENGTH, "Variable name"); - parts.push({ - name, - operator, - names, - exploded - }); - i = end + 1; - } else { - currentText += template[i]; - i++; - } - if (currentText) parts.push(currentText); - return parts; - } - getOperator(expr) { - return [ - "+", - "#", - ".", - "/", - "?", - "&" - ].find((op) => expr.startsWith(op)) || ""; - } - getNames(expr) { - const operator = this.getOperator(expr); - return expr.slice(operator.length).split(",").map((name) => name.replace("*", "").trim()).filter((name) => name.length > 0); - } - encodeValue(value, operator) { - UriTemplate.validateLength(value, MAX_VARIABLE_LENGTH, "Variable value"); - if (operator === "+" || operator === "#") return encodeURI(value); - return encodeURIComponent(value); - } - expandPart(part, variables) { - if (part.operator === "?" || part.operator === "&") { - const pairs = part.names.map((name) => { - const value$1 = variables[name]; - if (value$1 === void 0) return ""; - return `${name}=${Array.isArray(value$1) ? value$1.map((v) => this.encodeValue(v, part.operator)).join(",") : this.encodeValue(value$1.toString(), part.operator)}`; - }).filter((pair) => pair.length > 0); - if (pairs.length === 0) return ""; - return (part.operator === "?" ? "?" : "&") + pairs.join("&"); - } - if (part.names.length > 1) { - const values = part.names.map((name) => variables[name]).filter((v) => v !== void 0); - if (values.length === 0) return ""; - return values.map((v) => Array.isArray(v) ? v[0] : v).join(","); - } - const value = variables[part.name]; - if (value === void 0) return ""; - const encoded = (Array.isArray(value) ? value : [value]).map((v) => this.encodeValue(v, part.operator)); - switch (part.operator) { - case "": return encoded.join(","); - case "+": return encoded.join(","); - case "#": return "#" + encoded.join(","); - case ".": return "." + encoded.join("."); - case "/": return "/" + encoded.join("/"); - default: return encoded.join(","); - } - } - expand(variables) { - let result = ""; - let hasQueryParam = false; - for (const part of this.parts) { - if (typeof part === "string") { - result += part; - continue; - } - const expanded = this.expandPart(part, variables); - if (!expanded) continue; - result += (part.operator === "?" || part.operator === "&") && hasQueryParam ? expanded.replace("?", "&") : expanded; - if (part.operator === "?" || part.operator === "&") hasQueryParam = true; - } - return result; - } - escapeRegExp(str) { - return str.replaceAll(/[.*+?^${}()|[\]\\]/g, String.raw`\$&`); - } - partToRegExp(part) { - const patterns = []; - for (const name$1 of part.names) UriTemplate.validateLength(name$1, MAX_VARIABLE_LENGTH, "Variable name"); - if (part.operator === "?" || part.operator === "&") { - for (let i = 0; i < part.names.length; i++) { - const name$1 = part.names[i]; - const prefix = i === 0 ? "\\" + part.operator : "&"; - patterns.push({ - pattern: prefix + this.escapeRegExp(name$1) + "=([^&]+)", - name: name$1 - }); - } - return patterns; - } - let pattern; - const name = part.name; - switch (part.operator) { - case "": - pattern = part.exploded ? "([^/,]+(?:,[^/,]+)*)" : "([^/,]+)"; - break; - case "+": - case "#": - pattern = "(.+)"; - break; - case ".": - pattern = String.raw`\.([^/,]+)`; - break; - case "/": - pattern = "/" + (part.exploded ? "([^/,]+(?:,[^/,]+)*)" : "([^/,]+)"); - break; - default: pattern = "([^/]+)"; - } - patterns.push({ - pattern, - name - }); - return patterns; - } - match(uri) { - UriTemplate.validateLength(uri, MAX_TEMPLATE_LENGTH, "URI"); - let pattern = "^"; - const names = []; - for (const part of this.parts) if (typeof part === "string") pattern += this.escapeRegExp(part); - else { - const patterns = this.partToRegExp(part); - for (const { pattern: partPattern, name } of patterns) { - pattern += partPattern; - names.push({ - name, - exploded: part.exploded - }); - } - } - pattern += "$"; - UriTemplate.validateLength(pattern, MAX_REGEX_LENGTH, "Generated regex pattern"); - const regex = new RegExp(pattern); - const match = uri.match(regex); - if (!match) return null; - const result = {}; - for (const [i, name_] of names.entries()) { - const { name, exploded } = name_; - const value = match[i + 1]; - const cleanName = name.replace("*", ""); - result[cleanName] = exploded && value.includes(",") ? value.split(",") : value; - } - return result; - } -}; - -//#endregion -//#region ../core-internal/src/util/inMemory.ts -/** -* In-memory transport for creating clients and servers that talk to each other within the same process. -* -* Intended for testing and development. For production in-process connections, use -* `StreamableHTTPClientTransport` against a local server URL. -*/ -var src_CX2iR2pK_InMemoryTransport = class InMemoryTransport { - _otherTransport; - _messageQueue = []; - _closed = false; - onclose; - onerror; - onmessage; - sessionId; - /** - * Creates a pair of linked in-memory transports that can communicate with each other. One should be passed to a {@linkcode @modelcontextprotocol/client!client/client.Client | Client} and one to a {@linkcode @modelcontextprotocol/server!server/server.Server | Server}. - */ - static createLinkedPair() { - const clientTransport = new InMemoryTransport(); - const serverTransport = new InMemoryTransport(); - clientTransport._otherTransport = serverTransport; - serverTransport._otherTransport = clientTransport; - return [clientTransport, serverTransport]; - } - async start() { - while (this._messageQueue.length > 0) { - const queuedMessage = this._messageQueue.shift(); - this.onmessage?.(queuedMessage.message, queuedMessage.extra); - } - } - async close() { - if (this._closed) return; - this._closed = true; - const other = this._otherTransport; - this._otherTransport = void 0; - try { - await other?.close(); - } finally { - this.onclose?.(); - } - } - /** - * Sends a message with optional auth info. - * This is useful for testing authentication scenarios. - */ - async send(message, options) { - if (!this._otherTransport) throw new src_CX2iR2pK_SdkError(src_CX2iR2pK_SdkErrorCode.NotConnected, "Not connected"); - if (this._otherTransport.onmessage) this._otherTransport.onmessage(message, { authInfo: options?.authInfo }); - else this._otherTransport._messageQueue.push({ - message, - extra: { authInfo: options?.authInfo } - }); - } -}; - -//#endregion -//#region ../core-internal/src/util/zodCompat.ts -/** -* Zod-specific helpers for the v1-compat raw-shape shorthand on -* `registerTool`/`registerPrompt`. Kept separate from `standardSchema.ts` so -* that file stays library-agnostic per the Standard Schema spec. -*/ -function isZodV4Schema(v) { - return typeof v === "object" && v !== null && "_zod" in v; -} -function looksLikeZodV3(v) { - return typeof v === "object" && v !== null && !("_zod" in v) && "_def" in v && typeof v._def?.typeName === "string"; -} -/** -* Detects a "raw shape" — a plain object whose values are Zod field schemas, -* e.g. `{ name: z.string() }`. Powers the auto-wrap in -* {@linkcode normalizeRawShapeSchema}, which wraps with `z.object()`, so only -* Zod values are supported. -* -* @internal -*/ -function isZodRawShape(obj) { - if (typeof obj !== "object" || obj === null) return false; - if (isStandardSchema(obj)) return false; - const proto = Object.getPrototypeOf(obj); - if (proto !== Object.prototype && proto !== null) return false; - return Object.values(obj).every((v) => isZodV4Schema(v)); -} -/** -* Accepts either a {@linkcode StandardSchemaWithJSON} or a raw Zod shape -* `{ field: z.string() }` and returns a {@linkcode StandardSchemaWithJSON}. -* Raw shapes are wrapped with `z.object()` so the rest of the pipeline sees a -* uniform schema type; already-wrapped schemas pass through unchanged. -* -* @internal -*/ -function normalizeRawShapeSchema(schema) { - if (schema === void 0) return void 0; - if (isZodRawShape(schema)) return schemas_object(schema); - if (typeof schema === "object" && schema !== null && !isStandardSchema(schema) && Object.values(schema).some((v) => looksLikeZodV3(v))) throw new TypeError("Raw-shape inputSchema/outputSchema/argsSchema fields must be Zod v4 schemas. Got a Zod v3 field schema. Import from `zod/v4` (or upgrade your zod import), or wrap with `z.object({...})` yourself."); - if (!isStandardSchema(schema)) throw new TypeError("inputSchema/outputSchema/argsSchema must be a Standard Schema (e.g. z.object({...})) or a raw Zod shape ({ field: z.string() })."); - return schema; -} - -//#endregion -//#region ../core-internal/src/wire/preload.ts -/** -* Explicit warm-up entry for the lazy wire-schema layers. -* -* The per-revision wire schemas are built lazily: each era's schema set sits -* behind a memoized factory (`buildSchemas2025`/`buildSchemas2026`), and the -* registry/codec lookup maps above those factories are memoized the same way. -* That laziness is the right default on process-per-invocation runtimes (CLI -* tools, dev servers), where module evaluation IS startup latency and most -* short-lived processes never validate a message on both eras. -* -* On platforms that bill request CPU but not module evaluation — isolate-based -* edge/serverless runtimes such as Cloudflare Workers — the trade inverts: -* module-scope work runs during isolate warm-up outside any request, while -* lazy construction lands inside the first request's billed (and latency -* budgeted) CPU. `preloadSchemas()` lets deployments on such platforms move -* the one-time construction cost back to module scope by calling it at module -* scope themselves. The packages' own workerd shims already do this, so -* Workers deployments get eager construction automatically. -*/ -/** -* Eagerly builds every lazily-constructed wire-schema layer, so that no later -* validation pays schema-construction cost. -* -* Synchronous and idempotent: every layer is a memo, so the first call does -* all the work and subsequent calls return immediately. Reference identity is -* unaffected — this forces the same memos every lazy consumer pulls through. -* -* Call it at module scope on platforms that bill per-request CPU but not -* module evaluation (isolate-based edge/serverless runtimes), where deferring -* construction would move it into the first request of every fresh isolate: -* -* ```ts -* // from '@modelcontextprotocol/server' or '@modelcontextprotocol/client' — -* // each package bundles its own schema copy, so warm the one(s) you import. -* preloadSchemas(); // module scope — runs during isolate warm-up -* ``` -* -* On Node CLIs and other process-per-invocation runtimes, prefer the lazy -* default — there, module-scope construction is pure added boot latency. -*/ -function preloadSchemas() { - buildSchemas2025(); - buildSchemas2026(); - warmRegistryMaps2025(); - warmInputSchemaMaps2026(); - warmWireResultSchemas2026(); -} - -//#endregion -//#region ../core-internal/src/validators/fromJsonSchema.ts -/** -* Wrap a raw JSON Schema object as a {@linkcode StandardSchemaWithJSON} so it can be -* passed to `registerTool` / `registerPrompt`. Use this when you already have JSON -* Schema (e.g. from TypeBox, or hand-written) and want to register it without going -* through a Standard Schema library. -* -* The callback arguments will be typed `unknown` (raw JSON Schema has no TypeScript -* types attached). Cast at the call site, or use the generic `fromJsonSchema(...)`. -* -* @param schema - A JSON Schema object describing the expected shape -* @param validator - A validator provider. When importing `fromJsonSchema` from -* `@modelcontextprotocol/server` or `@modelcontextprotocol/client`, a runtime-appropriate -* default is provided automatically (AJV on Node.js, CfWorker on edge runtimes). -* -* @example -* ```ts source="./fromJsonSchema.examples.ts#fromJsonSchema_basicUsage" -* const inputSchema = fromJsonSchema<{ name: string }>( -* { type: 'object', properties: { name: { type: 'string' } }, required: ['name'] }, -* validator -* ); -* // Use with server.registerTool('greet', { inputSchema }, handler) -* ``` -*/ -function fromJsonSchema(schema, validator) { - const check = validator.getValidator(schema); - return { "~standard": { - version: 1, - vendor: "mcp", - jsonSchema: { - input: () => schema, - output: () => schema - }, - validate: (data) => { - const result = check(data); - return result.valid ? { value: result.data } : { issues: [{ message: result.errorMessage }] }; - } - } }; -} - -//#endregion - -//# sourceMappingURL=src-CX2iR2pK.mjs.map - - - -//#region ../../node_modules/.pnpm/ajv@8.18.0/node_modules/ajv/dist/compile/codegen/code.js -var require_code$1 = /* @__PURE__ */ __commonJSMin(((exports) => { - Object.defineProperty(exports, "__esModule", { value: true }); - exports.regexpCode = exports.getEsmExportName = exports.getProperty = exports.safeStringify = exports.stringify = exports.strConcat = exports.addCodeArg = exports.str = exports._ = exports.nil = exports._Code = exports.Name = exports.IDENTIFIER = exports._CodeOrName = void 0; - var _CodeOrName = class {}; - exports._CodeOrName = _CodeOrName; - exports.IDENTIFIER = /^[a-z$_][a-z$_0-9]*$/i; - var Name = class extends _CodeOrName { - constructor(s) { - super(); - if (!exports.IDENTIFIER.test(s)) throw new Error("CodeGen: name must be a valid identifier"); - this.str = s; - } - toString() { - return this.str; - } - emptyStr() { - return false; - } - get names() { - return { [this.str]: 1 }; - } - }; - exports.Name = Name; - var _Code = class extends _CodeOrName { - constructor(code) { - super(); - this._items = typeof code === "string" ? [code] : code; - } - toString() { - return this.str; - } - emptyStr() { - if (this._items.length > 1) return false; - const item = this._items[0]; - return item === "" || item === "\"\""; - } - get str() { - var _a; - return (_a = this._str) !== null && _a !== void 0 ? _a : this._str = this._items.reduce((s, c) => `${s}${c}`, ""); - } - get names() { - var _a; - return (_a = this._names) !== null && _a !== void 0 ? _a : this._names = this._items.reduce((names, c) => { - if (c instanceof Name) names[c.str] = (names[c.str] || 0) + 1; - return names; - }, {}); - } - }; - exports._Code = _Code; - exports.nil = new _Code(""); - function _(strs, ...args) { - const code = [strs[0]]; - let i = 0; - while (i < args.length) { - addCodeArg(code, args[i]); - code.push(strs[++i]); - } - return new _Code(code); - } - exports._ = _; - const plus = new _Code("+"); - function str(strs, ...args) { - const expr = [safeStringify(strs[0])]; - let i = 0; - while (i < args.length) { - expr.push(plus); - addCodeArg(expr, args[i]); - expr.push(plus, safeStringify(strs[++i])); - } - optimize(expr); - return new _Code(expr); - } - exports.str = str; - function addCodeArg(code, arg) { - if (arg instanceof _Code) code.push(...arg._items); - else if (arg instanceof Name) code.push(arg); - else code.push(interpolate(arg)); - } - exports.addCodeArg = addCodeArg; - function optimize(expr) { - let i = 1; - while (i < expr.length - 1) { - if (expr[i] === plus) { - const res = mergeExprItems(expr[i - 1], expr[i + 1]); - if (res !== void 0) { - expr.splice(i - 1, 3, res); - continue; - } - expr[i++] = "+"; - } - i++; - } - } - function mergeExprItems(a, b) { - if (b === "\"\"") return a; - if (a === "\"\"") return b; - if (typeof a == "string") { - if (b instanceof Name || a[a.length - 1] !== "\"") return; - if (typeof b != "string") return `${a.slice(0, -1)}${b}"`; - if (b[0] === "\"") return a.slice(0, -1) + b.slice(1); - return; - } - if (typeof b == "string" && b[0] === "\"" && !(a instanceof Name)) return `"${a}${b.slice(1)}`; - } - function strConcat(c1, c2) { - return c2.emptyStr() ? c1 : c1.emptyStr() ? c2 : str`${c1}${c2}`; - } - exports.strConcat = strConcat; - function interpolate(x) { - return typeof x == "number" || typeof x == "boolean" || x === null ? x : safeStringify(Array.isArray(x) ? x.join(",") : x); - } - function stringify(x) { - return new _Code(safeStringify(x)); - } - exports.stringify = stringify; - function safeStringify(x) { - return JSON.stringify(x).replace(/\u2028/g, "\\u2028").replace(/\u2029/g, "\\u2029"); - } - exports.safeStringify = safeStringify; - function getProperty(key) { - return typeof key == "string" && exports.IDENTIFIER.test(key) ? new _Code(`.${key}`) : _`[${key}]`; - } - exports.getProperty = getProperty; - function getEsmExportName(key) { - if (typeof key == "string" && exports.IDENTIFIER.test(key)) return new _Code(`${key}`); - throw new Error(`CodeGen: invalid export name: ${key}, use explicit $id name mapping`); - } - exports.getEsmExportName = getEsmExportName; - function regexpCode(rx) { - return new _Code(rx.toString()); - } - exports.regexpCode = regexpCode; -})); - -//#endregion -//#region ../../node_modules/.pnpm/ajv@8.18.0/node_modules/ajv/dist/compile/codegen/scope.js -var require_scope = /* @__PURE__ */ __commonJSMin(((exports) => { - Object.defineProperty(exports, "__esModule", { value: true }); - exports.ValueScope = exports.ValueScopeName = exports.Scope = exports.varKinds = exports.UsedValueState = void 0; - const code_1 = require_code$1(); - var ValueError = class extends Error { - constructor(name) { - super(`CodeGen: "code" for ${name} not defined`); - this.value = name.value; - } - }; - var UsedValueState; - (function(UsedValueState) { - UsedValueState[UsedValueState["Started"] = 0] = "Started"; - UsedValueState[UsedValueState["Completed"] = 1] = "Completed"; - })(UsedValueState || (exports.UsedValueState = UsedValueState = {})); - exports.varKinds = { - const: new code_1.Name("const"), - let: new code_1.Name("let"), - var: new code_1.Name("var") - }; - var Scope = class { - constructor({ prefixes, parent } = {}) { - this._names = {}; - this._prefixes = prefixes; - this._parent = parent; - } - toName(nameOrPrefix) { - return nameOrPrefix instanceof code_1.Name ? nameOrPrefix : this.name(nameOrPrefix); - } - name(prefix) { - return new code_1.Name(this._newName(prefix)); - } - _newName(prefix) { - const ng = this._names[prefix] || this._nameGroup(prefix); - return `${prefix}${ng.index++}`; - } - _nameGroup(prefix) { - var _a, _b; - if (((_b = (_a = this._parent) === null || _a === void 0 ? void 0 : _a._prefixes) === null || _b === void 0 ? void 0 : _b.has(prefix)) || this._prefixes && !this._prefixes.has(prefix)) throw new Error(`CodeGen: prefix "${prefix}" is not allowed in this scope`); - return this._names[prefix] = { - prefix, - index: 0 - }; - } - }; - exports.Scope = Scope; - var ValueScopeName = class extends code_1.Name { - constructor(prefix, nameStr) { - super(nameStr); - this.prefix = prefix; - } - setValue(value, { property, itemIndex }) { - this.value = value; - this.scopePath = (0, code_1._)`.${new code_1.Name(property)}[${itemIndex}]`; - } - }; - exports.ValueScopeName = ValueScopeName; - const line = (0, code_1._)`\n`; - var ValueScope = class extends Scope { - constructor(opts) { - super(opts); - this._values = {}; - this._scope = opts.scope; - this.opts = { - ...opts, - _n: opts.lines ? line : code_1.nil - }; - } - get() { - return this._scope; - } - name(prefix) { - return new ValueScopeName(prefix, this._newName(prefix)); - } - value(nameOrPrefix, value) { - var _a; - if (value.ref === void 0) throw new Error("CodeGen: ref must be passed in value"); - const name = this.toName(nameOrPrefix); - const { prefix } = name; - const valueKey = (_a = value.key) !== null && _a !== void 0 ? _a : value.ref; - let vs = this._values[prefix]; - if (vs) { - const _name = vs.get(valueKey); - if (_name) return _name; - } else vs = this._values[prefix] = /* @__PURE__ */ new Map(); - vs.set(valueKey, name); - const s = this._scope[prefix] || (this._scope[prefix] = []); - const itemIndex = s.length; - s[itemIndex] = value.ref; - name.setValue(value, { - property: prefix, - itemIndex - }); - return name; - } - getValue(prefix, keyOrRef) { - const vs = this._values[prefix]; - if (!vs) return; - return vs.get(keyOrRef); - } - scopeRefs(scopeName, values = this._values) { - return this._reduceValues(values, (name) => { - if (name.scopePath === void 0) throw new Error(`CodeGen: name "${name}" has no value`); - return (0, code_1._)`${scopeName}${name.scopePath}`; - }); - } - scopeCode(values = this._values, usedValues, getCode) { - return this._reduceValues(values, (name) => { - if (name.value === void 0) throw new Error(`CodeGen: name "${name}" has no value`); - return name.value.code; - }, usedValues, getCode); - } - _reduceValues(values, valueCode, usedValues = {}, getCode) { - let code = code_1.nil; - for (const prefix in values) { - const vs = values[prefix]; - if (!vs) continue; - const nameSet = usedValues[prefix] = usedValues[prefix] || /* @__PURE__ */ new Map(); - vs.forEach((name) => { - if (nameSet.has(name)) return; - nameSet.set(name, UsedValueState.Started); - let c = valueCode(name); - if (c) { - const def = this.opts.es5 ? exports.varKinds.var : exports.varKinds.const; - code = (0, code_1._)`${code}${def} ${name} = ${c};${this.opts._n}`; - } else if (c = getCode === null || getCode === void 0 ? void 0 : getCode(name)) code = (0, code_1._)`${code}${c}${this.opts._n}`; - else throw new ValueError(name); - nameSet.set(name, UsedValueState.Completed); - }); - } - return code; - } - }; - exports.ValueScope = ValueScope; -})); - -//#endregion -//#region ../../node_modules/.pnpm/ajv@8.18.0/node_modules/ajv/dist/compile/codegen/index.js -var require_codegen = /* @__PURE__ */ __commonJSMin(((exports) => { - Object.defineProperty(exports, "__esModule", { value: true }); - exports.or = exports.and = exports.not = exports.CodeGen = exports.operators = exports.varKinds = exports.ValueScopeName = exports.ValueScope = exports.Scope = exports.Name = exports.regexpCode = exports.stringify = exports.getProperty = exports.nil = exports.strConcat = exports.str = exports._ = void 0; - const code_1 = require_code$1(); - const scope_1 = require_scope(); - var code_2 = require_code$1(); - Object.defineProperty(exports, "_", { - enumerable: true, - get: function() { - return code_2._; - } - }); - Object.defineProperty(exports, "str", { - enumerable: true, - get: function() { - return code_2.str; - } - }); - Object.defineProperty(exports, "strConcat", { - enumerable: true, - get: function() { - return code_2.strConcat; - } - }); - Object.defineProperty(exports, "nil", { - enumerable: true, - get: function() { - return code_2.nil; - } - }); - Object.defineProperty(exports, "getProperty", { - enumerable: true, - get: function() { - return code_2.getProperty; - } - }); - Object.defineProperty(exports, "stringify", { - enumerable: true, - get: function() { - return code_2.stringify; - } - }); - Object.defineProperty(exports, "regexpCode", { - enumerable: true, - get: function() { - return code_2.regexpCode; - } - }); - Object.defineProperty(exports, "Name", { - enumerable: true, - get: function() { - return code_2.Name; - } - }); - var scope_2 = require_scope(); - Object.defineProperty(exports, "Scope", { - enumerable: true, - get: function() { - return scope_2.Scope; - } - }); - Object.defineProperty(exports, "ValueScope", { - enumerable: true, - get: function() { - return scope_2.ValueScope; - } - }); - Object.defineProperty(exports, "ValueScopeName", { - enumerable: true, - get: function() { - return scope_2.ValueScopeName; - } - }); - Object.defineProperty(exports, "varKinds", { - enumerable: true, - get: function() { - return scope_2.varKinds; - } - }); - exports.operators = { - GT: new code_1._Code(">"), - GTE: new code_1._Code(">="), - LT: new code_1._Code("<"), - LTE: new code_1._Code("<="), - EQ: new code_1._Code("==="), - NEQ: new code_1._Code("!=="), - NOT: new code_1._Code("!"), - OR: new code_1._Code("||"), - AND: new code_1._Code("&&"), - ADD: new code_1._Code("+") - }; - var Node = class { - optimizeNodes() { - return this; - } - optimizeNames(_names, _constants) { - return this; - } - }; - var Def = class extends Node { - constructor(varKind, name, rhs) { - super(); - this.varKind = varKind; - this.name = name; - this.rhs = rhs; - } - render({ es5, _n }) { - const varKind = es5 ? scope_1.varKinds.var : this.varKind; - const rhs = this.rhs === void 0 ? "" : ` = ${this.rhs}`; - return `${varKind} ${this.name}${rhs};` + _n; - } - optimizeNames(names, constants) { - if (!names[this.name.str]) return; - if (this.rhs) this.rhs = optimizeExpr(this.rhs, names, constants); - return this; - } - get names() { - return this.rhs instanceof code_1._CodeOrName ? this.rhs.names : {}; - } - }; - var Assign = class extends Node { - constructor(lhs, rhs, sideEffects) { - super(); - this.lhs = lhs; - this.rhs = rhs; - this.sideEffects = sideEffects; - } - render({ _n }) { - return `${this.lhs} = ${this.rhs};` + _n; - } - optimizeNames(names, constants) { - if (this.lhs instanceof code_1.Name && !names[this.lhs.str] && !this.sideEffects) return; - this.rhs = optimizeExpr(this.rhs, names, constants); - return this; - } - get names() { - return addExprNames(this.lhs instanceof code_1.Name ? {} : { ...this.lhs.names }, this.rhs); - } - }; - var AssignOp = class extends Assign { - constructor(lhs, op, rhs, sideEffects) { - super(lhs, rhs, sideEffects); - this.op = op; - } - render({ _n }) { - return `${this.lhs} ${this.op}= ${this.rhs};` + _n; - } - }; - var Label = class extends Node { - constructor(label) { - super(); - this.label = label; - this.names = {}; - } - render({ _n }) { - return `${this.label}:` + _n; - } - }; - var Break = class extends Node { - constructor(label) { - super(); - this.label = label; - this.names = {}; - } - render({ _n }) { - return `break${this.label ? ` ${this.label}` : ""};` + _n; - } - }; - var Throw = class extends Node { - constructor(error) { - super(); - this.error = error; - } - render({ _n }) { - return `throw ${this.error};` + _n; - } - get names() { - return this.error.names; - } - }; - var AnyCode = class extends Node { - constructor(code) { - super(); - this.code = code; - } - render({ _n }) { - return `${this.code};` + _n; - } - optimizeNodes() { - return `${this.code}` ? this : void 0; - } - optimizeNames(names, constants) { - this.code = optimizeExpr(this.code, names, constants); - return this; - } - get names() { - return this.code instanceof code_1._CodeOrName ? this.code.names : {}; - } - }; - var ParentNode = class extends Node { - constructor(nodes = []) { - super(); - this.nodes = nodes; - } - render(opts) { - return this.nodes.reduce((code, n) => code + n.render(opts), ""); - } - optimizeNodes() { - const { nodes } = this; - let i = nodes.length; - while (i--) { - const n = nodes[i].optimizeNodes(); - if (Array.isArray(n)) nodes.splice(i, 1, ...n); - else if (n) nodes[i] = n; - else nodes.splice(i, 1); - } - return nodes.length > 0 ? this : void 0; - } - optimizeNames(names, constants) { - const { nodes } = this; - let i = nodes.length; - while (i--) { - const n = nodes[i]; - if (n.optimizeNames(names, constants)) continue; - subtractNames(names, n.names); - nodes.splice(i, 1); - } - return nodes.length > 0 ? this : void 0; - } - get names() { - return this.nodes.reduce((names, n) => addNames(names, n.names), {}); - } - }; - var BlockNode = class extends ParentNode { - render(opts) { - return "{" + opts._n + super.render(opts) + "}" + opts._n; - } - }; - var Root = class extends ParentNode {}; - var Else = class extends BlockNode {}; - Else.kind = "else"; - var If = class If extends BlockNode { - constructor(condition, nodes) { - super(nodes); - this.condition = condition; - } - render(opts) { - let code = `if(${this.condition})` + super.render(opts); - if (this.else) code += "else " + this.else.render(opts); - return code; - } - optimizeNodes() { - super.optimizeNodes(); - const cond = this.condition; - if (cond === true) return this.nodes; - let e = this.else; - if (e) { - const ns = e.optimizeNodes(); - e = this.else = Array.isArray(ns) ? new Else(ns) : ns; - } - if (e) { - if (cond === false) return e instanceof If ? e : e.nodes; - if (this.nodes.length) return this; - return new If(not(cond), e instanceof If ? [e] : e.nodes); - } - if (cond === false || !this.nodes.length) return void 0; - return this; - } - optimizeNames(names, constants) { - var _a; - this.else = (_a = this.else) === null || _a === void 0 ? void 0 : _a.optimizeNames(names, constants); - if (!(super.optimizeNames(names, constants) || this.else)) return; - this.condition = optimizeExpr(this.condition, names, constants); - return this; - } - get names() { - const names = super.names; - addExprNames(names, this.condition); - if (this.else) addNames(names, this.else.names); - return names; - } - }; - If.kind = "if"; - var For = class extends BlockNode {}; - For.kind = "for"; - var ForLoop = class extends For { - constructor(iteration) { - super(); - this.iteration = iteration; - } - render(opts) { - return `for(${this.iteration})` + super.render(opts); - } - optimizeNames(names, constants) { - if (!super.optimizeNames(names, constants)) return; - this.iteration = optimizeExpr(this.iteration, names, constants); - return this; - } - get names() { - return addNames(super.names, this.iteration.names); - } - }; - var ForRange = class extends For { - constructor(varKind, name, from, to) { - super(); - this.varKind = varKind; - this.name = name; - this.from = from; - this.to = to; - } - render(opts) { - const varKind = opts.es5 ? scope_1.varKinds.var : this.varKind; - const { name, from, to } = this; - return `for(${varKind} ${name}=${from}; ${name}<${to}; ${name}++)` + super.render(opts); - } - get names() { - return addExprNames(addExprNames(super.names, this.from), this.to); - } - }; - var ForIter = class extends For { - constructor(loop, varKind, name, iterable) { - super(); - this.loop = loop; - this.varKind = varKind; - this.name = name; - this.iterable = iterable; - } - render(opts) { - return `for(${this.varKind} ${this.name} ${this.loop} ${this.iterable})` + super.render(opts); - } - optimizeNames(names, constants) { - if (!super.optimizeNames(names, constants)) return; - this.iterable = optimizeExpr(this.iterable, names, constants); - return this; - } - get names() { - return addNames(super.names, this.iterable.names); - } - }; - var Func = class extends BlockNode { - constructor(name, args, async) { - super(); - this.name = name; - this.args = args; - this.async = async; - } - render(opts) { - return `${this.async ? "async " : ""}function ${this.name}(${this.args})` + super.render(opts); - } - }; - Func.kind = "func"; - var Return = class extends ParentNode { - render(opts) { - return "return " + super.render(opts); - } - }; - Return.kind = "return"; - var Try = class extends BlockNode { - render(opts) { - let code = "try" + super.render(opts); - if (this.catch) code += this.catch.render(opts); - if (this.finally) code += this.finally.render(opts); - return code; - } - optimizeNodes() { - var _a, _b; - super.optimizeNodes(); - (_a = this.catch) === null || _a === void 0 || _a.optimizeNodes(); - (_b = this.finally) === null || _b === void 0 || _b.optimizeNodes(); - return this; - } - optimizeNames(names, constants) { - var _a, _b; - super.optimizeNames(names, constants); - (_a = this.catch) === null || _a === void 0 || _a.optimizeNames(names, constants); - (_b = this.finally) === null || _b === void 0 || _b.optimizeNames(names, constants); - return this; - } - get names() { - const names = super.names; - if (this.catch) addNames(names, this.catch.names); - if (this.finally) addNames(names, this.finally.names); - return names; - } - }; - var Catch = class extends BlockNode { - constructor(error) { - super(); - this.error = error; - } - render(opts) { - return `catch(${this.error})` + super.render(opts); - } - }; - Catch.kind = "catch"; - var Finally = class extends BlockNode { - render(opts) { - return "finally" + super.render(opts); - } - }; - Finally.kind = "finally"; - var CodeGen = class { - constructor(extScope, opts = {}) { - this._values = {}; - this._blockStarts = []; - this._constants = {}; - this.opts = { - ...opts, - _n: opts.lines ? "\n" : "" - }; - this._extScope = extScope; - this._scope = new scope_1.Scope({ parent: extScope }); - this._nodes = [new Root()]; - } - toString() { - return this._root.render(this.opts); - } - name(prefix) { - return this._scope.name(prefix); - } - scopeName(prefix) { - return this._extScope.name(prefix); - } - scopeValue(prefixOrName, value) { - const name = this._extScope.value(prefixOrName, value); - (this._values[name.prefix] || (this._values[name.prefix] = /* @__PURE__ */ new Set())).add(name); - return name; - } - getScopeValue(prefix, keyOrRef) { - return this._extScope.getValue(prefix, keyOrRef); - } - scopeRefs(scopeName) { - return this._extScope.scopeRefs(scopeName, this._values); - } - scopeCode() { - return this._extScope.scopeCode(this._values); - } - _def(varKind, nameOrPrefix, rhs, constant) { - const name = this._scope.toName(nameOrPrefix); - if (rhs !== void 0 && constant) this._constants[name.str] = rhs; - this._leafNode(new Def(varKind, name, rhs)); - return name; - } - const(nameOrPrefix, rhs, _constant) { - return this._def(scope_1.varKinds.const, nameOrPrefix, rhs, _constant); - } - let(nameOrPrefix, rhs, _constant) { - return this._def(scope_1.varKinds.let, nameOrPrefix, rhs, _constant); - } - var(nameOrPrefix, rhs, _constant) { - return this._def(scope_1.varKinds.var, nameOrPrefix, rhs, _constant); - } - assign(lhs, rhs, sideEffects) { - return this._leafNode(new Assign(lhs, rhs, sideEffects)); - } - add(lhs, rhs) { - return this._leafNode(new AssignOp(lhs, exports.operators.ADD, rhs)); - } - code(c) { - if (typeof c == "function") c(); - else if (c !== code_1.nil) this._leafNode(new AnyCode(c)); - return this; - } - object(...keyValues) { - const code = ["{"]; - for (const [key, value] of keyValues) { - if (code.length > 1) code.push(","); - code.push(key); - if (key !== value || this.opts.es5) { - code.push(":"); - (0, code_1.addCodeArg)(code, value); - } - } - code.push("}"); - return new code_1._Code(code); - } - if(condition, thenBody, elseBody) { - this._blockNode(new If(condition)); - if (thenBody && elseBody) this.code(thenBody).else().code(elseBody).endIf(); - else if (thenBody) this.code(thenBody).endIf(); - else if (elseBody) throw new Error("CodeGen: \"else\" body without \"then\" body"); - return this; - } - elseIf(condition) { - return this._elseNode(new If(condition)); - } - else() { - return this._elseNode(new Else()); - } - endIf() { - return this._endBlockNode(If, Else); - } - _for(node, forBody) { - this._blockNode(node); - if (forBody) this.code(forBody).endFor(); - return this; - } - for(iteration, forBody) { - return this._for(new ForLoop(iteration), forBody); - } - forRange(nameOrPrefix, from, to, forBody, varKind = this.opts.es5 ? scope_1.varKinds.var : scope_1.varKinds.let) { - const name = this._scope.toName(nameOrPrefix); - return this._for(new ForRange(varKind, name, from, to), () => forBody(name)); - } - forOf(nameOrPrefix, iterable, forBody, varKind = scope_1.varKinds.const) { - const name = this._scope.toName(nameOrPrefix); - if (this.opts.es5) { - const arr = iterable instanceof code_1.Name ? iterable : this.var("_arr", iterable); - return this.forRange("_i", 0, (0, code_1._)`${arr}.length`, (i) => { - this.var(name, (0, code_1._)`${arr}[${i}]`); - forBody(name); - }); - } - return this._for(new ForIter("of", varKind, name, iterable), () => forBody(name)); - } - forIn(nameOrPrefix, obj, forBody, varKind = this.opts.es5 ? scope_1.varKinds.var : scope_1.varKinds.const) { - if (this.opts.ownProperties) return this.forOf(nameOrPrefix, (0, code_1._)`Object.keys(${obj})`, forBody); - const name = this._scope.toName(nameOrPrefix); - return this._for(new ForIter("in", varKind, name, obj), () => forBody(name)); - } - endFor() { - return this._endBlockNode(For); - } - label(label) { - return this._leafNode(new Label(label)); - } - break(label) { - return this._leafNode(new Break(label)); - } - return(value) { - const node = new Return(); - this._blockNode(node); - this.code(value); - if (node.nodes.length !== 1) throw new Error("CodeGen: \"return\" should have one node"); - return this._endBlockNode(Return); - } - try(tryBody, catchCode, finallyCode) { - if (!catchCode && !finallyCode) throw new Error("CodeGen: \"try\" without \"catch\" and \"finally\""); - const node = new Try(); - this._blockNode(node); - this.code(tryBody); - if (catchCode) { - const error = this.name("e"); - this._currNode = node.catch = new Catch(error); - catchCode(error); - } - if (finallyCode) { - this._currNode = node.finally = new Finally(); - this.code(finallyCode); - } - return this._endBlockNode(Catch, Finally); - } - throw(error) { - return this._leafNode(new Throw(error)); - } - block(body, nodeCount) { - this._blockStarts.push(this._nodes.length); - if (body) this.code(body).endBlock(nodeCount); - return this; - } - endBlock(nodeCount) { - const len = this._blockStarts.pop(); - if (len === void 0) throw new Error("CodeGen: not in self-balancing block"); - const toClose = this._nodes.length - len; - if (toClose < 0 || nodeCount !== void 0 && toClose !== nodeCount) throw new Error(`CodeGen: wrong number of nodes: ${toClose} vs ${nodeCount} expected`); - this._nodes.length = len; - return this; - } - func(name, args = code_1.nil, async, funcBody) { - this._blockNode(new Func(name, args, async)); - if (funcBody) this.code(funcBody).endFunc(); - return this; - } - endFunc() { - return this._endBlockNode(Func); - } - optimize(n = 1) { - while (n-- > 0) { - this._root.optimizeNodes(); - this._root.optimizeNames(this._root.names, this._constants); - } - } - _leafNode(node) { - this._currNode.nodes.push(node); - return this; - } - _blockNode(node) { - this._currNode.nodes.push(node); - this._nodes.push(node); - } - _endBlockNode(N1, N2) { - const n = this._currNode; - if (n instanceof N1 || N2 && n instanceof N2) { - this._nodes.pop(); - return this; - } - throw new Error(`CodeGen: not in block "${N2 ? `${N1.kind}/${N2.kind}` : N1.kind}"`); - } - _elseNode(node) { - const n = this._currNode; - if (!(n instanceof If)) throw new Error("CodeGen: \"else\" without \"if\""); - this._currNode = n.else = node; - return this; - } - get _root() { - return this._nodes[0]; - } - get _currNode() { - const ns = this._nodes; - return ns[ns.length - 1]; - } - set _currNode(node) { - const ns = this._nodes; - ns[ns.length - 1] = node; - } - }; - exports.CodeGen = CodeGen; - function addNames(names, from) { - for (const n in from) names[n] = (names[n] || 0) + (from[n] || 0); - return names; - } - function addExprNames(names, from) { - return from instanceof code_1._CodeOrName ? addNames(names, from.names) : names; - } - function optimizeExpr(expr, names, constants) { - if (expr instanceof code_1.Name) return replaceName(expr); - if (!canOptimize(expr)) return expr; - return new code_1._Code(expr._items.reduce((items, c) => { - if (c instanceof code_1.Name) c = replaceName(c); - if (c instanceof code_1._Code) items.push(...c._items); - else items.push(c); - return items; - }, [])); - function replaceName(n) { - const c = constants[n.str]; - if (c === void 0 || names[n.str] !== 1) return n; - delete names[n.str]; - return c; - } - function canOptimize(e) { - return e instanceof code_1._Code && e._items.some((c) => c instanceof code_1.Name && names[c.str] === 1 && constants[c.str] !== void 0); - } - } - function subtractNames(names, from) { - for (const n in from) names[n] = (names[n] || 0) - (from[n] || 0); - } - function not(x) { - return typeof x == "boolean" || typeof x == "number" || x === null ? !x : (0, code_1._)`!${par(x)}`; - } - exports.not = not; - const andCode = mappend(exports.operators.AND); - function and(...args) { - return args.reduce(andCode); - } - exports.and = and; - const orCode = mappend(exports.operators.OR); - function or(...args) { - return args.reduce(orCode); - } - exports.or = or; - function mappend(op) { - return (x, y) => x === code_1.nil ? y : y === code_1.nil ? x : (0, code_1._)`${par(x)} ${op} ${par(y)}`; - } - function par(x) { - return x instanceof code_1.Name ? x : (0, code_1._)`(${x})`; - } -})); - -//#endregion -//#region ../../node_modules/.pnpm/ajv@8.18.0/node_modules/ajv/dist/compile/util.js -var require_util = /* @__PURE__ */ __commonJSMin(((exports) => { - Object.defineProperty(exports, "__esModule", { value: true }); - exports.checkStrictMode = exports.getErrorPath = exports.Type = exports.useFunc = exports.setEvaluated = exports.evaluatedPropsToName = exports.mergeEvaluated = exports.eachItem = exports.unescapeJsonPointer = exports.escapeJsonPointer = exports.escapeFragment = exports.unescapeFragment = exports.schemaRefOrVal = exports.schemaHasRulesButRef = exports.schemaHasRules = exports.checkUnknownRules = exports.alwaysValidSchema = exports.toHash = void 0; - const codegen_1 = require_codegen(); - const code_1 = require_code$1(); - function toHash(arr) { - const hash = {}; - for (const item of arr) hash[item] = true; - return hash; - } - exports.toHash = toHash; - function alwaysValidSchema(it, schema) { - if (typeof schema == "boolean") return schema; - if (Object.keys(schema).length === 0) return true; - checkUnknownRules(it, schema); - return !schemaHasRules(schema, it.self.RULES.all); - } - exports.alwaysValidSchema = alwaysValidSchema; - function checkUnknownRules(it, schema = it.schema) { - const { opts, self } = it; - if (!opts.strictSchema) return; - if (typeof schema === "boolean") return; - const rules = self.RULES.keywords; - for (const key in schema) if (!rules[key]) checkStrictMode(it, `unknown keyword: "${key}"`); - } - exports.checkUnknownRules = checkUnknownRules; - function schemaHasRules(schema, rules) { - if (typeof schema == "boolean") return !schema; - for (const key in schema) if (rules[key]) return true; - return false; - } - exports.schemaHasRules = schemaHasRules; - function schemaHasRulesButRef(schema, RULES) { - if (typeof schema == "boolean") return !schema; - for (const key in schema) if (key !== "$ref" && RULES.all[key]) return true; - return false; - } - exports.schemaHasRulesButRef = schemaHasRulesButRef; - function schemaRefOrVal({ topSchemaRef, schemaPath }, schema, keyword, $data) { - if (!$data) { - if (typeof schema == "number" || typeof schema == "boolean") return schema; - if (typeof schema == "string") return (0, codegen_1._)`${schema}`; - } - return (0, codegen_1._)`${topSchemaRef}${schemaPath}${(0, codegen_1.getProperty)(keyword)}`; - } - exports.schemaRefOrVal = schemaRefOrVal; - function unescapeFragment(str) { - return unescapeJsonPointer(decodeURIComponent(str)); - } - exports.unescapeFragment = unescapeFragment; - function escapeFragment(str) { - return encodeURIComponent(escapeJsonPointer(str)); - } - exports.escapeFragment = escapeFragment; - function escapeJsonPointer(str) { - if (typeof str == "number") return `${str}`; - return str.replace(/~/g, "~0").replace(/\//g, "~1"); - } - exports.escapeJsonPointer = escapeJsonPointer; - function unescapeJsonPointer(str) { - return str.replace(/~1/g, "/").replace(/~0/g, "~"); - } - exports.unescapeJsonPointer = unescapeJsonPointer; - function eachItem(xs, f) { - if (Array.isArray(xs)) for (const x of xs) f(x); - else f(xs); - } - exports.eachItem = eachItem; - function makeMergeEvaluated({ mergeNames, mergeToName, mergeValues, resultToName }) { - return (gen, from, to, toName) => { - const res = to === void 0 ? from : to instanceof codegen_1.Name ? (from instanceof codegen_1.Name ? mergeNames(gen, from, to) : mergeToName(gen, from, to), to) : from instanceof codegen_1.Name ? (mergeToName(gen, to, from), from) : mergeValues(from, to); - return toName === codegen_1.Name && !(res instanceof codegen_1.Name) ? resultToName(gen, res) : res; - }; - } - exports.mergeEvaluated = { - props: makeMergeEvaluated({ - mergeNames: (gen, from, to) => gen.if((0, codegen_1._)`${to} !== true && ${from} !== undefined`, () => { - gen.if((0, codegen_1._)`${from} === true`, () => gen.assign(to, true), () => gen.assign(to, (0, codegen_1._)`${to} || {}`).code((0, codegen_1._)`Object.assign(${to}, ${from})`)); - }), - mergeToName: (gen, from, to) => gen.if((0, codegen_1._)`${to} !== true`, () => { - if (from === true) gen.assign(to, true); - else { - gen.assign(to, (0, codegen_1._)`${to} || {}`); - setEvaluated(gen, to, from); - } - }), - mergeValues: (from, to) => from === true ? true : { - ...from, - ...to - }, - resultToName: evaluatedPropsToName - }), - items: makeMergeEvaluated({ - mergeNames: (gen, from, to) => gen.if((0, codegen_1._)`${to} !== true && ${from} !== undefined`, () => gen.assign(to, (0, codegen_1._)`${from} === true ? true : ${to} > ${from} ? ${to} : ${from}`)), - mergeToName: (gen, from, to) => gen.if((0, codegen_1._)`${to} !== true`, () => gen.assign(to, from === true ? true : (0, codegen_1._)`${to} > ${from} ? ${to} : ${from}`)), - mergeValues: (from, to) => from === true ? true : Math.max(from, to), - resultToName: (gen, items) => gen.var("items", items) - }) - }; - function evaluatedPropsToName(gen, ps) { - if (ps === true) return gen.var("props", true); - const props = gen.var("props", (0, codegen_1._)`{}`); - if (ps !== void 0) setEvaluated(gen, props, ps); - return props; - } - exports.evaluatedPropsToName = evaluatedPropsToName; - function setEvaluated(gen, props, ps) { - Object.keys(ps).forEach((p) => gen.assign((0, codegen_1._)`${props}${(0, codegen_1.getProperty)(p)}`, true)); - } - exports.setEvaluated = setEvaluated; - const snippets = {}; - function useFunc(gen, f) { - return gen.scopeValue("func", { - ref: f, - code: snippets[f.code] || (snippets[f.code] = new code_1._Code(f.code)) - }); - } - exports.useFunc = useFunc; - var Type; - (function(Type) { - Type[Type["Num"] = 0] = "Num"; - Type[Type["Str"] = 1] = "Str"; - })(Type || (exports.Type = Type = {})); - function getErrorPath(dataProp, dataPropType, jsPropertySyntax) { - if (dataProp instanceof codegen_1.Name) { - const isNumber = dataPropType === Type.Num; - return jsPropertySyntax ? isNumber ? (0, codegen_1._)`"[" + ${dataProp} + "]"` : (0, codegen_1._)`"['" + ${dataProp} + "']"` : isNumber ? (0, codegen_1._)`"/" + ${dataProp}` : (0, codegen_1._)`"/" + ${dataProp}.replace(/~/g, "~0").replace(/\\//g, "~1")`; - } - return jsPropertySyntax ? (0, codegen_1.getProperty)(dataProp).toString() : "/" + escapeJsonPointer(dataProp); - } - exports.getErrorPath = getErrorPath; - function checkStrictMode(it, msg, mode = it.opts.strictSchema) { - if (!mode) return; - msg = `strict mode: ${msg}`; - if (mode === true) throw new Error(msg); - it.self.logger.warn(msg); - } - exports.checkStrictMode = checkStrictMode; -})); - -//#endregion -//#region ../../node_modules/.pnpm/ajv@8.18.0/node_modules/ajv/dist/compile/names.js -var require_names = /* @__PURE__ */ __commonJSMin(((exports) => { - Object.defineProperty(exports, "__esModule", { value: true }); - const codegen_1 = require_codegen(); - const names = { - data: new codegen_1.Name("data"), - valCxt: new codegen_1.Name("valCxt"), - instancePath: new codegen_1.Name("instancePath"), - parentData: new codegen_1.Name("parentData"), - parentDataProperty: new codegen_1.Name("parentDataProperty"), - rootData: new codegen_1.Name("rootData"), - dynamicAnchors: new codegen_1.Name("dynamicAnchors"), - vErrors: new codegen_1.Name("vErrors"), - errors: new codegen_1.Name("errors"), - this: new codegen_1.Name("this"), - self: new codegen_1.Name("self"), - scope: new codegen_1.Name("scope"), - json: new codegen_1.Name("json"), - jsonPos: new codegen_1.Name("jsonPos"), - jsonLen: new codegen_1.Name("jsonLen"), - jsonPart: new codegen_1.Name("jsonPart") - }; - exports.default = names; -})); - -//#endregion -//#region ../../node_modules/.pnpm/ajv@8.18.0/node_modules/ajv/dist/compile/errors.js -var require_errors = /* @__PURE__ */ __commonJSMin(((exports) => { - Object.defineProperty(exports, "__esModule", { value: true }); - exports.extendErrors = exports.resetErrorsCount = exports.reportExtraError = exports.reportError = exports.keyword$DataError = exports.keywordError = void 0; - const codegen_1 = require_codegen(); - const util_1 = require_util(); - const names_1 = require_names(); - exports.keywordError = { message: ({ keyword }) => (0, codegen_1.str)`must pass "${keyword}" keyword validation` }; - exports.keyword$DataError = { message: ({ keyword, schemaType }) => schemaType ? (0, codegen_1.str)`"${keyword}" keyword must be ${schemaType} ($data)` : (0, codegen_1.str)`"${keyword}" keyword is invalid ($data)` }; - function reportError(cxt, error = exports.keywordError, errorPaths, overrideAllErrors) { - const { it } = cxt; - const { gen, compositeRule, allErrors } = it; - const errObj = errorObjectCode(cxt, error, errorPaths); - if (overrideAllErrors !== null && overrideAllErrors !== void 0 ? overrideAllErrors : compositeRule || allErrors) addError(gen, errObj); - else returnErrors(it, (0, codegen_1._)`[${errObj}]`); - } - exports.reportError = reportError; - function reportExtraError(cxt, error = exports.keywordError, errorPaths) { - const { it } = cxt; - const { gen, compositeRule, allErrors } = it; - addError(gen, errorObjectCode(cxt, error, errorPaths)); - if (!(compositeRule || allErrors)) returnErrors(it, names_1.default.vErrors); - } - exports.reportExtraError = reportExtraError; - function resetErrorsCount(gen, errsCount) { - gen.assign(names_1.default.errors, errsCount); - gen.if((0, codegen_1._)`${names_1.default.vErrors} !== null`, () => gen.if(errsCount, () => gen.assign((0, codegen_1._)`${names_1.default.vErrors}.length`, errsCount), () => gen.assign(names_1.default.vErrors, null))); - } - exports.resetErrorsCount = resetErrorsCount; - function extendErrors({ gen, keyword, schemaValue, data, errsCount, it }) { - /* istanbul ignore if */ - if (errsCount === void 0) throw new Error("ajv implementation error"); - const err = gen.name("err"); - gen.forRange("i", errsCount, names_1.default.errors, (i) => { - gen.const(err, (0, codegen_1._)`${names_1.default.vErrors}[${i}]`); - gen.if((0, codegen_1._)`${err}.instancePath === undefined`, () => gen.assign((0, codegen_1._)`${err}.instancePath`, (0, codegen_1.strConcat)(names_1.default.instancePath, it.errorPath))); - gen.assign((0, codegen_1._)`${err}.schemaPath`, (0, codegen_1.str)`${it.errSchemaPath}/${keyword}`); - if (it.opts.verbose) { - gen.assign((0, codegen_1._)`${err}.schema`, schemaValue); - gen.assign((0, codegen_1._)`${err}.data`, data); - } - }); - } - exports.extendErrors = extendErrors; - function addError(gen, errObj) { - const err = gen.const("err", errObj); - gen.if((0, codegen_1._)`${names_1.default.vErrors} === null`, () => gen.assign(names_1.default.vErrors, (0, codegen_1._)`[${err}]`), (0, codegen_1._)`${names_1.default.vErrors}.push(${err})`); - gen.code((0, codegen_1._)`${names_1.default.errors}++`); - } - function returnErrors(it, errs) { - const { gen, validateName, schemaEnv } = it; - if (schemaEnv.$async) gen.throw((0, codegen_1._)`new ${it.ValidationError}(${errs})`); - else { - gen.assign((0, codegen_1._)`${validateName}.errors`, errs); - gen.return(false); - } - } - const E = { - keyword: new codegen_1.Name("keyword"), - schemaPath: new codegen_1.Name("schemaPath"), - params: new codegen_1.Name("params"), - propertyName: new codegen_1.Name("propertyName"), - message: new codegen_1.Name("message"), - schema: new codegen_1.Name("schema"), - parentSchema: new codegen_1.Name("parentSchema") - }; - function errorObjectCode(cxt, error, errorPaths) { - const { createErrors } = cxt.it; - if (createErrors === false) return (0, codegen_1._)`{}`; - return errorObject(cxt, error, errorPaths); - } - function errorObject(cxt, error, errorPaths = {}) { - const { gen, it } = cxt; - const keyValues = [errorInstancePath(it, errorPaths), errorSchemaPath(cxt, errorPaths)]; - extraErrorProps(cxt, error, keyValues); - return gen.object(...keyValues); - } - function errorInstancePath({ errorPath }, { instancePath }) { - const instPath = instancePath ? (0, codegen_1.str)`${errorPath}${(0, util_1.getErrorPath)(instancePath, util_1.Type.Str)}` : errorPath; - return [names_1.default.instancePath, (0, codegen_1.strConcat)(names_1.default.instancePath, instPath)]; - } - function errorSchemaPath({ keyword, it: { errSchemaPath } }, { schemaPath, parentSchema }) { - let schPath = parentSchema ? errSchemaPath : (0, codegen_1.str)`${errSchemaPath}/${keyword}`; - if (schemaPath) schPath = (0, codegen_1.str)`${schPath}${(0, util_1.getErrorPath)(schemaPath, util_1.Type.Str)}`; - return [E.schemaPath, schPath]; - } - function extraErrorProps(cxt, { params, message }, keyValues) { - const { keyword, data, schemaValue, it } = cxt; - const { opts, propertyName, topSchemaRef, schemaPath } = it; - keyValues.push([E.keyword, keyword], [E.params, typeof params == "function" ? params(cxt) : params || (0, codegen_1._)`{}`]); - if (opts.messages) keyValues.push([E.message, typeof message == "function" ? message(cxt) : message]); - if (opts.verbose) keyValues.push([E.schema, schemaValue], [E.parentSchema, (0, codegen_1._)`${topSchemaRef}${schemaPath}`], [names_1.default.data, data]); - if (propertyName) keyValues.push([E.propertyName, propertyName]); - } -})); - -//#endregion -//#region ../../node_modules/.pnpm/ajv@8.18.0/node_modules/ajv/dist/compile/validate/boolSchema.js -var require_boolSchema = /* @__PURE__ */ __commonJSMin(((exports) => { - Object.defineProperty(exports, "__esModule", { value: true }); - exports.boolOrEmptySchema = exports.topBoolOrEmptySchema = void 0; - const errors_1 = require_errors(); - const codegen_1 = require_codegen(); - const names_1 = require_names(); - const boolError = { message: "boolean schema is false" }; - function topBoolOrEmptySchema(it) { - const { gen, schema, validateName } = it; - if (schema === false) falseSchemaError(it, false); - else if (typeof schema == "object" && schema.$async === true) gen.return(names_1.default.data); - else { - gen.assign((0, codegen_1._)`${validateName}.errors`, null); - gen.return(true); - } - } - exports.topBoolOrEmptySchema = topBoolOrEmptySchema; - function boolOrEmptySchema(it, valid) { - const { gen, schema } = it; - if (schema === false) { - gen.var(valid, false); - falseSchemaError(it); - } else gen.var(valid, true); - } - exports.boolOrEmptySchema = boolOrEmptySchema; - function falseSchemaError(it, overrideAllErrors) { - const { gen, data } = it; - const cxt = { - gen, - keyword: "false schema", - data, - schema: false, - schemaCode: false, - schemaValue: false, - params: {}, - it - }; - (0, errors_1.reportError)(cxt, boolError, void 0, overrideAllErrors); - } -})); - -//#endregion -//#region ../../node_modules/.pnpm/ajv@8.18.0/node_modules/ajv/dist/compile/rules.js -var require_rules = /* @__PURE__ */ __commonJSMin(((exports) => { - Object.defineProperty(exports, "__esModule", { value: true }); - exports.getRules = exports.isJSONType = void 0; - const jsonTypes = new Set([ - "string", - "number", - "integer", - "boolean", - "null", - "object", - "array" - ]); - function isJSONType(x) { - return typeof x == "string" && jsonTypes.has(x); - } - exports.isJSONType = isJSONType; - function getRules() { - const groups = { - number: { - type: "number", - rules: [] - }, - string: { - type: "string", - rules: [] - }, - array: { - type: "array", - rules: [] - }, - object: { - type: "object", - rules: [] - } - }; - return { - types: { - ...groups, - integer: true, - boolean: true, - null: true - }, - rules: [ - { rules: [] }, - groups.number, - groups.string, - groups.array, - groups.object - ], - post: { rules: [] }, - all: {}, - keywords: {} - }; - } - exports.getRules = getRules; -})); - -//#endregion -//#region ../../node_modules/.pnpm/ajv@8.18.0/node_modules/ajv/dist/compile/validate/applicability.js -var require_applicability = /* @__PURE__ */ __commonJSMin(((exports) => { - Object.defineProperty(exports, "__esModule", { value: true }); - exports.shouldUseRule = exports.shouldUseGroup = exports.schemaHasRulesForType = void 0; - function schemaHasRulesForType({ schema, self }, type) { - const group = self.RULES.types[type]; - return group && group !== true && shouldUseGroup(schema, group); - } - exports.schemaHasRulesForType = schemaHasRulesForType; - function shouldUseGroup(schema, group) { - return group.rules.some((rule) => shouldUseRule(schema, rule)); - } - exports.shouldUseGroup = shouldUseGroup; - function shouldUseRule(schema, rule) { - var _a; - return schema[rule.keyword] !== void 0 || ((_a = rule.definition.implements) === null || _a === void 0 ? void 0 : _a.some((kwd) => schema[kwd] !== void 0)); - } - exports.shouldUseRule = shouldUseRule; -})); - -//#endregion -//#region ../../node_modules/.pnpm/ajv@8.18.0/node_modules/ajv/dist/compile/validate/dataType.js -var require_dataType = /* @__PURE__ */ __commonJSMin(((exports) => { - Object.defineProperty(exports, "__esModule", { value: true }); - exports.reportTypeError = exports.checkDataTypes = exports.checkDataType = exports.coerceAndCheckDataType = exports.getJSONTypes = exports.getSchemaTypes = exports.DataType = void 0; - const rules_1 = require_rules(); - const applicability_1 = require_applicability(); - const errors_1 = require_errors(); - const codegen_1 = require_codegen(); - const util_1 = require_util(); - var DataType; - (function(DataType) { - DataType[DataType["Correct"] = 0] = "Correct"; - DataType[DataType["Wrong"] = 1] = "Wrong"; - })(DataType || (exports.DataType = DataType = {})); - function getSchemaTypes(schema) { - const types = getJSONTypes(schema.type); - if (types.includes("null")) { - if (schema.nullable === false) throw new Error("type: null contradicts nullable: false"); - } else { - if (!types.length && schema.nullable !== void 0) throw new Error("\"nullable\" cannot be used without \"type\""); - if (schema.nullable === true) types.push("null"); - } - return types; - } - exports.getSchemaTypes = getSchemaTypes; - function getJSONTypes(ts) { - const types = Array.isArray(ts) ? ts : ts ? [ts] : []; - if (types.every(rules_1.isJSONType)) return types; - throw new Error("type must be JSONType or JSONType[]: " + types.join(",")); - } - exports.getJSONTypes = getJSONTypes; - function coerceAndCheckDataType(it, types) { - const { gen, data, opts } = it; - const coerceTo = coerceToTypes(types, opts.coerceTypes); - const checkTypes = types.length > 0 && !(coerceTo.length === 0 && types.length === 1 && (0, applicability_1.schemaHasRulesForType)(it, types[0])); - if (checkTypes) { - const wrongType = checkDataTypes(types, data, opts.strictNumbers, DataType.Wrong); - gen.if(wrongType, () => { - if (coerceTo.length) coerceData(it, types, coerceTo); - else reportTypeError(it); - }); - } - return checkTypes; - } - exports.coerceAndCheckDataType = coerceAndCheckDataType; - const COERCIBLE = new Set([ - "string", - "number", - "integer", - "boolean", - "null" - ]); - function coerceToTypes(types, coerceTypes) { - return coerceTypes ? types.filter((t) => COERCIBLE.has(t) || coerceTypes === "array" && t === "array") : []; - } - function coerceData(it, types, coerceTo) { - const { gen, data, opts } = it; - const dataType = gen.let("dataType", (0, codegen_1._)`typeof ${data}`); - const coerced = gen.let("coerced", (0, codegen_1._)`undefined`); - if (opts.coerceTypes === "array") gen.if((0, codegen_1._)`${dataType} == 'object' && Array.isArray(${data}) && ${data}.length == 1`, () => gen.assign(data, (0, codegen_1._)`${data}[0]`).assign(dataType, (0, codegen_1._)`typeof ${data}`).if(checkDataTypes(types, data, opts.strictNumbers), () => gen.assign(coerced, data))); - gen.if((0, codegen_1._)`${coerced} !== undefined`); - for (const t of coerceTo) if (COERCIBLE.has(t) || t === "array" && opts.coerceTypes === "array") coerceSpecificType(t); - gen.else(); - reportTypeError(it); - gen.endIf(); - gen.if((0, codegen_1._)`${coerced} !== undefined`, () => { - gen.assign(data, coerced); - assignParentData(it, coerced); - }); - function coerceSpecificType(t) { - switch (t) { - case "string": - gen.elseIf((0, codegen_1._)`${dataType} == "number" || ${dataType} == "boolean"`).assign(coerced, (0, codegen_1._)`"" + ${data}`).elseIf((0, codegen_1._)`${data} === null`).assign(coerced, (0, codegen_1._)`""`); - return; - case "number": - gen.elseIf((0, codegen_1._)`${dataType} == "boolean" || ${data} === null - || (${dataType} == "string" && ${data} && ${data} == +${data})`).assign(coerced, (0, codegen_1._)`+${data}`); - return; - case "integer": - gen.elseIf((0, codegen_1._)`${dataType} === "boolean" || ${data} === null - || (${dataType} === "string" && ${data} && ${data} == +${data} && !(${data} % 1))`).assign(coerced, (0, codegen_1._)`+${data}`); - return; - case "boolean": - gen.elseIf((0, codegen_1._)`${data} === "false" || ${data} === 0 || ${data} === null`).assign(coerced, false).elseIf((0, codegen_1._)`${data} === "true" || ${data} === 1`).assign(coerced, true); - return; - case "null": - gen.elseIf((0, codegen_1._)`${data} === "" || ${data} === 0 || ${data} === false`); - gen.assign(coerced, null); - return; - case "array": gen.elseIf((0, codegen_1._)`${dataType} === "string" || ${dataType} === "number" - || ${dataType} === "boolean" || ${data} === null`).assign(coerced, (0, codegen_1._)`[${data}]`); - } - } - } - function assignParentData({ gen, parentData, parentDataProperty }, expr) { - gen.if((0, codegen_1._)`${parentData} !== undefined`, () => gen.assign((0, codegen_1._)`${parentData}[${parentDataProperty}]`, expr)); - } - function checkDataType(dataType, data, strictNums, correct = DataType.Correct) { - const EQ = correct === DataType.Correct ? codegen_1.operators.EQ : codegen_1.operators.NEQ; - let cond; - switch (dataType) { - case "null": return (0, codegen_1._)`${data} ${EQ} null`; - case "array": - cond = (0, codegen_1._)`Array.isArray(${data})`; - break; - case "object": - cond = (0, codegen_1._)`${data} && typeof ${data} == "object" && !Array.isArray(${data})`; - break; - case "integer": - cond = numCond((0, codegen_1._)`!(${data} % 1) && !isNaN(${data})`); - break; - case "number": - cond = numCond(); - break; - default: return (0, codegen_1._)`typeof ${data} ${EQ} ${dataType}`; - } - return correct === DataType.Correct ? cond : (0, codegen_1.not)(cond); - function numCond(_cond = codegen_1.nil) { - return (0, codegen_1.and)((0, codegen_1._)`typeof ${data} == "number"`, _cond, strictNums ? (0, codegen_1._)`isFinite(${data})` : codegen_1.nil); - } - } - exports.checkDataType = checkDataType; - function checkDataTypes(dataTypes, data, strictNums, correct) { - if (dataTypes.length === 1) return checkDataType(dataTypes[0], data, strictNums, correct); - let cond; - const types = (0, util_1.toHash)(dataTypes); - if (types.array && types.object) { - const notObj = (0, codegen_1._)`typeof ${data} != "object"`; - cond = types.null ? notObj : (0, codegen_1._)`!${data} || ${notObj}`; - delete types.null; - delete types.array; - delete types.object; - } else cond = codegen_1.nil; - if (types.number) delete types.integer; - for (const t in types) cond = (0, codegen_1.and)(cond, checkDataType(t, data, strictNums, correct)); - return cond; - } - exports.checkDataTypes = checkDataTypes; - const typeError = { - message: ({ schema }) => `must be ${schema}`, - params: ({ schema, schemaValue }) => typeof schema == "string" ? (0, codegen_1._)`{type: ${schema}}` : (0, codegen_1._)`{type: ${schemaValue}}` - }; - function reportTypeError(it) { - const cxt = getTypeErrorContext(it); - (0, errors_1.reportError)(cxt, typeError); - } - exports.reportTypeError = reportTypeError; - function getTypeErrorContext(it) { - const { gen, data, schema } = it; - const schemaCode = (0, util_1.schemaRefOrVal)(it, schema, "type"); - return { - gen, - keyword: "type", - data, - schema: schema.type, - schemaCode, - schemaValue: schemaCode, - parentSchema: schema, - params: {}, - it - }; - } -})); - -//#endregion -//#region ../../node_modules/.pnpm/ajv@8.18.0/node_modules/ajv/dist/compile/validate/defaults.js -var require_defaults = /* @__PURE__ */ __commonJSMin(((exports) => { - Object.defineProperty(exports, "__esModule", { value: true }); - exports.assignDefaults = void 0; - const codegen_1 = require_codegen(); - const util_1 = require_util(); - function assignDefaults(it, ty) { - const { properties, items } = it.schema; - if (ty === "object" && properties) for (const key in properties) assignDefault(it, key, properties[key].default); - else if (ty === "array" && Array.isArray(items)) items.forEach((sch, i) => assignDefault(it, i, sch.default)); - } - exports.assignDefaults = assignDefaults; - function assignDefault(it, prop, defaultValue) { - const { gen, compositeRule, data, opts } = it; - if (defaultValue === void 0) return; - const childData = (0, codegen_1._)`${data}${(0, codegen_1.getProperty)(prop)}`; - if (compositeRule) { - (0, util_1.checkStrictMode)(it, `default is ignored for: ${childData}`); - return; - } - let condition = (0, codegen_1._)`${childData} === undefined`; - if (opts.useDefaults === "empty") condition = (0, codegen_1._)`${condition} || ${childData} === null || ${childData} === ""`; - gen.if(condition, (0, codegen_1._)`${childData} = ${(0, codegen_1.stringify)(defaultValue)}`); - } -})); - -//#endregion -//#region ../../node_modules/.pnpm/ajv@8.18.0/node_modules/ajv/dist/vocabularies/code.js -var require_code = /* @__PURE__ */ __commonJSMin(((exports) => { - Object.defineProperty(exports, "__esModule", { value: true }); - exports.validateUnion = exports.validateArray = exports.usePattern = exports.callValidateCode = exports.schemaProperties = exports.allSchemaProperties = exports.noPropertyInData = exports.propertyInData = exports.isOwnProperty = exports.hasPropFunc = exports.reportMissingProp = exports.checkMissingProp = exports.checkReportMissingProp = void 0; - const codegen_1 = require_codegen(); - const util_1 = require_util(); - const names_1 = require_names(); - const util_2 = require_util(); - function checkReportMissingProp(cxt, prop) { - const { gen, data, it } = cxt; - gen.if(noPropertyInData(gen, data, prop, it.opts.ownProperties), () => { - cxt.setParams({ missingProperty: (0, codegen_1._)`${prop}` }, true); - cxt.error(); - }); - } - exports.checkReportMissingProp = checkReportMissingProp; - function checkMissingProp({ gen, data, it: { opts } }, properties, missing) { - return (0, codegen_1.or)(...properties.map((prop) => (0, codegen_1.and)(noPropertyInData(gen, data, prop, opts.ownProperties), (0, codegen_1._)`${missing} = ${prop}`))); - } - exports.checkMissingProp = checkMissingProp; - function reportMissingProp(cxt, missing) { - cxt.setParams({ missingProperty: missing }, true); - cxt.error(); - } - exports.reportMissingProp = reportMissingProp; - function hasPropFunc(gen) { - return gen.scopeValue("func", { - ref: Object.prototype.hasOwnProperty, - code: (0, codegen_1._)`Object.prototype.hasOwnProperty` - }); - } - exports.hasPropFunc = hasPropFunc; - function isOwnProperty(gen, data, property) { - return (0, codegen_1._)`${hasPropFunc(gen)}.call(${data}, ${property})`; - } - exports.isOwnProperty = isOwnProperty; - function propertyInData(gen, data, property, ownProperties) { - const cond = (0, codegen_1._)`${data}${(0, codegen_1.getProperty)(property)} !== undefined`; - return ownProperties ? (0, codegen_1._)`${cond} && ${isOwnProperty(gen, data, property)}` : cond; - } - exports.propertyInData = propertyInData; - function noPropertyInData(gen, data, property, ownProperties) { - const cond = (0, codegen_1._)`${data}${(0, codegen_1.getProperty)(property)} === undefined`; - return ownProperties ? (0, codegen_1.or)(cond, (0, codegen_1.not)(isOwnProperty(gen, data, property))) : cond; - } - exports.noPropertyInData = noPropertyInData; - function allSchemaProperties(schemaMap) { - return schemaMap ? Object.keys(schemaMap).filter((p) => p !== "__proto__") : []; - } - exports.allSchemaProperties = allSchemaProperties; - function schemaProperties(it, schemaMap) { - return allSchemaProperties(schemaMap).filter((p) => !(0, util_1.alwaysValidSchema)(it, schemaMap[p])); - } - exports.schemaProperties = schemaProperties; - function callValidateCode({ schemaCode, data, it: { gen, topSchemaRef, schemaPath, errorPath }, it }, func, context, passSchema) { - const dataAndSchema = passSchema ? (0, codegen_1._)`${schemaCode}, ${data}, ${topSchemaRef}${schemaPath}` : data; - const valCxt = [ - [names_1.default.instancePath, (0, codegen_1.strConcat)(names_1.default.instancePath, errorPath)], - [names_1.default.parentData, it.parentData], - [names_1.default.parentDataProperty, it.parentDataProperty], - [names_1.default.rootData, names_1.default.rootData] - ]; - if (it.opts.dynamicRef) valCxt.push([names_1.default.dynamicAnchors, names_1.default.dynamicAnchors]); - const args = (0, codegen_1._)`${dataAndSchema}, ${gen.object(...valCxt)}`; - return context !== codegen_1.nil ? (0, codegen_1._)`${func}.call(${context}, ${args})` : (0, codegen_1._)`${func}(${args})`; - } - exports.callValidateCode = callValidateCode; - const newRegExp = (0, codegen_1._)`new RegExp`; - function usePattern({ gen, it: { opts } }, pattern) { - const u = opts.unicodeRegExp ? "u" : ""; - const { regExp } = opts.code; - const rx = regExp(pattern, u); - return gen.scopeValue("pattern", { - key: rx.toString(), - ref: rx, - code: (0, codegen_1._)`${regExp.code === "new RegExp" ? newRegExp : (0, util_2.useFunc)(gen, regExp)}(${pattern}, ${u})` - }); - } - exports.usePattern = usePattern; - function validateArray(cxt) { - const { gen, data, keyword, it } = cxt; - const valid = gen.name("valid"); - if (it.allErrors) { - const validArr = gen.let("valid", true); - validateItems(() => gen.assign(validArr, false)); - return validArr; - } - gen.var(valid, true); - validateItems(() => gen.break()); - return valid; - function validateItems(notValid) { - const len = gen.const("len", (0, codegen_1._)`${data}.length`); - gen.forRange("i", 0, len, (i) => { - cxt.subschema({ - keyword, - dataProp: i, - dataPropType: util_1.Type.Num - }, valid); - gen.if((0, codegen_1.not)(valid), notValid); - }); - } - } - exports.validateArray = validateArray; - function validateUnion(cxt) { - const { gen, schema, keyword, it } = cxt; - /* istanbul ignore if */ - if (!Array.isArray(schema)) throw new Error("ajv implementation error"); - if (schema.some((sch) => (0, util_1.alwaysValidSchema)(it, sch)) && !it.opts.unevaluated) return; - const valid = gen.let("valid", false); - const schValid = gen.name("_valid"); - gen.block(() => schema.forEach((_sch, i) => { - const schCxt = cxt.subschema({ - keyword, - schemaProp: i, - compositeRule: true - }, schValid); - gen.assign(valid, (0, codegen_1._)`${valid} || ${schValid}`); - if (!cxt.mergeValidEvaluated(schCxt, schValid)) gen.if((0, codegen_1.not)(valid)); - })); - cxt.result(valid, () => cxt.reset(), () => cxt.error(true)); - } - exports.validateUnion = validateUnion; -})); - -//#endregion -//#region ../../node_modules/.pnpm/ajv@8.18.0/node_modules/ajv/dist/compile/validate/keyword.js -var require_keyword = /* @__PURE__ */ __commonJSMin(((exports) => { - Object.defineProperty(exports, "__esModule", { value: true }); - exports.validateKeywordUsage = exports.validSchemaType = exports.funcKeywordCode = exports.macroKeywordCode = void 0; - const codegen_1 = require_codegen(); - const names_1 = require_names(); - const code_1 = require_code(); - const errors_1 = require_errors(); - function macroKeywordCode(cxt, def) { - const { gen, keyword, schema, parentSchema, it } = cxt; - const macroSchema = def.macro.call(it.self, schema, parentSchema, it); - const schemaRef = useKeyword(gen, keyword, macroSchema); - if (it.opts.validateSchema !== false) it.self.validateSchema(macroSchema, true); - const valid = gen.name("valid"); - cxt.subschema({ - schema: macroSchema, - schemaPath: codegen_1.nil, - errSchemaPath: `${it.errSchemaPath}/${keyword}`, - topSchemaRef: schemaRef, - compositeRule: true - }, valid); - cxt.pass(valid, () => cxt.error(true)); - } - exports.macroKeywordCode = macroKeywordCode; - function funcKeywordCode(cxt, def) { - var _a; - const { gen, keyword, schema, parentSchema, $data, it } = cxt; - checkAsyncKeyword(it, def); - const validateRef = useKeyword(gen, keyword, !$data && def.compile ? def.compile.call(it.self, schema, parentSchema, it) : def.validate); - const valid = gen.let("valid"); - cxt.block$data(valid, validateKeyword); - cxt.ok((_a = def.valid) !== null && _a !== void 0 ? _a : valid); - function validateKeyword() { - if (def.errors === false) { - assignValid(); - if (def.modifying) modifyData(cxt); - reportErrs(() => cxt.error()); - } else { - const ruleErrs = def.async ? validateAsync() : validateSync(); - if (def.modifying) modifyData(cxt); - reportErrs(() => addErrs(cxt, ruleErrs)); - } - } - function validateAsync() { - const ruleErrs = gen.let("ruleErrs", null); - gen.try(() => assignValid((0, codegen_1._)`await `), (e) => gen.assign(valid, false).if((0, codegen_1._)`${e} instanceof ${it.ValidationError}`, () => gen.assign(ruleErrs, (0, codegen_1._)`${e}.errors`), () => gen.throw(e))); - return ruleErrs; - } - function validateSync() { - const validateErrs = (0, codegen_1._)`${validateRef}.errors`; - gen.assign(validateErrs, null); - assignValid(codegen_1.nil); - return validateErrs; - } - function assignValid(_await = def.async ? (0, codegen_1._)`await ` : codegen_1.nil) { - const passCxt = it.opts.passContext ? names_1.default.this : names_1.default.self; - const passSchema = !("compile" in def && !$data || def.schema === false); - gen.assign(valid, (0, codegen_1._)`${_await}${(0, code_1.callValidateCode)(cxt, validateRef, passCxt, passSchema)}`, def.modifying); - } - function reportErrs(errors) { - var _a$1; - gen.if((0, codegen_1.not)((_a$1 = def.valid) !== null && _a$1 !== void 0 ? _a$1 : valid), errors); - } - } - exports.funcKeywordCode = funcKeywordCode; - function modifyData(cxt) { - const { gen, data, it } = cxt; - gen.if(it.parentData, () => gen.assign(data, (0, codegen_1._)`${it.parentData}[${it.parentDataProperty}]`)); - } - function addErrs(cxt, errs) { - const { gen } = cxt; - gen.if((0, codegen_1._)`Array.isArray(${errs})`, () => { - gen.assign(names_1.default.vErrors, (0, codegen_1._)`${names_1.default.vErrors} === null ? ${errs} : ${names_1.default.vErrors}.concat(${errs})`).assign(names_1.default.errors, (0, codegen_1._)`${names_1.default.vErrors}.length`); - (0, errors_1.extendErrors)(cxt); - }, () => cxt.error()); - } - function checkAsyncKeyword({ schemaEnv }, def) { - if (def.async && !schemaEnv.$async) throw new Error("async keyword in sync schema"); - } - function useKeyword(gen, keyword, result) { - if (result === void 0) throw new Error(`keyword "${keyword}" failed to compile`); - return gen.scopeValue("keyword", typeof result == "function" ? { ref: result } : { - ref: result, - code: (0, codegen_1.stringify)(result) - }); - } - function validSchemaType(schema, schemaType, allowUndefined = false) { - return !schemaType.length || schemaType.some((st) => st === "array" ? Array.isArray(schema) : st === "object" ? schema && typeof schema == "object" && !Array.isArray(schema) : typeof schema == st || allowUndefined && typeof schema == "undefined"); - } - exports.validSchemaType = validSchemaType; - function validateKeywordUsage({ schema, opts, self, errSchemaPath }, def, keyword) { - /* istanbul ignore if */ - if (Array.isArray(def.keyword) ? !def.keyword.includes(keyword) : def.keyword !== keyword) throw new Error("ajv implementation error"); - const deps = def.dependencies; - if (deps === null || deps === void 0 ? void 0 : deps.some((kwd) => !Object.prototype.hasOwnProperty.call(schema, kwd))) throw new Error(`parent schema must have dependencies of ${keyword}: ${deps.join(",")}`); - if (def.validateSchema) { - if (!def.validateSchema(schema[keyword])) { - const msg = `keyword "${keyword}" value is invalid at path "${errSchemaPath}": ` + self.errorsText(def.validateSchema.errors); - if (opts.validateSchema === "log") self.logger.error(msg); - else throw new Error(msg); - } - } - } - exports.validateKeywordUsage = validateKeywordUsage; -})); - -//#endregion -//#region ../../node_modules/.pnpm/ajv@8.18.0/node_modules/ajv/dist/compile/validate/subschema.js -var require_subschema = /* @__PURE__ */ __commonJSMin(((exports) => { - Object.defineProperty(exports, "__esModule", { value: true }); - exports.extendSubschemaMode = exports.extendSubschemaData = exports.getSubschema = void 0; - const codegen_1 = require_codegen(); - const util_1 = require_util(); - function getSubschema(it, { keyword, schemaProp, schema, schemaPath, errSchemaPath, topSchemaRef }) { - if (keyword !== void 0 && schema !== void 0) throw new Error("both \"keyword\" and \"schema\" passed, only one allowed"); - if (keyword !== void 0) { - const sch = it.schema[keyword]; - return schemaProp === void 0 ? { - schema: sch, - schemaPath: (0, codegen_1._)`${it.schemaPath}${(0, codegen_1.getProperty)(keyword)}`, - errSchemaPath: `${it.errSchemaPath}/${keyword}` - } : { - schema: sch[schemaProp], - schemaPath: (0, codegen_1._)`${it.schemaPath}${(0, codegen_1.getProperty)(keyword)}${(0, codegen_1.getProperty)(schemaProp)}`, - errSchemaPath: `${it.errSchemaPath}/${keyword}/${(0, util_1.escapeFragment)(schemaProp)}` - }; - } - if (schema !== void 0) { - if (schemaPath === void 0 || errSchemaPath === void 0 || topSchemaRef === void 0) throw new Error("\"schemaPath\", \"errSchemaPath\" and \"topSchemaRef\" are required with \"schema\""); - return { - schema, - schemaPath, - topSchemaRef, - errSchemaPath - }; - } - throw new Error("either \"keyword\" or \"schema\" must be passed"); - } - exports.getSubschema = getSubschema; - function extendSubschemaData(subschema, it, { dataProp, dataPropType: dpType, data, dataTypes, propertyName }) { - if (data !== void 0 && dataProp !== void 0) throw new Error("both \"data\" and \"dataProp\" passed, only one allowed"); - const { gen } = it; - if (dataProp !== void 0) { - const { errorPath, dataPathArr, opts } = it; - dataContextProps(gen.let("data", (0, codegen_1._)`${it.data}${(0, codegen_1.getProperty)(dataProp)}`, true)); - subschema.errorPath = (0, codegen_1.str)`${errorPath}${(0, util_1.getErrorPath)(dataProp, dpType, opts.jsPropertySyntax)}`; - subschema.parentDataProperty = (0, codegen_1._)`${dataProp}`; - subschema.dataPathArr = [...dataPathArr, subschema.parentDataProperty]; - } - if (data !== void 0) { - dataContextProps(data instanceof codegen_1.Name ? data : gen.let("data", data, true)); - if (propertyName !== void 0) subschema.propertyName = propertyName; - } - if (dataTypes) subschema.dataTypes = dataTypes; - function dataContextProps(_nextData) { - subschema.data = _nextData; - subschema.dataLevel = it.dataLevel + 1; - subschema.dataTypes = []; - it.definedProperties = /* @__PURE__ */ new Set(); - subschema.parentData = it.data; - subschema.dataNames = [...it.dataNames, _nextData]; - } - } - exports.extendSubschemaData = extendSubschemaData; - function extendSubschemaMode(subschema, { jtdDiscriminator, jtdMetadata, compositeRule, createErrors, allErrors }) { - if (compositeRule !== void 0) subschema.compositeRule = compositeRule; - if (createErrors !== void 0) subschema.createErrors = createErrors; - if (allErrors !== void 0) subschema.allErrors = allErrors; - subschema.jtdDiscriminator = jtdDiscriminator; - subschema.jtdMetadata = jtdMetadata; - } - exports.extendSubschemaMode = extendSubschemaMode; -})); - -//#endregion -//#region ../../node_modules/.pnpm/fast-deep-equal@3.1.3/node_modules/fast-deep-equal/index.js -var require_fast_deep_equal = /* @__PURE__ */ __commonJSMin(((exports, module) => { - module.exports = function equal(a, b) { - if (a === b) return true; - if (a && b && typeof a == "object" && typeof b == "object") { - if (a.constructor !== b.constructor) return false; - var length, i, keys; - if (Array.isArray(a)) { - length = a.length; - if (length != b.length) return false; - for (i = length; i-- !== 0;) if (!equal(a[i], b[i])) return false; - return true; - } - if (a.constructor === RegExp) return a.source === b.source && a.flags === b.flags; - if (a.valueOf !== Object.prototype.valueOf) return a.valueOf() === b.valueOf(); - if (a.toString !== Object.prototype.toString) return a.toString() === b.toString(); - keys = Object.keys(a); - length = keys.length; - if (length !== Object.keys(b).length) return false; - for (i = length; i-- !== 0;) if (!Object.prototype.hasOwnProperty.call(b, keys[i])) return false; - for (i = length; i-- !== 0;) { - var key = keys[i]; - if (!equal(a[key], b[key])) return false; - } - return true; - } - return a !== a && b !== b; - }; -})); - -//#endregion -//#region ../../node_modules/.pnpm/json-schema-traverse@1.0.0/node_modules/json-schema-traverse/index.js -var require_json_schema_traverse = /* @__PURE__ */ __commonJSMin(((exports, module) => { - var traverse = module.exports = function(schema, opts, cb) { - if (typeof opts == "function") { - cb = opts; - opts = {}; - } - cb = opts.cb || cb; - var pre = typeof cb == "function" ? cb : cb.pre || function() {}; - var post = cb.post || function() {}; - _traverse(opts, pre, post, schema, "", schema); - }; - traverse.keywords = { - additionalItems: true, - items: true, - contains: true, - additionalProperties: true, - propertyNames: true, - not: true, - if: true, - then: true, - else: true - }; - traverse.arrayKeywords = { - items: true, - allOf: true, - anyOf: true, - oneOf: true - }; - traverse.propsKeywords = { - $defs: true, - definitions: true, - properties: true, - patternProperties: true, - dependencies: true - }; - traverse.skipKeywords = { - default: true, - enum: true, - const: true, - required: true, - maximum: true, - minimum: true, - exclusiveMaximum: true, - exclusiveMinimum: true, - multipleOf: true, - maxLength: true, - minLength: true, - pattern: true, - format: true, - maxItems: true, - minItems: true, - uniqueItems: true, - maxProperties: true, - minProperties: true - }; - function _traverse(opts, pre, post, schema, jsonPtr, rootSchema, parentJsonPtr, parentKeyword, parentSchema, keyIndex) { - if (schema && typeof schema == "object" && !Array.isArray(schema)) { - pre(schema, jsonPtr, rootSchema, parentJsonPtr, parentKeyword, parentSchema, keyIndex); - for (var key in schema) { - var sch = schema[key]; - if (Array.isArray(sch)) { - if (key in traverse.arrayKeywords) for (var i = 0; i < sch.length; i++) _traverse(opts, pre, post, sch[i], jsonPtr + "/" + key + "/" + i, rootSchema, jsonPtr, key, schema, i); - } else if (key in traverse.propsKeywords) { - if (sch && typeof sch == "object") for (var prop in sch) _traverse(opts, pre, post, sch[prop], jsonPtr + "/" + key + "/" + escapeJsonPtr(prop), rootSchema, jsonPtr, key, schema, prop); - } else if (key in traverse.keywords || opts.allKeys && !(key in traverse.skipKeywords)) _traverse(opts, pre, post, sch, jsonPtr + "/" + key, rootSchema, jsonPtr, key, schema); - } - post(schema, jsonPtr, rootSchema, parentJsonPtr, parentKeyword, parentSchema, keyIndex); - } - } - function escapeJsonPtr(str) { - return str.replace(/~/g, "~0").replace(/\//g, "~1"); - } -})); - -//#endregion -//#region ../../node_modules/.pnpm/ajv@8.18.0/node_modules/ajv/dist/compile/resolve.js -var require_resolve = /* @__PURE__ */ __commonJSMin(((exports) => { - Object.defineProperty(exports, "__esModule", { value: true }); - exports.getSchemaRefs = exports.resolveUrl = exports.normalizeId = exports._getFullPath = exports.getFullPath = exports.inlineRef = void 0; - const util_1 = require_util(); - const equal = require_fast_deep_equal(); - const traverse = require_json_schema_traverse(); - const SIMPLE_INLINED = new Set([ - "type", - "format", - "pattern", - "maxLength", - "minLength", - "maxProperties", - "minProperties", - "maxItems", - "minItems", - "maximum", - "minimum", - "uniqueItems", - "multipleOf", - "required", - "enum", - "const" - ]); - function inlineRef(schema, limit = true) { - if (typeof schema == "boolean") return true; - if (limit === true) return !hasRef(schema); - if (!limit) return false; - return countKeys(schema) <= limit; - } - exports.inlineRef = inlineRef; - const REF_KEYWORDS = new Set([ - "$ref", - "$recursiveRef", - "$recursiveAnchor", - "$dynamicRef", - "$dynamicAnchor" - ]); - function hasRef(schema) { - for (const key in schema) { - if (REF_KEYWORDS.has(key)) return true; - const sch = schema[key]; - if (Array.isArray(sch) && sch.some(hasRef)) return true; - if (typeof sch == "object" && hasRef(sch)) return true; - } - return false; - } - function countKeys(schema) { - let count = 0; - for (const key in schema) { - if (key === "$ref") return Infinity; - count++; - if (SIMPLE_INLINED.has(key)) continue; - if (typeof schema[key] == "object") (0, util_1.eachItem)(schema[key], (sch) => count += countKeys(sch)); - if (count === Infinity) return Infinity; - } - return count; - } - function getFullPath(resolver, id = "", normalize) { - if (normalize !== false) id = normalizeId(id); - return _getFullPath(resolver, resolver.parse(id)); - } - exports.getFullPath = getFullPath; - function _getFullPath(resolver, p) { - return resolver.serialize(p).split("#")[0] + "#"; - } - exports._getFullPath = _getFullPath; - const TRAILING_SLASH_HASH = /#\/?$/; - function normalizeId(id) { - return id ? id.replace(TRAILING_SLASH_HASH, "") : ""; - } - exports.normalizeId = normalizeId; - function resolveUrl(resolver, baseId, id) { - id = normalizeId(id); - return resolver.resolve(baseId, id); - } - exports.resolveUrl = resolveUrl; - const ANCHOR = /^[a-z_][-a-z0-9._]*$/i; - function getSchemaRefs(schema, baseId) { - if (typeof schema == "boolean") return {}; - const { schemaId, uriResolver } = this.opts; - const schId = normalizeId(schema[schemaId] || baseId); - const baseIds = { "": schId }; - const pathPrefix = getFullPath(uriResolver, schId, false); - const localRefs = {}; - const schemaRefs = /* @__PURE__ */ new Set(); - traverse(schema, { allKeys: true }, (sch, jsonPtr, _, parentJsonPtr) => { - if (parentJsonPtr === void 0) return; - const fullPath = pathPrefix + jsonPtr; - let innerBaseId = baseIds[parentJsonPtr]; - if (typeof sch[schemaId] == "string") innerBaseId = addRef.call(this, sch[schemaId]); - addAnchor.call(this, sch.$anchor); - addAnchor.call(this, sch.$dynamicAnchor); - baseIds[jsonPtr] = innerBaseId; - function addRef(ref) { - const _resolve = this.opts.uriResolver.resolve; - ref = normalizeId(innerBaseId ? _resolve(innerBaseId, ref) : ref); - if (schemaRefs.has(ref)) throw ambiguos(ref); - schemaRefs.add(ref); - let schOrRef = this.refs[ref]; - if (typeof schOrRef == "string") schOrRef = this.refs[schOrRef]; - if (typeof schOrRef == "object") checkAmbiguosRef(sch, schOrRef.schema, ref); - else if (ref !== normalizeId(fullPath)) if (ref[0] === "#") { - checkAmbiguosRef(sch, localRefs[ref], ref); - localRefs[ref] = sch; - } else this.refs[ref] = fullPath; - return ref; - } - function addAnchor(anchor) { - if (typeof anchor == "string") { - if (!ANCHOR.test(anchor)) throw new Error(`invalid anchor "${anchor}"`); - addRef.call(this, `#${anchor}`); - } - } - }); - return localRefs; - function checkAmbiguosRef(sch1, sch2, ref) { - if (sch2 !== void 0 && !equal(sch1, sch2)) throw ambiguos(ref); - } - function ambiguos(ref) { - return /* @__PURE__ */ new Error(`reference "${ref}" resolves to more than one schema`); - } - } - exports.getSchemaRefs = getSchemaRefs; -})); - -//#endregion -//#region ../../node_modules/.pnpm/ajv@8.18.0/node_modules/ajv/dist/compile/validate/index.js -var require_validate = /* @__PURE__ */ __commonJSMin(((exports) => { - Object.defineProperty(exports, "__esModule", { value: true }); - exports.getData = exports.KeywordCxt = exports.validateFunctionCode = void 0; - const boolSchema_1 = require_boolSchema(); - const dataType_1 = require_dataType(); - const applicability_1 = require_applicability(); - const dataType_2 = require_dataType(); - const defaults_1 = require_defaults(); - const keyword_1 = require_keyword(); - const subschema_1 = require_subschema(); - const codegen_1 = require_codegen(); - const names_1 = require_names(); - const resolve_1 = require_resolve(); - const util_1 = require_util(); - const errors_1 = require_errors(); - function validateFunctionCode(it) { - if (isSchemaObj(it)) { - checkKeywords(it); - if (schemaCxtHasRules(it)) { - topSchemaObjCode(it); - return; - } - } - validateFunction(it, () => (0, boolSchema_1.topBoolOrEmptySchema)(it)); - } - exports.validateFunctionCode = validateFunctionCode; - function validateFunction({ gen, validateName, schema, schemaEnv, opts }, body) { - if (opts.code.es5) gen.func(validateName, (0, codegen_1._)`${names_1.default.data}, ${names_1.default.valCxt}`, schemaEnv.$async, () => { - gen.code((0, codegen_1._)`"use strict"; ${funcSourceUrl(schema, opts)}`); - destructureValCxtES5(gen, opts); - gen.code(body); - }); - else gen.func(validateName, (0, codegen_1._)`${names_1.default.data}, ${destructureValCxt(opts)}`, schemaEnv.$async, () => gen.code(funcSourceUrl(schema, opts)).code(body)); - } - function destructureValCxt(opts) { - return (0, codegen_1._)`{${names_1.default.instancePath}="", ${names_1.default.parentData}, ${names_1.default.parentDataProperty}, ${names_1.default.rootData}=${names_1.default.data}${opts.dynamicRef ? (0, codegen_1._)`, ${names_1.default.dynamicAnchors}={}` : codegen_1.nil}}={}`; - } - function destructureValCxtES5(gen, opts) { - gen.if(names_1.default.valCxt, () => { - gen.var(names_1.default.instancePath, (0, codegen_1._)`${names_1.default.valCxt}.${names_1.default.instancePath}`); - gen.var(names_1.default.parentData, (0, codegen_1._)`${names_1.default.valCxt}.${names_1.default.parentData}`); - gen.var(names_1.default.parentDataProperty, (0, codegen_1._)`${names_1.default.valCxt}.${names_1.default.parentDataProperty}`); - gen.var(names_1.default.rootData, (0, codegen_1._)`${names_1.default.valCxt}.${names_1.default.rootData}`); - if (opts.dynamicRef) gen.var(names_1.default.dynamicAnchors, (0, codegen_1._)`${names_1.default.valCxt}.${names_1.default.dynamicAnchors}`); - }, () => { - gen.var(names_1.default.instancePath, (0, codegen_1._)`""`); - gen.var(names_1.default.parentData, (0, codegen_1._)`undefined`); - gen.var(names_1.default.parentDataProperty, (0, codegen_1._)`undefined`); - gen.var(names_1.default.rootData, names_1.default.data); - if (opts.dynamicRef) gen.var(names_1.default.dynamicAnchors, (0, codegen_1._)`{}`); - }); - } - function topSchemaObjCode(it) { - const { schema, opts, gen } = it; - validateFunction(it, () => { - if (opts.$comment && schema.$comment) commentKeyword(it); - checkNoDefault(it); - gen.let(names_1.default.vErrors, null); - gen.let(names_1.default.errors, 0); - if (opts.unevaluated) resetEvaluated(it); - typeAndKeywords(it); - returnResults(it); - }); - } - function resetEvaluated(it) { - const { gen, validateName } = it; - it.evaluated = gen.const("evaluated", (0, codegen_1._)`${validateName}.evaluated`); - gen.if((0, codegen_1._)`${it.evaluated}.dynamicProps`, () => gen.assign((0, codegen_1._)`${it.evaluated}.props`, (0, codegen_1._)`undefined`)); - gen.if((0, codegen_1._)`${it.evaluated}.dynamicItems`, () => gen.assign((0, codegen_1._)`${it.evaluated}.items`, (0, codegen_1._)`undefined`)); - } - function funcSourceUrl(schema, opts) { - const schId = typeof schema == "object" && schema[opts.schemaId]; - return schId && (opts.code.source || opts.code.process) ? (0, codegen_1._)`/*# sourceURL=${schId} */` : codegen_1.nil; - } - function subschemaCode(it, valid) { - if (isSchemaObj(it)) { - checkKeywords(it); - if (schemaCxtHasRules(it)) { - subSchemaObjCode(it, valid); - return; - } - } - (0, boolSchema_1.boolOrEmptySchema)(it, valid); - } - function schemaCxtHasRules({ schema, self }) { - if (typeof schema == "boolean") return !schema; - for (const key in schema) if (self.RULES.all[key]) return true; - return false; - } - function isSchemaObj(it) { - return typeof it.schema != "boolean"; - } - function subSchemaObjCode(it, valid) { - const { schema, gen, opts } = it; - if (opts.$comment && schema.$comment) commentKeyword(it); - updateContext(it); - checkAsyncSchema(it); - const errsCount = gen.const("_errs", names_1.default.errors); - typeAndKeywords(it, errsCount); - gen.var(valid, (0, codegen_1._)`${errsCount} === ${names_1.default.errors}`); - } - function checkKeywords(it) { - (0, util_1.checkUnknownRules)(it); - checkRefsAndKeywords(it); - } - function typeAndKeywords(it, errsCount) { - if (it.opts.jtd) return schemaKeywords(it, [], false, errsCount); - const types = (0, dataType_1.getSchemaTypes)(it.schema); - schemaKeywords(it, types, !(0, dataType_1.coerceAndCheckDataType)(it, types), errsCount); - } - function checkRefsAndKeywords(it) { - const { schema, errSchemaPath, opts, self } = it; - if (schema.$ref && opts.ignoreKeywordsWithRef && (0, util_1.schemaHasRulesButRef)(schema, self.RULES)) self.logger.warn(`$ref: keywords ignored in schema at path "${errSchemaPath}"`); - } - function checkNoDefault(it) { - const { schema, opts } = it; - if (schema.default !== void 0 && opts.useDefaults && opts.strictSchema) (0, util_1.checkStrictMode)(it, "default is ignored in the schema root"); - } - function updateContext(it) { - const schId = it.schema[it.opts.schemaId]; - if (schId) it.baseId = (0, resolve_1.resolveUrl)(it.opts.uriResolver, it.baseId, schId); - } - function checkAsyncSchema(it) { - if (it.schema.$async && !it.schemaEnv.$async) throw new Error("async schema in sync schema"); - } - function commentKeyword({ gen, schemaEnv, schema, errSchemaPath, opts }) { - const msg = schema.$comment; - if (opts.$comment === true) gen.code((0, codegen_1._)`${names_1.default.self}.logger.log(${msg})`); - else if (typeof opts.$comment == "function") { - const schemaPath = (0, codegen_1.str)`${errSchemaPath}/$comment`; - const rootName = gen.scopeValue("root", { ref: schemaEnv.root }); - gen.code((0, codegen_1._)`${names_1.default.self}.opts.$comment(${msg}, ${schemaPath}, ${rootName}.schema)`); - } - } - function returnResults(it) { - const { gen, schemaEnv, validateName, ValidationError, opts } = it; - if (schemaEnv.$async) gen.if((0, codegen_1._)`${names_1.default.errors} === 0`, () => gen.return(names_1.default.data), () => gen.throw((0, codegen_1._)`new ${ValidationError}(${names_1.default.vErrors})`)); - else { - gen.assign((0, codegen_1._)`${validateName}.errors`, names_1.default.vErrors); - if (opts.unevaluated) assignEvaluated(it); - gen.return((0, codegen_1._)`${names_1.default.errors} === 0`); - } - } - function assignEvaluated({ gen, evaluated, props, items }) { - if (props instanceof codegen_1.Name) gen.assign((0, codegen_1._)`${evaluated}.props`, props); - if (items instanceof codegen_1.Name) gen.assign((0, codegen_1._)`${evaluated}.items`, items); - } - function schemaKeywords(it, types, typeErrors, errsCount) { - const { gen, schema, data, allErrors, opts, self } = it; - const { RULES } = self; - if (schema.$ref && (opts.ignoreKeywordsWithRef || !(0, util_1.schemaHasRulesButRef)(schema, RULES))) { - gen.block(() => keywordCode(it, "$ref", RULES.all.$ref.definition)); - return; - } - if (!opts.jtd) checkStrictTypes(it, types); - gen.block(() => { - for (const group of RULES.rules) groupKeywords(group); - groupKeywords(RULES.post); - }); - function groupKeywords(group) { - if (!(0, applicability_1.shouldUseGroup)(schema, group)) return; - if (group.type) { - gen.if((0, dataType_2.checkDataType)(group.type, data, opts.strictNumbers)); - iterateKeywords(it, group); - if (types.length === 1 && types[0] === group.type && typeErrors) { - gen.else(); - (0, dataType_2.reportTypeError)(it); - } - gen.endIf(); - } else iterateKeywords(it, group); - if (!allErrors) gen.if((0, codegen_1._)`${names_1.default.errors} === ${errsCount || 0}`); - } - } - function iterateKeywords(it, group) { - const { gen, schema, opts: { useDefaults } } = it; - if (useDefaults) (0, defaults_1.assignDefaults)(it, group.type); - gen.block(() => { - for (const rule of group.rules) if ((0, applicability_1.shouldUseRule)(schema, rule)) keywordCode(it, rule.keyword, rule.definition, group.type); - }); - } - function checkStrictTypes(it, types) { - if (it.schemaEnv.meta || !it.opts.strictTypes) return; - checkContextTypes(it, types); - if (!it.opts.allowUnionTypes) checkMultipleTypes(it, types); - checkKeywordTypes(it, it.dataTypes); - } - function checkContextTypes(it, types) { - if (!types.length) return; - if (!it.dataTypes.length) { - it.dataTypes = types; - return; - } - types.forEach((t) => { - if (!includesType(it.dataTypes, t)) strictTypesError(it, `type "${t}" not allowed by context "${it.dataTypes.join(",")}"`); - }); - narrowSchemaTypes(it, types); - } - function checkMultipleTypes(it, ts) { - if (ts.length > 1 && !(ts.length === 2 && ts.includes("null"))) strictTypesError(it, "use allowUnionTypes to allow union type keyword"); - } - function checkKeywordTypes(it, ts) { - const rules = it.self.RULES.all; - for (const keyword in rules) { - const rule = rules[keyword]; - if (typeof rule == "object" && (0, applicability_1.shouldUseRule)(it.schema, rule)) { - const { type } = rule.definition; - if (type.length && !type.some((t) => hasApplicableType(ts, t))) strictTypesError(it, `missing type "${type.join(",")}" for keyword "${keyword}"`); - } - } - } - function hasApplicableType(schTs, kwdT) { - return schTs.includes(kwdT) || kwdT === "number" && schTs.includes("integer"); - } - function includesType(ts, t) { - return ts.includes(t) || t === "integer" && ts.includes("number"); - } - function narrowSchemaTypes(it, withTypes) { - const ts = []; - for (const t of it.dataTypes) if (includesType(withTypes, t)) ts.push(t); - else if (withTypes.includes("integer") && t === "number") ts.push("integer"); - it.dataTypes = ts; - } - function strictTypesError(it, msg) { - const schemaPath = it.schemaEnv.baseId + it.errSchemaPath; - msg += ` at "${schemaPath}" (strictTypes)`; - (0, util_1.checkStrictMode)(it, msg, it.opts.strictTypes); - } - var KeywordCxt = class { - constructor(it, def, keyword) { - (0, keyword_1.validateKeywordUsage)(it, def, keyword); - this.gen = it.gen; - this.allErrors = it.allErrors; - this.keyword = keyword; - this.data = it.data; - this.schema = it.schema[keyword]; - this.$data = def.$data && it.opts.$data && this.schema && this.schema.$data; - this.schemaValue = (0, util_1.schemaRefOrVal)(it, this.schema, keyword, this.$data); - this.schemaType = def.schemaType; - this.parentSchema = it.schema; - this.params = {}; - this.it = it; - this.def = def; - if (this.$data) this.schemaCode = it.gen.const("vSchema", getData(this.$data, it)); - else { - this.schemaCode = this.schemaValue; - if (!(0, keyword_1.validSchemaType)(this.schema, def.schemaType, def.allowUndefined)) throw new Error(`${keyword} value must be ${JSON.stringify(def.schemaType)}`); - } - if ("code" in def ? def.trackErrors : def.errors !== false) this.errsCount = it.gen.const("_errs", names_1.default.errors); - } - result(condition, successAction, failAction) { - this.failResult((0, codegen_1.not)(condition), successAction, failAction); - } - failResult(condition, successAction, failAction) { - this.gen.if(condition); - if (failAction) failAction(); - else this.error(); - if (successAction) { - this.gen.else(); - successAction(); - if (this.allErrors) this.gen.endIf(); - } else if (this.allErrors) this.gen.endIf(); - else this.gen.else(); - } - pass(condition, failAction) { - this.failResult((0, codegen_1.not)(condition), void 0, failAction); - } - fail(condition) { - if (condition === void 0) { - this.error(); - if (!this.allErrors) this.gen.if(false); - return; - } - this.gen.if(condition); - this.error(); - if (this.allErrors) this.gen.endIf(); - else this.gen.else(); - } - fail$data(condition) { - if (!this.$data) return this.fail(condition); - const { schemaCode } = this; - this.fail((0, codegen_1._)`${schemaCode} !== undefined && (${(0, codegen_1.or)(this.invalid$data(), condition)})`); - } - error(append, errorParams, errorPaths) { - if (errorParams) { - this.setParams(errorParams); - this._error(append, errorPaths); - this.setParams({}); - return; - } - this._error(append, errorPaths); - } - _error(append, errorPaths) { - (append ? errors_1.reportExtraError : errors_1.reportError)(this, this.def.error, errorPaths); - } - $dataError() { - (0, errors_1.reportError)(this, this.def.$dataError || errors_1.keyword$DataError); - } - reset() { - if (this.errsCount === void 0) throw new Error("add \"trackErrors\" to keyword definition"); - (0, errors_1.resetErrorsCount)(this.gen, this.errsCount); - } - ok(cond) { - if (!this.allErrors) this.gen.if(cond); - } - setParams(obj, assign) { - if (assign) Object.assign(this.params, obj); - else this.params = obj; - } - block$data(valid, codeBlock, $dataValid = codegen_1.nil) { - this.gen.block(() => { - this.check$data(valid, $dataValid); - codeBlock(); - }); - } - check$data(valid = codegen_1.nil, $dataValid = codegen_1.nil) { - if (!this.$data) return; - const { gen, schemaCode, schemaType, def } = this; - gen.if((0, codegen_1.or)((0, codegen_1._)`${schemaCode} === undefined`, $dataValid)); - if (valid !== codegen_1.nil) gen.assign(valid, true); - if (schemaType.length || def.validateSchema) { - gen.elseIf(this.invalid$data()); - this.$dataError(); - if (valid !== codegen_1.nil) gen.assign(valid, false); - } - gen.else(); - } - invalid$data() { - const { gen, schemaCode, schemaType, def, it } = this; - return (0, codegen_1.or)(wrong$DataType(), invalid$DataSchema()); - function wrong$DataType() { - if (schemaType.length) { - /* istanbul ignore if */ - if (!(schemaCode instanceof codegen_1.Name)) throw new Error("ajv implementation error"); - const st = Array.isArray(schemaType) ? schemaType : [schemaType]; - return (0, codegen_1._)`${(0, dataType_2.checkDataTypes)(st, schemaCode, it.opts.strictNumbers, dataType_2.DataType.Wrong)}`; - } - return codegen_1.nil; - } - function invalid$DataSchema() { - if (def.validateSchema) { - const validateSchemaRef = gen.scopeValue("validate$data", { ref: def.validateSchema }); - return (0, codegen_1._)`!${validateSchemaRef}(${schemaCode})`; - } - return codegen_1.nil; - } - } - subschema(appl, valid) { - const subschema = (0, subschema_1.getSubschema)(this.it, appl); - (0, subschema_1.extendSubschemaData)(subschema, this.it, appl); - (0, subschema_1.extendSubschemaMode)(subschema, appl); - const nextContext = { - ...this.it, - ...subschema, - items: void 0, - props: void 0 - }; - subschemaCode(nextContext, valid); - return nextContext; - } - mergeEvaluated(schemaCxt, toName) { - const { it, gen } = this; - if (!it.opts.unevaluated) return; - if (it.props !== true && schemaCxt.props !== void 0) it.props = util_1.mergeEvaluated.props(gen, schemaCxt.props, it.props, toName); - if (it.items !== true && schemaCxt.items !== void 0) it.items = util_1.mergeEvaluated.items(gen, schemaCxt.items, it.items, toName); - } - mergeValidEvaluated(schemaCxt, valid) { - const { it, gen } = this; - if (it.opts.unevaluated && (it.props !== true || it.items !== true)) { - gen.if(valid, () => this.mergeEvaluated(schemaCxt, codegen_1.Name)); - return true; - } - } - }; - exports.KeywordCxt = KeywordCxt; - function keywordCode(it, keyword, def, ruleType) { - const cxt = new KeywordCxt(it, def, keyword); - if ("code" in def) def.code(cxt, ruleType); - else if (cxt.$data && def.validate) (0, keyword_1.funcKeywordCode)(cxt, def); - else if ("macro" in def) (0, keyword_1.macroKeywordCode)(cxt, def); - else if (def.compile || def.validate) (0, keyword_1.funcKeywordCode)(cxt, def); - } - const JSON_POINTER = /^\/(?:[^~]|~0|~1)*$/; - const RELATIVE_JSON_POINTER = /^([0-9]+)(#|\/(?:[^~]|~0|~1)*)?$/; - function getData($data, { dataLevel, dataNames, dataPathArr }) { - let jsonPointer; - let data; - if ($data === "") return names_1.default.rootData; - if ($data[0] === "/") { - if (!JSON_POINTER.test($data)) throw new Error(`Invalid JSON-pointer: ${$data}`); - jsonPointer = $data; - data = names_1.default.rootData; - } else { - const matches = RELATIVE_JSON_POINTER.exec($data); - if (!matches) throw new Error(`Invalid JSON-pointer: ${$data}`); - const up = +matches[1]; - jsonPointer = matches[2]; - if (jsonPointer === "#") { - if (up >= dataLevel) throw new Error(errorMsg("property/index", up)); - return dataPathArr[dataLevel - up]; - } - if (up > dataLevel) throw new Error(errorMsg("data", up)); - data = dataNames[dataLevel - up]; - if (!jsonPointer) return data; - } - let expr = data; - const segments = jsonPointer.split("/"); - for (const segment of segments) if (segment) { - data = (0, codegen_1._)`${data}${(0, codegen_1.getProperty)((0, util_1.unescapeJsonPointer)(segment))}`; - expr = (0, codegen_1._)`${expr} && ${data}`; - } - return expr; - function errorMsg(pointerType, up) { - return `Cannot access ${pointerType} ${up} levels up, current level is ${dataLevel}`; - } - } - exports.getData = getData; -})); - -//#endregion -//#region ../../node_modules/.pnpm/ajv@8.18.0/node_modules/ajv/dist/runtime/validation_error.js -var require_validation_error = /* @__PURE__ */ __commonJSMin(((exports) => { - Object.defineProperty(exports, "__esModule", { value: true }); - var ValidationError = class extends Error { - constructor(errors) { - super("validation failed"); - this.errors = errors; - this.ajv = this.validation = true; - } - }; - exports.default = ValidationError; -})); - -//#endregion -//#region ../../node_modules/.pnpm/ajv@8.18.0/node_modules/ajv/dist/compile/ref_error.js -var require_ref_error = /* @__PURE__ */ __commonJSMin(((exports) => { - Object.defineProperty(exports, "__esModule", { value: true }); - const resolve_1 = require_resolve(); - var MissingRefError = class extends Error { - constructor(resolver, baseId, ref, msg) { - super(msg || `can't resolve reference ${ref} from id ${baseId}`); - this.missingRef = (0, resolve_1.resolveUrl)(resolver, baseId, ref); - this.missingSchema = (0, resolve_1.normalizeId)((0, resolve_1.getFullPath)(resolver, this.missingRef)); - } - }; - exports.default = MissingRefError; -})); - -//#endregion -//#region ../../node_modules/.pnpm/ajv@8.18.0/node_modules/ajv/dist/compile/index.js -var require_compile = /* @__PURE__ */ __commonJSMin(((exports) => { - Object.defineProperty(exports, "__esModule", { value: true }); - exports.resolveSchema = exports.getCompilingSchema = exports.resolveRef = exports.compileSchema = exports.SchemaEnv = void 0; - const codegen_1 = require_codegen(); - const validation_error_1 = require_validation_error(); - const names_1 = require_names(); - const resolve_1 = require_resolve(); - const util_1 = require_util(); - const validate_1 = require_validate(); - var SchemaEnv = class { - constructor(env) { - var _a; - this.refs = {}; - this.dynamicAnchors = {}; - let schema; - if (typeof env.schema == "object") schema = env.schema; - this.schema = env.schema; - this.schemaId = env.schemaId; - this.root = env.root || this; - this.baseId = (_a = env.baseId) !== null && _a !== void 0 ? _a : (0, resolve_1.normalizeId)(schema === null || schema === void 0 ? void 0 : schema[env.schemaId || "$id"]); - this.schemaPath = env.schemaPath; - this.localRefs = env.localRefs; - this.meta = env.meta; - this.$async = schema === null || schema === void 0 ? void 0 : schema.$async; - this.refs = {}; - } - }; - exports.SchemaEnv = SchemaEnv; - function compileSchema(sch) { - const _sch = getCompilingSchema.call(this, sch); - if (_sch) return _sch; - const rootId = (0, resolve_1.getFullPath)(this.opts.uriResolver, sch.root.baseId); - const { es5, lines } = this.opts.code; - const { ownProperties } = this.opts; - const gen = new codegen_1.CodeGen(this.scope, { - es5, - lines, - ownProperties - }); - let _ValidationError; - if (sch.$async) _ValidationError = gen.scopeValue("Error", { - ref: validation_error_1.default, - code: (0, codegen_1._)`require("ajv/dist/runtime/validation_error").default` - }); - const validateName = gen.scopeName("validate"); - sch.validateName = validateName; - const schemaCxt = { - gen, - allErrors: this.opts.allErrors, - data: names_1.default.data, - parentData: names_1.default.parentData, - parentDataProperty: names_1.default.parentDataProperty, - dataNames: [names_1.default.data], - dataPathArr: [codegen_1.nil], - dataLevel: 0, - dataTypes: [], - definedProperties: /* @__PURE__ */ new Set(), - topSchemaRef: gen.scopeValue("schema", this.opts.code.source === true ? { - ref: sch.schema, - code: (0, codegen_1.stringify)(sch.schema) - } : { ref: sch.schema }), - validateName, - ValidationError: _ValidationError, - schema: sch.schema, - schemaEnv: sch, - rootId, - baseId: sch.baseId || rootId, - schemaPath: codegen_1.nil, - errSchemaPath: sch.schemaPath || (this.opts.jtd ? "" : "#"), - errorPath: (0, codegen_1._)`""`, - opts: this.opts, - self: this - }; - let sourceCode; - try { - this._compilations.add(sch); - (0, validate_1.validateFunctionCode)(schemaCxt); - gen.optimize(this.opts.code.optimize); - const validateCode = gen.toString(); - sourceCode = `${gen.scopeRefs(names_1.default.scope)}return ${validateCode}`; - if (this.opts.code.process) sourceCode = this.opts.code.process(sourceCode, sch); - const validate = new Function(`${names_1.default.self}`, `${names_1.default.scope}`, sourceCode)(this, this.scope.get()); - this.scope.value(validateName, { ref: validate }); - validate.errors = null; - validate.schema = sch.schema; - validate.schemaEnv = sch; - if (sch.$async) validate.$async = true; - if (this.opts.code.source === true) validate.source = { - validateName, - validateCode, - scopeValues: gen._values - }; - if (this.opts.unevaluated) { - const { props, items } = schemaCxt; - validate.evaluated = { - props: props instanceof codegen_1.Name ? void 0 : props, - items: items instanceof codegen_1.Name ? void 0 : items, - dynamicProps: props instanceof codegen_1.Name, - dynamicItems: items instanceof codegen_1.Name - }; - if (validate.source) validate.source.evaluated = (0, codegen_1.stringify)(validate.evaluated); - } - sch.validate = validate; - return sch; - } catch (e) { - delete sch.validate; - delete sch.validateName; - if (sourceCode) this.logger.error("Error compiling schema, function code:", sourceCode); - throw e; - } finally { - this._compilations.delete(sch); - } - } - exports.compileSchema = compileSchema; - function resolveRef(root, baseId, ref) { - var _a; - ref = (0, resolve_1.resolveUrl)(this.opts.uriResolver, baseId, ref); - const schOrFunc = root.refs[ref]; - if (schOrFunc) return schOrFunc; - let _sch = resolve.call(this, root, ref); - if (_sch === void 0) { - const schema = (_a = root.localRefs) === null || _a === void 0 ? void 0 : _a[ref]; - const { schemaId } = this.opts; - if (schema) _sch = new SchemaEnv({ - schema, - schemaId, - root, - baseId - }); - } - if (_sch === void 0) return; - return root.refs[ref] = inlineOrCompile.call(this, _sch); - } - exports.resolveRef = resolveRef; - function inlineOrCompile(sch) { - if ((0, resolve_1.inlineRef)(sch.schema, this.opts.inlineRefs)) return sch.schema; - return sch.validate ? sch : compileSchema.call(this, sch); - } - function getCompilingSchema(schEnv) { - for (const sch of this._compilations) if (sameSchemaEnv(sch, schEnv)) return sch; - } - exports.getCompilingSchema = getCompilingSchema; - function sameSchemaEnv(s1, s2) { - return s1.schema === s2.schema && s1.root === s2.root && s1.baseId === s2.baseId; - } - function resolve(root, ref) { - let sch; - while (typeof (sch = this.refs[ref]) == "string") ref = sch; - return sch || this.schemas[ref] || resolveSchema.call(this, root, ref); - } - function resolveSchema(root, ref) { - const p = this.opts.uriResolver.parse(ref); - const refPath = (0, resolve_1._getFullPath)(this.opts.uriResolver, p); - let baseId = (0, resolve_1.getFullPath)(this.opts.uriResolver, root.baseId, void 0); - if (Object.keys(root.schema).length > 0 && refPath === baseId) return getJsonPointer.call(this, p, root); - const id = (0, resolve_1.normalizeId)(refPath); - const schOrRef = this.refs[id] || this.schemas[id]; - if (typeof schOrRef == "string") { - const sch = resolveSchema.call(this, root, schOrRef); - if (typeof (sch === null || sch === void 0 ? void 0 : sch.schema) !== "object") return; - return getJsonPointer.call(this, p, sch); - } - if (typeof (schOrRef === null || schOrRef === void 0 ? void 0 : schOrRef.schema) !== "object") return; - if (!schOrRef.validate) compileSchema.call(this, schOrRef); - if (id === (0, resolve_1.normalizeId)(ref)) { - const { schema } = schOrRef; - const { schemaId } = this.opts; - const schId = schema[schemaId]; - if (schId) baseId = (0, resolve_1.resolveUrl)(this.opts.uriResolver, baseId, schId); - return new SchemaEnv({ - schema, - schemaId, - root, - baseId - }); - } - return getJsonPointer.call(this, p, schOrRef); - } - exports.resolveSchema = resolveSchema; - const PREVENT_SCOPE_CHANGE = new Set([ - "properties", - "patternProperties", - "enum", - "dependencies", - "definitions" - ]); - function getJsonPointer(parsedRef, { baseId, schema, root }) { - var _a; - if (((_a = parsedRef.fragment) === null || _a === void 0 ? void 0 : _a[0]) !== "/") return; - for (const part of parsedRef.fragment.slice(1).split("/")) { - if (typeof schema === "boolean") return; - const partSchema = schema[(0, util_1.unescapeFragment)(part)]; - if (partSchema === void 0) return; - schema = partSchema; - const schId = typeof schema === "object" && schema[this.opts.schemaId]; - if (!PREVENT_SCOPE_CHANGE.has(part) && schId) baseId = (0, resolve_1.resolveUrl)(this.opts.uriResolver, baseId, schId); - } - let env; - if (typeof schema != "boolean" && schema.$ref && !(0, util_1.schemaHasRulesButRef)(schema, this.RULES)) { - const $ref = (0, resolve_1.resolveUrl)(this.opts.uriResolver, baseId, schema.$ref); - env = resolveSchema.call(this, root, $ref); - } - const { schemaId } = this.opts; - env = env || new SchemaEnv({ - schema, - schemaId, - root, - baseId - }); - if (env.schema !== env.root.schema) return env; - } -})); - -//#endregion -//#region ../../node_modules/.pnpm/ajv@8.18.0/node_modules/ajv/dist/refs/data.json -var require_data = /* @__PURE__ */ __commonJSMin(((exports, module) => { - module.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": false - }; -})); - -//#endregion -//#region ../../node_modules/.pnpm/fast-uri@3.1.0/node_modules/fast-uri/lib/utils.js -var require_utils = /* @__PURE__ */ __commonJSMin(((exports, module) => { - /** @type {(value: string) => boolean} */ - const isUUID = RegExp.prototype.test.bind(/^[\da-f]{8}-[\da-f]{4}-[\da-f]{4}-[\da-f]{4}-[\da-f]{12}$/iu); - /** @type {(value: string) => boolean} */ - const isIPv4 = 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); - /** - * @param {Array} input - * @returns {string} - */ - function stringArrayToHexStripped(input) { - let acc = ""; - let code = 0; - let i = 0; - for (i = 0; i < input.length; i++) { - code = input[i].charCodeAt(0); - if (code === 48) continue; - if (!(code >= 48 && code <= 57 || code >= 65 && code <= 70 || code >= 97 && code <= 102)) return ""; - acc += input[i]; - break; - } - for (i += 1; i < input.length; i++) { - code = input[i].charCodeAt(0); - if (!(code >= 48 && code <= 57 || code >= 65 && code <= 70 || code >= 97 && code <= 102)) return ""; - acc += input[i]; - } - return acc; - } - /** - * @typedef {Object} GetIPV6Result - * @property {boolean} error - Indicates if there was an error parsing the IPv6 address. - * @property {string} address - The parsed IPv6 address. - * @property {string} [zone] - The zone identifier, if present. - */ - /** - * @param {string} value - * @returns {boolean} - */ - const nonSimpleDomain = RegExp.prototype.test.bind(/[^!"$&'()*+,\-.;=_`a-z{}~]/u); - /** - * @param {Array} buffer - * @returns {boolean} - */ - function consumeIsZone(buffer) { - buffer.length = 0; - return true; - } - /** - * @param {Array} buffer - * @param {Array} address - * @param {GetIPV6Result} output - * @returns {boolean} - */ - function consumeHextets(buffer, address, output) { - if (buffer.length) { - const hex = stringArrayToHexStripped(buffer); - if (hex !== "") address.push(hex); - else { - output.error = true; - return false; - } - buffer.length = 0; - } - return true; - } - /** - * @param {string} input - * @returns {GetIPV6Result} - */ - function getIPV6(input) { - let tokenCount = 0; - const output = { - error: false, - address: "", - zone: "" - }; - /** @type {Array} */ - const address = []; - /** @type {Array} */ - const buffer = []; - let endipv6Encountered = false; - let endIpv6 = false; - let consume = consumeHextets; - for (let i = 0; i < input.length; i++) { - const cursor = input[i]; - if (cursor === "[" || cursor === "]") continue; - if (cursor === ":") { - if (endipv6Encountered === true) endIpv6 = true; - if (!consume(buffer, address, output)) break; - if (++tokenCount > 7) { - output.error = true; - break; - } - if (i > 0 && input[i - 1] === ":") endipv6Encountered = true; - address.push(":"); - continue; - } else if (cursor === "%") { - if (!consume(buffer, address, output)) break; - consume = consumeIsZone; - } else { - buffer.push(cursor); - continue; - } - } - if (buffer.length) if (consume === consumeIsZone) output.zone = buffer.join(""); - else if (endIpv6) address.push(buffer.join("")); - else address.push(stringArrayToHexStripped(buffer)); - output.address = address.join(""); - return output; - } - /** - * @typedef {Object} NormalizeIPv6Result - * @property {string} host - The normalized host. - * @property {string} [escapedHost] - The escaped host. - * @property {boolean} isIPV6 - Indicates if the host is an IPv6 address. - */ - /** - * @param {string} host - * @returns {NormalizeIPv6Result} - */ - function normalizeIPv6(host) { - if (findToken(host, ":") < 2) return { - host, - isIPV6: false - }; - const ipv6 = getIPV6(host); - if (!ipv6.error) { - let newHost = ipv6.address; - let escapedHost = ipv6.address; - if (ipv6.zone) { - newHost += "%" + ipv6.zone; - escapedHost += "%25" + ipv6.zone; - } - return { - host: newHost, - isIPV6: true, - escapedHost - }; - } else return { - host, - isIPV6: false - }; - } - /** - * @param {string} str - * @param {string} token - * @returns {number} - */ - function findToken(str, token) { - let ind = 0; - for (let i = 0; i < str.length; i++) if (str[i] === token) ind++; - return ind; - } - /** - * @param {string} path - * @returns {string} - * - * @see https://datatracker.ietf.org/doc/html/rfc3986#section-5.2.4 - */ - function removeDotSegments(path) { - let input = path; - const output = []; - let nextSlash = -1; - let len = 0; - while (len = input.length) { - if (len === 1) if (input === ".") break; - else if (input === "/") { - output.push("/"); - break; - } else { - output.push(input); - break; - } - else if (len === 2) { - if (input[0] === ".") { - if (input[1] === ".") break; - else if (input[1] === "/") { - input = input.slice(2); - continue; - } - } else if (input[0] === "/") { - if (input[1] === "." || input[1] === "/") { - output.push("/"); - break; - } - } - } else if (len === 3) { - if (input === "/..") { - if (output.length !== 0) output.pop(); - output.push("/"); - break; - } - } - if (input[0] === ".") { - if (input[1] === ".") { - if (input[2] === "/") { - input = input.slice(3); - continue; - } - } else if (input[1] === "/") { - input = input.slice(2); - continue; - } - } else if (input[0] === "/") { - if (input[1] === ".") { - if (input[2] === "/") { - input = input.slice(2); - continue; - } else if (input[2] === ".") { - if (input[3] === "/") { - input = input.slice(3); - if (output.length !== 0) output.pop(); - continue; - } - } - } - } - if ((nextSlash = input.indexOf("/", 1)) === -1) { - output.push(input); - break; - } else { - output.push(input.slice(0, nextSlash)); - input = input.slice(nextSlash); - } - } - return output.join(""); - } - /** - * @param {import('../types/index').URIComponent} component - * @param {boolean} esc - * @returns {import('../types/index').URIComponent} - */ - function normalizeComponentEncoding(component, esc) { - const func = esc !== true ? escape : unescape; - if (component.scheme !== void 0) component.scheme = func(component.scheme); - if (component.userinfo !== void 0) component.userinfo = func(component.userinfo); - if (component.host !== void 0) component.host = func(component.host); - if (component.path !== void 0) component.path = func(component.path); - if (component.query !== void 0) component.query = func(component.query); - if (component.fragment !== void 0) component.fragment = func(component.fragment); - return component; - } - /** - * @param {import('../types/index').URIComponent} component - * @returns {string|undefined} - */ - function recomposeAuthority(component) { - const uriTokens = []; - if (component.userinfo !== void 0) { - uriTokens.push(component.userinfo); - uriTokens.push("@"); - } - if (component.host !== void 0) { - let host = unescape(component.host); - if (!isIPv4(host)) { - const ipV6res = normalizeIPv6(host); - if (ipV6res.isIPV6 === true) host = `[${ipV6res.escapedHost}]`; - else host = component.host; - } - uriTokens.push(host); - } - if (typeof component.port === "number" || typeof component.port === "string") { - uriTokens.push(":"); - uriTokens.push(String(component.port)); - } - return uriTokens.length ? uriTokens.join("") : void 0; - } - module.exports = { - nonSimpleDomain, - recomposeAuthority, - normalizeComponentEncoding, - removeDotSegments, - isIPv4, - isUUID, - normalizeIPv6, - stringArrayToHexStripped - }; -})); - -//#endregion -//#region ../../node_modules/.pnpm/fast-uri@3.1.0/node_modules/fast-uri/lib/schemes.js -var require_schemes = /* @__PURE__ */ __commonJSMin(((exports, module) => { - const { isUUID } = require_utils(); - const URN_REG = /([\da-z][\d\-a-z]{0,31}):((?:[\w!$'()*+,\-.:;=@]|%[\da-f]{2})+)/iu; - const supportedSchemeNames = [ - "http", - "https", - "ws", - "wss", - "urn", - "urn:uuid" - ]; - /** @typedef {supportedSchemeNames[number]} SchemeName */ - /** - * @param {string} name - * @returns {name is SchemeName} - */ - function isValidSchemeName(name) { - return supportedSchemeNames.indexOf(name) !== -1; - } - /** - * @callback SchemeFn - * @param {import('../types/index').URIComponent} component - * @param {import('../types/index').Options} options - * @returns {import('../types/index').URIComponent} - */ - /** - * @typedef {Object} SchemeHandler - * @property {SchemeName} scheme - The scheme name. - * @property {boolean} [domainHost] - Indicates if the scheme supports domain hosts. - * @property {SchemeFn} parse - Function to parse the URI component for this scheme. - * @property {SchemeFn} serialize - Function to serialize the URI component for this scheme. - * @property {boolean} [skipNormalize] - Indicates if normalization should be skipped for this scheme. - * @property {boolean} [absolutePath] - Indicates if the scheme uses absolute paths. - * @property {boolean} [unicodeSupport] - Indicates if the scheme supports Unicode. - */ - /** - * @param {import('../types/index').URIComponent} wsComponent - * @returns {boolean} - */ - function wsIsSecure(wsComponent) { - if (wsComponent.secure === true) return true; - else if (wsComponent.secure === false) return false; - else if (wsComponent.scheme) return wsComponent.scheme.length === 3 && (wsComponent.scheme[0] === "w" || wsComponent.scheme[0] === "W") && (wsComponent.scheme[1] === "s" || wsComponent.scheme[1] === "S") && (wsComponent.scheme[2] === "s" || wsComponent.scheme[2] === "S"); - else return false; - } - /** @type {SchemeFn} */ - function httpParse(component) { - if (!component.host) component.error = component.error || "HTTP URIs must have a host."; - return component; - } - /** @type {SchemeFn} */ - function httpSerialize(component) { - const secure = String(component.scheme).toLowerCase() === "https"; - if (component.port === (secure ? 443 : 80) || component.port === "") component.port = void 0; - if (!component.path) component.path = "/"; - return component; - } - /** @type {SchemeFn} */ - function wsParse(wsComponent) { - wsComponent.secure = wsIsSecure(wsComponent); - wsComponent.resourceName = (wsComponent.path || "/") + (wsComponent.query ? "?" + wsComponent.query : ""); - wsComponent.path = void 0; - wsComponent.query = void 0; - return wsComponent; - } - /** @type {SchemeFn} */ - function wsSerialize(wsComponent) { - if (wsComponent.port === (wsIsSecure(wsComponent) ? 443 : 80) || wsComponent.port === "") wsComponent.port = void 0; - if (typeof wsComponent.secure === "boolean") { - wsComponent.scheme = wsComponent.secure ? "wss" : "ws"; - wsComponent.secure = void 0; - } - if (wsComponent.resourceName) { - const [path, query] = wsComponent.resourceName.split("?"); - wsComponent.path = path && path !== "/" ? path : void 0; - wsComponent.query = query; - wsComponent.resourceName = void 0; - } - wsComponent.fragment = void 0; - return wsComponent; - } - /** @type {SchemeFn} */ - function urnParse(urnComponent, options) { - if (!urnComponent.path) { - urnComponent.error = "URN can not be parsed"; - return urnComponent; - } - const matches = urnComponent.path.match(URN_REG); - if (matches) { - const scheme = options.scheme || urnComponent.scheme || "urn"; - urnComponent.nid = matches[1].toLowerCase(); - urnComponent.nss = matches[2]; - const schemeHandler = getSchemeHandler(`${scheme}:${options.nid || urnComponent.nid}`); - urnComponent.path = void 0; - if (schemeHandler) urnComponent = schemeHandler.parse(urnComponent, options); - } else urnComponent.error = urnComponent.error || "URN can not be parsed."; - return urnComponent; - } - /** @type {SchemeFn} */ - function urnSerialize(urnComponent, options) { - if (urnComponent.nid === void 0) throw new Error("URN without nid cannot be serialized"); - const scheme = options.scheme || urnComponent.scheme || "urn"; - const nid = urnComponent.nid.toLowerCase(); - const schemeHandler = getSchemeHandler(`${scheme}:${options.nid || nid}`); - if (schemeHandler) urnComponent = schemeHandler.serialize(urnComponent, options); - const uriComponent = urnComponent; - const nss = urnComponent.nss; - uriComponent.path = `${nid || options.nid}:${nss}`; - options.skipEscape = true; - return uriComponent; - } - /** @type {SchemeFn} */ - function urnuuidParse(urnComponent, options) { - const uuidComponent = urnComponent; - uuidComponent.uuid = uuidComponent.nss; - uuidComponent.nss = void 0; - if (!options.tolerant && (!uuidComponent.uuid || !isUUID(uuidComponent.uuid))) uuidComponent.error = uuidComponent.error || "UUID is not valid."; - return uuidComponent; - } - /** @type {SchemeFn} */ - function urnuuidSerialize(uuidComponent) { - const urnComponent = uuidComponent; - urnComponent.nss = (uuidComponent.uuid || "").toLowerCase(); - return urnComponent; - } - const http = { - scheme: "http", - domainHost: true, - parse: httpParse, - serialize: httpSerialize - }; - const https = { - scheme: "https", - domainHost: http.domainHost, - parse: httpParse, - serialize: httpSerialize - }; - const ws = { - scheme: "ws", - domainHost: true, - parse: wsParse, - serialize: wsSerialize - }; - const wss = { - scheme: "wss", - domainHost: ws.domainHost, - parse: ws.parse, - serialize: ws.serialize - }; - const urn = { - scheme: "urn", - parse: urnParse, - serialize: urnSerialize, - skipNormalize: true - }; - const urnuuid = { - scheme: "urn:uuid", - parse: urnuuidParse, - serialize: urnuuidSerialize, - skipNormalize: true - }; - const SCHEMES = { - http, - https, - ws, - wss, - urn, - "urn:uuid": urnuuid - }; - Object.setPrototypeOf(SCHEMES, null); - /** - * @param {string|undefined} scheme - * @returns {SchemeHandler|undefined} - */ - function getSchemeHandler(scheme) { - return scheme && (SCHEMES[scheme] || SCHEMES[scheme.toLowerCase()]) || void 0; - } - module.exports = { - wsIsSecure, - SCHEMES, - isValidSchemeName, - getSchemeHandler - }; -})); - -//#endregion -//#region ../../node_modules/.pnpm/fast-uri@3.1.0/node_modules/fast-uri/index.js -var require_fast_uri = /* @__PURE__ */ __commonJSMin(((exports, module) => { - const { normalizeIPv6, removeDotSegments, recomposeAuthority, normalizeComponentEncoding, isIPv4, nonSimpleDomain } = require_utils(); - const { SCHEMES, getSchemeHandler } = require_schemes(); - /** - * @template {import('./types/index').URIComponent|string} T - * @param {T} uri - * @param {import('./types/index').Options} [options] - * @returns {T} - */ - function normalize(uri, options) { - if (typeof uri === "string") uri = serialize(parse(uri, options), options); - else if (typeof uri === "object") uri = parse(serialize(uri, options), options); - return uri; - } - /** - * @param {string} baseURI - * @param {string} relativeURI - * @param {import('./types/index').Options} [options] - * @returns {string} - */ - function resolve(baseURI, relativeURI, options) { - const schemelessOptions = options ? Object.assign({ scheme: "null" }, options) : { scheme: "null" }; - const resolved = resolveComponent(parse(baseURI, schemelessOptions), parse(relativeURI, schemelessOptions), schemelessOptions, true); - schemelessOptions.skipEscape = true; - return serialize(resolved, schemelessOptions); - } - /** - * @param {import ('./types/index').URIComponent} base - * @param {import ('./types/index').URIComponent} relative - * @param {import('./types/index').Options} [options] - * @param {boolean} [skipNormalization=false] - * @returns {import ('./types/index').URIComponent} - */ - function resolveComponent(base, relative, options, skipNormalization) { - /** @type {import('./types/index').URIComponent} */ - const target = {}; - if (!skipNormalization) { - base = parse(serialize(base, options), options); - relative = parse(serialize(relative, options), options); - } - options = options || {}; - if (!options.tolerant && relative.scheme) { - target.scheme = relative.scheme; - target.userinfo = relative.userinfo; - target.host = relative.host; - target.port = relative.port; - target.path = removeDotSegments(relative.path || ""); - target.query = relative.query; - } else { - if (relative.userinfo !== void 0 || relative.host !== void 0 || relative.port !== void 0) { - target.userinfo = relative.userinfo; - target.host = relative.host; - target.port = relative.port; - target.path = removeDotSegments(relative.path || ""); - target.query = relative.query; - } else { - if (!relative.path) { - target.path = base.path; - if (relative.query !== void 0) target.query = relative.query; - else target.query = base.query; - } else { - if (relative.path[0] === "/") target.path = removeDotSegments(relative.path); - else { - if ((base.userinfo !== void 0 || base.host !== void 0 || base.port !== void 0) && !base.path) target.path = "/" + relative.path; - else if (!base.path) target.path = relative.path; - else target.path = base.path.slice(0, base.path.lastIndexOf("/") + 1) + relative.path; - target.path = removeDotSegments(target.path); - } - target.query = relative.query; - } - target.userinfo = base.userinfo; - target.host = base.host; - target.port = base.port; - } - target.scheme = base.scheme; - } - target.fragment = relative.fragment; - return target; - } - /** - * @param {import ('./types/index').URIComponent|string} uriA - * @param {import ('./types/index').URIComponent|string} uriB - * @param {import ('./types/index').Options} options - * @returns {boolean} - */ - function equal(uriA, uriB, options) { - if (typeof uriA === "string") { - uriA = unescape(uriA); - uriA = serialize(normalizeComponentEncoding(parse(uriA, options), true), { - ...options, - skipEscape: true - }); - } else if (typeof uriA === "object") uriA = serialize(normalizeComponentEncoding(uriA, true), { - ...options, - skipEscape: true - }); - if (typeof uriB === "string") { - uriB = unescape(uriB); - uriB = serialize(normalizeComponentEncoding(parse(uriB, options), true), { - ...options, - skipEscape: true - }); - } else if (typeof uriB === "object") uriB = serialize(normalizeComponentEncoding(uriB, true), { - ...options, - skipEscape: true - }); - return uriA.toLowerCase() === uriB.toLowerCase(); - } - /** - * @param {Readonly} cmpts - * @param {import('./types/index').Options} [opts] - * @returns {string} - */ - function serialize(cmpts, opts) { - const component = { - host: cmpts.host, - scheme: cmpts.scheme, - userinfo: cmpts.userinfo, - port: cmpts.port, - path: cmpts.path, - query: cmpts.query, - nid: cmpts.nid, - nss: cmpts.nss, - uuid: cmpts.uuid, - fragment: cmpts.fragment, - reference: cmpts.reference, - resourceName: cmpts.resourceName, - secure: cmpts.secure, - error: "" - }; - const options = Object.assign({}, opts); - const uriTokens = []; - const schemeHandler = getSchemeHandler(options.scheme || component.scheme); - if (schemeHandler && schemeHandler.serialize) schemeHandler.serialize(component, options); - if (component.path !== void 0) if (!options.skipEscape) { - component.path = escape(component.path); - if (component.scheme !== void 0) component.path = component.path.split("%3A").join(":"); - } else component.path = unescape(component.path); - if (options.reference !== "suffix" && component.scheme) uriTokens.push(component.scheme, ":"); - const authority = recomposeAuthority(component); - if (authority !== void 0) { - if (options.reference !== "suffix") uriTokens.push("//"); - uriTokens.push(authority); - if (component.path && component.path[0] !== "/") uriTokens.push("/"); - } - if (component.path !== void 0) { - let s = component.path; - if (!options.absolutePath && (!schemeHandler || !schemeHandler.absolutePath)) s = removeDotSegments(s); - if (authority === void 0 && s[0] === "/" && s[1] === "/") s = "/%2F" + s.slice(2); - uriTokens.push(s); - } - if (component.query !== void 0) uriTokens.push("?", component.query); - if (component.fragment !== void 0) uriTokens.push("#", component.fragment); - return uriTokens.join(""); - } - const URI_PARSE = /^(?:([^#/:?]+):)?(?:\/\/((?:([^#/?@]*)@)?(\[[^#/?\]]+\]|[^#/:?]*)(?::(\d*))?))?([^#?]*)(?:\?([^#]*))?(?:#((?:.|[\n\r])*))?/u; - /** - * @param {string} uri - * @param {import('./types/index').Options} [opts] - * @returns - */ - function parse(uri, opts) { - const options = Object.assign({}, opts); - /** @type {import('./types/index').URIComponent} */ - const parsed = { - scheme: void 0, - userinfo: void 0, - host: "", - port: void 0, - path: "", - query: void 0, - fragment: void 0 - }; - let isIP = false; - if (options.reference === "suffix") if (options.scheme) uri = options.scheme + ":" + uri; - else uri = "//" + uri; - const matches = uri.match(URI_PARSE); - if (matches) { - parsed.scheme = matches[1]; - parsed.userinfo = matches[3]; - parsed.host = matches[4]; - parsed.port = parseInt(matches[5], 10); - parsed.path = matches[6] || ""; - parsed.query = matches[7]; - parsed.fragment = matches[8]; - if (isNaN(parsed.port)) parsed.port = matches[5]; - if (parsed.host) if (isIPv4(parsed.host) === false) { - const ipv6result = normalizeIPv6(parsed.host); - parsed.host = ipv6result.host.toLowerCase(); - isIP = ipv6result.isIPV6; - } else isIP = true; - if (parsed.scheme === void 0 && parsed.userinfo === void 0 && parsed.host === void 0 && parsed.port === void 0 && parsed.query === void 0 && !parsed.path) parsed.reference = "same-document"; - else if (parsed.scheme === void 0) parsed.reference = "relative"; - else if (parsed.fragment === void 0) parsed.reference = "absolute"; - else parsed.reference = "uri"; - if (options.reference && options.reference !== "suffix" && options.reference !== parsed.reference) parsed.error = parsed.error || "URI is not a " + options.reference + " reference."; - const schemeHandler = getSchemeHandler(options.scheme || parsed.scheme); - if (!options.unicodeSupport && (!schemeHandler || !schemeHandler.unicodeSupport)) { - if (parsed.host && (options.domainHost || schemeHandler && schemeHandler.domainHost) && isIP === false && nonSimpleDomain(parsed.host)) try { - parsed.host = URL.domainToASCII(parsed.host.toLowerCase()); - } catch (e) { - parsed.error = parsed.error || "Host's domain name can not be converted to ASCII: " + e; - } - } - if (!schemeHandler || schemeHandler && !schemeHandler.skipNormalize) { - if (uri.indexOf("%") !== -1) { - if (parsed.scheme !== void 0) parsed.scheme = unescape(parsed.scheme); - if (parsed.host !== void 0) parsed.host = unescape(parsed.host); - } - if (parsed.path) parsed.path = escape(unescape(parsed.path)); - if (parsed.fragment) parsed.fragment = encodeURI(decodeURIComponent(parsed.fragment)); - } - if (schemeHandler && schemeHandler.parse) schemeHandler.parse(parsed, options); - } else parsed.error = parsed.error || "URI can not be parsed."; - return parsed; - } - const fastUri = { - SCHEMES, - normalize, - resolve, - resolveComponent, - equal, - serialize, - parse - }; - module.exports = fastUri; - module.exports.default = fastUri; - module.exports.fastUri = fastUri; -})); - -//#endregion -//#region ../../node_modules/.pnpm/ajv@8.18.0/node_modules/ajv/dist/runtime/uri.js -var require_uri = /* @__PURE__ */ __commonJSMin(((exports) => { - Object.defineProperty(exports, "__esModule", { value: true }); - const uri = require_fast_uri(); - uri.code = "require(\"ajv/dist/runtime/uri\").default"; - exports.default = uri; -})); - -//#endregion -//#region ../../node_modules/.pnpm/ajv@8.18.0/node_modules/ajv/dist/core.js -var require_core$3 = /* @__PURE__ */ __commonJSMin(((exports) => { - Object.defineProperty(exports, "__esModule", { value: true }); - exports.CodeGen = exports.Name = exports.nil = exports.stringify = exports.str = exports._ = exports.KeywordCxt = void 0; - var validate_1 = require_validate(); - Object.defineProperty(exports, "KeywordCxt", { - enumerable: true, - get: function() { - return validate_1.KeywordCxt; - } - }); - var codegen_1 = require_codegen(); - Object.defineProperty(exports, "_", { - enumerable: true, - get: function() { - return codegen_1._; - } - }); - Object.defineProperty(exports, "str", { - enumerable: true, - get: function() { - return codegen_1.str; - } - }); - Object.defineProperty(exports, "stringify", { - enumerable: true, - get: function() { - return codegen_1.stringify; - } - }); - Object.defineProperty(exports, "nil", { - enumerable: true, - get: function() { - return codegen_1.nil; - } - }); - Object.defineProperty(exports, "Name", { - enumerable: true, - get: function() { - return codegen_1.Name; - } - }); - Object.defineProperty(exports, "CodeGen", { - enumerable: true, - get: function() { - return codegen_1.CodeGen; - } - }); - const validation_error_1 = require_validation_error(); - const ref_error_1 = require_ref_error(); - const rules_1 = require_rules(); - const compile_1 = require_compile(); - const codegen_2 = require_codegen(); - const resolve_1 = require_resolve(); - const dataType_1 = require_dataType(); - const util_1 = require_util(); - const $dataRefSchema = require_data(); - const uri_1 = require_uri(); - const defaultRegExp = (str, flags) => new RegExp(str, flags); - defaultRegExp.code = "new RegExp"; - const META_IGNORE_OPTIONS = [ - "removeAdditional", - "useDefaults", - "coerceTypes" - ]; - const EXT_SCOPE_NAMES = new Set([ - "validate", - "serialize", - "parse", - "wrapper", - "root", - "schema", - "keyword", - "pattern", - "formats", - "validate$data", - "func", - "obj", - "Error" - ]); - const removedOptions = { - 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." - }; - const deprecatedOptions = { - ignoreKeywordsWithRef: "", - jsPropertySyntax: "", - unicode: "\"minLength\"/\"maxLength\" account for unicode characters by default." - }; - const MAX_EXPRESSION = 200; - function requiredOptions(o) { - var _a, _b, _c, _d, _e, _f, _g, _h, _j, _k, _l, _m, _o, _p, _q, _r, _s, _t, _u, _v, _w, _x, _y, _z, _0; - const s = o.strict; - const _optz = (_a = o.code) === null || _a === void 0 ? void 0 : _a.optimize; - const optimize = _optz === true || _optz === void 0 ? 1 : _optz || 0; - const regExp = (_c = (_b = o.code) === null || _b === void 0 ? void 0 : _b.regExp) !== null && _c !== void 0 ? _c : defaultRegExp; - const uriResolver = (_d = o.uriResolver) !== null && _d !== void 0 ? _d : uri_1.default; - return { - strictSchema: (_f = (_e = o.strictSchema) !== null && _e !== void 0 ? _e : s) !== null && _f !== void 0 ? _f : true, - strictNumbers: (_h = (_g = o.strictNumbers) !== null && _g !== void 0 ? _g : s) !== null && _h !== void 0 ? _h : true, - strictTypes: (_k = (_j = o.strictTypes) !== null && _j !== void 0 ? _j : s) !== null && _k !== void 0 ? _k : "log", - strictTuples: (_m = (_l = o.strictTuples) !== null && _l !== void 0 ? _l : s) !== null && _m !== void 0 ? _m : "log", - strictRequired: (_p = (_o = o.strictRequired) !== null && _o !== void 0 ? _o : s) !== null && _p !== void 0 ? _p : false, - code: o.code ? { - ...o.code, - optimize, - regExp - } : { - optimize, - regExp - }, - loopRequired: (_q = o.loopRequired) !== null && _q !== void 0 ? _q : MAX_EXPRESSION, - loopEnum: (_r = o.loopEnum) !== null && _r !== void 0 ? _r : MAX_EXPRESSION, - meta: (_s = o.meta) !== null && _s !== void 0 ? _s : true, - messages: (_t = o.messages) !== null && _t !== void 0 ? _t : true, - inlineRefs: (_u = o.inlineRefs) !== null && _u !== void 0 ? _u : true, - schemaId: (_v = o.schemaId) !== null && _v !== void 0 ? _v : "$id", - addUsedSchema: (_w = o.addUsedSchema) !== null && _w !== void 0 ? _w : true, - validateSchema: (_x = o.validateSchema) !== null && _x !== void 0 ? _x : true, - validateFormats: (_y = o.validateFormats) !== null && _y !== void 0 ? _y : true, - unicodeRegExp: (_z = o.unicodeRegExp) !== null && _z !== void 0 ? _z : true, - int32range: (_0 = o.int32range) !== null && _0 !== void 0 ? _0 : true, - uriResolver - }; - } - var Ajv = class { - constructor(opts = {}) { - this.schemas = {}; - this.refs = {}; - this.formats = {}; - this._compilations = /* @__PURE__ */ new Set(); - this._loading = {}; - this._cache = /* @__PURE__ */ new Map(); - opts = this.opts = { - ...opts, - ...requiredOptions(opts) - }; - const { es5, lines } = this.opts.code; - this.scope = new codegen_2.ValueScope({ - scope: {}, - prefixes: EXT_SCOPE_NAMES, - es5, - lines - }); - this.logger = getLogger(opts.logger); - const formatOpt = opts.validateFormats; - opts.validateFormats = false; - this.RULES = (0, rules_1.getRules)(); - checkOptions.call(this, removedOptions, opts, "NOT SUPPORTED"); - checkOptions.call(this, deprecatedOptions, opts, "DEPRECATED", "warn"); - this._metaOpts = getMetaSchemaOptions.call(this); - if (opts.formats) addInitialFormats.call(this); - this._addVocabularies(); - this._addDefaultMetaSchema(); - if (opts.keywords) addInitialKeywords.call(this, opts.keywords); - if (typeof opts.meta == "object") this.addMetaSchema(opts.meta); - addInitialSchemas.call(this); - opts.validateFormats = formatOpt; - } - _addVocabularies() { - this.addKeyword("$async"); - } - _addDefaultMetaSchema() { - const { $data, meta, schemaId } = this.opts; - let _dataRefSchema = $dataRefSchema; - if (schemaId === "id") { - _dataRefSchema = { ...$dataRefSchema }; - _dataRefSchema.id = _dataRefSchema.$id; - delete _dataRefSchema.$id; - } - if (meta && $data) this.addMetaSchema(_dataRefSchema, _dataRefSchema[schemaId], false); - } - defaultMeta() { - const { meta, schemaId } = this.opts; - return this.opts.defaultMeta = typeof meta == "object" ? meta[schemaId] || meta : void 0; - } - validate(schemaKeyRef, data) { - let v; - if (typeof schemaKeyRef == "string") { - v = this.getSchema(schemaKeyRef); - if (!v) throw new Error(`no schema with key or ref "${schemaKeyRef}"`); - } else v = this.compile(schemaKeyRef); - const valid = v(data); - if (!("$async" in v)) this.errors = v.errors; - return valid; - } - compile(schema, _meta) { - const sch = this._addSchema(schema, _meta); - return sch.validate || this._compileSchemaEnv(sch); - } - compileAsync(schema, meta) { - if (typeof this.opts.loadSchema != "function") throw new Error("options.loadSchema should be a function"); - const { loadSchema } = this.opts; - return runCompileAsync.call(this, schema, meta); - async function runCompileAsync(_schema, _meta) { - await loadMetaSchema.call(this, _schema.$schema); - const sch = this._addSchema(_schema, _meta); - return sch.validate || _compileAsync.call(this, sch); - } - async function loadMetaSchema($ref) { - if ($ref && !this.getSchema($ref)) await runCompileAsync.call(this, { $ref }, true); - } - async function _compileAsync(sch) { - try { - return this._compileSchemaEnv(sch); - } catch (e) { - if (!(e instanceof ref_error_1.default)) throw e; - checkLoaded.call(this, e); - await loadMissingSchema.call(this, e.missingSchema); - return _compileAsync.call(this, sch); - } - } - function checkLoaded({ missingSchema: ref, missingRef }) { - if (this.refs[ref]) throw new Error(`AnySchema ${ref} is loaded but ${missingRef} cannot be resolved`); - } - async function loadMissingSchema(ref) { - const _schema = await _loadSchema.call(this, ref); - if (!this.refs[ref]) await loadMetaSchema.call(this, _schema.$schema); - if (!this.refs[ref]) this.addSchema(_schema, ref, meta); - } - async function _loadSchema(ref) { - const p = this._loading[ref]; - if (p) return p; - try { - return await (this._loading[ref] = loadSchema(ref)); - } finally { - delete this._loading[ref]; - } - } - } - addSchema(schema, key, _meta, _validateSchema = this.opts.validateSchema) { - if (Array.isArray(schema)) { - for (const sch of schema) this.addSchema(sch, void 0, _meta, _validateSchema); - return this; - } - let id; - if (typeof schema === "object") { - const { schemaId } = this.opts; - id = schema[schemaId]; - if (id !== void 0 && typeof id != "string") throw new Error(`schema ${schemaId} must be string`); - } - key = (0, resolve_1.normalizeId)(key || id); - this._checkUnique(key); - this.schemas[key] = this._addSchema(schema, _meta, key, _validateSchema, true); - return this; - } - addMetaSchema(schema, key, _validateSchema = this.opts.validateSchema) { - this.addSchema(schema, key, true, _validateSchema); - return this; - } - validateSchema(schema, throwOrLogError) { - if (typeof schema == "boolean") return true; - let $schema; - $schema = schema.$schema; - if ($schema !== void 0 && typeof $schema != "string") throw new Error("$schema must be a string"); - $schema = $schema || this.opts.defaultMeta || this.defaultMeta(); - if (!$schema) { - this.logger.warn("meta-schema not available"); - this.errors = null; - return true; - } - const valid = this.validate($schema, schema); - if (!valid && throwOrLogError) { - const message = "schema is invalid: " + this.errorsText(); - if (this.opts.validateSchema === "log") this.logger.error(message); - else throw new Error(message); - } - return valid; - } - getSchema(keyRef) { - let sch; - while (typeof (sch = getSchEnv.call(this, keyRef)) == "string") keyRef = sch; - if (sch === void 0) { - const { schemaId } = this.opts; - const root = new compile_1.SchemaEnv({ - schema: {}, - schemaId - }); - sch = compile_1.resolveSchema.call(this, root, keyRef); - if (!sch) return; - this.refs[keyRef] = sch; - } - return sch.validate || this._compileSchemaEnv(sch); - } - removeSchema(schemaKeyRef) { - if (schemaKeyRef instanceof RegExp) { - this._removeAllSchemas(this.schemas, schemaKeyRef); - this._removeAllSchemas(this.refs, schemaKeyRef); - return this; - } - switch (typeof schemaKeyRef) { - case "undefined": - this._removeAllSchemas(this.schemas); - this._removeAllSchemas(this.refs); - this._cache.clear(); - return this; - case "string": { - const sch = getSchEnv.call(this, schemaKeyRef); - if (typeof sch == "object") this._cache.delete(sch.schema); - delete this.schemas[schemaKeyRef]; - delete this.refs[schemaKeyRef]; - return this; - } - case "object": { - const cacheKey = schemaKeyRef; - this._cache.delete(cacheKey); - let id = schemaKeyRef[this.opts.schemaId]; - if (id) { - id = (0, resolve_1.normalizeId)(id); - delete this.schemas[id]; - delete this.refs[id]; - } - return this; - } - default: throw new Error("ajv.removeSchema: invalid parameter"); - } - } - addVocabulary(definitions) { - for (const def of definitions) this.addKeyword(def); - return this; - } - addKeyword(kwdOrDef, def) { - let keyword; - if (typeof kwdOrDef == "string") { - keyword = kwdOrDef; - if (typeof def == "object") { - this.logger.warn("these parameters are deprecated, see docs for addKeyword"); - def.keyword = keyword; - } - } else if (typeof kwdOrDef == "object" && def === void 0) { - def = kwdOrDef; - keyword = def.keyword; - if (Array.isArray(keyword) && !keyword.length) throw new Error("addKeywords: keyword must be string or non-empty array"); - } else throw new Error("invalid addKeywords parameters"); - checkKeyword.call(this, keyword, def); - if (!def) { - (0, util_1.eachItem)(keyword, (kwd) => addRule.call(this, kwd)); - return this; - } - keywordMetaschema.call(this, def); - const definition = { - ...def, - type: (0, dataType_1.getJSONTypes)(def.type), - schemaType: (0, dataType_1.getJSONTypes)(def.schemaType) - }; - (0, util_1.eachItem)(keyword, definition.type.length === 0 ? (k) => addRule.call(this, k, definition) : (k) => definition.type.forEach((t) => addRule.call(this, k, definition, t))); - return this; - } - getKeyword(keyword) { - const rule = this.RULES.all[keyword]; - return typeof rule == "object" ? rule.definition : !!rule; - } - removeKeyword(keyword) { - const { RULES } = this; - delete RULES.keywords[keyword]; - delete RULES.all[keyword]; - for (const group of RULES.rules) { - const i = group.rules.findIndex((rule) => rule.keyword === keyword); - if (i >= 0) group.rules.splice(i, 1); - } - return this; - } - addFormat(name, format) { - if (typeof format == "string") format = new RegExp(format); - this.formats[name] = format; - return this; - } - errorsText(errors = this.errors, { separator = ", ", dataVar = "data" } = {}) { - if (!errors || errors.length === 0) return "No errors"; - return errors.map((e) => `${dataVar}${e.instancePath} ${e.message}`).reduce((text, msg) => text + separator + msg); - } - $dataMetaSchema(metaSchema, keywordsJsonPointers) { - const rules = this.RULES.all; - metaSchema = JSON.parse(JSON.stringify(metaSchema)); - for (const jsonPointer of keywordsJsonPointers) { - const segments = jsonPointer.split("/").slice(1); - let keywords = metaSchema; - for (const seg of segments) keywords = keywords[seg]; - for (const key in rules) { - const rule = rules[key]; - if (typeof rule != "object") continue; - const { $data } = rule.definition; - const schema = keywords[key]; - if ($data && schema) keywords[key] = schemaOrData(schema); - } - } - return metaSchema; - } - _removeAllSchemas(schemas, regex) { - for (const keyRef in schemas) { - const sch = schemas[keyRef]; - if (!regex || regex.test(keyRef)) { - if (typeof sch == "string") delete schemas[keyRef]; - else if (sch && !sch.meta) { - this._cache.delete(sch.schema); - delete schemas[keyRef]; - } - } - } - } - _addSchema(schema, meta, baseId, validateSchema = this.opts.validateSchema, addSchema = this.opts.addUsedSchema) { - let id; - const { schemaId } = this.opts; - if (typeof schema == "object") id = schema[schemaId]; - else if (this.opts.jtd) throw new Error("schema must be object"); - else if (typeof schema != "boolean") throw new Error("schema must be object or boolean"); - let sch = this._cache.get(schema); - if (sch !== void 0) return sch; - baseId = (0, resolve_1.normalizeId)(id || baseId); - const localRefs = resolve_1.getSchemaRefs.call(this, schema, baseId); - sch = new compile_1.SchemaEnv({ - schema, - schemaId, - meta, - baseId, - localRefs - }); - this._cache.set(sch.schema, sch); - if (addSchema && !baseId.startsWith("#")) { - if (baseId) this._checkUnique(baseId); - this.refs[baseId] = sch; - } - if (validateSchema) this.validateSchema(schema, true); - return sch; - } - _checkUnique(id) { - if (this.schemas[id] || this.refs[id]) throw new Error(`schema with key or id "${id}" already exists`); - } - _compileSchemaEnv(sch) { - if (sch.meta) this._compileMetaSchema(sch); - else compile_1.compileSchema.call(this, sch); - /* istanbul ignore if */ - if (!sch.validate) throw new Error("ajv implementation error"); - return sch.validate; - } - _compileMetaSchema(sch) { - const currentOpts = this.opts; - this.opts = this._metaOpts; - try { - compile_1.compileSchema.call(this, sch); - } finally { - this.opts = currentOpts; - } - } - }; - Ajv.ValidationError = validation_error_1.default; - Ajv.MissingRefError = ref_error_1.default; - exports.default = Ajv; - function checkOptions(checkOpts, options, msg, log = "error") { - for (const key in checkOpts) { - const opt = key; - if (opt in options) this.logger[log](`${msg}: option ${key}. ${checkOpts[opt]}`); - } - } - function getSchEnv(keyRef) { - keyRef = (0, resolve_1.normalizeId)(keyRef); - return this.schemas[keyRef] || this.refs[keyRef]; - } - function addInitialSchemas() { - const optsSchemas = this.opts.schemas; - if (!optsSchemas) return; - if (Array.isArray(optsSchemas)) this.addSchema(optsSchemas); - else for (const key in optsSchemas) this.addSchema(optsSchemas[key], key); - } - function addInitialFormats() { - for (const name in this.opts.formats) { - const format = this.opts.formats[name]; - if (format) this.addFormat(name, format); - } - } - function addInitialKeywords(defs) { - if (Array.isArray(defs)) { - this.addVocabulary(defs); - return; - } - this.logger.warn("keywords option as map is deprecated, pass array"); - for (const keyword in defs) { - const def = defs[keyword]; - if (!def.keyword) def.keyword = keyword; - this.addKeyword(def); - } - } - function getMetaSchemaOptions() { - const metaOpts = { ...this.opts }; - for (const opt of META_IGNORE_OPTIONS) delete metaOpts[opt]; - return metaOpts; - } - const noLogs = { - log() {}, - warn() {}, - error() {} - }; - function getLogger(logger) { - if (logger === false) return noLogs; - if (logger === void 0) return console; - if (logger.log && logger.warn && logger.error) return logger; - throw new Error("logger must implement log, warn and error methods"); - } - const KEYWORD_NAME = /^[a-z_$][a-z0-9_$:-]*$/i; - function checkKeyword(keyword, def) { - const { RULES } = this; - (0, util_1.eachItem)(keyword, (kwd) => { - if (RULES.keywords[kwd]) throw new Error(`Keyword ${kwd} is already defined`); - if (!KEYWORD_NAME.test(kwd)) throw new Error(`Keyword ${kwd} has invalid name`); - }); - if (!def) return; - if (def.$data && !("code" in def || "validate" in def)) throw new Error("$data keyword must have \"code\" or \"validate\" function"); - } - function addRule(keyword, definition, dataType) { - var _a; - const post = definition === null || definition === void 0 ? void 0 : definition.post; - if (dataType && post) throw new Error("keyword with \"post\" flag cannot have \"type\""); - const { RULES } = this; - let ruleGroup = post ? RULES.post : RULES.rules.find(({ type: t }) => t === dataType); - if (!ruleGroup) { - ruleGroup = { - type: dataType, - rules: [] - }; - RULES.rules.push(ruleGroup); - } - RULES.keywords[keyword] = true; - if (!definition) return; - const rule = { - keyword, - definition: { - ...definition, - type: (0, dataType_1.getJSONTypes)(definition.type), - schemaType: (0, dataType_1.getJSONTypes)(definition.schemaType) - } - }; - if (definition.before) addBeforeRule.call(this, ruleGroup, rule, definition.before); - else ruleGroup.rules.push(rule); - RULES.all[keyword] = rule; - (_a = definition.implements) === null || _a === void 0 || _a.forEach((kwd) => this.addKeyword(kwd)); - } - function addBeforeRule(ruleGroup, rule, before) { - const i = ruleGroup.rules.findIndex((_rule) => _rule.keyword === before); - if (i >= 0) ruleGroup.rules.splice(i, 0, rule); - else { - ruleGroup.rules.push(rule); - this.logger.warn(`rule ${before} is not defined`); - } - } - function keywordMetaschema(def) { - let { metaSchema } = def; - if (metaSchema === void 0) return; - if (def.$data && this.opts.$data) metaSchema = schemaOrData(metaSchema); - def.validateSchema = this.compile(metaSchema, true); - } - const $dataRef = { $ref: "https://raw.githubusercontent.com/ajv-validator/ajv/master/lib/refs/data.json#" }; - function schemaOrData(schema) { - return { anyOf: [schema, $dataRef] }; - } -})); - -//#endregion -//#region ../../node_modules/.pnpm/ajv@8.18.0/node_modules/ajv/dist/vocabularies/core/id.js -var require_id = /* @__PURE__ */ __commonJSMin(((exports) => { - Object.defineProperty(exports, "__esModule", { value: true }); - const def = { - keyword: "id", - code() { - throw new Error("NOT SUPPORTED: keyword \"id\", use \"$id\" for schema ID"); - } - }; - exports.default = def; -})); - -//#endregion -//#region ../../node_modules/.pnpm/ajv@8.18.0/node_modules/ajv/dist/vocabularies/core/ref.js -var require_ref = /* @__PURE__ */ __commonJSMin(((exports) => { - Object.defineProperty(exports, "__esModule", { value: true }); - exports.callRef = exports.getValidate = void 0; - const ref_error_1 = require_ref_error(); - const code_1 = require_code(); - const codegen_1 = require_codegen(); - const names_1 = require_names(); - const compile_1 = require_compile(); - const util_1 = require_util(); - const def = { - keyword: "$ref", - schemaType: "string", - code(cxt) { - const { gen, schema: $ref, it } = cxt; - const { baseId, schemaEnv: env, validateName, opts, self } = it; - const { root } = env; - if (($ref === "#" || $ref === "#/") && baseId === root.baseId) return callRootRef(); - const schOrEnv = compile_1.resolveRef.call(self, root, baseId, $ref); - if (schOrEnv === void 0) throw new ref_error_1.default(it.opts.uriResolver, baseId, $ref); - if (schOrEnv instanceof compile_1.SchemaEnv) return callValidate(schOrEnv); - return inlineRefSchema(schOrEnv); - function callRootRef() { - if (env === root) return callRef(cxt, validateName, env, env.$async); - const rootName = gen.scopeValue("root", { ref: root }); - return callRef(cxt, (0, codegen_1._)`${rootName}.validate`, root, root.$async); - } - function callValidate(sch) { - callRef(cxt, getValidate(cxt, sch), sch, sch.$async); - } - function inlineRefSchema(sch) { - const schName = gen.scopeValue("schema", opts.code.source === true ? { - ref: sch, - code: (0, codegen_1.stringify)(sch) - } : { ref: sch }); - const valid = gen.name("valid"); - const schCxt = cxt.subschema({ - schema: sch, - dataTypes: [], - schemaPath: codegen_1.nil, - topSchemaRef: schName, - errSchemaPath: $ref - }, valid); - cxt.mergeEvaluated(schCxt); - cxt.ok(valid); - } - } - }; - function getValidate(cxt, sch) { - const { gen } = cxt; - return sch.validate ? gen.scopeValue("validate", { ref: sch.validate }) : (0, codegen_1._)`${gen.scopeValue("wrapper", { ref: sch })}.validate`; - } - exports.getValidate = getValidate; - function callRef(cxt, v, sch, $async) { - const { gen, it } = cxt; - const { allErrors, schemaEnv: env, opts } = it; - const passCxt = opts.passContext ? names_1.default.this : codegen_1.nil; - if ($async) callAsyncRef(); - else callSyncRef(); - function callAsyncRef() { - if (!env.$async) throw new Error("async schema referenced by sync schema"); - const valid = gen.let("valid"); - gen.try(() => { - gen.code((0, codegen_1._)`await ${(0, code_1.callValidateCode)(cxt, v, passCxt)}`); - addEvaluatedFrom(v); - if (!allErrors) gen.assign(valid, true); - }, (e) => { - gen.if((0, codegen_1._)`!(${e} instanceof ${it.ValidationError})`, () => gen.throw(e)); - addErrorsFrom(e); - if (!allErrors) gen.assign(valid, false); - }); - cxt.ok(valid); - } - function callSyncRef() { - cxt.result((0, code_1.callValidateCode)(cxt, v, passCxt), () => addEvaluatedFrom(v), () => addErrorsFrom(v)); - } - function addErrorsFrom(source) { - const errs = (0, codegen_1._)`${source}.errors`; - gen.assign(names_1.default.vErrors, (0, codegen_1._)`${names_1.default.vErrors} === null ? ${errs} : ${names_1.default.vErrors}.concat(${errs})`); - gen.assign(names_1.default.errors, (0, codegen_1._)`${names_1.default.vErrors}.length`); - } - function addEvaluatedFrom(source) { - var _a; - if (!it.opts.unevaluated) return; - const schEvaluated = (_a = sch === null || sch === void 0 ? void 0 : sch.validate) === null || _a === void 0 ? void 0 : _a.evaluated; - if (it.props !== true) if (schEvaluated && !schEvaluated.dynamicProps) { - if (schEvaluated.props !== void 0) it.props = util_1.mergeEvaluated.props(gen, schEvaluated.props, it.props); - } else { - const props = gen.var("props", (0, codegen_1._)`${source}.evaluated.props`); - it.props = util_1.mergeEvaluated.props(gen, props, it.props, codegen_1.Name); - } - if (it.items !== true) if (schEvaluated && !schEvaluated.dynamicItems) { - if (schEvaluated.items !== void 0) it.items = util_1.mergeEvaluated.items(gen, schEvaluated.items, it.items); - } else { - const items = gen.var("items", (0, codegen_1._)`${source}.evaluated.items`); - it.items = util_1.mergeEvaluated.items(gen, items, it.items, codegen_1.Name); - } - } - } - exports.callRef = callRef; - exports.default = def; -})); - -//#endregion -//#region ../../node_modules/.pnpm/ajv@8.18.0/node_modules/ajv/dist/vocabularies/core/index.js -var require_core$2 = /* @__PURE__ */ __commonJSMin(((exports) => { - Object.defineProperty(exports, "__esModule", { value: true }); - const id_1 = require_id(); - const ref_1 = require_ref(); - const core = [ - "$schema", - "$id", - "$defs", - "$vocabulary", - { keyword: "$comment" }, - "definitions", - id_1.default, - ref_1.default - ]; - exports.default = core; -})); - -//#endregion -//#region ../../node_modules/.pnpm/ajv@8.18.0/node_modules/ajv/dist/vocabularies/validation/limitNumber.js -var require_limitNumber = /* @__PURE__ */ __commonJSMin(((exports) => { - Object.defineProperty(exports, "__esModule", { value: true }); - const codegen_1 = require_codegen(); - const ops = codegen_1.operators; - const KWDs = { - maximum: { - okStr: "<=", - ok: ops.LTE, - fail: ops.GT - }, - minimum: { - okStr: ">=", - ok: ops.GTE, - fail: ops.LT - }, - exclusiveMaximum: { - okStr: "<", - ok: ops.LT, - fail: ops.GTE - }, - exclusiveMinimum: { - okStr: ">", - ok: ops.GT, - fail: ops.LTE - } - }; - const def = { - keyword: Object.keys(KWDs), - type: "number", - schemaType: "number", - $data: true, - error: { - message: ({ keyword, schemaCode }) => (0, codegen_1.str)`must be ${KWDs[keyword].okStr} ${schemaCode}`, - params: ({ keyword, schemaCode }) => (0, codegen_1._)`{comparison: ${KWDs[keyword].okStr}, limit: ${schemaCode}}` - }, - code(cxt) { - const { keyword, data, schemaCode } = cxt; - cxt.fail$data((0, codegen_1._)`${data} ${KWDs[keyword].fail} ${schemaCode} || isNaN(${data})`); - } - }; - exports.default = def; -})); - -//#endregion -//#region ../../node_modules/.pnpm/ajv@8.18.0/node_modules/ajv/dist/vocabularies/validation/multipleOf.js -var require_multipleOf = /* @__PURE__ */ __commonJSMin(((exports) => { - Object.defineProperty(exports, "__esModule", { value: true }); - const codegen_1 = require_codegen(); - const def = { - keyword: "multipleOf", - type: "number", - schemaType: "number", - $data: true, - error: { - message: ({ schemaCode }) => (0, codegen_1.str)`must be multiple of ${schemaCode}`, - params: ({ schemaCode }) => (0, codegen_1._)`{multipleOf: ${schemaCode}}` - }, - code(cxt) { - const { gen, data, schemaCode, it } = cxt; - const prec = it.opts.multipleOfPrecision; - const res = gen.let("res"); - const invalid = prec ? (0, codegen_1._)`Math.abs(Math.round(${res}) - ${res}) > 1e-${prec}` : (0, codegen_1._)`${res} !== parseInt(${res})`; - cxt.fail$data((0, codegen_1._)`(${schemaCode} === 0 || (${res} = ${data}/${schemaCode}, ${invalid}))`); - } - }; - exports.default = def; -})); - -//#endregion -//#region ../../node_modules/.pnpm/ajv@8.18.0/node_modules/ajv/dist/runtime/ucs2length.js -var require_ucs2length = /* @__PURE__ */ __commonJSMin(((exports) => { - Object.defineProperty(exports, "__esModule", { value: true }); - function ucs2length(str) { - const len = str.length; - let length = 0; - let pos = 0; - let value; - while (pos < len) { - length++; - value = str.charCodeAt(pos++); - if (value >= 55296 && value <= 56319 && pos < len) { - value = str.charCodeAt(pos); - if ((value & 64512) === 56320) pos++; - } - } - return length; - } - exports.default = ucs2length; - ucs2length.code = "require(\"ajv/dist/runtime/ucs2length\").default"; -})); - -//#endregion -//#region ../../node_modules/.pnpm/ajv@8.18.0/node_modules/ajv/dist/vocabularies/validation/limitLength.js -var require_limitLength = /* @__PURE__ */ __commonJSMin(((exports) => { - Object.defineProperty(exports, "__esModule", { value: true }); - const codegen_1 = require_codegen(); - const util_1 = require_util(); - const ucs2length_1 = require_ucs2length(); - const def = { - keyword: ["maxLength", "minLength"], - type: "string", - schemaType: "number", - $data: true, - error: { - message({ keyword, schemaCode }) { - const comp = keyword === "maxLength" ? "more" : "fewer"; - return (0, codegen_1.str)`must NOT have ${comp} than ${schemaCode} characters`; - }, - params: ({ schemaCode }) => (0, codegen_1._)`{limit: ${schemaCode}}` - }, - code(cxt) { - const { keyword, data, schemaCode, it } = cxt; - const op = keyword === "maxLength" ? codegen_1.operators.GT : codegen_1.operators.LT; - const len = it.opts.unicode === false ? (0, codegen_1._)`${data}.length` : (0, codegen_1._)`${(0, util_1.useFunc)(cxt.gen, ucs2length_1.default)}(${data})`; - cxt.fail$data((0, codegen_1._)`${len} ${op} ${schemaCode}`); - } - }; - exports.default = def; -})); - -//#endregion -//#region ../../node_modules/.pnpm/ajv@8.18.0/node_modules/ajv/dist/vocabularies/validation/pattern.js -var require_pattern = /* @__PURE__ */ __commonJSMin(((exports) => { - Object.defineProperty(exports, "__esModule", { value: true }); - const code_1 = require_code(); - const util_1 = require_util(); - const codegen_1 = require_codegen(); - const def = { - keyword: "pattern", - type: "string", - schemaType: "string", - $data: true, - error: { - message: ({ schemaCode }) => (0, codegen_1.str)`must match pattern "${schemaCode}"`, - params: ({ schemaCode }) => (0, codegen_1._)`{pattern: ${schemaCode}}` - }, - code(cxt) { - const { gen, data, $data, schema, schemaCode, it } = cxt; - const u = it.opts.unicodeRegExp ? "u" : ""; - if ($data) { - const { regExp } = it.opts.code; - const regExpCode = regExp.code === "new RegExp" ? (0, codegen_1._)`new RegExp` : (0, util_1.useFunc)(gen, regExp); - const valid = gen.let("valid"); - gen.try(() => gen.assign(valid, (0, codegen_1._)`${regExpCode}(${schemaCode}, ${u}).test(${data})`), () => gen.assign(valid, false)); - cxt.fail$data((0, codegen_1._)`!${valid}`); - } else { - const regExp = (0, code_1.usePattern)(cxt, schema); - cxt.fail$data((0, codegen_1._)`!${regExp}.test(${data})`); - } - } - }; - exports.default = def; -})); - -//#endregion -//#region ../../node_modules/.pnpm/ajv@8.18.0/node_modules/ajv/dist/vocabularies/validation/limitProperties.js -var require_limitProperties = /* @__PURE__ */ __commonJSMin(((exports) => { - Object.defineProperty(exports, "__esModule", { value: true }); - const codegen_1 = require_codegen(); - const def = { - keyword: ["maxProperties", "minProperties"], - type: "object", - schemaType: "number", - $data: true, - error: { - message({ keyword, schemaCode }) { - const comp = keyword === "maxProperties" ? "more" : "fewer"; - return (0, codegen_1.str)`must NOT have ${comp} than ${schemaCode} properties`; - }, - params: ({ schemaCode }) => (0, codegen_1._)`{limit: ${schemaCode}}` - }, - code(cxt) { - const { keyword, data, schemaCode } = cxt; - const op = keyword === "maxProperties" ? codegen_1.operators.GT : codegen_1.operators.LT; - cxt.fail$data((0, codegen_1._)`Object.keys(${data}).length ${op} ${schemaCode}`); - } - }; - exports.default = def; -})); - -//#endregion -//#region ../../node_modules/.pnpm/ajv@8.18.0/node_modules/ajv/dist/vocabularies/validation/required.js -var require_required = /* @__PURE__ */ __commonJSMin(((exports) => { - Object.defineProperty(exports, "__esModule", { value: true }); - const code_1 = require_code(); - const codegen_1 = require_codegen(); - const util_1 = require_util(); - const def = { - keyword: "required", - type: "object", - schemaType: "array", - $data: true, - error: { - message: ({ params: { missingProperty } }) => (0, codegen_1.str)`must have required property '${missingProperty}'`, - params: ({ params: { missingProperty } }) => (0, codegen_1._)`{missingProperty: ${missingProperty}}` - }, - code(cxt) { - const { gen, schema, schemaCode, data, $data, it } = cxt; - const { opts } = it; - if (!$data && schema.length === 0) return; - const useLoop = schema.length >= opts.loopRequired; - if (it.allErrors) allErrorsMode(); - else exitOnErrorMode(); - if (opts.strictRequired) { - const props = cxt.parentSchema.properties; - const { definedProperties } = cxt.it; - for (const requiredKey of schema) if ((props === null || props === void 0 ? void 0 : props[requiredKey]) === void 0 && !definedProperties.has(requiredKey)) { - const msg = `required property "${requiredKey}" is not defined at "${it.schemaEnv.baseId + it.errSchemaPath}" (strictRequired)`; - (0, util_1.checkStrictMode)(it, msg, it.opts.strictRequired); - } - } - function allErrorsMode() { - if (useLoop || $data) cxt.block$data(codegen_1.nil, loopAllRequired); - else for (const prop of schema) (0, code_1.checkReportMissingProp)(cxt, prop); - } - function exitOnErrorMode() { - const missing = gen.let("missing"); - if (useLoop || $data) { - const valid = gen.let("valid", true); - cxt.block$data(valid, () => loopUntilMissing(missing, valid)); - cxt.ok(valid); - } else { - gen.if((0, code_1.checkMissingProp)(cxt, schema, missing)); - (0, code_1.reportMissingProp)(cxt, missing); - gen.else(); - } - } - function loopAllRequired() { - gen.forOf("prop", schemaCode, (prop) => { - cxt.setParams({ missingProperty: prop }); - gen.if((0, code_1.noPropertyInData)(gen, data, prop, opts.ownProperties), () => cxt.error()); - }); - } - function loopUntilMissing(missing, valid) { - cxt.setParams({ missingProperty: missing }); - gen.forOf(missing, schemaCode, () => { - gen.assign(valid, (0, code_1.propertyInData)(gen, data, missing, opts.ownProperties)); - gen.if((0, codegen_1.not)(valid), () => { - cxt.error(); - gen.break(); - }); - }, codegen_1.nil); - } - } - }; - exports.default = def; -})); - -//#endregion -//#region ../../node_modules/.pnpm/ajv@8.18.0/node_modules/ajv/dist/vocabularies/validation/limitItems.js -var require_limitItems = /* @__PURE__ */ __commonJSMin(((exports) => { - Object.defineProperty(exports, "__esModule", { value: true }); - const codegen_1 = require_codegen(); - const def = { - keyword: ["maxItems", "minItems"], - type: "array", - schemaType: "number", - $data: true, - error: { - message({ keyword, schemaCode }) { - const comp = keyword === "maxItems" ? "more" : "fewer"; - return (0, codegen_1.str)`must NOT have ${comp} than ${schemaCode} items`; - }, - params: ({ schemaCode }) => (0, codegen_1._)`{limit: ${schemaCode}}` - }, - code(cxt) { - const { keyword, data, schemaCode } = cxt; - const op = keyword === "maxItems" ? codegen_1.operators.GT : codegen_1.operators.LT; - cxt.fail$data((0, codegen_1._)`${data}.length ${op} ${schemaCode}`); - } - }; - exports.default = def; -})); - -//#endregion -//#region ../../node_modules/.pnpm/ajv@8.18.0/node_modules/ajv/dist/runtime/equal.js -var require_equal = /* @__PURE__ */ __commonJSMin(((exports) => { - Object.defineProperty(exports, "__esModule", { value: true }); - const equal = require_fast_deep_equal(); - equal.code = "require(\"ajv/dist/runtime/equal\").default"; - exports.default = equal; -})); - -//#endregion -//#region ../../node_modules/.pnpm/ajv@8.18.0/node_modules/ajv/dist/vocabularies/validation/uniqueItems.js -var require_uniqueItems = /* @__PURE__ */ __commonJSMin(((exports) => { - Object.defineProperty(exports, "__esModule", { value: true }); - const dataType_1 = require_dataType(); - const codegen_1 = require_codegen(); - const util_1 = require_util(); - const equal_1 = require_equal(); - const def = { - keyword: "uniqueItems", - type: "array", - schemaType: "boolean", - $data: true, - error: { - message: ({ params: { i, j } }) => (0, codegen_1.str)`must NOT have duplicate items (items ## ${j} and ${i} are identical)`, - params: ({ params: { i, j } }) => (0, codegen_1._)`{i: ${i}, j: ${j}}` - }, - code(cxt) { - const { gen, data, $data, schema, parentSchema, schemaCode, it } = cxt; - if (!$data && !schema) return; - const valid = gen.let("valid"); - const itemTypes = parentSchema.items ? (0, dataType_1.getSchemaTypes)(parentSchema.items) : []; - cxt.block$data(valid, validateUniqueItems, (0, codegen_1._)`${schemaCode} === false`); - cxt.ok(valid); - function validateUniqueItems() { - const i = gen.let("i", (0, codegen_1._)`${data}.length`); - const j = gen.let("j"); - cxt.setParams({ - i, - j - }); - gen.assign(valid, true); - gen.if((0, codegen_1._)`${i} > 1`, () => (canOptimize() ? loopN : loopN2)(i, j)); - } - function canOptimize() { - return itemTypes.length > 0 && !itemTypes.some((t) => t === "object" || t === "array"); - } - function loopN(i, j) { - const item = gen.name("item"); - const wrongType = (0, dataType_1.checkDataTypes)(itemTypes, item, it.opts.strictNumbers, dataType_1.DataType.Wrong); - const indices = gen.const("indices", (0, codegen_1._)`{}`); - gen.for((0, codegen_1._)`;${i}--;`, () => { - gen.let(item, (0, codegen_1._)`${data}[${i}]`); - gen.if(wrongType, (0, codegen_1._)`continue`); - if (itemTypes.length > 1) gen.if((0, codegen_1._)`typeof ${item} == "string"`, (0, codegen_1._)`${item} += "_"`); - gen.if((0, codegen_1._)`typeof ${indices}[${item}] == "number"`, () => { - gen.assign(j, (0, codegen_1._)`${indices}[${item}]`); - cxt.error(); - gen.assign(valid, false).break(); - }).code((0, codegen_1._)`${indices}[${item}] = ${i}`); - }); - } - function loopN2(i, j) { - const eql = (0, util_1.useFunc)(gen, equal_1.default); - const outer = gen.name("outer"); - gen.label(outer).for((0, codegen_1._)`;${i}--;`, () => gen.for((0, codegen_1._)`${j} = ${i}; ${j}--;`, () => gen.if((0, codegen_1._)`${eql}(${data}[${i}], ${data}[${j}])`, () => { - cxt.error(); - gen.assign(valid, false).break(outer); - }))); - } - } - }; - exports.default = def; -})); - -//#endregion -//#region ../../node_modules/.pnpm/ajv@8.18.0/node_modules/ajv/dist/vocabularies/validation/const.js -var require_const = /* @__PURE__ */ __commonJSMin(((exports) => { - Object.defineProperty(exports, "__esModule", { value: true }); - const codegen_1 = require_codegen(); - const util_1 = require_util(); - const equal_1 = require_equal(); - const def = { - keyword: "const", - $data: true, - error: { - message: "must be equal to constant", - params: ({ schemaCode }) => (0, codegen_1._)`{allowedValue: ${schemaCode}}` - }, - code(cxt) { - const { gen, data, $data, schemaCode, schema } = cxt; - if ($data || schema && typeof schema == "object") cxt.fail$data((0, codegen_1._)`!${(0, util_1.useFunc)(gen, equal_1.default)}(${data}, ${schemaCode})`); - else cxt.fail((0, codegen_1._)`${schema} !== ${data}`); - } - }; - exports.default = def; -})); - -//#endregion -//#region ../../node_modules/.pnpm/ajv@8.18.0/node_modules/ajv/dist/vocabularies/validation/enum.js -var require_enum = /* @__PURE__ */ __commonJSMin(((exports) => { - Object.defineProperty(exports, "__esModule", { value: true }); - const codegen_1 = require_codegen(); - const util_1 = require_util(); - const equal_1 = require_equal(); - const def = { - keyword: "enum", - schemaType: "array", - $data: true, - error: { - message: "must be equal to one of the allowed values", - params: ({ schemaCode }) => (0, codegen_1._)`{allowedValues: ${schemaCode}}` - }, - code(cxt) { - const { gen, data, $data, schema, schemaCode, it } = cxt; - if (!$data && schema.length === 0) throw new Error("enum must have non-empty array"); - const useLoop = schema.length >= it.opts.loopEnum; - let eql; - const getEql = () => eql !== null && eql !== void 0 ? eql : eql = (0, util_1.useFunc)(gen, equal_1.default); - let valid; - if (useLoop || $data) { - valid = gen.let("valid"); - cxt.block$data(valid, loopEnum); - } else { - /* istanbul ignore if */ - if (!Array.isArray(schema)) throw new Error("ajv implementation error"); - const vSchema = gen.const("vSchema", schemaCode); - valid = (0, codegen_1.or)(...schema.map((_x, i) => equalCode(vSchema, i))); - } - cxt.pass(valid); - function loopEnum() { - gen.assign(valid, false); - gen.forOf("v", schemaCode, (v) => gen.if((0, codegen_1._)`${getEql()}(${data}, ${v})`, () => gen.assign(valid, true).break())); - } - function equalCode(vSchema, i) { - const sch = schema[i]; - return typeof sch === "object" && sch !== null ? (0, codegen_1._)`${getEql()}(${data}, ${vSchema}[${i}])` : (0, codegen_1._)`${data} === ${sch}`; - } - } - }; - exports.default = def; -})); - -//#endregion -//#region ../../node_modules/.pnpm/ajv@8.18.0/node_modules/ajv/dist/vocabularies/validation/index.js -var require_validation$2 = /* @__PURE__ */ __commonJSMin(((exports) => { - Object.defineProperty(exports, "__esModule", { value: true }); - const limitNumber_1 = require_limitNumber(); - const multipleOf_1 = require_multipleOf(); - const limitLength_1 = require_limitLength(); - const pattern_1 = require_pattern(); - const limitProperties_1 = require_limitProperties(); - const required_1 = require_required(); - const limitItems_1 = require_limitItems(); - const uniqueItems_1 = require_uniqueItems(); - const const_1 = require_const(); - const enum_1 = require_enum(); - const validation = [ - limitNumber_1.default, - multipleOf_1.default, - limitLength_1.default, - pattern_1.default, - limitProperties_1.default, - required_1.default, - limitItems_1.default, - uniqueItems_1.default, - { - keyword: "type", - schemaType: ["string", "array"] - }, - { - keyword: "nullable", - schemaType: "boolean" - }, - const_1.default, - enum_1.default - ]; - exports.default = validation; -})); - -//#endregion -//#region ../../node_modules/.pnpm/ajv@8.18.0/node_modules/ajv/dist/vocabularies/applicator/additionalItems.js -var require_additionalItems = /* @__PURE__ */ __commonJSMin(((exports) => { - Object.defineProperty(exports, "__esModule", { value: true }); - exports.validateAdditionalItems = void 0; - const codegen_1 = require_codegen(); - const util_1 = require_util(); - const def = { - keyword: "additionalItems", - type: "array", - schemaType: ["boolean", "object"], - before: "uniqueItems", - error: { - message: ({ params: { len } }) => (0, codegen_1.str)`must NOT have more than ${len} items`, - params: ({ params: { len } }) => (0, codegen_1._)`{limit: ${len}}` - }, - code(cxt) { - const { parentSchema, it } = cxt; - const { items } = parentSchema; - if (!Array.isArray(items)) { - (0, util_1.checkStrictMode)(it, "\"additionalItems\" is ignored when \"items\" is not an array of schemas"); - return; - } - validateAdditionalItems(cxt, items); - } - }; - function validateAdditionalItems(cxt, items) { - const { gen, schema, data, keyword, it } = cxt; - it.items = true; - const len = gen.const("len", (0, codegen_1._)`${data}.length`); - if (schema === false) { - cxt.setParams({ len: items.length }); - cxt.pass((0, codegen_1._)`${len} <= ${items.length}`); - } else if (typeof schema == "object" && !(0, util_1.alwaysValidSchema)(it, schema)) { - const valid = gen.var("valid", (0, codegen_1._)`${len} <= ${items.length}`); - gen.if((0, codegen_1.not)(valid), () => validateItems(valid)); - cxt.ok(valid); - } - function validateItems(valid) { - gen.forRange("i", items.length, len, (i) => { - cxt.subschema({ - keyword, - dataProp: i, - dataPropType: util_1.Type.Num - }, valid); - if (!it.allErrors) gen.if((0, codegen_1.not)(valid), () => gen.break()); - }); - } - } - exports.validateAdditionalItems = validateAdditionalItems; - exports.default = def; -})); - -//#endregion -//#region ../../node_modules/.pnpm/ajv@8.18.0/node_modules/ajv/dist/vocabularies/applicator/items.js -var require_items = /* @__PURE__ */ __commonJSMin(((exports) => { - Object.defineProperty(exports, "__esModule", { value: true }); - exports.validateTuple = void 0; - const codegen_1 = require_codegen(); - const util_1 = require_util(); - const code_1 = require_code(); - const def = { - keyword: "items", - type: "array", - schemaType: [ - "object", - "array", - "boolean" - ], - before: "uniqueItems", - code(cxt) { - const { schema, it } = cxt; - if (Array.isArray(schema)) return validateTuple(cxt, "additionalItems", schema); - it.items = true; - if ((0, util_1.alwaysValidSchema)(it, schema)) return; - cxt.ok((0, code_1.validateArray)(cxt)); - } - }; - function validateTuple(cxt, extraItems, schArr = cxt.schema) { - const { gen, parentSchema, data, keyword, it } = cxt; - checkStrictTuple(parentSchema); - if (it.opts.unevaluated && schArr.length && it.items !== true) it.items = util_1.mergeEvaluated.items(gen, schArr.length, it.items); - const valid = gen.name("valid"); - const len = gen.const("len", (0, codegen_1._)`${data}.length`); - schArr.forEach((sch, i) => { - if ((0, util_1.alwaysValidSchema)(it, sch)) return; - gen.if((0, codegen_1._)`${len} > ${i}`, () => cxt.subschema({ - keyword, - schemaProp: i, - dataProp: i - }, valid)); - cxt.ok(valid); - }); - function checkStrictTuple(sch) { - const { opts, errSchemaPath } = it; - const l = schArr.length; - const fullTuple = l === sch.minItems && (l === sch.maxItems || sch[extraItems] === false); - if (opts.strictTuples && !fullTuple) { - const msg = `"${keyword}" is ${l}-tuple, but minItems or maxItems/${extraItems} are not specified or different at path "${errSchemaPath}"`; - (0, util_1.checkStrictMode)(it, msg, opts.strictTuples); - } - } - } - exports.validateTuple = validateTuple; - exports.default = def; -})); - -//#endregion -//#region ../../node_modules/.pnpm/ajv@8.18.0/node_modules/ajv/dist/vocabularies/applicator/prefixItems.js -var require_prefixItems = /* @__PURE__ */ __commonJSMin(((exports) => { - Object.defineProperty(exports, "__esModule", { value: true }); - const items_1 = require_items(); - const def = { - keyword: "prefixItems", - type: "array", - schemaType: ["array"], - before: "uniqueItems", - code: (cxt) => (0, items_1.validateTuple)(cxt, "items") - }; - exports.default = def; -})); - -//#endregion -//#region ../../node_modules/.pnpm/ajv@8.18.0/node_modules/ajv/dist/vocabularies/applicator/items2020.js -var require_items2020 = /* @__PURE__ */ __commonJSMin(((exports) => { - Object.defineProperty(exports, "__esModule", { value: true }); - const codegen_1 = require_codegen(); - const util_1 = require_util(); - const code_1 = require_code(); - const additionalItems_1 = require_additionalItems(); - const def = { - keyword: "items", - type: "array", - schemaType: ["object", "boolean"], - before: "uniqueItems", - error: { - message: ({ params: { len } }) => (0, codegen_1.str)`must NOT have more than ${len} items`, - params: ({ params: { len } }) => (0, codegen_1._)`{limit: ${len}}` - }, - code(cxt) { - const { schema, parentSchema, it } = cxt; - const { prefixItems } = parentSchema; - it.items = true; - if ((0, util_1.alwaysValidSchema)(it, schema)) return; - if (prefixItems) (0, additionalItems_1.validateAdditionalItems)(cxt, prefixItems); - else cxt.ok((0, code_1.validateArray)(cxt)); - } - }; - exports.default = def; -})); - -//#endregion -//#region ../../node_modules/.pnpm/ajv@8.18.0/node_modules/ajv/dist/vocabularies/applicator/contains.js -var require_contains = /* @__PURE__ */ __commonJSMin(((exports) => { - Object.defineProperty(exports, "__esModule", { value: true }); - const codegen_1 = require_codegen(); - const util_1 = require_util(); - const def = { - keyword: "contains", - type: "array", - schemaType: ["object", "boolean"], - before: "uniqueItems", - trackErrors: true, - error: { - message: ({ params: { min, max } }) => max === void 0 ? (0, codegen_1.str)`must contain at least ${min} valid item(s)` : (0, codegen_1.str)`must contain at least ${min} and no more than ${max} valid item(s)`, - params: ({ params: { min, max } }) => max === void 0 ? (0, codegen_1._)`{minContains: ${min}}` : (0, codegen_1._)`{minContains: ${min}, maxContains: ${max}}` - }, - code(cxt) { - const { gen, schema, parentSchema, data, it } = cxt; - let min; - let max; - const { minContains, maxContains } = parentSchema; - if (it.opts.next) { - min = minContains === void 0 ? 1 : minContains; - max = maxContains; - } else min = 1; - const len = gen.const("len", (0, codegen_1._)`${data}.length`); - cxt.setParams({ - min, - max - }); - if (max === void 0 && min === 0) { - (0, util_1.checkStrictMode)(it, `"minContains" == 0 without "maxContains": "contains" keyword ignored`); - return; - } - if (max !== void 0 && min > max) { - (0, util_1.checkStrictMode)(it, `"minContains" > "maxContains" is always invalid`); - cxt.fail(); - return; - } - if ((0, util_1.alwaysValidSchema)(it, schema)) { - let cond = (0, codegen_1._)`${len} >= ${min}`; - if (max !== void 0) cond = (0, codegen_1._)`${cond} && ${len} <= ${max}`; - cxt.pass(cond); - return; - } - it.items = true; - const valid = gen.name("valid"); - if (max === void 0 && min === 1) validateItems(valid, () => gen.if(valid, () => gen.break())); - else if (min === 0) { - gen.let(valid, true); - if (max !== void 0) gen.if((0, codegen_1._)`${data}.length > 0`, validateItemsWithCount); - } else { - gen.let(valid, false); - validateItemsWithCount(); - } - cxt.result(valid, () => cxt.reset()); - function validateItemsWithCount() { - const schValid = gen.name("_valid"); - const count = gen.let("count", 0); - validateItems(schValid, () => gen.if(schValid, () => checkLimits(count))); - } - function validateItems(_valid, block) { - gen.forRange("i", 0, len, (i) => { - cxt.subschema({ - keyword: "contains", - dataProp: i, - dataPropType: util_1.Type.Num, - compositeRule: true - }, _valid); - block(); - }); - } - function checkLimits(count) { - gen.code((0, codegen_1._)`${count}++`); - if (max === void 0) gen.if((0, codegen_1._)`${count} >= ${min}`, () => gen.assign(valid, true).break()); - else { - gen.if((0, codegen_1._)`${count} > ${max}`, () => gen.assign(valid, false).break()); - if (min === 1) gen.assign(valid, true); - else gen.if((0, codegen_1._)`${count} >= ${min}`, () => gen.assign(valid, true)); - } - } - } - }; - exports.default = def; -})); - -//#endregion -//#region ../../node_modules/.pnpm/ajv@8.18.0/node_modules/ajv/dist/vocabularies/applicator/dependencies.js -var require_dependencies = /* @__PURE__ */ __commonJSMin(((exports) => { - Object.defineProperty(exports, "__esModule", { value: true }); - exports.validateSchemaDeps = exports.validatePropertyDeps = exports.error = void 0; - const codegen_1 = require_codegen(); - const util_1 = require_util(); - const code_1 = require_code(); - exports.error = { - message: ({ params: { property, depsCount, deps } }) => { - const property_ies = depsCount === 1 ? "property" : "properties"; - return (0, codegen_1.str)`must have ${property_ies} ${deps} when property ${property} is present`; - }, - params: ({ params: { property, depsCount, deps, missingProperty } }) => (0, codegen_1._)`{property: ${property}, - missingProperty: ${missingProperty}, - depsCount: ${depsCount}, - deps: ${deps}}` - }; - const def = { - keyword: "dependencies", - type: "object", - schemaType: "object", - error: exports.error, - code(cxt) { - const [propDeps, schDeps] = splitDependencies(cxt); - validatePropertyDeps(cxt, propDeps); - validateSchemaDeps(cxt, schDeps); - } - }; - function splitDependencies({ schema }) { - const propertyDeps = {}; - const schemaDeps = {}; - for (const key in schema) { - if (key === "__proto__") continue; - const deps = Array.isArray(schema[key]) ? propertyDeps : schemaDeps; - deps[key] = schema[key]; - } - return [propertyDeps, schemaDeps]; - } - function validatePropertyDeps(cxt, propertyDeps = cxt.schema) { - const { gen, data, it } = cxt; - if (Object.keys(propertyDeps).length === 0) return; - const missing = gen.let("missing"); - for (const prop in propertyDeps) { - const deps = propertyDeps[prop]; - if (deps.length === 0) continue; - const hasProperty = (0, code_1.propertyInData)(gen, data, prop, it.opts.ownProperties); - cxt.setParams({ - property: prop, - depsCount: deps.length, - deps: deps.join(", ") - }); - if (it.allErrors) gen.if(hasProperty, () => { - for (const depProp of deps) (0, code_1.checkReportMissingProp)(cxt, depProp); - }); - else { - gen.if((0, codegen_1._)`${hasProperty} && (${(0, code_1.checkMissingProp)(cxt, deps, missing)})`); - (0, code_1.reportMissingProp)(cxt, missing); - gen.else(); - } - } - } - exports.validatePropertyDeps = validatePropertyDeps; - function validateSchemaDeps(cxt, schemaDeps = cxt.schema) { - const { gen, data, keyword, it } = cxt; - const valid = gen.name("valid"); - for (const prop in schemaDeps) { - if ((0, util_1.alwaysValidSchema)(it, schemaDeps[prop])) continue; - gen.if((0, code_1.propertyInData)(gen, data, prop, it.opts.ownProperties), () => { - const schCxt = cxt.subschema({ - keyword, - schemaProp: prop - }, valid); - cxt.mergeValidEvaluated(schCxt, valid); - }, () => gen.var(valid, true)); - cxt.ok(valid); - } - } - exports.validateSchemaDeps = validateSchemaDeps; - exports.default = def; -})); - -//#endregion -//#region ../../node_modules/.pnpm/ajv@8.18.0/node_modules/ajv/dist/vocabularies/applicator/propertyNames.js -var require_propertyNames = /* @__PURE__ */ __commonJSMin(((exports) => { - Object.defineProperty(exports, "__esModule", { value: true }); - const codegen_1 = require_codegen(); - const util_1 = require_util(); - const def = { - keyword: "propertyNames", - type: "object", - schemaType: ["object", "boolean"], - error: { - message: "property name must be valid", - params: ({ params }) => (0, codegen_1._)`{propertyName: ${params.propertyName}}` - }, - code(cxt) { - const { gen, schema, data, it } = cxt; - if ((0, util_1.alwaysValidSchema)(it, schema)) return; - const valid = gen.name("valid"); - gen.forIn("key", data, (key) => { - cxt.setParams({ propertyName: key }); - cxt.subschema({ - keyword: "propertyNames", - data: key, - dataTypes: ["string"], - propertyName: key, - compositeRule: true - }, valid); - gen.if((0, codegen_1.not)(valid), () => { - cxt.error(true); - if (!it.allErrors) gen.break(); - }); - }); - cxt.ok(valid); - } - }; - exports.default = def; -})); - -//#endregion -//#region ../../node_modules/.pnpm/ajv@8.18.0/node_modules/ajv/dist/vocabularies/applicator/additionalProperties.js -var require_additionalProperties = /* @__PURE__ */ __commonJSMin(((exports) => { - Object.defineProperty(exports, "__esModule", { value: true }); - const code_1 = require_code(); - const codegen_1 = require_codegen(); - const names_1 = require_names(); - const util_1 = require_util(); - const def = { - keyword: "additionalProperties", - type: ["object"], - schemaType: ["boolean", "object"], - allowUndefined: true, - trackErrors: true, - error: { - message: "must NOT have additional properties", - params: ({ params }) => (0, codegen_1._)`{additionalProperty: ${params.additionalProperty}}` - }, - code(cxt) { - const { gen, schema, parentSchema, data, errsCount, it } = cxt; - /* istanbul ignore if */ - if (!errsCount) throw new Error("ajv implementation error"); - const { allErrors, opts } = it; - it.props = true; - if (opts.removeAdditional !== "all" && (0, util_1.alwaysValidSchema)(it, schema)) return; - const props = (0, code_1.allSchemaProperties)(parentSchema.properties); - const patProps = (0, code_1.allSchemaProperties)(parentSchema.patternProperties); - checkAdditionalProperties(); - cxt.ok((0, codegen_1._)`${errsCount} === ${names_1.default.errors}`); - function checkAdditionalProperties() { - gen.forIn("key", data, (key) => { - if (!props.length && !patProps.length) additionalPropertyCode(key); - else gen.if(isAdditional(key), () => additionalPropertyCode(key)); - }); - } - function isAdditional(key) { - let definedProp; - if (props.length > 8) { - const propsSchema = (0, util_1.schemaRefOrVal)(it, parentSchema.properties, "properties"); - definedProp = (0, code_1.isOwnProperty)(gen, propsSchema, key); - } else if (props.length) definedProp = (0, codegen_1.or)(...props.map((p) => (0, codegen_1._)`${key} === ${p}`)); - else definedProp = codegen_1.nil; - if (patProps.length) definedProp = (0, codegen_1.or)(definedProp, ...patProps.map((p) => (0, codegen_1._)`${(0, code_1.usePattern)(cxt, p)}.test(${key})`)); - return (0, codegen_1.not)(definedProp); - } - function deleteAdditional(key) { - gen.code((0, codegen_1._)`delete ${data}[${key}]`); - } - function additionalPropertyCode(key) { - if (opts.removeAdditional === "all" || opts.removeAdditional && schema === false) { - deleteAdditional(key); - return; - } - if (schema === false) { - cxt.setParams({ additionalProperty: key }); - cxt.error(); - if (!allErrors) gen.break(); - return; - } - if (typeof schema == "object" && !(0, util_1.alwaysValidSchema)(it, schema)) { - const valid = gen.name("valid"); - if (opts.removeAdditional === "failing") { - applyAdditionalSchema(key, valid, false); - gen.if((0, codegen_1.not)(valid), () => { - cxt.reset(); - deleteAdditional(key); - }); - } else { - applyAdditionalSchema(key, valid); - if (!allErrors) gen.if((0, codegen_1.not)(valid), () => gen.break()); - } - } - } - function applyAdditionalSchema(key, valid, errors) { - const subschema = { - keyword: "additionalProperties", - dataProp: key, - dataPropType: util_1.Type.Str - }; - if (errors === false) Object.assign(subschema, { - compositeRule: true, - createErrors: false, - allErrors: false - }); - cxt.subschema(subschema, valid); - } - } - }; - exports.default = def; -})); - -//#endregion -//#region ../../node_modules/.pnpm/ajv@8.18.0/node_modules/ajv/dist/vocabularies/applicator/properties.js -var require_properties = /* @__PURE__ */ __commonJSMin(((exports) => { - Object.defineProperty(exports, "__esModule", { value: true }); - const validate_1 = require_validate(); - const code_1 = require_code(); - const util_1 = require_util(); - const additionalProperties_1 = require_additionalProperties(); - const def = { - keyword: "properties", - type: "object", - schemaType: "object", - code(cxt) { - const { gen, schema, parentSchema, data, it } = cxt; - if (it.opts.removeAdditional === "all" && parentSchema.additionalProperties === void 0) additionalProperties_1.default.code(new validate_1.KeywordCxt(it, additionalProperties_1.default, "additionalProperties")); - const allProps = (0, code_1.allSchemaProperties)(schema); - for (const prop of allProps) it.definedProperties.add(prop); - if (it.opts.unevaluated && allProps.length && it.props !== true) it.props = util_1.mergeEvaluated.props(gen, (0, util_1.toHash)(allProps), it.props); - const properties = allProps.filter((p) => !(0, util_1.alwaysValidSchema)(it, schema[p])); - if (properties.length === 0) return; - const valid = gen.name("valid"); - for (const prop of properties) { - if (hasDefault(prop)) applyPropertySchema(prop); - else { - gen.if((0, code_1.propertyInData)(gen, data, prop, it.opts.ownProperties)); - applyPropertySchema(prop); - if (!it.allErrors) gen.else().var(valid, true); - gen.endIf(); - } - cxt.it.definedProperties.add(prop); - cxt.ok(valid); - } - function hasDefault(prop) { - return it.opts.useDefaults && !it.compositeRule && schema[prop].default !== void 0; - } - function applyPropertySchema(prop) { - cxt.subschema({ - keyword: "properties", - schemaProp: prop, - dataProp: prop - }, valid); - } - } - }; - exports.default = def; -})); - -//#endregion -//#region ../../node_modules/.pnpm/ajv@8.18.0/node_modules/ajv/dist/vocabularies/applicator/patternProperties.js -var require_patternProperties = /* @__PURE__ */ __commonJSMin(((exports) => { - Object.defineProperty(exports, "__esModule", { value: true }); - const code_1 = require_code(); - const codegen_1 = require_codegen(); - const util_1 = require_util(); - const util_2 = require_util(); - const def = { - keyword: "patternProperties", - type: "object", - schemaType: "object", - code(cxt) { - const { gen, schema, data, parentSchema, it } = cxt; - const { opts } = it; - const patterns = (0, code_1.allSchemaProperties)(schema); - const alwaysValidPatterns = patterns.filter((p) => (0, util_1.alwaysValidSchema)(it, schema[p])); - if (patterns.length === 0 || alwaysValidPatterns.length === patterns.length && (!it.opts.unevaluated || it.props === true)) return; - const checkProperties = opts.strictSchema && !opts.allowMatchingProperties && parentSchema.properties; - const valid = gen.name("valid"); - if (it.props !== true && !(it.props instanceof codegen_1.Name)) it.props = (0, util_2.evaluatedPropsToName)(gen, it.props); - const { props } = it; - validatePatternProperties(); - function validatePatternProperties() { - for (const pat of patterns) { - if (checkProperties) checkMatchingProperties(pat); - if (it.allErrors) validateProperties(pat); - else { - gen.var(valid, true); - validateProperties(pat); - gen.if(valid); - } - } - } - function checkMatchingProperties(pat) { - for (const prop in checkProperties) if (new RegExp(pat).test(prop)) (0, util_1.checkStrictMode)(it, `property ${prop} matches pattern ${pat} (use allowMatchingProperties)`); - } - function validateProperties(pat) { - gen.forIn("key", data, (key) => { - gen.if((0, codegen_1._)`${(0, code_1.usePattern)(cxt, pat)}.test(${key})`, () => { - const alwaysValid = alwaysValidPatterns.includes(pat); - if (!alwaysValid) cxt.subschema({ - keyword: "patternProperties", - schemaProp: pat, - dataProp: key, - dataPropType: util_2.Type.Str - }, valid); - if (it.opts.unevaluated && props !== true) gen.assign((0, codegen_1._)`${props}[${key}]`, true); - else if (!alwaysValid && !it.allErrors) gen.if((0, codegen_1.not)(valid), () => gen.break()); - }); - }); - } - } - }; - exports.default = def; -})); - -//#endregion -//#region ../../node_modules/.pnpm/ajv@8.18.0/node_modules/ajv/dist/vocabularies/applicator/not.js -var require_not = /* @__PURE__ */ __commonJSMin(((exports) => { - Object.defineProperty(exports, "__esModule", { value: true }); - const util_1 = require_util(); - const def = { - keyword: "not", - schemaType: ["object", "boolean"], - trackErrors: true, - code(cxt) { - const { gen, schema, it } = cxt; - if ((0, util_1.alwaysValidSchema)(it, schema)) { - cxt.fail(); - return; - } - const valid = gen.name("valid"); - cxt.subschema({ - keyword: "not", - compositeRule: true, - createErrors: false, - allErrors: false - }, valid); - cxt.failResult(valid, () => cxt.reset(), () => cxt.error()); - }, - error: { message: "must NOT be valid" } - }; - exports.default = def; -})); - -//#endregion -//#region ../../node_modules/.pnpm/ajv@8.18.0/node_modules/ajv/dist/vocabularies/applicator/anyOf.js -var require_anyOf = /* @__PURE__ */ __commonJSMin(((exports) => { - Object.defineProperty(exports, "__esModule", { value: true }); - const def = { - keyword: "anyOf", - schemaType: "array", - trackErrors: true, - code: require_code().validateUnion, - error: { message: "must match a schema in anyOf" } - }; - exports.default = def; -})); - -//#endregion -//#region ../../node_modules/.pnpm/ajv@8.18.0/node_modules/ajv/dist/vocabularies/applicator/oneOf.js -var require_oneOf = /* @__PURE__ */ __commonJSMin(((exports) => { - Object.defineProperty(exports, "__esModule", { value: true }); - const codegen_1 = require_codegen(); - const util_1 = require_util(); - const def = { - keyword: "oneOf", - schemaType: "array", - trackErrors: true, - error: { - message: "must match exactly one schema in oneOf", - params: ({ params }) => (0, codegen_1._)`{passingSchemas: ${params.passing}}` - }, - code(cxt) { - const { gen, schema, parentSchema, it } = cxt; - /* istanbul ignore if */ - if (!Array.isArray(schema)) throw new Error("ajv implementation error"); - if (it.opts.discriminator && parentSchema.discriminator) return; - const schArr = schema; - const valid = gen.let("valid", false); - const passing = gen.let("passing", null); - const schValid = gen.name("_valid"); - cxt.setParams({ passing }); - gen.block(validateOneOf); - cxt.result(valid, () => cxt.reset(), () => cxt.error(true)); - function validateOneOf() { - schArr.forEach((sch, i) => { - let schCxt; - if ((0, util_1.alwaysValidSchema)(it, sch)) gen.var(schValid, true); - else schCxt = cxt.subschema({ - keyword: "oneOf", - schemaProp: i, - compositeRule: true - }, schValid); - if (i > 0) gen.if((0, codegen_1._)`${schValid} && ${valid}`).assign(valid, false).assign(passing, (0, codegen_1._)`[${passing}, ${i}]`).else(); - gen.if(schValid, () => { - gen.assign(valid, true); - gen.assign(passing, i); - if (schCxt) cxt.mergeEvaluated(schCxt, codegen_1.Name); - }); - }); - } - } - }; - exports.default = def; -})); - -//#endregion -//#region ../../node_modules/.pnpm/ajv@8.18.0/node_modules/ajv/dist/vocabularies/applicator/allOf.js -var require_allOf = /* @__PURE__ */ __commonJSMin(((exports) => { - Object.defineProperty(exports, "__esModule", { value: true }); - const util_1 = require_util(); - const def = { - keyword: "allOf", - schemaType: "array", - code(cxt) { - const { gen, schema, it } = cxt; - /* istanbul ignore if */ - if (!Array.isArray(schema)) throw new Error("ajv implementation error"); - const valid = gen.name("valid"); - schema.forEach((sch, i) => { - if ((0, util_1.alwaysValidSchema)(it, sch)) return; - const schCxt = cxt.subschema({ - keyword: "allOf", - schemaProp: i - }, valid); - cxt.ok(valid); - cxt.mergeEvaluated(schCxt); - }); - } - }; - exports.default = def; -})); - -//#endregion -//#region ../../node_modules/.pnpm/ajv@8.18.0/node_modules/ajv/dist/vocabularies/applicator/if.js -var require_if = /* @__PURE__ */ __commonJSMin(((exports) => { - Object.defineProperty(exports, "__esModule", { value: true }); - const codegen_1 = require_codegen(); - const util_1 = require_util(); - const def = { - keyword: "if", - schemaType: ["object", "boolean"], - trackErrors: true, - error: { - message: ({ params }) => (0, codegen_1.str)`must match "${params.ifClause}" schema`, - params: ({ params }) => (0, codegen_1._)`{failingKeyword: ${params.ifClause}}` - }, - code(cxt) { - const { gen, parentSchema, it } = cxt; - if (parentSchema.then === void 0 && parentSchema.else === void 0) (0, util_1.checkStrictMode)(it, "\"if\" without \"then\" and \"else\" is ignored"); - const hasThen = hasSchema(it, "then"); - const hasElse = hasSchema(it, "else"); - if (!hasThen && !hasElse) return; - const valid = gen.let("valid", true); - const schValid = gen.name("_valid"); - validateIf(); - cxt.reset(); - if (hasThen && hasElse) { - const ifClause = gen.let("ifClause"); - cxt.setParams({ ifClause }); - gen.if(schValid, validateClause("then", ifClause), validateClause("else", ifClause)); - } else if (hasThen) gen.if(schValid, validateClause("then")); - else gen.if((0, codegen_1.not)(schValid), validateClause("else")); - cxt.pass(valid, () => cxt.error(true)); - function validateIf() { - const schCxt = cxt.subschema({ - keyword: "if", - compositeRule: true, - createErrors: false, - allErrors: false - }, schValid); - cxt.mergeEvaluated(schCxt); - } - function validateClause(keyword, ifClause) { - return () => { - const schCxt = cxt.subschema({ keyword }, schValid); - gen.assign(valid, schValid); - cxt.mergeValidEvaluated(schCxt, valid); - if (ifClause) gen.assign(ifClause, (0, codegen_1._)`${keyword}`); - else cxt.setParams({ ifClause: keyword }); - }; - } - } - }; - function hasSchema(it, keyword) { - const schema = it.schema[keyword]; - return schema !== void 0 && !(0, util_1.alwaysValidSchema)(it, schema); - } - exports.default = def; -})); - -//#endregion -//#region ../../node_modules/.pnpm/ajv@8.18.0/node_modules/ajv/dist/vocabularies/applicator/thenElse.js -var require_thenElse = /* @__PURE__ */ __commonJSMin(((exports) => { - Object.defineProperty(exports, "__esModule", { value: true }); - const util_1 = require_util(); - const def = { - keyword: ["then", "else"], - schemaType: ["object", "boolean"], - code({ keyword, parentSchema, it }) { - if (parentSchema.if === void 0) (0, util_1.checkStrictMode)(it, `"${keyword}" without "if" is ignored`); - } - }; - exports.default = def; -})); - -//#endregion -//#region ../../node_modules/.pnpm/ajv@8.18.0/node_modules/ajv/dist/vocabularies/applicator/index.js -var require_applicator$2 = /* @__PURE__ */ __commonJSMin(((exports) => { - Object.defineProperty(exports, "__esModule", { value: true }); - const additionalItems_1 = require_additionalItems(); - const prefixItems_1 = require_prefixItems(); - const items_1 = require_items(); - const items2020_1 = require_items2020(); - const contains_1 = require_contains(); - const dependencies_1 = require_dependencies(); - const propertyNames_1 = require_propertyNames(); - const additionalProperties_1 = require_additionalProperties(); - const properties_1 = require_properties(); - const patternProperties_1 = require_patternProperties(); - const not_1 = require_not(); - const anyOf_1 = require_anyOf(); - const oneOf_1 = require_oneOf(); - const allOf_1 = require_allOf(); - const if_1 = require_if(); - const thenElse_1 = require_thenElse(); - function getApplicator(draft2020 = false) { - const applicator = [ - not_1.default, - anyOf_1.default, - oneOf_1.default, - allOf_1.default, - if_1.default, - thenElse_1.default, - propertyNames_1.default, - additionalProperties_1.default, - dependencies_1.default, - properties_1.default, - patternProperties_1.default - ]; - if (draft2020) applicator.push(prefixItems_1.default, items2020_1.default); - else applicator.push(additionalItems_1.default, items_1.default); - applicator.push(contains_1.default); - return applicator; - } - exports.default = getApplicator; -})); - -//#endregion -//#region ../../node_modules/.pnpm/ajv@8.18.0/node_modules/ajv/dist/vocabularies/format/format.js -var require_format$2 = /* @__PURE__ */ __commonJSMin(((exports) => { - Object.defineProperty(exports, "__esModule", { value: true }); - const codegen_1 = require_codegen(); - const def = { - keyword: "format", - type: ["number", "string"], - schemaType: "string", - $data: true, - error: { - message: ({ schemaCode }) => (0, codegen_1.str)`must match format "${schemaCode}"`, - params: ({ schemaCode }) => (0, codegen_1._)`{format: ${schemaCode}}` - }, - code(cxt, ruleType) { - const { gen, data, $data, schema, schemaCode, it } = cxt; - const { opts, errSchemaPath, schemaEnv, self } = it; - if (!opts.validateFormats) return; - if ($data) validate$DataFormat(); - else validateFormat(); - function validate$DataFormat() { - const fmts = gen.scopeValue("formats", { - ref: self.formats, - code: opts.code.formats - }); - const fDef = gen.const("fDef", (0, codegen_1._)`${fmts}[${schemaCode}]`); - const fType = gen.let("fType"); - const format = gen.let("format"); - gen.if((0, codegen_1._)`typeof ${fDef} == "object" && !(${fDef} instanceof RegExp)`, () => gen.assign(fType, (0, codegen_1._)`${fDef}.type || "string"`).assign(format, (0, codegen_1._)`${fDef}.validate`), () => gen.assign(fType, (0, codegen_1._)`"string"`).assign(format, fDef)); - cxt.fail$data((0, codegen_1.or)(unknownFmt(), invalidFmt())); - function unknownFmt() { - if (opts.strictSchema === false) return codegen_1.nil; - return (0, codegen_1._)`${schemaCode} && !${format}`; - } - function invalidFmt() { - const callFormat = schemaEnv.$async ? (0, codegen_1._)`(${fDef}.async ? await ${format}(${data}) : ${format}(${data}))` : (0, codegen_1._)`${format}(${data})`; - const validData = (0, codegen_1._)`(typeof ${format} == "function" ? ${callFormat} : ${format}.test(${data}))`; - return (0, codegen_1._)`${format} && ${format} !== true && ${fType} === ${ruleType} && !${validData}`; - } - } - function validateFormat() { - const formatDef = self.formats[schema]; - if (!formatDef) { - unknownFormat(); - return; - } - if (formatDef === true) return; - const [fmtType, format, fmtRef] = getFormat(formatDef); - if (fmtType === ruleType) cxt.pass(validCondition()); - function unknownFormat() { - if (opts.strictSchema === false) { - self.logger.warn(unknownMsg()); - return; - } - throw new Error(unknownMsg()); - function unknownMsg() { - return `unknown format "${schema}" ignored in schema at path "${errSchemaPath}"`; - } - } - function getFormat(fmtDef) { - const code = fmtDef instanceof RegExp ? (0, codegen_1.regexpCode)(fmtDef) : opts.code.formats ? (0, codegen_1._)`${opts.code.formats}${(0, codegen_1.getProperty)(schema)}` : void 0; - const fmt = gen.scopeValue("formats", { - key: schema, - ref: fmtDef, - code - }); - if (typeof fmtDef == "object" && !(fmtDef instanceof RegExp)) return [ - fmtDef.type || "string", - fmtDef.validate, - (0, codegen_1._)`${fmt}.validate` - ]; - return [ - "string", - fmtDef, - fmt - ]; - } - function validCondition() { - if (typeof formatDef == "object" && !(formatDef instanceof RegExp) && formatDef.async) { - if (!schemaEnv.$async) throw new Error("async format in sync schema"); - return (0, codegen_1._)`await ${fmtRef}(${data})`; - } - return typeof format == "function" ? (0, codegen_1._)`${fmtRef}(${data})` : (0, codegen_1._)`${fmtRef}.test(${data})`; - } - } - } - }; - exports.default = def; -})); - -//#endregion -//#region ../../node_modules/.pnpm/ajv@8.18.0/node_modules/ajv/dist/vocabularies/format/index.js -var require_format$1 = /* @__PURE__ */ __commonJSMin(((exports) => { - Object.defineProperty(exports, "__esModule", { value: true }); - const format = [require_format$2().default]; - exports.default = format; -})); - -//#endregion -//#region ../../node_modules/.pnpm/ajv@8.18.0/node_modules/ajv/dist/vocabularies/metadata.js -var require_metadata = /* @__PURE__ */ __commonJSMin(((exports) => { - Object.defineProperty(exports, "__esModule", { value: true }); - exports.contentVocabulary = exports.metadataVocabulary = void 0; - exports.metadataVocabulary = [ - "title", - "description", - "default", - "deprecated", - "readOnly", - "writeOnly", - "examples" - ]; - exports.contentVocabulary = [ - "contentMediaType", - "contentEncoding", - "contentSchema" - ]; -})); - -//#endregion -//#region ../../node_modules/.pnpm/ajv@8.18.0/node_modules/ajv/dist/vocabularies/draft7.js -var require_draft7 = /* @__PURE__ */ __commonJSMin(((exports) => { - Object.defineProperty(exports, "__esModule", { value: true }); - const core_1 = require_core$2(); - const validation_1 = require_validation$2(); - const applicator_1 = require_applicator$2(); - const format_1 = require_format$1(); - const metadata_1 = require_metadata(); - const draft7Vocabularies = [ - core_1.default, - validation_1.default, - (0, applicator_1.default)(), - format_1.default, - metadata_1.metadataVocabulary, - metadata_1.contentVocabulary - ]; - exports.default = draft7Vocabularies; -})); - -//#endregion -//#region ../../node_modules/.pnpm/ajv@8.18.0/node_modules/ajv/dist/vocabularies/discriminator/types.js -var require_types = /* @__PURE__ */ __commonJSMin(((exports) => { - Object.defineProperty(exports, "__esModule", { value: true }); - exports.DiscrError = void 0; - var DiscrError; - (function(DiscrError) { - DiscrError["Tag"] = "tag"; - DiscrError["Mapping"] = "mapping"; - })(DiscrError || (exports.DiscrError = DiscrError = {})); -})); - -//#endregion -//#region ../../node_modules/.pnpm/ajv@8.18.0/node_modules/ajv/dist/vocabularies/discriminator/index.js -var require_discriminator = /* @__PURE__ */ __commonJSMin(((exports) => { - Object.defineProperty(exports, "__esModule", { value: true }); - const codegen_1 = require_codegen(); - const types_1 = require_types(); - const compile_1 = require_compile(); - const ref_error_1 = require_ref_error(); - const util_1 = require_util(); - const def = { - keyword: "discriminator", - type: "object", - schemaType: "object", - error: { - message: ({ params: { discrError, tagName } }) => discrError === types_1.DiscrError.Tag ? `tag "${tagName}" must be string` : `value of tag "${tagName}" must be in oneOf`, - params: ({ params: { discrError, tag, tagName } }) => (0, codegen_1._)`{error: ${discrError}, tag: ${tagName}, tagValue: ${tag}}` - }, - code(cxt) { - const { gen, data, schema, parentSchema, it } = cxt; - const { oneOf } = parentSchema; - if (!it.opts.discriminator) throw new Error("discriminator: requires discriminator option"); - const tagName = schema.propertyName; - if (typeof tagName != "string") throw new Error("discriminator: requires propertyName"); - if (schema.mapping) throw new Error("discriminator: mapping is not supported"); - if (!oneOf) throw new Error("discriminator: requires oneOf keyword"); - const valid = gen.let("valid", false); - const tag = gen.const("tag", (0, codegen_1._)`${data}${(0, codegen_1.getProperty)(tagName)}`); - gen.if((0, codegen_1._)`typeof ${tag} == "string"`, () => validateMapping(), () => cxt.error(false, { - discrError: types_1.DiscrError.Tag, - tag, - tagName - })); - cxt.ok(valid); - function validateMapping() { - const mapping = getMapping(); - gen.if(false); - for (const tagValue in mapping) { - gen.elseIf((0, codegen_1._)`${tag} === ${tagValue}`); - gen.assign(valid, applyTagSchema(mapping[tagValue])); - } - gen.else(); - cxt.error(false, { - discrError: types_1.DiscrError.Mapping, - tag, - tagName - }); - gen.endIf(); - } - function applyTagSchema(schemaProp) { - const _valid = gen.name("valid"); - const schCxt = cxt.subschema({ - keyword: "oneOf", - schemaProp - }, _valid); - cxt.mergeEvaluated(schCxt, codegen_1.Name); - return _valid; - } - function getMapping() { - var _a; - const oneOfMapping = {}; - const topRequired = hasRequired(parentSchema); - let tagRequired = true; - for (let i = 0; i < oneOf.length; i++) { - let sch = oneOf[i]; - if ((sch === null || sch === void 0 ? void 0 : sch.$ref) && !(0, util_1.schemaHasRulesButRef)(sch, it.self.RULES)) { - const ref = sch.$ref; - sch = compile_1.resolveRef.call(it.self, it.schemaEnv.root, it.baseId, ref); - if (sch instanceof compile_1.SchemaEnv) sch = sch.schema; - if (sch === void 0) throw new ref_error_1.default(it.opts.uriResolver, it.baseId, ref); - } - const propSch = (_a = sch === null || sch === void 0 ? void 0 : sch.properties) === null || _a === void 0 ? void 0 : _a[tagName]; - if (typeof propSch != "object") throw new Error(`discriminator: oneOf subschemas (or referenced schemas) must have "properties/${tagName}"`); - tagRequired = tagRequired && (topRequired || hasRequired(sch)); - addMappings(propSch, i); - } - if (!tagRequired) throw new Error(`discriminator: "${tagName}" must be required`); - return oneOfMapping; - function hasRequired({ required }) { - return Array.isArray(required) && required.includes(tagName); - } - function addMappings(sch, i) { - if (sch.const) addMapping(sch.const, i); - else if (sch.enum) for (const tagValue of sch.enum) addMapping(tagValue, i); - else throw new Error(`discriminator: "properties/${tagName}" must have "const" or "enum"`); - } - function addMapping(tagValue, i) { - if (typeof tagValue != "string" || tagValue in oneOfMapping) throw new Error(`discriminator: "${tagName}" values must be unique strings`); - oneOfMapping[tagValue] = i; - } - } - } - }; - exports.default = def; -})); - -//#endregion -//#region ../../node_modules/.pnpm/ajv@8.18.0/node_modules/ajv/dist/refs/json-schema-draft-07.json -var require_json_schema_draft_07 = /* @__PURE__ */ __commonJSMin(((exports, module) => { - module.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": true, - "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": true, - "readOnly": { - "type": "boolean", - "default": false - }, - "examples": { - "type": "array", - "items": true - }, - "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": true - }, - "maxItems": { "$ref": "#/definitions/nonNegativeInteger" }, - "minItems": { "$ref": "#/definitions/nonNegativeIntegerDefault0" }, - "uniqueItems": { - "type": "boolean", - "default": false - }, - "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": true, - "enum": { - "type": "array", - "items": true, - "minItems": 1, - "uniqueItems": true - }, - "type": { "anyOf": [{ "$ref": "#/definitions/simpleTypes" }, { - "type": "array", - "items": { "$ref": "#/definitions/simpleTypes" }, - "minItems": 1, - "uniqueItems": true - }] }, - "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": true - }; -})); - -//#endregion -//#region ../../node_modules/.pnpm/ajv@8.18.0/node_modules/ajv/dist/ajv.js -var require_ajv = /* @__PURE__ */ __commonJSMin(((exports, module) => { - Object.defineProperty(exports, "__esModule", { value: true }); - exports.MissingRefError = exports.ValidationError = exports.CodeGen = exports.Name = exports.nil = exports.stringify = exports.str = exports._ = exports.KeywordCxt = exports.Ajv = void 0; - const core_1 = require_core$3(); - const draft7_1 = require_draft7(); - const discriminator_1 = require_discriminator(); - const draft7MetaSchema = require_json_schema_draft_07(); - const META_SUPPORT_DATA = ["/properties"]; - const META_SCHEMA_ID = "http://json-schema.org/draft-07/schema"; - var Ajv = class extends core_1.default { - _addVocabularies() { - super._addVocabularies(); - draft7_1.default.forEach((v) => this.addVocabulary(v)); - if (this.opts.discriminator) this.addKeyword(discriminator_1.default); - } - _addDefaultMetaSchema() { - super._addDefaultMetaSchema(); - if (!this.opts.meta) return; - const metaSchema = this.opts.$data ? this.$dataMetaSchema(draft7MetaSchema, META_SUPPORT_DATA) : draft7MetaSchema; - this.addMetaSchema(metaSchema, META_SCHEMA_ID, false); - this.refs["http://json-schema.org/schema"] = META_SCHEMA_ID; - } - defaultMeta() { - return this.opts.defaultMeta = super.defaultMeta() || (this.getSchema(META_SCHEMA_ID) ? META_SCHEMA_ID : void 0); - } - }; - exports.Ajv = Ajv; - module.exports = exports = Ajv; - module.exports.Ajv = Ajv; - Object.defineProperty(exports, "__esModule", { value: true }); - exports.default = Ajv; - var validate_1 = require_validate(); - Object.defineProperty(exports, "KeywordCxt", { - enumerable: true, - get: function() { - return validate_1.KeywordCxt; - } - }); - var codegen_1 = require_codegen(); - Object.defineProperty(exports, "_", { - enumerable: true, - get: function() { - return codegen_1._; - } - }); - Object.defineProperty(exports, "str", { - enumerable: true, - get: function() { - return codegen_1.str; - } - }); - Object.defineProperty(exports, "stringify", { - enumerable: true, - get: function() { - return codegen_1.stringify; - } - }); - Object.defineProperty(exports, "nil", { - enumerable: true, - get: function() { - return codegen_1.nil; - } - }); - Object.defineProperty(exports, "Name", { - enumerable: true, - get: function() { - return codegen_1.Name; - } - }); - Object.defineProperty(exports, "CodeGen", { - enumerable: true, - get: function() { - return codegen_1.CodeGen; - } - }); - var validation_error_1 = require_validation_error(); - Object.defineProperty(exports, "ValidationError", { - enumerable: true, - get: function() { - return validation_error_1.default; - } - }); - var ref_error_1 = require_ref_error(); - Object.defineProperty(exports, "MissingRefError", { - enumerable: true, - get: function() { - return ref_error_1.default; - } - }); -})); - -//#endregion -//#region ../../node_modules/.pnpm/ajv@8.18.0/node_modules/ajv/dist/vocabularies/dynamic/dynamicAnchor.js -var require_dynamicAnchor = /* @__PURE__ */ __commonJSMin(((exports) => { - Object.defineProperty(exports, "__esModule", { value: true }); - exports.dynamicAnchor = void 0; - const codegen_1 = require_codegen(); - const names_1 = require_names(); - const compile_1 = require_compile(); - const ref_1 = require_ref(); - const def = { - keyword: "$dynamicAnchor", - schemaType: "string", - code: (cxt) => dynamicAnchor(cxt, cxt.schema) - }; - function dynamicAnchor(cxt, anchor) { - const { gen, it } = cxt; - it.schemaEnv.root.dynamicAnchors[anchor] = true; - const v = (0, codegen_1._)`${names_1.default.dynamicAnchors}${(0, codegen_1.getProperty)(anchor)}`; - const validate = it.errSchemaPath === "#" ? it.validateName : _getValidate(cxt); - gen.if((0, codegen_1._)`!${v}`, () => gen.assign(v, validate)); - } - exports.dynamicAnchor = dynamicAnchor; - function _getValidate(cxt) { - const { schemaEnv, schema, self } = cxt.it; - const { root, baseId, localRefs, meta } = schemaEnv.root; - const { schemaId } = self.opts; - const sch = new compile_1.SchemaEnv({ - schema, - schemaId, - root, - baseId, - localRefs, - meta - }); - compile_1.compileSchema.call(self, sch); - return (0, ref_1.getValidate)(cxt, sch); - } - exports.default = def; -})); - -//#endregion -//#region ../../node_modules/.pnpm/ajv@8.18.0/node_modules/ajv/dist/vocabularies/dynamic/dynamicRef.js -var require_dynamicRef = /* @__PURE__ */ __commonJSMin(((exports) => { - Object.defineProperty(exports, "__esModule", { value: true }); - exports.dynamicRef = void 0; - const codegen_1 = require_codegen(); - const names_1 = require_names(); - const ref_1 = require_ref(); - const def = { - keyword: "$dynamicRef", - schemaType: "string", - code: (cxt) => dynamicRef(cxt, cxt.schema) - }; - function dynamicRef(cxt, ref) { - const { gen, keyword, it } = cxt; - if (ref[0] !== "#") throw new Error(`"${keyword}" only supports hash fragment reference`); - const anchor = ref.slice(1); - if (it.allErrors) _dynamicRef(); - else { - const valid = gen.let("valid", false); - _dynamicRef(valid); - cxt.ok(valid); - } - function _dynamicRef(valid) { - if (it.schemaEnv.root.dynamicAnchors[anchor]) { - const v = gen.let("_v", (0, codegen_1._)`${names_1.default.dynamicAnchors}${(0, codegen_1.getProperty)(anchor)}`); - gen.if(v, _callRef(v, valid), _callRef(it.validateName, valid)); - } else _callRef(it.validateName, valid)(); - } - function _callRef(validate, valid) { - return valid ? () => gen.block(() => { - (0, ref_1.callRef)(cxt, validate); - gen.let(valid, true); - }) : () => (0, ref_1.callRef)(cxt, validate); - } - } - exports.dynamicRef = dynamicRef; - exports.default = def; -})); - -//#endregion -//#region ../../node_modules/.pnpm/ajv@8.18.0/node_modules/ajv/dist/vocabularies/dynamic/recursiveAnchor.js -var require_recursiveAnchor = /* @__PURE__ */ __commonJSMin(((exports) => { - Object.defineProperty(exports, "__esModule", { value: true }); - const dynamicAnchor_1 = require_dynamicAnchor(); - const util_1 = require_util(); - const def = { - keyword: "$recursiveAnchor", - schemaType: "boolean", - code(cxt) { - if (cxt.schema) (0, dynamicAnchor_1.dynamicAnchor)(cxt, ""); - else (0, util_1.checkStrictMode)(cxt.it, "$recursiveAnchor: false is ignored"); - } - }; - exports.default = def; -})); - -//#endregion -//#region ../../node_modules/.pnpm/ajv@8.18.0/node_modules/ajv/dist/vocabularies/dynamic/recursiveRef.js -var require_recursiveRef = /* @__PURE__ */ __commonJSMin(((exports) => { - Object.defineProperty(exports, "__esModule", { value: true }); - const dynamicRef_1 = require_dynamicRef(); - const def = { - keyword: "$recursiveRef", - schemaType: "string", - code: (cxt) => (0, dynamicRef_1.dynamicRef)(cxt, cxt.schema) - }; - exports.default = def; -})); - -//#endregion -//#region ../../node_modules/.pnpm/ajv@8.18.0/node_modules/ajv/dist/vocabularies/dynamic/index.js -var require_dynamic = /* @__PURE__ */ __commonJSMin(((exports) => { - Object.defineProperty(exports, "__esModule", { value: true }); - const dynamicAnchor_1 = require_dynamicAnchor(); - const dynamicRef_1 = require_dynamicRef(); - const recursiveAnchor_1 = require_recursiveAnchor(); - const recursiveRef_1 = require_recursiveRef(); - const dynamic = [ - dynamicAnchor_1.default, - dynamicRef_1.default, - recursiveAnchor_1.default, - recursiveRef_1.default - ]; - exports.default = dynamic; -})); - -//#endregion -//#region ../../node_modules/.pnpm/ajv@8.18.0/node_modules/ajv/dist/vocabularies/validation/dependentRequired.js -var require_dependentRequired = /* @__PURE__ */ __commonJSMin(((exports) => { - Object.defineProperty(exports, "__esModule", { value: true }); - const dependencies_1 = require_dependencies(); - const def = { - keyword: "dependentRequired", - type: "object", - schemaType: "object", - error: dependencies_1.error, - code: (cxt) => (0, dependencies_1.validatePropertyDeps)(cxt) - }; - exports.default = def; -})); - -//#endregion -//#region ../../node_modules/.pnpm/ajv@8.18.0/node_modules/ajv/dist/vocabularies/applicator/dependentSchemas.js -var require_dependentSchemas = /* @__PURE__ */ __commonJSMin(((exports) => { - Object.defineProperty(exports, "__esModule", { value: true }); - const dependencies_1 = require_dependencies(); - const def = { - keyword: "dependentSchemas", - type: "object", - schemaType: "object", - code: (cxt) => (0, dependencies_1.validateSchemaDeps)(cxt) - }; - exports.default = def; -})); - -//#endregion -//#region ../../node_modules/.pnpm/ajv@8.18.0/node_modules/ajv/dist/vocabularies/validation/limitContains.js -var require_limitContains = /* @__PURE__ */ __commonJSMin(((exports) => { - Object.defineProperty(exports, "__esModule", { value: true }); - const util_1 = require_util(); - const def = { - keyword: ["maxContains", "minContains"], - type: "array", - schemaType: "number", - code({ keyword, parentSchema, it }) { - if (parentSchema.contains === void 0) (0, util_1.checkStrictMode)(it, `"${keyword}" without "contains" is ignored`); - } - }; - exports.default = def; -})); - -//#endregion -//#region ../../node_modules/.pnpm/ajv@8.18.0/node_modules/ajv/dist/vocabularies/next.js -var require_next = /* @__PURE__ */ __commonJSMin(((exports) => { - Object.defineProperty(exports, "__esModule", { value: true }); - const dependentRequired_1 = require_dependentRequired(); - const dependentSchemas_1 = require_dependentSchemas(); - const limitContains_1 = require_limitContains(); - const next = [ - dependentRequired_1.default, - dependentSchemas_1.default, - limitContains_1.default - ]; - exports.default = next; -})); - -//#endregion -//#region ../../node_modules/.pnpm/ajv@8.18.0/node_modules/ajv/dist/vocabularies/unevaluated/unevaluatedProperties.js -var require_unevaluatedProperties = /* @__PURE__ */ __commonJSMin(((exports) => { - Object.defineProperty(exports, "__esModule", { value: true }); - const codegen_1 = require_codegen(); - const util_1 = require_util(); - const names_1 = require_names(); - const def = { - keyword: "unevaluatedProperties", - type: "object", - schemaType: ["boolean", "object"], - trackErrors: true, - error: { - message: "must NOT have unevaluated properties", - params: ({ params }) => (0, codegen_1._)`{unevaluatedProperty: ${params.unevaluatedProperty}}` - }, - code(cxt) { - const { gen, schema, data, errsCount, it } = cxt; - /* istanbul ignore if */ - if (!errsCount) throw new Error("ajv implementation error"); - const { allErrors, props } = it; - if (props instanceof codegen_1.Name) gen.if((0, codegen_1._)`${props} !== true`, () => gen.forIn("key", data, (key) => gen.if(unevaluatedDynamic(props, key), () => unevaluatedPropCode(key)))); - else if (props !== true) gen.forIn("key", data, (key) => props === void 0 ? unevaluatedPropCode(key) : gen.if(unevaluatedStatic(props, key), () => unevaluatedPropCode(key))); - it.props = true; - cxt.ok((0, codegen_1._)`${errsCount} === ${names_1.default.errors}`); - function unevaluatedPropCode(key) { - if (schema === false) { - cxt.setParams({ unevaluatedProperty: key }); - cxt.error(); - if (!allErrors) gen.break(); - return; - } - if (!(0, util_1.alwaysValidSchema)(it, schema)) { - const valid = gen.name("valid"); - cxt.subschema({ - keyword: "unevaluatedProperties", - dataProp: key, - dataPropType: util_1.Type.Str - }, valid); - if (!allErrors) gen.if((0, codegen_1.not)(valid), () => gen.break()); - } - } - function unevaluatedDynamic(evaluatedProps, key) { - return (0, codegen_1._)`!${evaluatedProps} || !${evaluatedProps}[${key}]`; - } - function unevaluatedStatic(evaluatedProps, key) { - const ps = []; - for (const p in evaluatedProps) if (evaluatedProps[p] === true) ps.push((0, codegen_1._)`${key} !== ${p}`); - return (0, codegen_1.and)(...ps); - } - } - }; - exports.default = def; -})); - -//#endregion -//#region ../../node_modules/.pnpm/ajv@8.18.0/node_modules/ajv/dist/vocabularies/unevaluated/unevaluatedItems.js -var require_unevaluatedItems = /* @__PURE__ */ __commonJSMin(((exports) => { - Object.defineProperty(exports, "__esModule", { value: true }); - const codegen_1 = require_codegen(); - const util_1 = require_util(); - const def = { - keyword: "unevaluatedItems", - type: "array", - schemaType: ["boolean", "object"], - error: { - message: ({ params: { len } }) => (0, codegen_1.str)`must NOT have more than ${len} items`, - params: ({ params: { len } }) => (0, codegen_1._)`{limit: ${len}}` - }, - code(cxt) { - const { gen, schema, data, it } = cxt; - const items = it.items || 0; - if (items === true) return; - const len = gen.const("len", (0, codegen_1._)`${data}.length`); - if (schema === false) { - cxt.setParams({ len: items }); - cxt.fail((0, codegen_1._)`${len} > ${items}`); - } else if (typeof schema == "object" && !(0, util_1.alwaysValidSchema)(it, schema)) { - const valid = gen.var("valid", (0, codegen_1._)`${len} <= ${items}`); - gen.if((0, codegen_1.not)(valid), () => validateItems(valid, items)); - cxt.ok(valid); - } - it.items = true; - function validateItems(valid, from) { - gen.forRange("i", from, len, (i) => { - cxt.subschema({ - keyword: "unevaluatedItems", - dataProp: i, - dataPropType: util_1.Type.Num - }, valid); - if (!it.allErrors) gen.if((0, codegen_1.not)(valid), () => gen.break()); - }); - } - } - }; - exports.default = def; -})); - -//#endregion -//#region ../../node_modules/.pnpm/ajv@8.18.0/node_modules/ajv/dist/vocabularies/unevaluated/index.js -var require_unevaluated$1 = /* @__PURE__ */ __commonJSMin(((exports) => { - Object.defineProperty(exports, "__esModule", { value: true }); - const unevaluatedProperties_1 = require_unevaluatedProperties(); - const unevaluatedItems_1 = require_unevaluatedItems(); - const unevaluated = [unevaluatedProperties_1.default, unevaluatedItems_1.default]; - exports.default = unevaluated; -})); - -//#endregion -//#region ../../node_modules/.pnpm/ajv@8.18.0/node_modules/ajv/dist/refs/json-schema-2019-09/schema.json -var require_schema$1 = /* @__PURE__ */ __commonJSMin(((exports, module) => { - module.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": true, - "https://json-schema.org/draft/2019-09/vocab/applicator": true, - "https://json-schema.org/draft/2019-09/vocab/validation": true, - "https://json-schema.org/draft/2019-09/vocab/meta-data": true, - "https://json-schema.org/draft/2019-09/vocab/format": false, - "https://json-schema.org/draft/2019-09/vocab/content": true - }, - "$recursiveAnchor": true, - "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" }] } - } - } - }; -})); - -//#endregion -//#region ../../node_modules/.pnpm/ajv@8.18.0/node_modules/ajv/dist/refs/json-schema-2019-09/meta/applicator.json -var require_applicator$1 = /* @__PURE__ */ __commonJSMin(((exports, module) => { - module.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": true }, - "$recursiveAnchor": true, - "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": "#" } - } } - }; -})); - -//#endregion -//#region ../../node_modules/.pnpm/ajv@8.18.0/node_modules/ajv/dist/refs/json-schema-2019-09/meta/content.json -var require_content$1 = /* @__PURE__ */ __commonJSMin(((exports, module) => { - module.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": true }, - "$recursiveAnchor": true, - "title": "Content vocabulary meta-schema", - "type": ["object", "boolean"], - "properties": { - "contentMediaType": { "type": "string" }, - "contentEncoding": { "type": "string" }, - "contentSchema": { "$recursiveRef": "#" } - } - }; -})); - -//#endregion -//#region ../../node_modules/.pnpm/ajv@8.18.0/node_modules/ajv/dist/refs/json-schema-2019-09/meta/core.json -var require_core$1 = /* @__PURE__ */ __commonJSMin(((exports, module) => { - module.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": true }, - "$recursiveAnchor": true, - "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": false - }, - "$vocabulary": { - "type": "object", - "propertyNames": { - "type": "string", - "format": "uri" - }, - "additionalProperties": { "type": "boolean" } - }, - "$comment": { "type": "string" }, - "$defs": { - "type": "object", - "additionalProperties": { "$recursiveRef": "#" }, - "default": {} - } - } - }; -})); - -//#endregion -//#region ../../node_modules/.pnpm/ajv@8.18.0/node_modules/ajv/dist/refs/json-schema-2019-09/meta/format.json -var require_format = /* @__PURE__ */ __commonJSMin(((exports, module) => { - module.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": true }, - "$recursiveAnchor": true, - "title": "Format vocabulary meta-schema", - "type": ["object", "boolean"], - "properties": { "format": { "type": "string" } } - }; -})); - -//#endregion -//#region ../../node_modules/.pnpm/ajv@8.18.0/node_modules/ajv/dist/refs/json-schema-2019-09/meta/meta-data.json -var require_meta_data$1 = /* @__PURE__ */ __commonJSMin(((exports, module) => { - module.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": true }, - "$recursiveAnchor": true, - "title": "Meta-data vocabulary meta-schema", - "type": ["object", "boolean"], - "properties": { - "title": { "type": "string" }, - "description": { "type": "string" }, - "default": true, - "deprecated": { - "type": "boolean", - "default": false - }, - "readOnly": { - "type": "boolean", - "default": false - }, - "writeOnly": { - "type": "boolean", - "default": false - }, - "examples": { - "type": "array", - "items": true - } - } - }; -})); - -//#endregion -//#region ../../node_modules/.pnpm/ajv@8.18.0/node_modules/ajv/dist/refs/json-schema-2019-09/meta/validation.json -var require_validation$1 = /* @__PURE__ */ __commonJSMin(((exports, module) => { - module.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": true }, - "$recursiveAnchor": true, - "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": false - }, - "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": true, - "enum": { - "type": "array", - "items": true - }, - "type": { "anyOf": [{ "$ref": "#/$defs/simpleTypes" }, { - "type": "array", - "items": { "$ref": "#/$defs/simpleTypes" }, - "minItems": 1, - "uniqueItems": true - }] } - }, - "$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": true, - "default": [] - } - } - }; -})); - -//#endregion -//#region ../../node_modules/.pnpm/ajv@8.18.0/node_modules/ajv/dist/refs/json-schema-2019-09/index.js -var require_json_schema_2019_09 = /* @__PURE__ */ __commonJSMin(((exports) => { - Object.defineProperty(exports, "__esModule", { value: true }); - const metaSchema = require_schema$1(); - const applicator = require_applicator$1(); - const content = require_content$1(); - const core = require_core$1(); - const format = require_format(); - const metadata = require_meta_data$1(); - const validation = require_validation$1(); - const META_SUPPORT_DATA = ["/properties"]; - function addMetaSchema2019($data) { - [ - metaSchema, - applicator, - content, - core, - with$data(this, format), - metadata, - with$data(this, validation) - ].forEach((sch) => this.addMetaSchema(sch, void 0, false)); - return this; - function with$data(ajv, sch) { - return $data ? ajv.$dataMetaSchema(sch, META_SUPPORT_DATA) : sch; - } - } - exports.default = addMetaSchema2019; -})); - -//#endregion -//#region ../../node_modules/.pnpm/ajv@8.18.0/node_modules/ajv/dist/2019.js -var require__2019 = /* @__PURE__ */ __commonJSMin(((exports, module) => { - Object.defineProperty(exports, "__esModule", { value: true }); - exports.MissingRefError = exports.ValidationError = exports.CodeGen = exports.Name = exports.nil = exports.stringify = exports.str = exports._ = exports.KeywordCxt = exports.Ajv2019 = void 0; - const core_1 = require_core$3(); - const draft7_1 = require_draft7(); - const dynamic_1 = require_dynamic(); - const next_1 = require_next(); - const unevaluated_1 = require_unevaluated$1(); - const discriminator_1 = require_discriminator(); - const json_schema_2019_09_1 = require_json_schema_2019_09(); - const META_SCHEMA_ID = "https://json-schema.org/draft/2019-09/schema"; - var Ajv2019 = class extends core_1.default { - constructor(opts = {}) { - super({ - ...opts, - dynamicRef: true, - next: true, - unevaluated: true - }); - } - _addVocabularies() { - super._addVocabularies(); - this.addVocabulary(dynamic_1.default); - draft7_1.default.forEach((v) => this.addVocabulary(v)); - this.addVocabulary(next_1.default); - this.addVocabulary(unevaluated_1.default); - if (this.opts.discriminator) this.addKeyword(discriminator_1.default); - } - _addDefaultMetaSchema() { - super._addDefaultMetaSchema(); - const { $data, meta } = this.opts; - if (!meta) return; - json_schema_2019_09_1.default.call(this, $data); - this.refs["http://json-schema.org/schema"] = META_SCHEMA_ID; - } - defaultMeta() { - return this.opts.defaultMeta = super.defaultMeta() || (this.getSchema(META_SCHEMA_ID) ? META_SCHEMA_ID : void 0); - } - }; - exports.Ajv2019 = Ajv2019; - module.exports = exports = Ajv2019; - module.exports.Ajv2019 = Ajv2019; - Object.defineProperty(exports, "__esModule", { value: true }); - exports.default = Ajv2019; - var validate_1 = require_validate(); - Object.defineProperty(exports, "KeywordCxt", { - enumerable: true, - get: function() { - return validate_1.KeywordCxt; - } - }); - var codegen_1 = require_codegen(); - Object.defineProperty(exports, "_", { - enumerable: true, - get: function() { - return codegen_1._; - } - }); - Object.defineProperty(exports, "str", { - enumerable: true, - get: function() { - return codegen_1.str; - } - }); - Object.defineProperty(exports, "stringify", { - enumerable: true, - get: function() { - return codegen_1.stringify; - } - }); - Object.defineProperty(exports, "nil", { - enumerable: true, - get: function() { - return codegen_1.nil; - } - }); - Object.defineProperty(exports, "Name", { - enumerable: true, - get: function() { - return codegen_1.Name; - } - }); - Object.defineProperty(exports, "CodeGen", { - enumerable: true, - get: function() { - return codegen_1.CodeGen; - } - }); - var validation_error_1 = require_validation_error(); - Object.defineProperty(exports, "ValidationError", { - enumerable: true, - get: function() { - return validation_error_1.default; - } - }); - var ref_error_1 = require_ref_error(); - Object.defineProperty(exports, "MissingRefError", { - enumerable: true, - get: function() { - return ref_error_1.default; - } - }); -})); - -//#endregion -//#region ../../node_modules/.pnpm/ajv@8.18.0/node_modules/ajv/dist/vocabularies/draft2020.js -var require_draft2020 = /* @__PURE__ */ __commonJSMin(((exports) => { - Object.defineProperty(exports, "__esModule", { value: true }); - const core_1 = require_core$2(); - const validation_1 = require_validation$2(); - const applicator_1 = require_applicator$2(); - const dynamic_1 = require_dynamic(); - const next_1 = require_next(); - const unevaluated_1 = require_unevaluated$1(); - const format_1 = require_format$1(); - const metadata_1 = require_metadata(); - const draft2020Vocabularies = [ - dynamic_1.default, - core_1.default, - validation_1.default, - (0, applicator_1.default)(true), - format_1.default, - metadata_1.metadataVocabulary, - metadata_1.contentVocabulary, - next_1.default, - unevaluated_1.default - ]; - exports.default = draft2020Vocabularies; -})); - -//#endregion -//#region ../../node_modules/.pnpm/ajv@8.18.0/node_modules/ajv/dist/refs/json-schema-2020-12/schema.json -var require_schema = /* @__PURE__ */ __commonJSMin(((exports, module) => { - module.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": true, - "https://json-schema.org/draft/2020-12/vocab/applicator": true, - "https://json-schema.org/draft/2020-12/vocab/unevaluated": true, - "https://json-schema.org/draft/2020-12/vocab/validation": true, - "https://json-schema.org/draft/2020-12/vocab/meta-data": true, - "https://json-schema.org/draft/2020-12/vocab/format-annotation": true, - "https://json-schema.org/draft/2020-12/vocab/content": true - }, - "$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": true, - "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": true, - "default": {} - }, - "$recursiveAnchor": { - "$comment": "\"$recursiveAnchor\" has been replaced by \"$dynamicAnchor\".", - "$ref": "meta/core#/$defs/anchorString", - "deprecated": true - }, - "$recursiveRef": { - "$comment": "\"$recursiveRef\" has been replaced by \"$dynamicRef\".", - "$ref": "meta/core#/$defs/uriReferenceString", - "deprecated": true - } - } - }; -})); - -//#endregion -//#region ../../node_modules/.pnpm/ajv@8.18.0/node_modules/ajv/dist/refs/json-schema-2020-12/meta/applicator.json -var require_applicator = /* @__PURE__ */ __commonJSMin(((exports, module) => { - module.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": true }, - "$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" } - } } - }; -})); - -//#endregion -//#region ../../node_modules/.pnpm/ajv@8.18.0/node_modules/ajv/dist/refs/json-schema-2020-12/meta/unevaluated.json -var require_unevaluated = /* @__PURE__ */ __commonJSMin(((exports, module) => { - module.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": true }, - "$dynamicAnchor": "meta", - "title": "Unevaluated applicator vocabulary meta-schema", - "type": ["object", "boolean"], - "properties": { - "unevaluatedItems": { "$dynamicRef": "#meta" }, - "unevaluatedProperties": { "$dynamicRef": "#meta" } - } - }; -})); - -//#endregion -//#region ../../node_modules/.pnpm/ajv@8.18.0/node_modules/ajv/dist/refs/json-schema-2020-12/meta/content.json -var require_content = /* @__PURE__ */ __commonJSMin(((exports, module) => { - module.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": true }, - "$dynamicAnchor": "meta", - "title": "Content vocabulary meta-schema", - "type": ["object", "boolean"], - "properties": { - "contentEncoding": { "type": "string" }, - "contentMediaType": { "type": "string" }, - "contentSchema": { "$dynamicRef": "#meta" } - } - }; -})); - -//#endregion -//#region ../../node_modules/.pnpm/ajv@8.18.0/node_modules/ajv/dist/refs/json-schema-2020-12/meta/core.json -var require_core = /* @__PURE__ */ __commonJSMin(((exports, module) => { - module.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": true }, - "$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" - } - } - }; -})); - -//#endregion -//#region ../../node_modules/.pnpm/ajv@8.18.0/node_modules/ajv/dist/refs/json-schema-2020-12/meta/format-annotation.json -var require_format_annotation = /* @__PURE__ */ __commonJSMin(((exports, module) => { - module.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": true }, - "$dynamicAnchor": "meta", - "title": "Format vocabulary meta-schema for annotation results", - "type": ["object", "boolean"], - "properties": { "format": { "type": "string" } } - }; -})); - -//#endregion -//#region ../../node_modules/.pnpm/ajv@8.18.0/node_modules/ajv/dist/refs/json-schema-2020-12/meta/meta-data.json -var require_meta_data = /* @__PURE__ */ __commonJSMin(((exports, module) => { - module.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": true }, - "$dynamicAnchor": "meta", - "title": "Meta-data vocabulary meta-schema", - "type": ["object", "boolean"], - "properties": { - "title": { "type": "string" }, - "description": { "type": "string" }, - "default": true, - "deprecated": { - "type": "boolean", - "default": false - }, - "readOnly": { - "type": "boolean", - "default": false - }, - "writeOnly": { - "type": "boolean", - "default": false - }, - "examples": { - "type": "array", - "items": true - } - } - }; -})); - -//#endregion -//#region ../../node_modules/.pnpm/ajv@8.18.0/node_modules/ajv/dist/refs/json-schema-2020-12/meta/validation.json -var require_validation = /* @__PURE__ */ __commonJSMin(((exports, module) => { - module.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": true }, - "$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": true - }] }, - "const": true, - "enum": { - "type": "array", - "items": true - }, - "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": false - }, - "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": true, - "default": [] - } - } - }; -})); - -//#endregion -//#region ../../node_modules/.pnpm/ajv@8.18.0/node_modules/ajv/dist/refs/json-schema-2020-12/index.js -var require_json_schema_2020_12 = /* @__PURE__ */ __commonJSMin(((exports) => { - Object.defineProperty(exports, "__esModule", { value: true }); - const metaSchema = require_schema(); - const applicator = require_applicator(); - const unevaluated = require_unevaluated(); - const content = require_content(); - const core = require_core(); - const format = require_format_annotation(); - const metadata = require_meta_data(); - const validation = require_validation(); - const META_SUPPORT_DATA = ["/properties"]; - function addMetaSchema2020($data) { - [ - metaSchema, - applicator, - unevaluated, - content, - core, - with$data(this, format), - metadata, - with$data(this, validation) - ].forEach((sch) => this.addMetaSchema(sch, void 0, false)); - return this; - function with$data(ajv, sch) { - return $data ? ajv.$dataMetaSchema(sch, META_SUPPORT_DATA) : sch; - } - } - exports.default = addMetaSchema2020; -})); - -//#endregion -//#region ../../node_modules/.pnpm/ajv@8.18.0/node_modules/ajv/dist/2020.js -var require__2020 = /* @__PURE__ */ __commonJSMin(((exports, module) => { - Object.defineProperty(exports, "__esModule", { value: true }); - exports.MissingRefError = exports.ValidationError = exports.CodeGen = exports.Name = exports.nil = exports.stringify = exports.str = exports._ = exports.KeywordCxt = exports.Ajv2020 = void 0; - const core_1 = require_core$3(); - const draft2020_1 = require_draft2020(); - const discriminator_1 = require_discriminator(); - const json_schema_2020_12_1 = require_json_schema_2020_12(); - const META_SCHEMA_ID = "https://json-schema.org/draft/2020-12/schema"; - var Ajv2020 = class extends core_1.default { - constructor(opts = {}) { - super({ - ...opts, - dynamicRef: true, - next: true, - unevaluated: true - }); - } - _addVocabularies() { - super._addVocabularies(); - draft2020_1.default.forEach((v) => this.addVocabulary(v)); - if (this.opts.discriminator) this.addKeyword(discriminator_1.default); - } - _addDefaultMetaSchema() { - super._addDefaultMetaSchema(); - const { $data, meta } = this.opts; - if (!meta) return; - json_schema_2020_12_1.default.call(this, $data); - this.refs["http://json-schema.org/schema"] = META_SCHEMA_ID; - } - defaultMeta() { - return this.opts.defaultMeta = super.defaultMeta() || (this.getSchema(META_SCHEMA_ID) ? META_SCHEMA_ID : void 0); - } - }; - exports.Ajv2020 = Ajv2020; - module.exports = exports = Ajv2020; - module.exports.Ajv2020 = Ajv2020; - Object.defineProperty(exports, "__esModule", { value: true }); - exports.default = Ajv2020; - var validate_1 = require_validate(); - Object.defineProperty(exports, "KeywordCxt", { - enumerable: true, - get: function() { - return validate_1.KeywordCxt; - } - }); - var codegen_1 = require_codegen(); - Object.defineProperty(exports, "_", { - enumerable: true, - get: function() { - return codegen_1._; - } - }); - Object.defineProperty(exports, "str", { - enumerable: true, - get: function() { - return codegen_1.str; - } - }); - Object.defineProperty(exports, "stringify", { - enumerable: true, - get: function() { - return codegen_1.stringify; - } - }); - Object.defineProperty(exports, "nil", { - enumerable: true, - get: function() { - return codegen_1.nil; - } - }); - Object.defineProperty(exports, "Name", { - enumerable: true, - get: function() { - return codegen_1.Name; - } - }); - Object.defineProperty(exports, "CodeGen", { - enumerable: true, - get: function() { - return codegen_1.CodeGen; - } - }); - var validation_error_1 = require_validation_error(); - Object.defineProperty(exports, "ValidationError", { - enumerable: true, - get: function() { - return validation_error_1.default; - } - }); - var ref_error_1 = require_ref_error(); - Object.defineProperty(exports, "MissingRefError", { - enumerable: true, - get: function() { - return ref_error_1.default; - } - }); -})); - -//#endregion -//#region ../../node_modules/.pnpm/ajv-formats@3.0.1_ajv@8.18.0/node_modules/ajv-formats/dist/formats.js -var require_formats = /* @__PURE__ */ __commonJSMin(((exports) => { - Object.defineProperty(exports, "__esModule", { value: true }); - exports.formatNames = exports.fastFormats = exports.fullFormats = void 0; - function fmtDef(validate, compare) { - return { - validate, - compare - }; - } - exports.fullFormats = { - date: fmtDef(date, compareDate), - time: fmtDef(getTime(true), compareTime), - "date-time": fmtDef(getDateTime(true), compareDateTime), - "iso-time": fmtDef(getTime(), compareIsoTime), - "iso-date-time": fmtDef(getDateTime(), compareIsoDateTime), - duration: /^P(?!$)((\d+Y)?(\d+M)?(\d+D)?(T(?=\d)(\d+H)?(\d+M)?(\d+S)?)?|(\d+W)?)$/, - uri, - "uri-reference": /^(?:[a-z][a-z0-9+\-.]*:)?(?:\/?\/(?:(?:[a-z0-9\-._~!$&'()*+,;=:]|%[0-9a-f]{2})*@)?(?:\[(?:(?:(?:(?:[0-9a-f]{1,4}:){6}|::(?:[0-9a-f]{1,4}:){5}|(?:[0-9a-f]{1,4})?::(?:[0-9a-f]{1,4}:){4}|(?:(?:[0-9a-f]{1,4}:){0,1}[0-9a-f]{1,4})?::(?:[0-9a-f]{1,4}:){3}|(?:(?:[0-9a-f]{1,4}:){0,2}[0-9a-f]{1,4})?::(?:[0-9a-f]{1,4}:){2}|(?:(?:[0-9a-f]{1,4}:){0,3}[0-9a-f]{1,4})?::[0-9a-f]{1,4}:|(?:(?:[0-9a-f]{1,4}:){0,4}[0-9a-f]{1,4})?::)(?:[0-9a-f]{1,4}:[0-9a-f]{1,4}|(?:(?:25[0-5]|2[0-4]\d|[01]?\d\d?)\.){3}(?:25[0-5]|2[0-4]\d|[01]?\d\d?))|(?:(?:[0-9a-f]{1,4}:){0,5}[0-9a-f]{1,4})?::[0-9a-f]{1,4}|(?:(?:[0-9a-f]{1,4}:){0,6}[0-9a-f]{1,4})?::)|[Vv][0-9a-f]+\.[a-z0-9\-._~!$&'()*+,;=:]+)\]|(?:(?:25[0-5]|2[0-4]\d|[01]?\d\d?)\.){3}(?:25[0-5]|2[0-4]\d|[01]?\d\d?)|(?:[a-z0-9\-._~!$&'"()*+,;=]|%[0-9a-f]{2})*)(?::\d*)?(?:\/(?:[a-z0-9\-._~!$&'"()*+,;=:@]|%[0-9a-f]{2})*)*|\/(?:(?:[a-z0-9\-._~!$&'"()*+,;=:@]|%[0-9a-f]{2})+(?:\/(?:[a-z0-9\-._~!$&'"()*+,;=:@]|%[0-9a-f]{2})*)*)?|(?:[a-z0-9\-._~!$&'"()*+,;=:@]|%[0-9a-f]{2})+(?:\/(?:[a-z0-9\-._~!$&'"()*+,;=:@]|%[0-9a-f]{2})*)*)?(?:\?(?:[a-z0-9\-._~!$&'"()*+,;=:@/?]|%[0-9a-f]{2})*)?(?:#(?:[a-z0-9\-._~!$&'"()*+,;=:@/?]|%[0-9a-f]{2})*)?$/i, - "uri-template": /^(?:(?:[^\x00-\x20"'<>%\\^`{|}]|%[0-9a-f]{2})|\{[+#./;?&=,!@|]?(?:[a-z0-9_]|%[0-9a-f]{2})+(?::[1-9][0-9]{0,3}|\*)?(?:,(?:[a-z0-9_]|%[0-9a-f]{2})+(?::[1-9][0-9]{0,3}|\*)?)*\})*$/i, - url: /^(?:https?|ftp):\/\/(?:\S+(?::\S*)?@)?(?:(?!(?:10|127)(?:\.\d{1,3}){3})(?!(?:169\.254|192\.168)(?:\.\d{1,3}){2})(?!172\.(?:1[6-9]|2\d|3[0-1])(?:\.\d{1,3}){2})(?:[1-9]\d?|1\d\d|2[01]\d|22[0-3])(?:\.(?:1?\d{1,2}|2[0-4]\d|25[0-5])){2}(?:\.(?:[1-9]\d?|1\d\d|2[0-4]\d|25[0-4]))|(?:(?:[a-z0-9\u{00a1}-\u{ffff}]+-)*[a-z0-9\u{00a1}-\u{ffff}]+)(?:\.(?:[a-z0-9\u{00a1}-\u{ffff}]+-)*[a-z0-9\u{00a1}-\u{ffff}]+)*(?:\.(?:[a-z\u{00a1}-\u{ffff}]{2,})))(?::\d{2,5})?(?:\/[^\s]*)?$/iu, - email: /^[a-z0-9!#$%&'*+/=?^_`{|}~-]+(?:\.[a-z0-9!#$%&'*+/=?^_`{|}~-]+)*@(?:[a-z0-9](?:[a-z0-9-]*[a-z0-9])?\.)+[a-z0-9](?:[a-z0-9-]*[a-z0-9])?$/i, - hostname: /^(?=.{1,253}\.?$)[a-z0-9](?:[a-z0-9-]{0,61}[a-z0-9])?(?:\.[a-z0-9](?:[-0-9a-z]{0,61}[0-9a-z])?)*\.?$/i, - ipv4: /^(?:(?:25[0-5]|2[0-4]\d|1\d\d|[1-9]?\d)\.){3}(?:25[0-5]|2[0-4]\d|1\d\d|[1-9]?\d)$/, - ipv6: /^((([0-9a-f]{1,4}:){7}([0-9a-f]{1,4}|:))|(([0-9a-f]{1,4}:){6}(:[0-9a-f]{1,4}|((25[0-5]|2[0-4]\d|1\d\d|[1-9]?\d)(\.(25[0-5]|2[0-4]\d|1\d\d|[1-9]?\d)){3})|:))|(([0-9a-f]{1,4}:){5}(((:[0-9a-f]{1,4}){1,2})|:((25[0-5]|2[0-4]\d|1\d\d|[1-9]?\d)(\.(25[0-5]|2[0-4]\d|1\d\d|[1-9]?\d)){3})|:))|(([0-9a-f]{1,4}:){4}(((:[0-9a-f]{1,4}){1,3})|((:[0-9a-f]{1,4})?:((25[0-5]|2[0-4]\d|1\d\d|[1-9]?\d)(\.(25[0-5]|2[0-4]\d|1\d\d|[1-9]?\d)){3}))|:))|(([0-9a-f]{1,4}:){3}(((:[0-9a-f]{1,4}){1,4})|((:[0-9a-f]{1,4}){0,2}:((25[0-5]|2[0-4]\d|1\d\d|[1-9]?\d)(\.(25[0-5]|2[0-4]\d|1\d\d|[1-9]?\d)){3}))|:))|(([0-9a-f]{1,4}:){2}(((:[0-9a-f]{1,4}){1,5})|((:[0-9a-f]{1,4}){0,3}:((25[0-5]|2[0-4]\d|1\d\d|[1-9]?\d)(\.(25[0-5]|2[0-4]\d|1\d\d|[1-9]?\d)){3}))|:))|(([0-9a-f]{1,4}:){1}(((:[0-9a-f]{1,4}){1,6})|((:[0-9a-f]{1,4}){0,4}:((25[0-5]|2[0-4]\d|1\d\d|[1-9]?\d)(\.(25[0-5]|2[0-4]\d|1\d\d|[1-9]?\d)){3}))|:))|(:(((:[0-9a-f]{1,4}){1,7})|((:[0-9a-f]{1,4}){0,5}:((25[0-5]|2[0-4]\d|1\d\d|[1-9]?\d)(\.(25[0-5]|2[0-4]\d|1\d\d|[1-9]?\d)){3}))|:)))$/i, - regex, - 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, - int32: { - type: "number", - validate: validateInt32 - }, - int64: { - type: "number", - validate: validateInt64 - }, - float: { - type: "number", - validate: validateNumber - }, - double: { - type: "number", - validate: validateNumber - }, - password: true, - binary: true - }; - exports.fastFormats = { - ...exports.fullFormats, - date: fmtDef(/^\d\d\d\d-[0-1]\d-[0-3]\d$/, compareDate), - time: fmtDef(/^(?:[0-2]\d:[0-5]\d:[0-5]\d|23:59:60)(?:\.\d+)?(?:z|[+-]\d\d(?::?\d\d)?)$/i, compareTime), - "date-time": fmtDef(/^\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, compareDateTime), - "iso-time": fmtDef(/^(?:[0-2]\d:[0-5]\d:[0-5]\d|23:59:60)(?:\.\d+)?(?:z|[+-]\d\d(?::?\d\d)?)?$/i, compareIsoTime), - "iso-date-time": fmtDef(/^\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, compareIsoDateTime), - uri: /^(?:[a-z][a-z0-9+\-.]*:)(?:\/?\/)?[^\s]*$/i, - "uri-reference": /^(?:(?:[a-z][a-z0-9+\-.]*:)?\/?\/)?(?:[^\\\s#][^\s#]*)?(?:#[^\\\s]*)?$/i, - email: /^[a-z0-9.!#$%&'*+/=?^_`{|}~-]+@[a-z0-9](?:[a-z0-9-]{0,61}[a-z0-9])?(?:\.[a-z0-9](?:[a-z0-9-]{0,61}[a-z0-9])?)*$/i - }; - exports.formatNames = Object.keys(exports.fullFormats); - function isLeapYear(year) { - return year % 4 === 0 && (year % 100 !== 0 || year % 400 === 0); - } - const DATE = /^(\d\d\d\d)-(\d\d)-(\d\d)$/; - const DAYS = [ - 0, - 31, - 28, - 31, - 30, - 31, - 30, - 31, - 31, - 30, - 31, - 30, - 31 - ]; - function date(str) { - const matches = DATE.exec(str); - if (!matches) return false; - const year = +matches[1]; - const month = +matches[2]; - const day = +matches[3]; - return month >= 1 && month <= 12 && day >= 1 && day <= (month === 2 && isLeapYear(year) ? 29 : DAYS[month]); - } - function compareDate(d1, d2) { - if (!(d1 && d2)) return void 0; - if (d1 > d2) return 1; - if (d1 < d2) return -1; - return 0; - } - const TIME = /^(\d\d):(\d\d):(\d\d(?:\.\d+)?)(z|([+-])(\d\d)(?::?(\d\d))?)?$/i; - function getTime(strictTimeZone) { - return function time(str) { - const matches = TIME.exec(str); - if (!matches) return false; - const hr = +matches[1]; - const min = +matches[2]; - const sec = +matches[3]; - const tz = matches[4]; - const tzSign = matches[5] === "-" ? -1 : 1; - const tzH = +(matches[6] || 0); - const tzM = +(matches[7] || 0); - if (tzH > 23 || tzM > 59 || strictTimeZone && !tz) return false; - if (hr <= 23 && min <= 59 && sec < 60) return true; - const utcMin = min - tzM * tzSign; - const utcHr = hr - tzH * tzSign - (utcMin < 0 ? 1 : 0); - return (utcHr === 23 || utcHr === -1) && (utcMin === 59 || utcMin === -1) && sec < 61; - }; - } - function compareTime(s1, s2) { - if (!(s1 && s2)) return void 0; - const t1 = (/* @__PURE__ */ new Date("2020-01-01T" + s1)).valueOf(); - const t2 = (/* @__PURE__ */ new Date("2020-01-01T" + s2)).valueOf(); - if (!(t1 && t2)) return void 0; - return t1 - t2; - } - function compareIsoTime(t1, t2) { - if (!(t1 && t2)) return void 0; - const a1 = TIME.exec(t1); - const a2 = TIME.exec(t2); - if (!(a1 && a2)) return void 0; - t1 = a1[1] + a1[2] + a1[3]; - t2 = a2[1] + a2[2] + a2[3]; - if (t1 > t2) return 1; - if (t1 < t2) return -1; - return 0; - } - const DATE_TIME_SEPARATOR = /t|\s/i; - function getDateTime(strictTimeZone) { - const time = getTime(strictTimeZone); - return function date_time(str) { - const dateTime = str.split(DATE_TIME_SEPARATOR); - return dateTime.length === 2 && date(dateTime[0]) && time(dateTime[1]); - }; - } - function compareDateTime(dt1, dt2) { - if (!(dt1 && dt2)) return void 0; - const d1 = new Date(dt1).valueOf(); - const d2 = new Date(dt2).valueOf(); - if (!(d1 && d2)) return void 0; - return d1 - d2; - } - function compareIsoDateTime(dt1, dt2) { - if (!(dt1 && dt2)) return void 0; - const [d1, t1] = dt1.split(DATE_TIME_SEPARATOR); - const [d2, t2] = dt2.split(DATE_TIME_SEPARATOR); - const res = compareDate(d1, d2); - if (res === void 0) return void 0; - return res || compareTime(t1, t2); - } - const NOT_URI_FRAGMENT = /\/|:/; - const URI = /^(?:[a-z][a-z0-9+\-.]*:)(?:\/?\/(?:(?:[a-z0-9\-._~!$&'()*+,;=:]|%[0-9a-f]{2})*@)?(?:\[(?:(?:(?:(?:[0-9a-f]{1,4}:){6}|::(?:[0-9a-f]{1,4}:){5}|(?:[0-9a-f]{1,4})?::(?:[0-9a-f]{1,4}:){4}|(?:(?:[0-9a-f]{1,4}:){0,1}[0-9a-f]{1,4})?::(?:[0-9a-f]{1,4}:){3}|(?:(?:[0-9a-f]{1,4}:){0,2}[0-9a-f]{1,4})?::(?:[0-9a-f]{1,4}:){2}|(?:(?:[0-9a-f]{1,4}:){0,3}[0-9a-f]{1,4})?::[0-9a-f]{1,4}:|(?:(?:[0-9a-f]{1,4}:){0,4}[0-9a-f]{1,4})?::)(?:[0-9a-f]{1,4}:[0-9a-f]{1,4}|(?:(?:25[0-5]|2[0-4]\d|[01]?\d\d?)\.){3}(?:25[0-5]|2[0-4]\d|[01]?\d\d?))|(?:(?:[0-9a-f]{1,4}:){0,5}[0-9a-f]{1,4})?::[0-9a-f]{1,4}|(?:(?:[0-9a-f]{1,4}:){0,6}[0-9a-f]{1,4})?::)|[Vv][0-9a-f]+\.[a-z0-9\-._~!$&'()*+,;=:]+)\]|(?:(?:25[0-5]|2[0-4]\d|[01]?\d\d?)\.){3}(?:25[0-5]|2[0-4]\d|[01]?\d\d?)|(?:[a-z0-9\-._~!$&'()*+,;=]|%[0-9a-f]{2})*)(?::\d*)?(?:\/(?:[a-z0-9\-._~!$&'()*+,;=:@]|%[0-9a-f]{2})*)*|\/(?:(?:[a-z0-9\-._~!$&'()*+,;=:@]|%[0-9a-f]{2})+(?:\/(?:[a-z0-9\-._~!$&'()*+,;=:@]|%[0-9a-f]{2})*)*)?|(?:[a-z0-9\-._~!$&'()*+,;=:@]|%[0-9a-f]{2})+(?:\/(?:[a-z0-9\-._~!$&'()*+,;=:@]|%[0-9a-f]{2})*)*)(?:\?(?:[a-z0-9\-._~!$&'()*+,;=:@/?]|%[0-9a-f]{2})*)?(?:#(?:[a-z0-9\-._~!$&'()*+,;=:@/?]|%[0-9a-f]{2})*)?$/i; - function uri(str) { - return NOT_URI_FRAGMENT.test(str) && URI.test(str); - } - const BYTE = /^(?:[A-Za-z0-9+/]{4})*(?:[A-Za-z0-9+/]{2}==|[A-Za-z0-9+/]{3}=)?$/gm; - function byte(str) { - BYTE.lastIndex = 0; - return BYTE.test(str); - } - const MIN_INT32 = -(2 ** 31); - const MAX_INT32 = 2 ** 31 - 1; - function validateInt32(value) { - return Number.isInteger(value) && value <= MAX_INT32 && value >= MIN_INT32; - } - function validateInt64(value) { - return Number.isInteger(value); - } - function validateNumber() { - return true; - } - const Z_ANCHOR = /[^\\]\\Z/; - function regex(str) { - if (Z_ANCHOR.test(str)) return false; - try { - new RegExp(str); - return true; - } catch (e) { - return false; - } - } -})); - -//#endregion -//#region ../../node_modules/.pnpm/ajv-formats@3.0.1_ajv@8.18.0/node_modules/ajv-formats/dist/limit.js -var require_limit = /* @__PURE__ */ __commonJSMin(((exports) => { - Object.defineProperty(exports, "__esModule", { value: true }); - exports.formatLimitDefinition = void 0; - const ajv_1 = require_ajv(); - const codegen_1 = require_codegen(); - const ops = codegen_1.operators; - const KWDs = { - formatMaximum: { - okStr: "<=", - ok: ops.LTE, - fail: ops.GT - }, - formatMinimum: { - okStr: ">=", - ok: ops.GTE, - fail: ops.LT - }, - formatExclusiveMaximum: { - okStr: "<", - ok: ops.LT, - fail: ops.GTE - }, - formatExclusiveMinimum: { - okStr: ">", - ok: ops.GT, - fail: ops.LTE - } - }; - const error = { - message: ({ keyword, schemaCode }) => (0, codegen_1.str)`should be ${KWDs[keyword].okStr} ${schemaCode}`, - params: ({ keyword, schemaCode }) => (0, codegen_1._)`{comparison: ${KWDs[keyword].okStr}, limit: ${schemaCode}}` - }; - exports.formatLimitDefinition = { - keyword: Object.keys(KWDs), - type: "string", - schemaType: "string", - $data: true, - error, - code(cxt) { - const { gen, data, schemaCode, keyword, it } = cxt; - const { opts, self } = it; - if (!opts.validateFormats) return; - const fCxt = new ajv_1.KeywordCxt(it, self.RULES.all.format.definition, "format"); - if (fCxt.$data) validate$DataFormat(); - else validateFormat(); - function validate$DataFormat() { - const fmts = gen.scopeValue("formats", { - ref: self.formats, - code: opts.code.formats - }); - const fmt = gen.const("fmt", (0, codegen_1._)`${fmts}[${fCxt.schemaCode}]`); - cxt.fail$data((0, codegen_1.or)((0, codegen_1._)`typeof ${fmt} != "object"`, (0, codegen_1._)`${fmt} instanceof RegExp`, (0, codegen_1._)`typeof ${fmt}.compare != "function"`, compareCode(fmt))); - } - function validateFormat() { - const format = fCxt.schema; - const fmtDef = self.formats[format]; - if (!fmtDef || fmtDef === true) return; - if (typeof fmtDef != "object" || fmtDef instanceof RegExp || typeof fmtDef.compare != "function") throw new Error(`"${keyword}": format "${format}" does not define "compare" function`); - const fmt = gen.scopeValue("formats", { - key: format, - ref: fmtDef, - code: opts.code.formats ? (0, codegen_1._)`${opts.code.formats}${(0, codegen_1.getProperty)(format)}` : void 0 - }); - cxt.fail$data(compareCode(fmt)); - } - function compareCode(fmt) { - return (0, codegen_1._)`${fmt}.compare(${data}, ${schemaCode}) ${KWDs[keyword].fail} 0`; - } - }, - dependencies: ["format"] - }; - const formatLimitPlugin = (ajv) => { - ajv.addKeyword(exports.formatLimitDefinition); - return ajv; - }; - exports.default = formatLimitPlugin; -})); - -//#endregion -//#region ../../node_modules/.pnpm/ajv-formats@3.0.1_ajv@8.18.0/node_modules/ajv-formats/dist/index.js -var require_dist = /* @__PURE__ */ __commonJSMin(((exports, module) => { - Object.defineProperty(exports, "__esModule", { value: true }); - const formats_1 = require_formats(); - const limit_1 = require_limit(); - const codegen_1 = require_codegen(); - const fullName = new codegen_1.Name("fullFormats"); - const fastName = new codegen_1.Name("fastFormats"); - const formatsPlugin = (ajv, opts = { keywords: true }) => { - if (Array.isArray(opts)) { - addFormats(ajv, opts, formats_1.fullFormats, fullName); - return ajv; - } - const [formats, exportName] = opts.mode === "fast" ? [formats_1.fastFormats, fastName] : [formats_1.fullFormats, fullName]; - addFormats(ajv, opts.formats || formats_1.formatNames, formats, exportName); - if (opts.keywords) (0, limit_1.default)(ajv); - return ajv; - }; - formatsPlugin.get = (name, mode = "full") => { - const f = (mode === "fast" ? formats_1.fastFormats : formats_1.fullFormats)[name]; - if (!f) throw new Error(`Unknown format "${name}"`); - return f; - }; - function addFormats(ajv, list, fs, exportName) { - var _a; - var _b; - (_a = (_b = ajv.opts.code).formats) !== null && _a !== void 0 || (_b.formats = (0, codegen_1._)`require("ajv-formats/dist/formats").${exportName}`); - for (const f of list) ajv.addFormat(f, fs[f]); - } - module.exports = exports = formatsPlugin; - Object.defineProperty(exports, "__esModule", { value: true }); - exports.default = formatsPlugin; -})); - -//#endregion -//#region ../core-internal/src/validators/ajvProvider.ts -var import_ajv = require_ajv(); -var import__2019 = require__2019(); -var import__2020 = require__2020(); -var import_dist = /* @__PURE__ */ __toESM(require_dist(), 1); -/** `ajv-formats` default export, normalised through the CJS/ESM interop wrapper. */ -const ajvProvider_CEoC_sr_addFormats = import_dist.default; -function createDefaultAjvInstance(engineClass) { - const ajv = new engineClass({ - strict: false, - validateFormats: true, - validateSchema: false, - allErrors: true - }); - ajvProvider_CEoC_sr_addFormats(ajv); - return ajv; -} -/** -* AJV-backed JSON Schema validator. See `@modelcontextprotocol/{client,server}/validators/ajv` -* for the customisation entry point (re-exports `Ajv` and `addFormats` from the bundled copy). -* -* Default dispatches on the schema's declared dialect: no `$schema` or 2020-12 → `Ajv2020` -* (SEP-1613); 2019-09 → `Ajv2019`; draft-07 or draft-06 → the classic draft-07 `Ajv` class -* (draft-07's changes over draft-06 are additive, so one engine covers both). Known draft-07 deviation: classic Ajv -* evaluates keywords adjacent to `$ref` (stricter than draft-07's ignore-siblings rule, matching -* v1's default engine), while the cfworker provider ignores them per spec. -* Schemas declaring any other `$schema` are -* rejected with a plain `Error`; pass a pre-configured Ajv instance to validate -* other dialects. The SDK bundles ajv internally but does not re-export `Ajv2020` (its type -* graph tips downstream declaration bundling — see #2339). To construct a custom 2020-12 -* instance, add `ajv` to your own dependencies (matching the SDK's pinned version) and -* `import { Ajv2020 } from 'ajv/dist/2020.js'` — `new Ajv(...)` is the draft-07 class and would -* silently downgrade dialect. -* -* @example Use with default configuration -* ```ts source="./ajvProvider.examples.ts#AjvJsonSchemaValidator_default" -* const validator = new AjvJsonSchemaValidator(); -* ``` -* -* @example Use with a custom AJV instance -* ```ts source="./ajvProvider.examples.ts#AjvJsonSchemaValidator_customInstance" -* // import { Ajv2020 } from 'ajv/dist/2020.js'; -* const ajv = new Ajv2020({ strict: false, validateSchema: false, allErrors: true }); -* const validator = new AjvJsonSchemaValidator(ajv); -* ``` -* -* @example Register ajv-formats -* ```ts source="./ajvProvider.examples.ts#AjvJsonSchemaValidator_withFormats" -* // import { Ajv2020 } from 'ajv/dist/2020.js'; -* const ajv = new Ajv2020({ strict: false, validateSchema: false, allErrors: true }); -* addFormats(ajv); -* const validator = new AjvJsonSchemaValidator(ajv); -* ``` -*/ -var AjvJsonSchemaValidator = class { - _ajv; - /** Lazy classic (draft-07) engine, built on the first draft-07/draft-06-declared schema. */ - _ajvDraft7; - /** Lazy 2019-09 engine, built on the first 2019-09-declared schema. */ - _ajv2019; - /** True iff the constructor received a caller-supplied engine; the `$schema` dispatch is skipped. */ - _userAjv; - /** - * @param ajv - Optional pre-configured AJV-compatible instance. When supplied, this instance is - * used for **every** schema regardless of its declared `$schema` (the caller owns dialect - * choice). When omitted, the provider constructs per-dialect engines (`Ajv2020`, `Ajv2019`, - * and the classic draft-07 `Ajv` for draft-07/06-declared schemas) with - * `strict: false`, `validateFormats: true`, `validateSchema: false`, `allErrors: true`, and - * `ajv-formats` registered — **lazily, on the first {@linkcode getValidator} call needing each**, so - * constructing the provider (e.g. as the default validator of a `Client`/`Server` that never - * validates a JSON Schema) does not pay the ajv + ajv-formats instantiation cost. The parameter - * is typed structurally so consumers who don't pass an instance need not have `ajv` installed. - */ - constructor(ajv) { - this._userAjv = ajv !== void 0; - this._ajv = ajv; - } - /** The underlying 2020-12 engine — the default instance is created on first use. */ - get ajv() { - return this._ajv ??= createDefaultAjvInstance(import__2020.Ajv2020); - } - /** - * Pick the engine for a schema's declared dialect. A caller-supplied engine is used for - * every schema — do not second-guess by `$schema` (bring-your-own-validator means - * bring-your-own-dialect). Otherwise: no `$schema` or 2020-12 → `Ajv2020`; 2019-09 → - * `Ajv2019`; draft-07 or draft-06 → classic `Ajv`; anything else → `Error`. - */ - _engineFor(schema) { - if (this._userAjv) return this.ajv; - const dialect = declaredDialect(schema, "pass a pre-configured Ajv instance to AjvJsonSchemaValidator(ajv) to validate other dialects."); - if (dialect === "2020-12") return this.ajv; - if (dialect === "2019-09") return this._ajv2019 ??= createDefaultAjvInstance(import__2019.Ajv2019); - return this._ajvDraft7 ??= createDefaultAjvInstance(import_ajv.Ajv); - } - getValidator(schema) { - const engine = this._engineFor(schema); - const ajvValidator = "$id" in schema && typeof schema.$id === "string" ? engine.getSchema(schema.$id) ?? engine.compile(schema) : engine.compile(schema); - return (input) => { - return ajvValidator(input) ? { - valid: true, - data: input, - errorMessage: void 0 - } : { - valid: false, - data: void 0, - errorMessage: engine.errorsText(ajvValidator.errors) - }; - }; - } -}; -/** -* Draft-07 AJV class, re-exported for consumers who need to opt back to the pre-SEP-1613 default. -* The full v1-equivalent construction is: -* -* ```ts -* const ajv = new Ajv({ strict: false, validateFormats: true, validateSchema: false, allErrors: true }); -* addFormats(ajv); -* new AjvJsonSchemaValidator(ajv); -* ``` -* -* (omitting `validateSchema: false` makes a 2020-12-stamped `$schema` fail with an opaque -* "no schema with key or ref …" engine error; omitting `addFormats` silently drops `format` -* validation that the v1 default had). -* -* The SDK bundles ajv internally but does not re-export `Ajv2020` (its type graph tips downstream -* declaration bundling — see #2339). To construct a custom 2020-12 instance, add `ajv` to your own -* dependencies (matching the SDK's pinned version) and `import { Ajv2020 } from 'ajv/dist/2020.js'`. -*/ -const ajvProvider_CEoC_sr_Ajv = import_ajv.Ajv; - -//#endregion - -//# sourceMappingURL=ajvProvider-CEoC__sr.mjs.map - - - - - - - - -//#region src/server/completable.ts -const COMPLETABLE_SYMBOL = Symbol.for("mcp.completable"); -/** -* Wraps a schema to provide autocompletion capabilities. Useful for, e.g., prompt arguments in MCP. -* -* @example -* ```ts source="./completable.examples.ts#completable_basicUsage" -* server.registerPrompt( -* 'review-code', -* { -* title: 'Code Review', -* argsSchema: z.object({ -* language: completable(z.string().describe('Programming language'), value => -* ['typescript', 'javascript', 'python', 'rust', 'go'].filter(lang => lang.startsWith(value)) -* ) -* }) -* }, -* ({ language }) => ({ -* messages: [ -* { -* role: 'user' as const, -* content: { -* type: 'text' as const, -* text: `Review this ${language} code.` -* } -* } -* ] -* }) -* ); -* ``` -* -* @see {@linkcode server/mcp.McpServer.registerPrompt | McpServer.registerPrompt} for using completable schemas in prompt argument definitions -*/ -function completable(schema, complete) { - Object.defineProperty(schema, COMPLETABLE_SYMBOL, { - value: { complete }, - enumerable: false, - writable: false, - configurable: false - }); - return schema; -} -/** -* Checks if a schema is completable (has completion metadata). -*/ -function isCompletable(schema) { - return !!schema && typeof schema === "object" && COMPLETABLE_SYMBOL in schema; -} -/** -* Gets the completer callback from a completable schema, if it exists. -*/ -function getCompleter(schema) { - return schema[COMPLETABLE_SYMBOL]?.complete; -} - -//#endregion -//#region src/server/sseKeepAlive.ts -/** Default interval between SSE keep-alive comment frames. */ -const mcp_DXXb3Vv3_DEFAULT_SSE_KEEP_ALIVE_MS = 15e3; -const MAX_TIMER_DELAY_MS = (/* unused pure expression or super */ null && (2 ** 31 - 1)); -/** Arms an unref'd timer, or disables keep-alive for invalid delays. */ -function mcp_DXXb3Vv3_armSseKeepAlive(intervalMs, onTick) { - if (!Number.isFinite(intervalMs) || intervalMs < 1) return; - const timer = setInterval(onTick, Math.min(intervalMs, MAX_TIMER_DELAY_MS)); - timer.unref?.(); - return timer; -} - -//#endregion -//#region src/server/serverEventBus.ts -/** -* A `ServerEventBus` backed by an in-process listener set. -* -* `publish()` delivers synchronously to the live listener set (a listener -* unsubscribing itself mid-dispatch is safe; the entry's listen-router -* listeners never unsubscribe peers). A throwing listener does not stop -* delivery to the others. -*/ -var mcp_DXXb3Vv3_InMemoryServerEventBus = class { - _listeners = /* @__PURE__ */ new Set(); - /** - * @param onerror - Optional callback for errors thrown by listeners - * during dispatch. - */ - constructor(onerror) { - this.onerror = onerror; - } - publish(event) { - for (const listener of this._listeners) try { - listener(event); - } catch (error) { - this.onerror?.(error instanceof Error ? error : new Error(String(error))); - } - } - subscribe(listener) { - this._listeners.add(listener); - let live = true; - return () => { - if (!live) return; - live = false; - this._listeners.delete(listener); - }; - } - /** The number of currently registered listeners (test/introspection only — the routers track capacity via their own open-subscription set). */ - get listenerCount() { - return this._listeners.size; - } -}; -/** Build a {@linkcode ServerNotifier} over a bus. */ -function mcp_DXXb3Vv3_createServerNotifier(bus) { - return { - toolsChanged: () => bus.publish({ kind: "tools_list_changed" }), - promptsChanged: () => bus.publish({ kind: "prompts_list_changed" }), - resourcesChanged: () => bus.publish({ kind: "resources_list_changed" }), - resourceUpdated: (uri) => bus.publish({ - kind: "resource_updated", - uri - }) - }; -} -/** -* Whether a `subscriptions/listen` filter accepts a given change event. -* -* Pure: no I/O, no mutation. The filter governs ONLY the four -* subscription-gated change types — non-gated notifications never reach the -* bus and are not modeled here. -* -* `resource_updated` matches only when `resourceSubscriptions` is present and -* contains the event's URI exactly (per the spec: "for these resource URIs"). -*/ -function listenFilterAccepts(filter, event) { - switch (event.kind) { - case "tools_list_changed": return filter.toolsListChanged === true; - case "prompts_list_changed": return filter.promptsListChanged === true; - case "resources_list_changed": return filter.resourcesListChanged === true; - case "resource_updated": return filter.resourceSubscriptions !== void 0 && filter.resourceSubscriptions.includes(event.uri); - } -} -/** -* The honored subset of a requested filter: keeps only the fields the client -* explicitly opted in to (drops `false` and absent fields), narrowed against -* the server's declared capabilities when supplied. The serving entry sends -* this back in `notifications/subscriptions/acknowledged` so the ack reflects -* what the server can actually deliver. -* -* - `toolsListChanged` is honored only when `capabilities.tools.listChanged` -* is advertised; likewise `promptsListChanged` / `resourcesListChanged`. -* - `resourceSubscriptions` is honored only when -* `capabilities.resources.subscribe` is advertised. -* -* `capabilities` is optional on this pure helper for test convenience only — -* both wired routers REQUIRE capabilities at the call site (the HTTP router's -* `serve()` takes a required parameter; `StdioListenRouter.serve()` throws -* before `setServerCapabilities()` was called), so the fail-open -* `undefined → honor everything` branch is never reachable on a wired entry. -*/ -function honoredSubset(requested, capabilities) { - const honored = {}; - const allow = (bit) => capabilities === void 0 || bit === true; - if (requested.toolsListChanged === true && allow(capabilities?.tools?.listChanged)) honored.toolsListChanged = true; - if (requested.promptsListChanged === true && allow(capabilities?.prompts?.listChanged)) honored.promptsListChanged = true; - if (requested.resourcesListChanged === true && allow(capabilities?.resources?.listChanged)) honored.resourcesListChanged = true; - if (requested.resourceSubscriptions !== void 0 && requested.resourceSubscriptions.length > 0 && allow(capabilities?.resources?.subscribe)) honored.resourceSubscriptions = [...requested.resourceSubscriptions]; - return honored; -} -/** Map a {@linkcode ServerEvent} onto its wire notification `{method, params}`. */ -function serverEventToNotification(event) { - switch (event.kind) { - case "tools_list_changed": return { method: "notifications/tools/list_changed" }; - case "prompts_list_changed": return { method: "notifications/prompts/list_changed" }; - case "resources_list_changed": return { method: "notifications/resources/list_changed" }; - case "resource_updated": return { - method: "notifications/resources/updated", - params: { uri: event.uri } - }; - } -} - -//#endregion -//#region src/server/listenRouter.ts -/** Default capacity guard: refuse a new subscription when this many are already open. */ -const mcp_DXXb3Vv3_DEFAULT_MAX_SUBSCRIPTIONS = 1024; -function jsonRpcError(id, code, message) { - return Response.json({ - jsonrpc: "2.0", - error: { - code, - message - }, - id - }, { status: 200 }); -} -/** Stamp the subscription id onto a notification's `_meta`. Non-mutating. */ -function stampSubscriptionId(notification, subscriptionId) { - return { - method: notification.method, - params: { - ...notification.params, - _meta: { - ...notification.params?._meta, - [SUBSCRIPTION_ID_META_KEY]: subscriptionId - } - } - }; -} -/** -* Read the requested filter off a `subscriptions/listen` request body. -* Returns the validated filter, or `undefined` when `params.notifications` -* is absent or fails the schema (the caller answers `-32602` — the spec -* marks `notifications` REQUIRED on the listen request). -*/ -function parseListenFilter(message) { - const outcome = codecForVersion(MODERN_WIRE_REVISION).validateRequest("subscriptions/listen", message); - return outcome.ok ? outcome.value.params?.notifications : void 0; -} -function mcp_DXXb3Vv3_createListenRouter(options) { - const { bus, onerror } = options; - const maxSubscriptions = options.maxSubscriptions ?? mcp_DXXb3Vv3_DEFAULT_MAX_SUBSCRIPTIONS; - const keepAliveMs = options.keepAliveMs ?? mcp_DXXb3Vv3_DEFAULT_SSE_KEEP_ALIVE_MS; - const open = /* @__PURE__ */ new Set(); - function serve(message, signal, capabilities, serverInfo) { - if (open.size >= maxSubscriptions) { - onerror?.(/* @__PURE__ */ new Error(`subscriptions/listen refused: subscription limit reached (${maxSubscriptions})`)); - return jsonRpcError(message.id, -32603, "Subscription limit reached"); - } - const filter = parseListenFilter(message); - if (filter === void 0) return jsonRpcError(message.id, -32602, "Invalid params: 'notifications' is required and must be a valid SubscriptionFilter"); - const honored = honoredSubset(filter, capabilities); - const subscriptionId = message.id; - const encoder = new TextEncoder(); - let controller; - let closed = false; - let unsubscribe; - let keepAliveTimer; - let abortCleanup; - const writeFrame = (frame) => { - if (closed) return; - try { - controller.enqueue(encoder.encode(frame)); - } catch (error) { - onerror?.(error instanceof Error ? error : new Error(String(error))); - } - }; - const writeNotification = (method, params) => { - writeFrame(`event: message\ndata: ${JSON.stringify({ - jsonrpc: "2.0", - method, - params - })}\n\n`); - }; - const teardown = (graceful) => { - if (closed) return; - if (graceful) writeFrame(`event: message\ndata: ${JSON.stringify({ - jsonrpc: "2.0", - id: subscriptionId, - result: { - resultType: "complete", - _meta: { - [SUBSCRIPTION_ID_META_KEY]: subscriptionId, - [SERVER_INFO_META_KEY]: serverInfo - } - } - })}\n\n`); - closed = true; - try { - unsubscribe?.(); - } catch (error) { - onerror?.(error instanceof Error ? error : new Error(String(error))); - } - if (keepAliveTimer !== void 0) clearInterval(keepAliveTimer); - abortCleanup?.(); - open.delete(teardown); - try { - controller.close(); - } catch {} - }; - const readable = new ReadableStream({ - start(streamController) { - controller = streamController; - const ack = stampSubscriptionId({ - method: "notifications/subscriptions/acknowledged", - params: { notifications: honored } - }, subscriptionId); - writeNotification(ack.method, ack.params); - unsubscribe = bus.subscribe((event) => { - if (closed || !listenFilterAccepts(honored, event)) return; - const note = stampSubscriptionId(serverEventToNotification(event), subscriptionId); - writeNotification(note.method, note.params); - }); - keepAliveTimer = mcp_DXXb3Vv3_armSseKeepAlive(keepAliveMs, () => writeFrame(": keepalive\n\n")); - open.add(teardown); - }, - cancel() { - teardown(false); - } - }); - if (signal !== void 0) if (signal.aborted) teardown(false); - else { - const onAbort = () => teardown(false); - signal.addEventListener("abort", onAbort, { once: true }); - abortCleanup = () => signal.removeEventListener("abort", onAbort); - } - return new Response(readable, { - status: 200, - headers: { - "Content-Type": "text/event-stream", - "Cache-Control": "no-cache, no-transform", - Connection: "keep-alive", - "X-Accel-Buffering": "no" - } - }); - } - return { - serve, - closeAll() { - for (const teardown of open) teardown(true); - }, - get openCount() { - return open.size; - } - }; -} -const CHANGE_NOTIFICATION_METHODS = new Set([ - "notifications/tools/list_changed", - "notifications/prompts/list_changed", - "notifications/resources/list_changed", - "notifications/resources/updated" -]); -/** -* Per-connection listen state for the stdio entry. One instance is held by -* `serveStdio` for the connection lifetime; it routes inbound -* `subscriptions/listen` / `notifications/cancelled` and rewrites outbound -* change notifications onto the active subscriptions. No bus — the long-lived -* pinned instance's existing `send*ListChanged()` calls feed straight into -* `routeOutbound()`. -*/ -var mcp_DXXb3Vv3_StdioListenRouter = class { - /** Active subscriptions, keyed by the listen request's JSON-RPC id verbatim. */ - _subs = /* @__PURE__ */ new Map(); - /** - * The serving instance's declared capabilities. Filled in by the entry - * once the modern instance is constructed (the router is created before - * the instance exists), so the acknowledged filter is narrowed against - * what the server can actually deliver. - */ - _serverCapabilities; - /** - * The serving instance's identity, stamped onto the graceful-close - * results' `_meta` (the spec's `SubscriptionsListenResultMeta` extends - * `ResultMetaObject`). Handed over together with the capabilities. - */ - _serverInfo; - constructor(_maxSubscriptions = mcp_DXXb3Vv3_DEFAULT_MAX_SUBSCRIPTIONS, serverCapabilities, serverInfo) { - this._maxSubscriptions = _maxSubscriptions; - this._serverCapabilities = serverCapabilities; - this._serverInfo = serverInfo; - } - /** - * Record the serving instance's declared capabilities and identity once - * it has been constructed. Called by `serveStdio`'s connect path; - * subsequent `serve()` calls narrow the honored filter against the - * capabilities, and `teardownAll()` stamps the identity. - */ - setServerCapabilities(capabilities, serverInfo) { - this._serverCapabilities = capabilities; - if (serverInfo !== void 0) this._serverInfo = serverInfo; - } - /** Whether `id` is an active listen subscription on this connection. */ - has(id) { - return this._subs.has(id); - } - /** - * Serve one inbound `subscriptions/listen` request: registers the - * subscription and returns the stamped acknowledged notification (or, on - * capacity / params rejection, the in-band JSON-RPC error response). - * - * @throws when called before {@linkcode setServerCapabilities} (or the - * constructor) has supplied the serving instance's capabilities. Honoring a - * filter without knowing the server's advertised capabilities would fail - * open (deliver unadvertised types); the entry guarantees capabilities are - * set before any listen request is routed here. - */ - serve(message) { - if (this._serverCapabilities === void 0) throw new Error("StdioListenRouter.serve() called before setServerCapabilities(); refusing to honor a filter without capabilities"); - if (this._subs.size >= this._maxSubscriptions) return { - jsonrpc: "2.0", - id: message.id, - error: { - code: -32603, - message: "Subscription limit reached" - } - }; - const filter = parseListenFilter(message); - if (filter === void 0) return { - jsonrpc: "2.0", - id: message.id, - error: { - code: -32602, - message: "Invalid params: 'notifications' is required and must be a valid SubscriptionFilter" - } - }; - const honored = honoredSubset(filter, this._serverCapabilities); - this._subs.set(message.id, honored); - return stampSubscriptionId({ - method: "notifications/subscriptions/acknowledged", - params: { notifications: honored } - }, message.id); - } - /** - * Tear down one subscription (inbound `notifications/cancelled`). Returns - * `true` when a subscription was removed. After this call NOTHING further - * is delivered for that subscription id (the post-cancel hardening). - */ - cancel(id) { - return this._subs.delete(id); - } - /** - * Route an outbound notification through the active subscriptions. - * - * - For a subscription-gated change notification, returns one stamped copy - * per subscription that opted in to it (an empty array means it is - * dropped — the modern era never delivers an un-requested change type). - * - For any other outbound message, returns `'passthrough'` (the entry - * forwards it as-is). - */ - routeOutbound(message) { - if (!CHANGE_NOTIFICATION_METHODS.has(message.method)) return "passthrough"; - const uriParam = message.params?.["uri"]; - const uri = typeof uriParam === "string" ? uriParam : void 0; - const event = notificationToServerEvent(message.method, uri); - const out = []; - for (const [subscriptionId, filter] of this._subs) if (listenFilterAccepts(filter, event)) out.push(stampSubscriptionId({ - method: message.method, - params: message.params ?? {} - }, subscriptionId)); - return out; - } - /** - * Server-side graceful teardown of every active subscription: returns the - * empty `subscriptions/listen` JSON-RPC result for each subscription id — - * the spec's graceful-close signal, `_meta` carrying the subscription id - * and the serving instance's identity — for the entry to emit before - * closing the wire. Clears the set so nothing further is delivered. - */ - teardownAll() { - const out = []; - for (const id of this._subs.keys()) out.push({ - jsonrpc: "2.0", - id, - result: { - resultType: "complete", - _meta: { - [SUBSCRIPTION_ID_META_KEY]: id, - ...this._serverInfo !== void 0 && { [SERVER_INFO_META_KEY]: this._serverInfo } - } - } - }); - this._subs.clear(); - return out; - } -}; -function notificationToServerEvent(method, uri) { - switch (method) { - case "notifications/tools/list_changed": return { kind: "tools_list_changed" }; - case "notifications/prompts/list_changed": return { kind: "prompts_list_changed" }; - case "notifications/resources/list_changed": return { kind: "resources_list_changed" }; - default: return { - kind: "resource_updated", - uri: uri ?? "" - }; - } -} - -//#endregion -//#region src/server/legacyInputRequiredShim.ts -/** -* Default handler re-entries per originating request — tighter than the -* client driver's 10 because the shim holds a live wire request open. -*/ -const DEFAULT_LEGACY_SHIM_MAX_ROUNDS = 8; -/** Default per-leg timeout: legs are human-paced, so the 60s protocol default is wrong. */ -const DEFAULT_LEGACY_SHIM_ROUND_TIMEOUT_MS = 6e5; -/** Resolves and validates `ServerOptions.inputRequired`, failing loudly at construction time. */ -function resolveLegacyShimOptions(options) { - if (options?.maxRounds !== void 0 && (!Number.isInteger(options.maxRounds) || options.maxRounds < 1)) throw new RangeError(`inputRequired.maxRounds must be a positive integer (got ${options.maxRounds})`); - if (options?.roundTimeoutMs !== void 0 && (!Number.isFinite(options.roundTimeoutMs) || options.roundTimeoutMs <= 0)) throw new RangeError(`inputRequired.roundTimeoutMs must be a positive number (got ${options.roundTimeoutMs})`); - return { - maxRounds: options?.maxRounds ?? DEFAULT_LEGACY_SHIM_MAX_ROUNDS, - roundTimeoutMs: options?.roundTimeoutMs ?? DEFAULT_LEGACY_SHIM_ROUND_TIMEOUT_MS, - legacyShim: options?.legacyShim ?? true - }; -} -/** -* Validates one `inputRequests` entry: malformed or unknown kinds are server -* bugs and fail loudly on both eras. Shared by the modern seam's capability -* check and the shim's gate. -*/ -function coerceEmbeddedInputRequest(method, key, entry) { - if (entry === null || typeof entry !== "object" || typeof entry.method !== "string") throw new src_CX2iR2pK_ProtocolError(src_CX2iR2pK_ProtocolErrorCode.InternalError, `Handler for ${method} returned an invalid input request '${key}': each inputRequests entry must be an embedded elicitation/create, sampling/createMessage, or roots/list request`); - const embedded = entry; - const required = requiredClientCapabilitiesForInputRequest(embedded); - if (required === void 0) throw new src_CX2iR2pK_ProtocolError(src_CX2iR2pK_ProtocolErrorCode.InternalError, `Handler for ${method} returned an input request '${key}' of kind '${embedded.method}', which is not an embedded request the 2026-07-28 revision defines`); - return { - embedded, - required - }; -} -/** -* The 2025-11-25 URL-mode wire shape requires an `elicitationId`; the 2026 -* in-band shape has none, so URL legs mint one (CSPRNG-backed, with a -* getRandomValues fallback for runtimes without `randomUUID`). -*/ -function syntheticElicitationId() { - const webCrypto = globalThis.crypto; - if (webCrypto?.randomUUID !== void 0) return webCrypto.randomUUID(); - const bytes = new Uint8Array(16); - webCrypto.getRandomValues(bytes); - bytes[6] = bytes[6] & 15 | 64; - bytes[8] = bytes[8] & 63 | 128; - const hex = [...bytes].map((byte) => byte.toString(16).padStart(2, "0")).join(""); - return `${hex.slice(0, 8)}-${hex.slice(8, 12)}-${hex.slice(12, 16)}-${hex.slice(16, 20)}-${hex.slice(20)}`; -} -/** Per-family surfacing: tools/call → isError result (the 2025 idiom); prompts/resources → JSON-RPC error. */ -function legacyShimFailure(method, message) { - if (method === "tools/call") return { - content: [{ - type: "text", - text: message - }], - isError: true - }; - throw new src_CX2iR2pK_ProtocolError(src_CX2iR2pK_ProtocolErrorCode.InternalError, message); -} -/** The fulfilment loop — see the module doc for the contract. */ -var LegacyInputRequiredShim = class { - constructor(_host) { - this._host = _host; - } - async fulfill(method, handler, request, ctx, firstResult) { - const { maxRounds, roundTimeoutMs } = this._host; - const outerSignal = ctx.mcpReq.signal; - let current = firstResult; - let round = 0; - while (true) { - round += 1; - if (round > maxRounds) return legacyShimFailure(method, inputRequiredRoundsExceededMessage(method, maxRounds)); - const inputRequests = current.inputRequests; - const hasInputRequests = inputRequests != null && Object.keys(inputRequests).length > 0; - const requestState = typeof current.requestState === "string" ? current.requestState : void 0; - if (!hasInputRequests && requestState === void 0) throw new src_CX2iR2pK_ProtocolError(src_CX2iR2pK_ProtocolErrorCode.InternalError, `Handler for ${method} returned an input-required result with neither inputRequests nor requestState (every InputRequiredResult must include at least one of the two)`); - let responses; - if (hasInputRequests) { - const declared = this._host.resolvedClientCapabilities(ctx); - const coerced = []; - for (const [key, entry] of Object.entries(inputRequests)) { - const { embedded, required } = coerceEmbeddedInputRequest(method, key, entry); - if (embedded.method !== "roots/list" && embedded.params === void 0) throw new src_CX2iR2pK_ProtocolError(src_CX2iR2pK_ProtocolErrorCode.InternalError, `Handler for ${method} returned an input request '${key}' of kind '${embedded.method}' without params`); - if (src_CX2iR2pK_missingClientCapabilities(required, declared) !== void 0) return legacyShimFailure(method, `Cannot request input '${key}' (${embedded.method}): the client on this 2025-era connection did not declare the required capability${declared === void 0 ? " (no client capabilities are available on this connection — per-request legacy serving cannot receive server-to-client requests)" : ""}`); - coerced.push([key, embedded]); - } - const roundAbort = linkedRoundAbort(outerSignal); - try { - const legOptions = { - relatedRequestId: ctx.mcpReq.id, - timeout: roundTimeoutMs, - resetTimeoutOnProgress: true, - onprogress: () => {}, - signal: roundAbort.signal - }; - const fulfilled = await Promise.all(coerced.map(async ([key, embedded]) => { - try { - return [key, await this._dispatchLeg(embedded, legOptions)]; - } catch (error) { - roundAbort.abort(error); - throw error; - } - })); - responses = Object.fromEntries(fulfilled); - } catch (error) { - if (outerSignal.aborted) throw error; - return legacyShimFailure(method, `Fulfilling input required by '${method}' failed: ${error instanceof Error ? error.message : String(error)}`); - } finally { - roundAbort.dispose(); - } - } else await sleep((/* inlined export .C */250), outerSignal); - let ctxNext = { - ...ctx, - mcpReq: { - ...ctx.mcpReq, - inputResponses: responses, - droppedInputResponseKeys: void 0, - requestState: requestStateAccessor(requestState) - } - }; - if (requestState !== void 0) { - const decoded = await this._host.verifyRequestState(requestState, ctxNext, method); - if (decoded !== void 0) ctxNext = withRequestStateValue(ctxNext, decoded); - } - const next = await handler(request, ctxNext); - if (!isInputRequiredResult(next)) return next; - current = next; - } - } - /** Routes one embedded request through the host's existing 2025-era senders (gate already ran). */ - async _dispatchLeg(embedded, options) { - switch (embedded.method) { - case "elicitation/create": { - let params = embedded.params; - if (params.mode === "url" && params.elicitationId === void 0) params = { - ...params, - elicitationId: syntheticElicitationId() - }; - return await this._host.sendElicitation(params, options); - } - case "sampling/createMessage": return await this._host.sendSampling(embedded.params, options); - case "roots/list": return await this._host.listRoots(embedded.params, options); - } - } -}; - -//#endregion -//#region src/server/server.ts -/** -* The request methods whose 2026-07-28 result vocabulary includes -* `input_required` (the multi round-trip methods). Returning an -* input-required result from any other handler is a server bug. -*/ -const INPUT_REQUIRED_CAPABLE_METHODS = new Set([ - "tools/call", - "prompts/get", - "resources/read" -]); -let writeClientIdentity; -let installDiscoverHandler; -let readServerIdentity; -/** -* Package-internal: backfills the connection-scoped client-identity fields of a -* per-request server instance from the request's validated `_meta` envelope, so the -* (deprecated) {@linkcode Server.getClientCapabilities} / {@linkcode Server.getClientVersion} -* accessors keep answering on instances that never see an `initialize` handshake. -* Not public API. -*/ -function mcp_DXXb3Vv3_seedClientIdentityFromEnvelope(server, identity) { - writeClientIdentity(server, identity); -} -/** -* Package-internal: installs the modern-only `server/discover` handler on an instance -* the HTTP entry has marked as serving the 2026-07-28 era, and makes sure the modern -* revisions the entry serves appear in the instance's supported-versions list (so the -* discover advertisement and version-mismatch errors name them). Idempotent. -* Hand-constructed instances are unaffected: nothing else calls this, so they keep -* answering `-32601` unless their own supported-versions list opts into a modern -* revision. Not public API. -*/ -function mcp_DXXb3Vv3_installModernOnlyHandlers(server, servedModernVersions) { - installDiscoverHandler(server, servedModernVersions); -} -/** -* Package-internal: the instance's implementation identity, for the serving -* entries to stamp onto entry-built results (the `subscriptions/listen` -* graceful-close result — built outside the encode seam, but the spec's -* `SubscriptionsListenResultMeta` extends `ResultMetaObject`, so it carries -* the serverInfo SHOULD like every other result). Not public API. -*/ -function mcp_DXXb3Vv3_serverIdentityOf(server) { - return readServerIdentity(server); -} -/** -* An MCP server on top of a pluggable transport. -* -* This server will automatically respond to the initialization flow as initiated from the client. -* -* @deprecated Use {@linkcode server/mcp.McpServer | McpServer} instead for the high-level API. Only use `Server` for advanced use cases. -*/ -var Server = class extends Protocol { - _clientCapabilities; - _clientVersion; - static { - writeClientIdentity = (server, identity) => { - if (identity.clientCapabilities !== void 0) server._clientCapabilities = identity.clientCapabilities; - if (identity.clientInfo !== void 0) server._clientVersion = identity.clientInfo; - }; - installDiscoverHandler = (server, servedModernVersions) => { - const missing = servedModernVersions.filter((version) => !server._supportedProtocolVersions.includes(version)); - if (missing.length > 0) server._supportedProtocolVersions = [...server._supportedProtocolVersions, ...missing]; - server.setRequestHandler("server/discover", () => server._ondiscover()); - }; - readServerIdentity = (server) => server._serverInfo; - } - _capabilities; - _instructions; - _jsonSchemaValidator; - _cacheHints; - _requestStateVerify; - _inputRequiredServing; - _legacyShim; - /** Lazily-built legacy shim; the loop lives in legacyInputRequiredShim.ts behind a narrow host contract. */ - _legacyInputRequiredShim() { - return this._legacyShim ??= new LegacyInputRequiredShim({ - maxRounds: this._inputRequiredServing.maxRounds, - roundTimeoutMs: this._inputRequiredServing.roundTimeoutMs, - resolvedClientCapabilities: (ctx) => this._inputRequestCapabilityView(ctx), - verifyRequestState: (state, ctx, method) => this._verifyRequestState(state, ctx, method), - sendElicitation: (params, options) => this._sendElicitationLeg(params, options, { validateAcceptedContent: false }), - sendSampling: (params, options) => this.createMessage(params, options), - listRoots: (params, options) => this.listRoots(params, options) - }); - } - /** - * Callback for when initialization has fully completed (i.e., the client has sent an `notifications/initialized` notification). - */ - oninitialized; - /** - * Initializes this server with the given name and version information. - */ - constructor(_serverInfo, options) { - super(options); - this._serverInfo = _serverInfo; - this._capabilities = options?.capabilities ? { ...options.capabilities } : {}; - this._instructions = options?.instructions; - this._jsonSchemaValidator = options?.jsonSchemaValidator ?? new AjvJsonSchemaValidator(); - this._requestStateVerify = options?.requestState?.verify; - this._inputRequiredServing = resolveLegacyShimOptions(options?.inputRequired); - if (options?.cacheHints !== void 0) { - for (const [operation, hint] of Object.entries(options.cacheHints)) if (hint !== void 0) assertValidCacheHint(hint, `cacheHints['${operation}']`); - this._cacheHints = options.cacheHints; - } - this.setRequestHandler("initialize", (request) => this._oninitialize(request)); - this.setNotificationHandler("notifications/initialized", () => this.oninitialized?.()); - if (modernProtocolVersions(this._supportedProtocolVersions).length > 0) this.setRequestHandler("server/discover", () => this._ondiscover()); - if (this._capabilities.logging) this._registerLoggingHandler(); - } - /** - * Registers the built-in `logging/setLevel` request handler. - * - * @deprecated Deprecated as of protocol version 2026-07-28 (SEP-2577). - * Remains functional during the deprecation window (at least twelve months). - * Migrate to stderr logging (STDIO servers) or OpenTelemetry. - */ - _registerLoggingHandler() { - this.setRequestHandler("logging/setLevel", async (request, ctx) => { - const transportSessionId = ctx.sessionId || ctx.http?.req?.headers.get("mcp-session-id") || void 0; - const { level } = request.params; - const parseResult = parseSchema(LoggingLevelSchema, level); - if (parseResult.success) this._loggingLevels.set(transportSessionId, parseResult.data); - return {}; - }); - } - buildContext(ctx, transportInfo) { - const hasHttpInfo = ctx.http || transportInfo?.request || transportInfo?.closeSSEStream || transportInfo?.closeStandaloneSSEStream; - return { - ...ctx, - mcpReq: { - ...ctx.mcpReq, - log: (level, data, logger) => { - if (!this._capabilities.logging) return Promise.resolve(); - let threshold; - if (this._servedModernEra()) { - threshold = ctx.mcpReq.envelope?.[LOG_LEVEL_META_KEY]; - if (threshold === void 0) return Promise.resolve(); - } else threshold = this._loggingLevels.get(ctx.sessionId) ?? this._loggingLevels.get(void 0); - if (threshold !== void 0 && this.LOG_LEVEL_SEVERITY.get(level) < this.LOG_LEVEL_SEVERITY.get(threshold)) return Promise.resolve(); - return ctx.mcpReq.notify({ - method: "notifications/message", - params: { - level, - data, - logger - } - }); - }, - elicitInput: (params, options) => this.elicitInput(params, options), - requestSampling: (params, options) => this.createMessage(params, options) - }, - http: hasHttpInfo ? { - ...ctx.http, - req: transportInfo?.request, - closeSSE: transportInfo?.closeSSEStream, - closeStandaloneSSE: transportInfo?.closeStandaloneSSEStream - } : void 0 - }; - } - _loggingLevels = /* @__PURE__ */ new Map(); - LOG_LEVEL_SEVERITY = new Map(LoggingLevelSchema.options.map((level, index) => [level, index])); - isMessageIgnored = (level, sessionId) => { - const currentLevel = this._loggingLevels.get(sessionId); - return currentLevel ? this.LOG_LEVEL_SEVERITY.get(level) < this.LOG_LEVEL_SEVERITY.get(currentLevel) : false; - }; - /** - * Registers new capabilities. This can only be called before connecting to a transport. - * - * The new capabilities will be merged with any existing capabilities previously given (e.g., at initialization). - */ - registerCapabilities(capabilities) { - if (this.transport) throw new src_CX2iR2pK_SdkError(src_CX2iR2pK_SdkErrorCode.AlreadyConnected, "Cannot register capabilities after connecting to transport"); - const hadLogging = !!this._capabilities.logging; - this._capabilities = mergeCapabilities(this._capabilities, capabilities); - if (!hadLogging && this._capabilities.logging) this._registerLoggingHandler(); - } - /** - * Enforces server-side validation for `tools/call` results regardless of how the - * handler was registered, attaches the configured per-operation cache hint - * (when one exists) so the 2026-07-28 encode seam can fill `ttlMs`/`cacheScope` - * for results that do not provide their own, and owns the multi-round-trip - * seam: on the methods whose 2026-07-28 result vocabulary includes - * `input_required` (`tools/call`, `prompts/get`, `resources/read`) an - * input-required return skips result-schema validation and is checked - * against the served era, the at-least-one rule, and the request's own - * declared client capabilities; on every other method an input-required - * return is a server bug and fails loudly. The hint rides a symbol-keyed - * property that is never serialized, so 2025-era responses are unaffected. - */ - _wrapHandler(method, handler) { - if (method !== "tools/call") { - const cacheHint = this._cacheHints?.[method]; - const isInputRequiredCapable = INPUT_REQUIRED_CAPABLE_METHODS.has(method); - if (cacheHint === void 0 && !isInputRequiredCapable) return async (request, ctx) => { - const result = await handler(request, ctx); - if (isInputRequiredResult(result)) throw new src_CX2iR2pK_ProtocolError(src_CX2iR2pK_ProtocolErrorCode.InternalError, `Handler for ${method} returned an input-required result, but only tools/call, prompts/get and resources/read support input_required (protocol revision 2026-07-28)`); - return result; - }; - return async (request, ctx) => { - const result = isInputRequiredCapable ? await this._invokeInputRequiredCapableHandler(method, handler, request, ctx) : await handler(request, ctx); - if (isInputRequiredResult(result)) { - if (!isInputRequiredCapable) throw new src_CX2iR2pK_ProtocolError(src_CX2iR2pK_ProtocolErrorCode.InternalError, `Handler for ${method} returned an input-required result, but only tools/call, prompts/get and resources/read support input_required (protocol revision 2026-07-28)`); - return result; - } - return cacheHint === void 0 ? result : attachCacheHintFallback(result, cacheHint); - }; - } - return async (request, ctx) => { - const codec = src_CX2iR2pK_codecForVersion(this._negotiatedProtocolVersion); - const validatedRequest = codec.validateRequest("tools/call", request); - if (!validatedRequest.ok) throw new src_CX2iR2pK_ProtocolError(validatedRequest.reason === "not-in-era" ? src_CX2iR2pK_ProtocolErrorCode.InternalError : src_CX2iR2pK_ProtocolErrorCode.InvalidParams, validatedRequest.reason === "not-in-era" ? "No wire schema for tools/call in the resolved era" : `Invalid tools/call request: ${validatedRequest.message}`); - const result = await this._invokeInputRequiredCapableHandler("tools/call", handler, request, ctx); - if (isInputRequiredResult(result)) return result; - const normalizedResult = normalizeContentlessToolResult(result); - const validationResult = codec.validateResult("tools/call", normalizedResult); - if (!validationResult.ok) throw new src_CX2iR2pK_ProtocolError(validationResult.reason === "not-in-era" ? src_CX2iR2pK_ProtocolErrorCode.InternalError : src_CX2iR2pK_ProtocolErrorCode.InvalidParams, validationResult.reason === "not-in-era" ? "No wire schema for tools/call in the resolved era" : `Invalid tools/call result: ${validationResult.message}`); - return validationResult.value; - }; - } - /** - * Whether this instance is bound to a 2026-07-28-or-later protocol - * revision. Era is instance state — a serving entry (`createMcpHandler`, - * `serveStdio`) marks the instance modern at construction; a 2025-era - * `initialize` handshake binds it legacy. The multi-round-trip seam reads - * this directly: there is no per-request era consult. - */ - _servedModernEra() { - return this._negotiatedProtocolVersion !== void 0 && isModernProtocolVersion(this._negotiatedProtocolVersion); - } - /** - * Invokes a handler for one of the multi-round-trip methods and applies - * the input-required seam: - * - * - a `UrlElicitationRequiredError` (or any 2025-style server→client - * request idiom) escaping the handler on a request served on the - * 2026-07-28 era fails LOUDLY with a clear steer to - * `inputRequired.elicitUrl(...)` — the `-32042` error never reaches the - * 2026-07-28 wire and the throw is not silently converted. Requests - * served on the 2025 era keep today's `-32042` behavior byte-exact (the - * error is rethrown unchanged). - * - an input-required RETURN toward a 2026-07-28 request must satisfy - * the at-least-one rule, and every embedded request must be covered by - * the capabilities declared on the request's envelope (violations - * answer the typed `-32021` error). Toward a 2025-era request the - * return is fulfilled by the default-on legacy shim, whose own gate - * consults the initialize-declared capabilities and surfaces - * violations per family; `inputRequired.legacyShim: false` restores - * the pre-shim loud failure. - */ - async _invokeInputRequiredCapableHandler(method, handler, request, ctx) { - const servedModern = this._servedModernEra(); - const rawRequestState = ctx.mcpReq.requestState(); - if (rawRequestState !== void 0 && typeof rawRequestState !== "string") throw new src_CX2iR2pK_ProtocolError(src_CX2iR2pK_ProtocolErrorCode.InvalidParams, "Invalid or expired requestState", { reason: "invalid_request_state" }); - let ctxForHandler = ctx; - if (typeof rawRequestState === "string") { - const decoded = await this._verifyRequestState(rawRequestState, ctx, method); - if (decoded !== void 0) ctxForHandler = withRequestStateValue(ctx, decoded); - } - let result; - try { - result = await handler(request, ctxForHandler); - } catch (error) { - if (error instanceof src_CX2iR2pK_ProtocolError && error.code === src_CX2iR2pK_ProtocolErrorCode.UrlElicitationRequired) { - if (!servedModern) throw error; - throw new src_CX2iR2pK_ProtocolError(src_CX2iR2pK_ProtocolErrorCode.InternalError, `URL elicitation cannot be signalled by throwing UrlElicitationRequiredError on protocol revision ${this._negotiatedProtocolVersion}: return inputRequired({ inputRequests: { …: inputRequired.elicitUrl(...) } }) from the handler instead. The urlElicitationRequired error (-32042) of earlier revisions is not available on this revision.`); - } - throw error; - } - if (!isInputRequiredResult(result)) return result; - if (!servedModern) { - if (!this._inputRequiredServing.legacyShim) throw new src_CX2iR2pK_ProtocolError(src_CX2iR2pK_ProtocolErrorCode.InternalError, `Handler for ${method} returned an input-required result, but this request is served on protocol revision ${this._negotiatedProtocolVersion ?? LATEST_PROTOCOL_VERSION}, which has no input_required vocabulary`); - return await this._legacyInputRequiredShim().fulfill(method, handler, request, ctxForHandler, result); - } - const inputRequests = result.inputRequests; - const hasInputRequests = inputRequests != null && Object.keys(inputRequests).length > 0; - const hasRequestState = typeof result.requestState === "string"; - if (!hasInputRequests && !hasRequestState) throw new src_CX2iR2pK_ProtocolError(src_CX2iR2pK_ProtocolErrorCode.InternalError, `Handler for ${method} returned an input-required result with neither inputRequests nor requestState (every InputRequiredResult must include at least one of the two)`); - if (hasInputRequests) { - const declared = this._inputRequestCapabilityView(ctx); - for (const [key, entry] of Object.entries(inputRequests)) { - const { embedded, required } = coerceEmbeddedInputRequest(method, key, entry); - const missing = src_CX2iR2pK_missingClientCapabilities(required, declared); - if (missing !== void 0) throw new src_CX2iR2pK_MissingRequiredClientCapabilityError({ requiredCapabilities: missing }, `Cannot request input '${key}' (${embedded.method}): the request's client capabilities do not declare the required capability`); - } - } - return result; - } - /** - * Runs the configured `requestState.verify` hook and returns its - * resolved value (`undefined` when unconfigured or the hook returns - * nothing). Deny-on-error: any hook failure answers the frozen `-32602`; - * the reason goes to `onerror` only. - */ - async _verifyRequestState(state, ctx, method) { - if (this._requestStateVerify === void 0) return; - try { - return await this._requestStateVerify(state, ctx); - } catch (error) { - this.onerror?.(/* @__PURE__ */ new Error(`requestState verification rejected ${method}: ${error instanceof Error ? error.message : String(error)}`)); - throw new src_CX2iR2pK_ProtocolError(src_CX2iR2pK_ProtocolErrorCode.InvalidParams, "Invalid or expired requestState", { reason: "invalid_request_state" }); - } - } - /** - * The per-request resolved client-capabilities view: the request's own - * `_meta` envelope on the 2026 era; the `initialize`-declared state on a - * 2025-era connection. Per-request instances that never saw an - * initialize (stateless legacy) hold nothing, so gates refuse there. - */ - _inputRequestCapabilityView(ctx) { - return this._servedModernEra() ? ctx.mcpReq.envelope?.[auth_CUe6YdwF_CLIENT_CAPABILITIES_META_KEY] : this._clientCapabilities; - } - /** - * Guard for the push-style server→client request APIs ({@linkcode createMessage}, - * {@linkcode elicitInput}, {@linkcode listRoots}, {@linkcode ping}) on a - * modern-era instance: the 2026-07-28 revision has no server→client request - * channel, so the call fails before any wire traffic with a typed error - * whose message steers to `inputRequired(...)`. The base era gate would - * also reject it; this guard runs first to carry the steer. - */ - _assertPushApiInServedEra(method) { - if (this._servedModernEra()) throw new src_CX2iR2pK_SdkError(src_CX2iR2pK_SdkErrorCode.MethodNotSupportedByProtocolVersion, `Server-to-client requests are not available on protocol revision ${this._negotiatedProtocolVersion}: '${method}' cannot be sent while serving a request on that revision. Return inputRequired({ ... }) from the handler instead — the client fulfils the embedded requests and retries the original request (multi round-trip requests).`, { - method, - era: "2026-07-28" - }); - } - assertCapabilityForMethod(method) { - switch (method) { - case "sampling/createMessage": - if (!this._clientCapabilities?.sampling) throw new src_CX2iR2pK_SdkError(src_CX2iR2pK_SdkErrorCode.CapabilityNotSupported, `Client does not support sampling (required for ${method})`); - break; - case "elicitation/create": - if (!this._clientCapabilities?.elicitation) throw new src_CX2iR2pK_SdkError(src_CX2iR2pK_SdkErrorCode.CapabilityNotSupported, `Client does not support elicitation (required for ${method})`); - break; - case "roots/list": - if (!this._clientCapabilities?.roots) throw new src_CX2iR2pK_SdkError(src_CX2iR2pK_SdkErrorCode.CapabilityNotSupported, `Client does not support listing roots (required for ${method})`); - break; - case "ping": break; - } - } - assertNotificationCapability(method) { - switch (method) { - case "notifications/message": - if (!this._capabilities.logging) throw new src_CX2iR2pK_SdkError(src_CX2iR2pK_SdkErrorCode.CapabilityNotSupported, `Server does not support logging (required for ${method})`); - break; - case "notifications/resources/updated": - case "notifications/resources/list_changed": - if (!this._capabilities.resources) throw new src_CX2iR2pK_SdkError(src_CX2iR2pK_SdkErrorCode.CapabilityNotSupported, `Server does not support notifying about resources (required for ${method})`); - break; - case "notifications/tools/list_changed": - if (!this._capabilities.tools) throw new src_CX2iR2pK_SdkError(src_CX2iR2pK_SdkErrorCode.CapabilityNotSupported, `Server does not support notifying of tool list changes (required for ${method})`); - break; - case "notifications/prompts/list_changed": - if (!this._capabilities.prompts) throw new src_CX2iR2pK_SdkError(src_CX2iR2pK_SdkErrorCode.CapabilityNotSupported, `Server does not support notifying of prompt list changes (required for ${method})`); - break; - case "notifications/elicitation/complete": - if (!this._clientCapabilities?.elicitation?.url) throw new src_CX2iR2pK_SdkError(src_CX2iR2pK_SdkErrorCode.CapabilityNotSupported, `Client does not support URL elicitation (required for ${method})`); - break; - case "notifications/cancelled": break; - case "notifications/progress": break; - } - } - assertRequestHandlerCapability(method) { - switch (method) { - case "completion/complete": - if (!this._capabilities.completions) throw new src_CX2iR2pK_SdkError(src_CX2iR2pK_SdkErrorCode.CapabilityNotSupported, `Server does not support completions (required for ${method})`); - break; - case "logging/setLevel": - if (!this._capabilities.logging) throw new src_CX2iR2pK_SdkError(src_CX2iR2pK_SdkErrorCode.CapabilityNotSupported, `Server does not support logging (required for ${method})`); - break; - case "prompts/get": - case "prompts/list": - if (!this._capabilities.prompts) throw new src_CX2iR2pK_SdkError(src_CX2iR2pK_SdkErrorCode.CapabilityNotSupported, `Server does not support prompts (required for ${method})`); - break; - case "resources/list": - case "resources/templates/list": - case "resources/read": - if (!this._capabilities.resources) throw new src_CX2iR2pK_SdkError(src_CX2iR2pK_SdkErrorCode.CapabilityNotSupported, `Server does not support resources (required for ${method})`); - break; - case "tools/call": - case "tools/list": - if (!this._capabilities.tools) throw new src_CX2iR2pK_SdkError(src_CX2iR2pK_SdkErrorCode.CapabilityNotSupported, `Server does not support tools (required for ${method})`); - break; - case "ping": - case "initialize": break; - } - } - async _oninitialize(request) { - const requestedVersion = request.params.protocolVersion; - this._clientCapabilities = request.params.capabilities; - this._clientVersion = request.params.clientInfo; - const legacyVersions = legacyProtocolVersions(this._supportedProtocolVersions); - const protocolVersion = legacyVersions.includes(requestedVersion) ? requestedVersion : legacyVersions[0] ?? LATEST_PROTOCOL_VERSION; - this._negotiatedProtocolVersion = protocolVersion; - this.transport?.setProtocolVersion?.(protocolVersion); - return { - protocolVersion, - capabilities: this.getCapabilities(), - serverInfo: this._serverInfo, - ...this._instructions && { instructions: this._instructions } - }; - } - /** - * Answers `server/discover` (protocol revision 2026-07-28). `supportedVersions` - * lists only modern revisions (2025-era versions are negotiated via `initialize`); - * the capabilities are advertised as-is, listChanged/subscribe bits included - * (see {@linkcode discoverAdvertisedCapabilities}). - */ - _ondiscover() { - return { - supportedVersions: modernProtocolVersions(this._supportedProtocolVersions), - capabilities: discoverAdvertisedCapabilities(this.getCapabilities()), - ...this._instructions && { instructions: this._instructions } - }; - } - /** - * The identity the 2026-era encode seam stamps into every outbound - * result's `_meta` under `io.modelcontextprotocol/serverInfo` (spec PR - * #3002: servers SHOULD identify themselves on every response). - */ - _outboundServerInfo() { - return this._serverInfo; - } - /** - * After initialization has completed, this will be populated with the client's reported capabilities. - * - * @deprecated Read client identity from the per-request handler context instead: on - * 2026-07-28 (per-request envelope) requests `ctx.mcpReq.envelope` carries the client's - * declared capabilities, while on 2025-era connections this accessor keeps returning the - * `initialize`-scoped value. The accessor remains functional — instances serving the - * 2026-07-28 era are backfilled per request from the validated envelope. - */ - getClientCapabilities() { - return this._clientCapabilities; - } - /** - * After initialization has completed, this will be populated with information about the client's name and version. - * - * @deprecated Read client identity from the per-request handler context instead: on - * 2026-07-28 (per-request envelope) requests `ctx.mcpReq.envelope` carries the client's - * name and version, while on 2025-era connections this accessor keeps returning the - * `initialize`-scoped value. The accessor remains functional — instances serving the - * 2026-07-28 era are backfilled per request from the validated envelope. - */ - getClientVersion() { - return this._clientVersion; - } - /** - * After initialization has completed, this will be populated with the protocol version negotiated - * with the client (the version the server responded with during the initialize handshake), or - * `undefined` before initialization. - * - * @deprecated Read the protocol revision from the per-request handler context instead: on - * 2026-07-28 (per-request envelope) requests `ctx.mcpReq.envelope` names the revision the - * request was sent for, while on 2025-era connections this accessor keeps returning the - * `initialize`-negotiated version. The accessor remains functional — instances serving the - * 2026-07-28 era report that revision. - */ - getNegotiatedProtocolVersion() { - return this._negotiatedProtocolVersion; - } - /** - * Project a `tools/call` result through this instance's negotiated wire - * codec — the era-agnostic SEP-2106 §4.3 TextContent auto-append, plus on - * the 2025 era the `{result:…}` wrap when `structuredContent` is a - * non-object value or the advertised `outputSchema` had a non-object root. - * Identity for object-shaped `structuredContent` on the 2026 era. - * - * `McpServer`'s built-in `tools/call` handler routes through this method. - * Low-level `setRequestHandler('tools/call', …)` authors call it - * themselves so the projection lives in one place (the codec) and the - * server-side handler stays era-blind. - * - * This is the only codec function exposed on `Server` — the full - * `WireCodec` is intentionally not part of the public surface. - */ - projectCallToolResult(result, advertisedOutputSchema) { - return this._wireCodec().projectCallToolResult(result, advertisedOutputSchema); - } - /** - * Returns the current server capabilities. - */ - getCapabilities() { - return this._capabilities; - } - /** - * Sends a `ping` request to the connected client. - * - * @deprecated The 2026-07-28 protocol removed ping; it throws on a 2026-07-28-era instance. - * If your factory serves both eras, this only works on the legacy path. - */ - async ping() { - this._assertPushApiInServedEra("ping"); - return this.request({ method: "ping" }); - } - async createMessage(params, options) { - this._assertPushApiInServedEra("sampling/createMessage"); - if ((params.tools || params.toolChoice) && !this._clientCapabilities?.sampling?.tools) throw new src_CX2iR2pK_SdkError(src_CX2iR2pK_SdkErrorCode.CapabilityNotSupported, "Client does not support sampling tools capability."); - if (params.messages.length > 0) { - const lastMessage = params.messages.at(-1); - const lastContent = Array.isArray(lastMessage.content) ? lastMessage.content : [lastMessage.content]; - const hasToolResults = lastContent.some((c) => c.type === "tool_result"); - const previousMessage = params.messages.length > 1 ? params.messages.at(-2) : void 0; - const previousContent = previousMessage ? Array.isArray(previousMessage.content) ? previousMessage.content : [previousMessage.content] : []; - const hasPreviousToolUse = previousContent.some((c) => c.type === "tool_use"); - if (hasToolResults) { - if (lastContent.some((c) => c.type !== "tool_result")) throw new src_CX2iR2pK_ProtocolError(src_CX2iR2pK_ProtocolErrorCode.InvalidParams, "The last message must contain only tool_result content if any is present"); - if (!hasPreviousToolUse) throw new src_CX2iR2pK_ProtocolError(src_CX2iR2pK_ProtocolErrorCode.InvalidParams, "tool_result blocks are not matching any tool_use from the previous message"); - } - if (hasPreviousToolUse) { - const toolUseIds = new Set(previousContent.filter((c) => c.type === "tool_use").map((c) => c.id)); - const toolResultIds = new Set(lastContent.filter((c) => c.type === "tool_result").map((c) => c.toolUseId)); - if (toolUseIds.size !== toolResultIds.size || ![...toolUseIds].every((id) => toolResultIds.has(id))) throw new src_CX2iR2pK_ProtocolError(src_CX2iR2pK_ProtocolErrorCode.InvalidParams, "ids of tool_result blocks and tool_use blocks from previous message do not match"); - } - } - const hasTools = Boolean(params.tools || params.toolChoice); - const wide = await this.request({ - method: "sampling/createMessage", - params - }, options); - const outcome = this._wireCodec().samplingResultVariant(hasTools, wide); - if (!outcome.ok) throw new src_CX2iR2pK_SdkError(src_CX2iR2pK_SdkErrorCode.InvalidResult, `Invalid sampling/createMessage result: ${outcome.reason === "invalid" ? outcome.message : outcome.reason}`); - return outcome.value; - } - /** - * Creates an elicitation request for the given parameters. - * For backwards compatibility, `mode` may be omitted for form requests and will default to `"form"`. - * @param params The parameters for the elicitation request. - * @param options Optional request options. - * @returns The result of the elicitation request. - * - * @deprecated Throws on a 2026-07-28-era request — use {@link index.inputRequired | inputRequired} (multi-round-trip) - * instead. The 2025 push-style server-to-client request model is replaced by input_required - * results in the 2026-07-28 protocol. If your factory serves both eras, this only works on the - * legacy path. - */ - async elicitInput(params, options) { - this._assertPushApiInServedEra("elicitation/create"); - switch (params.mode ?? "form") { - case "url": - if (!this._clientCapabilities?.elicitation?.url) throw new src_CX2iR2pK_SdkError(src_CX2iR2pK_SdkErrorCode.CapabilityNotSupported, "Client does not support url elicitation."); - break; - case "form": - if (!this._clientCapabilities?.elicitation?.form) throw new src_CX2iR2pK_SdkError(src_CX2iR2pK_SdkErrorCode.CapabilityNotSupported, "Client does not support form elicitation."); - break; - } - return this._sendElicitationLeg(params, options); - } - /** - * The capability-check-free core of {@linkcode elicitInput}. The shim - * uses it because its gate differs from the public checks: a bare - * `elicitation: {}` counts as form support (the pre-mode rule), and - * accepted content passes through unvalidated for parity with the - * modern client driver (handlers validate via the schema-aware - * `acceptedContent` overload and can re-ask). - */ - async _sendElicitationLeg(params, options, behavior) { - const mode = params.mode ?? "form"; - const validateAcceptedContent = behavior?.validateAcceptedContent ?? true; - switch (mode) { - case "url": { - const urlParams = params; - return this.request({ - method: "elicitation/create", - params: urlParams - }, options); - } - case "form": { - const formParams = params.mode === "form" ? params : { - ...params, - mode: "form" - }; - const result = await this.request({ - method: "elicitation/create", - params: formParams - }, options); - if (validateAcceptedContent && result.action === "accept" && result.content && formParams.requestedSchema) try { - const validationResult = this._jsonSchemaValidator.getValidator(formParams.requestedSchema)(result.content); - if (!validationResult.valid) throw new src_CX2iR2pK_ProtocolError(src_CX2iR2pK_ProtocolErrorCode.InvalidParams, `Elicitation response content does not match requested schema: ${validationResult.errorMessage}`); - } catch (error) { - if (error instanceof src_CX2iR2pK_ProtocolError) throw error; - throw new src_CX2iR2pK_ProtocolError(src_CX2iR2pK_ProtocolErrorCode.InternalError, `Error validating elicitation response: ${error instanceof Error ? error.message : String(error)}`); - } - return result; - } - } - } - /** - * Creates a reusable callback that, when invoked, will send a `notifications/elicitation/complete` - * notification for the specified elicitation ID. - * - * The notification (and the `elicitationId` it references) exists only on protocol revision - * 2025-11-25 — the 2026-07-28 revision removed both. On a connection negotiated at 2026-07-28 the - * returned callback rejects with a typed local error before anything reaches the transport - * (the method is not part of that revision's wire registry). - * - * @param elicitationId The ID of the elicitation to mark as complete. - * @param options Optional notification options. Useful when the completion notification should be related to a prior request. - * @returns A function that emits the completion notification when awaited. - */ - createElicitationCompletionNotifier(elicitationId, options) { - if (!this._clientCapabilities?.elicitation?.url) throw new src_CX2iR2pK_SdkError(src_CX2iR2pK_SdkErrorCode.CapabilityNotSupported, "Client does not support URL elicitation (required for notifications/elicitation/complete)"); - return () => this.notification({ - method: "notifications/elicitation/complete", - params: { elicitationId } - }, options); - } - /** - * Requests the list of roots from the client. - * - * @deprecated Deprecated as of protocol version 2026-07-28 (SEP-2577). - * Throws on a 2026-07-28-era request — use {@link index.inputRequired | inputRequired} (multi-round-trip) instead, - * or migrate to passing paths via tool parameters, resource URIs, or configuration. The 2025 - * push-style server-to-client request model is replaced by input_required results in the - * 2026-07-28 protocol. If your factory serves both eras, this only works on the legacy path. - */ - async listRoots(params, options) { - this._assertPushApiInServedEra("roots/list"); - return this.request({ - method: "roots/list", - params - }, options); - } - /** - * Sends a logging message to the client, if connected. - * Note: You only need to send the parameters object, not the entire JSON-RPC message. - * @see {@linkcode LoggingMessageNotification} - * @param params - * @param sessionId Optional for stateless transports and backward compatibility. - * - * @deprecated Deprecated as of protocol version 2026-07-28 (SEP-2577). - * Remains functional during the deprecation window (at least twelve months). - * Migrate to stderr logging (STDIO servers) or OpenTelemetry. - */ - async sendLoggingMessage(params, sessionId) { - if (this._capabilities.logging && !this.isMessageIgnored(params.level, sessionId)) return this.notification({ - method: "notifications/message", - params - }); - } - async sendResourceUpdated(params) { - return this.notification({ - method: "notifications/resources/updated", - params - }); - } - 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" }); - } -}; -/** -* The capability set a server advertises on `server/discover`. Pure — never -* mutates the input; the legacy `initialize` advertisement is untouched. -* -* The serving entries serve `subscriptions/listen` themselves, so the -* `listChanged` and `resources.subscribe` capability bits are advertised -* as-is: a modern-era client uses them to decide which notification types to -* request on its listen filter. -*/ -function discoverAdvertisedCapabilities(capabilities) { - return { ...capabilities }; -} - -//#endregion -//#region src/server/mcp.ts -/** -* High-level MCP server that provides a simpler API for working with resources, tools, and prompts. -* For advanced usage (like sending notifications or setting custom request handlers), use the underlying -* {@linkcode Server} instance available via the {@linkcode McpServer.server | server} property. -* -* @example -* ```ts source="./mcp.examples.ts#McpServer_basicUsage" -* const server = new McpServer({ -* name: 'my-server', -* version: '1.0.0' -* }); -* ``` -*/ -var mcp_DXXb3Vv3_McpServer = class { - /** - * The underlying {@linkcode Server} instance, useful for advanced operations like sending notifications. - */ - server; - _registeredResources = {}; - _registeredResourceTemplates = {}; - _registeredTools = {}; - _registeredPrompts = {}; - /** - * Per-tool JSON-converted `inputSchema`, memoized so the SEP-2243 - * registration-time scan and the pre-dispatch validation step share one - * conversion instead of paying it twice per request under the - * per-request-factory `createMcpHandler` model. - */ - _toolInputSchemaJson = {}; - /** - * The JSON-serialized `inputSchema` of a registered tool, or `undefined` - * when no such tool is registered. Used by the HTTP entry's pre-dispatch - * SEP-2243 `Mcp-Param-*` validation step (which needs the same JSON Schema - * `tools/list` would emit, before dispatch reaches the handler). - * - * @internal - */ - toolInputSchemaJson(name) { - const tool = this._registeredTools[name]; - if (tool === void 0 || !tool.enabled) return void 0; - if (Object.hasOwn(this._toolInputSchemaJson, name)) return this._toolInputSchemaJson[name]; - if (tool.inputSchema === void 0) return EMPTY_OBJECT_JSON_SCHEMA; - try { - const json = standardSchemaToJsonSchema(tool.inputSchema, "input"); - this._toolInputSchemaJson[name] = json; - return json; - } catch { - return; - } - } - constructor(serverInfo, options) { - this.server = new Server(serverInfo, options); - if (options?.capabilities?.tools) this.setToolRequestHandlers(); - if (options?.capabilities?.resources) this.setResourceRequestHandlers(); - if (options?.capabilities?.prompts) this.setPromptRequestHandlers(); - } - /** - * Attaches to the given transport, starts it, and starts listening for messages. - * - * The `server` object assumes ownership of the {@linkcode Transport}, replacing any callbacks that have already been set, and expects that it is the only user of the {@linkcode Transport} instance going forward. - * - * @example - * ```ts source="./mcp.examples.ts#McpServer_connect_stdio" - * const server = new McpServer({ name: 'my-server', version: '1.0.0' }); - * const transport = new StdioServerTransport(); - * await server.connect(transport); - * ``` - */ - async connect(transport) { - return await this.server.connect(transport); - } - /** - * Closes the connection. - */ - async close() { - await this.server.close(); - } - _toolHandlersInitialized = false; - setToolRequestHandlers() { - if (this._toolHandlersInitialized) return; - this.server.assertCanSetRequestHandler("tools/list"); - this.server.assertCanSetRequestHandler("tools/call"); - this.server.registerCapabilities({ tools: { listChanged: this.server.getCapabilities().tools?.listChanged ?? true } }); - this.server.setRequestHandler("tools/list", () => ({ tools: Object.entries(this._registeredTools).filter(([, tool]) => tool.enabled).map(([name, tool]) => { - const toolDefinition = { - name, - title: tool.title, - description: tool.description, - inputSchema: tool.inputSchema ? standardSchemaToJsonSchema(tool.inputSchema, "input") : EMPTY_OBJECT_JSON_SCHEMA, - annotations: tool.annotations, - icons: tool.icons, - execution: tool.execution, - _meta: tool._meta - }; - if (tool.outputSchema) toolDefinition.outputSchema = standardSchemaToJsonSchema(tool.outputSchema, "output"); - return toolDefinition; - }) })); - this.server.setRequestHandler("tools/call", async (request, ctx) => { - const tool = this._registeredTools[request.params.name]; - if (!tool) throw new src_CX2iR2pK_ProtocolError(src_CX2iR2pK_ProtocolErrorCode.InvalidParams, `Tool ${request.params.name} not found`); - if (!tool.enabled) throw new src_CX2iR2pK_ProtocolError(src_CX2iR2pK_ProtocolErrorCode.InvalidParams, `Tool ${request.params.name} disabled`); - try { - const args = await this.validateToolInput(tool, request.params.arguments, request.params.name); - const result = await this.executeToolHandler(tool, args, ctx); - await this.validateToolOutput(tool, result, request.params.name); - if (isInputRequiredResult(result)) return result; - return this.server.projectCallToolResult(result, tool.outputSchemaJson); - } catch (error) { - if (error instanceof src_CX2iR2pK_ProtocolError && error.code === src_CX2iR2pK_ProtocolErrorCode.UrlElicitationRequired) throw error; - return this.createToolError(error instanceof Error ? error.message : String(error)); - } - }); - this._toolHandlersInitialized = true; - } - /** - * Creates a tool error result. - * - * @param errorMessage - The error message. - * @returns The tool error result. - */ - createToolError(errorMessage) { - return { - content: [{ - type: "text", - text: errorMessage - }], - isError: true - }; - } - /** - * Validates tool input arguments against the tool's input schema. - */ - async validateToolInput(tool, args, toolName) { - if (!tool.inputSchema) return; - const parseResult = await validateStandardSchema(tool.inputSchema, args ?? {}); - if (!parseResult.success) throw new src_CX2iR2pK_ProtocolError(src_CX2iR2pK_ProtocolErrorCode.InvalidParams, `Input validation error: Invalid arguments for tool ${toolName}: ${parseResult.error}`); - return parseResult.data; - } - /** - * Validates tool output against the tool's output schema. - */ - async validateToolOutput(tool, result, toolName) { - if (!tool.outputSchema) return; - if (isInputRequiredResult(result)) return; - if (result.isError) return; - if (result.structuredContent === void 0) throw new src_CX2iR2pK_ProtocolError(src_CX2iR2pK_ProtocolErrorCode.InvalidParams, `Output validation error: Tool ${toolName} has an output schema but no structured content was provided`); - const parseResult = await validateStandardSchema(tool.outputSchema, result.structuredContent); - if (!parseResult.success) throw new src_CX2iR2pK_ProtocolError(src_CX2iR2pK_ProtocolErrorCode.InvalidParams, `Output validation error: Invalid structured content for tool ${toolName}: ${parseResult.error}`); - } - /** - * Executes a tool handler. - */ - async executeToolHandler(tool, args, ctx) { - return tool.executor(args, ctx); - } - _completionHandlerInitialized = false; - setCompletionRequestHandler() { - if (this._completionHandlerInitialized) return; - this.server.assertCanSetRequestHandler("completion/complete"); - this.server.registerCapabilities({ completions: {} }); - this.server.setRequestHandler("completion/complete", async (request) => { - switch (request.params.ref.type) { - case "ref/prompt": - assertCompleteRequestPrompt(request); - return this.handlePromptCompletion(request, request.params.ref); - case "ref/resource": - assertCompleteRequestResourceTemplate(request); - return this.handleResourceCompletion(request, request.params.ref); - default: throw new src_CX2iR2pK_ProtocolError(src_CX2iR2pK_ProtocolErrorCode.InvalidParams, `Invalid completion reference: ${request.params.ref}`); - } - }); - this._completionHandlerInitialized = true; - } - async handlePromptCompletion(request, ref) { - const prompt = this._registeredPrompts[ref.name]; - if (!prompt) throw new src_CX2iR2pK_ProtocolError(src_CX2iR2pK_ProtocolErrorCode.InvalidParams, `Prompt ${ref.name} not found`); - if (!prompt.enabled) throw new src_CX2iR2pK_ProtocolError(src_CX2iR2pK_ProtocolErrorCode.InvalidParams, `Prompt ${ref.name} disabled`); - if (!prompt.argsSchema) return EMPTY_COMPLETION_RESULT; - const field = unwrapOptionalSchema(getSchemaShape(prompt.argsSchema)?.[request.params.argument.name]); - if (!isCompletable(field)) return EMPTY_COMPLETION_RESULT; - const completer = getCompleter(field); - if (!completer) return EMPTY_COMPLETION_RESULT; - return createCompletionResult(await completer(request.params.argument.value, request.params.context)); - } - async handleResourceCompletion(request, ref) { - const template = Object.values(this._registeredResourceTemplates).find((t) => t.resourceTemplate.uriTemplate.toString() === ref.uri); - if (!template) { - if (this._registeredResources[ref.uri]) return EMPTY_COMPLETION_RESULT; - throw new src_CX2iR2pK_ProtocolError(src_CX2iR2pK_ProtocolErrorCode.InvalidParams, `Resource template ${request.params.ref.uri} not found`); - } - const completer = template.resourceTemplate.completeCallback(request.params.argument.name); - if (!completer) return EMPTY_COMPLETION_RESULT; - return createCompletionResult(await completer(request.params.argument.value, request.params.context)); - } - _resourceHandlersInitialized = false; - setResourceRequestHandlers() { - if (this._resourceHandlersInitialized) return; - this.server.assertCanSetRequestHandler("resources/list"); - this.server.assertCanSetRequestHandler("resources/templates/list"); - this.server.assertCanSetRequestHandler("resources/read"); - this.server.registerCapabilities({ resources: { listChanged: this.server.getCapabilities().resources?.listChanged ?? true } }); - this.server.setRequestHandler("resources/list", async (_request, ctx) => { - const resources = Object.entries(this._registeredResources).filter(([_, resource]) => resource.enabled).map(([uri, resource]) => ({ - uri, - name: resource.name, - ...resource.metadata - })); - const templateResources = []; - for (const template of Object.values(this._registeredResourceTemplates)) { - if (!template.resourceTemplate.listCallback) continue; - const result = await template.resourceTemplate.listCallback(ctx); - for (const resource of result.resources) templateResources.push({ - ...template.metadata, - ...resource - }); - } - return { resources: [...resources, ...templateResources] }; - }); - this.server.setRequestHandler("resources/templates/list", async () => { - return { resourceTemplates: Object.entries(this._registeredResourceTemplates).map(([name, template]) => ({ - name, - uriTemplate: template.resourceTemplate.uriTemplate.toString(), - ...template.metadata - })) }; - }); - this.server.setRequestHandler("resources/read", async (request, ctx) => { - let uri; - try { - uri = new URL(request.params.uri); - } catch { - throw new src_CX2iR2pK_ProtocolError(src_CX2iR2pK_ProtocolErrorCode.InvalidParams, `Resource URI ${request.params.uri} is invalid`, { - uri: request.params.uri, - reason: "invalid_uri" - }); - } - const resource = this._registeredResources[uri.toString()]; - if (resource) { - if (!resource.enabled) throw new src_CX2iR2pK_ProtocolError(src_CX2iR2pK_ProtocolErrorCode.InvalidParams, `Resource ${uri} disabled`); - return attachCacheHintFallback(await resource.readCallback(uri, ctx), resource.cacheHint); - } - for (const template of Object.values(this._registeredResourceTemplates)) { - const variables = template.resourceTemplate.uriTemplate.match(uri.toString()); - if (variables) return attachCacheHintFallback(await template.readCallback(uri, variables, ctx), template.cacheHint); - } - throw new ResourceNotFoundError(request.params.uri); - }); - this._resourceHandlersInitialized = true; - } - _promptHandlersInitialized = false; - setPromptRequestHandlers() { - if (this._promptHandlersInitialized) return; - this.server.assertCanSetRequestHandler("prompts/list"); - this.server.assertCanSetRequestHandler("prompts/get"); - this.server.registerCapabilities({ prompts: { listChanged: this.server.getCapabilities().prompts?.listChanged ?? true } }); - this.server.setRequestHandler("prompts/list", () => ({ prompts: Object.entries(this._registeredPrompts).filter(([, prompt]) => prompt.enabled).map(([name, prompt]) => { - return { - name, - title: prompt.title, - description: prompt.description, - arguments: prompt.argsSchema ? promptArgumentsFromStandardSchema(prompt.argsSchema) : void 0, - icons: prompt.icons, - _meta: prompt._meta - }; - }) })); - this.server.setRequestHandler("prompts/get", async (request, ctx) => { - const prompt = this._registeredPrompts[request.params.name]; - if (!prompt) throw new src_CX2iR2pK_ProtocolError(src_CX2iR2pK_ProtocolErrorCode.InvalidParams, `Prompt ${request.params.name} not found`); - if (!prompt.enabled) throw new src_CX2iR2pK_ProtocolError(src_CX2iR2pK_ProtocolErrorCode.InvalidParams, `Prompt ${request.params.name} disabled`); - return prompt.handler(request.params.arguments, ctx); - }); - this._promptHandlersInitialized = true; - } - registerResource(name, uriOrTemplate, config, readCallback) { - const cacheHint = config.cacheHint; - let metadata = config; - if (cacheHint !== void 0) { - assertValidCacheHint(cacheHint, `resource ${name}`); - const rest = { ...config }; - delete rest.cacheHint; - metadata = rest; - } - if (typeof uriOrTemplate === "string") { - if (this._registeredResources[uriOrTemplate]) throw new Error(`Resource ${uriOrTemplate} is already registered`); - const registeredResource = this._createRegisteredResource(name, config.title, uriOrTemplate, metadata, readCallback); - if (cacheHint !== void 0) registeredResource.cacheHint = cacheHint; - this.setResourceRequestHandlers(); - this.sendResourceListChanged(); - return registeredResource; - } else { - if (this._registeredResourceTemplates[name]) throw new Error(`Resource template ${name} is already registered`); - const registeredResourceTemplate = this._createRegisteredResourceTemplate(name, config.title, uriOrTemplate, metadata, readCallback); - if (cacheHint !== void 0) registeredResourceTemplate.cacheHint = cacheHint; - this.setResourceRequestHandlers(); - this.sendResourceListChanged(); - return registeredResourceTemplate; - } - } - _createRegisteredResource(name, title, uri, metadata, readCallback) { - const registeredResource = { - name, - title, - metadata, - readCallback, - enabled: true, - disable: () => registeredResource.update({ enabled: false }), - enable: () => registeredResource.update({ enabled: true }), - remove: () => registeredResource.update({ uri: null }), - update: (updates) => { - if (updates.uri !== void 0 && updates.uri !== uri) { - delete this._registeredResources[uri]; - if (updates.uri) this._registeredResources[updates.uri] = registeredResource; - } - if (updates.name !== void 0) registeredResource.name = updates.name; - if (updates.title !== void 0) registeredResource.title = updates.title; - if (updates.metadata !== void 0) registeredResource.metadata = updates.metadata; - if (updates.callback !== void 0) registeredResource.readCallback = updates.callback; - if (updates.enabled !== void 0) registeredResource.enabled = updates.enabled; - this.sendResourceListChanged(); - } - }; - this._registeredResources[uri] = registeredResource; - return registeredResource; - } - _createRegisteredResourceTemplate(name, title, template, metadata, readCallback) { - const registeredResourceTemplate = { - resourceTemplate: template, - title, - metadata, - readCallback, - enabled: true, - disable: () => registeredResourceTemplate.update({ enabled: false }), - enable: () => registeredResourceTemplate.update({ enabled: true }), - remove: () => registeredResourceTemplate.update({ name: null }), - update: (updates) => { - if (updates.name !== void 0 && updates.name !== name) { - delete this._registeredResourceTemplates[name]; - if (updates.name) this._registeredResourceTemplates[updates.name] = registeredResourceTemplate; - } - if (updates.title !== void 0) registeredResourceTemplate.title = updates.title; - if (updates.template !== void 0) registeredResourceTemplate.resourceTemplate = updates.template; - if (updates.metadata !== void 0) registeredResourceTemplate.metadata = updates.metadata; - if (updates.callback !== void 0) registeredResourceTemplate.readCallback = updates.callback; - if (updates.enabled !== void 0) registeredResourceTemplate.enabled = updates.enabled; - this.sendResourceListChanged(); - } - }; - this._registeredResourceTemplates[name] = registeredResourceTemplate; - const variableNames = template.uriTemplate.variableNames; - if (Array.isArray(variableNames) && variableNames.some((v) => !!template.completeCallback(v))) this.setCompletionRequestHandler(); - return registeredResourceTemplate; - } - _createRegisteredPrompt(name, title, description, argsSchema, callback, icons, _meta) { - let currentArgsSchema = argsSchema; - let currentCallback = callback; - const registeredPrompt = { - title, - description, - argsSchema, - icons, - _meta, - handler: createPromptHandler(name, argsSchema, callback), - enabled: true, - disable: () => registeredPrompt.update({ enabled: false }), - enable: () => registeredPrompt.update({ enabled: true }), - remove: () => registeredPrompt.update({ name: null }), - update: (updates) => { - if (updates.name !== void 0 && updates.name !== name) { - delete this._registeredPrompts[name]; - if (updates.name) this._registeredPrompts[updates.name] = registeredPrompt; - } - if (updates.title !== void 0) registeredPrompt.title = updates.title; - if (updates.description !== void 0) registeredPrompt.description = updates.description; - if (updates.icons !== void 0) registeredPrompt.icons = updates.icons; - if (updates._meta !== void 0) registeredPrompt._meta = updates._meta; - let needsHandlerRegen = false; - if (updates.argsSchema !== void 0) { - registeredPrompt.argsSchema = updates.argsSchema; - currentArgsSchema = updates.argsSchema; - needsHandlerRegen = true; - } - if (updates.callback !== void 0) { - currentCallback = updates.callback; - needsHandlerRegen = true; - } - if (needsHandlerRegen) registeredPrompt.handler = createPromptHandler(name, currentArgsSchema, currentCallback); - if (updates.enabled !== void 0) registeredPrompt.enabled = updates.enabled; - this.sendPromptListChanged(); - } - }; - this._registeredPrompts[name] = registeredPrompt; - if (argsSchema) { - const shape = getSchemaShape(argsSchema); - if (shape) { - if (Object.values(shape).some((field) => { - return isCompletable(unwrapOptionalSchema(field)); - })) this.setCompletionRequestHandler(); - } - } - return registeredPrompt; - } - _createRegisteredTool(name, title, description, inputSchema, outputSchema, annotations, icons, execution, _meta, handler) { - validateAndWarnToolName(name); - if (inputSchema !== void 0) try { - const json = standardSchemaToJsonSchema(inputSchema, "input"); - this._toolInputSchemaJson[name] = json; - const scan = src_CX2iR2pK_scanXMcpHeaderDeclarations(json); - if (!scan.valid) console.warn(`[mcp-sdk] tool '${name}' carries an invalid x-mcp-header declaration and will be excluded by conforming Streamable HTTP clients: ${scan.reason}`); - } catch {} - let currentHandler = handler; - const registeredTool = { - title, - description, - inputSchema, - outputSchema, - outputSchemaJson: convertOutputSchemaJson(outputSchema), - annotations, - icons, - execution, - _meta, - handler, - executor: createToolExecutor(inputSchema, handler), - enabled: true, - disable: () => registeredTool.update({ enabled: false }), - enable: () => registeredTool.update({ enabled: true }), - remove: () => registeredTool.update({ name: null }), - update: (updates) => { - if (updates.name !== void 0 && updates.name !== name) { - if (typeof updates.name === "string") validateAndWarnToolName(updates.name); - delete this._registeredTools[name]; - delete this._toolInputSchemaJson[name]; - if (updates.name) { - delete this._toolInputSchemaJson[updates.name]; - this._registeredTools[updates.name] = registeredTool; - name = updates.name; - } - } - if (updates.title !== void 0) registeredTool.title = updates.title; - if (updates.description !== void 0) registeredTool.description = updates.description; - let needsExecutorRegen = false; - if (updates.paramsSchema !== void 0) { - registeredTool.inputSchema = updates.paramsSchema; - delete this._toolInputSchemaJson[name]; - needsExecutorRegen = true; - } - if (updates.callback !== void 0) { - registeredTool.handler = updates.callback; - currentHandler = updates.callback; - needsExecutorRegen = true; - } - if (needsExecutorRegen) registeredTool.executor = createToolExecutor(registeredTool.inputSchema, currentHandler); - if (updates.outputSchema !== void 0) { - registeredTool.outputSchema = updates.outputSchema; - registeredTool.outputSchemaJson = convertOutputSchemaJson(updates.outputSchema); - } - if (updates.annotations !== void 0) registeredTool.annotations = updates.annotations; - if (updates.icons !== void 0) registeredTool.icons = updates.icons; - if (updates._meta !== void 0) registeredTool._meta = updates._meta; - if (updates.enabled !== void 0) registeredTool.enabled = updates.enabled; - this.sendToolListChanged(); - } - }; - this._registeredTools[name] = registeredTool; - this.setToolRequestHandlers(); - this.sendToolListChanged(); - return registeredTool; - } - registerTool(name, config, cb) { - if (this._registeredTools[name]) throw new Error(`Tool ${name} is already registered`); - const { title, description, inputSchema, outputSchema, annotations, icons, _meta } = config; - return this._createRegisteredTool(name, title, description, normalizeRawShapeSchema(inputSchema), normalizeRawShapeSchema(outputSchema), annotations, icons, void 0, _meta, cb); - } - registerPrompt(name, config, cb) { - if (this._registeredPrompts[name]) throw new Error(`Prompt ${name} is already registered`); - const { title, description, argsSchema, icons, _meta } = config; - const registeredPrompt = this._createRegisteredPrompt(name, title, description, normalizeRawShapeSchema(argsSchema), cb, icons, _meta); - this.setPromptRequestHandlers(); - this.sendPromptListChanged(); - return registeredPrompt; - } - /** - * Checks if the server is connected to a transport. - * @returns `true` if the server is connected - */ - isConnected() { - return this.server.transport !== void 0; - } - /** - * Sends a logging message to the client, if connected. - * Note: You only need to send the parameters object, not the entire JSON-RPC message. - * @see {@linkcode LoggingMessageNotification} - * @param params - * @param sessionId Optional for stateless transports and backward compatibility. - * - * @example - * ```ts source="./mcp.examples.ts#McpServer_sendLoggingMessage_basic" - * await server.sendLoggingMessage({ - * level: 'info', - * data: 'Processing complete' - * }); - * ``` - * - * @deprecated Deprecated as of protocol version 2026-07-28 (SEP-2577). - * Remains functional during the deprecation window (at least twelve months). - * Migrate to stderr logging (STDIO servers) or OpenTelemetry. - */ - async sendLoggingMessage(params, sessionId) { - return this.server.sendLoggingMessage(params, sessionId); - } - /** - * Sends a resource list changed event to the client, if connected. - */ - sendResourceListChanged() { - if (this.isConnected()) this.server.sendResourceListChanged(); - } - /** - * Sends a tool list changed event to the client, if connected. - */ - sendToolListChanged() { - if (this.isConnected()) this.server.sendToolListChanged(); - } - /** - * Sends a prompt list changed event to the client, if connected. - */ - sendPromptListChanged() { - if (this.isConnected()) this.server.sendPromptListChanged(); - } -}; -/** -* A resource template combines a URI pattern with optional functionality to enumerate -* all resources matching that pattern. -*/ -var ResourceTemplate = class { - _uriTemplate; - constructor(uriTemplate, _callbacks) { - this._callbacks = _callbacks; - this._uriTemplate = typeof uriTemplate === "string" ? new UriTemplate(uriTemplate) : uriTemplate; - } - /** - * Gets the URI template pattern. - */ - get uriTemplate() { - return this._uriTemplate; - } - /** - * Gets the list callback, if one was provided. - */ - get listCallback() { - return this._callbacks.list; - } - /** - * Gets the callback for completing a specific URI template variable, if one was provided. - */ - completeCallback(variable) { - return this._callbacks.complete?.[variable]; - } -}; -/** -* Creates an executor that invokes the handler with the appropriate arguments. -* When `inputSchema` is defined, the handler is called with `(args, ctx)`. -* When `inputSchema` is undefined, the handler is called with just `(ctx)`. -*/ -function createToolExecutor(inputSchema, handler) { - if (inputSchema) { - const callback$1 = handler; - return async (args, ctx) => callback$1(args, ctx); - } - const callback = handler; - return async (_args, ctx) => callback(ctx); -} -const EMPTY_OBJECT_JSON_SCHEMA = { - type: "object", - properties: {} -}; -/** -* Convert a registered `outputSchema` to JSON Schema, memoised on {@link RegisteredTool.outputSchemaJson} -* so `tools/call` passes the SAME advertised schema to the wire codec's `projectCallToolResult` that -* `tools/list` emits (and that the 2025 codec's `encodeResult('tools/list', …)` may wrap). A conversion -* failure yields `undefined` so the failure surfaces where it always has (`tools/list`). -*/ -function convertOutputSchemaJson(outputSchema) { - if (outputSchema === void 0) return void 0; - try { - return standardSchemaToJsonSchema(outputSchema, "output"); - } catch { - return; - } -} -/** -* Creates a type-safe prompt handler that captures the schema and callback in a closure. -* This eliminates the need for type assertions at the call site. -*/ -function createPromptHandler(name, argsSchema, callback) { - if (argsSchema) { - const typedCallback = callback; - return async (args, ctx) => { - const parseResult = await validateStandardSchema(argsSchema, args); - if (!parseResult.success) throw new src_CX2iR2pK_ProtocolError(src_CX2iR2pK_ProtocolErrorCode.InvalidParams, `Invalid arguments for prompt ${name}: ${parseResult.error}`); - return typedCallback(parseResult.data, ctx); - }; - } else { - const typedCallback = callback; - return async (_args, ctx) => { - return typedCallback(ctx); - }; - } -} -function createCompletionResult(suggestions) { - return { completion: { - values: suggestions.map(String).slice(0, 100), - total: suggestions.length, - hasMore: suggestions.length > 100 - } }; -} -const EMPTY_COMPLETION_RESULT = { completion: { - values: [], - hasMore: false -} }; -/** @internal Gets the shape of a Zod object schema */ -function getSchemaShape(schema) { - const candidate = schema; - if (candidate.shape && typeof candidate.shape === "object") return candidate.shape; -} -/** @internal Checks if a Zod schema is optional */ -function isOptionalSchema(schema) { - return schema?.type === "optional"; -} -/** @internal Unwraps an optional Zod schema */ -function unwrapOptionalSchema(schema) { - if (!isOptionalSchema(schema)) return schema; - return schema.def?.innerType ?? schema; -} - -//#endregion - -//# sourceMappingURL=mcp-DXXb3Vv3.mjs.map - - - - -//#region src/server/perRequestTransport.ts -/** -* The per-request micro-transport: a real, connected `Transport` whose whole -* lifetime is one HTTP exchange. See the module documentation for the -* response shapes it produces. -*/ -var PerRequestHTTPServerTransport = class { - onclose; - onerror; - onmessage; - _classification; - _responseMode; - _started = false; - _used = false; - _closed = false; - _terminalDelivered = false; - /** - * `true` only while the inbound message is being delivered synchronously - * to the connected protocol layer. The pre-handler gates (the era - * registry gate, the edge→instance handoff check, the missing-handler - * rejection) answer inside this window; request handlers always run - * after it (the protocol layer defers them to a microtask). An error - * sent inside the window is therefore ladder-originated, and an error - * sent after it is handler-produced. - */ - _dispatchWindowOpen = false; - _requestId; - _deferredResponse; - _sse; - _abortCleanup; - _keepAliveMs; - constructor(options) { - this._classification = options.classification; - this._responseMode = options.responseMode ?? "auto"; - this._keepAliveMs = options.keepAliveMs ?? DEFAULT_SSE_KEEP_ALIVE_MS; - } - async start() { - if (this._started) throw new Error("PerRequestHTTPServerTransport is already started"); - this._started = true; - } - /** - * Serves the single exchange: delivers the classified message to the - * connected server instance and resolves with the HTTP response. - * - * Throws when called a second time (the transport is strictly - * single-use), or before a server has been connected to the transport. - * The returned promise rejects with a connection-closed error when the - * transport is closed before a response was produced (for example because - * the client disconnected). - */ - async handleMessage(message, extra) { - if (this._used) throw new Error("PerRequestHTTPServerTransport serves exactly one exchange; construct a new transport per request"); - if (!this._started || this.onmessage === void 0) throw new Error("PerRequestHTTPServerTransport is not connected: connect a server to this transport before handling a message"); - if (this._closed) throw new Error("PerRequestHTTPServerTransport is closed"); - this._used = true; - const signal = extra?.request?.signal; - if (signal?.aborted) { - await this.close(); - throw new SdkError(SdkErrorCode.ConnectionClosed, "The request was aborted before it could be handled"); - } - const messageExtra = { - classification: this._classification, - ...extra?.request !== void 0 && { request: extra.request }, - ...extra?.authInfo !== void 0 && { authInfo: extra.authInfo } - }; - if (isJSONRPCRequest(message)) { - this._requestId = message.id; - let resolve; - let reject; - const promise = new Promise((promiseResolve, promiseReject) => { - resolve = promiseResolve; - reject = promiseReject; - }); - this._deferredResponse = { - promise, - resolve, - reject, - settled: false - }; - if (signal !== void 0) { - const onAbort = () => void this.close(); - signal.addEventListener("abort", onAbort, { once: true }); - this._abortCleanup = () => signal.removeEventListener("abort", onAbort); - } - this._dispatchWindowOpen = true; - try { - this.onmessage(message, messageExtra); - } finally { - this._dispatchWindowOpen = false; - } - if (this._responseMode === "sse" && !this._closed && !this._deferredResponse.settled) this.upgradeToSse(); - return promise; - } - this.onmessage(message, messageExtra); - return new Response(null, { status: 202 }); - } - async send(message, options) { - if (this._closed) return; - const isResponse = isJSONRPCResultResponse(message) || isJSONRPCErrorResponse(message); - const relatedId = isResponse ? message.id : options?.relatedRequestId; - if (this._requestId === void 0 || relatedId === void 0 || relatedId !== this._requestId) { - if (isResponse) this.onerror?.(/* @__PURE__ */ new Error(`Received a response for an unknown request id: ${String(message.id)}`)); - return; - } - if (isResponse) { - if (this._terminalDelivered) return; - this._terminalDelivered = true; - const errorCode = isJSONRPCErrorResponse(message) ? message.error.code : void 0; - const ladderStatus = errorCode !== void 0 && (this._dispatchWindowOpen || errorCode === ProtocolErrorCode.MissingRequiredClientCapability) ? LADDER_ERROR_HTTP_STATUS[errorCode] : void 0; - if (ladderStatus !== void 0 && this._sse === void 0) { - this.settleResponse(Response.json(message, { - status: ladderStatus, - headers: { "Content-Type": "application/json" } - })); - queueMicrotask(() => void this.close()); - return; - } - if (this._sse !== void 0 || this._responseMode === "sse") { - if (this._sse === void 0) this.upgradeToSse(); - this.writeMessageFrame(message); - this.finalizeStream(); - return; - } - this.settleResponse(Response.json(message, { - status: 200, - headers: { "Content-Type": "application/json" } - })); - queueMicrotask(() => void this.close()); - return; - } - if (this._responseMode === "json") return; - if (this._sse === void 0) this.upgradeToSse(); - this.writeMessageFrame(message); - } - /** - * Writes an SSE comment frame (a keep-alive heartbeat). Dropped when the - * exchange is not currently streaming. - */ - writeCommentFrame(comment) { - if (this._closed || this._sse === void 0 || this._sse.closed) return; - const frame = comment.split("\n").map((line) => `: ${line}`).join("\n"); - this.writeFrame(`${frame}\n\n`); - } - async close() { - if (this._closed) return; - this._closed = true; - this._abortCleanup?.(); - this._abortCleanup = void 0; - if (this._sse?.keepAliveTimer !== void 0) clearInterval(this._sse.keepAliveTimer); - if (this._sse !== void 0 && !this._sse.closed) { - this._sse.closed = true; - try { - this._sse.controller.close(); - } catch {} - } - if (this._deferredResponse !== void 0 && !this._deferredResponse.settled) { - this._deferredResponse.settled = true; - this._deferredResponse.reject(new SdkError(SdkErrorCode.ConnectionClosed, "Connection closed before a response was produced")); - } - this.onclose?.(); - } - settleResponse(response) { - if (this._deferredResponse === void 0 || this._deferredResponse.settled) return; - this._deferredResponse.settled = true; - this._deferredResponse.resolve(response); - } - upgradeToSse() { - let controller; - const readable = new ReadableStream({ - start: (streamController) => { - controller = streamController; - }, - cancel: () => { - this.close(); - } - }); - this._sse = { - controller, - encoder: new TextEncoder(), - closed: false - }; - this._sse.keepAliveTimer = armSseKeepAlive(this._keepAliveMs, () => this.writeCommentFrame("keepalive")); - this.settleResponse(new Response(readable, { - status: 200, - headers: { - "Content-Type": "text/event-stream", - "Cache-Control": "no-cache, no-transform", - Connection: "keep-alive", - "X-Accel-Buffering": "no" - } - })); - } - finalizeStream() { - if (this._sse?.keepAliveTimer !== void 0) clearInterval(this._sse.keepAliveTimer); - if (this._sse !== void 0 && !this._sse.closed) { - this._sse.closed = true; - try { - this._sse.controller.close(); - } catch {} - } - queueMicrotask(() => void this.close()); - } - writeMessageFrame(message) { - this.writeFrame(`event: message\ndata: ${JSON.stringify(message)}\n\n`); - } - writeFrame(frame) { - if (this._sse === void 0 || this._sse.closed) return; - try { - this._sse.controller.enqueue(this._sse.encoder.encode(frame)); - } catch (error) { - this.onerror?.(/* @__PURE__ */ new Error(`Failed to write to the response stream: ${error}`)); - } - } -}; - -//#endregion -//#region src/server/invoke.ts -/** -* Serves one classified inbound message on the given server instance and -* returns the HTTP response for the exchange. -* -* The instance is connected to a fresh single-exchange transport, the message -* is injected through the normal transport message path, and whatever the -* dispatch layer produces (the handler result, a protocol-level rejection, or -* streamed related messages followed by the result) is captured as the -* returned `Response`. For request exchanges, teardown rides the transport's -* close chain once the terminal response has been delivered; notification -* exchanges resolve with the 202 response immediately and do NOT run the -* close chain — the transport stays connected until the caller closes it or -* drops the per-request instance, which is the caller's choice either way. -*/ -async function invoke(server, message, ctx) { - const transport = new PerRequestHTTPServerTransport({ - classification: ctx.classification, - ...ctx.responseMode !== void 0 && { responseMode: ctx.responseMode }, - ...ctx.keepAliveMs !== void 0 && { keepAliveMs: ctx.keepAliveMs } - }); - await server.connect(transport); - return transport.handleMessage(message, { - ...ctx.request !== void 0 && { request: ctx.request }, - ...ctx.authInfo !== void 0 && { authInfo: ctx.authInfo } - }); -} - -//#endregion -//#region src/server/streamableHttp.ts -/** -* Server transport for Web Standards Streamable HTTP: this implements the MCP Streamable HTTP transport specification -* using Web Standard APIs (`Request`, `Response`, `ReadableStream`). -* -* This transport works on any runtime that supports Web Standards: Node.js 18+, Cloudflare Workers, Deno, Bun, etc. -* -* In stateful mode: -* - Session ID is generated and included in response headers -* - Session ID is always included in initialization responses -* - Requests with invalid session IDs are rejected with `404 Not Found` -* - Non-initialization requests without a session ID are rejected with `400 Bad Request` -* - State is maintained in-memory (connections, message history) -* -* In stateless mode: -* - No Session ID is included in any responses -* - No session validation is performed -* -* @example Stateful setup -* ```ts source="./streamableHttp.examples.ts#WebStandardStreamableHTTPServerTransport_stateful" -* const server = new McpServer({ name: 'my-server', version: '1.0.0' }); -* -* const transport = new WebStandardStreamableHTTPServerTransport({ -* sessionIdGenerator: () => crypto.randomUUID() -* }); -* -* await server.connect(transport); -* ``` -* -* @example Stateless setup -* ```ts source="./streamableHttp.examples.ts#WebStandardStreamableHTTPServerTransport_stateless" -* const transport = new WebStandardStreamableHTTPServerTransport({ -* sessionIdGenerator: undefined -* }); -* ``` -* -* @example Hono.js -* ```ts source="./streamableHttp.examples.ts#WebStandardStreamableHTTPServerTransport_hono" -* app.all('/mcp', async c => { -* return transport.handleRequest(c.req.raw); -* }); -* ``` -* -* @example Cloudflare Workers -* ```ts source="./streamableHttp.examples.ts#WebStandardStreamableHTTPServerTransport_workers" -* const worker = { -* async fetch(request: Request): Promise { -* return transport.handleRequest(request); -* } -* }; -* ``` -*/ -var WebStandardStreamableHTTPServerTransport = class { - sessionIdGenerator; - _started = false; - _closed = false; - _streamMapping = /* @__PURE__ */ new Map(); - _requestToStreamMapping = /* @__PURE__ */ new Map(); - _requestResponseMap = /* @__PURE__ */ new Map(); - _initialized = false; - _enableJsonResponse = false; - _standaloneSseStreamId = "_GET_stream"; - _eventStore; - _onsessioninitialized; - _onsessionclosed; - _allowedHosts; - _allowedOrigins; - _enableDnsRebindingProtection; - _retryInterval; - _supportedProtocolVersions; - _keepAliveMs; - sessionId; - onclose; - onerror; - onmessage; - constructor(options = {}) { - this.sessionIdGenerator = options.sessionIdGenerator; - this._enableJsonResponse = options.enableJsonResponse ?? false; - this._eventStore = options.eventStore; - this._onsessioninitialized = options.onsessioninitialized; - this._onsessionclosed = options.onsessionclosed; - this._allowedHosts = options.allowedHosts; - this._allowedOrigins = options.allowedOrigins; - this._enableDnsRebindingProtection = options.enableDnsRebindingProtection ?? false; - this._retryInterval = options.retryInterval; - this._supportedProtocolVersions = options.supportedProtocolVersions ?? SUPPORTED_PROTOCOL_VERSIONS; - this._keepAliveMs = options.keepAliveMs ?? DEFAULT_SSE_KEEP_ALIVE_MS; - } - startKeepAlive(controller, encoder) { - if (this._closed) return void 0; - const timer = armSseKeepAlive(this._keepAliveMs, () => { - try { - controller.enqueue(encoder.encode(": keepalive\n\n")); - } catch { - if (timer !== void 0) clearInterval(timer); - } - }); - return timer; - } - /** - * Starts the transport. This is required by the {@linkcode Transport} interface but is a no-op - * for the Streamable HTTP transport as connections are managed per-request. - */ - async start() { - if (this._started) throw new Error("Transport already started"); - this._started = true; - } - /** - * Sets the supported protocol versions for header validation. - * Called by the server during {@linkcode server/server.Server.connect | connect()} to pass its supported versions. - */ - setSupportedProtocolVersions(versions) { - this._supportedProtocolVersions = versions; - } - /** - * Helper to create a JSON error response - */ - createJsonErrorResponse(status, code, message, options) { - const error = { - code, - message - }; - if (options?.data !== void 0) error.data = options.data; - return Response.json({ - jsonrpc: "2.0", - error, - id: null - }, { - status, - headers: { - "Content-Type": "application/json", - ...options?.headers - } - }); - } - /** - * Validates request headers for DNS rebinding protection. - * @returns Error response if validation fails, `undefined` if validation passes. - */ - validateRequestHeaders(req) { - if (!this._enableDnsRebindingProtection) return; - if (this._allowedHosts && this._allowedHosts.length > 0) { - const hostHeader = req.headers.get("host"); - if (!hostHeader || !this._allowedHosts.includes(hostHeader)) { - const error = `Invalid Host header: ${hostHeader}`; - this.onerror?.(new Error(error)); - return this.createJsonErrorResponse(403, -32e3, error); - } - } - if (this._allowedOrigins && this._allowedOrigins.length > 0) { - const originHeader = req.headers.get("origin"); - if (originHeader && !this._allowedOrigins.includes(originHeader)) { - const error = `Invalid Origin header: ${originHeader}`; - this.onerror?.(new Error(error)); - return this.createJsonErrorResponse(403, -32e3, error); - } - } - } - /** - * Handles an incoming HTTP request, whether `GET`, `POST`, or `DELETE` - * Returns a `Response` object (Web Standard) - */ - async handleRequest(req, options) { - if (this._closed) return this.createJsonErrorResponse(404, -32001, "Session not found"); - const validationError = this.validateRequestHeaders(req); - if (validationError) return validationError; - switch (req.method) { - case "POST": return this.handlePostRequest(req, options); - case "GET": return this.handleGetRequest(req); - case "DELETE": return this.handleDeleteRequest(req); - default: return this.handleUnsupportedRequest(); - } - } - /** - * Returns true if the client's protocol version supports empty SSE data in - * priming events (the fix shipped with protocol version `2025-11-25`). - * - * The version is checked for membership in this transport instance's - * supported protocol versions rather than with an open-ended - * `>= '2025-11-25'` comparison: the value may come from an `initialize` - * request body, which (unlike the `MCP-Protocol-Version` header) is not - * validated against `supportedProtocolVersions` before reaching this - * check. An unknown future version string must not silently enable - * behavior reserved for versions this transport actually supports. - */ - supportsEmptySSEData(protocolVersion) { - return this._supportedProtocolVersions.includes(protocolVersion) && protocolVersion >= "2025-11-25"; - } - /** - * Writes a priming event to establish resumption capability. - * Only sends if `eventStore` is configured (opt-in for resumability) and - * the client's protocol version supports empty SSE data (a supported - * version that is >= `2025-11-25`). - */ - async writePrimingEvent(controller, encoder, streamId, protocolVersion) { - if (!this._eventStore) return; - if (!this.supportsEmptySSEData(protocolVersion)) return; - const primingEventId = await this._eventStore.storeEvent(streamId, {}); - let primingEvent = `id: ${primingEventId}\ndata: \n\n`; - if (this._retryInterval !== void 0) primingEvent = `id: ${primingEventId}\nretry: ${this._retryInterval}\ndata: \n\n`; - controller.enqueue(encoder.encode(primingEvent)); - } - /** - * Handles `GET` requests for SSE stream - */ - async handleGetRequest(req) { - if (!req.headers.get("accept")?.includes("text/event-stream")) { - this.onerror?.(/* @__PURE__ */ new Error("Not Acceptable: Client must accept text/event-stream")); - return this.createJsonErrorResponse(406, -32e3, "Not Acceptable: Client must accept text/event-stream"); - } - const sessionError = this.validateSession(req); - if (sessionError) return sessionError; - const protocolError = this.validateProtocolVersion(req); - if (protocolError) return protocolError; - if (this._eventStore) { - const lastEventId = req.headers.get("last-event-id"); - if (lastEventId) return this.replayEvents(lastEventId); - } - if (this._streamMapping.get(this._standaloneSseStreamId) !== void 0) { - this.onerror?.(/* @__PURE__ */ new Error("Conflict: Only one SSE stream is allowed per session")); - return this.createJsonErrorResponse(409, -32e3, "Conflict: Only one SSE stream is allowed per session"); - } - const encoder = new TextEncoder(); - let streamController; - let keepAliveTimer; - const readable = new ReadableStream({ - start: (controller) => { - streamController = controller; - }, - cancel: () => { - if (keepAliveTimer !== void 0) clearInterval(keepAliveTimer); - if (this._streamMapping.get(this._standaloneSseStreamId)?.controller === streamController) this._streamMapping.delete(this._standaloneSseStreamId); - } - }); - const headers = { - "Content-Type": "text/event-stream", - "Cache-Control": "no-cache, no-transform", - Connection: "keep-alive", - "X-Accel-Buffering": "no" - }; - if (this.sessionId !== void 0) headers["mcp-session-id"] = this.sessionId; - this._streamMapping.set(this._standaloneSseStreamId, { - controller: streamController, - encoder, - cleanup: () => { - if (keepAliveTimer !== void 0) clearInterval(keepAliveTimer); - this._streamMapping.delete(this._standaloneSseStreamId); - try { - streamController.close(); - } catch {} - } - }); - keepAliveTimer = this.startKeepAlive(streamController, encoder); - return new Response(readable, { headers }); - } - /** - * Replays events that would have been sent after the specified event ID - * Only used when resumability is enabled - */ - async replayEvents(lastEventId) { - if (!this._eventStore) { - this.onerror?.(/* @__PURE__ */ new Error("Event store not configured")); - return this.createJsonErrorResponse(400, -32e3, "Event store not configured"); - } - try { - let streamId; - if (this._eventStore.getStreamIdForEventId) { - streamId = await this._eventStore.getStreamIdForEventId(lastEventId); - if (!streamId) { - this.onerror?.(/* @__PURE__ */ new Error("Invalid event ID format")); - return this.createJsonErrorResponse(400, -32e3, "Invalid event ID format"); - } - if (this._streamMapping.get(streamId) !== void 0) { - this.onerror?.(/* @__PURE__ */ new Error("Conflict: Stream already has an active connection")); - return this.createJsonErrorResponse(409, -32e3, "Conflict: Stream already has an active connection"); - } - } - const headers = { - "Content-Type": "text/event-stream", - "Cache-Control": "no-cache, no-transform", - Connection: "keep-alive", - "X-Accel-Buffering": "no" - }; - if (this.sessionId !== void 0) headers["mcp-session-id"] = this.sessionId; - const encoder = new TextEncoder(); - let streamController; - let keepAliveTimer; - let cancelled = false; - let replayedStreamId; - const readable = new ReadableStream({ - start: (controller) => { - streamController = controller; - }, - cancel: () => { - cancelled = true; - if (keepAliveTimer !== void 0) clearInterval(keepAliveTimer); - if (replayedStreamId !== void 0 && this._streamMapping.get(replayedStreamId)?.controller === streamController) this._streamMapping.delete(replayedStreamId); - } - }); - const replayedEventIds = /* @__PURE__ */ new Set(); - replayedStreamId = await this._eventStore.replayEventsAfter(lastEventId, { send: async (eventId, message) => { - replayedEventIds.add(eventId); - if (!this.writeSSEEvent(streamController, encoder, message, eventId)) try { - streamController.close(); - } catch {} - } }); - if (this._closed || cancelled) { - try { - streamController.close(); - } catch {} - return this.createJsonErrorResponse(404, -32001, "Session not found"); - } - this._streamMapping.get(replayedStreamId)?.cleanup(); - this._streamMapping.set(replayedStreamId, { - controller: streamController, - encoder, - replayedEventIds, - cleanup: () => { - if (keepAliveTimer !== void 0) clearInterval(keepAliveTimer); - this._streamMapping.delete(replayedStreamId); - try { - streamController.close(); - } catch {} - } - }); - if (replayedStreamId !== this._standaloneSseStreamId) { - if (![...this._requestToStreamMapping.values()].includes(replayedStreamId)) { - this._streamMapping.delete(replayedStreamId); - try { - streamController.close(); - } catch {} - } - } - if (this._streamMapping.get(replayedStreamId)?.controller === streamController) keepAliveTimer = this.startKeepAlive(streamController, encoder); - return new Response(readable, { headers }); - } catch (error) { - this.onerror?.(error); - return this.createJsonErrorResponse(500, -32e3, "Error replaying events"); - } - } - /** - * Writes an event to an SSE stream via controller with proper formatting - */ - writeSSEEvent(controller, encoder, message, eventId) { - try { - let eventData = `event: message\n`; - if (eventId) eventData += `id: ${eventId}\n`; - eventData += `data: ${JSON.stringify(message)}\n\n`; - controller.enqueue(encoder.encode(eventData)); - return true; - } catch (error) { - this.onerror?.(error); - return false; - } - } - /** - * Handles unsupported requests (`PUT`, `PATCH`, etc.) - */ - handleUnsupportedRequest() { - this.onerror?.(/* @__PURE__ */ new Error("Method not allowed.")); - return Response.json({ - jsonrpc: "2.0", - error: { - code: -32e3, - message: "Method not allowed." - }, - id: null - }, { - status: 405, - headers: { - Allow: "GET, POST, DELETE", - "Content-Type": "application/json" - } - }); - } - /** - * Handles `POST` requests containing JSON-RPC messages - */ - async handlePostRequest(req, options) { - try { - const acceptHeader = req.headers.get("accept"); - if (!acceptHeader?.includes("application/json") || !acceptHeader.includes("text/event-stream")) { - this.onerror?.(/* @__PURE__ */ new Error("Not Acceptable: Client must accept both application/json and text/event-stream")); - return this.createJsonErrorResponse(406, -32e3, "Not Acceptable: Client must accept both application/json and text/event-stream"); - } - if (!isJsonContentType(req.headers.get("content-type"))) { - this.onerror?.(/* @__PURE__ */ new Error("Unsupported Media Type: Content-Type must be application/json")); - return this.createJsonErrorResponse(415, -32e3, "Unsupported Media Type: Content-Type must be application/json"); - } - const request = req; - let rawMessage; - if (options?.parsedBody === void 0) try { - rawMessage = await req.json(); - } catch (error) { - this.onerror?.(error); - return this.createJsonErrorResponse(400, -32700, "Parse error: Invalid JSON"); - } - else rawMessage = options.parsedBody; - let messages; - try { - messages = Array.isArray(rawMessage) ? rawMessage.map((msg) => JSONRPCMessageSchema.parse(msg)) : [JSONRPCMessageSchema.parse(rawMessage)]; - } catch (error) { - this.onerror?.(error); - return this.createJsonErrorResponse(400, -32700, "Parse error: Invalid JSON-RPC message"); - } - if (this._closed) return this.createJsonErrorResponse(404, -32001, "Session not found"); - const isInitializationRequest = messages.some((element) => isInitializeRequest(element)); - if (isInitializationRequest) { - if (this._initialized && this.sessionId !== void 0) { - this.onerror?.(/* @__PURE__ */ new Error("Invalid Request: Server already initialized")); - return this.createJsonErrorResponse(400, -32600, "Invalid Request: Server already initialized"); - } - if (messages.length > 1) { - this.onerror?.(/* @__PURE__ */ new Error("Invalid Request: Only one initialization request is allowed")); - return this.createJsonErrorResponse(400, -32600, "Invalid Request: Only one initialization request is allowed"); - } - this.sessionId = this.sessionIdGenerator?.(); - this._initialized = true; - if (this.sessionId && this._onsessioninitialized) await Promise.resolve(this._onsessioninitialized(this.sessionId)); - } - if (!isInitializationRequest) { - const sessionError = this.validateSession(req); - if (sessionError) return sessionError; - const protocolError = this.validateProtocolVersion(req); - if (protocolError) return protocolError; - } - if (this._closed) return this.createJsonErrorResponse(404, -32001, "Session not found"); - if (!messages.some((element) => isJSONRPCRequest(element))) { - for (const message of messages) this.onmessage?.(message, { - authInfo: options?.authInfo, - request - }); - return new Response(null, { status: 202 }); - } - const streamId = crypto.randomUUID(); - const initRequest = messages.find((m) => isInitializeRequest(m)); - const clientProtocolVersion = initRequest ? initRequest.params.protocolVersion : req.headers.get("mcp-protocol-version") ?? DEFAULT_NEGOTIATED_PROTOCOL_VERSION; - if (this._enableJsonResponse) return new Promise((resolve) => { - this._streamMapping.set(streamId, { - resolveJson: resolve, - cleanup: () => { - this._streamMapping.delete(streamId); - } - }); - for (const message of messages) if (isJSONRPCRequest(message)) this._requestToStreamMapping.set(message.id, streamId); - for (const message of messages) this.onmessage?.(message, { - authInfo: options?.authInfo, - request - }); - }); - const encoder = new TextEncoder(); - let streamController; - let keepAliveTimer; - const readable = new ReadableStream({ - start: (controller) => { - streamController = controller; - }, - cancel: () => { - if (keepAliveTimer !== void 0) clearInterval(keepAliveTimer); - if (this._streamMapping.get(streamId)?.controller === streamController) this._streamMapping.delete(streamId); - } - }); - const headers = { - "Content-Type": "text/event-stream", - "Cache-Control": "no-cache, no-transform", - Connection: "keep-alive", - "X-Accel-Buffering": "no" - }; - if (this.sessionId !== void 0) headers["mcp-session-id"] = this.sessionId; - for (const message of messages) if (isJSONRPCRequest(message)) { - this._streamMapping.set(streamId, { - controller: streamController, - encoder, - cleanup: () => { - if (keepAliveTimer !== void 0) clearInterval(keepAliveTimer); - this._streamMapping.delete(streamId); - try { - streamController.close(); - } catch {} - } - }); - this._requestToStreamMapping.set(message.id, streamId); - } - await this.writePrimingEvent(streamController, encoder, streamId, clientProtocolVersion); - for (const message of messages) { - let closeSSEStream; - let closeStandaloneSSEStream; - if (isJSONRPCRequest(message) && this._eventStore && this.supportsEmptySSEData(clientProtocolVersion)) { - closeSSEStream = () => { - this.closeSSEStream(message.id); - }; - closeStandaloneSSEStream = () => { - this.closeStandaloneSSEStream(); - }; - } - this.onmessage?.(message, { - authInfo: options?.authInfo, - request, - closeSSEStream, - closeStandaloneSSEStream - }); - } - if (this._streamMapping.get(streamId)?.controller === streamController) keepAliveTimer = this.startKeepAlive(streamController, encoder); - return new Response(readable, { - status: 200, - headers - }); - } catch (error) { - this.onerror?.(error); - return this.createJsonErrorResponse(400, -32700, "Parse error", { data: String(error) }); - } - } - /** - * Handles `DELETE` requests to terminate sessions - */ - async handleDeleteRequest(req) { - const sessionError = this.validateSession(req); - if (sessionError) return sessionError; - const protocolError = this.validateProtocolVersion(req); - if (protocolError) return protocolError; - try { - await Promise.resolve(this._onsessionclosed?.(this.sessionId)); - return new Response(null, { status: 200 }); - } finally { - await this.close(); - } - } - /** - * Validates session ID for non-initialization requests. - * Returns `Response` error if invalid, `undefined` otherwise - */ - validateSession(req) { - if (this.sessionIdGenerator === void 0) return; - if (!this._initialized) { - this.onerror?.(/* @__PURE__ */ new Error("Bad Request: Server not initialized")); - return this.createJsonErrorResponse(400, -32e3, "Bad Request: Server not initialized"); - } - const sessionId = req.headers.get("mcp-session-id"); - if (!sessionId) { - this.onerror?.(/* @__PURE__ */ new Error("Bad Request: Mcp-Session-Id header is required")); - return this.createJsonErrorResponse(400, -32e3, "Bad Request: Mcp-Session-Id header is required"); - } - if (sessionId !== this.sessionId) { - this.onerror?.(/* @__PURE__ */ new Error("Session not found")); - return this.createJsonErrorResponse(404, -32001, "Session not found"); - } - } - /** - * Validates the `MCP-Protocol-Version` header on incoming requests. - * - * For initialization: Version negotiation handles unknown versions gracefully - * (server responds with its supported version). - * - * For subsequent requests with `MCP-Protocol-Version` header: - * - Accept if in supported list - * - 400 if unsupported - * - * For HTTP requests without the `MCP-Protocol-Version` header: - * - Accept and default to the version negotiated at initialization - */ - validateProtocolVersion(req) { - const protocolVersion = req.headers.get("mcp-protocol-version"); - if (protocolVersion !== null && !this._supportedProtocolVersions.includes(protocolVersion)) { - const error = `Bad Request: Unsupported protocol version: ${protocolVersion} (supported versions: ${this._supportedProtocolVersions.join(", ")})`; - this.onerror?.(new Error(error)); - return this.createJsonErrorResponse(400, -32e3, error); - } - } - async close() { - if (this._closed) return; - this._closed = true; - for (const { cleanup } of this._streamMapping.values()) cleanup(); - this._streamMapping.clear(); - this._requestResponseMap.clear(); - this.onclose?.(); - } - /** - * Close an SSE stream for a specific request, triggering client reconnection. - * Use this to implement polling behavior during long-running operations - - * client will reconnect after the retry interval specified in the priming event. - */ - closeSSEStream(requestId) { - const streamId = this._requestToStreamMapping.get(requestId); - if (!streamId) return; - const stream = this._streamMapping.get(streamId); - if (stream) stream.cleanup(); - } - /** - * Close the standalone `GET` SSE stream, triggering client reconnection. - * Use this to implement polling behavior for server-initiated notifications. - */ - closeStandaloneSSEStream() { - const stream = this._streamMapping.get(this._standaloneSseStreamId); - if (stream) stream.cleanup(); - } - async send(message, options) { - let requestId = options?.relatedRequestId; - if (isJSONRPCResultResponse(message) || isJSONRPCErrorResponse(message)) requestId = message.id; - if (requestId === void 0) { - if (isJSONRPCResultResponse(message) || isJSONRPCErrorResponse(message)) throw new Error("Cannot send a response on a standalone SSE stream unless resuming a previous client request"); - let eventId; - if (this._eventStore) eventId = await this._eventStore.storeEvent(this._standaloneSseStreamId, message); - const standaloneSse = this._streamMapping.get(this._standaloneSseStreamId); - if (standaloneSse === void 0) return; - if (standaloneSse.controller && standaloneSse.encoder && (eventId === void 0 || !standaloneSse.replayedEventIds?.has(eventId))) this.writeSSEEvent(standaloneSse.controller, standaloneSse.encoder, message, eventId); - return; - } - const streamId = this._requestToStreamMapping.get(requestId); - if (!streamId) throw new Error(`No connection established for request ID: ${String(requestId)}`); - let stream = this._streamMapping.get(streamId); - if (!this._enableJsonResponse) { - let eventId; - if (this._eventStore) { - eventId = await this._eventStore.storeEvent(streamId, message); - stream = this._streamMapping.get(streamId); - } - if (stream?.controller && stream?.encoder && (eventId === void 0 || !stream.replayedEventIds?.has(eventId))) this.writeSSEEvent(stream.controller, stream.encoder, message, eventId); - } - if (isJSONRPCResultResponse(message) || isJSONRPCErrorResponse(message)) { - this._requestResponseMap.set(requestId, message); - const relatedIds = [...this._requestToStreamMapping.entries()].filter(([_, sid]) => sid === streamId).map(([id]) => id); - if (relatedIds.every((id) => this._requestResponseMap.has(id))) { - if (!stream) { - if (this._enableJsonResponse) throw new Error(`No connection established for request ID: ${String(requestId)}`); - if (!this._eventStore) { - this.onerror?.(/* @__PURE__ */ new Error(`Response for request ID ${String(requestId)} is undeliverable: per-request stream is disconnected and no eventStore is configured`)); - for (const id of relatedIds) { - this._requestResponseMap.delete(id); - this._requestToStreamMapping.delete(id); - } - return; - } - for (const id of relatedIds) { - this._requestResponseMap.delete(id); - this._requestToStreamMapping.delete(id); - } - return; - } - if (this._enableJsonResponse && stream.resolveJson) { - const headers = { "Content-Type": "application/json" }; - if (this.sessionId !== void 0) headers["mcp-session-id"] = this.sessionId; - const responses = relatedIds.map((id) => this._requestResponseMap.get(id)); - if (responses.length === 1) stream.resolveJson(Response.json(responses[0], { - status: 200, - headers - })); - else stream.resolveJson(Response.json(responses, { - status: 200, - headers - })); - stream.cleanup(); - } else stream.cleanup(); - for (const id of relatedIds) { - this._requestResponseMap.delete(id); - this._requestToStreamMapping.delete(id); - } - } - } - } -}; - -//#endregion -//#region src/server/createMcpHandler.ts -/** -* The JSON-RPC id to echo on an entry-built error response: the body's `id` -* when the body is a single JSON-RPC request whose id is a string or number, -* `null` otherwise. Error responses must carry the id of the request they -* correspond to whenever it could be read; `null` is reserved for the cases -* where no single request id is determinable — unparseable bodies, body-less -* methods, notifications, posted responses and batch arrays. -*/ -function echoableRequestId(body) { - if (body === null || typeof body !== "object" || Array.isArray(body)) return null; - const { method, id } = body; - if (typeof method !== "string") return null; - return typeof id === "string" || typeof id === "number" ? id : null; -} -function jsonRpcErrorResponse(httpStatus, code, message, data, id = null) { - return Response.json({ - jsonrpc: "2.0", - error: { - code, - message, - ...data !== void 0 && { data } - }, - id - }, { status: httpStatus }); -} -function rejectionResponse(rejection, id = null) { - return jsonRpcErrorResponse(rejection.httpStatus, rejection.code, rejection.message, rejection.data, id); -} -function toError(value) { - return value instanceof Error ? value : new Error(String(value)); -} -function internalServerErrorResponse(id = null) { - return jsonRpcErrorResponse(500, -32603, "Internal server error", void 0, id); -} -/** -* The entry's default legacy serving (`legacy: 'stateless'`): per-request -* stateless serving of 2025-era traffic using the same factory as the modern -* path. Exported as a standalone building block for hand-wired compositions -* (for example mounting legacy stateless serving on its own route next to a -* strict modern endpoint). -* -* Each POST is served by a fresh instance from the factory connected to a -* fresh streamable HTTP transport constructed with only -* `sessionIdGenerator: undefined` — the established stateless idiom, unchanged. -* Because serving is per-request and stateless, GET and DELETE (2025 session -* operations) are answered with `405` / `Method not allowed.`, exactly like the -* canonical stateless example. -* -* The optional `onerror` callback receives factory and serving failures on -* this leg (reporting only — the response stays the 500 internal-error body). -* The entry passes its own `onerror` here when expanding the default, so -* legacy-leg failures are never silently swallowed. -*/ -function createLegacyStatelessFallback(factory, onerror, keepAliveMs) { - return async (request, options) => { - if (request.method.toUpperCase() !== "POST") return jsonRpcErrorResponse(405, -32e3, "Method not allowed."); - try { - const product = await factory({ - era: "legacy", - ...options?.authInfo !== void 0 && { authInfo: options.authInfo }, - requestInfo: request - }); - const transport = new WebStandardStreamableHTTPServerTransport({ - sessionIdGenerator: void 0, - ...keepAliveMs !== void 0 && { keepAliveMs } - }); - await product.connect(transport); - const teardown = () => { - transport.close().catch(() => {}); - product.close().catch(() => {}); - }; - request.signal?.addEventListener("abort", teardown, { once: true }); - const response = await transport.handleRequest(request, { - ...options?.authInfo !== void 0 && { authInfo: options.authInfo }, - ...options?.parsedBody !== void 0 && { parsedBody: options.parsedBody } - }); - if (response.body === null || mediaTypeEssence(response.headers.get("content-type")) !== "text/event-stream") { - teardown(); - return response; - } - const reader = response.body.getReader(); - let toreDown = false; - const completeExchange = () => { - if (!toreDown) { - toreDown = true; - teardown(); - } - }; - const monitoredBody = new ReadableStream({ - pull: async (controller) => { - try { - const { done, value } = await reader.read(); - if (done) { - completeExchange(); - controller.close(); - return; - } - if (value !== void 0) controller.enqueue(value); - } catch (error) { - completeExchange(); - controller.error(error); - } - }, - cancel: (reason) => { - completeExchange(); - return reader.cancel(reason).catch(() => {}); - } - }); - return new Response(monitoredBody, { - status: response.status, - statusText: response.statusText, - headers: response.headers - }); - } catch (error) { - try { - onerror?.(toError(error)); - } catch {} - return internalServerErrorResponse(echoableRequestId(options?.parsedBody)); - } - }; -} -function legacyStatelessFallback(factory, onerror) { - return createLegacyStatelessFallback(factory, onerror); -} -/** -* The entry's classification step: read the request body exactly once (unless -* a pre-parsed body is supplied) and classify the request with -* {@linkcode classifyInboundRequest}. This is the single code path behind both -* {@linkcode createMcpHandler}'s routing and the exported -* {@linkcode isLegacyRequest} predicate, so the two can never disagree. -* -* Pass `needsForward: false` when the caller never reads `forwardRequest` — -* the body-preserving clone is then skipped and `forwardRequest` is the -* (consumed) input request. -*/ -async function classifyEntryRequest(request, providedParsedBody, needsForward = true) { - const httpMethod = request.method.toUpperCase(); - let body; - let parsedBody = providedParsedBody; - let forwardRequest = request; - let unparseable = false; - if (httpMethod === "POST") { - if (parsedBody === void 0) { - if (needsForward) forwardRequest = request.clone(); - let bodyText; - try { - bodyText = await request.text(); - } catch { - return { step: "unreadable-body" }; - } - try { - body = bodyText.length === 0 ? void 0 : JSON.parse(bodyText); - } catch { - unparseable = true; - } - if (!unparseable && body !== void 0) parsedBody = body; - } else body = parsedBody; - if (unparseable || body === void 0) return { - step: "no-json-body", - forwardRequest - }; - } - return { - step: "classified", - outcome: classifyInboundRequest({ - httpMethod, - protocolVersionHeader: request.headers.get("mcp-protocol-version") ?? void 0, - mcpMethodHeader: request.headers.get("mcp-method") ?? void 0, - mcpNameHeader: request.headers.get("mcp-name") ?? void 0, - ...body !== void 0 && { body } - }), - body, - parsedBody, - forwardRequest - }; -} -/** -* Whether {@linkcode createMcpHandler} would route this request to its legacy -* (2025-era) serving rather than the modern (2026-07-28) path. -* -* Call it with just the request: `await isLegacyRequest(request)`. For a -* `POST` the body is read from an internal clone, so the request you pass -* stays fully readable for whichever handler you route it to — no second -* argument is needed. (In a Node `(req, res)` handler, build that `Request` -* with `toWebRequest(req)` from `@modelcontextprotocol/node`; behind a body -* parser, which has already drained the Node stream, build it as -* `toWebRequest(req, req.body)` so the bytes come from the parsed body — -* either way the predicate still takes just the request.) The optional -* `parsedBody` is a perf escape hatch for a body you already hold parsed: -* pass it and the predicate classifies from the value directly, reading and -* cloning nothing. It is needed, not just faster, when the request's own -* body was already read — the internal clone is then impossible (cloning a -* used body throws a `TypeError`), so such a single-argument call rejects -* instead of guessing. -* -* This is the entry's own classification step exported as a predicate — it -* runs exactly the code `createMcpHandler` runs to make the routing decision, -* not a re-implementation — so a hand-wired composition that branches on it -* can never disagree with the entry. It is classification only: hand-wired -* compositions must validate Content-Type themselves (415 for POSTs whose -* media type is not `application/json`, via {@linkcode isJsonContentType}) -* before dispatching either leg — routing the legacy leg into the SDK -* transports gets their built-in check, but a custom modern leg has none. Use it to keep an existing legacy -* deployment (for example a sessionful streamable HTTP wiring) serving 2025 -* traffic next to a strict modern endpoint, now that the entry has no -* handler-valued `legacy` option: -* -* ```ts -* import { createMcpHandler, isLegacyRequest } from '@modelcontextprotocol/server'; -* -* const modern = createMcpHandler(factory, { legacy: 'reject' }); -* -* export default { -* async fetch(request: Request): Promise { -* if (await isLegacyRequest(request)) { -* // e.g. an existing sessionful WebStandardStreamableHTTPServerTransport wiring -* return myExistingLegacyHandler(request); -* } -* return modern.fetch(request); -* } -* }; -* ``` -* -* Semantics (identical to the entry's routing): -* -* - Returns `true` only for requests with no per-request `_meta` envelope -* claim: claim-less POSTs (including the `initialize` handshake and 2025-era -* notification POSTs without a modern protocol-version header), body-less -* GET/DELETE session operations, all-legacy JSON-RPC batch arrays, posted -* JSON-RPC responses, and POSTs whose body is empty or not valid JSON. -* - Returns `false` for everything the modern path answers, including its -* validation-ladder rejections: a request carrying the envelope claim (even -* one naming a revision the endpoint does not serve — the modern path -* answers it with the unsupported-protocol-version error), a malformed -* envelope behind a present claim (answered `-32602`), a request whose -* `MCP-Protocol-Version` header names a modern revision but that lacks the -* envelope (`-32602`), and header/body mismatches (`-32020`). Consumers -* routing on the predicate must send `false` traffic to the modern handler, -* never to a legacy handler — the modern path owns those error answers. -* - `server/discover` probes sent by negotiating clients always carry the -* envelope claim, so they are never legacy; a hand-built claim-less POST to -* a method named `server/discover` has no claim and classifies legacy, -* exactly as the entry itself routes it. -*/ -async function isLegacyRequest(request, parsedBody) { - const classified = await classifyEntryRequest(parsedBody === void 0 && request.method.toUpperCase() === "POST" ? request.clone() : request, parsedBody, false); - return classified.step === "no-json-body" || classified.step === "classified" && classified.outcome.kind === "legacy"; -} -/** -* Creates an HTTP handler that serves the 2026-07-28 protocol revision from a -* per-request server factory and, by default, falls back to old-school -* stateless serving for 2025-era traffic. Pass `legacy: 'reject'` for a -* modern-only strict endpoint. -* -* Mounting: `handler.fetch` is the web-standard face (Cloudflare Workers, -* Deno, Bun, Hono's `c.req.raw`); for Express/Fastify/plain `node:http`, wrap -* the handler once with `toNodeHandler(handler)` from -* `@modelcontextprotocol/node`. When mounting bare on a fetch-native runtime, -* put Origin/Host validation in front of the handler — the entry itself is -* deliberately validation-free: -* -* ```ts -* import { hostHeaderValidationResponse, originValidationResponse, localhostAllowedHostnames, localhostAllowedOrigins } from '@modelcontextprotocol/server'; -* -* export default { -* async fetch(request: Request): Promise { -* const rejected = -* hostHeaderValidationResponse(request, localhostAllowedHostnames()) ?? -* originValidationResponse(request, localhostAllowedOrigins()); -* return rejected ?? handler.fetch(request); -* } -* }; -* ``` -* -* Use ONE factory for both legs: the same tools/resources/prompts definition -* backs the modern path and the stateless legacy fallback, so the two eras can -* never drift apart. To keep an existing legacy deployment (for example a -* sessionful streamable HTTP wiring) serving 2025 traffic instead of the -* stateless fallback, route in user land with {@linkcode isLegacyRequest} in -* front of a strict handler — see that predicate's documentation for the -* pattern. Power users composing transport-neutral routing can also use the -* exported building blocks directly: {@linkcode classifyInboundRequest} for -* the era decision and `PerRequestHTTPServerTransport` for single-exchange -* serving — such compositions must reject POSTs whose Content-Type media type -* is not `application/json` (415) before parsing the body, using -* {@linkcode isJsonContentType}; neither building block performs this -* validation itself. -* -* The entry performs no token verification: `authInfo` given to `fetch` is -* passed through to handlers and the factory as-is and is never derived from -* request headers. -*/ -function createMcpHandler(factory, options = {}) { - const { legacy, onerror, responseMode } = options; - if (typeof legacy === "function") throw new TypeError("The 'legacy' option only accepts 'stateless' or 'reject', not a handler function. To serve 2025-era traffic with your own handler, route in user land with the exported isLegacyRequest(request) predicate in front of a strict (legacy: 'reject') handler."); - /** Modern per-request instances with an exchange still in flight (close() tears these down). */ - const inflight = /* @__PURE__ */ new Set(); - let closed = false; - const reportError = (error) => { - try { - onerror?.(error); - } catch {} - }; - const bus = options.bus ?? new InMemoryServerEventBus(reportError); - const notify = createServerNotifier(bus); - const listenRouter = createListenRouter({ - bus, - maxSubscriptions: options.maxSubscriptions ?? DEFAULT_MAX_SUBSCRIPTIONS, - keepAliveMs: options.keepAliveMs ?? DEFAULT_SSE_KEEP_ALIVE_MS, - onerror: reportError - }); - if (responseMode === "json") console.warn("responseMode: 'json' drops mid-call notifications. subscriptions/listen streams are always served over SSE regardless; other notifications emitted before a result are dropped."); - const legacyHandler = legacy === "reject" ? void 0 : createLegacyStatelessFallback(factory, reportError, options.keepAliveMs); - async function serveModern(route, request, authInfo) { - const claimedRevision = route.classification.revision; - if (claimedRevision === void 0 || !SUPPORTED_MODERN_PROTOCOL_VERSIONS.includes(claimedRevision)) { - const error = new UnsupportedProtocolVersionError({ - supported: [...SUPPORTED_MODERN_PROTOCOL_VERSIONS], - requested: claimedRevision ?? "unknown" - }); - reportError(error); - return jsonRpcErrorResponse(400, error.code, error.message, error.data, echoableRequestId(route.message)); - } - const stdHeaderRejection = validateStandardRequestHeaders({ - httpMethod: request.method, - mcpMethodHeader: request.headers.get("mcp-method") ?? void 0, - mcpNameHeader: request.headers.get("mcp-name") ?? void 0 - }, route); - if (stdHeaderRejection !== void 0) { - reportError(/* @__PURE__ */ new Error(`Rejected inbound request (${stdHeaderRejection.cell}): ${stdHeaderRejection.message}`)); - return rejectionResponse(stdHeaderRejection, echoableRequestId(route.message)); - } - const meta = route.messageKind === "request" ? requestMetaOf(route.message.params) : void 0; - const declaredClientCapabilities = meta?.[CLIENT_CAPABILITIES_META_KEY]; - if (route.messageKind === "request") { - const required = requiredClientCapabilitiesForRequest(route.message.method); - if (required !== void 0) { - const missing = missingClientCapabilities(required, declaredClientCapabilities); - if (missing !== void 0) { - const error = new MissingRequiredClientCapabilityError({ requiredCapabilities: missing }); - reportError(error); - return jsonRpcErrorResponse(httpStatusForErrorCode(error.code, "ladder"), error.code, error.message, error.data, route.message.id); - } - } - } - const product = await factory({ - era: "modern", - ...authInfo !== void 0 && { authInfo }, - requestInfo: request - }); - const server = product instanceof McpServer ? product.server : product; - if (route.messageKind === "request" && route.message.method === "subscriptions/listen") { - const capabilities = server.getCapabilities(); - const serverInfo = serverIdentityOf(server); - product.close().catch(reportError); - return listenRouter.serve(route.message, request.signal, capabilities, serverInfo); - } - if (route.messageKind === "request" && route.message.method === "tools/call" && product instanceof McpServer) { - const callParams = route.message.params; - const toolName = typeof callParams?.name === "string" ? callParams.name : void 0; - const inputSchema = toolName === void 0 ? void 0 : product.toolInputSchemaJson(toolName); - if (inputSchema !== void 0) { - const scan = scanXMcpHeaderDeclarations(inputSchema); - if (scan.valid && scan.declarations.length > 0) { - const rejection = validateMcpParamHeaders(scan.declarations, callParams?.arguments, request.headers); - if (rejection !== void 0) { - product.close().catch(reportError); - reportError(/* @__PURE__ */ new Error(`Rejected inbound request (${rejection.cell}): ${rejection.message}`)); - return rejectionResponse(rejection, route.message.id); - } - } - } - } - setNegotiatedProtocolVersion(server, claimedRevision); - installModernOnlyHandlers(server, SUPPORTED_MODERN_PROTOCOL_VERSIONS); - if (meta !== void 0) seedClientIdentityFromEnvelope(server, { - clientInfo: meta[CLIENT_INFO_META_KEY], - clientCapabilities: declaredClientCapabilities - }); - const previousOnClose = server.onclose; - inflight.add(server); - server.onclose = () => { - inflight.delete(server); - previousOnClose?.(); - }; - try { - const response = await invoke(product, route.message, { - classification: route.classification, - request, - ...authInfo !== void 0 && { authInfo }, - ...responseMode !== void 0 && { responseMode }, - ...options.keepAliveMs !== void 0 && { keepAliveMs: options.keepAliveMs } - }); - if (route.messageKind === "notification") queueMicrotask(() => void server.close().catch(() => {})); - return response; - } catch (error) { - if (error instanceof SdkError && error.code === SdkErrorCode.ConnectionClosed) return new Response(null, { status: 499 }); - await server.close().catch(() => {}); - inflight.delete(server); - reportError(toError(error)); - return internalServerErrorResponse(echoableRequestId(route.message)); - } - } - async function serveLegacyRoute(route, forwardRequest, authInfo, parsedBody) { - if (legacyHandler !== void 0) return legacyHandler(forwardRequest, { - ...authInfo !== void 0 && { authInfo }, - ...parsedBody !== void 0 && { parsedBody } - }); - const strict = modernOnlyStrictRejection(route, SUPPORTED_MODERN_PROTOCOL_VERSIONS); - if (strict === void 0) return new Response(null, { status: 202 }); - reportError(/* @__PURE__ */ new Error(`Rejected 2025-era request on a modern-only endpoint (${strict.cell}): ${strict.message}`)); - return rejectionResponse(strict, echoableRequestId(parsedBody)); - } - async function handle(request, requestOptions) { - const authInfo = requestOptions?.authInfo; - if (request.method.toUpperCase() === "POST" && !isJsonContentType(request.headers.get("content-type"))) { - reportError(/* @__PURE__ */ new Error("Unsupported Media Type: Content-Type must be application/json")); - return jsonRpcErrorResponse(415, -32e3, "Unsupported Media Type: Content-Type must be application/json"); - } - const classified = await classifyEntryRequest(request, requestOptions?.parsedBody); - if (classified.step === "unreadable-body") return jsonRpcErrorResponse(400, -32700, "Parse error: the request body could not be read"); - if (classified.step === "no-json-body") { - if (legacyHandler !== void 0) return legacyHandler(classified.forwardRequest, { ...authInfo !== void 0 && { authInfo } }); - return jsonRpcErrorResponse(400, -32700, "Parse error: the request body is not valid JSON"); - } - const { outcome, body, parsedBody, forwardRequest } = classified; - try { - switch (outcome.kind) { - case "reject": - reportError(/* @__PURE__ */ new Error(`Rejected inbound request (${outcome.cell}): ${outcome.message}`)); - return rejectionResponse(outcome, echoableRequestId(body)); - case "modern": return await serveModern(outcome, request, authInfo); - case "legacy": return await serveLegacyRoute(outcome, forwardRequest, authInfo, parsedBody); - } - } catch (error) { - reportError(toError(error)); - return internalServerErrorResponse(echoableRequestId(body)); - } - } - const fetchFace = async (request, requestOptions) => { - if (closed) throw new Error("This MCP handler has been closed"); - try { - return await handle(request, requestOptions); - } catch (error) { - reportError(toError(error)); - return internalServerErrorResponse(echoableRequestId(requestOptions?.parsedBody)); - } - }; - return { - fetch: fetchFace, - notify, - bus, - close: async () => { - closed = true; - listenRouter.closeAll(); - const closing = [...inflight].map((server) => server.close().catch(() => {})); - inflight.clear(); - await Promise.all(closing); - } - }; -} - -//#endregion -//#region src/server/middleware/bearerAuth.ts -function headerQuotedValue(value) { - return value.replaceAll(/[\\"]/g, String.raw`\$&`).replaceAll(/[^\u0020-\u007E]/g, " "); -} -function buildWwwAuthenticateHeader(errorCode, description, requiredScopes, resourceMetadataUrl) { - let header = `Bearer error="${headerQuotedValue(errorCode)}", error_description="${headerQuotedValue(description)}"`; - if (requiredScopes.length > 0) header += `, scope="${requiredScopes.join(" ")}"`; - if (resourceMetadataUrl) header += `, resource_metadata="${resourceMetadataUrl}"`; - return header; -} -/** -* Validate a raw `Authorization` header value as a Bearer token and return -* the verified {@link AuthInfo}. -* -* The runtime-neutral core of Bearer authentication: it parses the header, -* runs the verifier, enforces `requiredScopes`, and rejects tokens without an -* expiration or past it. On any failure it throws an {@link OAuthError} — -* pass that to {@link bearerAuthChallengeResponse} for the matching HTTP -* answer, or use {@link requireBearerAuth} to get both steps as one call. -* -* Framework adapters build on this: `requireBearerAuth` from -* `@modelcontextprotocol/express` feeds it `req.headers.authorization`. -*/ -async function verifyBearerToken(authorizationHeader, options) { - const { verifier, requiredScopes = [] } = options; - if (!authorizationHeader) throw new OAuthError(OAuthErrorCode.InvalidToken, "Missing Authorization header"); - const [type, token] = authorizationHeader.split(" "); - if (type?.toLowerCase() !== "bearer" || !token) throw new OAuthError(OAuthErrorCode.InvalidToken, "Invalid Authorization header format, expected 'Bearer TOKEN'"); - const authInfo = await verifier.verifyAccessToken(token); - if (requiredScopes.length > 0) { - if (!requiredScopes.every((scope) => authInfo.scopes.includes(scope))) throw new OAuthError(OAuthErrorCode.InsufficientScope, "Insufficient scope"); - } - if (typeof authInfo.expiresAt !== "number" || Number.isNaN(authInfo.expiresAt)) throw new OAuthError(OAuthErrorCode.InvalidToken, "Token has no expiration time"); - else if (authInfo.expiresAt < Date.now() / 1e3) throw new OAuthError(OAuthErrorCode.InvalidToken, "Token has expired"); - return authInfo; -} -/** -* Build the HTTP answer for a Bearer authentication failure. -* -* Maps an {@link OAuthError} to its status — `401` for `invalid_token` and -* `403` for `insufficient_scope` (both carrying the `WWW-Authenticate: Bearer …` -* challenge, with `resource_metadata` when configured so clients can discover -* the Authorization Server), `500` for `server_error`, `400` for anything -* else. A non-`OAuthError` value answers `500 server_error`. The body is the -* OAuth error JSON. -*/ -function bearerAuthChallengeResponse(error, options) { - const { requiredScopes = [], resourceMetadataUrl } = options ?? {}; - if (!(error instanceof OAuthError)) { - const serverError = new OAuthError(OAuthErrorCode.ServerError, "Internal Server Error"); - return Response.json(serverError.toResponseObject(), { status: 500 }); - } - switch (error.code) { - case OAuthErrorCode.InvalidToken: { - const challenge = buildWwwAuthenticateHeader(error.code, error.message, requiredScopes, resourceMetadataUrl); - return Response.json(error.toResponseObject(), { - status: 401, - headers: { "WWW-Authenticate": challenge } - }); - } - case OAuthErrorCode.InsufficientScope: { - const challenge = buildWwwAuthenticateHeader(error.code, error.message, requiredScopes, resourceMetadataUrl); - return Response.json(error.toResponseObject(), { - status: 403, - headers: { "WWW-Authenticate": challenge } - }); - } - case OAuthErrorCode.ServerError: return Response.json(error.toResponseObject(), { status: 500 }); - default: return Response.json(error.toResponseObject(), { status: 400 }); - } -} -/** -* Require a valid Bearer token on web-standard requests. -* -* The framework-free counterpart of `requireBearerAuth` from -* `@modelcontextprotocol/express`, for hosts whose HTTP surface is a -* `fetch(request)` handler — Cloudflare Workers, Deno, Bun, Hono. The -* returned gate resolves to the verified {@link AuthInfo}, or to the -* ready-to-return challenge `Response` when the request must be refused. -* -* @example -* ```ts source="./bearerAuth.examples.ts#requireBearerAuth_fetchGate" -* const gate = requireBearerAuth({ verifier, requiredScopes: ['mcp'] }); -* -* async function fetchHandler(request: Request): Promise { -* const auth: AuthInfo | Response = await gate(request); -* if (auth instanceof Response) return auth; -* return handler.fetch(request, { authInfo: auth }); -* } -* ``` -*/ -function requireBearerAuth(options) { - const { verifier, requiredScopes = [], resourceMetadataUrl } = options; - const resolved = { - verifier, - requiredScopes, - resourceMetadataUrl - }; - return async (request) => { - const [authorizationHeader] = (request.headers.get("authorization") ?? "").split(","); - try { - return await verifyBearerToken(authorizationHeader || void 0, resolved); - } catch (error) { - return bearerAuthChallengeResponse(error, resolved); - } - }; -} - -//#endregion -//#region src/server/middleware/hostHeaderValidation.ts -/** -* Parse and validate a `Host` header against an allowlist of hostnames (port-agnostic). -* -* - Input host header may include a port (e.g. `localhost:3000`) or IPv6 brackets (e.g. `[::1]:3000`). -* - Allowlist items should be hostnames only (no ports). For IPv6, include brackets (e.g. `[::1]`). -*/ -function validateHostHeader(hostHeader, allowedHostnames) { - if (!hostHeader) return { - ok: false, - errorCode: "missing_host", - message: "Missing Host header" - }; - let hostname; - try { - hostname = new URL(`http://${hostHeader}`).hostname; - } catch { - return { - ok: false, - errorCode: "invalid_host_header", - message: `Invalid Host header: ${hostHeader}`, - hostHeader - }; - } - if (!allowedHostnames.includes(hostname)) return { - ok: false, - errorCode: "invalid_host", - message: `Invalid Host: ${hostname}`, - hostHeader, - hostname - }; - return { - ok: true, - hostname - }; -} -/** -* Convenience allowlist for `localhost` DNS rebinding protection. -*/ -function localhostAllowedHostnames() { - return [ - "localhost", - "127.0.0.1", - "[::1]" - ]; -} -/** -* Web-standard `Request` helper for DNS rebinding protection. -* @example -* ```ts source="./hostHeaderValidation.examples.ts#hostHeaderValidationResponse_basicUsage" -* const result = validateHostHeader(req.headers.get('host'), ['localhost']); -* ``` -*/ -function hostHeaderValidationResponse(req, allowedHostnames) { - const result = validateHostHeader(req.headers.get("host"), allowedHostnames); - if (result.ok) return void 0; - return Response.json({ - jsonrpc: "2.0", - error: { - code: -32e3, - message: result.message - }, - id: null - }, { - status: 403, - headers: { "Content-Type": "application/json" } - }); -} - -//#endregion -//#region src/server/middleware/oauthMetadata.ts -function checkIssuerUrl(issuer, allowInsecure) { - if (issuer.protocol !== "https:" && issuer.hostname !== "localhost" && issuer.hostname !== "127.0.0.1" && !allowInsecure) throw new Error("Issuer URL must be HTTPS"); - if (issuer.hash) throw new Error(`Issuer URL must not have a fragment: ${issuer}`); - if (issuer.search) throw new Error(`Issuer URL must not have a query string: ${issuer}`); -} -/** -* Derive the RFC 9728 Protected Resource Metadata document from -* {@link AuthMetadataOptions}, validating the Authorization Server issuer URL -* (HTTPS required outside localhost) in the process. -* -* `oauthMetadataResponse` and the Express `mcpAuthMetadataRouter` both build -* on this; use it directly when serving the document through your own -* routing — or call it once at startup to fail fast on a misconfigured -* issuer before any request arrives. -*/ -function buildOAuthProtectedResourceMetadata(options) { - checkIssuerUrl(new URL(options.oauthMetadata.issuer), options.dangerouslyAllowInsecureIssuerUrl); - return { - resource: options.resourceServerUrl.href, - authorization_servers: [options.oauthMetadata.issuer], - scopes_supported: options.scopesSupported, - resource_name: options.resourceName, - resource_documentation: options.serviceDocumentationUrl?.href - }; -} -/** -* Builds the RFC 9728 Protected Resource Metadata URL for a given MCP server -* URL by inserting `/.well-known/oauth-protected-resource` ahead of the path. -* -* @example -* ```ts -* getOAuthProtectedResourceMetadataUrl(new URL('https://api.example.com/mcp')) -* // → 'https://api.example.com/.well-known/oauth-protected-resource/mcp' -* ``` -*/ -function getOAuthProtectedResourceMetadataUrl(serverUrl) { - return new URL(protectedResourceMetadataPath(serverUrl), serverUrl).href; -} -/** The RFC 9728 path-aware well-known path for a resource URL. */ -function protectedResourceMetadataPath(resourceServerUrl) { - const rsPath = stripTrailingSlash(resourceServerUrl.pathname); - return `/.well-known/oauth-protected-resource${rsPath === "/" ? "" : rsPath}`; -} -function stripTrailingSlash(path) { - return path.length > 1 && path.endsWith("/") ? path.slice(0, -1) : path; -} -const ALLOWED_METHODS = "GET, HEAD, OPTIONS"; -function metadataDocumentResponse(request, metadata) { - if (request.method === "OPTIONS") { - const requestedHeaders = request.headers.get("access-control-request-headers"); - return new Response(null, { - status: 204, - headers: { - "Access-Control-Allow-Origin": "*", - "Access-Control-Allow-Methods": ALLOWED_METHODS, - ...requestedHeaders === null ? {} : { - "Access-Control-Allow-Headers": requestedHeaders, - Vary: "Access-Control-Request-Headers" - } - } - }); - } - if (request.method !== "GET" && request.method !== "HEAD") { - const error = new OAuthError(OAuthErrorCode.MethodNotAllowed, `The method ${request.method} is not allowed for this endpoint`); - return Response.json(error.toResponseObject(), { - status: 405, - headers: { - Allow: ALLOWED_METHODS, - "Access-Control-Allow-Origin": "*" - } - }); - } - const response = Response.json(metadata, { headers: { "Access-Control-Allow-Origin": "*" } }); - return request.method === "HEAD" ? new Response(null, { - status: response.status, - headers: response.headers - }) : response; -} -/** -* Serve the two OAuth discovery documents an MCP server acting as a Resource -* Server exposes, from a web-standard `fetch(request)` handler: -* -* - `/.well-known/oauth-protected-resource[/]` — RFC 9728 Protected -* Resource Metadata, derived from the supplied options (path-aware: the -* resource URL's path is reflected in the route). -* - `/.well-known/oauth-authorization-server` — RFC 8414 Authorization -* Server Metadata, passed through verbatim. -* -* Returns the matched document `Response` (JSON with permissive CORS, `405` -* with an `Allow` header for non-GET methods, `204` for CORS preflight), or -* `undefined` when the request path is neither well-known route — fall -* through to your own routing. The framework-free counterpart of -* `mcpAuthMetadataRouter` from `@modelcontextprotocol/express`; pair it with -* `requireBearerAuth` and `getOAuthProtectedResourceMetadataUrl` so -* unauthenticated clients can discover the AS from the `401` challenge. -* -* @example -* ```ts source="./oauthMetadata.examples.ts#oauthMetadataResponse_fetchHandler" -* async function fetchHandler(request: Request): Promise { -* return oauthMetadataResponse(request, options) ?? serveMcp(request); -* } -* ``` -*/ -function oauthMetadataResponse(request, options) { - const requestPath = stripTrailingSlash(new URL(request.url).pathname); - if (requestPath === protectedResourceMetadataPath(options.resourceServerUrl)) return metadataDocumentResponse(request, buildOAuthProtectedResourceMetadata(options)); - if (requestPath === "/.well-known/oauth-authorization-server") { - buildOAuthProtectedResourceMetadata(options); - return metadataDocumentResponse(request, options.oauthMetadata); - } -} - -//#endregion -//#region src/server/middleware/originValidation.ts -/** -* Validate an `Origin` header against an allowlist of hostnames (port-agnostic). -* -* - A missing/empty `Origin` header passes: non-browser clients do not send one, -* and only browser-originated requests carry the header this check defends against. -* - Allowlist items are hostnames only (no scheme, no port), the same convention as -* `validateHostHeader`. For IPv6, include brackets (e.g. `[::1]`). -* - Any present value that cannot be parsed as an origin URL — including the literal -* `null` origin browsers send for opaque contexts — is rejected (deny on failure). -*/ -function validateOriginHeader(originHeader, allowedOriginHostnames) { - if (originHeader === null || originHeader === void 0 || originHeader === "") return { ok: true }; - let hostname; - try { - hostname = new URL(originHeader).hostname; - } catch { - return { - ok: false, - errorCode: "invalid_origin_header", - message: `Invalid Origin header: ${originHeader}`, - originHeader - }; - } - if (hostname === "") return { - ok: false, - errorCode: "invalid_origin_header", - message: `Invalid Origin header: ${originHeader}`, - originHeader - }; - if (!allowedOriginHostnames.includes(hostname)) return { - ok: false, - errorCode: "invalid_origin", - message: `Invalid Origin: ${hostname}`, - originHeader, - hostname - }; - return { - ok: true, - origin: originHeader, - hostname - }; -} -/** -* Convenience allowlist of localhost-class origin hostnames, mirroring -* `localhostAllowedHostnames`. -*/ -function localhostAllowedOrigins() { - return [ - "localhost", - "127.0.0.1", - "[::1]" - ]; -} -/** -* Web-standard `Request` helper for Origin validation: returns a `403` JSON-RPC -* error response when the request's `Origin` header is not allowed, and -* `undefined` when the request may proceed. -* -* ```ts -* const rejected = originValidationResponse(request, localhostAllowedOrigins()); -* if (rejected) return rejected; -* ``` -*/ -function originValidationResponse(req, allowedOriginHostnames) { - const result = validateOriginHeader(req.headers.get("origin"), allowedOriginHostnames); - if (result.ok) return void 0; - return Response.json({ - jsonrpc: "2.0", - error: { - code: -32e3, - message: result.message - }, - id: null - }, { - status: 403, - headers: { "Content-Type": "application/json" } - }); -} - -//#endregion -//#region src/server/requestStateCodec.ts -const PREFIX = "v1."; -function bytesToBase64Url(bytes) { - let bin = ""; - for (const b of bytes) bin += String.fromCodePoint(b); - return btoa(bin).replaceAll("+", "-").replaceAll("/", "_").replace(/=+$/, ""); -} -function constantTimeTagEqual(a, b) { - if (a.length !== b.length) return false; - let r = 0; - for (let i = 0; i < a.length; i++) r |= a.codePointAt(i) ^ b.codePointAt(i); - return r === 0; -} -function base64UrlToBytes(s) { - const b64 = s.replaceAll("-", "+").replaceAll("_", "/"); - const bin = atob(b64); - const bytes = new Uint8Array(bin.length); - for (let i = 0; i < bin.length; i++) bytes[i] = bin.codePointAt(i); - return bytes; -} -/** -* Create an opt-in HMAC-SHA256 codec for the multi-round-trip `requestState` -* (protocol revision 2026-07-28). -* -* `requestState` round-trips through the client and is attacker-controlled -* input on re-entry. The SDK applies no protection of its own; this helper is -* the convenience implementation of the spec's integrity MUST so authors don't -* hand-roll HMAC. Wire shape: -* -* "v1." b64url({"p":,"exp":,"b":?}) "." b64url(mac) -* -* where `bindTag` is `b64url(HMAC(key, "mcp.requestState.bind:" + bind(ctx))[:16])` -* — the binding value is never embedded raw. -* -* The codec is **signed, not encrypted**: the body is integrity-protected but -* the client can base64url-decode it and read the payload (`p`) in clear. Do -* not put secrets in the payload; use an AEAD construction if confidentiality -* is required. The handler reads its payload back via the typed -* `ctx.mcpReq.requestState()` accessor — the seam has already run `verify` -* (integrity proven, payload decoded) by the time the handler is entered. -* -* Verification is fail-closed and constant-time (WebCrypto `subtle.verify` for -* the body MAC; a fixed-length XOR-accumulator compare for the bind tag). -* See `examples/mrtr/server.ts` for a worked end-to-end example. -* -* Design comparison (mcp.d `secureRequestState`, the peer SDK's reference -* implementation): mcp.d additionally offers an AES-256-GCM encrypted mode and -* derives independent cipher / bind-HMAC sub-keys from the operator secret via -* HKDF-SHA256, with an auto-generated per-process ephemeral key when none is -* supplied. This codec deliberately ships only the signed mode and a single -* keyed HMAC (domain-separated by input prefix) — HKDF sub-key derivation and -* an encrypted mode are intentionally out of scope for the initial release. -*/ -function createRequestStateCodec(options) { - const subtle = globalThis.crypto?.subtle; - if (subtle === void 0) throw new TypeError("createRequestStateCodec requires the Web Crypto API (globalThis.crypto.subtle); see https://ts.sdk.modelcontextprotocol.io/v2/troubleshooting for the Node.js polyfill instructions"); - const keyBytes = typeof options.key === "string" ? new TextEncoder().encode(options.key) : Uint8Array.from(options.key); - if (keyBytes.byteLength < 32) throw new RangeError(`createRequestStateCodec: key must be at least 32 bytes (got ${keyBytes.byteLength})`); - const ttlSeconds = options.ttlSeconds ?? 600; - if (!Number.isFinite(ttlSeconds)) throw new RangeError("createRequestStateCodec: ttlSeconds must be a finite number"); - const bind = options.bind; - let cryptoKey; - const importedKey = () => cryptoKey ??= subtle.importKey("raw", keyBytes, { - name: "HMAC", - hash: "SHA-256" - }, false, ["sign", "verify"]); - const utf8 = new TextEncoder(); - const BIND_LABEL = "mcp.requestState.bind:"; - const bindTag = async (value) => { - return bytesToBase64Url(new Uint8Array(await subtle.sign("HMAC", await importedKey(), utf8.encode(BIND_LABEL + value))).slice(0, 16)); - }; - return { - async mint(payload, ctx) { - const envelope = { - p: payload, - exp: Math.floor(Date.now() / 1e3) + ttlSeconds - }; - if (bind !== void 0) { - if (ctx === void 0) throw new TypeError("createRequestStateCodec: mint() requires ctx when a bind callback is configured"); - envelope.b = await bindTag(bind(ctx)); - } - const body = bytesToBase64Url(utf8.encode(JSON.stringify(envelope))); - return `${PREFIX}${body}.${bytesToBase64Url(new Uint8Array(await subtle.sign("HMAC", await importedKey(), utf8.encode(PREFIX + body))))}`; - }, - async verify(state, ctx) { - const dot = state.lastIndexOf("."); - if (!state.startsWith(PREFIX) || dot <= 3) throw new Error("malformed"); - const body = state.slice(3, dot); - let macBytes; - try { - macBytes = base64UrlToBytes(state.slice(dot + 1)); - } catch { - throw new Error("malformed"); - } - if (!await subtle.verify("HMAC", await importedKey(), macBytes, utf8.encode(PREFIX + body))) throw new Error("mac"); - let envelope; - try { - envelope = JSON.parse(new TextDecoder("utf-8", { fatal: true }).decode(base64UrlToBytes(body))); - } catch { - throw new Error("malformed"); - } - if (typeof envelope.exp !== "number" || envelope.exp < Math.floor(Date.now() / 1e3)) throw new Error("expired"); - if (bind !== void 0) { - const expected = await bindTag(bind(ctx)); - if (envelope.b === void 0 || !constantTimeTagEqual(envelope.b, expected)) throw new Error("bind"); - } else if (envelope.b !== void 0) throw new Error("bind"); - return envelope.p; - } - }; -} - -//#endregion -//#region src/fromJsonSchema.ts -let _defaultValidator; -function dist_fromJsonSchema(schema, validator) { - return fromJsonSchema$1(schema, validator ?? (_defaultValidator ??= new DefaultJsonSchemaValidator())); -} - -//#endregion - -//# sourceMappingURL=index.mjs.map -const mcpApps = Object.freeze([]); - -/* export default */ const mcp_status_073c1634_0 = (mcpApps); - -// Generated by agent-bundle. Do not edit. -const meta_name = "mcp-app-example"; -const packageName = "@agent-bundle-example/mcp-app"; -const packageVersion = undefined; -const meta_version = "1.0.0"; -const meta_meta = Object.freeze({ - name: meta_name, - packageName: packageName, - packageVersion: packageVersion, - version: meta_version -}); -/* export default */ const _agent_bundle_virtual_meta = ((/* unused pure expression or super */ null && (meta_meta))); - -const healthyCompilerStatus = Object.freeze({ - checks: Object.freeze([ - Object.freeze({ - label: 'Availability', - status: 'passing' - }), - Object.freeze({ - label: 'Build queue', - status: 'passing' - }) - ]), - service: 'compiler', - status: 'healthy', - summary: 'Compiler service is ready for release.' -}); -const isRecord = (value)=>value !== null && typeof value === 'object' && !Array.isArray(value); -const isHealthyCompilerFixture = (value)=>{ - if (!isRecord(value) || value.service !== healthyCompilerStatus.service || value.status !== healthyCompilerStatus.status || value.summary !== healthyCompilerStatus.summary || !Array.isArray(value.checks) || value.checks.length !== healthyCompilerStatus.checks.length) { - return false; - } - return healthyCompilerStatus.checks.every((expected, index)=>{ - const received = value.checks[index]; - return isRecord(received) && received.label === expected.label && received.status === expected.status; - }); -}; - - - - - - -const app = mcp_status_073c1634_0["0"]; -if (app === undefined) throw new Error('Expected the status MCP App.'); -const serviceCatalog = Object.freeze({ - compiler: healthyCompilerStatus, - 'payments-api': Object.freeze({ - checks: Object.freeze([ - Object.freeze({ - label: 'Availability', - status: 'passing' - }), - Object.freeze({ - label: 'P95 latency', - status: 'failing' - }) - ]), - service: 'payments-api', - status: 'degraded', - summary: 'Payment latency is above the release threshold.' - }) -}); -const createStatusServer = ()=>{ - // The compiler stamps this project's identity into `agent-bundle/meta`, so - // the wire identity cannot drift from the config or package.json. - const server = new mcp_DXXb3Vv3_McpServer({ - name: meta_name, - version: (/* inlined export .version */"1.0.0") - }); - server.registerResource(app.name, app.resourceUri, { - _meta: { - ui: { - resourceUri: app.resourceUri - } - }, - mimeType: app.mimeType - }, async (uri)=>({ - contents: [ - { - mimeType: app.mimeType, - text: app.html, - uri: uri.href - } - ] - })); - server.registerTool('show-status', { - _meta: { - ui: { - resourceUri: app.resourceUri - } - }, - description: 'Show the health of one example service.', - inputSchema: schemas_object({ - service: schemas_enum([ - 'compiler', - 'payments-api' - ]) - }) - }, async ({ service })=>{ - const result = serviceCatalog[service]; - return { - _meta: { - ui: { - resourceUri: app.resourceUri - } - }, - content: [ - { - text: result.summary, - type: 'text' - } - ], - structuredContent: result - }; - }); - return server; -}; -/** - * Default-exported server factory: `agent-bundle build` detects it and wraps - * this entry in the framework stdio lifecycle shell (console-to-stderr guard, - * SIGINT/SIGTERM handling, stdin-EOF exit, bounded shutdown, heartbeat). - */ /* export default */ const mcp_status = (createStatusServer); - - - - - -//#region src/server/stdio.ts -/** -* Server transport for stdio: this communicates with an MCP client by reading from the current process' `stdin` and writing to `stdout`. -* -* This transport is only available in Node.js environments. -* -* @example -* ```ts source="./stdio.examples.ts#StdioServerTransport_basicUsage" -* const server = new McpServer({ name: 'my-server', version: '1.0.0' }); -* const transport = new StdioServerTransport(); -* await server.connect(transport); -* ``` -*/ -var stdio_StdioServerTransport = class { - _readBuffer; - _started = false; - _closed = false; - constructor(_stdin = node_process.stdin, _stdout = node_process.stdout, options) { - this._stdin = _stdin; - this._stdout = _stdout; - this._readBuffer = new ReadBuffer({ maxBufferSize: options?.maxBufferSize }); - } - onclose; - onerror; - onmessage; - _ondata = (chunk) => { - try { - this._readBuffer.append(chunk); - this.processReadBuffer(); - } catch (error) { - this.onerror?.(error); - this.close().catch(() => {}); - } - }; - _onerror = (error) => { - this.onerror?.(error); - }; - _onstdouterror = (error) => { - this.onerror?.(error); - this.close().catch(() => {}); - }; - /** - * Starts listening for messages on `stdin`. - */ - async start() { - if (this._started) throw new Error("StdioServerTransport already started! If using Server class, note that connect() calls start() automatically."); - this._started = true; - this._stdin.on("data", this._ondata); - this._stdin.on("error", this._onerror); - this._stdout.on("error", this._onstdouterror); - } - processReadBuffer() { - while (true) try { - const message = this._readBuffer.readMessage(); - if (message === null) break; - this.onmessage?.(message); - } catch (error) { - this.onerror?.(error); - } - } - async close() { - if (this._closed) return; - this._closed = true; - this._stdin.off("data", this._ondata); - this._stdin.off("error", this._onerror); - this._stdout.off("error", this._onstdouterror); - if (this._stdin.listenerCount("data") === 0) this._stdin.pause(); - this._readBuffer.clear(); - this.onclose?.(); - } - send(message) { - if (this._closed) return Promise.reject(/* @__PURE__ */ new Error("StdioServerTransport is closed")); - return new Promise((resolve, reject) => { - const json = serializeMessage(message); - let settled = false; - const onError = (error) => { - if (settled) return; - settled = true; - this._stdout.off("error", onError); - this._stdout.off("drain", onDrain); - reject(error); - }; - const onDrain = () => { - if (settled) return; - settled = true; - this._stdout.off("error", onError); - this._stdout.off("drain", onDrain); - resolve(); - }; - this._stdout.once("error", onError); - if (this._stdout.write(json)) { - if (settled) return; - settled = true; - this._stdout.off("error", onError); - resolve(); - } else if (!settled) this._stdout.once("drain", onDrain); - }); - } -}; - -//#endregion -//#region src/server/serveStdio.ts -/** -* How long the probe-discard path waits for the probe instance to answer the -* requests it was delivered before closing it. The wait normally settles as -* soon as the DiscoverResult is handed to the wire (or immediately, when a -* delivered cancellation already settled the probe); the bound is a backstop -* so no edge can ever hold the connection's inbound pump indefinitely behind -* the discard. -*/ -const DISCARD_ANSWER_TIMEOUT_MS = 3e3; -/** -* The transport a pinned instance is connected to: a thin channel that writes -* through to the entry-owned wire transport and receives the messages the -* entry forwards. The wire transport itself is never handed to an instance — -* that is what lets the entry discard an optimistic probe instance (close the -* channel) without tearing down the connection. -*/ -var StdioConnectionChannel = class { - onclose; - onerror; - onmessage; - _closed = false; - /** Request ids the entry delivered to the instance that the instance has not yet answered. */ - _pendingRequests = /* @__PURE__ */ new Set(); - _drainWaiters = []; - constructor(_wire, _onInstanceClose, _outboundIntercept) { - this._wire = _wire; - this._onInstanceClose = _onInstanceClose; - this._outboundIntercept = _outboundIntercept; - } - async start() {} - async send(message, options) { - if (isJSONRPCResultResponse(message) || isJSONRPCErrorResponse(message)) { - const { id } = message; - if (id !== void 0) this._settle(id); - } - if (this._closed) return; - if (this._outboundIntercept?.(message) === "handled") return; - return this._wire.send(message, options); - } - setProtocolVersion = (version) => { - this._wire.setProtocolVersion?.(version); - }; - /** Forwards one inbound message to the connected instance. */ - deliver(message, extra) { - if (this._closed) return; - if (isJSONRPCRequest(message)) this._pendingRequests.add(message.id); - else if (isJSONRPCNotification(message) && message.method === "notifications/cancelled") { - const cancelledId = message.params?.requestId; - if (cancelledId !== void 0) this._settle(cancelledId); - } - this.onmessage?.(message, extra); - } - /** - * Resolves once every request delivered to the instance has been answered - * through {@linkcode send}, settled by a delivered cancellation, or the - * channel has been closed and nothing further can be answered. The wait is - * bounded by `timeoutMs` as a backstop so no edge can hold the caller - * indefinitely; resolves `false` only when the bound elapsed with requests - * still unanswered. Used by the probe-discard path so a probe request the - * entry accepted is never silently dropped. - */ - async whenRequestsAnswered(timeoutMs) { - if (this._closed || this._pendingRequests.size === 0) return true; - return await new Promise((resolve) => { - const waiter = () => { - clearTimeout(timer); - resolve(true); - }; - const timer = setTimeout(() => { - this._drainWaiters = this._drainWaiters.filter((pending) => pending !== waiter); - resolve(false); - }, timeoutMs); - this._drainWaiters.push(waiter); - }); - } - async close() { - if (this._closed) return; - this._closed = true; - this._pendingRequests.clear(); - this._releaseDrainWaiters(); - try { - this._onInstanceClose(); - } finally { - this.onclose?.(); - } - } - _settle(id) { - this._pendingRequests.delete(id); - if (this._pendingRequests.size === 0) this._releaseDrainWaiters(); - } - _releaseDrainWaiters() { - const waiters = this._drainWaiters; - this._drainWaiters = []; - for (const waiter of waiters) waiter(); - } -}; -/** -* Classifies one message of the opening exchange with the same body-primary -* rules the HTTP entry applies per request: `initialize` is the legacy -* handshake unless it carries a valid modern envelope claim; a present claim -* is validated (never silently ignored); a claim-less message is 2025-era -* traffic. There is no header layer on stdio, so the body is the only signal. -*/ -function classifyOpeningMessage(message) { - const params = message.params; - if (message.method === "initialize" && !carriesValidModernEnvelopeClaim(params)) { - const requestedVersion = params !== null && typeof params === "object" && typeof params.protocolVersion === "string" ? params.protocolVersion : void 0; - return { - kind: "legacy", - reason: "initialize", - ...requestedVersion !== void 0 && { requestedVersion } - }; - } - if (!hasEnvelopeClaim(params)) return { - kind: "legacy", - reason: "no-claim" - }; - const meta = requestMetaOf(params); - const firstIssue = (meta === void 0 ? [] : validateEnvelopeMeta(meta))[0]; - if (firstIssue !== void 0) return { - kind: "invalid-envelope", - issue: firstIssue - }; - const claimedVersion = envelopeClaimVersion(params); - if (claimedVersion === void 0 || !SUPPORTED_MODERN_PROTOCOL_VERSIONS.includes(claimedVersion)) return { - kind: "unsupported-revision", - requested: claimedVersion ?? "unknown" - }; - return { - kind: "modern", - revision: claimedVersion, - classification: { - era: "modern", - revision: claimedVersion - } - }; -} -/** -* Serves MCP over stdio from a server factory, owning the era decision for -* the connection: the opening exchange selects the era, ONE instance from the -* factory is pinned for the connection lifetime, and everything after passes -* straight through to it. See the module documentation for the opening rules. -* -* ```ts -* import { serveStdio } from '@modelcontextprotocol/server/stdio'; -* -* serveStdio(() => { -* const server = new McpServer({ name: 'my-server', version: '1.0.0' }, { capabilities: { tools: {} } }); -* // register tools/resources/prompts once — the same factory serves both eras -* return server; -* }); -* ``` -*/ -function serveStdio(factory, options = {}) { - const legacyMode = options.legacy ?? "serve"; - const wire = options.transport ?? new stdio_StdioServerTransport(); - let state = { phase: "opening" }; - /** Channel currently being discarded (its close must not tear the connection down). */ - let discarding; - let closing = false; - /** - * Whether the connection has been torn down (`handle.close()` or the wire - * closing). The opening arms re-check this after every await: a close can - * race factory construction, and the continuation must neither resurrect - * the connection state nor keep a late-resolved instance around. - */ - const isTornDown = () => closing || state.phase === "closed"; - const reportError = (error) => { - try { - options.onerror?.(error); - } catch {} - }; - const writeErrorResponse = (id, code, message, data) => wire.send({ - jsonrpc: "2.0", - id, - error: { - code, - message, - ...data !== void 0 && { data } - } - }).catch((error) => reportError(stdio_toError(error))); - /** - * Entry-handled `subscriptions/listen` for this connection: holds the - * active subscriptions, serves inbound listen / cancelled-of-listen - * before the pinned instance is consulted, and rewrites the instance's - * outbound change notifications onto the active subscriptions. Only - * consulted on a modern-pinned connection — on a legacy connection - * change notifications pass straight through (the 2025 unsolicited - * delivery model is unchanged). - */ - const listenRouter = new StdioListenRouter(options.maxSubscriptions ?? DEFAULT_MAX_SUBSCRIPTIONS); - /** Outbound intercept installed on a modern instance's channel. */ - const modernOutboundIntercept = (message) => { - if (!isJSONRPCNotification(message)) return void 0; - const routed = listenRouter.routeOutbound(message); - if (routed === "passthrough") return void 0; - for (const stamped of routed) wire.send({ - jsonrpc: "2.0", - ...stamped - }).catch((error) => reportError(stdio_toError(error))); - return "handled"; - }; - /** - * Entry-handled inbound listen routing for a modern-pinned connection. - * Returns `true` when the message was served at the entry and must NOT - * be delivered to the pinned instance. - */ - const tryServeListen = async (message) => { - if (isJSONRPCRequest(message) && message.method === "subscriptions/listen") { - const meta = requestMetaOf(message.params); - const issue = hasEnvelopeClaim(message.params) ? (meta === void 0 ? [] : validateEnvelopeMeta(meta))[0] : { - key: "_meta", - problem: "the per-request envelope is required on protocol revision 2026-07-28" - }; - const claimedVersion = envelopeClaimVersion(message.params); - let reply; - if (issue !== void 0) reply = { - jsonrpc: "2.0", - id: message.id, - error: { - code: -32602, - message: `Invalid _meta envelope: ${issue.key}: ${issue.problem}` - } - }; - else if (claimedVersion === void 0 || !SUPPORTED_MODERN_PROTOCOL_VERSIONS.includes(claimedVersion)) { - const error = new UnsupportedProtocolVersionError({ - supported: [...SUPPORTED_MODERN_PROTOCOL_VERSIONS], - requested: claimedVersion ?? "unknown" - }); - reply = { - jsonrpc: "2.0", - id: message.id, - error: { - code: error.code, - message: error.message, - data: error.data - } - }; - } else reply = listenRouter.serve(message); - await wire.send("error" in reply ? reply : { - jsonrpc: "2.0", - method: reply.method, - params: reply.params - }).catch((error) => reportError(stdio_toError(error))); - return true; - } - if (isJSONRPCNotification(message) && message.method === "notifications/cancelled") { - const cancelledId = message.params?.requestId; - if (cancelledId !== void 0 && listenRouter.cancel(cancelledId)) return true; - } - return false; - }; - /** Answers a 2025-era request the entry will not serve (the modern-only rejection cells). */ - const answerLegacyRejection = (request, reason, requestedVersion) => { - const rejection = modernOnlyStrictRejection({ - kind: "legacy", - reason, - ...requestedVersion !== void 0 && { requestedVersion } - }, SUPPORTED_MODERN_PROTOCOL_VERSIONS); - if (rejection === void 0) return Promise.resolve(); - reportError(/* @__PURE__ */ new Error(`Rejected 2025-era request on a modern-only stdio connection (${rejection.cell}): ${rejection.message}`)); - return writeErrorResponse(request.id, rejection.code, rejection.message, rejection.data); - }; - const onInstanceClosed = (channel) => { - if (closing || channel === discarding) return; - closeAll(); - }; - const connectInstance = async (era, revision) => { - const product = await factory({ era }); - const server = product instanceof McpServer ? product.server : product; - if (era === "modern") { - setNegotiatedProtocolVersion(server, revision); - installModernOnlyHandlers(server, SUPPORTED_MODERN_PROTOCOL_VERSIONS); - listenRouter.setServerCapabilities(server.getCapabilities(), serverIdentityOf(server)); - } - const channel = new StdioConnectionChannel(wire, () => onInstanceClosed(channel), era === "modern" ? modernOutboundIntercept : void 0); - await product.connect(channel); - return { - product, - channel - }; - }; - /** Closes an instance whose factory resolved only after the connection was torn down. */ - const disposeLateInstance = (instance) => instance.product.close().catch((error) => reportError(stdio_toError(error))); - const discardProbeInstance = async (instance) => { - discarding = instance.channel; - try { - if (!await instance.channel.whenRequestsAnswered(DISCARD_ANSWER_TIMEOUT_MS)) reportError(/* @__PURE__ */ new Error(`Discarded the probe instance with requests still unanswered after ${DISCARD_ANSWER_TIMEOUT_MS}ms; continuing with the fallback`)); - await instance.product.close(); - } catch (error) { - reportError(stdio_toError(error)); - } finally { - discarding = void 0; - } - }; - const processMessage = async (message) => { - if (state.phase === "closed") return; - if (state.phase === "pinned") { - if (state.era === "modern" && isJSONRPCRequest(message) && message.method === "initialize" && !carriesValidModernEnvelopeClaim(message.params)) { - await answerLegacyRejection(message, "initialize", message.params !== null && typeof message.params === "object" && typeof message.params.protocolVersion === "string" ? message.params.protocolVersion : void 0); - return; - } - if (state.era === "modern" && await tryServeListen(message)) return; - state.instance.channel.deliver(message); - return; - } - if (!isJSONRPCRequest(message) && !isJSONRPCNotification(message)) { - reportError(/* @__PURE__ */ new Error("Discarded a JSON-RPC response received before the connection negotiated an era")); - return; - } - const opening = classifyOpeningMessage(message); - switch (opening.kind) { - case "invalid-envelope": { - const detail = `Invalid _meta envelope for protocol revision 2026-07-28: ${opening.issue.key}: ${opening.issue.problem}`; - if (isJSONRPCRequest(message)) await writeErrorResponse(message.id, ProtocolErrorCode.InvalidParams, detail, { envelope: opening.issue }); - else reportError(/* @__PURE__ */ new Error(`Discarded a notification with a malformed envelope: ${detail}`)); - return; - } - case "unsupported-revision": - if (isJSONRPCRequest(message)) { - const error = new UnsupportedProtocolVersionError({ - supported: [...SUPPORTED_MODERN_PROTOCOL_VERSIONS], - requested: opening.requested - }); - reportError(error); - await writeErrorResponse(message.id, error.code, error.message, error.data); - } else reportError(/* @__PURE__ */ new Error(`Discarded a notification claiming unsupported protocol revision ${opening.requested}`)); - return; - case "modern": - if (isJSONRPCRequest(message) && message.method === "server/discover") { - if (state.phase === "probe") { - state.instance.channel.deliver(message, { classification: opening.classification }); - return; - } - const instance = await connectInstance("modern", opening.revision); - if (isTornDown()) { - await disposeLateInstance(instance); - return; - } - state = { - phase: "probe", - instance - }; - instance.channel.deliver(message, { classification: opening.classification }); - return; - } - if (state.phase === "probe") { - if (isJSONRPCNotification(message)) { - state.instance.channel.deliver(message, { classification: opening.classification }); - return; - } - state = { - phase: "pinned", - era: "modern", - instance: state.instance - }; - } else { - const instance = await connectInstance("modern", opening.revision); - if (isTornDown()) { - await disposeLateInstance(instance); - return; - } - state = { - phase: "pinned", - era: "modern", - instance - }; - } - if (await tryServeListen(message)) return; - state.instance.channel.deliver(message, { classification: opening.classification }); - return; - case "legacy": { - if (legacyMode === "reject") { - if (isJSONRPCRequest(message)) await answerLegacyRejection(message, opening.reason, opening.requestedVersion); - return; - } - if (state.phase === "probe") { - await discardProbeInstance(state.instance); - if (isTornDown()) return; - state = { phase: "opening" }; - } - const instance = await connectInstance("legacy"); - if (isTornDown()) { - await disposeLateInstance(instance); - return; - } - state = { - phase: "pinned", - era: "legacy", - instance - }; - state.instance.channel.deliver(message); - return; - } - } - }; - const queue = []; - let pumping = false; - const pump = async () => { - if (pumping) return; - pumping = true; - try { - while (queue.length > 0) { - const message = queue.shift(); - try { - await processMessage(message); - } catch (error) { - if (isJSONRPCRequest(message)) await writeErrorResponse(message.id, ProtocolErrorCode.InternalError, "Internal server error"); - reportError(stdio_toError(error)); - } - } - } finally { - pumping = false; - } - }; - const closeAll = async () => { - if (closing || state.phase === "closed") return; - closing = true; - const current = state; - state = { phase: "closed" }; - for (const result of listenRouter.teardownAll()) await wire.send(result).catch((error) => reportError(stdio_toError(error))); - if (current.phase === "probe" || current.phase === "pinned") await current.instance.product.close().catch((error) => reportError(stdio_toError(error))); - await wire.close().catch((error) => reportError(stdio_toError(error))); - }; - wire.onmessage = (message) => { - queue.push(message); - pump(); - }; - wire.onerror = (error) => { - reportError(error); - if (state.phase === "probe" || state.phase === "pinned") state.instance.channel.onerror?.(error); - }; - wire.onclose = () => { - if (closing || state.phase === "closed") return; - closing = true; - const current = state; - state = { phase: "closed" }; - if (current.phase === "probe" || current.phase === "pinned") current.instance.product.close().catch((error) => reportError(stdio_toError(error))); - }; - const started = wire.start().catch((error) => { - reportError(stdio_toError(error)); - throw error; - }); - started.catch(() => {}); - return { close: async () => { - await started.catch(() => {}); - await closeAll(); - } }; -} -function stdio_toError(value) { - return value instanceof Error ? value : new Error(String(value)); -} - -//#endregion - -//# sourceMappingURL=stdio.mjs.map -const defaultHeartbeatIntervalMs = 300000; -const defaultActivityThrottleMs = 60000; -const defaultShutdownTimeoutMs = 5000; -const defaultHeartbeatName = 'agent-bundle'; -const redirectConsoleToStderr = ()=>{ - const originalStdoutWrite = process.stdout.write.bind(process.stdout); - const stderrConsole = new console.Console({ - stderr: process.stderr, - stdout: process.stderr - }); - const methods = [ - 'debug', - 'dir', - 'error', - 'info', - 'log', - 'trace', - 'warn' - ]; - for (const method of methods)console[method] = stderrConsole[method].bind(stderrConsole); - process.stdout.write = (chunk, encoding, callback)=>process.stderr.write(chunk, encoding, callback); - return Object.freeze({ - restoreProtocolStdout: ()=>{ - process.stdout.write = originalStdoutWrite; - } - }); -}; -const createHeartbeat = ({ activityThrottleMs = defaultActivityThrottleMs, intervalMs = defaultHeartbeatIntervalMs, name = defaultHeartbeatName, writeLine })=>{ - const startedAt = Date.now(); - let lastActivityAt = startedAt; - let lastActivityLogAt = 0; - const log = (reason)=>{ - const uptimeSeconds = Math.round((Date.now() - startedAt) / 1000); - const idleSeconds = Math.round((Date.now() - lastActivityAt) / 1000); - writeLine(`[${name}] stdio heartbeat (${reason}) pid=${process.pid} uptime=${uptimeSeconds}s idle=${idleSeconds}s`); - }; - const timer = setInterval(()=>log('interval'), intervalMs); - timer.unref?.(); - return Object.freeze({ - log, - noteActivity: ()=>{ - lastActivityAt = Date.now(); - if (lastActivityAt - lastActivityLogAt >= activityThrottleMs) { - lastActivityLogAt = lastActivityAt; - log('activity'); - } - }, - stop: ()=>clearInterval(timer) - }); -}; -const runStdioServer = async ({ activityThrottleMs, exit = (code)=>process.exit(code), heartbeat: heartbeatEnabled = true, heartbeatIntervalMs, server, serverName, shutdownTimeoutMs = defaultShutdownTimeoutMs, signals = process, stdin = process.stdin, transport, writeLine = (line)=>void process.stderr.write(`${line}\n`) })=>{ - const heartbeat = createHeartbeat({ - ...void 0 === activityThrottleMs ? {} : { - activityThrottleMs - }, - ...void 0 === heartbeatIntervalMs ? {} : { - intervalMs: heartbeatIntervalMs - }, - ...void 0 === serverName ? {} : { - name: serverName - }, - writeLine: heartbeatEnabled ? writeLine : ()=>void 0 - }); - const keepalive = setInterval(()=>void 0, 60000); - keepalive.unref?.(); - let shuttingDown = false; - const shutdown = async (exitCode = 0)=>{ - if (shuttingDown) return; - shuttingDown = true; - signals.off('SIGINT', handleSigint); - signals.off('SIGTERM', handleSigterm); - stdin.off?.('end', handleStdinEnd); - clearInterval(keepalive); - heartbeat.stop(); - await Promise.race([ - Promise.allSettled([ - Promise.resolve().then(()=>transport.close()), - Promise.resolve().then(()=>server.close()) - ]), - new Promise((resolve)=>setTimeout(resolve, shutdownTimeoutMs)) - ]); - exit(exitCode); - }; - const handleSigint = ()=>{ - shutdown(130); - }; - const handleSigterm = ()=>{ - shutdown(143); - }; - const handleStdinEnd = ()=>{ - shutdown(0); - }; - signals.on('SIGINT', handleSigint); - signals.on('SIGTERM', handleSigterm); - stdin.once?.('end', handleStdinEnd); - transport.onclose = ()=>{ - shutdown(0); - }; - await server.connect(transport); - const originalOnMessage = transport.onmessage; - transport.onmessage = (message, extra)=>{ - heartbeat.noteActivity(); - originalOnMessage?.(message, extra); - }; - return Object.freeze({ - heartbeat, - shutdown - }); -}; -const runGeneratedStdioMcpEntry = async (options)=>{ - const guard = redirectConsoleToStderr(); - const entry = await options.loadEntry(); - const factory = entry.default; - if ('function' != typeof factory) throw new TypeError(`Generated stdio entry for MCP server ${JSON.stringify(options.serverName)} must default-export a server factory.`); - const server = await factory(); - const { StdioServerTransport } = await Promise.resolve(stdio_namespaceObject); - guard.restoreProtocolStdout(); - const transport = new StdioServerTransport(); - return runStdioServer({ - ...options.lifecycle, - server, - serverName: options.serverName, - transport: transport - }); -}; - - - -await runGeneratedStdioMcpEntry({ - loadEntry: ()=>Promise.resolve(status_namespaceObject), - serverName: "status" -}); - -export {}; diff --git a/examples/mcp-app/artifact/claude/scripts/check-service-fixture.mjs b/examples/mcp-app/artifact/claude/scripts/check-service-fixture.mjs deleted file mode 100644 index a059060bb..000000000 --- a/examples/mcp-app/artifact/claude/scripts/check-service-fixture.mjs +++ /dev/null @@ -1,60 +0,0 @@ -import { readFile } from "node:fs/promises"; - - - - -const healthyCompilerStatus = Object.freeze({ - checks: Object.freeze([ - Object.freeze({ - label: 'Availability', - status: 'passing' - }), - Object.freeze({ - label: 'Build queue', - status: 'passing' - }) - ]), - service: 'compiler', - status: 'healthy', - summary: 'Compiler service is ready for release.' -}); -const isRecord = (value)=>value !== null && typeof value === 'object' && !Array.isArray(value); -const isHealthyCompilerFixture = (value)=>{ - if (!isRecord(value) || value.service !== healthyCompilerStatus.service || value.status !== healthyCompilerStatus.status || value.summary !== healthyCompilerStatus.summary || !Array.isArray(value.checks) || value.checks.length !== healthyCompilerStatus.checks.length) { - return false; - } - return healthyCompilerStatus.checks.every((expected, index)=>{ - const received = value.checks[index]; - return isRecord(received) && received.label === expected.label && received.status === expected.status; - }); -}; - - - -const fixturePath = new URL('../assets/evals/fixtures/status/result.json', import.meta.url); -/** - * `agent-bundle build` detects the `main` export and generates the process - * envelope (argv, awaiting, numeric-return exit-code adoption) around it. - */ const main = async ()=>{ - try { - const fixture = JSON.parse(await readFile(fixturePath, 'utf8')); - if (!isHealthyCompilerFixture(fixture)) { - throw new Error('compiler fixture must contain the exact healthy compiler status'); - } - process.stdout.write('Compiler fixture is healthy.\n'); - return 0; - } catch (error) { - process.stderr.write(`Unable to verify service fixture: ${error instanceof Error ? error.message : String(error)}\n`); - return 1; - } -}; - - -const check_service_fixture_entry_main = main; -if (typeof check_service_fixture_entry_main !== 'function') { - throw new TypeError('Executable entry must export a main function: ' + "/fast/projects/agent-bundle-worktrees/host-test/examples/mcp-app/src/scripts/check-service-fixture.ts"); -} -const code = await check_service_fixture_entry_main(process.argv.slice(2)); -if (typeof code === 'number') process.exitCode = code; - -export {}; diff --git a/examples/mcp-app/artifact/claude/skills/service-readiness/SKILL.md b/examples/mcp-app/artifact/claude/skills/service-readiness/SKILL.md deleted file mode 100644 index 8f91a79d7..000000000 --- a/examples/mcp-app/artifact/claude/skills/service-readiness/SKILL.md +++ /dev/null @@ -1,33 +0,0 @@ ---- -name: service-readiness -description: Reviews service health evidence and records an auditable readiness decision. ---- -# Service readiness - -## When to use - -Use this Skill when a release, incident decision, or service handoff needs a -clear health verdict backed by named checks and current evidence. - -## Required resources - -- Apply [the service status policy](references/status-policy.md) before - classifying a healthy, degraded, or blocked result. -- Deliver the decision with [the readiness report](assets/readiness-report.md). - -## Workflow - -1. Identify the service and collect its current summary and every labelled - check. Record the command, time, result, and evidence source. -2. Classify any failing check with the status policy. A degraded service is not - release-ready until its failing check has an approved mitigation. -3. State the readiness verdict only after confirming availability and the - service-specific release threshold. -4. Complete the report with the status, checks, evidence, owner, and next - action. Do not omit a failing check from the final decision. - -## Final report requirements - -State `ready`, `degraded`, `blocked`, or `needs evidence`; reproduce the -service summary; list each labelled check and its status; identify the owner -and due date for every non-passing check; and name the next required action. diff --git a/examples/mcp-app/artifact/claude/skills/service-readiness/assets/readiness-report.md b/examples/mcp-app/artifact/claude/skills/service-readiness/assets/readiness-report.md deleted file mode 100644 index 3da5d52ea..000000000 --- a/examples/mcp-app/artifact/claude/skills/service-readiness/assets/readiness-report.md +++ /dev/null @@ -1,22 +0,0 @@ -# Service readiness report - -## Verdict - -State `ready`, `degraded`, `blocked`, or `needs evidence` and name the service. - -## Evidence - -Record the collection time, command or artifact, service summary, and source. - -## Checks - -List every labelled check with its observed status and release threshold. - -## Findings and mitigation - -For each non-passing check, record the impact, owner, mitigation, due date, -and the evidence required to clear it. - -## Next action - -Name the decision owner and the next verification or release action. diff --git a/examples/mcp-app/artifact/claude/skills/service-readiness/references/status-policy.md b/examples/mcp-app/artifact/claude/skills/service-readiness/references/status-policy.md deleted file mode 100644 index 7e5766172..000000000 --- a/examples/mcp-app/artifact/claude/skills/service-readiness/references/status-policy.md +++ /dev/null @@ -1,22 +0,0 @@ -# Service status policy - -## Evidence standard - -Readiness evidence must identify the service, collection time, check label, -observed status, and source command or artifact. Missing or stale evidence is -not a passing check. - -## Status classification - -- **Healthy**: every required release check is passing. -- **Degraded**: availability remains sufficient, but a release threshold such - as P95 latency is failing. Record an owner and mitigation before release. -- **Blocked**: availability or a critical safety check is failing. Do not - release until new passing evidence is collected. -- **Needs evidence**: the service or any required check cannot be verified. - -## Release decision - -Issue `ready` only for a healthy service with current evidence. A degraded -service needs an explicit mitigation decision; a blocked service cannot pass; -and missing evidence requires a new check rather than an assumption. diff --git a/examples/mcp-app/artifact/codex/.agents/plugins/marketplace.json b/examples/mcp-app/artifact/codex/.agents/plugins/marketplace.json deleted file mode 100644 index 37ef3be4a..000000000 --- a/examples/mcp-app/artifact/codex/.agents/plugins/marketplace.json +++ /dev/null @@ -1 +0,0 @@ -{"interface":{"displayName":"mcp-app-example"},"name":"mcp-app-example-marketplace","plugins":[{"category":"Productivity","name":"mcp-app-example","policy":{"authentication":"ON_INSTALL","installation":"AVAILABLE"},"source":{"path":"./","source":"local"}}]} diff --git a/examples/mcp-app/artifact/codex/.codex-plugin/plugin.json b/examples/mcp-app/artifact/codex/.codex-plugin/plugin.json deleted file mode 100644 index a86a5db3f..000000000 --- a/examples/mcp-app/artifact/codex/.codex-plugin/plugin.json +++ /dev/null @@ -1 +0,0 @@ -{"author":{"name":"mcp-app-example"},"description":"A unified service-readiness assistant with MCP, Skills, Hooks, scripts, and evaluation.","hooks":"./hooks/hooks.json","interface":{"capabilities":["mcp","hooks","skills"],"category":"Productivity","defaultPrompt":["Help me use mcp-app-example."],"developerName":"mcp-app-example","displayName":"mcp-app-example","longDescription":"A unified service-readiness assistant with MCP, Skills, Hooks, scripts, and evaluation.","shortDescription":"A unified service-readiness assistant with MCP, Skills, Hooks, scripts, and evaluation."},"mcpServers":"./.mcp.json","name":"mcp-app-example","skills":"./skills/","version":"1.0.0"} diff --git a/examples/mcp-app/artifact/codex/.mcp.json b/examples/mcp-app/artifact/codex/.mcp.json deleted file mode 100644 index 8a84f9c2f..000000000 --- a/examples/mcp-app/artifact/codex/.mcp.json +++ /dev/null @@ -1 +0,0 @@ -{"mcpServers":{"status":{"args":["./mcp/mcp-status-073c1634.mjs"],"command":"node","cwd":"./","env":{"AGENT_BUNDLE_PLUGIN_ROOT":"./"},"type":"stdio"}}} diff --git a/examples/mcp-app/artifact/codex/INSTALL.md b/examples/mcp-app/artifact/codex/INSTALL.md deleted file mode 100644 index f93c7ff0b..000000000 --- a/examples/mcp-app/artifact/codex/INSTALL.md +++ /dev/null @@ -1,16 +0,0 @@ -# Install mcp-app-example - -A unified service-readiness assistant with MCP, Skills, Hooks, scripts, and evaluation. - -Version: `1.0.0` - -Run these commands from this bundle directory. - -## Codex - -Codex installs this bundle from its local marketplace snapshot: - -```sh -codex plugin marketplace add ./ -codex plugin add mcp-app-example@mcp-app-example-marketplace -``` diff --git a/examples/mcp-app/artifact/codex/assets/evals/fixtures/status/result.json b/examples/mcp-app/artifact/codex/assets/evals/fixtures/status/result.json deleted file mode 100644 index a765aa4b5..000000000 --- a/examples/mcp-app/artifact/codex/assets/evals/fixtures/status/result.json +++ /dev/null @@ -1,9 +0,0 @@ -{ - "service": "compiler", - "status": "healthy", - "summary": "Compiler service is ready for release.", - "checks": [ - { "label": "Availability", "status": "passing" }, - { "label": "Build queue", "status": "passing" } - ] -} diff --git a/examples/mcp-app/artifact/codex/hooks/hooks.json b/examples/mcp-app/artifact/codex/hooks/hooks.json deleted file mode 100644 index eb4f61756..000000000 --- a/examples/mcp-app/artifact/codex/hooks/hooks.json +++ /dev/null @@ -1 +0,0 @@ -{"hooks":{"SessionStart":[{"hooks":[{"command":"node \"${PLUGIN_ROOT}/hooks/session-start-session-start-7ab7e8a5.mjs\"","type":"command"}]}]}} diff --git a/examples/mcp-app/artifact/codex/hooks/session-start-session-start-7ab7e8a5.mjs b/examples/mcp-app/artifact/codex/hooks/session-start-session-start-7ab7e8a5.mjs deleted file mode 100644 index e38d8499c..000000000 --- a/examples/mcp-app/artifact/codex/hooks/session-start-session-start-7ab7e8a5.mjs +++ /dev/null @@ -1,258 +0,0 @@ -// The require scope -var __webpack_require__ = {}; - -// webpack/runtime/define_property_getters -(() => { -__webpack_require__.d = (exports, getters, values) => { - var define = (defs, kind) => { - for(var key in defs) { - if(__webpack_require__.o(defs, key) && !__webpack_require__.o(exports, key)) { - Object.defineProperty(exports, key, { enumerable: true, [kind]: defs[key] }); - } - } - }; - define(getters, "get"); - define(values, "value"); -}; -})(); -// webpack/runtime/has_own_property -(() => { -__webpack_require__.o = (obj, prop) => (Object.prototype.hasOwnProperty.call(obj, prop)) -})(); -// webpack/runtime/make_namespace_object -(() => { -// define __esModule on exports -__webpack_require__.r = (exports) => { - if(typeof Symbol !== 'undefined' && Symbol.toStringTag) { - Object.defineProperty(exports, Symbol.toStringTag, { value: 'Module' }); - } - Object.defineProperty(exports, '__esModule', { value: true }); -}; -})(); - -// NAMESPACE OBJECT: ./src/hooks/session-start.ts -var session_start_namespaceObject = {}; -__webpack_require__.r(session_start_namespaceObject); -__webpack_require__.d(session_start_namespaceObject, { - "default": () => (session_start) }); - - -/* export default */ const session_start = ((event)=>({ - additionalContext: [ - `Service readiness session ${event.sessionId ?? 'is active'} from ${event.source ?? 'an unknown source'}.`, - `Use the service-readiness Skill, then run check-service-fixture from ${event.cwd ?? process.cwd()} before release review.`, - 'Use show-status for compiler or payments-api when live service evidence is needed.' - ].join(' '), - outcome: 'continue' - })); - - -const target = "codex"; -const canonicalEvent = "sessionStart"; -const nativeEvent = "SessionStart"; -const isRecord = (value)=>typeof value === "object" && value !== null && !Array.isArray(value); -const defined = (value)=>Object.fromEntries(Object.entries(value).filter(([, item])=>item !== undefined)); -const decodeCodexNative = (nativeInput)=>({ - agentId: nativeInput.agent_id, - agentTranscriptPath: nativeInput.agent_transcript_path, - agentType: nativeInput.agent_type, - cwd: nativeInput.cwd, - effort: nativeInput.effort, - hookEventName: nativeInput.hook_event_name, - lastAssistantMessage: nativeInput.last_assistant_message, - model: nativeInput.model, - permissionMode: nativeInput.permission_mode, - promptId: nativeInput.prompt_id, - sessionId: nativeInput.session_id, - source: nativeInput.source, - stopHookActive: nativeInput.stop_hook_active, - toolInput: nativeInput.tool_input, - toolName: nativeInput.tool_name, - toolResponse: nativeInput.tool_response, - toolUseId: nativeInput.tool_use_id, - transcriptPath: nativeInput.transcript_path, - turnId: nativeInput.turn_id - }); -const encodeCodexNative = (canonicalInput)=>defined({ - hook_event_name: nativeEvent, - agent_id: canonicalInput.agentId, - agent_transcript_path: canonicalInput.agentTranscriptPath, - agent_type: canonicalInput.agentType, - cwd: canonicalInput.cwd, - effort: canonicalInput.effort, - last_assistant_message: canonicalInput.lastAssistantMessage, - model: canonicalInput.model, - permission_mode: canonicalInput.permissionMode, - prompt_id: canonicalInput.promptId, - session_id: canonicalInput.sessionId, - source: canonicalInput.source, - stop_hook_active: canonicalInput.stopHookActive, - tool_input: canonicalInput.toolInput, - tool_name: canonicalInput.toolName, - tool_response: canonicalInput.toolResponse, - tool_use_id: canonicalInput.toolUseId, - transcript_path: canonicalInput.transcriptPath, - turn_id: canonicalInput.turnId - }); -const decodeNative = decodeCodexNative; -const encodeNative = encodeCodexNative; -const fail = (message)=>{ - throw new Error(`Agent Bundle hook error: ${message}`); -}; -const validateResult = (result)=>{ - if (result === undefined) return undefined; - if (!isRecord(result)) fail("handler must return void or a result object"); - const allowed = new Set([ - "outcome", - "reason", - "updatedInput", - "additionalContext" - ]); - for (const key of Object.keys(result))if (!allowed.has(key)) fail(`handler result has unsupported field ${key}`); - if (result.outcome !== undefined && ![ - "continue", - "deny", - "stop" - ].includes(result.outcome)) fail("handler result outcome is invalid"); - if (result.reason !== undefined && typeof result.reason !== "string") fail("handler result reason must be a string"); - if (result.additionalContext !== undefined && typeof result.additionalContext !== "string") fail("handler result additionalContext must be a string"); - if (result.updatedInput !== undefined && !isRecord(result.updatedInput)) fail("handler result updatedInput must be an object"); - const supportsDeniedReason = canonicalEvent === "beforeTool" || canonicalEvent === "stop" || canonicalEvent === "agentStop"; - if (result.reason !== undefined && !(result.outcome === "deny" && supportsDeniedReason)) fail("reason is only valid for a denied beforeTool, stop, or agentStop hook"); - if (result.outcome === "deny" && supportsDeniedReason && (typeof result.reason !== "string" || result.reason.trim().length === 0)) fail(`denied ${canonicalEvent} hook requires a nonempty reason`); - if ((canonicalEvent === "sessionStart" || canonicalEvent === "afterTool" || canonicalEvent === "agentStart") && (result.outcome === "deny" || result.outcome === "stop" || result.updatedInput !== undefined)) fail(`${canonicalEvent} cannot deny, stop, or replace input`); - if (canonicalEvent === "beforeTool" && (result.outcome === "stop" || result.outcome === "deny" && result.updatedInput !== undefined)) fail("beforeTool cannot stop or replace input while denying"); - if (canonicalEvent === "stop" && (result.outcome === "stop" || result.updatedInput !== undefined || result.additionalContext !== undefined)) fail("stop only accepts continue or deny with a reason"); - if (canonicalEvent === "agentStop" && (result.outcome === "stop" || result.updatedInput !== undefined)) fail("agentStop cannot stop the parent flow or replace input"); - if (canonicalEvent === "agentStop" && target === "codex" && result.additionalContext !== undefined) fail("Codex SubagentStop does not support additionalContext"); - return result; -}; -const encodeOutput = (result)=>{ - if (result === undefined) return undefined; - if (canonicalEvent === "stop" || canonicalEvent === "agentStop") { - if (result.outcome === "deny") return defined({ - decision: "block", - reason: result.reason - }); - if (canonicalEvent === "agentStop" && target === "claude" && 0) {} - return undefined; - } - const output = defined({ - additionalContext: result.additionalContext, - hookEventName: nativeEvent, - permissionDecision: canonicalEvent === "beforeTool" ? result.outcome === "deny" ? "deny" : "allow" : undefined, - permissionDecisionReason: canonicalEvent === "beforeTool" && result.outcome === "deny" ? result.reason : undefined, - updatedInput: canonicalEvent === "beforeTool" && result.outcome !== "deny" ? result.updatedInput : undefined - }); - return Object.keys(output).length === 1 && output.hookEventName !== undefined ? undefined : { - hookSpecificOutput: output - }; -}; -const decodeOutput = (nativeOutput)=>{ - if (nativeOutput === undefined) return undefined; - if (canonicalEvent === "stop" || canonicalEvent === "agentStop") { - if (nativeOutput.decision === "block") return defined({ - outcome: "deny", - reason: nativeOutput.reason - }); - if (canonicalEvent === "agentStop" && target === "claude" && 0) {} - return undefined; - } - const output = nativeOutput.hookSpecificOutput; - if (!isRecord(output)) fail("native hook output is malformed"); - return defined({ - additionalContext: output.additionalContext, - outcome: output.permissionDecision === "deny" ? "deny" : "continue", - reason: output.permissionDecisionReason, - updatedInput: output.updatedInput - }); -}; -const requireString = (input, field)=>{ - if (typeof input[field] !== "string") fail(`native ${field} must be a string`); -}; -const requireNullableString = (input, field)=>{ - if (input[field] !== null && typeof input[field] !== "string") fail(`native ${field} must be a string or null`); -}; -const validateNativeInput = (input)=>{ - requireString(input, "session_id"); - if (true) requireNullableString(input, "transcript_path"); - else {} - requireString(input, "cwd"); - if (input.hook_event_name !== nativeEvent) fail(`native hook_event_name must equal ${nativeEvent}`); - if (input.prompt_id !== undefined) requireString(input, "prompt_id"); - if (input.permission_mode !== undefined) requireString(input, "permission_mode"); - if (input.model !== undefined) requireString(input, "model"); - if (canonicalEvent === "sessionStart") { - requireString(input, "source"); - return; - } - if (canonicalEvent === "beforeTool" || canonicalEvent === "afterTool") { - requireString(input, "tool_name"); - if (true) { - if (input.tool_input === undefined) fail(`native ${nativeEvent} tool_input is required`); - } else {} - requireString(input, "tool_use_id"); - if (canonicalEvent === "afterTool") { - if (input.tool_response === undefined) fail("native PostToolUse tool_response is required"); - } - return; - } - if (canonicalEvent === "agentStart" || canonicalEvent === "agentStop") { - requireString(input, "agent_id"); - requireString(input, "agent_type"); - if (true) { - requireString(input, "turn_id"); - requireString(input, "model"); - requireString(input, "permission_mode"); - if (![ - "default", - "acceptEdits", - "plan", - "dontAsk", - "bypassPermissions" - ].includes(input.permission_mode)) fail("native permission_mode is invalid"); - } - if (canonicalEvent === "agentStart") return; - if (typeof input.stop_hook_active !== "boolean") fail("native SubagentStop stop_hook_active must be a boolean"); - requireNullableString(input, "agent_transcript_path"); - requireNullableString(input, "last_assistant_message"); - return; - } - if (typeof input.stop_hook_active !== "boolean") fail("native Stop stop_hook_active must be a boolean"); - if (true) requireNullableString(input, "last_assistant_message"); - else {} -}; -const run = async ()=>{ - const handler = Reflect.get(session_start_namespaceObject, "default"); - if (typeof handler !== "function") fail("default export must be a function"); - let raw = ""; - for await (const chunk of process.stdin)raw += chunk; - if (raw.trim().length === 0) fail("stdin must contain exactly one JSON value"); - let input; - try { - input = JSON.parse(raw); - } catch { - fail("stdin must contain exactly one JSON value"); - } - if (!isRecord(input)) fail("stdin JSON value must be an object"); - const simulation = process.env.AGENT_BUNDLE_HOOK_SIMULATION === "1"; - const nativeInput = simulation ? encodeNative(input) : input; - validateNativeInput(nativeInput); - const event = decodeNative(nativeInput); - const result = validateResult(await handler(event, { - nativeEvent: nativeEvent, - nativeInput, - target: target - })); - const nativeOutput = encodeOutput(result); - const output = simulation ? decodeOutput(nativeOutput) : nativeOutput; - if (output !== undefined) process.stdout.write(JSON.stringify(output)); -}; -if (import.meta.main) { - await run().catch((error)=>{ - process.stderr.write(`${error instanceof Error ? error.message : String(error)}\n`); - process.exitCode = 1; - }); -} - -export {}; diff --git a/examples/mcp-app/artifact/codex/mcp/mcp-status-073c1634.mjs b/examples/mcp-app/artifact/codex/mcp/mcp-status-073c1634.mjs deleted file mode 100644 index 29189bf45..000000000 --- a/examples/mcp-app/artifact/codex/mcp/mcp-status-073c1634.mjs +++ /dev/null @@ -1,30761 +0,0 @@ -import node_process from "node:process"; - -// The require scope -var __webpack_require__ = {}; - -// webpack/runtime/define_property_getters -(() => { -__webpack_require__.d = (exports, getters, values) => { - var define = (defs, kind) => { - for(var key in defs) { - if(__webpack_require__.o(defs, key) && !__webpack_require__.o(exports, key)) { - Object.defineProperty(exports, key, { enumerable: true, [kind]: defs[key] }); - } - } - }; - define(getters, "get"); - define(values, "value"); -}; -})(); -// webpack/runtime/has_own_property -(() => { -__webpack_require__.o = (obj, prop) => (Object.prototype.hasOwnProperty.call(obj, prop)) -})(); -// webpack/runtime/make_namespace_object -(() => { -// define __esModule on exports -__webpack_require__.r = (exports) => { - if(typeof Symbol !== 'undefined' && Symbol.toStringTag) { - Object.defineProperty(exports, Symbol.toStringTag, { value: 'Module' }); - } - Object.defineProperty(exports, '__esModule', { value: true }); -}; -})(); - -// NAMESPACE OBJECT: ./src/mcp/status.ts -var status_namespaceObject = {}; -__webpack_require__.r(status_namespaceObject); -__webpack_require__.d(status_namespaceObject, { - createStatusServer: () => (createStatusServer), - "default": () => (mcp_status) }); - - -// NAMESPACE OBJECT: ../../node_modules/.pnpm/@modelcontextprotocol+server@2.0.0/node_modules/@modelcontextprotocol/server/dist/stdio.mjs -var stdio_namespaceObject = {}; -__webpack_require__.r(stdio_namespaceObject); -__webpack_require__.d(stdio_namespaceObject, { - StdioServerTransport: () => (stdio_StdioServerTransport) }); - - -//#region rolldown:runtime -var __create = Object.create; -var __defProp = Object.defineProperty; -var __getOwnPropDesc = Object.getOwnPropertyDescriptor; -var __getOwnPropNames = Object.getOwnPropertyNames; -var __getProtoOf = Object.getPrototypeOf; -var __hasOwnProp = Object.prototype.hasOwnProperty; -var __commonJSMin = (cb, mod) => () => (mod || cb((mod = { exports: {} }).exports, mod), mod.exports); -var __exportAll = (all, symbols) => { - let target = {}; - for (var name in all) { - __defProp(target, name, { - get: all[name], - enumerable: true - }); - } - if (symbols) { - __defProp(target, Symbol.toStringTag, { value: "Module" }); - } - return target; -}; -var __copyProps = (to, from, except, desc) => { - if (from && typeof from === "object" || typeof from === "function") { - for (var keys = __getOwnPropNames(from), i = 0, n = keys.length, key; i < n; i++) { - key = keys[i]; - if (!__hasOwnProp.call(to, key) && key !== except) { - __defProp(to, key, { - get: ((k) => from[k]).bind(null, key), - enumerable: !(desc = __getOwnPropDesc(from, key)) || desc.enumerable - }); - } - } - } - return to; -}; -var __toESM = (mod, isNodeMode, target) => (target = mod != null ? __create(__getProtoOf(mod)) : {}, __copyProps(isNodeMode || !mod || !mod.__esModule ? __defProp(target, "default", { - value: mod, - enumerable: true -}) : target, mod)); - -//#endregion - -//#region ../core-internal/src/validators/dialects.ts -/** -* Canonical `$schema` URIs per supported dialect (http + https variants, trailing-`#` stripped). -*/ -const DRAFT_2020_12_URIS = new Set(["https://json-schema.org/draft/2020-12/schema", "http://json-schema.org/draft/2020-12/schema"]); -const DRAFT_2019_09_URIS = new Set(["https://json-schema.org/draft/2019-09/schema", "http://json-schema.org/draft/2019-09/schema"]); -const DRAFT_07_URIS = new Set(["https://json-schema.org/draft-07/schema", "http://json-schema.org/draft-07/schema"]); -const DRAFT_06_URIS = new Set(["https://json-schema.org/draft-06/schema", "http://json-schema.org/draft-06/schema"]); -/** -* Whether a `$schema` value declares the 2019-09 dialect — the only supported dialect with -* `$recursiveRef`/`$recursiveAnchor`. Non-throwing (unlike {@linkcode declaredDialect}) so -* wire-layer callers can consult it for documents whose dialect may be unsupported. -*/ -function declares2019Dialect($schema) { - return typeof $schema === "string" && DRAFT_2019_09_URIS.has($schema.replace(/#$/, "")); -} -/** -* Classify a schema's declared `$schema` dialect. No `$schema` (or a non-string one) means -* 2020-12. Any other dialect throws a plain `Error` with a clear message rather than letting the -* engine crash on an opaque internal error or silently mis-validate; `remedy` names the calling -* provider's escape hatch in that message. -*/ -function declaredDialect(schema, remedy) { - if (!("$schema" in schema) || typeof schema.$schema !== "string") return "2020-12"; - const declared = schema.$schema.replace(/#$/, ""); - if (DRAFT_2020_12_URIS.has(declared)) return "2020-12"; - if (DRAFT_2019_09_URIS.has(declared)) return "2019-09"; - if (DRAFT_07_URIS.has(declared) || DRAFT_06_URIS.has(declared)) return "draft-7"; - throw new Error(`JSON Schema declares an unsupported dialect ("$schema": "${schema.$schema.slice(0, 200)}"). The default validator supports JSON Schema 2020-12, 2019-09, draft-07, and draft-06; ${remedy}`); -} - -//#endregion - -//# sourceMappingURL=dialects-DoSzNhcb.mjs.map - -// functions -function assertEqual(val) { - return val; -} -function assertNotEqual(val) { - return val; -} -function toZod() { - return (schema) => schema; -} -function assertIs(_arg) { } -function assertNever(_x) { - throw new Error("Unexpected value in exhaustive check"); -} -function assert(_) { } -function getEnumValues(entries) { - const numericValues = Object.values(entries).filter((v) => typeof v === "number"); - const values = Object.entries(entries) - .filter(([k, _]) => numericValues.indexOf(+k) === -1) - .map(([_, v]) => v); - return values; -} -function joinValues(array, separator = "|") { - return array.map((val) => stringifyPrimitive(val)).join(separator); -} -function jsonStringifyReplacer(_, value) { - if (typeof value === "bigint") - return value.toString(); - return value; -} -function util_cached(getter) { - const set = false; - return { - get value() { - if (!set) { - const value = getter(); - Object.defineProperty(this, "value", { value }); - return value; - } - throw new Error("cached value already set"); - }, - }; -} -function nullish(input) { - return input === null || input === undefined; -} -function cleanRegex(source) { - const start = source.startsWith("^") ? 1 : 0; - const end = source.endsWith("$") ? source.length - 1 : source.length; - return source.slice(start, end); -} -function floatSafeRemainder(val, step) { - const ratio = val / step; - const roundedRatio = Math.round(ratio); - // `val` and `step` each round to a double before the division rounds again, so a true decimal multiple's quotient can sit up to 1.5 of these scaled epsilons from the integer. A 1x tolerance therefore rejected 2.03 as a multiple of 0.07; 4x covers the worst case with margin. - const tolerance = 4 * Number.EPSILON * Math.max(Math.abs(ratio), 1); - if (Math.abs(ratio - roundedRatio) < tolerance) - return 0; - return ratio - roundedRatio; -} -const EVALUATING = /* @__PURE__*/ Symbol("evaluating"); -function defineLazy(object, key, getter) { - let value = undefined; - Object.defineProperty(object, key, { - get() { - if (value === EVALUATING) { - // Circular reference detected, return undefined to break the cycle - return undefined; - } - if (value === undefined) { - value = EVALUATING; - value = getter(); - } - return value; - }, - set(v) { - Object.defineProperty(object, key, { - value: v, - // configurable: true, - }); - // object[key] = v; - }, - configurable: true, - }); -} -function objectClone(obj) { - return Object.create(Object.getPrototypeOf(obj), Object.getOwnPropertyDescriptors(obj)); -} -function assignProp(target, prop, value) { - Object.defineProperty(target, prop, { - value, - writable: true, - enumerable: true, - configurable: true, - }); -} -function mergeDefs(...defs) { - const mergedDescriptors = {}; - for (const def of defs) { - const descriptors = Object.getOwnPropertyDescriptors(def); - Object.assign(mergedDescriptors, descriptors); - } - return Object.defineProperties({}, mergedDescriptors); -} -function cloneDef(schema) { - return mergeDefs(schema._zod.def); -} -function getElementAtPath(obj, path) { - if (!path) - return obj; - return path.reduce((acc, key) => acc?.[key], obj); -} -function promiseAllObject(promisesObj) { - const keys = Object.keys(promisesObj); - const promises = keys.map((key) => promisesObj[key]); - return Promise.all(promises).then((results) => { - const resolvedObj = {}; - for (let i = 0; i < keys.length; i++) { - resolvedObj[keys[i]] = results[i]; - } - return resolvedObj; - }); -} -function randomString(length = 10) { - const chars = "abcdefghijklmnopqrstuvwxyz"; - let str = ""; - for (let i = 0; i < length; i++) { - str += chars[Math.floor(Math.random() * chars.length)]; - } - return str; -} -function util_esc(str) { - return JSON.stringify(str); -} -function slugify(input) { - return input - .toLowerCase() - .trim() - .replace(/[^\w\s-]/g, "") - .replace(/[\s_-]+/g, "-") - .replace(/^-+|-+$/g, ""); -} -const captureStackTrace = ("captureStackTrace" in Error ? Error.captureStackTrace : (..._args) => { }); -function util_isObject(data) { - return typeof data === "object" && data !== null && !Array.isArray(data); -} -const util_allowsEval = /* @__PURE__*/ util_cached(() => { - // Skip the probe under `jitless`: strict CSPs report the caught `new Function` as a `securitypolicyviolation` even though the throw is swallowed. - if (globalConfig.jitless) { - return false; - } - // @ts-ignore - if (typeof navigator !== "undefined" && navigator?.userAgent?.includes("Cloudflare")) { - return false; - } - try { - const F = Function; - new F(""); - return true; - } - catch (_) { - return false; - } -}); -function isPlainObject(o) { - if (util_isObject(o) === false) - return false; - // modified constructor - const ctor = o.constructor; - if (ctor === undefined) - return true; - if (typeof ctor !== "function") - return true; - // modified prototype - const prot = ctor.prototype; - if (util_isObject(prot) === false) - return false; - // ctor doesn't have static `isPrototypeOf` - if (Object.prototype.hasOwnProperty.call(prot, "isPrototypeOf") === false) { - return false; - } - return true; -} -function shallowClone(o) { - if (isPlainObject(o)) - return { ...o }; - if (Array.isArray(o)) - return [...o]; - if (o instanceof Map) - return new Map(o); - if (o instanceof Set) - return new Set(o); - return o; -} -function numKeys(data) { - let keyCount = 0; - for (const key in data) { - if (Object.prototype.hasOwnProperty.call(data, key)) { - keyCount++; - } - } - return keyCount; -} -const getParsedType = (data) => { - const t = typeof data; - switch (t) { - case "undefined": - return "undefined"; - case "string": - return "string"; - case "number": - return Number.isNaN(data) ? "nan" : "number"; - case "boolean": - return "boolean"; - case "function": - return "function"; - case "bigint": - return "bigint"; - case "symbol": - return "symbol"; - case "object": - if (Array.isArray(data)) { - return "array"; - } - if (data === null) { - return "null"; - } - if (data.then && typeof data.then === "function" && data.catch && typeof data.catch === "function") { - return "promise"; - } - if (typeof Map !== "undefined" && data instanceof Map) { - return "map"; - } - if (typeof Set !== "undefined" && data instanceof Set) { - return "set"; - } - if (typeof Date !== "undefined" && data instanceof Date) { - return "date"; - } - // @ts-ignore - if (typeof File !== "undefined" && data instanceof File) { - return "file"; - } - return "object"; - default: - throw new Error(`Unknown data type: ${t}`); - } -}; -const propertyKeyTypes = /* @__PURE__*/ new Set(["string", "number", "symbol"]); -const primitiveTypes = /* @__PURE__*/ (/* unused pure expression or super */ null && (new Set([ - "string", - "number", - "bigint", - "boolean", - "symbol", - "undefined", -]))); -function escapeRegex(str) { - return str.replace(/[.*+?^${}()|[\]\\]/g, "\\$&"); -} -// zod-specific utils -function clone(inst, def, params) { - const cl = new inst._zod.constr(def ?? inst._zod.def); - if (!def || params?.parent) - cl._zod.parent = inst; - return cl; -} -function normalizeParams(_params) { - const params = _params; - if (!params) - return {}; - if (typeof params === "string") - return { error: () => params }; - if (params?.message !== undefined) { - if (params?.error !== undefined) - throw new Error("Cannot specify both `message` and `error` params"); - params.error = params.message; - } - delete params.message; - if (typeof params.error === "string") - return { ...params, error: () => params.error }; - return params; -} -function createTransparentProxy(getter) { - let target; - return new Proxy({}, { - get(_, prop, receiver) { - target ?? (target = getter()); - return Reflect.get(target, prop, receiver); - }, - set(_, prop, value, receiver) { - target ?? (target = getter()); - return Reflect.set(target, prop, value, receiver); - }, - has(_, prop) { - target ?? (target = getter()); - return Reflect.has(target, prop); - }, - deleteProperty(_, prop) { - target ?? (target = getter()); - return Reflect.deleteProperty(target, prop); - }, - ownKeys(_) { - target ?? (target = getter()); - return Reflect.ownKeys(target); - }, - getOwnPropertyDescriptor(_, prop) { - target ?? (target = getter()); - return Reflect.getOwnPropertyDescriptor(target, prop); - }, - defineProperty(_, prop, descriptor) { - target ?? (target = getter()); - return Reflect.defineProperty(target, prop, descriptor); - }, - }); -} -function stringifyPrimitive(value) { - if (typeof value === "bigint") - return value.toString() + "n"; - if (typeof value === "string") - return `"${value}"`; - return `${value}`; -} -function optionalKeys(shape) { - return Object.keys(shape).filter((k) => { - return shape[k]._zod.optin !== undefined && shape[k]._zod.optout === "optional"; - }); -} -// Wrapped in a `@__PURE__` IIFE: esbuild never tree-shakes a top-level initializer that contains a member access on `Number`, so the bare object literal survived into every bundle. -const NUMBER_FORMAT_RANGES = /*@__PURE__*/ (() => ({ - safeint: [Number.MIN_SAFE_INTEGER, Number.MAX_SAFE_INTEGER], - int32: [-2147483648, 2147483647], - uint32: [0, 4294967295], - float32: [-3.4028234663852886e38, 3.4028234663852886e38], - float64: [-Number.MAX_VALUE, Number.MAX_VALUE], -}))(); -const BIGINT_FORMAT_RANGES = { - int64: [/* @__PURE__*/ BigInt("-9223372036854775808"), /* @__PURE__*/ BigInt("9223372036854775807")], - uint64: [/* @__PURE__*/ BigInt(0), /* @__PURE__*/ BigInt("18446744073709551615")], -}; -function pick(schema, mask) { - const currDef = schema._zod.def; - const checks = currDef.checks; - const hasChecks = checks && checks.length > 0; - if (hasChecks) { - throw new Error(".pick() cannot be used on object schemas containing refinements"); - } - const def = mergeDefs(schema._zod.def, { - get shape() { - const newShape = {}; - // `for...in` skips symbols, so a symbol in the mask would select nothing - for (const key of Reflect.ownKeys(mask)) { - if (!Object.prototype.hasOwnProperty.call(currDef.shape, key)) { - throw new Error(`Unrecognized key: "${String(key)}"`); - } - if (!mask[key]) - continue; - assignProp(newShape, key, currDef.shape[key]); - } - assignProp(this, "shape", newShape); // self-caching - return newShape; - }, - checks: [], - }); - return clone(schema, def); -} -function omit(schema, mask) { - const currDef = schema._zod.def; - const checks = currDef.checks; - const hasChecks = checks && checks.length > 0; - if (hasChecks) { - throw new Error(".omit() cannot be used on object schemas containing refinements"); - } - const def = mergeDefs(schema._zod.def, { - get shape() { - const newShape = { ...schema._zod.def.shape }; - for (const key of Reflect.ownKeys(mask)) { - if (!Object.prototype.hasOwnProperty.call(currDef.shape, key)) { - throw new Error(`Unrecognized key: "${String(key)}"`); - } - if (!mask[key]) - continue; - delete newShape[key]; - } - assignProp(this, "shape", newShape); // self-caching - return newShape; - }, - checks: [], - }); - return clone(schema, def); -} -function extend(schema, shape) { - if (!isPlainObject(shape)) { - throw new Error("Invalid input to extend: expected a plain object"); - } - const checks = schema._zod.def.checks; - const hasChecks = checks && checks.length > 0; - if (hasChecks) { - // Only throw if new shape overlaps with existing shape. Use getOwnPropertyDescriptor to check key existence without accessing values - const existingShape = schema._zod.def.shape; - for (const key of Reflect.ownKeys(shape)) { - if (Object.getOwnPropertyDescriptor(existingShape, key) !== undefined) { - throw new Error("Cannot overwrite keys on object schemas containing refinements. Use `.safeExtend()` instead."); - } - } - } - const def = mergeDefs(schema._zod.def, { - get shape() { - const _shape = { ...schema._zod.def.shape, ...shape }; - assignProp(this, "shape", _shape); // self-caching - return _shape; - }, - }); - return clone(schema, def); -} -function safeExtend(schema, shape) { - if (!isPlainObject(shape)) { - throw new Error("Invalid input to safeExtend: expected a plain object"); - } - const def = mergeDefs(schema._zod.def, { - get shape() { - const _shape = { ...schema._zod.def.shape, ...shape }; - assignProp(this, "shape", _shape); // self-caching - return _shape; - }, - }); - return clone(schema, def); -} -function merge(a, b) { - if (!b?._zod?.def) { - throw new Error("Invalid input to merge: expected an object schema. To merge a plain shape, use `.extend()`."); - } - if (a._zod.def.checks?.length) { - throw new Error(".merge() cannot be used on object schemas containing refinements. Use .safeExtend() instead."); - } - const def = mergeDefs(a._zod.def, { - get shape() { - const _shape = { ...a._zod.def.shape, ...b._zod.def.shape }; - assignProp(this, "shape", _shape); // self-caching - return _shape; - }, - get catchall() { - return b._zod.def.catchall; - }, - checks: b._zod.def.checks ?? [], - }); - return clone(a, def); -} -function partial(Class, schema, mask, name = "partial") { - const currDef = schema._zod.def; - const checks = currDef.checks; - const hasChecks = checks && checks.length > 0; - if (hasChecks) { - throw new Error(`.${name}() cannot be used on object schemas containing refinements`); - } - const def = mergeDefs(schema._zod.def, { - get shape() { - const oldShape = schema._zod.def.shape; - const shape = { ...oldShape }; - if (mask) { - for (const key of Reflect.ownKeys(mask)) { - if (!Object.prototype.hasOwnProperty.call(oldShape, key)) { - throw new Error(`Unrecognized key: "${String(key)}"`); - } - if (!mask[key]) - continue; - // if (oldShape[key]!._zod.optin === "optional") continue; - shape[key] = Class - ? new Class({ - type: "optional", - innerType: oldShape[key], - }) - : oldShape[key]; - } - } - else { - // the spread copies symbol keys; `for...in` would not reach them - for (const key of Reflect.ownKeys(oldShape)) { - // if (oldShape[key]!._zod.optin === "optional") continue; - shape[key] = Class - ? new Class({ - type: "optional", - innerType: oldShape[key], - }) - : oldShape[key]; - } - } - assignProp(this, "shape", shape); // self-caching - return shape; - }, - checks: [], - }); - return clone(schema, def); -} -function util_required(Class, schema, mask) { - const def = mergeDefs(schema._zod.def, { - get shape() { - const oldShape = schema._zod.def.shape; - const shape = { ...oldShape }; - if (mask) { - for (const key of Reflect.ownKeys(mask)) { - if (!Object.prototype.hasOwnProperty.call(shape, key)) { - throw new Error(`Unrecognized key: "${String(key)}"`); - } - if (!mask[key]) - continue; - // overwrite with non-optional - shape[key] = new Class({ - type: "nonoptional", - innerType: oldShape[key], - }); - } - } - else { - for (const key of Reflect.ownKeys(oldShape)) { - // overwrite with non-optional - shape[key] = new Class({ - type: "nonoptional", - innerType: oldShape[key], - }); - } - } - assignProp(this, "shape", shape); // self-caching - return shape; - }, - }); - return clone(schema, def); -} -// invalid_type | too_big | too_small | invalid_format | not_multiple_of | unrecognized_keys | invalid_union | invalid_key | invalid_element | invalid_value | custom -function aborted(x, startIndex = 0) { - if (x.aborted === true) - return true; - for (let i = startIndex; i < x.issues.length; i++) { - if (x.issues[i]?.continue !== true) { - return true; - } - } - return false; -} -// Checks for explicit abort (continue === false), as opposed to implicit abort (continue === undefined). Used to respect `abort: true` in .refine() even for checks that have a `when` function. -function explicitlyAborted(x, startIndex = 0) { - if (x.aborted === true) - return true; - for (let i = startIndex; i < x.issues.length; i++) { - if (x.issues[i]?.continue === false) { - return true; - } - } - return false; -} -function prefixIssues(path, issues) { - return issues.map((iss) => { - var _a; - (_a = iss).path ?? (_a.path = []); - iss.path.unshift(path); - return iss; - }); -} -function unwrapMessage(message) { - return typeof message === "string" ? message : message?.message; -} -/* A check holds no link back to the schema it is attached to — the same check instance is shared by every clone of that schema — so the owner is stamped onto the issues a check just raised, at the only point where both are in scope. Runs on the failure path only; `start` is the issue count from before the check ran. */ -function attachSchema(issues, start, inst) { - var _a; - for (let i = start; i < issues.length; i++) { - (_a = issues[i]).schema ?? (_a.schema = inst); - } -} -function finalizeIssue(iss, ctx, config) { - var _a; - // A schema that raised an issue itself owns it outright, and outranks any stamp an enclosing check left in `attachSchema`. String formats and z.custom() are schema and check at once, so when they act as a check they defer to that stamp instead. - const traits = iss.inst?._zod?.traits; - if (traits?.has("$ZodType")) { - if (traits.has("$ZodCheck")) - (_a = iss).schema ?? (_a.schema = iss.inst); - else - iss.schema = iss.inst; - } - // Decreasing specificity, first map to return a message wins. `inst` is whatever raised the issue, so a check's own map outranks the owning schema's. - const schemaError = iss.schema !== iss.inst ? iss.schema?._zod.def?.error : undefined; - const message = iss.message - ? iss.message - : (unwrapMessage(iss.inst?._zod.def?.error?.(iss)) ?? - unwrapMessage(schemaError?.(iss)) ?? - unwrapMessage(ctx?.error?.(iss)) ?? - unwrapMessage(config.customError?.(iss)) ?? - unwrapMessage(config.localeError?.(iss)) ?? - "Invalid input"); - const { inst: _inst, schema: _schema, continue: _continue, input: _input, ...rest } = iss; - rest.path ?? (rest.path = []); - rest.message = message; - if (ctx?.reportInput) { - rest.input = _input; - } - return rest; -} -function getSizableOrigin(input) { - if (input instanceof Set) - return "set"; - if (input instanceof Map) - return "map"; - // @ts-ignore - if (input instanceof File) - return "file"; - return "unknown"; -} -const highSurrogate = /[\uD800-\uDBFF]/; -// Code points in `str`: a surrogate pair counts once, a lone surrogate as itself. Hand-rolled because the string iterator allocates and runs ~250x slower on this path; the regex probe exits ~50x quicker for a string with no astral characters. -function codePointLength(str) { - const units = str.length; - if (!highSurrogate.test(str)) - return units; - let count = units; - for (let i = 0; i < units - 1; i++) { - if ((str.charCodeAt(i) & 0xfc00) === 0xd800 && (str.charCodeAt(i + 1) & 0xfc00) === 0xdc00) { - count--; - i++; - } - } - return count; -} -function getLengthableOrigin(input) { - if (Array.isArray(input)) - return "array"; - if (typeof input === "string") - return "string"; - return "unknown"; -} -function parsedType(data) { - const t = typeof data; - switch (t) { - case "number": { - return Number.isNaN(data) ? "nan" : "number"; - } - case "object": { - if (data === null) { - return "null"; - } - if (Array.isArray(data)) { - return "array"; - } - const obj = data; - if (obj && Object.getPrototypeOf(obj) !== Object.prototype && "constructor" in obj && obj.constructor) { - return obj.constructor.name; - } - } - } - return t; -} -function util_issue(...args) { - const [iss, input, inst] = args; - if (typeof iss === "string") { - return { - message: iss, - code: "custom", - input, - inst, - }; - } - return { ...iss }; -} -function cleanEnum(obj) { - return Object.entries(obj) - .filter(([k, _]) => { - // return true if NaN, meaning it's not a number, thus a string key - return Number.isNaN(Number.parseInt(k, 10)); - }) - .map((el) => el[1]); -} -// Codec utility functions -function base64ToUint8Array(base64) { - const binaryString = atob(base64); - const bytes = new Uint8Array(binaryString.length); - for (let i = 0; i < binaryString.length; i++) { - bytes[i] = binaryString.charCodeAt(i); - } - return bytes; -} -function uint8ArrayToBase64(bytes) { - let binaryString = ""; - for (let i = 0; i < bytes.length; i++) { - binaryString += String.fromCharCode(bytes[i]); - } - return btoa(binaryString); -} -function base64urlToUint8Array(base64url) { - const base64 = base64url.replace(/-/g, "+").replace(/_/g, "/"); - const padding = "=".repeat((4 - (base64.length % 4)) % 4); - return base64ToUint8Array(base64 + padding); -} -function uint8ArrayToBase64url(bytes) { - return uint8ArrayToBase64(bytes).replace(/\+/g, "-").replace(/\//g, "_").replace(/=/g, ""); -} -function hexToUint8Array(hex) { - const cleanHex = hex.replace(/^0x/, ""); - if (cleanHex.length % 2 !== 0) { - throw new Error("Invalid hex string length"); - } - const bytes = new Uint8Array(cleanHex.length / 2); - for (let i = 0; i < cleanHex.length; i += 2) { - bytes[i / 2] = Number.parseInt(cleanHex.slice(i, i + 2), 16); - } - return bytes; -} -function uint8ArrayToHex(bytes) { - return Array.from(bytes) - .map((b) => b.toString(16).padStart(2, "0")) - .join(""); -} -// instanceof -class util_Class { - constructor(..._args) { } -} -////////// PROTOTYPE INSTALLERS ////////// -// -// Members live on the prototype and materialize per instance on first read, which keeps own-property count under the step where V8 stops using inline slots. Changing anything here means re-measuring runtime, memory and bundle size together — see "The three axes" in AGENTS.md. -/** - * Installs a trait's members on its prototype. Each value builds that member for the instance on first read; the built value shadows the accessor as an own property, so a detached `const { parse } = schema` keeps working. - * - * Call this from a `proto` initializer, which runs once per prototype — never per instance. - */ -function util_members(proto, table) { - for (const key in table) { - const desc = Object.getOwnPropertyDescriptor(table, key); - // a getter installs as written, so it stays live: `description` reads through to the registry on every access. not enumerable: an object literal's is, and a prototype member never was - if (desc.get) - Object.defineProperty(proto, key, { ...desc, enumerable: false }); - // a method materializes bound on first read, which is what keeps a detached member working: `const opt = schema.optional; opt()` - else - defineBound(proto, key, desc.value); - } -} -/** Shadows a prototype member with an own value, so a getter that builds from the instance runs once. */ -function util_own(inst, key, value, enumerable = true) { - Object.defineProperty(inst, key, { configurable: true, writable: true, enumerable, value }); - return value; -} -/** Like {@link own}, for a member that was never an own data property and has to stay out of `Object.keys`. */ -function hide(inst, key, value) { - return util_own(inst, key, value, false); -} -function defineBound(proto, key, fn) { - Object.defineProperty(proto, key, { - configurable: true, - get() { - // vitest's spyOn calls a prototype getter bare to find the function it wraps, so a nullish receiver answers the raw method - return this == null ? fn : util_own(this, key, fn.bind(this)); - }, - set(value) { - util_own(this, key, value); - }, - }); -} -/** Returns the prototype to install on, or `undefined` if this group is already installed on it. */ -function claim(inst, sentinel) { - const proto = Object.getPrototypeOf(inst); - // Runs on every construction, so `in` rather than the costlier `hasOwnProperty.call`. Sentinels are keys the group itself defines. - return sentinel in proto ? undefined : proto; -} -// The internals whose init chain is installing. A second call for the same one is a derived constructor overriding its base, so it must not construct another schema in between or the override is dropped. -let installing; -// Set while a getter is running, so a value that resolved through a recursion break is not memoized. One shared descriptor shadows the key for the duration, which costs no per-key allocation. -let broke = false; -const breaker = { - configurable: true, - get() { - broke = true; - return undefined; - }, -}; -/** - * Installs a lazily-derived internal on the `_zod` prototype of `inst`'s - * constructor, computed from the internals object itself and cached there on - * first read. One accessor per constructor rather than one per instance. - */ -function defineLazyInternal(inst, key, compute) { - const proto = Object.getPrototypeOf(inst._zod); - if (key in proto && installing !== inst._zod) { - // A repeat construction: everything is installed already. Cleared here so the reference is not held past the first construction of every type. - installing = undefined; - return; - } - installing = inst._zod; - Object.defineProperty(proto, key, { - configurable: true, - get() { - // Shadowed before computing so a re-entrant read from a recursive schema resolves to undefined instead of running the getter again. - Object.defineProperty(this, key, breaker); - const outer = broke; - broke = false; - try { - const value = compute(this); - // A result that resolved through a recursion break is recomputed once the graph is complete; everything else memoizes, undefined included. - if (broke) - delete this[key]; - else - Object.defineProperty(this, key, { configurable: true, writable: true, value }); - broke = broke || outer; - return value; - } - catch (err) { - // A compute that threw memoizes nothing, so a later read runs it again and fails the same way. The shadow goes with it, since leaving it installed would answer undefined for every later read. - delete this[key]; - broke = broke || outer; - throw err; - } - }, - set(value) { - Object.defineProperty(this, key, { configurable: true, writable: true, value }); - }, - }); -} -/** - * Installs `key` on `inst`'s prototype, computed by `make` on first read and cached there as an own - * data property. One accessor per constructor rather than one per instance, because an own accessor - * puts every instance after the first into v8 dictionary mode. The key doubles as the sentinel. - */ -function installLazyProp(inst, key, make, enumerable) { - const proto = claim(inst, key); - if (!proto) - return; - Object.defineProperty(proto, key, { - configurable: true, - get() { - // Shadowed before computing, so a re-entrant read from a self-referential shape resolves to undefined instead of running the getter again. A data property rather than an accessor: an own accessor is the dictionary-mode transition this exists to avoid. - const desc = { configurable: true, writable: true, enumerable, value: undefined }; - Object.defineProperty(this, key, desc); - // a compute that throws leaves the shadow behind, so later reads answer undefined instead of re-throwing; `defineLazy` did the same, and `defineLazyInternal`'s delete-on-catch would cost bytes in every bundle for a case only a throwing user getter reaches - desc.value = make(this); - Object.defineProperty(this, key, desc); - return desc.value; - }, - set(value) { - Object.defineProperty(this, key, { configurable: true, writable: true, enumerable, value }); - }, - }); -} -/** Marks the thunk `_catch` synthesises for a constant catch value. `Function.length` cannot tell that thunk from a user callback — rest and defaulted parameters both report arity 0 — and a user callback reads `ctx.error`, whose issues only finalize correctly against the caller's per-parse error map. Provenance can say what arity cannot. A plain string key rather than `Symbol.for`, whose call at module scope no bundler can prove pure — the same shape that anchored `urlCanParse` into every build. */ -const CONSTANT_CATCH = "~constantCatch"; -/** Wraps a constant catch value in a thunk tagged with {@link CONSTANT_CATCH}. */ -function constantCatch(value) { - const fn = () => value; - fn[CONSTANT_CATCH] = true; - return fn; -} - -var core_a; - -/** A special constant with type `never` */ -const NEVER = /*@__PURE__*/ Object.freeze({ - status: "aborted", -}); -/* Shared descriptor for installing `_zod`; defineProperty reads it - * synchronously, so reusing one object avoids a per-instance allocation. */ -const _zodDesc = { value: undefined, enumerable: false }; -// null where suppressing the capture would be unrecoverable: `parse()` puts the frames back with `captureStackTrace`, so without it the throw would lose its stack. also latched to null once `stackTraceLimit` proves unassignable, which a realm can do at any point by hardening Error -let _E = "captureStackTrace" in Error ? Error : null; -// v8 captures a stack trace inside the Error constructor, which dominates a failed parse; costs only the frames, and parse() restores those. the constructor must RUN: Object.create is cheaper and passes instanceof, but Error.isError and util.types.isNativeError check an internal slot -function newError(Definition) { - const E = _E; - if (E) { - const saved = E.stackTraceLimit; - if (typeof saved === "number") { - try { - E.stackTraceLimit = 0; - } - catch { - _E = null; - return new Definition(); - } - try { - return new Definition(); - } - finally { - E.stackTraceLimit = saved; - } - } - } - return new Definition(); -} -function $constructor(name, initializer, -/** This trait's members, installed once on every prototype that composes it. They cannot be declared in the initializer above: that runs per instance, and the prototype is shared. */ -proto, params) { - // Prototype for this constructor's `_zod` internals. Lazily-derived fields (`values`, `pattern`, `optin`, …) install here once rather than as an accessor on every instance. - const zodProto = {}; - // Assigning the fields in the constructor body is what gives instances in-object slots; building the object literally and reparenting it costs a second allocation and a generic property copy. - function Internals(def) { - this.def = def; - this.constr = _; - this.traits = new Set(); - } - Internals.prototype = zodProto; - const protoMembers = proto; - // One trait's members land on every prototype whose chain composes it, so the answer is per prototype rather than per trait. - const initialized = protoMembers && new WeakSet(); - function init(inst, def) { - if (!inst._zod) { - _zodDesc.value = new Internals(def); - try { - Object.defineProperty(inst, "_zod", _zodDesc); - } - finally { - // Cleared even on throw, so the shared descriptor never leaks one instance's internals into the next. - _zodDesc.value = undefined; - } - } - if (inst._zod.traits.has(name)) { - return; - } - inst._zod.traits.add(name); - initializer(inst, def); - if (initialized) { - // `super(def)` from a user subclass gives `this` a prototype the subclass owns, and installing there would overwrite whatever the subclass declared. `constr` built the instance, so its prototype is the one below the subclass's that should carry the members. A receiver whose chain never reaches that prototype installs on its own, which for a plain object handed straight to `init` means `Object.prototype` — unchanged from before. - const own = Object.getPrototypeOf(inst); - const ctorProto = inst._zod.constr.prototype; - let up = own; - while (up && up !== ctorProto) - up = Object.getPrototypeOf(up); - const target = up ?? own; - if (!initialized.has(target)) { - initialized.add(target); - util_members(target, protoMembers); - } - } - // support prototype modifications; for-in avoids the array allocation of Object.keys on the (usually empty) prototype - const proto = _.prototype; - for (const k in proto) { - if (!Object.prototype.hasOwnProperty.call(proto, k)) - continue; - if (!(k in inst)) { - inst[k] = proto[k].bind(inst); - } - } - } - // doesn't work if Parent has a constructor with arguments - const Parent = params?.Parent ?? Object; - class Definition extends Parent { - } - Object.defineProperty(Definition, "name", { value: name }); - function _(def) { - const inst = params?.Parent ? newError(Definition) : this; - init(inst, def); - const deferred = inst._zod.deferred; - if (deferred) { - for (const fn of deferred) { - fn(); - } - // Released: initializers run once, and the list would otherwise be retained for the schema's lifetime. - inst._zod.deferred = undefined; - } - // Global post-processor hook. Internal: installed by `import "zod/compile"` to enable AOT compilation for every constructed schema. Runs last, once the instance is fully built, because it hands the instance to compile(). The post-processor is expected to be reentrancy-guarded by its own implementation. - const pp = globalThis.__zod_globalConfig?.postProcessor; - if (pp) - pp(inst); - return inst; - } - Object.defineProperty(_, "init", { value: init }); - Object.defineProperty(_, Symbol.hasInstance, { - value: (inst) => { - if (params?.Parent && inst instanceof params.Parent) - return true; - return inst?._zod?.traits?.has(name); - }, - }); - Object.defineProperty(_, "name", { value: name }); - return _; -} -////////////////////////////// UTILITIES /////////////////////////////////////// -const $brand = /*@__PURE__*/ (/* unused pure expression or super */ null && (Symbol("zod_brand"))); -class $ZodAsyncError extends Error { - constructor() { - super(`Encountered Promise during synchronous parse. Use .parseAsync() instead.`); - } -} -class $ZodEncodeError extends Error { - constructor(name) { - super(`Encountered unidirectional transform during encode: ${name}`); - this.name = "ZodEncodeError"; - } -} -(core_a = globalThis).__zod_globalConfig ?? (core_a.__zod_globalConfig = {}); -const globalConfig = globalThis.__zod_globalConfig; -function core_config(newConfig) { - if (newConfig) - Object.assign(globalConfig, newConfig); - return globalConfig; -} - -class $ZodCyclicError extends Error { - constructor() { - super(`Cannot parse a reference cycle that closes through a transform`); - this.name = "ZodCyclicError"; - } -} -/** Keyed off the context object every schema in one parse call already shares. */ -const STATE = "~memo"; -const NO_ISSUES = []; -// Receivers prefix paths in place, so the cache and every hand-out need their own copies. -function cloneIssues(issues) { - return issues.map((iss) => (iss.path ? { ...iss, path: iss.path.slice() } : { ...iss })); -} -const recursive = /*@__PURE__*/ new WeakMap(); -/** Whether this schema's subtree contains a cycle, so one parse can re-enter it. */ -function isRecursive(inst, stack) { - const cached = recursive.get(inst); - if (cached !== undefined) - return cached; - // Relative to the walk in progress, so not cached. - if (stack.has(inst)) - return true; - stack.add(inst); - let result = false; - const check = (child) => { - if (!result && child?._zod && isRecursive(child, stack)) - result = true; - }; - const def = inst._zod.def; - const kind = def.type; - switch (kind) { - case "object": { - // `Reflect.ownKeys` rather than `Object.keys`, so a cycle through a declared symbol key is still seen - for (const key of Reflect.ownKeys(def.shape)) - check(def.shape[key]); - check(def.catchall); - break; - } - case "array": - check(def.element); - break; - case "tuple": - for (const el of def.items) - check(el); - check(def.rest); - break; - case "record": - case "map": - check(def.keyType); - check(def.valueType); - break; - case "set": - check(def.valueType); - break; - case "union": - for (const el of def.options) - check(el); - break; - case "intersection": - check(def.left); - check(def.right); - break; - case "optional": - case "nullable": - case "default": - case "prefault": - case "catch": - case "readonly": - case "nonoptional": - case "promise": - case "success": - check(def.innerType); - break; - case "pipe": - check(def.in); - check(def.out); - break; - case "function": - check(def.input); - check(def.output); - break; - // reading `_zod.innerType` resolves the getter once and caches it - case "lazy": - check(inst._zod.innerType); - break; - // a leaf by choice: `parts` are regex fragments, not data positions - case "template_literal": - // leaves - case "string": - case "number": - case "int": - case "boolean": - case "bigint": - case "symbol": - case "undefined": - case "null": - case "void": - case "never": - case "any": - case "unknown": - case "date": - case "nan": - case "enum": - case "literal": - case "file": - case "transform": - case "custom": - break; - default: { - // a new built-in kind becomes a compile error here - kind; - // a user-defined kind can still hold children, and only its author knows where, so fall back to scanning the def — skipping accessors, since reading one can run user code - for (const key in def) { - const desc = Object.getOwnPropertyDescriptor(def, key); - if (!desc || desc.get) - continue; - const value = desc.value; - if (!value || typeof value !== "object") - continue; - if (value._zod) - check(value); - else if (Array.isArray(value)) - for (const el of value) - check(el); - } - } - } - stack.delete(inst); - recursive.set(inst, result); - return result; -} -/** - * Whether one parse can re-enter this schema, i.e. its subtree contains a cycle. - * Exported for `z.compile`, which refuses to compile such a schema: cycle - * breaking is driven from here off state keyed on the parse context, and a - * generated fast path has no context to key on. - */ -function isRecursiveSchema(inst) { - return isRecursive(inst, new Set()); -} -function bucketFor(state, inst) { - let bucket = state.buckets.get(inst); - if (!bucket) { - bucket = new Map(); - state.buckets.set(inst, bucket); - } - return bucket; -} -// Set immediately before delegating to core and cleared immediately after, so `alloc` registers only for a visit this module is driving. -let handoff; -// Allocated but unfinished entries. `alloc` and the matching pop both happen in the synchronous part of a parse, so they nest even when children are async, and one stack serves every schema. -const memoizer_open = []; -const memoizer_memo = { - alloc(_inst, payload, empty) { - const bucket = handoff; - if (!bucket) - return empty; - handoff = undefined; - const entry = { value: empty, issues: null }; - bucket.set(payload.value, entry); - memoizer_open.push(entry); - return empty; - }, - guard(inst) { - var _a; - (_a = inst._zod).deferred ?? (_a.deferred = []); - inst._zod.deferred.push(() => { - const base = inst._zod.parse; - const wrapped = (payload, ctx) => { - // The value is a placeholder a back-edge is still waiting on, so the cycle closes through this transform. Its output can't exist in time to bind. - if (ctx.direction !== "backward" && isBackEdge(ctx, payload.value)) - throw new $ZodCyclicError(); - return base(payload, ctx); - }; - inst._zod.parse = wrapped; - if (inst._zod.run === base) - inst._zod.run = wrapped; - }); - }, - attach(inst) { - var _a; - let isRecursiveInst; - // `bucket` memoized for one parse; a recursive schema is re-entered many times and its bucket never changes - let lastCtx; - let lastBucket; - // Wraps `parse` in a deferred so it sees the container's final parse. Core's own deferred copies `parse` into `run` when there are no checks, and it ran first, so `run` is patched to match; with checks, `run` reads `parse` dynamically. - (_a = inst._zod).deferred ?? (_a.deferred = []); - inst._zod.deferred.push(() => { - const base = inst._zod.parse; - const wrapped = (payload, ctx) => { - if (isRecursiveInst === undefined) { - isRecursiveInst = isRecursive(inst, new Set()); - if (!isRecursiveInst) { - // Nothing here can ever fire, so take it back out. - inst._zod.parse = base; - if (inst._zod.run === wrapped) - inst._zod.run = base; - return base(payload, ctx); - } - } - const input = payload.value; - if (input === null || typeof input !== "object") - return base(payload, ctx); - let state = ctx[STATE]; - if (!state) { - state = { buckets: new Map(), backEdges: undefined }; - ctx[STATE] = state; - } - let bucket; - if (lastCtx === ctx) { - bucket = lastBucket; - } - else { - bucket = bucketFor(state, inst); - lastCtx = ctx; - lastBucket = bucket; - } - const hit = bucket.get(input); - if (hit) { - payload.value = hit.value; - if (hit.issues) { - if (hit.issues.length) - payload.issues.push(...cloneIssues(hit.issues)); - } - else { - // Still being parsed: its own checks cover it, so skip them here. - payload.memo = true; - state.backEdges ?? (state.backEdges = new Set()); - state.backEdges.add(hit.value); - } - return payload; - } - handoff = bucket; - const depth = memoizer_open.length; - const result = base(payload, ctx); - handoff = undefined; - // A container that rejected its input outright allocated nothing. - const entry = memoizer_open.length > depth ? memoizer_open.pop() : undefined; - // Both paths written out so the sync one allocates no closure. It runs once per node, and capturing here cost more than everything else combined. - if (result instanceof Promise) { - return result.then((r) => { - if (entry) - entry.issues = r.issues.length ? cloneIssues(r.issues) : NO_ISSUES; - return r; - }); - } - if (entry) - entry.issues = result.issues.length ? cloneIssues(result.issues) : NO_ISSUES; - return result; - }; - inst._zod.parse = wrapped; - if (inst._zod.run === base) - inst._zod.run = wrapped; - }); - }, -}; -/** The memoizer that gives containers cycle support. `zod` installs it by default; `zod/mini` opts in with `config({ memoizer: memoizer() })`. */ -function memoizer() { - return memoizer_memo; -} -/** Whether this value is a node a back-edge resolved to before it finished. */ -function isBackEdge(ctx, value) { - const backEdges = ctx[STATE]?.backEdges; - return backEdges !== undefined && value !== null && typeof value === "object" && backEdges.has(value); -} - - -/** - * @deprecated CUID v1 is deprecated by its authors due to information leakage - * (timestamps embedded in the id). Use {@link cuid2} instead. - * See https://github.com/paralleldrive/cuid. - */ -const cuid = /^[cC][0-9a-z]{6,}$/; -const cuid2 = /^[0-9a-z]+$/; -const ulid = /^[0-7][0-9A-HJKMNP-TV-Za-hjkmnp-tv-z]{25}$/; -const xid = /^[0-9a-vA-V]{20}$/; -const ksuid = /^[A-Za-z0-9]{27}$/; -const nanoid = /^[a-zA-Z0-9_-]{21}$/; -function nanoidOfLength(length) { - return new RegExp(`^[a-zA-Z0-9_-]{${length}}$`); -} -/** ISO 8601-1 duration regex. Does not support the 8601-2 extensions like negative durations or fractional/negative components. */ -const duration = /^P(?:(\d+W)|(?!.*W)(?=\d|T\d)(\d+Y)?(\d+M)?(\d+D)?(T(?=\d)(\d+H)?(\d+M)?(\d+([.,]\d+)?S)?)?)$/; -/** Implements ISO 8601-2 extensions like explicit +- prefixes, mixing weeks with other units, and fractional/negative components. */ -const extendedDuration = /^[-+]?P(?!$)(?:(?:[-+]?\d+Y)|(?:[-+]?\d+[.,]\d+Y$))?(?:(?:[-+]?\d+M)|(?:[-+]?\d+[.,]\d+M$))?(?:(?:[-+]?\d+W)|(?:[-+]?\d+[.,]\d+W$))?(?:(?:[-+]?\d+D)|(?:[-+]?\d+[.,]\d+D$))?(?:T(?=[\d+-])(?:(?:[-+]?\d+H)|(?:[-+]?\d+[.,]\d+H$))?(?:(?:[-+]?\d+M)|(?:[-+]?\d+[.,]\d+M$))?(?:[-+]?\d+(?:[.,]\d+)?S)?)??$/; -/** A regex for any UUID-like identifier: 8-4-4-4-12 hex pattern */ -const guid = /^([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})$/; -/** Returns a regex for validating an RFC 9562/4122 UUID. - * - * @param version Optionally specify a version 1-8. If no version is specified, all versions are supported. */ -const uuid = (version) => { - if (!version) - return /^([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)$/; - return new RegExp(`^([0-9a-fA-F]{8}-[0-9a-fA-F]{4}-${version}[0-9a-fA-F]{3}-[89abAB][0-9a-fA-F]{3}-[0-9a-fA-F]{12})$`); -}; -const uuid4 = /*@__PURE__*/ (/* unused pure expression or super */ null && (uuid(4))); -const uuid6 = /*@__PURE__*/ (/* unused pure expression or super */ null && (uuid(6))); -const uuid7 = /*@__PURE__*/ (/* unused pure expression or super */ null && (uuid(7))); -/** Practical email validation */ -const email = /^(?!\.)(?!.*\.\.)([A-Za-z0-9_'+\-\.]*)[A-Za-z0-9_+-]@([A-Za-z0-9][A-Za-z0-9\-]*\.)+[A-Za-z]{2,}$/; -/** Equivalent to the HTML5 input[type=email] validation implemented by browsers. Source: https://developer.mozilla.org/en-US/docs/Web/HTML/Element/input/email */ -const html5Email = /^[a-zA-Z0-9.!#$%&'*+/=?^_`{|}~-]+@[a-zA-Z0-9](?:[a-zA-Z0-9-]{0,61}[a-zA-Z0-9])?(?:\.[a-zA-Z0-9](?:[a-zA-Z0-9-]{0,61}[a-zA-Z0-9])?)*$/; -/** The classic emailregex.com regex for RFC 5322-compliant emails */ -const rfc5322Email = /^(([^<>()\[\]\\.,;:\s@"]+(\.[^<>()\[\]\\.,;:\s@"]+)*)|(".+"))@((\[[0-9]{1,3}\.[0-9]{1,3}\.[0-9]{1,3}\.[0-9]{1,3}])|(([a-zA-Z\-0-9]+\.)+[a-zA-Z]{2,}))$/; -/** A loose regex that allows Unicode characters, enforces length limits, and that's about it. */ -const unicodeEmail = /^[^\s@"]{1,64}@[^\s@]{1,255}$/u; -const idnEmail = (/* unused pure expression or super */ null && (unicodeEmail)); -const browserEmail = /^[a-zA-Z0-9.!#$%&'*+/=?^_`{|}~-]+@[a-zA-Z0-9](?:[a-zA-Z0-9-]{0,61}[a-zA-Z0-9])?(?:\.[a-zA-Z0-9](?:[a-zA-Z0-9-]{0,61}[a-zA-Z0-9])?)*$/; -// from https://thekevinscott.com/emojis-in-javascript/#writing-a-regular-expression -// Single character class, not an alternation: the two properties overlap (U+1F9B0-U+1F9B3), so `(A|B)+` backtracks exponentially on a failed match. -const _emoji = `^[\\p{Extended_Pictographic}\\p{Emoji_Component}]+$`; -function emoji() { - return new RegExp(_emoji, "u"); -} -const ipv4 = /^(?:(?: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])$/; -const regexes_ipv6 = /^(([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}|:))$/; -const mac = (delimiter) => { - const escapedDelim = util.escapeRegex(delimiter ?? ":"); - return new RegExp(`^(?:[0-9A-F]{2}${escapedDelim}){5}[0-9A-F]{2}$|^(?:[0-9a-f]{2}${escapedDelim}){5}[0-9a-f]{2}$`); -}; -const cidrv4 = /^((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])$/; -const cidrv6 = /^(([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}|:))\/(12[0-8]|1[01][0-9]|[1-9]?[0-9])$/; -// https://stackoverflow.com/questions/7860392/determine-if-string-is-in-base64-using-javascript -const regexes_base64 = /^$|^(?:[0-9a-zA-Z+/]{4})*(?:(?:[0-9a-zA-Z+/]{2}==)|(?:[0-9a-zA-Z+/]{3}=))?$/; -const regexes_base64url = /^[A-Za-z0-9_-]*$/; -// based on https://stackoverflow.com/questions/106179/regular-expression-to-match-dns-hostname-or-ip-address -// export const hostname: RegExp = /^([a-zA-Z0-9-]+\.)*[a-zA-Z0-9-]+$/; -const regexes_hostname = /^(?=.{1,253}\.?$)[a-zA-Z0-9](?:[a-zA-Z0-9-]{0,61}[a-zA-Z0-9])?(?:\.[a-zA-Z0-9](?:[-0-9a-zA-Z]{0,61}[0-9a-zA-Z])?)*\.?$/; -const domain = /^(?=.{1,253}$)([a-zA-Z0-9](?:[a-zA-Z0-9-]{0,61}[a-zA-Z0-9])?\.)+[a-zA-Z]{2,63}$/; -const httpProtocol = /^https?$/; -// https://blog.stevenlevithan.com/archives/validate-phone-number#r4-3 (regex sans spaces) E.164: leading digit must be 1-9; total digits (excluding '+') between 7-15 -const e164 = /^\+[1-9]\d{6,14}$/; -// Credit card shape: 12–19 digits, optionally separated by single spaces or single hyphens. ISO/IEC 7812 caps the PAN at 19 digits; 12 is the shortest issued length (Maestro). -const creditCard = /^\d(?:[ -]?\d){11,18}$/; -const dateSource = `(?:(?:\\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])))`; -/** Anchors a pattern source. The interpolation lives here rather than at the call site because - * esbuild will not drop a `@__PURE__` call whose own argument interpolates a variable, but it - * will drop `anchor(dateSource)`. Keeping it inline pinned `date` into every bundle. */ -function regexes_anchor(source) { - return new RegExp(`^${source}$`); -} -const regexes_date = /*@__PURE__*/ regexes_anchor(dateSource); -function timeSource(args) { - const hhmm = `(?:[01]\\d|2[0-3]):[0-5]\\d`; - const regex = typeof args.precision === "number" - ? args.precision === -1 - ? `${hhmm}` - : args.precision === 0 - ? `${hhmm}:[0-5]\\d` - : `${hhmm}:[0-5]\\d\\.\\d{${args.precision}}` - : args.seconds - ? `${hhmm}:[0-5]\\d(?:\\.\\d+)?` - : `${hhmm}(?::[0-5]\\d(?:\\.\\d+)?)?`; - return regex; -} -function regexes_time(args) { - return new RegExp(`^${timeSource(args)}$`); -} -// Adapted from https://stackoverflow.com/a/3143231 -function datetime(args) { - const opts = ["Z"]; - // if (args.offset) opts.push(`([+-]\\d{2}:\\d{2})`); - if (args.offset) - opts.push(`([+-](?:[01]\\d|2[0-3]):[0-5]\\d)`); - // RFC 3339 mandates seconds wherever the time carries a `Z` or an offset, so only the unqualified form `local` adds may omit them - const qualified = `${timeSource({ precision: args.precision, seconds: true })}(?:${opts.join("|")})`; - const timeRegex = args.local ? `${qualified}|${timeSource({ precision: args.precision })}` : qualified; - return new RegExp(`^${dateSource}T(?:${timeRegex})$`); -} -const regexes_string = (params) => { - const regex = params ? `[\\s\\S]{${params?.minimum ?? 0},${params?.maximum ?? ""}}` : `[\\s\\S]*`; - return new RegExp(`^${regex}$`); -}; -const bigint = /^-?\d+n?$/; -const integer = /^-?\d+$/; -const number = /^-?\d+(?:\.\d+)?$/; -const regexes_boolean = /^(?:true|false)$/i; -const _null = /^null$/i; - -const _undefined = /^undefined$/i; - -// regex for string with no uppercase letters -const lowercase = /^[^A-Z]*$/; -// regex for string with no lowercase letters -const uppercase = /^[^a-z]*$/; -// regex for hexadecimal strings (any length) -const regexes_hex = /^[0-9a-fA-F]*$/; -// Hash regexes for different algorithms and encodings -// Helper function to create base64 regex with exact length and padding -function fixedBase64(bodyLength, padding) { - return new RegExp(`^[A-Za-z0-9+/]{${bodyLength}}${padding}$`); -} -// Helper function to create base64url regex with exact length (no padding) -function fixedBase64url(length) { - return new RegExp(`^[A-Za-z0-9_-]{${length}}$`); -} -// MD5 (16 bytes): base64 = 24 chars total (22 + "==") -const md5_hex = /^[0-9a-fA-F]{32}$/; -const md5_base64 = /*@__PURE__*/ (/* unused pure expression or super */ null && (fixedBase64(22, "=="))); -const md5_base64url = /*@__PURE__*/ (/* unused pure expression or super */ null && (fixedBase64url(22))); -// SHA1 (20 bytes): base64 = 28 chars total (27 + "=") -const sha1_hex = /^[0-9a-fA-F]{40}$/; -const sha1_base64 = /*@__PURE__*/ (/* unused pure expression or super */ null && (fixedBase64(27, "="))); -const sha1_base64url = /*@__PURE__*/ (/* unused pure expression or super */ null && (fixedBase64url(27))); -// SHA256 (32 bytes): base64 = 44 chars total (43 + "=") -const sha256_hex = /^[0-9a-fA-F]{64}$/; -const sha256_base64 = /*@__PURE__*/ (/* unused pure expression or super */ null && (fixedBase64(43, "="))); -const sha256_base64url = /*@__PURE__*/ (/* unused pure expression or super */ null && (fixedBase64url(43))); -// SHA384 (48 bytes): base64 = 64 chars total (no padding) -const sha384_hex = /^[0-9a-fA-F]{96}$/; -const sha384_base64 = /*@__PURE__*/ (/* unused pure expression or super */ null && (fixedBase64(64, ""))); -const sha384_base64url = /*@__PURE__*/ (/* unused pure expression or super */ null && (fixedBase64url(64))); -// SHA512 (64 bytes): base64 = 88 chars total (86 + "==") -const sha512_hex = /^[0-9a-fA-F]{128}$/; -const sha512_base64 = /*@__PURE__*/ (/* unused pure expression or super */ null && (fixedBase64(86, "=="))); -const sha512_base64url = /*@__PURE__*/ (/* unused pure expression or super */ null && (fixedBase64url(86))); - -// import { $ZodType } from "./schemas.js"; - - - -const $ZodCheck = /*@__PURE__*/ $constructor("$ZodCheck", (inst, def) => { - var _a; - inst._zod ?? (inst._zod = {}); - inst._zod.def = def; - (_a = inst._zod).onattach ?? (_a.onattach = []); -}); -/** Default `when` for size-based checks: run only on non-nullish values with a `size`. */ -const _whenHasSize = (payload) => { - const val = payload.value; - return !util.nullish(val) && val.size !== undefined; -}; -/** Default `when` for length-based checks: run only on non-nullish values with a `length`. */ -const _whenHasLength = (payload) => { - const val = payload.value; - return !nullish(val) && val.length !== undefined; -}; -const numericOriginMap = { - number: "number", - bigint: "bigint", - object: "date", -}; -const $ZodCheckLessThan = /*@__PURE__*/ $constructor("$ZodCheckLessThan", (inst, def) => { - $ZodCheck.init(inst, def); - const origin = numericOriginMap[typeof def.value]; - inst._zod.onattach.push((inst) => { - const bag = inst._zod.bag; - const curr = (def.inclusive ? bag.maximum : bag.exclusiveMaximum) ?? Number.POSITIVE_INFINITY; - if (def.value < curr) { - if (def.inclusive) - bag.maximum = def.value; - else - bag.exclusiveMaximum = def.value; - } - }); - inst._zod.check = (payload) => { - if (def.inclusive ? payload.value <= def.value : payload.value < def.value) { - return; - } - payload.issues.push({ - origin: numericOriginMap[typeof payload.value] ?? origin, - code: "too_big", - maximum: typeof def.value === "object" ? def.value.getTime() : def.value, - input: payload.value, - inclusive: def.inclusive, - inst, - continue: !def.abort, - }); - }; -}); -const $ZodCheckGreaterThan = /*@__PURE__*/ $constructor("$ZodCheckGreaterThan", (inst, def) => { - $ZodCheck.init(inst, def); - const origin = numericOriginMap[typeof def.value]; - inst._zod.onattach.push((inst) => { - const bag = inst._zod.bag; - const curr = (def.inclusive ? bag.minimum : bag.exclusiveMinimum) ?? Number.NEGATIVE_INFINITY; - if (def.value > curr) { - if (def.inclusive) - bag.minimum = def.value; - else - bag.exclusiveMinimum = def.value; - } - }); - inst._zod.check = (payload) => { - if (def.inclusive ? payload.value >= def.value : payload.value > def.value) { - return; - } - payload.issues.push({ - origin: numericOriginMap[typeof payload.value] ?? origin, - code: "too_small", - minimum: typeof def.value === "object" ? def.value.getTime() : def.value, - input: payload.value, - inclusive: def.inclusive, - inst, - continue: !def.abort, - }); - }; -}); -const $ZodCheckMultipleOf = -/*@__PURE__*/ $constructor("$ZodCheckMultipleOf", (inst, def) => { - $ZodCheck.init(inst, def); - inst._zod.onattach.push((inst) => { - var _a; - (_a = inst._zod.bag).multipleOf ?? (_a.multipleOf = def.value); - }); - inst._zod.check = (payload) => { - if (typeof payload.value !== typeof def.value) - throw new Error("Cannot mix number and bigint in multiple_of check."); - const isMultiple = typeof payload.value === "bigint" - ? // `value % 0n` throws, and nothing is a multiple of zero — the number branch already fails this way via NaN - def.value !== BigInt(0) && payload.value % def.value === BigInt(0) - : floatSafeRemainder(payload.value, def.value) === 0; - if (isMultiple) - return; - payload.issues.push({ - origin: typeof payload.value, - code: "not_multiple_of", - divisor: def.value, - input: payload.value, - inst, - continue: !def.abort, - }); - }; -}); -const $ZodCheckNumberFormat = /*@__PURE__*/ $constructor("$ZodCheckNumberFormat", (inst, def) => { - $ZodCheck.init(inst, def); // no format checks - def.format = def.format || "float64"; - const isInt = def.format?.includes("int"); - const origin = isInt ? "int" : "number"; - const [minimum, maximum] = NUMBER_FORMAT_RANGES[def.format]; - inst._zod.onattach.push((inst) => { - const bag = inst._zod.bag; - bag.format = def.format; - bag.minimum = minimum; - bag.maximum = maximum; - if (isInt) - bag.pattern = integer; - }); - inst._zod.check = (payload) => { - const input = payload.value; - if (isInt) { - if (!Number.isInteger(input)) { - // invalid_format issue - // payload.issues.push({ - // expected: def.format, - // format: def.format, - // code: "invalid_format", - // input, - // inst, - // }); - // invalid_type issue - payload.issues.push({ - expected: origin, - format: def.format, - code: "invalid_type", - continue: false, - input, - inst, - }); - return; - // not_multiple_of issue - // payload.issues.push({ - // code: "not_multiple_of", - // origin: "number", - // input, - // inst, - // divisor: 1, - // }); - } - if (!Number.isSafeInteger(input)) { - if (input > 0) { - // too_big - payload.issues.push({ - input, - code: "too_big", - maximum: Number.MAX_SAFE_INTEGER, - note: "Integers must be within the safe integer range.", - inst, - origin, - inclusive: true, - continue: !def.abort, - }); - } - else { - // too_small - payload.issues.push({ - input, - code: "too_small", - minimum: Number.MIN_SAFE_INTEGER, - note: "Integers must be within the safe integer range.", - inst, - origin, - inclusive: true, - continue: !def.abort, - }); - } - return; - } - } - if (input < minimum) { - payload.issues.push({ - origin: "number", - input, - code: "too_small", - minimum, - inclusive: true, - inst, - continue: !def.abort, - }); - } - if (input > maximum) { - payload.issues.push({ - origin: "number", - input, - code: "too_big", - maximum, - inclusive: true, - inst, - continue: !def.abort, - }); - } - }; -}); -const $ZodCheckBigIntFormat = /*@__PURE__*/ (/* unused pure expression or super */ null && (core.$constructor("$ZodCheckBigIntFormat", (inst, def) => { - $ZodCheck.init(inst, def); // no format checks - const [minimum, maximum] = util.BIGINT_FORMAT_RANGES[def.format]; - inst._zod.onattach.push((inst) => { - const bag = inst._zod.bag; - bag.format = def.format; - bag.minimum = minimum; - bag.maximum = maximum; - }); - inst._zod.check = (payload) => { - const input = payload.value; - if (input < minimum) { - payload.issues.push({ - origin: "bigint", - input, - code: "too_small", - minimum: minimum, - inclusive: true, - inst, - continue: !def.abort, - }); - } - if (input > maximum) { - payload.issues.push({ - origin: "bigint", - input, - code: "too_big", - maximum, - inclusive: true, - inst, - continue: !def.abort, - }); - } - }; -}))); -const $ZodCheckMaxSize = /*@__PURE__*/ (/* unused pure expression or super */ null && (core.$constructor("$ZodCheckMaxSize", (inst, def) => { - var _a; - $ZodCheck.init(inst, def); - (_a = inst._zod.def).when ?? (_a.when = _whenHasSize); - inst._zod.onattach.push((inst) => { - const curr = (inst._zod.bag.maximum ?? Number.POSITIVE_INFINITY); - if (def.maximum < curr) - inst._zod.bag.maximum = def.maximum; - }); - inst._zod.check = (payload) => { - const input = payload.value; - const size = input.size; - if (size <= def.maximum) - return; - payload.issues.push({ - origin: util.getSizableOrigin(input), - code: "too_big", - maximum: def.maximum, - inclusive: true, - input, - inst, - continue: !def.abort, - }); - }; -}))); -const $ZodCheckMinSize = /*@__PURE__*/ (/* unused pure expression or super */ null && (core.$constructor("$ZodCheckMinSize", (inst, def) => { - var _a; - $ZodCheck.init(inst, def); - (_a = inst._zod.def).when ?? (_a.when = _whenHasSize); - inst._zod.onattach.push((inst) => { - const curr = (inst._zod.bag.minimum ?? Number.NEGATIVE_INFINITY); - if (def.minimum > curr) - inst._zod.bag.minimum = def.minimum; - }); - inst._zod.check = (payload) => { - const input = payload.value; - const size = input.size; - if (size >= def.minimum) - return; - payload.issues.push({ - origin: util.getSizableOrigin(input), - code: "too_small", - minimum: def.minimum, - inclusive: true, - input, - inst, - continue: !def.abort, - }); - }; -}))); -const $ZodCheckSizeEquals = /*@__PURE__*/ (/* unused pure expression or super */ null && (core.$constructor("$ZodCheckSizeEquals", (inst, def) => { - var _a; - $ZodCheck.init(inst, def); - (_a = inst._zod.def).when ?? (_a.when = _whenHasSize); - inst._zod.onattach.push((inst) => { - const bag = inst._zod.bag; - bag.minimum = def.size; - bag.maximum = def.size; - bag.size = def.size; - }); - inst._zod.check = (payload) => { - const input = payload.value; - const size = input.size; - if (size === def.size) - return; - const tooBig = size > def.size; - payload.issues.push({ - origin: util.getSizableOrigin(input), - ...(tooBig ? { code: "too_big", maximum: def.size } : { code: "too_small", minimum: def.size }), - inclusive: true, - exact: true, - input: payload.value, - inst, - continue: !def.abort, - }); - }; -}))); -const $ZodCheckMaxLength = /*@__PURE__*/ $constructor("$ZodCheckMaxLength", (inst, def) => { - var _a; - $ZodCheck.init(inst, def); - (_a = inst._zod.def).when ?? (_a.when = _whenHasLength); - inst._zod.onattach.push((inst) => { - const curr = (inst._zod.bag.maximum ?? Number.POSITIVE_INFINITY); - if (def.maximum < curr) - inst._zod.bag.maximum = def.maximum; - }); - inst._zod.check = (payload) => { - const input = payload.value; - const units = input.length; - // Strings are measured in Unicode code points, not UTF-16 units. A code point is at most two units, so a string that already fits in units fits in code points; only an overflow has to be counted. - const length = typeof input === "string" && units > def.maximum ? codePointLength(input) : units; - if (length <= def.maximum) - return; - const origin = getLengthableOrigin(input); - payload.issues.push({ - origin, - code: "too_big", - maximum: def.maximum, - inclusive: true, - input, - inst, - continue: !def.abort, - }); - }; -}); -const $ZodCheckMinLength = /*@__PURE__*/ $constructor("$ZodCheckMinLength", (inst, def) => { - var _a; - $ZodCheck.init(inst, def); - (_a = inst._zod.def).when ?? (_a.when = _whenHasLength); - inst._zod.onattach.push((inst) => { - const curr = (inst._zod.bag.minimum ?? Number.NEGATIVE_INFINITY); - if (def.minimum > curr) - inst._zod.bag.minimum = def.minimum; - }); - inst._zod.check = (payload) => { - const input = payload.value; - const units = input.length; - // A code point is one or two UTF-16 units, so fewer units than the floor can never reach it and twice the floor always clears it. Only in between is the exact count in doubt. - const length = typeof input === "string" && units >= def.minimum && units < def.minimum * 2 - ? codePointLength(input) - : units; - if (length >= def.minimum) - return; - const origin = getLengthableOrigin(input); - payload.issues.push({ - origin, - code: "too_small", - minimum: def.minimum, - inclusive: true, - input, - inst, - continue: !def.abort, - }); - }; -}); -const $ZodCheckLengthEquals = /*@__PURE__*/ $constructor("$ZodCheckLengthEquals", (inst, def) => { - var _a; - $ZodCheck.init(inst, def); - (_a = inst._zod.def).when ?? (_a.when = _whenHasLength); - inst._zod.onattach.push((inst) => { - const bag = inst._zod.bag; - bag.minimum = def.length; - bag.maximum = def.length; - bag.length = def.length; - }); - inst._zod.check = (payload) => { - const input = payload.value; - const units = input.length; - // A code point is one or two UTF-16 units, so outside `[length, length * 2]` units the target is missed either way — and missed in the same direction in both measures. - const length = typeof input === "string" && units >= def.length && units <= def.length * 2 - ? codePointLength(input) - : units; - if (length === def.length) - return; - const origin = getLengthableOrigin(input); - const tooBig = length > def.length; - payload.issues.push({ - origin, - ...(tooBig ? { code: "too_big", maximum: def.length } : { code: "too_small", minimum: def.length }), - inclusive: true, - exact: true, - input: payload.value, - inst, - continue: !def.abort, - }); - }; -}); -const $ZodCheckStringFormat = /*@__PURE__*/ $constructor("$ZodCheckStringFormat", (inst, def) => { - var _a, _b; - $ZodCheck.init(inst, def); - inst._zod.onattach.push((inst) => { - const bag = inst._zod.bag; - bag.format = def.format; - if (def.pattern) { - bag.patterns ?? (bag.patterns = new Set()); - bag.patterns.add(def.pattern); - } - }); - if (def.pattern) - (_a = inst._zod).check ?? (_a.check = (payload) => { - def.pattern.lastIndex = 0; - if (def.pattern.test(payload.value)) - return; - payload.issues.push({ - origin: "string", - code: "invalid_format", - format: def.format, - input: payload.value, - ...(def.pattern ? { pattern: def.pattern.toString() } : {}), - inst, - continue: !def.abort, - }); - }); - else - (_b = inst._zod).check ?? (_b.check = () => { }); -}); -const $ZodCheckRegex = /*@__PURE__*/ $constructor("$ZodCheckRegex", (inst, def) => { - $ZodCheckStringFormat.init(inst, def); - inst._zod.check = (payload) => { - def.pattern.lastIndex = 0; - if (def.pattern.test(payload.value)) - return; - payload.issues.push({ - origin: "string", - code: "invalid_format", - format: "regex", - input: payload.value, - pattern: def.pattern.toString(), - inst, - continue: !def.abort, - }); - }; -}); -const $ZodCheckLowerCase = /*@__PURE__*/ $constructor("$ZodCheckLowerCase", (inst, def) => { - def.pattern ?? (def.pattern = lowercase); - $ZodCheckStringFormat.init(inst, def); -}); -const $ZodCheckUpperCase = /*@__PURE__*/ $constructor("$ZodCheckUpperCase", (inst, def) => { - def.pattern ?? (def.pattern = uppercase); - $ZodCheckStringFormat.init(inst, def); -}); -const $ZodCheckIncludes = /*@__PURE__*/ $constructor("$ZodCheckIncludes", (inst, def) => { - $ZodCheck.init(inst, def); - const escapedRegex = escapeRegex(def.includes); - // `String.prototype.includes(sub, position)` matches `sub` at `position` - // OR LATER, so the pattern must allow at least `position` leading chars - // (`{N,}`), not exactly `position` chars (`{N}`). - const pattern = new RegExp(typeof def.position === "number" ? `^.{${def.position},}${escapedRegex}` : escapedRegex); - def.pattern = pattern; - inst._zod.onattach.push((inst) => { - const bag = inst._zod.bag; - bag.patterns ?? (bag.patterns = new Set()); - bag.patterns.add(pattern); - }); - inst._zod.check = (payload) => { - if (payload.value.includes(def.includes, def.position)) - return; - payload.issues.push({ - origin: "string", - code: "invalid_format", - format: "includes", - includes: def.includes, - input: payload.value, - inst, - continue: !def.abort, - }); - }; -}); -const $ZodCheckStartsWith = /*@__PURE__*/ $constructor("$ZodCheckStartsWith", (inst, def) => { - $ZodCheck.init(inst, def); - const pattern = new RegExp(`^${escapeRegex(def.prefix)}.*`); - def.pattern ?? (def.pattern = pattern); - inst._zod.onattach.push((inst) => { - const bag = inst._zod.bag; - bag.patterns ?? (bag.patterns = new Set()); - bag.patterns.add(pattern); - }); - inst._zod.check = (payload) => { - if (payload.value.startsWith(def.prefix)) - return; - payload.issues.push({ - origin: "string", - code: "invalid_format", - format: "starts_with", - prefix: def.prefix, - input: payload.value, - inst, - continue: !def.abort, - }); - }; -}); -const $ZodCheckEndsWith = /*@__PURE__*/ $constructor("$ZodCheckEndsWith", (inst, def) => { - $ZodCheck.init(inst, def); - const pattern = new RegExp(`.*${escapeRegex(def.suffix)}$`); - def.pattern ?? (def.pattern = pattern); - inst._zod.onattach.push((inst) => { - const bag = inst._zod.bag; - bag.patterns ?? (bag.patterns = new Set()); - bag.patterns.add(pattern); - }); - inst._zod.check = (payload) => { - if (payload.value.endsWith(def.suffix)) - return; - payload.issues.push({ - origin: "string", - code: "invalid_format", - format: "ends_with", - suffix: def.suffix, - input: payload.value, - inst, - continue: !def.abort, - }); - }; -}); -/////////////////////////////////// -///// $ZodCheckProperty ///// -/////////////////////////////////// -function handleCheckPropertyResult(result, payload, property) { - if (result.issues.length) { - payload.issues.push(...util.prefixIssues(property, result.issues)); - } -} -const $ZodCheckProperty = /*@__PURE__*/ (/* unused pure expression or super */ null && (core.$constructor("$ZodCheckProperty", (inst, def) => { - $ZodCheck.init(inst, def); - inst._zod.check = (payload) => { - const result = def.schema._zod.run({ - value: payload.value[def.property], - issues: [], - }, {}); - if (result instanceof Promise) { - return result.then((result) => handleCheckPropertyResult(result, payload, def.property)); - } - handleCheckPropertyResult(result, payload, def.property); - return; - }; -}))); -const $ZodCheckMimeType = /*@__PURE__*/ (/* unused pure expression or super */ null && (core.$constructor("$ZodCheckMimeType", (inst, def) => { - $ZodCheck.init(inst, def); - const mimeSet = new Set(def.mime); - inst._zod.onattach.push((inst) => { - inst._zod.bag.mime = def.mime; - }); - inst._zod.check = (payload) => { - if (mimeSet.has(payload.value.type)) - return; - payload.issues.push({ - code: "invalid_value", - values: def.mime, - input: payload.value.type, - inst, - continue: !def.abort, - }); - }; -}))); -const $ZodCheckOverwrite = /*@__PURE__*/ $constructor("$ZodCheckOverwrite", (inst, def) => { - $ZodCheck.init(inst, def); - inst._zod.check = (payload) => { - payload.value = def.tx(payload.value); - }; -}); - -class Doc { - constructor(args = [], closed = {}) { - this.content = []; - this.indent = 0; - this.args = args; - this.closed = closed; - } - indented(fn) { - this.indent += 1; - fn(this); - this.indent -= 1; - } - write(arg) { - if (typeof arg === "function") { - arg(this, { execution: "sync" }); - arg(this, { execution: "async" }); - return; - } - const content = arg; - const lines = content.split("\n").filter((x) => x); - const minIndent = Math.min(...lines.map((x) => x.length - x.trimStart().length)); - const dedented = lines.map((x) => x.slice(minIndent)).map((x) => " ".repeat(this.indent * 2) + x); - for (const line of dedented) { - this.content.push(line); - } - } - compile() { - const F = Function; - const content = this?.content ?? [``]; - const factory = new F(...Object.keys(this.closed), `return function (${this.args.join(", ")}) {\n${content.join("\n")}\n};`); - return factory(...Object.values(this.closed)); - } -} - - - -/* Computing the message eagerly is expensive (pretty-printed JSON of all - * issues), so defer it until first read. The accessor functions and - * descriptors are shared across instances to keep error construction - * cheap; the computed message is cached on the internals object. The - * setter preserves plain assignment semantics for consumers that - * overwrite `message`. */ -function _getMessage() { - const internals = this._zod; - internals.message ?? (internals.message = JSON.stringify(internals.def, jsonStringifyReplacer, 2)); - return internals.message; -} -function _setMessage(value) { - this._zod.message = value; -} -const _messageDesc = { - get: _getMessage, - set: _setMessage, - enumerable: true, - configurable: true, -}; -const errors_zodDesc = { value: undefined, enumerable: false }; -const _issuesDesc = { value: undefined, enumerable: false }; -/* Prototypes that already carry the lazy `toString`. Seeded with the - * intrinsics so that `init` on a foreign object — it accepts any object — - * can never install an accessor onto a prototype we do not own. */ -const _installedToString = /* @__PURE__ */ new WeakSet([Object.prototype, Error.prototype]); -const errors_initializer = (inst, def) => { - inst.name = "$ZodError"; - errors_zodDesc.value = inst._zod; - Object.defineProperty(inst, "_zod", errors_zodDesc); - _issuesDesc.value = def; - Object.defineProperty(inst, "issues", _issuesDesc); - // Clear the shared slots; a retained `value` pins the last error's issues. - errors_zodDesc.value = undefined; - _issuesDesc.value = undefined; - Object.defineProperty(inst, "message", _messageDesc); - /* `toString` lives as a non-enumerable lazy getter on the shared - * prototype; on first access it caches a per-instance closure so - * detached usage still works. */ - const proto = Object.getPrototypeOf(inst); - if (!_installedToString.has(proto)) { - _installedToString.add(proto); - Object.defineProperty(proto, "toString", { - configurable: true, - enumerable: false, - get() { - const value = () => this.message; - Object.defineProperty(this, "toString", { value, configurable: true, writable: true }); - return value; - }, - set(value) { - Object.defineProperty(this, "toString", { value, configurable: true, writable: true }); - }, - }); - } -}; -const $ZodError = $constructor("$ZodError", errors_initializer); -const $ZodRealError = $constructor("$ZodError", errors_initializer, undefined, { - Parent: Error, -}); -/** Get-or-create `obj[key]` as an own data property. A path segment naming an inherited member - * ("toString", "constructor") would otherwise read through to the prototype, and assigning - * "__proto__" would hit the setter instead of creating a key. */ -function errors_node(obj, key, make) { - if (!Object.prototype.hasOwnProperty.call(obj, key)) { - if (key === "__proto__") { - Object.defineProperty(obj, key, { value: make(), writable: true, enumerable: true, configurable: true }); - } - else { - obj[key] = make(); - } - } - return obj[key]; -} -function flattenError(error, mapper = (issue) => issue.message) { - const fieldErrors = {}; - const formErrors = []; - for (const sub of error.issues) { - if (sub.path.length > 0) { - errors_node(fieldErrors, sub.path[0], () => []).push(mapper(sub)); - } - else { - formErrors.push(mapper(sub)); - } - } - return { formErrors, fieldErrors }; -} -function formatError(error, mapper = (issue) => issue.message) { - const fieldErrors = { _errors: [] }; - const processError = (error, path = []) => { - for (const issue of error.issues) { - if (issue.code === "invalid_union" && issue.errors.length) { - issue.errors.map((issues) => processError({ issues }, [...path, ...issue.path])); - } - else if (issue.code === "invalid_key") { - processError({ issues: issue.issues }, [...path, ...issue.path]); - } - else if (issue.code === "invalid_element") { - processError({ issues: issue.issues }, [...path, ...issue.path]); - } - else { - const fullpath = [...path, ...issue.path]; - if (fullpath.length === 0) { - fieldErrors._errors.push(mapper(issue)); - } - else { - let curr = fieldErrors; - let i = 0; - while (i < fullpath.length) { - const el = fullpath[i]; - const terminal = i === fullpath.length - 1; - // `_errors` is reserved by this legacy format, so merge a matching path segment into the current node instead of treating its array as a child. - if (el === "_errors") { - if (terminal) - curr._errors.push(mapper(issue)); - i++; - continue; - } - // A path element may collide with an inherited property name such as - // "__proto__" or "constructor". Truthiness checks read the prototype - // (so no node is created, then ._errors.push throws), and bracket - // assignment of "__proto__" hits the setter instead of creating an - // own key. Guard the read with hasOwnProperty and create the node - // with defineProperty so any path element becomes a real own key. - if (!Object.prototype.hasOwnProperty.call(curr, el)) { - Object.defineProperty(curr, el, { - value: { _errors: [] }, - enumerable: true, - writable: true, - configurable: true, - }); - } - const node = curr[el]; - if (terminal) { - node._errors.push(mapper(issue)); - } - curr = node; - i++; - } - } - } - } - }; - processError(error); - return fieldErrors; -} -function treeifyError(error, mapper = (issue) => issue.message) { - const result = { errors: [] }; - const processError = (error, path = []) => { - var _a; - for (const issue of error.issues) { - if (issue.code === "invalid_union" && issue.errors.length) { - // regular union error - issue.errors.map((issues) => processError({ issues }, [...path, ...issue.path])); - } - else if (issue.code === "invalid_key") { - processError({ issues: issue.issues }, [...path, ...issue.path]); - } - else if (issue.code === "invalid_element") { - processError({ issues: issue.issues }, [...path, ...issue.path]); - } - else { - const fullpath = [...path, ...issue.path]; - if (fullpath.length === 0) { - result.errors.push(mapper(issue)); - continue; - } - let curr = result; - let i = 0; - while (i < fullpath.length) { - const el = fullpath[i]; - const terminal = i === fullpath.length - 1; - if (typeof el === "string") { - curr.properties ?? (curr.properties = {}); - // el may collide with an inherited property name ("__proto__", - // "constructor", ...); ??= reads the prototype so the node is never - // created and curr.errors.push throws. Guard with hasOwnProperty and - // create the node with defineProperty so "__proto__" becomes a real - // own key rather than invoking the prototype setter. - if (!Object.prototype.hasOwnProperty.call(curr.properties, el)) { - Object.defineProperty(curr.properties, el, { - value: { errors: [] }, - enumerable: true, - writable: true, - configurable: true, - }); - } - curr = curr.properties[el]; - } - else { - curr.items ?? (curr.items = []); - (_a = curr.items)[el] ?? (_a[el] = { errors: [] }); - curr = curr.items[el]; - } - if (terminal) { - curr.errors.push(mapper(issue)); - } - i++; - } - } - } - }; - processError(error); - return result; -} -/** Format a ZodError as a human-readable string in the following form. - * - * From - * - * ```ts - * ZodError { - * issues: [ - * { - * expected: 'string', - * code: 'invalid_type', - * path: [ 'username' ], - * message: 'Invalid input: expected string' - * }, - * { - * expected: 'number', - * code: 'invalid_type', - * path: [ 'favoriteNumbers', 1 ], - * message: 'Invalid input: expected number' - * } - * ]; - * } - * ``` - * - * to - * - * ``` - * username - * ✖ Expected number, received string at "username - * favoriteNumbers[0] - * ✖ Invalid input: expected number - * ``` - */ -function toDotPath(_path) { - const segs = []; - const path = _path.map((seg) => (typeof seg === "object" ? seg.key : seg)); - for (const seg of path) { - if (typeof seg === "number") - segs.push(`[${seg}]`); - else if (typeof seg === "symbol") - segs.push(`[${JSON.stringify(String(seg))}]`); - else if (/[^\w$]/.test(seg)) - segs.push(`[${JSON.stringify(seg)}]`); - else { - if (segs.length) - segs.push("."); - segs.push(seg); - } - } - return segs.join(""); -} -function prettifyError(error) { - const lines = []; - // sort by path length - const issues = [...error.issues].sort((a, b) => (a.path ?? []).length - (b.path ?? []).length); - // Process each issue - for (const issue of issues) { - lines.push(`✖ ${issue.message}`); - if (issue.path?.length) - lines.push(` → at ${toDotPath(issue.path)}`); - } - // Convert Map to formatted string - return lines.join("\n"); -} - - - - -// Always both keys, so the `_params` read site in `_parse` sees one object shape rather than two. -function finalizeParams(callee, params) { - return { callee: params?.callee ?? callee, Err: params?.Err }; -} -const parse_parse = (_Err) => { - const fn = (schema, value, _ctx, _params) => { - const ctx = _ctx ? { ..._ctx, async: false } : { async: false }; - const result = schema._zod.run({ value, issues: [] }, ctx); - if (result instanceof Promise) { - throw new $ZodAsyncError(); - } - if (result.issues.length) { - const e = new (_params?.Err ?? _Err)(result.issues.map((iss) => finalizeIssue(iss, ctx, core_config()))); - captureStackTrace(e, _params?.callee ?? fn); - throw e; - } - return result.value; - }; - return fn; -}; -const core_parse_parse = /* @__PURE__*/ parse_parse($ZodRealError); -const parse_parseAsync = (_Err) => { - const fn = async (schema, value, _ctx, params) => { - const ctx = _ctx ? { ..._ctx, async: true } : { async: true }; - let result = schema._zod.run({ value, issues: [] }, ctx); - if (result instanceof Promise) - result = await result; - if (result.issues.length) { - const e = new (params?.Err ?? _Err)(result.issues.map((iss) => finalizeIssue(iss, ctx, core_config()))); - captureStackTrace(e, params?.callee ?? fn); - throw e; - } - return result.value; - }; - return fn; -}; -const core_parse_parseAsync = /* @__PURE__*/ parse_parseAsync($ZodRealError); -const _safeParse = (_Err) => (schema, value, _ctx) => { - const ctx = _ctx ? { ..._ctx, async: false } : { async: false }; - const result = schema._zod.run({ value, issues: [] }, ctx); - if (result instanceof Promise) { - throw new $ZodAsyncError(); - } - return result.issues.length - ? { - success: false, - error: new (_Err ?? $ZodError)(result.issues.map((iss) => finalizeIssue(iss, ctx, core_config()))), - } - : { success: true, data: result.value }; -}; -const safeParse = /* @__PURE__*/ _safeParse($ZodRealError); -const _safeParseAsync = (_Err) => async (schema, value, _ctx) => { - const ctx = _ctx ? { ..._ctx, async: true } : { async: true }; - let result = schema._zod.run({ value, issues: [] }, ctx); - if (result instanceof Promise) - result = await result; - return result.issues.length - ? { - success: false, - error: new _Err(result.issues.map((iss) => finalizeIssue(iss, ctx, core_config()))), - } - : { success: true, data: result.value }; -}; -const safeParseAsync = /* @__PURE__*/ _safeParseAsync($ZodRealError); -// registry mirrors of the compiler's sentinels, so this module never imports the compiler -const COMPILE_INVALID = /* @__PURE__ */ (/* unused pure expression or super */ null && (Symbol.for("zod.compile.invalid"))); -const COMPILE_FALLBACK = /* @__PURE__ */ (/* unused pure expression or super */ null && (Symbol.for("zod.compile.fallback"))); -// Deliberately tiny, because v8 will not inline a body carrying the fallback's object literals and throw. Everything that is not the compiled happy path lives in validateFallback, and that split is worth ~35% on a compiled schema. -const parse_validate = ((schema, value, _ctx) => { - const validator = schema._zod.bag.validator; - if (validator !== undefined && validator(value) !== COMPILE_INVALID) - return true; - return validateFallback(schema, value, _ctx); -}); -function validateFallback(schema, value, _ctx) { - const ctx = _ctx ? { ..._ctx, async: false } : { async: false }; - const fallbackRun = schema._zod.bag.fallbackRun; - let result; - if (fallbackRun) { - // skip nested fast paths on the fallback, so user callbacks keep the at-most-twice bound - ctx[COMPILE_FALLBACK] = true; - result = fallbackRun({ value, issues: [] }, ctx); - } - else { - result = schema._zod.run({ value, issues: [] }, ctx); - } - if (result instanceof Promise) { - throw new core.$ZodAsyncError(); - } - return result.issues.length === 0; -} -// no fast path: the compiler keeps async parses on the runtime, because a promise-returning callback that is not declared async compiles to a throw -const parse_validateAsync = async (schema, value, _ctx) => { - const ctx = _ctx ? { ..._ctx, async: true } : { async: true }; - let result = schema._zod.run({ value, issues: [] }, ctx); - if (result instanceof Promise) - result = await result; - return result.issues.length === 0; -}; -const parse_encode = (_Err) => { - const parse = parse_parse(_Err); - const fn = (schema, value, _ctx, _params) => { - const ctx = _ctx ? { ..._ctx, direction: "backward" } : { direction: "backward" }; - return parse(schema, value, ctx, finalizeParams(fn, _params)); - }; - return fn; -}; -const encode = /* @__PURE__*/ parse_encode($ZodRealError); -const parse_decode = (_Err) => { - const parse = parse_parse(_Err); - const fn = (schema, value, _ctx, _params) => { - return parse(schema, value, _ctx, finalizeParams(fn, _params)); - }; - return fn; -}; -const decode = /* @__PURE__*/ parse_decode($ZodRealError); -const parse_encodeAsync = (_Err) => { - const parseAsync = parse_parseAsync(_Err); - const fn = async (schema, value, _ctx, _params) => { - const ctx = _ctx ? { ..._ctx, direction: "backward" } : { direction: "backward" }; - return (await parseAsync(schema, value, ctx, finalizeParams(fn, _params))); - }; - return fn; -}; -const encodeAsync = /* @__PURE__*/ parse_encodeAsync($ZodRealError); -const parse_decodeAsync = (_Err) => { - const parseAsync = parse_parseAsync(_Err); - const fn = async (schema, value, _ctx, _params) => { - return await parseAsync(schema, value, _ctx, finalizeParams(fn, _params)); - }; - return fn; -}; -const decodeAsync = /* @__PURE__*/ parse_decodeAsync($ZodRealError); -const _safeEncode = (_Err) => (schema, value, _ctx) => { - const ctx = _ctx ? { ..._ctx, direction: "backward" } : { direction: "backward" }; - return _safeParse(_Err)(schema, value, ctx); -}; -const safeEncode = /* @__PURE__*/ _safeEncode($ZodRealError); -const _safeDecode = (_Err) => (schema, value, _ctx) => { - return _safeParse(_Err)(schema, value, _ctx); -}; -const safeDecode = /* @__PURE__*/ _safeDecode($ZodRealError); -const _safeEncodeAsync = (_Err) => async (schema, value, _ctx) => { - const ctx = _ctx ? { ..._ctx, direction: "backward" } : { direction: "backward" }; - return _safeParseAsync(_Err)(schema, value, ctx); -}; -const safeEncodeAsync = /* @__PURE__*/ _safeEncodeAsync($ZodRealError); -const _safeDecodeAsync = (_Err) => async (schema, value, _ctx) => { - return _safeParseAsync(_Err)(schema, value, _ctx); -}; -const safeDecodeAsync = /* @__PURE__*/ _safeDecodeAsync($ZodRealError); - -const versions_version = { - major: 4, - minor: 5, - patch: 4, -}; - - - - - - - - -const $ZodType = /*@__PURE__*/ $constructor("$ZodType", (inst, def) => { - var _a; - inst ?? (inst = {}); - inst._zod.def = def; // set _def property - inst._zod.bag = inst._zod.bag || {}; // initialize _bag object - inst._zod.version = versions_version; - const defChecks = inst._zod.def.checks; - // if inst is itself a checks.$ZodCheck, run it as a check - const checks = inst._zod.traits.has("$ZodCheck") - ? [inst, ...(defChecks ?? [])] - : defChecks?.length - ? [...defChecks] - : []; - for (const ch of checks) { - for (const fn of ch._zod.onattach) { - fn(inst); - } - } - if (checks.length === 0) { - // deferred initializer inst._zod.parse is not yet defined - (_a = inst._zod).deferred ?? (_a.deferred = []); - inst._zod.deferred?.push(() => { - inst._zod.run = inst._zod.parse; - }); - } - else { - const runChecks = (payload, checks, ctx) => { - if (payload.memo) - return payload; - let isAborted = aborted(payload); - let asyncResult; - for (const ch of checks) { - if (ch._zod.def.when) { - if (explicitlyAborted(payload)) - continue; - const shouldRun = ch._zod.def.when(payload); - if (!shouldRun) - continue; - } - else if (isAborted) { - continue; - } - const currLen = payload.issues.length; - const _ = ch._zod.check(payload); - if (_ instanceof Promise && ctx?.async === false) { - throw new $ZodAsyncError(); - } - if (asyncResult || _ instanceof Promise) { - asyncResult = (asyncResult ?? Promise.resolve()).then(async () => { - await _; - const nextLen = payload.issues.length; - if (nextLen === currLen) - return; - attachSchema(payload.issues, currLen, inst); - if (!isAborted) - isAborted = aborted(payload, currLen); - }); - } - else { - const nextLen = payload.issues.length; - if (nextLen === currLen) - continue; - attachSchema(payload.issues, currLen, inst); - if (!isAborted) - isAborted = aborted(payload, currLen); - } - } - if (asyncResult) { - return asyncResult.then(() => { - return payload; - }); - } - return payload; - }; - const handleCanaryResult = (canary, payload, ctx) => { - // abort if the canary is aborted - if (aborted(canary)) { - canary.aborted = true; - return canary; - } - // run checks first, then - const checkResult = runChecks(payload, checks, ctx); - if (checkResult instanceof Promise) { - if (ctx.async === false) - throw new $ZodAsyncError(); - return checkResult.then((checkResult) => inst._zod.parse(checkResult, ctx)); - } - return inst._zod.parse(checkResult, ctx); - }; - inst._zod.run = (payload, ctx) => { - if (ctx.skipChecks) { - return inst._zod.parse(payload, ctx); - } - if (ctx.direction === "backward") { - // run canary initial pass (no checks) - const canary = inst._zod.parse({ value: payload.value, issues: [] }, { ...ctx, skipChecks: true }); - if (canary instanceof Promise) { - return canary.then((canary) => { - return handleCanaryResult(canary, payload, ctx); - }); - } - return handleCanaryResult(canary, payload, ctx); - } - // forward - const result = inst._zod.parse(payload, ctx); - if (result instanceof Promise) { - if (ctx.async === false) - throw new $ZodAsyncError(); - return result.then((result) => runChecks(result, checks, ctx)); - } - return runChecks(result, checks, ctx); - }; - } -}, { - // Wrappers extend this by installing a richer factory over it; reading it eagerly would defeat the laziness. - get "~standard"() { - return hide(this, "~standard", standardProps(this)); - }, - set "~standard"(value) { - util_own(this, "~standard", value); - }, -}); -/** The Standard Schema surface for `inst`. Shared so wrappers can extend it without forcing it. */ -const toStandardResult = (r) => r.success ? { value: r.data } : { issues: r.error?.issues }; -function standardProps(inst) { - return { - validate: (value) => { - try { - return toStandardResult(safeParse(inst, value)); - } - catch (_) { - return safeParseAsync(inst, value).then(toStandardResult); - } - }, - vendor: "zod", - version: 1, - }; -} - -const $ZodString = /*@__PURE__*/ $constructor("$ZodString", (inst, def) => { - $ZodType.init(inst, def); - inst._zod.pattern = [...(inst?._zod.bag?.patterns ?? [])].pop() ?? regexes_string(inst._zod.bag); - inst._zod.parse = (payload, _) => { - if (def.coerce) - try { - payload.value = String(payload.value); - } - catch (_) { } - if (typeof payload.value === "string") - return payload; - payload.issues.push({ - expected: "string", - code: "invalid_type", - input: payload.value, - inst, - }); - return payload; - }; -}); -const $ZodStringFormat = /*@__PURE__*/ $constructor("$ZodStringFormat", (inst, def) => { - // check initialization must come first - $ZodCheckStringFormat.init(inst, def); - $ZodString.init(inst, def); -}); -const $ZodGUID = /*@__PURE__*/ $constructor("$ZodGUID", (inst, def) => { - def.pattern ?? (def.pattern = guid); - $ZodStringFormat.init(inst, def); -}); -const $ZodUUID = /*@__PURE__*/ $constructor("$ZodUUID", (inst, def) => { - if (def.version) { - const versionMap = { - v1: 1, - v2: 2, - v3: 3, - v4: 4, - v5: 5, - v6: 6, - v7: 7, - v8: 8, - }; - const v = versionMap[def.version]; - if (v === undefined) - throw new Error(`Invalid UUID version: "${def.version}"`); - def.pattern ?? (def.pattern = uuid(v)); - } - else - def.pattern ?? (def.pattern = uuid()); - $ZodStringFormat.init(inst, def); -}); -const $ZodEmail = /*@__PURE__*/ $constructor("$ZodEmail", (inst, def) => { - def.pattern ?? (def.pattern = email); - $ZodStringFormat.init(inst, def); -}); -/** The `://` guard rejected the input before the URL constructor saw it. */ -const URL_BAD_FORMAT = 1; -/** The URL constructor rejected the input. */ -const URL_UNPARSEABLE = 2; -/** Parses a URL for `$ZodURL`, applying the one guard the URL constructor cannot express. Returns the parsed URL, or a code naming the stage that rejected it — the runtime needs that distinction to pick an issue note, and compiled code only needs to know it is not a URL. */ -function parseURLObject(trimmed, def) { - // When normalize is off, require :// for http/https URLs. This prevents strings like "http:example.com" or "https:/path" from being silently accepted - if (!def.normalize && def.protocol?.source === httpProtocol.source && !/^https?:\/\//i.test(trimmed)) { - return URL_BAD_FORMAT; - } - try { - // @ts-ignore - return new URL(trimmed); - } - catch { - return URL_UNPARSEABLE; - } -} -const asciiTabOrNewline = /[\t\n\r]/g; -/** The URL parser deletes every ASCII tab, LF and CR from its input before it parses, so `new URL("https://exa\nmple.com")` reports on `example.com`. Applying the same deletion to the returned value closes the half of that divergence which can move the host; the parser's other rewrite, stripping C0 controls at the edges, cannot. */ -function stripTabAndNewline(value) { - return value.replace(asciiTabOrNewline, ""); -} -function urlHostnameOk(url, hostname) { - hostname.lastIndex = 0; - return hostname.test(url.hostname); -} -function urlProtocolOk(url, protocol) { - protocol.lastIndex = 0; - return protocol.test(url.protocol.endsWith(":") ? url.protocol.slice(0, -1) : url.protocol); -} -const $ZodURL = /*@__PURE__*/ $constructor("$ZodURL", (inst, def) => { - $ZodStringFormat.init(inst, def); - inst._zod.check = (payload) => { - try { - // Trim whitespace from input - const trimmed = payload.value.trim(); - const url = parseURLObject(trimmed, def); - if (url === URL_BAD_FORMAT) { - payload.issues.push({ - code: "invalid_format", - format: "url", - note: "Invalid URL format", - input: payload.value, - inst, - continue: !def.abort, - }); - return; - } - if (url === URL_UNPARSEABLE) { - payload.issues.push({ - code: "invalid_format", - format: "url", - input: payload.value, - inst, - continue: !def.abort, - }); - return; - } - if (def.hostname && !urlHostnameOk(url, def.hostname)) { - payload.issues.push({ - code: "invalid_format", - format: "url", - note: "Invalid hostname", - pattern: def.hostname.source, - input: payload.value, - inst, - continue: !def.abort, - }); - } - if (def.protocol && !urlProtocolOk(url, def.protocol)) { - payload.issues.push({ - code: "invalid_format", - format: "url", - note: "Invalid protocol", - pattern: def.protocol.source, - input: payload.value, - inst, - continue: !def.abort, - }); - } - // Set the output value based on normalize flag - payload.value = def.normalize ? url.href : stripTabAndNewline(trimmed); - return; - } - catch (_) { - payload.issues.push({ - code: "invalid_format", - format: "url", - input: payload.value, - inst, - continue: !def.abort, - }); - } - }; -}); -const $ZodEmoji = /*@__PURE__*/ $constructor("$ZodEmoji", (inst, def) => { - def.pattern ?? (def.pattern = emoji()); - $ZodStringFormat.init(inst, def); -}); -const $ZodNanoID = /*@__PURE__*/ $constructor("$ZodNanoID", (inst, def) => { - if (def.length !== undefined && (!Number.isInteger(def.length) || def.length < 1)) - throw new Error(`Invalid nanoid length: ${def.length}`); - def.pattern ?? (def.pattern = def.length === undefined ? nanoid : nanoidOfLength(def.length)); - $ZodStringFormat.init(inst, def); -}); -/** - * @deprecated CUID v1 is deprecated by its authors due to information leakage - * (timestamps embedded in the id). Use {@link $ZodCUID2} instead. - * See https://github.com/paralleldrive/cuid. - */ -const $ZodCUID = /*@__PURE__*/ $constructor("$ZodCUID", (inst, def) => { - def.pattern ?? (def.pattern = cuid); - $ZodStringFormat.init(inst, def); -}); -const $ZodCUID2 = /*@__PURE__*/ $constructor("$ZodCUID2", (inst, def) => { - def.pattern ?? (def.pattern = cuid2); - $ZodStringFormat.init(inst, def); -}); -const $ZodULID = /*@__PURE__*/ $constructor("$ZodULID", (inst, def) => { - def.pattern ?? (def.pattern = ulid); - $ZodStringFormat.init(inst, def); -}); -const $ZodXID = /*@__PURE__*/ $constructor("$ZodXID", (inst, def) => { - def.pattern ?? (def.pattern = xid); - $ZodStringFormat.init(inst, def); -}); -const $ZodKSUID = /*@__PURE__*/ $constructor("$ZodKSUID", (inst, def) => { - def.pattern ?? (def.pattern = ksuid); - $ZodStringFormat.init(inst, def); -}); -const $ZodISODateTime = /*@__PURE__*/ $constructor("$ZodISODateTime", (inst, def) => { - def.pattern ?? (def.pattern = datetime(def)); - $ZodStringFormat.init(inst, def); - // these two drop the offset or seconds `date-time` requires — on the bag not the def, since `z.string().check(...)` lands the format on a different schema - if (def.local || def.precision === -1) { - inst._zod.bag.laxFormat = true; - inst._zod.onattach.push((s) => { - s._zod.bag.laxFormat = true; - }); - } -}); -const $ZodISODate = /*@__PURE__*/ $constructor("$ZodISODate", (inst, def) => { - def.pattern ?? (def.pattern = regexes_date); - $ZodStringFormat.init(inst, def); -}); -const $ZodISOTime = /*@__PURE__*/ $constructor("$ZodISOTime", (inst, def) => { - def.pattern ?? (def.pattern = regexes_time(def)); - $ZodStringFormat.init(inst, def); -}); -const $ZodISODuration = /*@__PURE__*/ $constructor("$ZodISODuration", (inst, def) => { - def.pattern ?? (def.pattern = duration); - $ZodStringFormat.init(inst, def); -}); -const $ZodIPv4 = /*@__PURE__*/ $constructor("$ZodIPv4", (inst, def) => { - def.pattern ?? (def.pattern = ipv4); - $ZodStringFormat.init(inst, def); - inst._zod.bag.format = `ipv4`; -}); -/** An IPv6 address is written with hex digits, colons and dots, and nothing else. The guard is what makes the check below an IPv6 check: `new URL("http://[...]")` parses an authority, not an address, so `@` and `\` re-delimit it and `"::@1\\"` validates against the host `0.0.0.1`. The URL parser also deletes ASCII tab, LF and CR rather than failing, which is how `"::1\n"` validated as `::1`. */ -const ipv6Alphabet = /^[0-9a-fA-F:.]+$/; -function isValidIPv6(value) { - if (!ipv6Alphabet.test(value)) - return false; - try { - // @ts-ignore - new URL(`http://[${value}]`); - return true; - } - catch { - return false; - } -} -const $ZodIPv6 = /*@__PURE__*/ $constructor("$ZodIPv6", (inst, def) => { - def.pattern ?? (def.pattern = regexes_ipv6); - $ZodStringFormat.init(inst, def); - inst._zod.bag.format = `ipv6`; - inst._zod.check = (payload) => { - if (!isValidIPv6(payload.value)) { - payload.issues.push({ - code: "invalid_format", - format: "ipv6", - input: payload.value, - inst, - continue: !def.abort, - }); - } - }; -}); -const $ZodMAC = /*@__PURE__*/ (/* unused pure expression or super */ null && (core.$constructor("$ZodMAC", (inst, def) => { - def.pattern ?? (def.pattern = regexes.mac(def.delimiter)); - $ZodStringFormat.init(inst, def); - inst._zod.bag.format = `mac`; -}))); -const $ZodCIDRv4 = /*@__PURE__*/ $constructor("$ZodCIDRv4", (inst, def) => { - def.pattern ?? (def.pattern = cidrv4); - $ZodStringFormat.init(inst, def); -}); -function isValidCIDRv6(value) { - const parts = value.split("/"); - if (parts.length !== 2) - return false; - const [address, prefix] = parts; - if (!prefix) - return false; - const prefixNum = Number(prefix); - if (`${prefixNum}` !== prefix) - return false; - if (prefixNum < 0 || prefixNum > 128) - return false; - return isValidIPv6(address); -} -const $ZodCIDRv6 = /*@__PURE__*/ $constructor("$ZodCIDRv6", (inst, def) => { - def.pattern ?? (def.pattern = cidrv6); // not used for validation - $ZodStringFormat.init(inst, def); - inst._zod.check = (payload) => { - if (!isValidCIDRv6(payload.value)) { - payload.issues.push({ - code: "invalid_format", - format: "cidrv6", - input: payload.value, - inst, - continue: !def.abort, - }); - } - }; -}); -////////////////////////////// ZodBase64 ////////////////////////////// -function isValidBase64(data) { - if (data === "") - return true; - // atob ignores whitespace, so reject it up front. - if (/\s/.test(data)) - return false; - if (data.length % 4 !== 0) - return false; - try { - // @ts-ignore - atob(data); - return true; - } - catch { - return false; - } -} -const $ZodBase64 = /*@__PURE__*/ $constructor("$ZodBase64", (inst, def) => { - def.pattern ?? (def.pattern = regexes_base64); - $ZodStringFormat.init(inst, def); - inst._zod.bag.contentEncoding = "base64"; - inst._zod.check = (payload) => { - if (isValidBase64(payload.value)) - return; - payload.issues.push({ - code: "invalid_format", - format: "base64", - input: payload.value, - inst, - continue: !def.abort, - }); - }; -}); -////////////////////////////// ZodBase64 ////////////////////////////// -function isValidBase64URL(data) { - if (!regexes_base64url.test(data)) - return false; - const base64 = data.replace(/[-_]/g, (c) => (c === "-" ? "+" : "/")); - const padded = base64.padEnd(Math.ceil(base64.length / 4) * 4, "="); - return isValidBase64(padded); -} -const $ZodBase64URL = /*@__PURE__*/ $constructor("$ZodBase64URL", (inst, def) => { - def.pattern ?? (def.pattern = regexes_base64url); - $ZodStringFormat.init(inst, def); - inst._zod.bag.contentEncoding = "base64url"; - inst._zod.check = (payload) => { - if (isValidBase64URL(payload.value)) - return; - payload.issues.push({ - code: "invalid_format", - format: "base64url", - input: payload.value, - inst, - continue: !def.abort, - }); - }; -}); -const $ZodE164 = /*@__PURE__*/ $constructor("$ZodE164", (inst, def) => { - def.pattern ?? (def.pattern = e164); - $ZodStringFormat.init(inst, def); -}); -////////////////////////////// ZodCreditCard ////////////////////////////// -const CC_SANITIZE = /[- ]/g; -/** Luhn checksum on a digit-only string. Adapted from valibot (MIT). */ -function isLuhnAlgo(digits) { - let length = digits.length; - let bit = 1; - let sum = 0; - while (length) { - const value = +digits[--length]; - bit ^= 1; - sum += bit ? [0, 2, 4, 6, 8, 1, 3, 5, 7, 9][value] : value; - } - return sum % 10 === 0; -} -function isValidCreditCard(input) { - if (!regexes.creditCard.test(input)) - return false; - return isLuhnAlgo(input.replace(CC_SANITIZE, "")); -} -const $ZodCreditCard = /*@__PURE__*/ (/* unused pure expression or super */ null && (core.$constructor("$ZodCreditCard", (inst, def) => { - // Shape only — the Luhn check below is not expressible as a pattern, so consumers of `pattern` (JSON Schema, template literals) get the length and separator rules alone. - def.pattern ?? (def.pattern = regexes.creditCard); - $ZodStringFormat.init(inst, def); - inst._zod.check = (payload) => { - if (isValidCreditCard(payload.value)) - return; - payload.issues.push({ - code: "invalid_format", - format: "credit_card", - input: payload.value, - inst, - continue: !def.abort, - }); - }; -}))); -////////////////////////////// ZodJWT ////////////////////////////// -function isValidJWT(token, algorithm = null) { - try { - const tokensParts = token.split("."); - if (tokensParts.length !== 3) - return false; - const [header] = tokensParts; - if (!header) - return false; - // @ts-ignore - const parsedHeader = JSON.parse(atob(header)); - if ("typ" in parsedHeader && parsedHeader?.typ !== "JWT") - return false; - if (!parsedHeader.alg) - return false; - if (algorithm && (!("alg" in parsedHeader) || parsedHeader.alg !== algorithm)) - return false; - return true; - } - catch { - return false; - } -} -const $ZodJWT = /*@__PURE__*/ $constructor("$ZodJWT", (inst, def) => { - $ZodStringFormat.init(inst, def); - inst._zod.check = (payload) => { - if (isValidJWT(payload.value, def.alg)) - return; - payload.issues.push({ - code: "invalid_format", - format: "jwt", - input: payload.value, - inst, - continue: !def.abort, - }); - }; -}); -const $ZodCustomStringFormat = /*@__PURE__*/ (/* unused pure expression or super */ null && (core.$constructor("$ZodCustomStringFormat", (inst, def) => { - $ZodStringFormat.init(inst, def); - inst._zod.check = (payload) => { - if (def.fn(payload.value)) - return; - payload.issues.push({ - code: "invalid_format", - format: def.format, - input: payload.value, - inst, - continue: !def.abort, - }); - }; -}))); -const $ZodNumber = /*@__PURE__*/ $constructor("$ZodNumber", (inst, def) => { - $ZodType.init(inst, def); - inst._zod.pattern = inst._zod.bag.pattern ?? number; - inst._zod.parse = (payload, _ctx) => { - if (def.coerce) - try { - payload.value = Number(payload.value); - } - catch (_) { } - const input = payload.value; - if (typeof input === "number" && !Number.isNaN(input) && Number.isFinite(input)) { - return payload; - } - const received = typeof input === "number" - ? Number.isNaN(input) - ? "NaN" - : !Number.isFinite(input) - ? String(input) - : undefined - : undefined; - payload.issues.push({ - expected: "number", - code: "invalid_type", - input, - inst, - ...(received ? { received } : {}), - }); - return payload; - }; -}); -const $ZodNumberFormat = /*@__PURE__*/ $constructor("$ZodNumberFormat", (inst, def) => { - $ZodCheckNumberFormat.init(inst, def); - $ZodNumber.init(inst, def); // no format checks -}); -const $ZodBoolean = /*@__PURE__*/ $constructor("$ZodBoolean", (inst, def) => { - $ZodType.init(inst, def); - inst._zod.pattern = regexes_boolean; - inst._zod.parse = (payload, _ctx) => { - if (def.coerce) - try { - payload.value = Boolean(payload.value); - } - catch (_) { } - const input = payload.value; - if (typeof input === "boolean") - return payload; - payload.issues.push({ - expected: "boolean", - code: "invalid_type", - input, - inst, - }); - return payload; - }; -}); -const $ZodBigInt = /*@__PURE__*/ (/* unused pure expression or super */ null && (core.$constructor("$ZodBigInt", (inst, def) => { - $ZodType.init(inst, def); - inst._zod.pattern = regexes.bigint; - inst._zod.parse = (payload, _ctx) => { - if (def.coerce) - try { - payload.value = BigInt(payload.value); - } - catch (_) { } - if (typeof payload.value === "bigint") - return payload; - payload.issues.push({ - expected: "bigint", - code: "invalid_type", - input: payload.value, - inst, - }); - return payload; - }; -}))); -const $ZodBigIntFormat = /*@__PURE__*/ (/* unused pure expression or super */ null && (core.$constructor("$ZodBigIntFormat", (inst, def) => { - checks.$ZodCheckBigIntFormat.init(inst, def); - $ZodBigInt.init(inst, def); // no format checks -}))); -const $ZodSymbol = /*@__PURE__*/ (/* unused pure expression or super */ null && (core.$constructor("$ZodSymbol", (inst, def) => { - $ZodType.init(inst, def); - inst._zod.parse = (payload, _ctx) => { - const input = payload.value; - if (typeof input === "symbol") - return payload; - payload.issues.push({ - expected: "symbol", - code: "invalid_type", - input, - inst, - }); - return payload; - }; -}))); -const $ZodUndefined = /*@__PURE__*/ (/* unused pure expression or super */ null && (core.$constructor("$ZodUndefined", (inst, def) => { - $ZodType.init(inst, def); - inst._zod.pattern = regexes.undefined; - inst._zod.values = new Set([undefined]); - inst._zod.parse = (payload, _ctx) => { - const input = payload.value; - if (typeof input === "undefined") - return payload; - payload.issues.push({ - expected: "undefined", - code: "invalid_type", - input, - inst, - }); - return payload; - }; -}))); -const $ZodNull = /*@__PURE__*/ $constructor("$ZodNull", (inst, def) => { - $ZodType.init(inst, def); - inst._zod.pattern = _null; - inst._zod.values = new Set([null]); - inst._zod.parse = (payload, _ctx) => { - const input = payload.value; - if (input === null) - return payload; - payload.issues.push({ - expected: "null", - code: "invalid_type", - input, - inst, - }); - return payload; - }; -}); -const $ZodAny = /*@__PURE__*/ $constructor("$ZodAny", (inst, def) => { - $ZodType.init(inst, def); - inst._zod.parse = (payload) => payload; -}); -const $ZodUnknown = /*@__PURE__*/ $constructor("$ZodUnknown", (inst, def) => { - $ZodType.init(inst, def); - inst._zod.parse = (payload) => payload; -}); -const $ZodNever = /*@__PURE__*/ $constructor("$ZodNever", (inst, def) => { - $ZodType.init(inst, def); - inst._zod.parse = (payload, _ctx) => { - payload.issues.push({ - expected: "never", - code: "invalid_type", - input: payload.value, - inst, - }); - return payload; - }; -}); -const $ZodVoid = /*@__PURE__*/ (/* unused pure expression or super */ null && (core.$constructor("$ZodVoid", (inst, def) => { - $ZodType.init(inst, def); - inst._zod.parse = (payload, _ctx) => { - const input = payload.value; - if (typeof input === "undefined") - return payload; - payload.issues.push({ - expected: "void", - code: "invalid_type", - input, - inst, - }); - return payload; - }; -}))); -const $ZodDate = /*@__PURE__*/ (/* unused pure expression or super */ null && (core.$constructor("$ZodDate", (inst, def) => { - $ZodType.init(inst, def); - inst._zod.parse = (payload, _ctx) => { - if (def.coerce) { - try { - payload.value = new Date(payload.value); - } - catch (_err) { } - } - const input = payload.value; - const isDate = input instanceof Date; - const isValidDate = isDate && !Number.isNaN(input.getTime()); - if (isValidDate) - return payload; - payload.issues.push({ - expected: "date", - code: "invalid_type", - input, - ...(isDate ? { received: "Invalid Date" } : {}), - inst, - }); - return payload; - }; -}))); -function handleArrayResult(result, final, index) { - if (result.issues.length) { - final.issues.push(...prefixIssues(index, result.issues)); - } - final.value[index] = result.value; -} -const $ZodArray = /*@__PURE__*/ $constructor("$ZodArray", (inst, def) => { - $ZodType.init(inst, def); - const memo = globalConfig.memoizer; - memo?.attach(inst); - inst._zod.parse = (payload, ctx) => { - const input = payload.value; - if (!Array.isArray(input)) { - payload.issues.push({ - expected: "array", - code: "invalid_type", - input, - inst, - }); - return payload; - } - payload.value = memo ? memo.alloc(inst, payload, Array(input.length), ctx) : Array(input.length); - const proms = []; - for (let i = 0; i < input.length; i++) { - const item = input[i]; - const result = def.element._zod.run({ - value: item, - issues: [], - }, ctx); - if (result instanceof Promise) { - proms.push(result.then((result) => handleArrayResult(result, payload, i))); - } - else { - handleArrayResult(result, payload, i); - } - } - if (proms.length) { - return Promise.all(proms).then(() => payload); - } - return payload; //handleArrayResultsAsync(parseResults, final); - }; -}); -function handlePropertyResult(result, final, key, input, optin, optout) { - const isPresent = key in input; - const isOptionalOut = optout === "optional"; - // The middle rung means "absence permitted, nothing supplied in its place", so an absent key contributes nothing — whatever the schema made of `undefined` is invented, not substituted. Only `optional` reaches this with a value: `defaulted` substitutes, and a schema that isn't optional-out has to keep the key. - if (!isPresent && isOptionalOut && optin === "optional") { - return; - } - if (result.issues.length) { - // For optional-in/out schemas, ignore errors on absent keys. - if (optin !== undefined && isOptionalOut && !isPresent) { - return; - } - final.issues.push(...prefixIssues(key, result.issues)); - } - if (!isPresent && optin === undefined) { - if (!result.issues.length) { - final.issues.push({ - code: "invalid_type", - expected: "nonoptional", - input: undefined, - path: [key], - }); - } - return; - } - if (result.value === undefined) { - if (isPresent) { - final.value[key] = undefined; - } - } - else { - final.value[key] = result.value; - } -} -// one shared instance; a fresh [] per schema cost 56 bytes retained -const NO_SYMBOL_KEYS = []; -function normalizeDef(def) { - const keys = Object.keys(def.shape); - const ownSymbols = Object.getOwnPropertySymbols(def.shape); - const symbolKeys = ownSymbols.length ? ownSymbols : NO_SYMBOL_KEYS; - // aliases `keys` when there are no symbols, so a string-only shape keeps one array - const allKeys = symbolKeys.length ? [...keys, ...symbolKeys] : keys; - for (const k of allKeys) { - if (!def.shape?.[k]?._zod?.traits?.has("$ZodType")) { - throw new Error(`Invalid element at key "${String(k)}": expected a Zod schema`); - } - } - const okeys = optionalKeys(def.shape); - return { - ...def, - allKeys, - symbolKeys, - // string-only: handleCatchall matches it against `for...in`, which never yields a symbol - keySet: new Set(keys), - numKeys: keys.length, - optionalKeys: new Set(okeys), - }; -} -function handleCatchall(proms, input, payload, ctx, def, inst) { - const unrecognized = []; - const keySet = def.keySet; - const _catchall = def.catchall._zod; - const t = _catchall.def.type; - const optin = _catchall.optin; - const optout = _catchall.optout; - for (const key in input) { - // Must precede the __proto__ branch: a declared key is not unrecognized, even though the shape loop deliberately strips __proto__ from the parsed output. - if (keySet.has(key)) - continue; - // Don't copy an undeclared __proto__ into the result; assignment to a plain {} would replace the result prototype. But in strict mode it is still an unknown key, so report it before skipping. - if (key === "__proto__") { - if (t === "never") - unrecognized.push(key); - continue; - } - if (t === "never") { - unrecognized.push(key); - continue; - } - const r = _catchall.run({ value: input[key], issues: [] }, ctx); - if (r instanceof Promise) { - proms.push(r.then((r) => handlePropertyResult(r, payload, key, input, optin, optout))); - } - else { - handlePropertyResult(r, payload, key, input, optin, optout); - } - } - if (unrecognized.length) { - payload.issues.push({ - code: "unrecognized_keys", - keys: unrecognized, - input, - inst, - // Describes the shape of the input, not the validity of the parsed value, so it never aborts. The parse still fails; the schema's own checks just get to run first, and an enclosing intersection can reconcile the key against a sibling operand. - continue: true, - }); - } - if (!proms.length) - return payload; - return Promise.all(proms).then(() => { - return payload; - }); -} -// Whichever object a def's `shape` currently answers from: the one the caller passed until the first read, the frozen copy after it. Keyed by def, so a def rebuilt by a builder is simply absent rather than inheriting the source's. Read its keys with `Object.keys`, which does not invoke them — that is what lets a discriminated union check its discriminator without resolving an option whose getters reference the union being constructed. -const propShapes = new WeakMap(); -const $ZodObject = /*@__PURE__*/ $constructor("$ZodObject", (inst, def) => { - // requires cast because technically $ZodObject doesn't extend - $ZodType.init(inst, def); - // const sh = def.shape; - const desc = Object.getOwnPropertyDescriptor(def, "shape"); - if (!desc?.get) { - const sh = def.shape; - propShapes.set(def, sh); - Object.defineProperty(def, "shape", { - get: () => { - const newSh = { ...sh }; - Object.defineProperty(def, "shape", { - value: newSh, - }); - propShapes.set(def, newSh); - return newSh; - }, - }); - } - const _normalized = util_cached(() => normalizeDef(def)); - defineLazyInternal(inst, "propValues", (zod) => { - const shape = zod.def.shape; - const propValues = {}; - for (const key in shape) { - const field = shape[key]._zod; - if (field.values) { - if (!Object.prototype.hasOwnProperty.call(propValues, key)) { - assignProp(propValues, key, new Set()); - } - for (const v of field.values) - propValues[key].add(v); - // An omittable slot reads back as undefined at a discriminator lookup, so it has to claim undefined: two options that can both omit the key are not discriminable on it. - if (field.optin !== undefined) - propValues[key].add(undefined); - } - } - return propValues; - }); - const isObject = util_isObject; - const catchall = def.catchall; - let value; - const memo = globalConfig.memoizer; - memo?.attach(inst); - inst._zod.parse = (payload, ctx) => { - value ?? (value = _normalized.value); - const input = payload.value; - if (!isObject(input)) { - payload.issues.push({ - expected: "object", - code: "invalid_type", - input, - inst, - }); - return payload; - } - payload.value = memo ? memo.alloc(inst, payload, {}, ctx) : {}; - const proms = []; - const shape = value.shape; - for (const key of value.allKeys) { - if (key === "__proto__") - continue; - const el = shape[key]; - const optin = el._zod.optin; - const optout = el._zod.optout; - const r = el._zod.run({ value: input[key], issues: [] }, ctx); - if (r instanceof Promise) { - proms.push(r.then((r) => handlePropertyResult(r, payload, key, input, optin, optout))); - } - else { - handlePropertyResult(r, payload, key, input, optin, optout); - } - } - if (!catchall) { - return proms.length ? Promise.all(proms).then(() => payload) : payload; - } - return handleCatchall(proms, input, payload, ctx, _normalized.value, inst); - }; -}); -const $ZodObjectJIT = /*@__PURE__*/ $constructor("$ZodObjectJIT", (inst, def) => { - // requires cast because technically $ZodObject doesn't extend - $ZodObject.init(inst, def); - const superParse = inst._zod.parse; - const _normalized = util_cached(() => normalizeDef(def)); - const memo = globalConfig.memoizer; - const generateFastpass = (shape) => { - const normalized = _normalized.value; - const syms = normalized.symbolKeys; - // a symbol has no source literal, so it is read as `syms[i]` off the closed-over scope - const doc = new Doc(["payload", "ctx"], { shape, inst, memo, syms }); - const parseStr = (k) => `shape[${k}]._zod.run({ value: input[${k}], issues: [] }, ctx)`; - // Prefixes in place, like util.prefixIssues does for every interpreted path. - const prefixStr = (id, k) => ` - for (let i = 0; i < ${id}.issues.length; i++) { - const iss = ${id}.issues[i]; - iss.path = iss.path ? [${k}, ...iss.path] : [${k}]; - payload.issues.push(iss); - }`; - doc.write(`const input = payload.value;`); - const ids = Object.create(null); - let counter = 0; - for (const key of normalized.allKeys) { - ids[key] = `key_${counter++}`; - } - // A: preserve key order { - doc.write(memo ? `const newResult = memo.alloc(inst, payload, {}, ctx);` : `const newResult = {};`); - for (const key of normalized.allKeys) { - if (key === "__proto__") - continue; - const id = ids[key]; - const k = typeof key === "symbol" ? `syms[${syms.indexOf(key)}]` : util_esc(key); - const isPresent = `${k} in input`; - const schema = shape[key]; - const optin = schema?._zod?.optin; - const isOptionalIn = optin !== undefined; - const isOptionalOut = schema?._zod?.optout === "optional"; - doc.write(`const ${id} = ${parseStr(k)};`); - if (isOptionalIn && isOptionalOut) { - // For optional-in/out schemas, ignore errors on absent keys — and, like the interpreted path, drop the value produced alongside them. The middle rung goes further: it permits absence without supplying anything in its place, so an absent key contributes nothing at all. - const assign = optin === "optional" ? `${id}_present` : `${id}.value !== undefined || ${id}_present`; - doc.write(` - const ${id}_present = ${isPresent}; - if (!${id}.issues.length || ${id}_present) { - if (${id}.issues.length) {${prefixStr(id, k)} - } - - if (${assign}) { - newResult[${k}] = ${id}.value; - } - } - - `); - } - else if (!isOptionalIn) { - doc.write(` - const ${id}_present = ${isPresent}; - if (${id}.issues.length) {${prefixStr(id, k)} - } - if (!${id}_present && !${id}.issues.length) { - payload.issues.push({ - code: "invalid_type", - expected: "nonoptional", - input: undefined, - path: [${k}] - }); - } - - if (${id}_present) { - newResult[${k}] = ${id}.value; - } - - `); - } - else { - doc.write(` - if (${id}.issues.length) {${prefixStr(id, k)} - } - - if (${id}.value === undefined) { - if (${isPresent}) { - newResult[${k}] = undefined; - } - } else { - newResult[${k}] = ${id}.value; - } - - `); - } - } - doc.write(`payload.value = newResult;`); - doc.write(`return payload;`); - // closing `shape` in is what pays: turbofan specializes the parser against that one shape object, so every `shape[k]._zod.run` folds to a known callee. as a parameter it stays a generic load and measures 13% slower even with the forwarding frame gone - return doc.compile(); - }; - let fastpass; - const isObject = util_isObject; - const jit = !globalConfig.jitless; - const allowsEval = util_allowsEval; - const fastEnabled = jit && allowsEval.value; // && !def.catchall; - const catchall = def.catchall; - let value; - inst._zod.parse = (payload, ctx) => { - value ?? (value = _normalized.value); - const input = payload.value; - if (!isObject(input)) { - payload.issues.push({ - expected: "object", - code: "invalid_type", - input, - inst, - }); - return payload; - } - if (jit && fastEnabled && ctx?.async === false && ctx.jitless !== true) { - // always synchronous - if (!fastpass) - fastpass = generateFastpass(def.shape); - payload = fastpass(payload, ctx); - if (!catchall) - return payload; - return handleCatchall([], input, payload, ctx, value, inst); - } - return superParse(payload, ctx); - }; -}); -function handleUnionResults(results, final, inst, ctx) { - for (const result of results) { - if (result.issues.length === 0) { - final.value = result.value; - return final; - } - } - const nonaborted = results.filter((r) => !aborted(r)); - if (nonaborted.length === 1) { - final.value = nonaborted[0].value; - return nonaborted[0]; - } - final.issues.push({ - code: "invalid_union", - input: final.value, - inst, - errors: results.map((result) => result.issues.map((iss) => finalizeIssue(iss, ctx, core_config()))), - }); - return final; -} -const $ZodUnion = /*@__PURE__*/ $constructor("$ZodUnion", (inst, def) => { - $ZodType.init(inst, def); - defineLazyInternal(inst, "optin", (zod) => zod.def.options.some((o) => o._zod.optin === "defaulted") - ? "defaulted" - : zod.def.options.some((o) => o._zod.optin !== undefined) - ? "optional" - : undefined); - defineLazyInternal(inst, "optout", (zod) => zod.def.options.some((o) => o._zod.optout === "optional") ? "optional" : undefined); - defineLazyInternal(inst, "values", (zod) => { - if (zod.def.options.every((o) => o._zod.values)) { - return new Set(zod.def.options.flatMap((option) => Array.from(option._zod.values))); - } - return undefined; - }); - defineLazyInternal(inst, "pattern", (zod) => { - if (zod.def.options.every((o) => o._zod.pattern)) { - const patterns = zod.def.options.map((o) => o._zod.pattern); - return new RegExp(`^(${patterns.map((p) => cleanRegex(p.source)).join("|")})$`); - } - return undefined; - }); - const first = def.options.length === 1 ? def.options[0]._zod.run : null; - inst._zod.parse = (payload, ctx) => { - if (first) { - return first(payload, ctx); - } - let async = false; - const results = []; - for (const option of def.options) { - const result = option._zod.run({ - value: payload.value, - issues: [], - }, ctx); - if (result instanceof Promise) { - results.push(result); - async = true; - } - else { - if (result.issues.length === 0) - return result; - results.push(result); - } - } - if (!async) - return handleUnionResults(results, payload, inst, ctx); - return Promise.all(results).then((results) => { - return handleUnionResults(results, payload, inst, ctx); - }); - }; -}); -function handleExclusiveUnionResults(results, final, inst, ctx) { - const matches = []; - for (let i = 0; i < results.length; i++) { - if (results[i].issues.length === 0) - matches.push(i); - } - if (matches.length === 1) { - final.value = results[matches[0]].value; - return final; - } - if (matches.length === 0) { - // No matches - same as regular union - final.issues.push({ - code: "invalid_union", - input: final.value, - inst, - errors: results.map((result) => result.issues.map((iss) => util.finalizeIssue(iss, ctx, core.config()))), - }); - } - else { - // Multiple matches - exclusive union failure - final.issues.push({ - code: "invalid_union", - input: final.value, - inst, - errors: [], - inclusive: false, - matches, - }); - } - return final; -} -const $ZodXor = /*@__PURE__*/ (/* unused pure expression or super */ null && (core.$constructor("$ZodXor", (inst, def) => { - $ZodUnion.init(inst, def); - def.inclusive = false; - const first = def.options.length === 1 ? def.options[0]._zod.run : null; - inst._zod.parse = (payload, ctx) => { - if (first) { - return first(payload, ctx); - } - let async = false; - const results = []; - for (const option of def.options) { - const result = option._zod.run({ - value: payload.value, - issues: [], - }, ctx); - if (result instanceof Promise) { - results.push(result); - async = true; - } - else { - results.push(result); - } - } - if (!async) - return handleExclusiveUnionResults(results, payload, inst, ctx); - return Promise.all(results).then((results) => { - return handleExclusiveUnionResults(results, payload, inst, ctx); - }); - }; -}))); -/** Returns the option of `union` whose discriminator claims `value`. */ -function getDiscriminatedOption(union, value) { - const internals = union._zod; - let map = internals.bag.optionsMap; - if (!map) { - map = new Map(); - const { options, discriminator } = internals.def; - for (const option of options) { - // First declaration wins, matching the order the parse path resolves a duplicate in. - for (const v of option._zod.propValues?.[discriminator] ?? []) - if (!map.has(v)) - map.set(v, option); - } - internals.bag.optionsMap = map; - } - return map.get(value); -} -const $ZodDiscriminatedUnion = -/*@__PURE__*/ -$constructor("$ZodDiscriminatedUnion", (inst, def) => { - def.inclusive = false; - $ZodUnion.init(inst, def); - const _super = inst._zod.parse; - defineLazyInternal(inst, "propValues", (zod) => { - const propValues = {}; - for (const option of zod.def.options) { - const pv = option._zod.propValues; - if (!pv || Object.keys(pv).length === 0) - throw new Error(`Invalid discriminated union option at index "${zod.def.options.indexOf(option)}"`); - for (const [k, v] of Object.entries(pv)) { - if (!Object.prototype.hasOwnProperty.call(propValues, k)) { - assignProp(propValues, k, new Set()); - } - for (const val of v) { - propValues[k].add(val); - } - } - } - return propValues; - }); - // Checked now rather than in the lookup map below, so an option that lacks the discriminator fails at the `discriminatedUnion` call instead of on the first object parsed. Options whose shape cannot be enumerated without resolving it — pipes, lazies, and objects rebuilt by a builder such as `.extend()` — are left to the map. - def.options.forEach((option, i) => { - const propShape = propShapes.get(option._zod.def); - if (propShape && !Object.prototype.hasOwnProperty.call(propShape, def.discriminator)) { - throw new Error(`Invalid discriminated union option at index "${i}"`); - } - }); - const disc = util_cached(() => { - const opts = def.options; - const map = new Map(); - for (const o of opts) { - const values = o._zod.propValues?.[def.discriminator]; - if (!values || values.size === 0) - throw new Error(`Invalid discriminated union option at index "${def.options.indexOf(o)}"`); - for (const v of values) { - if (map.has(v)) { - throw new Error(`Duplicate discriminator value "${String(v)}"`); - } - map.set(v, o); - } - } - return map; - }); - inst._zod.parse = (payload, ctx) => { - const input = payload.value; - if (!util_isObject(input)) { - payload.issues.push({ - code: "invalid_type", - expected: "object", - input, - inst, - }); - return payload; - } - const opt = disc.value.get(input?.[def.discriminator]); - if (opt) { - return opt._zod.run(payload, ctx); - } - // Fall back to union matching when the fast discriminator path fails: - // - explicitly enabled via unionFallback, or - // - during backward direction (encode), since codec-based discriminators have different values in forward vs backward directions - if (def.unionFallback || ctx.direction === "backward") { - return _super(payload, ctx); - } - // no matching discriminator - payload.issues.push({ - code: "invalid_union", - errors: [], - note: "No matching discriminator", - discriminator: def.discriminator, - options: Array.from(disc.value.keys()), - input, - path: [def.discriminator], - inst, - }); - return payload; - }; -}); -const $ZodIntersection = /*@__PURE__*/ $constructor("$ZodIntersection", (inst, def) => { - $ZodType.init(inst, def); - inst._zod.parse = (payload, ctx) => { - const input = payload.value; - const left = def.left._zod.run({ value: input, issues: [] }, ctx); - const right = def.right._zod.run({ value: input, issues: [] }, ctx); - const async = left instanceof Promise || right instanceof Promise; - if (async) { - return Promise.all([left, right]).then(([left, right]) => { - return handleIntersectionResults(payload, left, right); - }); - } - return handleIntersectionResults(payload, left, right); - }; -}); -function schemas_mergeValues(a, b) { - // const aType = parse.t(a); - // const bType = parse.t(b); - if (a === b) { - return { valid: true, data: a }; - } - if (a instanceof Date && b instanceof Date && +a === +b) { - return { valid: true, data: a }; - } - if (isPlainObject(a) && isPlainObject(b)) { - const bKeys = Object.keys(b); - const sharedKeys = Object.keys(a).filter((key) => bKeys.indexOf(key) !== -1); - const newObj = { ...a, ...b }; - if (Object.prototype.hasOwnProperty.call(newObj, "__proto__")) - delete newObj.__proto__; - for (const key of sharedKeys) { - if (key === "__proto__") - continue; - const sharedValue = schemas_mergeValues(a[key], b[key]); - if (!sharedValue.valid) { - return { - valid: false, - mergeErrorPath: [key, ...sharedValue.mergeErrorPath], - }; - } - newObj[key] = sharedValue.data; - } - return { valid: true, data: newObj }; - } - if (Array.isArray(a) && Array.isArray(b)) { - if (a.length !== b.length) { - return { valid: false, mergeErrorPath: [] }; - } - const newArray = []; - for (let index = 0; index < a.length; index++) { - const itemA = a[index]; - const itemB = b[index]; - const sharedValue = schemas_mergeValues(itemA, itemB); - if (!sharedValue.valid) { - return { - valid: false, - mergeErrorPath: [index, ...sharedValue.mergeErrorPath], - }; - } - newArray.push(sharedValue.data); - } - return { valid: true, data: newArray }; - } - return { valid: false, mergeErrorPath: [] }; -} -function handleIntersectionResults(result, left, right) { - // Track which side(s) reject each key. A key rejection is reported only when BOTH sides reject it, so a key owned by one branch survives the other's key schema. strictObject reports these as unrecognized_keys; a record with an open key schema reports one invalid_key per key. - const unrecKeys = new Map(); - let unrecIssue; - const keyIssues = new Map(); - const collect = (iss, side) => { - let keys; - if (iss.code === "unrecognized_keys" && !iss.path?.length) { - unrecIssue ?? (unrecIssue = iss); - keys = iss.keys; - } - else if (iss.code === "invalid_key" && iss.origin === "record" && iss.path?.length === 1) { - const k = String(iss.path[0]); - if (!keyIssues.has(k)) - keyIssues.set(k, iss); - keys = [k]; - } - else { - return false; - } - for (const k of keys) { - if (!unrecKeys.has(k)) - unrecKeys.set(k, {}); - unrecKeys.get(k)[side] = true; - } - return true; - }; - for (const iss of left.issues) { - if (!collect(iss, "l")) - result.issues.push(iss); - } - for (const iss of right.issues) { - if (!collect(iss, "r")) - result.issues.push(iss); - } - // Report only keys rejected by BOTH sides - const bothKeys = [...unrecKeys].filter(([, f]) => f.l && f.r).map(([k]) => k); - if (bothKeys.length) { - const aggregated = unrecIssue ? bothKeys.filter((k) => unrecIssue.keys.includes(k)) : []; - if (aggregated.length) - result.issues.push({ ...unrecIssue, keys: aggregated }); - for (const k of bothKeys) { - if (!aggregated.includes(k) && keyIssues.has(k)) - result.issues.push(keyIssues.get(k)); - } - } - const merged = schemas_mergeValues(left.value, right.value); - if (!merged.valid) { - if (aborted(result)) - return result; - throw new Error(`Unmergable intersection. Error path: ` + `${JSON.stringify(merged.mergeErrorPath)}`); - } - result.value = merged.data; - return result; -} -const $ZodTuple = /*@__PURE__*/ (/* unused pure expression or super */ null && (core.$constructor("$ZodTuple", (inst, def) => { - $ZodType.init(inst, def); - const items = def.items; - const memo = core.globalConfig.memoizer; - memo?.attach(inst); - inst._zod.parse = (payload, ctx) => { - const input = payload.value; - if (!Array.isArray(input)) { - payload.issues.push({ - input, - inst, - expected: "tuple", - code: "invalid_type", - }); - return payload; - } - payload.value = memo ? memo.alloc(inst, payload, [], ctx) : []; - const proms = []; - const optinStart = getTupleOptStart(items, "optin"); - const optoutStart = getTupleOptStart(items, "optout"); - if (!def.rest) { - if (input.length < optinStart) { - payload.issues.push({ - code: "too_small", - minimum: optinStart, - inclusive: true, - input, - inst, - origin: "array", - }); - return payload; - } - if (input.length > items.length) { - payload.issues.push({ - code: "too_big", - maximum: items.length, - inclusive: true, - input, - inst, - origin: "array", - }); - } - } - // Run every item in parallel, collecting results into an indexed array. The post-processing in `handleTupleResults` walks them in order so it can decide whether an absent optional-output error can truncate the tail or must be reported to preserve required output. - const itemResults = new Array(items.length); - for (let i = 0; i < items.length; i++) { - const r = items[i]._zod.run({ value: input[i], issues: [] }, ctx); - if (r instanceof Promise) { - proms.push(r.then((rr) => { - itemResults[i] = rr; - })); - } - else { - itemResults[i] = r; - } - } - if (def.rest) { - let i = items.length - 1; - const rest = input.slice(items.length); - for (const el of rest) { - i++; - const result = def.rest._zod.run({ value: el, issues: [] }, ctx); - if (result instanceof Promise) { - proms.push(result.then((r) => handleTupleResult(r, payload, i))); - } - else { - handleTupleResult(result, payload, i); - } - } - } - if (proms.length) { - return Promise.all(proms).then(() => handleTupleResults(itemResults, payload, items, input, optoutStart)); - } - return handleTupleResults(itemResults, payload, items, input, optoutStart); - }; -}))); -function getTupleOptStart(items, key) { - for (let i = items.length - 1; i >= 0; i--) { - // optin is a three-rung ladder so any rung above `undefined` permits an absent slot; optout stays two-valued. - const omittable = key === "optin" ? items[i]._zod.optin !== undefined : items[i]._zod.optout === "optional"; - if (!omittable) - return i + 1; - } - return 0; -} -function handleTupleResult(result, final, index) { - if (result.issues.length) { - final.issues.push(...util.prefixIssues(index, result.issues)); - } - final.value[index] = result.value; -} -function handleTupleResults(itemResults, final, items, input, optoutStart) { - // Walk results in order. Mirror $ZodObject's swallow-on-absent-optional rule, but only after `optoutStart`: the first index where the output tuple tail can be absent. - for (let i = 0; i < items.length; i++) { - const r = itemResults[i]; - const isPresent = i < input.length; - // The array analog of `handlePropertyResult`'s absent-key early return: the middle rung permits absence without supplying anything in its place, so the tail truncates here instead of materializing whatever the item made of `undefined`. - if (!isPresent && i >= optoutStart && items[i]._zod.optin === "optional") { - final.value.length = i; - break; - } - if (r.issues.length) { - if (!isPresent && i >= optoutStart) { - final.value.length = i; - break; - } - final.issues.push(...util.prefixIssues(i, r.issues)); - } - final.value[i] = r.value; - } - // Drop trailing slots that produced `undefined` for absent input - // (the array analog of an absent optional key on an object). The - // `i >= input.length` floor is critical: an explicit `undefined` - // *inside* the input must be preserved even when the schema is - // optional-out (e.g. `z.string().or(z.undefined())` accepting an - // explicit undefined value). - for (let i = final.value.length - 1; i >= input.length; i--) { - if (items[i]._zod.optout === "optional" && final.value[i] === undefined) { - final.value.length = i; - } - else { - break; - } - } - return final; -} -const $ZodRecord = /*@__PURE__*/ $constructor("$ZodRecord", (inst, def) => { - $ZodType.init(inst, def); - const memo = globalConfig.memoizer; - memo?.attach(inst); - inst._zod.parse = (payload, ctx) => { - const input = payload.value; - if (!isPlainObject(input)) { - payload.issues.push({ - expected: "record", - code: "invalid_type", - input, - inst, - }); - return payload; - } - const proms = []; - const values = def.keyType._zod.values; - if (values && !def.partial) { - payload.value = memo ? memo.alloc(inst, payload, {}, ctx) : {}; - const recordKeys = new Set(); - for (const key of values) { - if (typeof key === "string" || typeof key === "number" || typeof key === "symbol") { - recordKeys.add(typeof key === "number" ? key.toString() : key); - // A declared __proto__ is stripped but is not an unrecognized key. - if (key === "__proto__") - continue; - const keyResult = def.keyType._zod.run({ value: key, issues: [] }, ctx); - if (keyResult instanceof Promise) { - throw new Error("Async schemas not supported in object keys currently"); - } - if (keyResult.issues.length) { - payload.issues.push({ - code: "invalid_key", - origin: "record", - issues: keyResult.issues.map((iss) => finalizeIssue(iss, ctx, core_config())), - input: key, - path: [key], - inst, - }); - continue; - } - const outKey = keyResult.value; - if (outKey === "__proto__") - continue; - const result = def.valueType._zod.run({ value: input[key], issues: [] }, ctx); - if (result instanceof Promise) { - proms.push(result.then((result) => { - if (result.issues.length) { - payload.issues.push(...prefixIssues(key, result.issues)); - } - payload.value[outKey] = result.value; - })); - } - else { - if (result.issues.length) { - payload.issues.push(...prefixIssues(key, result.issues)); - } - payload.value[outKey] = result.value; - } - } - } - let unrecognized; - for (const key in input) { - if (!recordKeys.has(key)) { - if (def.mode === "loose") { - // skip __proto__ so it can't replace the result prototype via the assignment setter on the plain {} we build into - if (key === "__proto__") - continue; - payload.value[key] = input[key]; - } - else { - unrecognized = unrecognized ?? []; - unrecognized.push(key); - } - } - } - if (unrecognized && unrecognized.length > 0) { - payload.issues.push({ - code: "unrecognized_keys", - input, - inst, - keys: unrecognized, - continue: true, - }); - } - } - else { - payload.value = memo ? memo.alloc(inst, payload, {}, ctx) : {}; - // An enumerable key schema declares which keys the record owns, so a key outside the set is unrecognized. A non-enumerable one (regex, refine) is a constraint every key must satisfy, so a failing key is invalid. Only the former is reconcilable against the other side of an intersection. - let unrecognized; - // Reflect.ownKeys for Symbol-key support; filter non-enumerable to match z.object() - for (const key of Reflect.ownKeys(input)) { - if (key === "__proto__") - continue; - if (!Object.prototype.propertyIsEnumerable.call(input, key)) - continue; - let keyResult = def.keyType._zod.run({ value: key, issues: [] }, ctx); - if (keyResult instanceof Promise) { - throw new Error("Async schemas not supported in object keys currently"); - } - // Numeric string fallback: if key is a numeric string and failed, retry with Number(key). This handles z.number(), z.literal([1, 2, 3]), and unions containing numeric literals - const checkNumericKey = typeof key === "string" && number.test(key) && keyResult.issues.length; - if (checkNumericKey) { - const retryResult = def.keyType._zod.run({ value: Number(key), issues: [] }, ctx); - if (retryResult instanceof Promise) { - throw new Error("Async schemas not supported in object keys currently"); - } - if (retryResult.issues.length === 0) { - keyResult = retryResult; - } - } - if (keyResult.issues.length) { - if (def.mode === "loose") { - // Pass through unchanged - payload.value[key] = input[key]; - } - else if (values) { - unrecognized = unrecognized ?? []; - unrecognized.push(key); - } - else { - // Default "strict" behavior: error on invalid key - payload.issues.push({ - code: "invalid_key", - origin: "record", - issues: keyResult.issues.map((iss) => finalizeIssue(iss, ctx, core_config())), - input: key, - path: [key], - inst, - }); - } - continue; - } - // the guard above tests the raw input key, but the key schema can normalize an ordinary key into __proto__; re-check the key we actually write under - const outKey = keyResult.value; - if (outKey === "__proto__") - continue; - const result = def.valueType._zod.run({ value: input[key], issues: [] }, ctx); - if (result instanceof Promise) { - proms.push(result.then((result) => { - if (result.issues.length) { - payload.issues.push(...prefixIssues(key, result.issues)); - } - payload.value[outKey] = result.value; - })); - } - else { - if (result.issues.length) { - payload.issues.push(...prefixIssues(key, result.issues)); - } - payload.value[outKey] = result.value; - } - } - if (unrecognized && unrecognized.length > 0) { - payload.issues.push({ - code: "unrecognized_keys", - input, - inst, - keys: unrecognized, - continue: true, - }); - } - } - if (proms.length) { - return Promise.all(proms).then(() => payload); - } - return payload; - }; -}); -const $ZodMap = /*@__PURE__*/ (/* unused pure expression or super */ null && (core.$constructor("$ZodMap", (inst, def) => { - $ZodType.init(inst, def); - const memo = core.globalConfig.memoizer; - memo?.attach(inst); - inst._zod.parse = (payload, ctx) => { - const input = payload.value; - if (!(input instanceof Map)) { - payload.issues.push({ - expected: "map", - code: "invalid_type", - input, - inst, - }); - return payload; - } - const proms = []; - payload.value = memo ? memo.alloc(inst, payload, new Map(), ctx) : new Map(); - for (const [key, value] of input) { - const keyResult = def.keyType._zod.run({ value: key, issues: [] }, ctx); - const valueResult = def.valueType._zod.run({ value: value, issues: [] }, ctx); - if (keyResult instanceof Promise || valueResult instanceof Promise) { - proms.push(Promise.all([keyResult, valueResult]).then(([keyResult, valueResult]) => { - handleMapResult(keyResult, valueResult, payload, key, input, inst, ctx); - })); - } - else { - handleMapResult(keyResult, valueResult, payload, key, input, inst, ctx); - } - } - if (proms.length) - return Promise.all(proms).then(() => payload); - return payload; - }; -}))); -function handleMapResult(keyResult, valueResult, final, key, input, inst, ctx) { - if (keyResult.issues.length) { - if (util.propertyKeyTypes.has(typeof key)) { - final.issues.push(...util.prefixIssues(key, keyResult.issues)); - } - else { - final.issues.push({ - code: "invalid_key", - origin: "map", - input, - inst, - issues: keyResult.issues.map((iss) => util.finalizeIssue(iss, ctx, core.config())), - }); - } - } - if (valueResult.issues.length) { - if (util.propertyKeyTypes.has(typeof key)) { - final.issues.push(...util.prefixIssues(key, valueResult.issues)); - } - else { - final.issues.push({ - origin: "map", - code: "invalid_element", - input, - inst, - key: key, - issues: valueResult.issues.map((iss) => util.finalizeIssue(iss, ctx, core.config())), - }); - } - } - final.value.set(keyResult.value, valueResult.value); -} -const $ZodSet = /*@__PURE__*/ (/* unused pure expression or super */ null && (core.$constructor("$ZodSet", (inst, def) => { - $ZodType.init(inst, def); - const memo = core.globalConfig.memoizer; - memo?.attach(inst); - inst._zod.parse = (payload, ctx) => { - const input = payload.value; - if (!(input instanceof Set)) { - payload.issues.push({ - input, - inst, - expected: "set", - code: "invalid_type", - }); - return payload; - } - const proms = []; - payload.value = memo ? memo.alloc(inst, payload, new Set(), ctx) : new Set(); - for (const item of input) { - const result = def.valueType._zod.run({ value: item, issues: [] }, ctx); - if (result instanceof Promise) { - proms.push(result.then((result) => handleSetResult(result, payload))); - } - else - handleSetResult(result, payload); - } - if (proms.length) - return Promise.all(proms).then(() => payload); - return payload; - }; -}))); -function handleSetResult(result, final) { - if (result.issues.length) { - final.issues.push(...result.issues); - } - final.value.add(result.value); -} -const $ZodEnum = /*@__PURE__*/ $constructor("$ZodEnum", (inst, def) => { - $ZodType.init(inst, def); - const values = getEnumValues(def.entries); - const valuesSet = new Set(values); - inst._zod.values = valuesSet; - const patternValues = values.filter((k) => propertyKeyTypes.has(typeof k)); - // unmatchable fallback, RE2-safe: an empty alternation would compile to /^()$/, which matches "" - inst._zod.pattern = new RegExp(patternValues.length ? `^(${patternValues.map((o) => escapeRegex(o.toString())).join("|")})$` : "^[^\\s\\S]$"); - inst._zod.parse = (payload, _ctx) => { - const input = payload.value; - if (valuesSet.has(input)) { - return payload; - } - payload.issues.push({ - code: "invalid_value", - values, - input, - inst, - }); - return payload; - }; -}); -const $ZodLiteral = /*@__PURE__*/ $constructor("$ZodLiteral", (inst, def) => { - $ZodType.init(inst, def); - const values = new Set(def.values); - inst._zod.values = values; - // unmatchable fallback, RE2-safe: an empty alternation would compile to /^()$/, which matches "" - inst._zod.pattern = new RegExp(def.values.length - ? `^(${def.values - .map((o) => (typeof o === "string" ? escapeRegex(o) : o ? escapeRegex(o.toString()) : String(o))) - .join("|")})$` - : "^[^\\s\\S]$"); - inst._zod.parse = (payload, _ctx) => { - const input = payload.value; - if (values.has(input)) { - return payload; - } - payload.issues.push({ - code: "invalid_value", - values: def.values, - input, - inst, - }); - return payload; - }; -}); -const $ZodFile = /*@__PURE__*/ (/* unused pure expression or super */ null && (core.$constructor("$ZodFile", (inst, def) => { - $ZodType.init(inst, def); - inst._zod.parse = (payload, _ctx) => { - const input = payload.value; - // @ts-ignore - if (input instanceof File) - return payload; - payload.issues.push({ - expected: "file", - code: "invalid_type", - input, - inst, - }); - return payload; - }; -}))); -const $ZodTransform = /*@__PURE__*/ $constructor("$ZodTransform", (inst, def) => { - $ZodType.init(inst, def); - inst._zod.optin = "optional"; - globalConfig.memoizer?.guard(inst); - inst._zod.parse = (payload, ctx) => { - if (ctx.direction === "backward") { - throw new $ZodEncodeError(inst.constructor.name); - } - const _out = def.transform(payload.value, payload); - if (ctx.async) { - const output = _out instanceof Promise ? _out : Promise.resolve(_out); - return output.then((output) => { - payload.value = output; - return payload; - }); - } - if (_out instanceof Promise) { - throw new $ZodAsyncError(); - } - payload.value = _out; - return payload; - }; -}); -function handleOptionalResult(payload, result) { - // A substituting schema that still failed has no usable answer; yield undefined. Its issues are simply dropped: it ran on a payload of its own, so there is no shared array to truncate and nothing of the caller's to lose with it. - payload.value = result.issues.length ? undefined : result.value; - return payload; -} -const $ZodOptional = /*@__PURE__*/ $constructor("$ZodOptional", (inst, def) => { - $ZodType.init(inst, def); - // .optional() propagates absence rather than substituting for it, so a defaulted inner keeps its rung. - defineLazyInternal(inst, "optin", (zod) => zod.def.innerType._zod.optin === "defaulted" ? "defaulted" : "optional"); - inst._zod.optout = "optional"; - defineLazyInternal(inst, "values", (zod) => { - const values = zod.def.innerType._zod.values; - return values ? new Set([...values, undefined]) : undefined; - }); - defineLazyInternal(inst, "pattern", (zod) => { - const pattern = zod.def.innerType._zod.pattern; - return pattern ? new RegExp(`^(${cleanRegex(pattern.source)})?$`) : undefined; - }); - inst._zod.parse = (payload, ctx) => { - if (payload.value === undefined) { - // Only the top rung substitutes a value for absence; everything else leaves it intact, which is what .optional() means. - if (def.innerType._zod.optin !== "defaulted") - return payload; - // Its own payload, for the same reason $ZodCatch gets one: a pipe forwards an unrecognized key through the caller's issues array, and this must not read that as the substituting schema failing and drop it. - const result = def.innerType._zod.run({ value: payload.value, issues: [] }, ctx); - if (result instanceof Promise) - return result.then((result) => handleOptionalResult(payload, result)); - return handleOptionalResult(payload, result); - } - return def.innerType._zod.run(payload, ctx); - }; -}); -const $ZodExactOptional = /*@__PURE__*/ $constructor("$ZodExactOptional", (inst, def) => { - // Call parent init - inherits optin/optout = "optional" - $ZodOptional.init(inst, def); - // Override values/pattern to NOT add undefined - defineLazyInternal(inst, "values", (zod) => zod.def.innerType._zod.values); - defineLazyInternal(inst, "pattern", (zod) => zod.def.innerType._zod.pattern); - // Override parse to just delegate (no undefined handling) - inst._zod.parse = (payload, ctx) => { - return def.innerType._zod.run(payload, ctx); - }; -}); -const $ZodNullable = /*@__PURE__*/ $constructor("$ZodNullable", (inst, def) => { - $ZodType.init(inst, def); - defineLazyInternal(inst, "optin", (zod) => zod.def.innerType._zod.optin); - defineLazyInternal(inst, "optout", (zod) => zod.def.innerType._zod.optout); - defineLazyInternal(inst, "pattern", (zod) => { - const pattern = zod.def.innerType._zod.pattern; - return pattern ? new RegExp(`^(${cleanRegex(pattern.source)}|null)$`) : undefined; - }); - defineLazyInternal(inst, "values", (zod) => { - return zod.def.innerType._zod.values ? new Set([...zod.def.innerType._zod.values, null]) : undefined; - }); - inst._zod.parse = (payload, ctx) => { - // Forward direction (decode): allow null to pass through - if (payload.value === null) - return payload; - return def.innerType._zod.run(payload, ctx); - }; -}); -const $ZodDefault = /*@__PURE__*/ $constructor("$ZodDefault", (inst, def) => { - $ZodType.init(inst, def); - // inst._zod.qin = "true"; - inst._zod.optin = "defaulted"; - defineLazyInternal(inst, "values", (zod) => zod.def.innerType._zod.values); - inst._zod.parse = (payload, ctx) => { - if (ctx.direction === "backward") { - return def.innerType._zod.run(payload, ctx); - } - // Forward direction (decode): apply defaults for undefined input - if (payload.value === undefined) { - payload.value = def.defaultValue; - /** - * $ZodDefault returns the default value immediately in forward direction. - * It doesn't pass the default value into the validator ("prefault"). There's no reason to pass the default value through validation. The validity of the default is enforced by TypeScript statically. Otherwise, it's the responsibility of the user to ensure the default is valid. In the case of pipes with divergent in/out types, you can specify the default on the `in` schema of your ZodPipe to set a "prefault" for the pipe. */ - return payload; - } - // Forward direction: continue with default handling - const result = def.innerType._zod.run(payload, ctx); - if (result instanceof Promise) { - return result.then((result) => handleDefaultResult(result, def)); - } - return handleDefaultResult(result, def); - }; -}); -function handleDefaultResult(payload, def) { - if (payload.value === undefined) { - payload.value = def.defaultValue; - } - return payload; -} -const $ZodPrefault = /*@__PURE__*/ $constructor("$ZodPrefault", (inst, def) => { - $ZodType.init(inst, def); - inst._zod.optin = "defaulted"; - defineLazyInternal(inst, "values", (zod) => zod.def.innerType._zod.values); - inst._zod.parse = (payload, ctx) => { - if (ctx.direction === "backward") { - return def.innerType._zod.run(payload, ctx); - } - // Forward direction (decode): apply prefault for undefined input - if (payload.value === undefined) { - payload.value = def.defaultValue; - } - return def.innerType._zod.run(payload, ctx); - }; -}); -const $ZodNonOptional = /*@__PURE__*/ $constructor("$ZodNonOptional", (inst, def) => { - $ZodType.init(inst, def); - defineLazyInternal(inst, "values", (zod) => { - const v = zod.def.innerType._zod.values; - return v ? new Set([...v].filter((x) => x !== undefined)) : undefined; - }); - inst._zod.parse = (payload, ctx) => { - const result = def.innerType._zod.run(payload, ctx); - if (result instanceof Promise) { - return result.then((result) => handleNonOptionalResult(result, inst)); - } - return handleNonOptionalResult(result, inst); - }; -}); -function handleNonOptionalResult(payload, inst) { - if (!payload.issues.length && payload.value === undefined) { - payload.issues.push({ - code: "invalid_type", - expected: "nonoptional", - input: payload.value, - inst, - }); - } - return payload; -} -const $ZodSuccess = /*@__PURE__*/ (/* unused pure expression or super */ null && (core.$constructor("$ZodSuccess", (inst, def) => { - $ZodType.init(inst, def); - inst._zod.parse = (payload, ctx) => { - if (ctx.direction === "backward") { - throw new core.$ZodEncodeError("ZodSuccess"); - } - const result = def.innerType._zod.run(payload, ctx); - if (result instanceof Promise) { - return result.then((result) => { - payload.value = result.issues.length === 0; - return payload; - }); - } - payload.value = result.issues.length === 0; - return payload; - }; -}))); -function handleCatchResult(payload, result, def, ctx) { - if (!result.issues.length) { - payload.value = result.value; - // The value carries up, so the flag describing it has to carry with it: a back-edge into a node still being parsed must not be frozen by an enclosing readonly, and its checks belong to the node itself. Guarded so the ordinary case adds no own property. - if (result.memo) - payload.memo = true; - return payload; - } - // Spread the inner's own payload, not ours: `value` has to stay the input the catch was handed, and the inner ran on a payload of its own so its issues are already private to this call. - payload.value = def.catchValue({ - ...result, - value: payload.value, - error: { - issues: result.issues.map((iss) => finalizeIssue(iss, ctx, core_config())), - }, - input: payload.value, - }); - return payload; -} -const $ZodCatch = /*@__PURE__*/ $constructor("$ZodCatch", (inst, def) => { - $ZodType.init(inst, def); - defineLazyInternal(inst, "optin", (zod) => zod.def.innerType._zod.optin === "defaulted" ? "defaulted" : "optional"); - defineLazyInternal(inst, "optout", (zod) => zod.def.innerType._zod.optout); - defineLazyInternal(inst, "values", (zod) => zod.def.innerType._zod.values); - inst._zod.parse = (payload, ctx) => { - if (ctx.direction === "backward") { - return def.innerType._zod.run(payload, ctx); - } - // Forward direction (decode): apply catch logic - const result = def.innerType._zod.run({ value: payload.value, issues: [] }, ctx); - if (result instanceof Promise) { - return result.then((result) => handleCatchResult(payload, result, def, ctx)); - } - return handleCatchResult(payload, result, def, ctx); - }; -}); -const $ZodNaN = /*@__PURE__*/ (/* unused pure expression or super */ null && (core.$constructor("$ZodNaN", (inst, def) => { - $ZodType.init(inst, def); - inst._zod.parse = (payload, _ctx) => { - if (typeof payload.value !== "number" || !Number.isNaN(payload.value)) { - payload.issues.push({ - input: payload.value, - inst, - expected: "nan", - code: "invalid_type", - }); - return payload; - } - return payload; - }; -}))); -const $ZodPipe = /*@__PURE__*/ $constructor("$ZodPipe", (inst, def) => { - $ZodType.init(inst, def); - defineLazyInternal(inst, "values", (zod) => zod.def.in._zod.values); - defineLazyInternal(inst, "optin", (zod) => zod.def.in._zod.optin); - defineLazyInternal(inst, "optout", (zod) => zod.def.out._zod.optout); - defineLazyInternal(inst, "propValues", (zod) => zod.def.in._zod.propValues); - inst._zod.parse = (payload, ctx) => { - if (ctx.direction === "backward") { - const right = def.out._zod.run(payload, ctx); - if (right instanceof Promise) { - return right.then((right) => handlePipeResult(right, def.in, ctx)); - } - return handlePipeResult(right, def.in, ctx); - } - const left = def.in._zod.run(payload, ctx); - if (left instanceof Promise) { - return left.then((left) => handlePipeResult(left, def.out, ctx)); - } - return handlePipeResult(left, def.out, ctx); - }; -}); -function handlePipeResult(left, next, ctx) { - // Any issue stops the pipe, so a failing refinement never feeds its transform. An unrecognized key is the exception: it describes the input's extra properties, not the value being piped, and an enclosing intersection may yet reconcile it. - if (left.issues.some((iss) => iss.code !== "unrecognized_keys")) { - // prevent further checks - left.aborted = true; - return left; - } - return next._zod.run({ value: left.value, issues: left.issues }, ctx); -} -const $ZodCodec = /*@__PURE__*/ (/* unused pure expression or super */ null && (core.$constructor("$ZodCodec", (inst, def) => { - $ZodType.init(inst, def); - util.defineLazyInternal(inst, "values", (zod) => zod.def.in._zod.values); - util.defineLazyInternal(inst, "optin", (zod) => zod.def.in._zod.optin); - util.defineLazyInternal(inst, "optout", (zod) => zod.def.out._zod.optout); - util.defineLazyInternal(inst, "propValues", (zod) => zod.def.in._zod.propValues); - inst._zod.parse = (payload, ctx) => { - const direction = ctx.direction || "forward"; - if (direction === "forward") { - const left = def.in._zod.run(payload, ctx); - if (left instanceof Promise) { - return left.then((left) => handleCodecAResult(left, def, ctx)); - } - return handleCodecAResult(left, def, ctx); - } - else { - const right = def.out._zod.run(payload, ctx); - if (right instanceof Promise) { - return right.then((right) => handleCodecAResult(right, def, ctx)); - } - return handleCodecAResult(right, def, ctx); - } - }; -}))); -function handleCodecAResult(result, def, ctx) { - if (result.issues.length) { - // prevent further checks - result.aborted = true; - return result; - } - const direction = ctx.direction || "forward"; - if (direction === "forward") { - const transformed = def.transform(result.value, result); - if (transformed instanceof Promise) { - return transformed.then((value) => handleCodecTxResult(result, value, def.out, ctx)); - } - return handleCodecTxResult(result, transformed, def.out, ctx); - } - else { - const transformed = def.reverseTransform(result.value, result); - if (transformed instanceof Promise) { - return transformed.then((value) => handleCodecTxResult(result, value, def.in, ctx)); - } - return handleCodecTxResult(result, transformed, def.in, ctx); - } -} -function handleCodecTxResult(left, value, nextSchema, ctx) { - // Check if transform added any issues - if (left.issues.length) { - left.aborted = true; - return left; - } - return nextSchema._zod.run({ value, issues: left.issues }, ctx); -} -const $ZodPreprocess = /*@__PURE__*/ $constructor("$ZodPreprocess", (inst, def) => { - $ZodPipe.init(inst, def); -}); -const $ZodReadonly = /*@__PURE__*/ $constructor("$ZodReadonly", (inst, def) => { - $ZodType.init(inst, def); - defineLazyInternal(inst, "propValues", (zod) => zod.def.innerType._zod.propValues); - defineLazyInternal(inst, "values", (zod) => zod.def.innerType._zod.values); - defineLazyInternal(inst, "optin", (zod) => zod.def.innerType?._zod?.optin); - defineLazyInternal(inst, "optout", (zod) => zod.def.innerType?._zod?.optout); - inst._zod.parse = (payload, ctx) => { - if (ctx.direction === "backward") { - return def.innerType._zod.run(payload, ctx); - } - const result = def.innerType._zod.run(payload, ctx); - if (result instanceof Promise) { - return result.then(handleReadonlyResult); - } - return handleReadonlyResult(result); - }; -}); -function handleReadonlyResult(payload) { - // A repeat visit hands back a node that is still being built; freezing it here would make the rest of its keys fail to assign. - if (!payload.memo) - payload.value = Object.freeze(payload.value); - return payload; -} -const $ZodTemplateLiteral = /*@__PURE__*/ (/* unused pure expression or super */ null && (core.$constructor("$ZodTemplateLiteral", (inst, def) => { - $ZodType.init(inst, def); - const regexParts = []; - for (const part of def.parts) { - if (typeof part === "object" && part !== null) { - // is Zod schema - if (!part._zod.pattern) { - // if (!source) - throw new Error(`Invalid template literal part, no pattern found: ${[...part._zod.traits].shift()}`); - } - const source = part._zod.pattern instanceof RegExp ? part._zod.pattern.source : part._zod.pattern; - if (!source) - throw new Error(`Invalid template literal part: ${part._zod.traits}`); - const start = source.startsWith("^") ? 1 : 0; - const end = source.endsWith("$") ? source.length - 1 : source.length; - regexParts.push(source.slice(start, end)); - } - else if (part === null || util.primitiveTypes.has(typeof part)) { - regexParts.push(util.escapeRegex(`${part}`)); - } - else { - throw new Error(`Invalid template literal part: ${part}`); - } - } - inst._zod.pattern = new RegExp(`^${regexParts.join("")}$`); - inst._zod.parse = (payload, _ctx) => { - if (typeof payload.value !== "string") { - payload.issues.push({ - input: payload.value, - inst, - expected: "string", - code: "invalid_type", - }); - return payload; - } - inst._zod.pattern.lastIndex = 0; - if (!inst._zod.pattern.test(payload.value)) { - payload.issues.push({ - input: payload.value, - inst, - code: "invalid_format", - format: def.format ?? "template_literal", - pattern: inst._zod.pattern.source, - }); - return payload; - } - return payload; - }; -}))); -const $ZodFunction = /*@__PURE__*/ (/* unused pure expression or super */ null && (core.$constructor("$ZodFunction", (inst, def) => { - $ZodType.init(inst, def); - // Defined, not assigned: the classic prototype exposes `_def` as a getter with no setter. - Object.defineProperty(inst, "_def", { value: def }); - inst._zod.def = def; - inst.implement = (func) => { - if (typeof func !== "function") { - throw new Error("implement() must be called with a function"); - } - // Defined inline so the closure stays anonymous: binding it to a `const` first names it, which costs 256 bytes per implemented function. - return Object.defineProperty(function (...args) { - const parsedArgs = inst._def.input ? parse(inst._def.input, args) : args; - const result = Reflect.apply(func, this, parsedArgs); - if (inst._def.output) { - return parse(inst._def.output, result); - } - return result; - }, "_zod", { value: inst._zod, enumerable: false }); - }; - inst.implementAsync = (func) => { - if (typeof func !== "function") { - throw new Error("implementAsync() must be called with a function"); - } - return Object.defineProperty(async function (...args) { - const parsedArgs = inst._def.input ? await parseAsync(inst._def.input, args) : args; - const result = await Reflect.apply(func, this, parsedArgs); - if (inst._def.output) { - return await parseAsync(inst._def.output, result); - } - return result; - }, "_zod", { value: inst._zod, enumerable: false }); - }; - inst._zod.parse = (payload, _ctx) => { - if (typeof payload.value !== "function") { - payload.issues.push({ - code: "invalid_type", - expected: "function", - input: payload.value, - inst, - }); - return payload; - } - // Check if output is a promise type to determine if we should use async implementation - const hasPromiseOutput = inst._def.output && inst._def.output._zod.def.type === "promise"; - if (hasPromiseOutput) { - payload.value = inst.implementAsync(payload.value); - } - else { - payload.value = inst.implement(payload.value); - } - return payload; - }; - inst.input = (...args) => { - const F = inst.constructor; - if (Array.isArray(args[0])) { - return new F({ - type: "function", - input: new $ZodTuple({ - type: "tuple", - items: args[0], - rest: args[1], - }), - output: inst._def.output, - }); - } - return new F({ - type: "function", - input: args[0], - output: inst._def.output, - }); - }; - inst.output = (output) => { - const F = inst.constructor; - return new F({ - type: "function", - input: inst._def.input, - output, - }); - }; - return inst; -}))); -const $ZodPromise = /*@__PURE__*/ (/* unused pure expression or super */ null && (core.$constructor("$ZodPromise", (inst, def) => { - $ZodType.init(inst, def); - inst._zod.parse = (payload, ctx) => { - return Promise.resolve(payload.value).then((inner) => def.innerType._zod.run({ value: inner, issues: [] }, ctx)); - }; -}))); -const $ZodLazy = /*@__PURE__*/ $constructor("$ZodLazy", (inst, def) => { - $ZodType.init(inst, def); - // Cache the resolved inner type on the shared `def` so all clones of this lazy (e.g. via `.describe()`/`.meta()`) share the same inner instance, preserving identity for cycle detection on recursive schemas. - defineLazy(inst._zod, "innerType", () => { - const d = def; - if (!d._cachedInner) - d._cachedInner = def.getter(); - return d._cachedInner; - }); - defineLazyInternal(inst, "pattern", (zod) => zod.innerType?._zod?.pattern); - defineLazyInternal(inst, "propValues", (zod) => zod.innerType?._zod?.propValues); - defineLazyInternal(inst, "optin", (zod) => zod.innerType?._zod?.optin ?? undefined); - defineLazyInternal(inst, "optout", (zod) => zod.innerType?._zod?.optout ?? undefined); - inst._zod.parse = (payload, ctx) => { - const inner = inst._zod.innerType; - return inner._zod.run(payload, ctx); - }; -}); -const $ZodCustom = /*@__PURE__*/ $constructor("$ZodCustom", (inst, def) => { - $ZodCheck.init(inst, def); - $ZodType.init(inst, def); - inst._zod.parse = (payload, _) => { - return payload; - }; - inst._zod.check = (payload) => { - const input = payload.value; - const r = def.fn(input); - if (r instanceof Promise) { - return r.then((r) => handleRefineResult(r, payload, input, inst)); - } - handleRefineResult(r, payload, input, inst); - return; - }; -}); -function handleRefineResult(result, payload, input, inst) { - if (!result) { - const _iss = { - code: "custom", - input, - inst, // incorporates params.error into issue reporting - path: [...(inst._zod.def.path ?? [])], // incorporates params.error into issue reporting - continue: !inst._zod.def.abort, - // params: inst._zod.def.params, - }; - if (inst._zod.def.params) - _iss.params = inst._zod.def.params; - payload.issues.push(util_issue(_iss)); - } -} - -var registries_a; -const $output = /*@__PURE__*/ (/* unused pure expression or super */ null && (Symbol("ZodOutput"))); -const $input = /*@__PURE__*/ (/* unused pure expression or super */ null && (Symbol("ZodInput"))); -class $ZodRegistry { - constructor() { - this._map = new WeakMap(); - this._idmap = new Map(); - } - add(schema, ..._meta) { - const meta = _meta[0]; - this._map.set(schema, meta); - if (meta && typeof meta === "object" && "id" in meta) { - this._idmap.set(meta.id, schema); - } - return this; - } - clear() { - this._map = new WeakMap(); - this._idmap = new Map(); - return this; - } - remove(schema) { - const meta = this._map.get(schema); - if (meta && typeof meta === "object" && "id" in meta) { - this._idmap.delete(meta.id); - } - this._map.delete(schema); - return this; - } - get(schema) { - // return this._map.get(schema) as any; - // inherit metadata - const p = schema._zod.parent; - if (p) { - const pm = { ...(this.get(p) ?? {}) }; - delete pm.id; // do not inherit id - const f = { ...pm, ...this._map.get(schema) }; - return Object.keys(f).length ? f : undefined; - } - return this._map.get(schema); - } - has(schema) { - return this._map.has(schema); - } -} -// registries -function registries_registry() { - return new $ZodRegistry(); -} -(registries_a = globalThis).__zod_globalRegistry ?? (registries_a.__zod_globalRegistry = registries_registry()); -const globalRegistry = globalThis.__zod_globalRegistry; - - - - - -// @__NO_SIDE_EFFECTS__ -function _string(Class, params) { - return new Class({ - type: "string", - ...normalizeParams(params), - }); -} -// @__NO_SIDE_EFFECTS__ -function _coercedString(Class, params) { - return new Class({ - type: "string", - coerce: true, - ...util.normalizeParams(params), - }); -} -// @__NO_SIDE_EFFECTS__ -function _email(Class, params) { - return new Class({ - type: "string", - format: "email", - check: "string_format", - abort: false, - ...normalizeParams(params), - }); -} -// @__NO_SIDE_EFFECTS__ -function _guid(Class, params) { - return new Class({ - type: "string", - format: "guid", - check: "string_format", - abort: false, - ...normalizeParams(params), - }); -} -// @__NO_SIDE_EFFECTS__ -function _uuid(Class, params) { - return new Class({ - type: "string", - format: "uuid", - check: "string_format", - abort: false, - ...normalizeParams(params), - }); -} -// @__NO_SIDE_EFFECTS__ -function _uuidv4(Class, params) { - return new Class({ - type: "string", - format: "uuid", - check: "string_format", - abort: false, - version: "v4", - ...normalizeParams(params), - }); -} -// @__NO_SIDE_EFFECTS__ -function _uuidv6(Class, params) { - return new Class({ - type: "string", - format: "uuid", - check: "string_format", - abort: false, - version: "v6", - ...normalizeParams(params), - }); -} -// @__NO_SIDE_EFFECTS__ -function _uuidv7(Class, params) { - return new Class({ - type: "string", - format: "uuid", - check: "string_format", - abort: false, - version: "v7", - ...normalizeParams(params), - }); -} -// @__NO_SIDE_EFFECTS__ -function _url(Class, params) { - return new Class({ - type: "string", - format: "url", - check: "string_format", - abort: false, - ...normalizeParams(params), - }); -} -// @__NO_SIDE_EFFECTS__ -function api_emoji(Class, params) { - return new Class({ - type: "string", - format: "emoji", - check: "string_format", - abort: false, - ...normalizeParams(params), - }); -} -// @__NO_SIDE_EFFECTS__ -function _nanoid(Class, params) { - return new Class({ - type: "string", - format: "nanoid", - check: "string_format", - abort: false, - ...normalizeParams(params), - }); -} -/** - * @deprecated CUID v1 is deprecated by its authors due to information leakage - * (timestamps embedded in the id). Use {@link _cuid2} instead. - * See https://github.com/paralleldrive/cuid. - */ -// @__NO_SIDE_EFFECTS__ -function _cuid(Class, params) { - return new Class({ - type: "string", - format: "cuid", - check: "string_format", - abort: false, - ...normalizeParams(params), - }); -} -// @__NO_SIDE_EFFECTS__ -function _cuid2(Class, params) { - return new Class({ - type: "string", - format: "cuid2", - check: "string_format", - abort: false, - ...normalizeParams(params), - }); -} -// @__NO_SIDE_EFFECTS__ -function _ulid(Class, params) { - return new Class({ - type: "string", - format: "ulid", - check: "string_format", - abort: false, - ...normalizeParams(params), - }); -} -// @__NO_SIDE_EFFECTS__ -function _xid(Class, params) { - return new Class({ - type: "string", - format: "xid", - check: "string_format", - abort: false, - ...normalizeParams(params), - }); -} -// @__NO_SIDE_EFFECTS__ -function _ksuid(Class, params) { - return new Class({ - type: "string", - format: "ksuid", - check: "string_format", - abort: false, - ...normalizeParams(params), - }); -} -// @__NO_SIDE_EFFECTS__ -function _ipv4(Class, params) { - return new Class({ - type: "string", - format: "ipv4", - check: "string_format", - abort: false, - ...normalizeParams(params), - }); -} -// @__NO_SIDE_EFFECTS__ -function _ipv6(Class, params) { - return new Class({ - type: "string", - format: "ipv6", - check: "string_format", - abort: false, - ...normalizeParams(params), - }); -} -// @__NO_SIDE_EFFECTS__ -function _mac(Class, params) { - return new Class({ - type: "string", - format: "mac", - check: "string_format", - abort: false, - ...util.normalizeParams(params), - }); -} -// @__NO_SIDE_EFFECTS__ -function _cidrv4(Class, params) { - return new Class({ - type: "string", - format: "cidrv4", - check: "string_format", - abort: false, - ...normalizeParams(params), - }); -} -// @__NO_SIDE_EFFECTS__ -function _cidrv6(Class, params) { - return new Class({ - type: "string", - format: "cidrv6", - check: "string_format", - abort: false, - ...normalizeParams(params), - }); -} -// @__NO_SIDE_EFFECTS__ -function _base64(Class, params) { - return new Class({ - type: "string", - format: "base64", - check: "string_format", - abort: false, - ...normalizeParams(params), - }); -} -// @__NO_SIDE_EFFECTS__ -function _base64url(Class, params) { - return new Class({ - type: "string", - format: "base64url", - check: "string_format", - abort: false, - ...normalizeParams(params), - }); -} -// @__NO_SIDE_EFFECTS__ -function _e164(Class, params) { - return new Class({ - type: "string", - format: "e164", - check: "string_format", - abort: false, - ...normalizeParams(params), - }); -} -// @__NO_SIDE_EFFECTS__ -function _creditCard(Class, params) { - return new Class({ - type: "string", - format: "credit_card", - check: "string_format", - abort: false, - ...util.normalizeParams(params), - }); -} -// @__NO_SIDE_EFFECTS__ -function _jwt(Class, params) { - return new Class({ - type: "string", - format: "jwt", - check: "string_format", - abort: false, - ...normalizeParams(params), - }); -} -const TimePrecision = (/* unused pure expression or super */ null && ({ - Any: null, - Minute: -1, - Second: 0, - Millisecond: 3, - Microsecond: 6, -})); -// @__NO_SIDE_EFFECTS__ -function _isoDateTime(Class, params) { - return new Class({ - type: "string", - format: "datetime", - check: "string_format", - offset: false, - local: false, - precision: null, - ...normalizeParams(params), - }); -} -// @__NO_SIDE_EFFECTS__ -function _isoDate(Class, params) { - return new Class({ - type: "string", - format: "date", - check: "string_format", - ...normalizeParams(params), - }); -} -// @__NO_SIDE_EFFECTS__ -function _isoTime(Class, params) { - return new Class({ - type: "string", - format: "time", - check: "string_format", - precision: null, - ...normalizeParams(params), - }); -} -// @__NO_SIDE_EFFECTS__ -function _isoDuration(Class, params) { - return new Class({ - type: "string", - format: "duration", - check: "string_format", - ...normalizeParams(params), - }); -} -// @__NO_SIDE_EFFECTS__ -function _number(Class, params) { - return new Class({ - type: "number", - checks: [], - ...normalizeParams(params), - }); -} -// @__NO_SIDE_EFFECTS__ -function _coercedNumber(Class, params) { - return new Class({ - type: "number", - coerce: true, - checks: [], - ...normalizeParams(params), - }); -} -// @__NO_SIDE_EFFECTS__ -function _int(Class, params) { - return new Class({ - type: "number", - check: "number_format", - abort: false, - format: "safeint", - ...normalizeParams(params), - }); -} -// @__NO_SIDE_EFFECTS__ -function _float32(Class, params) { - return new Class({ - type: "number", - check: "number_format", - abort: false, - format: "float32", - ...util.normalizeParams(params), - }); -} -// @__NO_SIDE_EFFECTS__ -function _float64(Class, params) { - return new Class({ - type: "number", - check: "number_format", - abort: false, - format: "float64", - ...util.normalizeParams(params), - }); -} -// @__NO_SIDE_EFFECTS__ -function _int32(Class, params) { - return new Class({ - type: "number", - check: "number_format", - abort: false, - format: "int32", - ...util.normalizeParams(params), - }); -} -// @__NO_SIDE_EFFECTS__ -function _uint32(Class, params) { - return new Class({ - type: "number", - check: "number_format", - abort: false, - format: "uint32", - ...util.normalizeParams(params), - }); -} -// @__NO_SIDE_EFFECTS__ -function _boolean(Class, params) { - return new Class({ - type: "boolean", - ...normalizeParams(params), - }); -} -// @__NO_SIDE_EFFECTS__ -function _coercedBoolean(Class, params) { - return new Class({ - type: "boolean", - coerce: true, - ...util.normalizeParams(params), - }); -} -// @__NO_SIDE_EFFECTS__ -function _bigint(Class, params) { - return new Class({ - type: "bigint", - ...util.normalizeParams(params), - }); -} -// @__NO_SIDE_EFFECTS__ -function _coercedBigint(Class, params) { - return new Class({ - type: "bigint", - coerce: true, - ...util.normalizeParams(params), - }); -} -// @__NO_SIDE_EFFECTS__ -function _int64(Class, params) { - return new Class({ - type: "bigint", - check: "bigint_format", - abort: false, - format: "int64", - ...util.normalizeParams(params), - }); -} -// @__NO_SIDE_EFFECTS__ -function _uint64(Class, params) { - return new Class({ - type: "bigint", - check: "bigint_format", - abort: false, - format: "uint64", - ...util.normalizeParams(params), - }); -} -// @__NO_SIDE_EFFECTS__ -function _symbol(Class, params) { - return new Class({ - type: "symbol", - ...util.normalizeParams(params), - }); -} -// @__NO_SIDE_EFFECTS__ -function api_undefined(Class, params) { - return new Class({ - type: "undefined", - ...util.normalizeParams(params), - }); -} -// @__NO_SIDE_EFFECTS__ -function api_null(Class, params) { - return new Class({ - type: "null", - ...normalizeParams(params), - }); -} -// @__NO_SIDE_EFFECTS__ -function _any(Class) { - return new Class({ - type: "any", - }); -} -// @__NO_SIDE_EFFECTS__ -function _unknown(Class) { - return new Class({ - type: "unknown", - }); -} -// @__NO_SIDE_EFFECTS__ -function _never(Class, params) { - return new Class({ - type: "never", - ...normalizeParams(params), - }); -} -// @__NO_SIDE_EFFECTS__ -function _void(Class, params) { - return new Class({ - type: "void", - ...util.normalizeParams(params), - }); -} -// @__NO_SIDE_EFFECTS__ -function _date(Class, params) { - return new Class({ - type: "date", - ...util.normalizeParams(params), - }); -} -// @__NO_SIDE_EFFECTS__ -function _coercedDate(Class, params) { - return new Class({ - type: "date", - coerce: true, - ...util.normalizeParams(params), - }); -} -// @__NO_SIDE_EFFECTS__ -function _nan(Class, params) { - return new Class({ - type: "nan", - ...util.normalizeParams(params), - }); -} -// @__NO_SIDE_EFFECTS__ -function _lt(value, params) { - return new $ZodCheckLessThan({ - check: "less_than", - ...normalizeParams(params), - value, - inclusive: false, - }); -} -// @__NO_SIDE_EFFECTS__ -function _lte(value, params) { - return new $ZodCheckLessThan({ - check: "less_than", - ...normalizeParams(params), - value, - inclusive: true, - }); -} - -// @__NO_SIDE_EFFECTS__ -function _gt(value, params) { - return new $ZodCheckGreaterThan({ - check: "greater_than", - ...normalizeParams(params), - value, - inclusive: false, - }); -} -// @__NO_SIDE_EFFECTS__ -function _gte(value, params) { - return new $ZodCheckGreaterThan({ - check: "greater_than", - ...normalizeParams(params), - value, - inclusive: true, - }); -} - -// @__NO_SIDE_EFFECTS__ -function _positive(params) { - return _gt(0, params); -} -// negative -// @__NO_SIDE_EFFECTS__ -function _negative(params) { - return _lt(0, params); -} -// nonpositive -// @__NO_SIDE_EFFECTS__ -function _nonpositive(params) { - return _lte(0, params); -} -// nonnegative -// @__NO_SIDE_EFFECTS__ -function _nonnegative(params) { - return _gte(0, params); -} -// @__NO_SIDE_EFFECTS__ -function _multipleOf(value, params) { - return new $ZodCheckMultipleOf({ - check: "multiple_of", - ...normalizeParams(params), - value, - }); -} -// @__NO_SIDE_EFFECTS__ -function _maxSize(maximum, params) { - return new checks.$ZodCheckMaxSize({ - check: "max_size", - ...util.normalizeParams(params), - maximum, - }); -} -// @__NO_SIDE_EFFECTS__ -function _minSize(minimum, params) { - return new checks.$ZodCheckMinSize({ - check: "min_size", - ...util.normalizeParams(params), - minimum, - }); -} -// @__NO_SIDE_EFFECTS__ -function _size(size, params) { - return new checks.$ZodCheckSizeEquals({ - check: "size_equals", - ...util.normalizeParams(params), - size, - }); -} -// @__NO_SIDE_EFFECTS__ -function _maxLength(maximum, params) { - const ch = new $ZodCheckMaxLength({ - check: "max_length", - ...normalizeParams(params), - maximum, - }); - return ch; -} -// @__NO_SIDE_EFFECTS__ -function _minLength(minimum, params) { - return new $ZodCheckMinLength({ - check: "min_length", - ...normalizeParams(params), - minimum, - }); -} -// @__NO_SIDE_EFFECTS__ -function _length(length, params) { - return new $ZodCheckLengthEquals({ - check: "length_equals", - ...normalizeParams(params), - length, - }); -} -// @__NO_SIDE_EFFECTS__ -function _regex(pattern, params) { - return new $ZodCheckRegex({ - check: "string_format", - format: "regex", - ...normalizeParams(params), - pattern, - }); -} -// @__NO_SIDE_EFFECTS__ -function _lowercase(params) { - return new $ZodCheckLowerCase({ - check: "string_format", - format: "lowercase", - ...normalizeParams(params), - }); -} -// @__NO_SIDE_EFFECTS__ -function _uppercase(params) { - return new $ZodCheckUpperCase({ - check: "string_format", - format: "uppercase", - ...normalizeParams(params), - }); -} -// @__NO_SIDE_EFFECTS__ -function _includes(includes, params) { - return new $ZodCheckIncludes({ - check: "string_format", - format: "includes", - ...normalizeParams(params), - includes, - }); -} -// @__NO_SIDE_EFFECTS__ -function _startsWith(prefix, params) { - return new $ZodCheckStartsWith({ - check: "string_format", - format: "starts_with", - ...normalizeParams(params), - prefix, - }); -} -// @__NO_SIDE_EFFECTS__ -function _endsWith(suffix, params) { - return new $ZodCheckEndsWith({ - check: "string_format", - format: "ends_with", - ...normalizeParams(params), - suffix, - }); -} -// @__NO_SIDE_EFFECTS__ -function _property(property, schema, params) { - return new checks.$ZodCheckProperty({ - check: "property", - property, - schema, - ...util.normalizeParams(params), - }); -} -// @__NO_SIDE_EFFECTS__ -function _properties(shape) { - return Object.entries(shape).map(([property, schema]) => new checks.$ZodCheckProperty({ check: "property", property, schema })); -} -// @__NO_SIDE_EFFECTS__ -function _mime(types, params) { - return new checks.$ZodCheckMimeType({ - check: "mime_type", - mime: types, - ...util.normalizeParams(params), - }); -} -// @__NO_SIDE_EFFECTS__ -function _overwrite(tx) { - return new $ZodCheckOverwrite({ - check: "overwrite", - tx, - }); -} -// normalize -// @__NO_SIDE_EFFECTS__ -function _normalize(form) { - return _overwrite((input) => input.normalize(form)); -} -// trim -// @__NO_SIDE_EFFECTS__ -function _trim() { - return _overwrite((input) => input.trim()); -} -// toLowerCase -// @__NO_SIDE_EFFECTS__ -function _toLowerCase() { - return _overwrite((input) => input.toLowerCase()); -} -// toUpperCase -// @__NO_SIDE_EFFECTS__ -function _toUpperCase() { - return _overwrite((input) => input.toUpperCase()); -} -// slugify -// @__NO_SIDE_EFFECTS__ -function _slugify() { - return _overwrite((input) => slugify(input)); -} -// @__NO_SIDE_EFFECTS__ -function _array(Class, element, params) { - return new Class({ - type: "array", - element, - // get element() { - // return element; - // }, - ...normalizeParams(params), - }); -} -// @__NO_SIDE_EFFECTS__ -function _union(Class, options, params) { - return new Class({ - type: "union", - options, - ...util.normalizeParams(params), - }); -} -function _xor(Class, options, params) { - return new Class({ - type: "union", - options, - inclusive: false, - ...util.normalizeParams(params), - }); -} -// @__NO_SIDE_EFFECTS__ -function _discriminatedUnion(Class, discriminator, options, params) { - return new Class({ - type: "union", - options: options, - discriminator, - ...util.normalizeParams(params), - }); -} -// @__NO_SIDE_EFFECTS__ -function _intersection(Class, left, right) { - return new Class({ - type: "intersection", - left, - right, - }); -} -// export function _tuple( -// Class: util.SchemaClass, -// items: [], -// params?: string | $ZodTupleParams -// ): schemas.$ZodTuple<[], null>; -// @__NO_SIDE_EFFECTS__ -function _tuple(Class, items, _paramsOrRest, _params) { - const hasRest = _paramsOrRest instanceof schemas.$ZodType; - const params = hasRest ? _params : _paramsOrRest; - const rest = hasRest ? _paramsOrRest : null; - return new Class({ - type: "tuple", - items, - rest, - ...util.normalizeParams(params), - }); -} -// @__NO_SIDE_EFFECTS__ -function _record(Class, keyType, valueType, params) { - return new Class({ - type: "record", - keyType, - valueType, - ...util.normalizeParams(params), - }); -} -// @__NO_SIDE_EFFECTS__ -function _map(Class, keyType, valueType, params) { - return new Class({ - type: "map", - keyType, - valueType, - ...util.normalizeParams(params), - }); -} -// @__NO_SIDE_EFFECTS__ -function _set(Class, valueType, params) { - return new Class({ - type: "set", - valueType, - ...util.normalizeParams(params), - }); -} -// @__NO_SIDE_EFFECTS__ -function _enum(Class, values, params) { - const entries = Array.isArray(values) ? Object.fromEntries(values.map((v) => [v, v])) : values; - // if (Array.isArray(values)) { - // for (const value of values) { - // entries[value] = value; - // } - // } else { - // Object.assign(entries, values); - // } - // const entries: util.EnumLike = {}; - // for (const val of values) { - // entries[val] = val; - // } - return new Class({ - type: "enum", - entries, - ...util.normalizeParams(params), - }); -} -// @__NO_SIDE_EFFECTS__ -/** @deprecated This API has been merged into `z.enum()`. Use `z.enum()` instead. - * - * ```ts - * enum Colors { red, green, blue } - * z.enum(Colors); - * ``` - */ -function _nativeEnum(Class, entries, params) { - return new Class({ - type: "enum", - entries, - ...util.normalizeParams(params), - }); -} -// @__NO_SIDE_EFFECTS__ -function _literal(Class, value, params) { - return new Class({ - type: "literal", - values: Array.isArray(value) ? value : [value], - ...util.normalizeParams(params), - }); -} -// @__NO_SIDE_EFFECTS__ -function _file(Class, params) { - return new Class({ - type: "file", - ...util.normalizeParams(params), - }); -} -// @__NO_SIDE_EFFECTS__ -function _transform(Class, fn) { - return new Class({ - type: "transform", - transform: fn, - }); -} -// @__NO_SIDE_EFFECTS__ -function _optional(Class, innerType) { - return new Class({ - type: "optional", - innerType, - }); -} -// @__NO_SIDE_EFFECTS__ -function _nullable(Class, innerType) { - return new Class({ - type: "nullable", - innerType, - }); -} -// @__NO_SIDE_EFFECTS__ -function _default(Class, innerType, defaultValue) { - return new Class({ - type: "default", - innerType, - get defaultValue() { - return typeof defaultValue === "function" ? defaultValue() : util.shallowClone(defaultValue); - }, - }); -} -// @__NO_SIDE_EFFECTS__ -function _nonoptional(Class, innerType, params) { - return new Class({ - type: "nonoptional", - innerType, - ...util.normalizeParams(params), - }); -} -// @__NO_SIDE_EFFECTS__ -function _success(Class, innerType) { - return new Class({ - type: "success", - innerType, - }); -} -// @__NO_SIDE_EFFECTS__ -function _catch(Class, innerType, catchValue) { - return new Class({ - type: "catch", - innerType, - catchValue: (typeof catchValue === "function" ? catchValue : util.constantCatch(catchValue)), - }); -} -// @__NO_SIDE_EFFECTS__ -function _pipe(Class, in_, out) { - return new Class({ - type: "pipe", - in: in_, - out, - }); -} -// @__NO_SIDE_EFFECTS__ -function _readonly(Class, innerType) { - return new Class({ - type: "readonly", - innerType, - }); -} -// @__NO_SIDE_EFFECTS__ -function _templateLiteral(Class, parts, params) { - return new Class({ - type: "template_literal", - parts, - ...util.normalizeParams(params), - }); -} -// @__NO_SIDE_EFFECTS__ -function _lazy(Class, getter) { - return new Class({ - type: "lazy", - getter, - }); -} -// @__NO_SIDE_EFFECTS__ -function _promise(Class, innerType) { - return new Class({ - type: "promise", - innerType, - }); -} -// @__NO_SIDE_EFFECTS__ -function _custom(Class, fn, _params) { - const norm = util.normalizeParams(_params); - norm.abort ?? (norm.abort = true); // default to abort:false - const schema = new Class({ - type: "custom", - check: "custom", - fn: fn, - ...norm, - }); - return schema; -} -// same as _custom but defaults to abort:false -// @__NO_SIDE_EFFECTS__ -function _refine(Class, fn, _params) { - const schema = new Class({ - type: "custom", - check: "custom", - fn: fn, - ...normalizeParams(_params), - }); - return schema; -} -// @__NO_SIDE_EFFECTS__ -function _superRefine(fn, params) { - const ch = _check((payload) => { - payload.addIssue = (issue) => { - if (typeof issue === "string") { - payload.issues.push(util_issue(issue, payload.value, ch._zod.def)); - } - else { - // for Zod 3 backwards compatibility - const _issue = issue; - if (_issue.fatal) - _issue.continue = false; - _issue.code ?? (_issue.code = "custom"); - if (!("input" in _issue)) - _issue.input = payload.value; - _issue.inst ?? (_issue.inst = ch); - _issue.continue ?? (_issue.continue = !ch._zod.def.abort); // abort is always undefined, so this is always true... - payload.issues.push(util_issue(_issue)); - } - }; - return fn(payload.value, payload); - }, params); - return ch; -} -// @__NO_SIDE_EFFECTS__ -function _check(fn, params) { - const ch = new $ZodCheck({ - check: "custom", - ...normalizeParams(params), - }); - ch._zod.check = fn; - return ch; -} -// @__NO_SIDE_EFFECTS__ -function describe(description) { - const ch = new $ZodCheck({ check: "describe" }); - ch._zod.onattach = [ - (inst) => { - const existing = globalRegistry.get(inst) ?? {}; - globalRegistry.add(inst, { ...existing, description }); - }, - ]; - ch._zod.check = () => { }; // no-op check - return ch; -} -// @__NO_SIDE_EFFECTS__ -function api_meta(metadata) { - const ch = new $ZodCheck({ check: "meta" }); - ch._zod.onattach = [ - (inst) => { - const existing = globalRegistry.get(inst) ?? {}; - globalRegistry.add(inst, { ...existing, ...metadata }); - }, - ]; - ch._zod.check = () => { }; // no-op check - return ch; -} -// @__NO_SIDE_EFFECTS__ -function _stringbool(Classes, _params) { - const params = util.normalizeParams(_params); - let truthyArray = params.truthy ?? ["true", "1", "yes", "on", "y", "enabled"]; - let falsyArray = params.falsy ?? ["false", "0", "no", "off", "n", "disabled"]; - if (params.case !== "sensitive") { - truthyArray = truthyArray.map((v) => (typeof v === "string" ? v.toLowerCase() : v)); - falsyArray = falsyArray.map((v) => (typeof v === "string" ? v.toLowerCase() : v)); - } - const truthySet = new Set(truthyArray); - const falsySet = new Set(falsyArray); - const _Codec = Classes.Codec ?? schemas.$ZodCodec; - const _Boolean = Classes.Boolean ?? schemas.$ZodBoolean; - const _String = Classes.String ?? schemas.$ZodString; - const stringSchema = new _String({ type: "string", error: params.error }); - const booleanSchema = new _Boolean({ type: "boolean", error: params.error }); - const codec = new _Codec({ - type: "pipe", - in: stringSchema, - out: booleanSchema, - transform: ((input, payload) => { - let data = input; - if (params.case !== "sensitive") - data = data.toLowerCase(); - if (truthySet.has(data)) { - return true; - } - else if (falsySet.has(data)) { - return false; - } - else { - payload.issues.push({ - code: "invalid_value", - expected: "stringbool", - values: [...truthySet, ...falsySet], - input: payload.value, - inst: codec, - continue: false, - }); - return {}; - } - }), - reverseTransform: ((input, _payload) => { - if (input === true) { - return truthyArray[0] || "true"; - } - else { - return falsyArray[0] || "false"; - } - }), - error: params.error, - }); - codec._zod.bag.truthy = truthyArray; - codec._zod.bag.falsy = falsyArray; - codec._zod.bag.case = params.case ?? "insensitive"; - return codec; -} -// @__NO_SIDE_EFFECTS__ -function _stringFormat(Class, format, fnOrRegex, _params = {}) { - const params = util.normalizeParams(_params); - const def = { - check: "string_format", - type: "string", - format, - fn: typeof fnOrRegex === "function" ? fnOrRegex : (val) => fnOrRegex.test(val), - ...params, - }; - if (fnOrRegex instanceof RegExp) { - def.pattern = fnOrRegex; - } - const inst = new Class(def); - return inst; -} - - - -function assignProps(target, ...sources) { - for (const source of sources) { - for (const key of Reflect.ownKeys(source)) { - if (Object.prototype.propertyIsEnumerable.call(source, key)) { - assignProp(target, key, source[key]); - } - } - } - return target; -} -// function initializeContext(inputs: JSONSchemaGeneratorParams): ToJSONSchemaContext { -// return { -// processor: inputs.processor, -// metadataRegistry: inputs.metadata ?? globalRegistry, -// target: inputs.target ?? "draft-2020-12", -// unrepresentable: inputs.unrepresentable ?? "throw", -// }; -// } -function initializeContext(params) { - // Normalize target: convert old non-hyphenated versions to hyphenated versions - let target = params?.target ?? "draft-2020-12"; - if (target === "draft-4") - target = "draft-04"; - if (target === "draft-7") - target = "draft-07"; - return { - processors: params.processors ?? {}, - metadataRegistry: params?.metadata ?? globalRegistry, - target, - unrepresentable: params?.unrepresentable ?? "throw", - override: params?.override ?? (() => { }), - io: params?.io ?? "output", - counter: 0, - seen: new Map(), - sharedDefsExtractedFor: undefined, - sharedEmitDoneFor: undefined, - cycles: params?.cycles ?? "ref", - reused: params?.reused ?? "inline", - intersections: [], - deferred: [], - external: params?.external ?? undefined, - }; -} -/** - * Applies the `unrepresentable` setting at a site that has no JSON Schema equivalent. Throws - * `message` unless the setting (or the handler's return value) says otherwise. Returns `true` if a - * custom JSON Schema was written into `json`, in which case the caller must not write its own. - */ -function handleUnrepresentable(schema, ctx, json, params, message) { - const result = typeof ctx.unrepresentable === "function" - ? ctx.unrepresentable({ zodSchema: schema, path: params.path, message }) - : ctx.unrepresentable; - if (result === "any") - return false; - if (result === undefined || result === "throw") - throw new Error(message); - Object.assign(json, result); - return true; -} -function to_json_schema_process(schema, ctx, _params = { path: [], schemaPath: [] }) { - var _a; - const def = schema._zod.def; - // check for schema in seens - const seen = ctx.seen.get(schema); - if (seen) { - seen.count++; - // check if cycle - const isCycle = _params.schemaPath.includes(schema); - if (isCycle) { - seen.cycle = _params.path; - } - return seen.schema; - } - // initialize - const result = { schema: {}, count: 1, cycle: undefined, path: _params.path }; - ctx.seen.set(schema, result); - ctx.sharedDefsExtractedFor = undefined; - ctx.sharedEmitDoneFor = undefined; - // custom method overrides default behavior - const overrideSchema = schema._zod.toJSONSchema?.(); - if (overrideSchema) { - result.schema = overrideSchema; - } - else { - const params = { - ..._params, - schemaPath: [..._params.schemaPath, schema], - path: _params.path, - }; - if (schema._zod.processJSONSchema) { - schema._zod.processJSONSchema(ctx, result.schema, params); - } - else { - const _json = result.schema; - const processor = ctx.processors[def.type]; - if (!processor) { - throw new Error(`[toJSONSchema]: Non-representable type encountered: ${def.type}`); - } - processor(schema, ctx, _json, params); - } - const parent = schema._zod.parent; - if (parent) { - // Also set ref if processor didn't (for inheritance) - if (!result.ref) - result.ref = parent; - to_json_schema_process(parent, ctx, params); - ctx.seen.get(parent).isParent = true; - } - } - // metadata - const meta = ctx.metadataRegistry.get(schema); - if (meta) - assignProps(result.schema, meta); - if (ctx.io === "input" && isTransforming(schema)) { - // examples/defaults only apply to output type of pipe - delete result.schema.examples; - delete result.schema.default; - } - // set prefault as default - if (ctx.io === "input" && "_prefault" in result.schema) - (_a = result.schema).default ?? (_a.default = result.schema._prefault); - delete result.schema._prefault; - // pulling fresh from ctx.seen in case it was overwritten - const _result = ctx.seen.get(schema); - return _result.schema; -} -// Escape a reference token for use in a JSON Pointer fragment (RFC 6901): `~` becomes `~0` and `/` becomes `~1`. The `~` replacement must run first. -function encodeJSONPointerSegment(segment) { - return segment.replace(/~/g, "~0").replace(/\//g, "~1"); -} -function extractDefs(ctx, schema -// params: EmitParams -) { - // iterate over seen map; - const root = ctx.seen.get(schema); - if (!root) - throw new Error("Unprocessed schema. This is a bug in Zod."); - // With `external` set, every registered schema resolves through the external branch of `makeURI`, so the root branch below produces the same ref the external branch would — this pass is identical whichever schema it is called with, and only needs to run once. - if (ctx.external && ctx.sharedDefsExtractedFor === ctx.external) - return; - // Track ids to detect duplicates across different schemas - const idToSchema = new Map(); - for (const entry of ctx.seen.entries()) { - const id = ctx.metadataRegistry.get(entry[0])?.id; - if (id) { - const existing = idToSchema.get(id); - if (existing && existing !== entry[0]) { - throw new Error(`Duplicate schema id "${id}" detected during JSON Schema conversion. Two different schemas cannot share the same id when converted together.`); - } - idToSchema.set(id, entry[0]); - } - } - // returns a ref to the schema defId will be empty if the ref points to an external schema (or #) - const makeURI = (entry) => { - // comparing the seen objects because sometimes multiple schemas map to the same seen object. e.g. lazy - // external is configured - const defsSegment = ctx.target === "draft-2020-12" ? "$defs" : "definitions"; - if (ctx.external) { - const externalId = ctx.external.registry.get(entry[0])?.id; // ?? "__shared";// `__schema${ctx.counter++}`; - // check if schema is in the external registry - const uriGenerator = ctx.external.uri ?? ((id) => id); - if (externalId) { - return { ref: uriGenerator(externalId) }; - } - // otherwise, add to __shared - const id = entry[1].defId ?? entry[1].schema.id ?? `schema${ctx.counter++}`; - entry[1].defId = id; // set defId so it will be reused if needed - return { defId: id, ref: `${uriGenerator("__shared")}#/${defsSegment}/${encodeJSONPointerSegment(id)}` }; - } - const uriPrefix = `#`; - const defUriPrefix = `${uriPrefix}/${defsSegment}/`; - // an id-less root has nowhere to be extracted to, so it stays inline and self-references as `#` - if (entry[1] === root && !entry[1].schema.id) { - return { ref: uriPrefix }; - } - // self-contained schema - const defId = entry[1].schema.id ?? `__schema${ctx.counter++}`; - return { defId, ref: defUriPrefix + encodeJSONPointerSegment(defId) }; - }; - // stored cached version in `def` property remove all properties, set $ref - const extractToDef = (entry) => { - // if the schema is already a reference, do not extract it - if (entry[1].schema.$ref) { - return; - } - const seen = entry[1]; - const { ref, defId } = makeURI(entry); - seen.def = { ...seen.schema }; - // defId won't be set if the schema is a reference to an external schema or if the schema is the root schema - if (defId) - seen.defId = defId; - // wipe away all properties except $ref - const schema = seen.schema; - for (const key in schema) { - delete schema[key]; - } - schema.$ref = ref; - }; - // throw on cycles - // break cycles - if (ctx.cycles === "throw") { - for (const entry of ctx.seen.entries()) { - const seen = entry[1]; - if (seen.cycle) { - throw new Error("Cycle detected: " + - `#/${seen.cycle?.join("/")}/` + - '\n\nSet the `cycles` parameter to `"ref"` to resolve cyclical schemas with defs.'); - } - } - } - // extract schemas into $defs - for (const entry of ctx.seen.entries()) { - const seen = entry[1]; - // convert root schema to # $ref - if (schema === entry[0]) { - extractToDef(entry); // this has special handling for the root schema - continue; - } - // extract schemas that are in the external registry - if (ctx.external) { - const ext = ctx.external.registry.get(entry[0])?.id; - if (schema !== entry[0] && ext) { - extractToDef(entry); - continue; - } - } - // extract schemas with `id` meta - const id = ctx.metadataRegistry.get(entry[0])?.id; - if (id) { - extractToDef(entry); - continue; - } - // break cycles - if (seen.cycle) { - // any - extractToDef(entry); - continue; - } - // extract reused schemas - if (seen.count > 1) { - if (ctx.reused === "ref") { - extractToDef(entry); - // biome-ignore lint: - continue; - } - } - } - if (ctx.external) - ctx.sharedDefsExtractedFor = ctx.external; -} -/** Rewrites `anyOf: [{type: "a"}, {type: "b"}]` to `type: ["a", "b"]`, which every JSON Schema draft treats as equivalent and most consumers render far better for the nullable case. Only branches that are a bare type assertion qualify — anything carrying a constraint, `$ref`, `const` or metadata is left alone. Runs after `flattenRef`, so a branch an override decorated or `$defs` extraction turned into a `$ref` is no longer bare and correctly stays in `anyOf`. `oneOf` is excluded: `integer` and `number` overlap, so "exactly one" and "at least one" are not the same there. OpenAPI 3.0 is excluded: its `type` must be a single string. */ -function compactTypeUnion(schema) { - const options = schema.anyOf; - if (!Array.isArray(options) || options.length === 0 || schema.type !== undefined) - return; - const types = []; - for (const option of options) { - if (!option || typeof option !== "object") - return; - // A branch that is itself a compactible union folds into this one — nested `anyOf` and a flat `type` array say the same thing. Compacting it first also makes the result independent of the order this pass walks the seen map in. - compactTypeUnion(option); - const keys = Object.keys(option); - if (keys.length !== 1 || keys[0] !== "type") - return; - const type = option.type; - for (const member of Array.isArray(type) ? type : [type]) { - if (typeof member !== "string") - return; - if (!types.includes(member)) - types.push(member); - } - } - delete schema.anyOf; - // A `type` array must be non-empty and unique (metaschema); a single member is spelled as a bare string. - schema.type = types.length === 1 ? types[0] : types; -} -/** Keywords `foldIntersection` knows how to combine. Anything else — `$ref`, `patternProperties`, - * an annotation like `description` — makes a member unfoldable, so a constraint this does not - * understand leaves the `allOf` alone instead of being silently dropped or misattributed. */ -const FOLDABLE_KEYS = new Set(["type", "properties", "required", "additionalProperties"]); -const UNION_KEYS = ["oneOf", "anyOf"]; -/** A member's constraint on a key it does not declare itself. A `catchall` states one; `false`, an absent `additionalProperties`, and the empty schema a loose object emits state nothing. */ -function undeclaredConstraint(member) { - const extra = member.additionalProperties; - if (extra === undefined || extra === false || typeof extra !== "object" || extra === null) - return null; - return Object.keys(extra).length ? extra : null; -} -/** Combines object members into the single object they describe together, or returns `null` if any of them carries a keyword outside {@link FOLDABLE_KEYS}. */ -function foldObjects(members) { - const objects = []; - for (const member of members) { - // A boolean subschema is legal JSON Schema and carries no keywords to fold. - if (typeof member !== "object" || member.type !== "object") - return null; - for (const key in member) { - if (!FOLDABLE_KEYS.has(key)) - return null; - } - objects.push(member); - } - const properties = {}; - const required = new Set(); - for (const object of objects) { - for (const key in object.properties) { - // `in` would report a `__proto__` key as already present via the prototype chain and skip it. - if (Object.prototype.hasOwnProperty.call(properties, key)) - continue; - // Every member constrains this key: the ones that declare it say how, and a `catchall` member constrains it too even though it does not name it. The key has to satisfy all of them, which is the same intersection one level down. - const parts = []; - for (const other of objects) { - const part = other.properties?.[key] ?? undeclaredConstraint(other); - if (part === null || part === undefined) - continue; - if (!parts.some((seen) => JSON.stringify(seen) === JSON.stringify(part))) - parts.push(part); - } - const merged = parts.length === 1 - ? parts[0] - : (foldObjects(parts) ?? { allOf: parts }); - assignProp(properties, key, merged); - } - for (const key of object.required ?? []) - required.add(key); - } - const folded = { type: "object", properties }; - if (required.size) - folded.required = [...required]; - // A key no member declares is rejected only when every member rejects it, so the fold is closed only when every member is. Otherwise it carries whatever the `catchall` members demand of such a key. - if (objects.every((object) => object.additionalProperties === false)) { - folded.additionalProperties = false; - } - else { - const constraints = []; - for (const object of objects) { - const constraint = undeclaredConstraint(object); - if (constraint && !constraints.some((seen) => JSON.stringify(seen) === JSON.stringify(constraint))) - constraints.push(constraint); - } - if (constraints.length === 1) - folded.additionalProperties = constraints[0]; - else if (constraints.length > 1) - folded.additionalProperties = { allOf: constraints }; - } - return folded; -} -/** `additionalProperties` in an `allOf` member sees only that member's own `properties`, so two - * closed object members reject each other's keys and the schema validates nothing. Zod's parser - * pools the key sets instead — `handleIntersectionResults` reports a key as unrecognized only when - * *every* side rejects it — so the emitted schema has to pool them too, and folding the members - * into one object is the encoding that says so on every target. - * - * This runs from `finalize`, after `extractDefs`, which is what keeps it clear of the `$ref` - * machinery: a member extracted into `$defs` is already a `$ref` by now and declines to fold, so it - * keeps its reference and its own closedness rather than being inlined as a stale copy. */ -function foldIntersection(json) { - const allOf = json.allOf; - if (!Array.isArray(allOf) || allOf.length < 2) - return; - // An `override` runs before this pass and may have written object keywords onto the intersection itself. Those are deliberate, so decline rather than overwrite them. - for (const key of FOLDABLE_KEYS) - if (key in json) - return; - // An intersection distributes over a union: `A & (X | Y)` is `(A & X) | (A & Y)`. Only the first union is distributed over; a second one stays among the members every branch folds against, where it fails the object check and declines the whole intersection rather than multiplying out. - const unions = allOf.filter((m) => UNION_KEYS.some((k) => Array.isArray(m[k]))); - let folded = null; - if (!unions.length) { - folded = foldObjects(allOf); - } - else { - const union = unions[0]; - const keyword = UNION_KEYS.find((k) => Array.isArray(union[k])); - if (Object.keys(union).length !== 1) - return; - const rest = allOf.filter((m) => m !== union); - const branches = union[keyword].map((branch) => foldObjects([...rest, branch])); - if (branches.some((b) => !b)) - return; - folded = { [keyword]: branches }; - } - if (!folded) - return; - delete json.allOf; - assignProps(json, folded); -} -function finalize(ctx, schema) { - const root = ctx.seen.get(schema); - if (!root) - throw new Error("Unprocessed schema. This is a bug in Zod."); - // flatten refs - inherit properties from parent schemas - const flattenRef = (zodSchema) => { - const seen = ctx.seen.get(zodSchema); - // already processed - if (seen.ref === null) - return; - const schema = seen.def ?? seen.schema; - const _cached = { ...schema }; - const ref = seen.ref; - seen.ref = null; // prevent infinite recursion - if (ref) { - flattenRef(ref); - const refSeen = ctx.seen.get(ref); - const refSchema = refSeen.schema; - // merge referenced schema into current - if (refSchema.$ref && (ctx.target === "draft-07" || ctx.target === "draft-04" || ctx.target === "openapi-3.0")) { - // older drafts can't combine $ref with other properties - schema.allOf = schema.allOf ?? []; - schema.allOf.push(refSchema); - } - else { - assignProps(schema, refSchema); - } - // restore child's own properties (child wins) - assignProps(schema, _cached); - const isParentRef = zodSchema._zod.parent === ref; - // For parent chain, child is a refinement - remove parent-only properties - if (isParentRef) { - for (const key in schema) { - if (key === "$ref" || key === "allOf") - continue; - if (!(key in _cached)) { - delete schema[key]; - } - } - } - // When ref was extracted to $defs, remove properties that match the definition - if (refSchema.$ref && refSeen.def) { - for (const key in schema) { - if (key === "$ref" || key === "allOf") - continue; - if (key in refSeen.def && JSON.stringify(schema[key]) === JSON.stringify(refSeen.def[key])) { - delete schema[key]; - } - } - } - } - // If parent was extracted (has $ref), propagate $ref to this schema. This handles cases like: readonly().meta({id}).describe() where processor sets ref to innerType but parent should be referenced - const parent = zodSchema._zod.parent; - if (parent && parent !== ref) { - // Ensure parent is processed first so its def has inherited properties - flattenRef(parent); - const parentSeen = ctx.seen.get(parent); - if (parentSeen?.schema.$ref) { - schema.$ref = parentSeen.schema.$ref; - // De-duplicate with parent's definition - if (parentSeen.def) { - for (const key in schema) { - if (key === "$ref" || key === "allOf") - continue; - if (key in parentSeen.def && JSON.stringify(schema[key]) === JSON.stringify(parentSeen.def[key])) { - delete schema[key]; - } - } - } - } - } - // execute overrides - ctx.override({ - zodSchema: zodSchema, - jsonSchema: schema, - path: seen.path ?? [], - }); - }; - // Flattening walks the whole map and clears each `ref` as it goes, so a second call over the same map is a no-op scan. Skip it outright once it has run for a registry conversion. - if (!ctx.external || ctx.sharedEmitDoneFor !== ctx.external) { - for (const entry of [...ctx.seen.entries()].reverse()) { - flattenRef(entry[0]); - } - if (ctx.target !== "openapi-3.0") { - for (const entry of ctx.seen.entries()) { - compactTypeUnion(entry[1].def ?? entry[1].schema); - } - } - for (const rewrite of ctx.deferred) - rewrite(); - // After flattening, every member that was extracted is a `$ref`, so the fold sees the final shape. A schema that inherits an intersection — through `z.lazy`, or any `ref` chain — holds the same `allOf` array, so fold by array identity to catch every copy. - if (ctx.intersections.length) { - const carriers = new Map(); - for (const seen of ctx.seen.values()) { - for (const json of [seen.schema, seen.def]) { - const allOf = json?.allOf; - if (!Array.isArray(allOf)) - continue; - const existing = carriers.get(allOf); - if (existing) - existing.push(json); - else - carriers.set(allOf, [json]); - } - } - for (const allOf of ctx.intersections) { - for (const json of carriers.get(allOf) ?? []) - foldIntersection(json); - } - } - } - const result = {}; - if (ctx.target === "draft-2020-12") { - result.$schema = "https://json-schema.org/draft/2020-12/schema"; - } - else if (ctx.target === "draft-07") { - result.$schema = "http://json-schema.org/draft-07/schema#"; - } - else if (ctx.target === "draft-04") { - result.$schema = "http://json-schema.org/draft-04/schema#"; - } - else if (ctx.target === "openapi-3.0") { - // OpenAPI 3.0 schema objects should not include a $schema property - } - else { - // Arbitrary string values are allowed but won't have a $schema property set - } - if (ctx.external?.uri) { - const id = ctx.external.registry.get(schema)?.id; - if (!id) - throw new Error("Schema is missing an `id` property"); - result.$id = ctx.external.uri(id); - } - // when the root was extracted into $defs, `root.schema` is the `$ref` wrapper and `root.def` is the body that now lives under $defs - assignProps(result, root.defId ? root.schema : (root.def ?? root.schema)); - // The `id` in `.meta()` is a Zod-specific registration tag used to extract schemas into $defs — it is not user-facing JSON Schema metadata. Strip it from the output body where it would otherwise leak. The id is preserved implicitly via the $defs key (and via $ref paths). - const rootMetaId = ctx.metadataRegistry.get(schema)?.id; - if (rootMetaId !== undefined && result.id === rootMetaId) - delete result.id; - // build defs object. With `external`, `defs` is the shared object every schema writes into, so the same entries are reassigned on every call. Without it, `defs` is fresh per call and must be rebuilt. - const defs = ctx.external?.defs ?? {}; - if (!ctx.external || ctx.sharedEmitDoneFor !== ctx.external) { - for (const entry of ctx.seen.entries()) { - const seen = entry[1]; - if (seen.def && seen.defId) { - if (seen.def.id === seen.defId) - delete seen.def.id; - assignProp(defs, seen.defId, seen.def); - } - } - } - if (ctx.external) - ctx.sharedEmitDoneFor = ctx.external; - // set definitions in result - if (ctx.external) { - } - else { - if (Object.keys(defs).length > 0) { - if (ctx.target === "draft-2020-12") { - result.$defs = defs; - } - else { - result.definitions = defs; - } - } - } - try { - // this "finalizes" this schema and ensures all cycles are removed each call to finalize() is functionally independent though the seen map is shared - const finalized = JSON.parse(JSON.stringify(result)); - Object.defineProperty(finalized, "~standard", { - value: { - ...schema["~standard"], - jsonSchema: { - input: createStandardJSONSchemaMethod(schema, "input", ctx.processors), - output: createStandardJSONSchemaMethod(schema, "output", ctx.processors), - }, - }, - enumerable: false, - writable: false, - }); - return finalized; - } - catch (_err) { - throw new Error("Error converting schema to JSON."); - } -} -function isTransforming(_schema, _ctx) { - const ctx = _ctx ?? { seen: new Set() }; - if (ctx.seen.has(_schema)) - return false; - ctx.seen.add(_schema); - const def = _schema._zod.def; - if (def.type === "transform") - return true; - if (def.type === "array") - return isTransforming(def.element, ctx); - if (def.type === "set") - return isTransforming(def.valueType, ctx); - if (def.type === "lazy") - return isTransforming(def.getter(), ctx); - if (def.type === "promise" || - def.type === "optional" || - def.type === "nonoptional" || - def.type === "nullable" || - def.type === "readonly" || - def.type === "default" || - def.type === "prefault" || - def.type === "catch") { - return isTransforming(def.innerType, ctx); - } - if (def.type === "intersection") { - return isTransforming(def.left, ctx) || isTransforming(def.right, ctx); - } - if (def.type === "record" || def.type === "map") { - return isTransforming(def.keyType, ctx) || isTransforming(def.valueType, ctx); - } - if (def.type === "pipe") { - if (_schema._zod.traits.has("$ZodCodec")) - return true; - return isTransforming(def.in, ctx) || isTransforming(def.out, ctx); - } - if (def.type === "object") { - for (const key in def.shape) { - if (isTransforming(def.shape[key], ctx)) - return true; - } - return false; - } - if (def.type === "union") { - for (const option of def.options) { - if (isTransforming(option, ctx)) - return true; - } - return false; - } - if (def.type === "tuple") { - for (const item of def.items) { - if (isTransforming(item, ctx)) - return true; - } - if (def.rest && isTransforming(def.rest, ctx)) - return true; - return false; - } - return false; -} -/** - * Creates a toJSONSchema method for a schema instance. - * This encapsulates the logic of initializing context, processing, extracting defs, and finalizing. - */ -const createToJSONSchemaMethod = (schema, processors = {}) => (params) => { - const ctx = initializeContext({ ...params, processors }); - to_json_schema_process(schema, ctx); - extractDefs(ctx, schema); - return finalize(ctx, schema); -}; -const createStandardJSONSchemaMethod = (schema, io, processors = {}) => (params) => { - const { libraryOptions, target } = params ?? {}; - const ctx = initializeContext({ ...(libraryOptions ?? {}), target, io, processors }); - to_json_schema_process(schema, ctx); - extractDefs(ctx, schema); - return finalize(ctx, schema); -}; - - - - -const formatMap = { - guid: "uuid", - url: "uri", - datetime: "date-time", - json_string: "json-string", - regex: "", // do not set -}; -// ==================== SIMPLE TYPE PROCESSORS ==================== -const stringProcessor = (schema, ctx, _json, _params) => { - const json = _json; - json.type = "string"; - const { minimum, maximum, format, patterns, contentEncoding, laxFormat } = schema._zod - .bag; - if (typeof minimum === "number") - json.minLength = minimum; - if (typeof maximum === "number") - json.maxLength = maximum; - // custom pattern overrides format - if (format) { - json.format = formatMap[format] ?? format; - if (json.format === "") - delete json.format; // empty format is not valid - // `z.iso.time()` is never full-time, and `laxFormat` carries the datetime shapes that also accept what their keyword forbids - if (format === "time" || laxFormat) { - delete json.format; - } - } - if (contentEncoding) - json.contentEncoding = contentEncoding; - if (patterns && patterns.size > 0) { - const patternList = [...patterns]; - if (patternList.length === 1) - json.pattern = patternList[0].source; - else if (patternList.length > 1) { - json.allOf = [ - ...patternList.map((regex) => ({ - ...(ctx.target === "draft-07" || ctx.target === "draft-04" || ctx.target === "openapi-3.0" - ? { type: "string" } - : {}), - pattern: regex.source, - })), - ]; - } - } -}; -const numberProcessor = (schema, ctx, _json, params) => { - const json = _json; - const { minimum, maximum, format, multipleOf, exclusiveMaximum, exclusiveMinimum } = schema._zod.bag; - if (typeof format === "string" && format.includes("int")) - json.type = "integer"; - else - json.type = "number"; - // when both minimum and exclusiveMinimum exist, pick the more restrictive one - const exMin = typeof exclusiveMinimum === "number" && exclusiveMinimum >= (minimum ?? Number.NEGATIVE_INFINITY); - const exMax = typeof exclusiveMaximum === "number" && exclusiveMaximum <= (maximum ?? Number.POSITIVE_INFINITY); - const legacy = ctx.target === "draft-04" || ctx.target === "openapi-3.0"; - if (exMin) { - if (legacy) { - json.minimum = exclusiveMinimum; - json.exclusiveMinimum = true; - } - else { - json.exclusiveMinimum = exclusiveMinimum; - } - } - else if (typeof minimum === "number") { - json.minimum = minimum; - } - if (exMax) { - if (legacy) { - json.maximum = exclusiveMaximum; - json.exclusiveMaximum = true; - } - else { - json.exclusiveMaximum = exclusiveMaximum; - } - } - else if (typeof maximum === "number") { - json.maximum = maximum; - } - if (typeof multipleOf === "number") { - // JSON Schema requires a divisor strictly greater than zero, and a non-finite one does not survive JSON at all. A negative divisor accepts exactly what its absolute value accepts, so it still maps; zero, NaN and Infinity have no keyword form. - if (Number.isFinite(multipleOf) && multipleOf !== 0) - json.multipleOf = Math.abs(multipleOf); - else - handleUnrepresentable(schema, ctx, json, params, `A multipleOf divisor of ${multipleOf} cannot be represented in JSON Schema`); - } -}; -const booleanProcessor = (_schema, _ctx, json, _params) => { - json.type = "boolean"; -}; -const bigintProcessor = (schema, ctx, json, params) => { - handleUnrepresentable(schema, ctx, json, params, "BigInt cannot be represented in JSON Schema"); -}; -const symbolProcessor = (schema, ctx, json, params) => { - handleUnrepresentable(schema, ctx, json, params, "Symbols cannot be represented in JSON Schema"); -}; -const nullProcessor = (_schema, ctx, json, _params) => { - if (ctx.target === "openapi-3.0") { - json.type = "string"; - json.nullable = true; - json.enum = [null]; - } - else { - json.type = "null"; - } -}; -const undefinedProcessor = (schema, ctx, json, params) => { - handleUnrepresentable(schema, ctx, json, params, "Undefined cannot be represented in JSON Schema"); -}; -const voidProcessor = (schema, ctx, json, params) => { - handleUnrepresentable(schema, ctx, json, params, "Void cannot be represented in JSON Schema"); -}; -const neverProcessor = (_schema, _ctx, json, _params) => { - json.not = {}; -}; -const anyProcessor = (_schema, _ctx, _json, _params) => { - // empty schema accepts anything -}; -const unknownProcessor = (_schema, _ctx, _json, _params) => { - // empty schema accepts anything -}; -const dateProcessor = (schema, ctx, json, params) => { - handleUnrepresentable(schema, ctx, json, params, "Date cannot be represented in JSON Schema"); -}; -const enumProcessor = (schema, _ctx, json, _params) => { - const def = schema._zod.def; - const values = getEnumValues(def.entries); - // an empty enum accepts nothing, same as z.never() - if (values.length === 0) { - json.not = {}; - return; - } - // Number enums can have both string and number values - if (values.every((v) => typeof v === "number")) - json.type = "number"; - if (values.every((v) => typeof v === "string")) - json.type = "string"; - json.enum = values; -}; -const literalProcessor = (schema, ctx, json, params) => { - const def = schema._zod.def; - // a literal with no values accepts nothing, same as z.never() - if (def.values.length === 0) { - json.not = {}; - return; - } - const vals = []; - for (const val of def.values) { - if (val === undefined) { - // a custom schema replaces the whole literal, so there is nothing left to accumulate - if (handleUnrepresentable(schema, ctx, json, params, "Literal `undefined` cannot be represented in JSON Schema")) - return; - // otherwise do not add to vals - } - else if (typeof val === "bigint") { - if (handleUnrepresentable(schema, ctx, json, params, "BigInt literals cannot be represented in JSON Schema")) - return; - vals.push(Number(val)); - } - else { - vals.push(val); - } - } - if (vals.length === 0) { - // do nothing (an undefined literal was stripped) - } - else if (vals.length === 1) { - const val = vals[0]; - json.type = val === null ? "null" : typeof val; - if (ctx.target === "draft-04" || ctx.target === "openapi-3.0") { - json.enum = [val]; - } - else { - json.const = val; - } - } - else { - if (vals.every((v) => typeof v === "number")) - json.type = "number"; - if (vals.every((v) => typeof v === "string")) - json.type = "string"; - if (vals.every((v) => typeof v === "boolean")) - json.type = "boolean"; - if (vals.every((v) => v === null)) - json.type = "null"; - json.enum = vals; - } -}; -const nanProcessor = (schema, ctx, json, params) => { - handleUnrepresentable(schema, ctx, json, params, "NaN cannot be represented in JSON Schema"); -}; -const templateLiteralProcessor = (schema, _ctx, json, _params) => { - const _json = json; - const pattern = schema._zod.pattern; - if (!pattern) - throw new Error("Pattern not found in template literal"); - _json.type = "string"; - _json.pattern = pattern.source; -}; -const fileProcessor = (schema, _ctx, json, _params) => { - const _json = json; - const file = { - type: "string", - format: "binary", - contentEncoding: "binary", - }; - const { minimum, maximum, mime } = schema._zod.bag; - if (minimum !== undefined) - file.minLength = minimum; - if (maximum !== undefined) - file.maxLength = maximum; - if (mime) { - if (mime.length === 1) { - file.contentMediaType = mime[0]; - Object.assign(_json, file); - } - else { - Object.assign(_json, file); // shared props at root - _json.anyOf = mime.map((m) => ({ contentMediaType: m })); // only contentMediaType differs - } - } - else { - Object.assign(_json, file); - } -}; -const successProcessor = (_schema, _ctx, json, _params) => { - json.type = "boolean"; -}; -const customProcessor = (schema, ctx, json, params) => { - handleUnrepresentable(schema, ctx, json, params, "Custom types cannot be represented in JSON Schema"); -}; -const functionProcessor = (schema, ctx, json, params) => { - handleUnrepresentable(schema, ctx, json, params, "Function types cannot be represented in JSON Schema"); -}; -const transformProcessor = (schema, ctx, json, params) => { - handleUnrepresentable(schema, ctx, json, params, "Transforms cannot be represented in JSON Schema"); -}; -const mapProcessor = (schema, ctx, json, params) => { - handleUnrepresentable(schema, ctx, json, params, "Map cannot be represented in JSON Schema"); -}; -const setProcessor = (schema, ctx, json, params) => { - handleUnrepresentable(schema, ctx, json, params, "Set cannot be represented in JSON Schema"); -}; -// ==================== COMPOSITE TYPE PROCESSORS ==================== -const arrayProcessor = (schema, ctx, _json, params) => { - const json = _json; - const def = schema._zod.def; - const { minimum, maximum } = schema._zod.bag; - if (typeof minimum === "number") - json.minItems = minimum; - if (typeof maximum === "number") - json.maxItems = maximum; - json.type = "array"; - json.items = to_json_schema_process(def.element, ctx, { - ...params, - path: [...params.path, "items"], - }); -}; -// Transform and catch set `optin = "optional"` at runtime so the parser lets them observe an -// absent key, but their declared input type stays required. An input JSON Schema describes the -// declared type, so resolve past them to the schema that actually carries the optionality. -// Used by both `objectProcessor` (for `required`) and `tupleProcessor` (for `minItems`); see -// wiki/optionality.md, "The JSON Schema emitter reads the *static* value". -function inputOptin(schema) { - const def = schema._zod.def; - if (def.type === "pipe" && def.in._zod.traits.has("$ZodTransform")) { - return inputOptin(def.out); - } - if (def.type === "catch") { - return inputOptin(def.innerType); - } - return schema._zod.optin; -} -const objectProcessor = (schema, ctx, _json, params) => { - const json = _json; - const def = schema._zod.def; - const shape = def.shape; - // dropping it while still emitting `additionalProperties: false` would emit a schema that rejects data this one requires - const symbolKeys = Object.getOwnPropertySymbols(shape); - if (symbolKeys.length && - handleUnrepresentable(schema, ctx, json, params, "Symbol keys cannot be represented in JSON Schema")) { - return; - } - json.type = "object"; - json.properties = {}; - for (const key in shape) { - // assignProp so a __proto__ key becomes an own property instead of hitting the inherited setter on the plain {} we build into - assignProp(json.properties, key, to_json_schema_process(shape[key], ctx, { - ...params, - path: [...params.path, "properties", key], - })); - } - // required keys - const allKeys = new Set(Object.keys(shape)); - const requiredKeys = new Set([...allKeys].filter((key) => { - const field = def.shape[key]; - if (ctx.io === "input") { - return inputOptin(field) === undefined; - } - else { - return field._zod.optout === undefined; - } - })); - if (requiredKeys.size > 0) { - json.required = Array.from(requiredKeys); - } - // catchall - if (def.catchall?._zod.def.type === "never") { - // strict - json.additionalProperties = false; - } - else if (!def.catchall) { - // regular - if (ctx.io === "output") - json.additionalProperties = false; - } - else if (def.catchall) { - json.additionalProperties = to_json_schema_process(def.catchall, ctx, { - ...params, - path: [...params.path, "additionalProperties"], - }); - } -}; -const unionProcessor = (schema, ctx, json, params) => { - const def = schema._zod.def; - // Exclusive unions (inclusive === false) use oneOf (exactly one match) instead of anyOf (one or more matches). This includes both z.xor() and discriminated unions - const isExclusive = def.inclusive === false; - const options = def.options.map((x, i) => to_json_schema_process(x, ctx, { - ...params, - path: [...params.path, isExclusive ? "oneOf" : "anyOf", i], - })); - if (isExclusive) { - json.oneOf = options; - } - else { - json.anyOf = options; - } -}; -const intersectionProcessor = (schema, ctx, json, params) => { - const def = schema._zod.def; - const a = to_json_schema_process(def.left, ctx, { - ...params, - path: [...params.path, "allOf", 0], - }); - const b = to_json_schema_process(def.right, ctx, { - ...params, - path: [...params.path, "allOf", 1], - }); - const isSimpleIntersection = (val) => "allOf" in val && Object.keys(val).length === 1; - const allOf = [ - ...(isSimpleIntersection(a) ? a.allOf : [a]), - ...(isSimpleIntersection(b) ? b.allOf : [b]), - ]; - json.allOf = allOf; - // Recorded innermost first, so a nested intersection has already folded by the time this one is considered. The array is the handle rather than the schema, because a wrapper that inherits this schema shares the same array; `finalize` folds every object holding it. See `foldIntersection`. - ctx.intersections.push(allOf); -}; -const tupleProcessor = (schema, ctx, _json, params) => { - const json = _json; - const def = schema._zod.def; - json.type = "array"; - const prefixPath = ctx.target === "draft-2020-12" ? "prefixItems" : "items"; - const restPath = ctx.target === "draft-2020-12" ? "items" : ctx.target === "openapi-3.0" ? "items" : "additionalItems"; - const prefixItems = def.items.map((x, i) => to_json_schema_process(x, ctx, { - ...params, - path: [...params.path, prefixPath, i], - })); - const rest = def.rest - ? to_json_schema_process(def.rest, ctx, { - ...params, - path: [...params.path, restPath, ...(ctx.target === "openapi-3.0" ? [def.items.length] : [])], - }) - : null; - let minItems = def.items.length; - while (minItems > 0) { - const item = def.items[minItems - 1]; - const optional = ctx.io === "input" ? inputOptin(item) !== undefined : item._zod.optout === "optional"; - if (!optional) - break; - minItems--; - } - const maxItems = def.items.length; - const isClosed = !def.rest; - if (ctx.target === "draft-2020-12") { - json.prefixItems = prefixItems; - if (isClosed) { - json.items = false; - } - else if (rest) { - json.items = rest; - } - if (minItems > 0) - json.minItems = minItems; - if (isClosed) - json.maxItems = maxItems; - } - else if (ctx.target === "openapi-3.0") { - json.items = { - anyOf: prefixItems, - }; - if (rest) { - json.items.anyOf.push(rest); - } - if (minItems > 0) - json.minItems = minItems; - if (isClosed) - json.maxItems = maxItems; - } - else { - json.items = prefixItems; - if (isClosed) { - json.additionalItems = false; - } - else if (rest) { - json.additionalItems = rest; - } - if (minItems > 0) - json.minItems = minItems; - if (isClosed) - json.maxItems = maxItems; - } - // explicit user-defined length checks take precedence - const { minimum, maximum } = schema._zod.bag; - if (typeof minimum === "number") - json.minItems = minimum; - if (typeof maximum === "number") - json.maxItems = maximum; -}; -/** JSON object keys are always strings, so a numeric record key schema is re-expressed over the - * numeric-string form the record parser matches. Deferred to `finalize`, after the flatten: a key - * behind a wrapper only carries its own `type` before then, and a union key only has its branches. - * - * A numeric bound cannot apply to a property name, so `minimum` and its siblings are dropped rather - * than carried over: keeping them beside `type: "string"` reproduces the match-nothing schema this - * exists to fix. A key that carries one therefore emits wider than the record parses — `z.record(z.number().min(5), V)` - * accepts `"3"` — which is the deliberate trade, since throwing on it would reject an ordinary schema - * outright. */ -function stringifyKeyNames(bySchema, json, visited) { - // an extracted key that rewrites cannot go on sharing its definition — the string form a key position needs is not the number form every other reference wants — so it inlines. One that does not rewrite keeps the `$ref`. - if (json.$ref) { - // a recursive key holds its own reference inside its definition, so a node already on the path is left alone rather than resolved again - if (visited.has(json)) - return json; - visited.add(json); - const def = bySchema.get(json)?.def; - if (!def) - return json; - const inlined = stringifyKeyNames(bySchema, def, visited); - return inlined === def ? json : inlined; - } - for (const keyword of ["anyOf", "oneOf"]) { - const branches = json[keyword]; - if (!Array.isArray(branches)) - continue; - const mapped = branches.map((branch) => stringifyKeyNames(bySchema, branch, visited)); - // rebuilding regardless would detach a key that had nothing to re-express, dropping its `$ref` and leaking the internal `id` - if (mapped.some((branch, i) => branch !== branches[i])) - json = { ...json, [keyword]: mapped }; - } - // a member that already admits a string leaves the key unconstrained, so the node's own type re-expresses only when every member is numeric - const types = Array.isArray(json.type) ? json.type : [json.type]; - const numericType = !types.includes("string") && types.some((t) => t === "number" || t === "integer"); - // a heterogeneous key carries no type at all, so its numeric members are caught here instead - const values = json.enum ?? (json.const !== undefined ? [json.const] : undefined); - if (!numericType && !values?.some((v) => typeof v === "number")) - return json; - const { minimum, maximum, exclusiveMinimum, exclusiveMaximum, multipleOf, format, id, ...rest } = json; - if (rest.enum) - rest.enum = rest.enum.map((v) => (typeof v === "number" ? String(v) : v)); - else if (typeof rest.const === "number") - rest.const = String(rest.const); - // a heterogeneous key keeps its absent type: the stringified members already say what a key may be - if (!numericType) - return rest; - rest.type = "string"; - if (!values) - rest.pattern = (types.includes("number") ? number : integer).source; - return rest; -} -/** Every record of one conversion, so the carriers are found in a single pass rather than once per record. */ -const pendingRecords = new WeakMap(); -function rewriteKeyNames(ctx) { - // an extracted key is resolved by the object `extractToDef` left in its place, so the map is built once rather than searched per reference. `_zod.toJSONSchema` can hand the same object to two schemas, so the first entry carrying a body wins, as a search would have found it. - const bySchema = new Map(); - for (const entry of ctx.seen.values()) { - if (entry.def && !bySchema.has(entry.schema)) - bySchema.set(entry.schema, entry); - } - const rewrites = new Map(); - for (const record of pendingRecords.get(ctx) ?? []) { - const seen = ctx.seen.get(record); - const names = (seen?.def ?? seen?.schema)?.propertyNames; - if (!names || names === true || rewrites.has(names)) - continue; - const rewritten = stringifyKeyNames(bySchema, names, new Set()); - if (rewritten !== names) - rewrites.set(names, rewritten); - } - if (!rewrites.size) - return; - // the flatten has already copied each record's own properties onto every wrapper by reference, and an extracted body is another such copy, so every carrier holding a rewritten key is updated together - for (const entry of ctx.seen.values()) { - for (const carrier of [entry.schema, entry.def]) { - const rewritten = carrier && rewrites.get(carrier.propertyNames); - if (rewritten) - carrier.propertyNames = rewritten; - } - } -} -const recordProcessor = (schema, ctx, _json, params) => { - const json = _json; - const def = schema._zod.def; - json.type = "object"; - // For looseRecord with regex patterns, use patternProperties. This correctly represents "only validate keys matching the pattern" semantics and composes well with allOf (intersections) - const keyType = def.keyType; - const keyBag = keyType._zod.bag; - const patterns = keyBag?.patterns; - if (def.mode === "loose" && patterns && patterns.size > 0) { - // Use patternProperties for looseRecord with regex patterns - const valueSchema = to_json_schema_process(def.valueType, ctx, { - ...params, - path: [...params.path, "patternProperties", "*"], - }); - json.patternProperties = {}; - for (const pattern of patterns) { - assignProp(json.patternProperties, pattern.source, valueSchema); - } - } - else { - // Default behavior: use propertyNames + additionalProperties - if (ctx.target === "draft-07" || ctx.target === "draft-2020-12") { - json.propertyNames = to_json_schema_process(def.keyType, ctx, { - ...params, - path: [...params.path, "propertyNames"], - }); - let pending = pendingRecords.get(ctx); - if (!pending) { - pending = []; - pendingRecords.set(ctx, pending); - ctx.deferred.push(() => rewriteKeyNames(ctx)); - } - pending.push(schema); - } - json.additionalProperties = to_json_schema_process(def.valueType, ctx, { - ...params, - path: [...params.path, "additionalProperties"], - }); - } - // Add required for keys with discrete values (enum, literal, etc.) - const keyValues = keyType._zod.values; - // Every key shares one value schema, so an optional-in value makes the whole key set omittable on input. Output keeps them: the exhaustive branch assigns every key, even one whose value came back undefined. - const omittableOnInput = ctx.io === "input" && inputOptin(def.valueType) !== undefined; - if (keyValues && !def.partial && !omittableOnInput) { - const validKeyValues = [...keyValues].filter((v) => typeof v === "string" || typeof v === "number"); - if (validKeyValues.length > 0) { - json.required = validKeyValues.map(String); - } - } -}; -const nullableProcessor = (schema, ctx, json, params) => { - const def = schema._zod.def; - const inner = to_json_schema_process(def.innerType, ctx, params); - const seen = ctx.seen.get(schema); - if (ctx.target === "openapi-3.0") { - seen.ref = def.innerType; - json.nullable = true; - } - else { - json.anyOf = [inner, { type: "null" }]; - } -}; -const nonoptionalProcessor = (schema, ctx, _json, params) => { - const def = schema._zod.def; - to_json_schema_process(def.innerType, ctx, params); - const seen = ctx.seen.get(schema); - seen.ref = def.innerType; -}; -/** Round-trips a default value through JSON so the emitted schema is guaranteed to be valid JSON. - * A BigInt has no reliable encoding, so it goes through `unrepresentable` like any other - * unrepresentable value. Returns a sentinel when the caller must not write a default of its own. */ -const UNREPRESENTABLE_DEFAULT = Symbol(); -function serializeDefaultValue(value, schema, ctx, json, params) { - let unrepresentable = false; - const serialized = JSON.stringify(value, (_, val) => { - if (typeof val !== "bigint") - return val; - unrepresentable = true; - return null; - }); - if (!unrepresentable) - return JSON.parse(serialized); - handleUnrepresentable(schema, ctx, json, params, "BigInt defaults cannot be represented in JSON Schema"); - return UNREPRESENTABLE_DEFAULT; -} -const defaultProcessor = (schema, ctx, json, params) => { - const def = schema._zod.def; - to_json_schema_process(def.innerType, ctx, params); - const seen = ctx.seen.get(schema); - seen.ref = def.innerType; - const value = serializeDefaultValue(def.defaultValue, schema, ctx, json, params); - if (value !== UNREPRESENTABLE_DEFAULT) - json.default = value; -}; -const prefaultProcessor = (schema, ctx, json, params) => { - const def = schema._zod.def; - to_json_schema_process(def.innerType, ctx, params); - const seen = ctx.seen.get(schema); - seen.ref = def.innerType; - if (ctx.io !== "input") - return; - const value = serializeDefaultValue(def.defaultValue, schema, ctx, json, params); - if (value !== UNREPRESENTABLE_DEFAULT) - json._prefault = value; -}; -const catchProcessor = (schema, ctx, json, params) => { - const def = schema._zod.def; - to_json_schema_process(def.innerType, ctx, params); - const seen = ctx.seen.get(schema); - seen.ref = def.innerType; - let catchValue; - try { - catchValue = def.catchValue(undefined); - } - catch { - handleUnrepresentable(schema, ctx, json, params, "Dynamic catch values are not supported in JSON Schema"); - return; - } - json.default = catchValue; -}; -const pipeProcessor = (schema, ctx, _json, params) => { - const def = schema._zod.def; - const inIsTransform = def.in._zod.traits.has("$ZodTransform"); - const innerType = ctx.io === "input" ? (inIsTransform ? def.out : def.in) : def.out; - to_json_schema_process(innerType, ctx, params); - const seen = ctx.seen.get(schema); - seen.ref = innerType; -}; -const readonlyProcessor = (schema, ctx, json, params) => { - const def = schema._zod.def; - to_json_schema_process(def.innerType, ctx, params); - const seen = ctx.seen.get(schema); - seen.ref = def.innerType; - json.readOnly = true; -}; -const promiseProcessor = (schema, ctx, _json, params) => { - const def = schema._zod.def; - to_json_schema_process(def.innerType, ctx, params); - const seen = ctx.seen.get(schema); - seen.ref = def.innerType; -}; -const optionalProcessor = (schema, ctx, _json, params) => { - const def = schema._zod.def; - to_json_schema_process(def.innerType, ctx, params); - const seen = ctx.seen.get(schema); - seen.ref = def.innerType; -}; -const lazyProcessor = (schema, ctx, _json, params) => { - const innerType = schema._zod.innerType; - to_json_schema_process(innerType, ctx, params); - const seen = ctx.seen.get(schema); - seen.ref = innerType; -}; -// ==================== ALL PROCESSORS ==================== -const allProcessors = { - string: stringProcessor, - number: numberProcessor, - boolean: booleanProcessor, - bigint: bigintProcessor, - symbol: symbolProcessor, - null: nullProcessor, - undefined: undefinedProcessor, - void: voidProcessor, - never: neverProcessor, - any: anyProcessor, - unknown: unknownProcessor, - date: dateProcessor, - enum: enumProcessor, - literal: literalProcessor, - nan: nanProcessor, - template_literal: templateLiteralProcessor, - file: fileProcessor, - success: successProcessor, - custom: customProcessor, - function: functionProcessor, - transform: transformProcessor, - map: mapProcessor, - set: setProcessor, - array: arrayProcessor, - object: objectProcessor, - union: unionProcessor, - intersection: intersectionProcessor, - tuple: tupleProcessor, - record: recordProcessor, - nullable: nullableProcessor, - nonoptional: nonoptionalProcessor, - default: defaultProcessor, - prefault: prefaultProcessor, - catch: catchProcessor, - pipe: pipeProcessor, - readonly: readonlyProcessor, - promise: promiseProcessor, - optional: optionalProcessor, - lazy: lazyProcessor, -}; -function toJSONSchema(input, params) { - if ("_idmap" in input) { - // Registry case - const registry = input; - const ctx = initializeContext({ ...params, processors: allProcessors }); - const defs = {}; - // First pass: process all schemas to build the seen map - for (const entry of registry._idmap.entries()) { - const [_, schema] = entry; - to_json_schema_process(schema, ctx); - } - const schemas = {}; - const external = { - registry, - uri: params?.uri, - defs, - }; - // Update the context with external configuration - ctx.external = external; - // Second pass: emit each schema - for (const entry of registry._idmap.entries()) { - const [key, schema] = entry; - extractDefs(ctx, schema); - assignProp(schemas, key, finalize(ctx, schema)); - } - if (Object.keys(defs).length > 0) { - const defsSegment = ctx.target === "draft-2020-12" ? "$defs" : "definitions"; - schemas.__shared = { - [defsSegment]: defs, - }; - } - return { schemas }; - } - // Single schema case - const ctx = initializeContext({ ...params, processors: allProcessors }); - to_json_schema_process(input, ctx); - extractDefs(ctx, input); - return finalize(ctx, input); -} - - -const en_error = () => { - const Sizable = { - string: { unit: "characters", verb: "to have" }, - file: { unit: "bytes", verb: "to have" }, - array: { unit: "items", verb: "to have" }, - set: { unit: "items", verb: "to have" }, - map: { unit: "entries", verb: "to have" }, - }; - function getSizing(origin) { - return Sizable[origin] ?? null; - } - const FormatDictionary = { - 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", - credit_card: "credit card number", - jwt: "JWT", - template_literal: "input", - }; - // type names: missing keys = do not translate (use raw value via ?? fallback) - const TypeDictionary = { - // Compatibility: "nan" -> "NaN" for display - nan: "NaN", - // All other type names omitted - they fall back to raw values via ?? operator - }; - function getTypeName(type, input) { - if (type === "number" && typeof input === "number" && !Number.isFinite(input)) { - return String(input); - } - return TypeDictionary[type] ?? type; - } - return (issue) => { - switch (issue.code) { - case "invalid_type": { - const expected = getTypeName(issue.expected); - const receivedType = parsedType(issue.input); - const received = getTypeName(receivedType, issue.input); - return `Invalid input: expected ${expected}, received ${received}`; - } - case "invalid_value": - if (issue.values.length === 1) - return `Invalid input: expected ${stringifyPrimitive(issue.values[0])}`; - return `Invalid option: expected one of ${joinValues(issue.values, "|")}`; - case "too_big": { - const adj = issue.exact ? "exactly " : issue.inclusive ? "<=" : "<"; - const sizing = getSizing(issue.origin); - if (sizing) - return `Too big: expected ${issue.origin ?? "value"} to have ${adj}${issue.maximum.toString()} ${sizing.unit ?? "elements"}`; - return `Too big: expected ${issue.origin ?? "value"} to be ${adj}${issue.maximum.toString()}`; - } - case "too_small": { - const adj = issue.exact ? "exactly " : issue.inclusive ? ">=" : ">"; - const sizing = getSizing(issue.origin); - if (sizing) { - return `Too small: expected ${issue.origin} to have ${adj}${issue.minimum.toString()} ${sizing.unit}`; - } - return `Too small: expected ${issue.origin} to be ${adj}${issue.minimum.toString()}`; - } - case "invalid_format": { - const _issue = issue; - if (_issue.format === "starts_with") { - return `Invalid string: must start with "${_issue.prefix}"`; - } - if (_issue.format === "ends_with") - return `Invalid string: must end with "${_issue.suffix}"`; - if (_issue.format === "includes") - return `Invalid string: must include "${_issue.includes}"`; - if (_issue.format === "regex") - return `Invalid string: must match pattern ${_issue.pattern}`; - return `Invalid ${FormatDictionary[_issue.format] ?? issue.format}`; - } - case "not_multiple_of": - return `Invalid number: must be a multiple of ${issue.divisor}`; - case "unrecognized_keys": - return `Unrecognized key${issue.keys.length > 1 ? "s" : ""}: ${joinValues(issue.keys, ", ")}`; - case "invalid_key": - return `Invalid key in ${issue.origin}`; - case "invalid_union": - if (issue.options && Array.isArray(issue.options) && issue.options.length > 0) { - const opts = issue.options.map((o) => `'${o}'`).join(" | "); - return `Invalid discriminator value. Expected ${opts}`; - } - if (issue.inclusive === false) { - return "Invalid input: more than one option matched"; - } - return "Invalid input"; - case "invalid_element": - return `Invalid value in ${issue.origin}`; - default: - return `Invalid input`; - } - }; -}; -/* export default */ function en() { - return { - localeError: en_error(), - }; -} - - - - -/* Prototypes that already carry the lazy helper methods. Seeded with the - * intrinsics so that `init` on a foreign object — it accepts any object — - * can never install an accessor onto a prototype we do not own. */ -const _installedErrorProtos = /* @__PURE__ */ new WeakSet([Object.prototype, Error.prototype]); -/* Helper methods live as non-enumerable lazy getters on the shared - * prototype instead of own properties on every instance. On first - * access the getter allocates the per-instance closure and caches it - * as a non-enumerable own property, so detached usage still works and - * the allocation only happens for methods actually touched. */ -function _lazyMethod(proto, key, make) { - Object.defineProperty(proto, key, { - configurable: true, - enumerable: false, - get() { - const value = make(this); - Object.defineProperty(this, key, { value, configurable: true, writable: true }); - return value; - }, - set(value) { - Object.defineProperty(this, key, { value, configurable: true, writable: true }); - }, - }); -} -const classic_errors_initializer = (inst, issues) => { - $ZodError.init(inst, issues); - inst.name = "ZodError"; - const proto = Object.getPrototypeOf(inst); - if (_installedErrorProtos.has(proto)) - return; - _installedErrorProtos.add(proto); - _lazyMethod(proto, "format", (self) => (mapper) => formatError(self, mapper)); - _lazyMethod(proto, "flatten", (self) => (mapper) => flattenError(self, mapper)); - _lazyMethod(proto, "addIssue", (self) => (issue) => { - self.issues.push(issue); - self.message = JSON.stringify(self.issues, jsonStringifyReplacer, 2); - }); - _lazyMethod(proto, "addIssues", (self) => (issues) => { - self.issues.push(...issues); - self.message = JSON.stringify(self.issues, jsonStringifyReplacer, 2); - }); - Object.defineProperty(proto, "isEmpty", { - configurable: true, - enumerable: false, - get() { - return this.issues.length === 0; - }, - }); -}; -const ZodError = /*@__PURE__*/ (/* unused pure expression or super */ null && (core.$constructor("ZodError", classic_errors_initializer))); -const ZodRealError = /*@__PURE__*/ $constructor("ZodError", classic_errors_initializer, undefined, { - Parent: Error, -}); -// /** @deprecated Use `z.core.$ZodErrorMapCtx` instead. */ -// export type ErrorMapCtx = core.$ZodErrorMapCtx; - - - -const classic_parse_parse = /* @__PURE__ */ parse_parse(ZodRealError); -const classic_parse_parseAsync = /* @__PURE__ */ parse_parseAsync(ZodRealError); -const parse_safeParse = /* @__PURE__ */ _safeParse(ZodRealError); -const parse_safeParseAsync = /* @__PURE__ */ _safeParseAsync(ZodRealError); - -// Codec functions -const classic_parse_encode = /* @__PURE__ */ parse_encode(ZodRealError); -const classic_parse_decode = /* @__PURE__ */ parse_decode(ZodRealError); -const classic_parse_encodeAsync = /* @__PURE__ */ parse_encodeAsync(ZodRealError); -const classic_parse_decodeAsync = /* @__PURE__ */ parse_decodeAsync(ZodRealError); -const parse_safeEncode = /* @__PURE__ */ _safeEncode(ZodRealError); -const parse_safeDecode = /* @__PURE__ */ _safeDecode(ZodRealError); -const parse_safeEncodeAsync = /* @__PURE__ */ _safeEncodeAsync(ZodRealError); -const parse_safeDecodeAsync = /* @__PURE__ */ _safeDecodeAsync(ZodRealError); - - - - - - - - -// Register English as the default locale on first ZodType construction. Hooked into the `ZodType` `$constructor` (rather than a top-level `config(en())` in `external.ts`) so bundlers honoring `sideEffects: false` can't tree-shake it out — see #5953, #5725. An explicit `z.config(z.locales.xx())` call wins regardless of order, since this only sets the default when none is present. -function _ensureDefaultLocale() { - if (!globalConfig.localeError) - core_config(en()); -} -// the default memoizer is read by the core container init, which runs before `ZodType.init`, so each container calls this first -function _ensureDefaultMemoizer() { - if (!globalConfig.memoizer) - core_config({ memoizer: memoizer() }); -} -const ZodType = /*@__PURE__*/ $constructor("ZodType", (inst, def) => { - _ensureDefaultLocale(); - $ZodType.init(inst, def); - inst.def = def; - inst.type = def.type; - return inst; -}, { - check(...chks) { - const def = this.def; - return this.clone(mergeDefs(def, { - checks: [ - ...(def.checks ?? []), - ...chks.map((ch) => typeof ch === "function" ? { _zod: { check: ch, def: { check: "custom" }, onattach: [] } } : ch), - ], - }), { parent: true }); - }, - with(...chks) { - return this.check(...chks); - }, - clone(def, params) { - return clone(this, def, params); - }, - brand() { - return this; - }, - register(reg, meta) { - reg.add(this, meta); - return this; - }, - refine(check, params) { - return this.check(refine(check, params)); - }, - superRefine(refinement, params) { - return this.check(superRefine(refinement, params)); - }, - overwrite(fn) { - return this.check(_overwrite(fn)); - }, - optional() { - return schemas_optional(this); - }, - exactOptional() { - return exactOptional(this); - }, - nullable() { - return nullable(this); - }, - nullish() { - return schemas_optional(nullable(this)); - }, - nonoptional(params) { - return nonoptional(this, params); - }, - array() { - return schemas_array(this); - }, - or(arg) { - return schemas_union([this, arg]); - }, - and(arg) { - return intersection(this, arg); - }, - transform(tx) { - return pipe(this, transform(tx)); - }, - default(d) { - return schemas_default(this, d); - }, - prefault(d) { - return prefault(this, d); - }, - catch(params) { - return schemas_catch(this, params); - }, - pipe(target) { - return pipe(this, target); - }, - readonly() { - return readonly(this); - }, - describe(description) { - const cl = this.clone(); - globalRegistry.add(cl, { description }); - return cl; - }, - meta(...args) { - // overloaded: meta() returns the registered metadata, meta(data) returns a clone with `data` registered. The mapped type picks up the second overload, so we accept variadic any-args and return `any` to satisfy both at runtime. - if (args.length === 0) - return globalRegistry.get(this); - const cl = this.clone(); - globalRegistry.add(cl, args[0]); - return cl; - }, - isOptional() { - return this.safeParse(undefined).success; - }, - isNullable() { - return this.safeParse(null).success; - }, - apply(fn, ...args) { - return args.length === 0 ? fn(this) : fn(this, ...args); - }, - // Overrides core's `~standard` to add `jsonSchema`. Must stay a prototype entry: redefining it per instance demotes instances to dictionary mode. - get "~standard"() { - return hide(this, "~standard", { - ...standardProps(this), - jsonSchema: { - input: createStandardJSONSchemaMethod(this, "input"), - output: createStandardJSONSchemaMethod(this, "output"), - }, - }); - }, - set "~standard"(value) { - util_own(this, "~standard", value); - }, - parse: function _parse(data, params) { - return classic_parse_parse(this, data, params, { callee: _parse }); - }, - parseAsync: async function _parseAsync(data, params) { - return await classic_parse_parseAsync(this, data, params, { callee: _parseAsync }); - }, - safeParse(data, params) { - return parse_safeParse(this, data, params); - }, - async safeParseAsync(data, params) { - return parse_safeParseAsync(this, data, params); - }, - // `spa` is an alias: same function object as `safeParseAsync`, as before. - get spa() { - return this?.safeParseAsync; - }, - set spa(value) { - util_own(this, "spa", value); - }, - encode: function _encode(data, params) { - return classic_parse_encode(this, data, params, { callee: _encode }); - }, - decode: function _decode(data, params) { - return classic_parse_decode(this, data, params, { callee: _decode }); - }, - encodeAsync: async function _encodeAsync(data, params) { - return await classic_parse_encodeAsync(this, data, params, { callee: _encodeAsync }); - }, - decodeAsync: async function _decodeAsync(data, params) { - return await classic_parse_decodeAsync(this, data, params, { callee: _decodeAsync }); - }, - safeEncode(data, params) { - return parse_safeEncode(this, data, params); - }, - safeDecode(data, params) { - return parse_safeDecode(this, data, params); - }, - async safeEncodeAsync(data, params) { - return parse_safeEncodeAsync(this, data, params); - }, - async safeDecodeAsync(data, params) { - return parse_safeDecodeAsync(this, data, params); - }, - toJSONSchema(params) { - return createToJSONSchemaMethod(this, {})(params); - }, - // Reads through to the registry on every access, so it must not cache. - get description() { - return globalRegistry.get(this)?.description; - }, - // No setter: `schema._def = x` throws, as it did when `_def` was a non-writable own property. - get _def() { - return this._zod.def; - }, -}); -/** @internal */ -const _ZodString = /*@__PURE__*/ $constructor("_ZodString", (inst, def) => { - $ZodString.init(inst, def); - ZodType.init(inst, def); - inst._zod.processJSONSchema = (ctx, json, params) => stringProcessor(inst, ctx, json, params); - const bag = inst._zod.bag; - inst.format = bag.format ?? null; - inst.minLength = bag.minimum ?? null; - inst.maxLength = bag.maximum ?? null; -}, { - regex(...args) { - return this.check(_regex(...args)); - }, - includes(...args) { - return this.check(_includes(...args)); - }, - startsWith(...args) { - return this.check(_startsWith(...args)); - }, - endsWith(...args) { - return this.check(_endsWith(...args)); - }, - min(...args) { - return this.check(_minLength(...args)); - }, - max(...args) { - return this.check(_maxLength(...args)); - }, - length(...args) { - return this.check(_length(...args)); - }, - nonempty(...args) { - return this.check(_minLength(1, ...args)); - }, - lowercase(params) { - return this.check(_lowercase(params)); - }, - uppercase(params) { - return this.check(_uppercase(params)); - }, - trim() { - return this.check(_trim()); - }, - normalize(...args) { - return this.check(_normalize(...args)); - }, - toLowerCase() { - return this.check(_toLowerCase()); - }, - toUpperCase() { - return this.check(_toUpperCase()); - }, - slugify() { - return this.check(_slugify()); - }, -}); -const ZodString = /*@__PURE__*/ $constructor("ZodString", (inst, def) => { - $ZodString.init(inst, def); - _ZodString.init(inst, def); -}, { - email(params) { - return this.check(_email(ZodEmail, params)); - }, - url(params) { - return this.check(_url(ZodURL, params)); - }, - jwt(params) { - return this.check(_jwt(ZodJWT, params)); - }, - emoji(params) { - return this.check(api_emoji(ZodEmoji, params)); - }, - guid(params) { - return this.check(_guid(ZodGUID, params)); - }, - uuid(params) { - return this.check(_uuid(ZodUUID, params)); - }, - uuidv4(params) { - return this.check(_uuidv4(ZodUUID, params)); - }, - uuidv6(params) { - return this.check(_uuidv6(ZodUUID, params)); - }, - uuidv7(params) { - return this.check(_uuidv7(ZodUUID, params)); - }, - nanoid(params) { - return this.check(_nanoid(ZodNanoID, params)); - }, - cuid(params) { - return this.check(_cuid(ZodCUID, params)); - }, - cuid2(params) { - return this.check(_cuid2(ZodCUID2, params)); - }, - ulid(params) { - return this.check(_ulid(ZodULID, params)); - }, - base64(params) { - return this.check(_base64(ZodBase64, params)); - }, - base64url(params) { - return this.check(_base64url(ZodBase64URL, params)); - }, - xid(params) { - return this.check(_xid(ZodXID, params)); - }, - ksuid(params) { - return this.check(_ksuid(ZodKSUID, params)); - }, - ipv4(params) { - return this.check(_ipv4(ZodIPv4, params)); - }, - ipv6(params) { - return this.check(_ipv6(ZodIPv6, params)); - }, - cidrv4(params) { - return this.check(_cidrv4(ZodCIDRv4, params)); - }, - cidrv6(params) { - return this.check(_cidrv6(ZodCIDRv6, params)); - }, - e164(params) { - return this.check(_e164(ZodE164, params)); - }, - datetime(params) { - return this.check(_isoDateTime(ZodISODateTime, params)); - }, - date(params) { - return this.check(_isoDate(ZodISODate, params)); - }, - time(params) { - return this.check(_isoTime(schemas_ZodISOTime, params)); - }, - duration(params) { - return this.check(_isoDuration(schemas_ZodISODuration, params)); - }, -}); -function schemas_string(params) { - return _string(ZodString, params); -} -const ZodStringFormat = /*@__PURE__*/ $constructor("ZodStringFormat", (inst, def) => { - $ZodStringFormat.init(inst, def); - _ZodString.init(inst, def); -}); -const ZodISODateTime = /*@__PURE__*/ $constructor("ZodISODateTime", (inst, def) => { - $ZodISODateTime.init(inst, def); - ZodStringFormat.init(inst, def); -}); -const ZodISODate = /*@__PURE__*/ $constructor("ZodISODate", (inst, def) => { - $ZodISODate.init(inst, def); - ZodStringFormat.init(inst, def); -}); -const schemas_ZodISOTime = /*@__PURE__*/ $constructor("ZodISOTime", (inst, def) => { - $ZodISOTime.init(inst, def); - ZodStringFormat.init(inst, def); -}); -const schemas_ZodISODuration = /*@__PURE__*/ $constructor("ZodISODuration", (inst, def) => { - $ZodISODuration.init(inst, def); - ZodStringFormat.init(inst, def); -}); -const ZodEmail = /*@__PURE__*/ $constructor("ZodEmail", (inst, def) => { - // ZodStringFormat.init(inst, def); - $ZodEmail.init(inst, def); - ZodStringFormat.init(inst, def); -}); -function schemas_email(params) { - return _email(ZodEmail, params); -} -const ZodGUID = /*@__PURE__*/ $constructor("ZodGUID", (inst, def) => { - // ZodStringFormat.init(inst, def); - $ZodGUID.init(inst, def); - ZodStringFormat.init(inst, def); -}); -function schemas_guid(params) { - return core._guid(ZodGUID, params); -} -const ZodUUID = /*@__PURE__*/ $constructor("ZodUUID", (inst, def) => { - // ZodStringFormat.init(inst, def); - $ZodUUID.init(inst, def); - ZodStringFormat.init(inst, def); -}); -function schemas_uuid(params) { - return core._uuid(ZodUUID, params); -} -function uuidv4(params) { - return core._uuidv4(ZodUUID, params); -} -// ZodUUIDv6 -function uuidv6(params) { - return core._uuidv6(ZodUUID, params); -} -// ZodUUIDv7 -function uuidv7(params) { - return core._uuidv7(ZodUUID, params); -} -const ZodURL = /*@__PURE__*/ $constructor("ZodURL", (inst, def) => { - // ZodStringFormat.init(inst, def); - $ZodURL.init(inst, def); - ZodStringFormat.init(inst, def); -}); -function schemas_url(params) { - return _url(ZodURL, params); -} -function httpUrl(params) { - return core._url(ZodURL, { - protocol: core.regexes.httpProtocol, - hostname: core.regexes.domain, - ...util.normalizeParams(params), - }); -} -const ZodEmoji = /*@__PURE__*/ $constructor("ZodEmoji", (inst, def) => { - // ZodStringFormat.init(inst, def); - $ZodEmoji.init(inst, def); - ZodStringFormat.init(inst, def); -}); -function schemas_emoji(params) { - return core._emoji(ZodEmoji, params); -} -const ZodNanoID = /*@__PURE__*/ $constructor("ZodNanoID", (inst, def) => { - // ZodStringFormat.init(inst, def); - $ZodNanoID.init(inst, def); - ZodStringFormat.init(inst, def); -}); -function schemas_nanoid(params) { - return core._nanoid(ZodNanoID, params); -} -/** - * @deprecated CUID v1 is deprecated by its authors due to information leakage - * (timestamps embedded in the id). Use {@link ZodCUID2} instead. - * See https://github.com/paralleldrive/cuid. - */ -const ZodCUID = /*@__PURE__*/ $constructor("ZodCUID", (inst, def) => { - // ZodStringFormat.init(inst, def); - $ZodCUID.init(inst, def); - ZodStringFormat.init(inst, def); -}); -/** - * Validates a CUID v1 string. - * - * @deprecated CUID v1 is deprecated by its authors due to information leakage - * (timestamps embedded in the id). Use {@link cuid2 | `z.cuid2()`} instead. - * See https://github.com/paralleldrive/cuid. - */ -function schemas_cuid(params) { - return core._cuid(ZodCUID, params); -} -const ZodCUID2 = /*@__PURE__*/ $constructor("ZodCUID2", (inst, def) => { - // ZodStringFormat.init(inst, def); - $ZodCUID2.init(inst, def); - ZodStringFormat.init(inst, def); -}); -function schemas_cuid2(params) { - return core._cuid2(ZodCUID2, params); -} -const ZodULID = /*@__PURE__*/ $constructor("ZodULID", (inst, def) => { - // ZodStringFormat.init(inst, def); - $ZodULID.init(inst, def); - ZodStringFormat.init(inst, def); -}); -function schemas_ulid(params) { - return core._ulid(ZodULID, params); -} -const ZodXID = /*@__PURE__*/ $constructor("ZodXID", (inst, def) => { - // ZodStringFormat.init(inst, def); - $ZodXID.init(inst, def); - ZodStringFormat.init(inst, def); -}); -function schemas_xid(params) { - return core._xid(ZodXID, params); -} -const ZodKSUID = /*@__PURE__*/ $constructor("ZodKSUID", (inst, def) => { - // ZodStringFormat.init(inst, def); - $ZodKSUID.init(inst, def); - ZodStringFormat.init(inst, def); -}); -function schemas_ksuid(params) { - return core._ksuid(ZodKSUID, params); -} -const ZodIPv4 = /*@__PURE__*/ $constructor("ZodIPv4", (inst, def) => { - // ZodStringFormat.init(inst, def); - $ZodIPv4.init(inst, def); - ZodStringFormat.init(inst, def); -}); -function schemas_ipv4(params) { - return core._ipv4(ZodIPv4, params); -} -const ZodMAC = /*@__PURE__*/ (/* unused pure expression or super */ null && (core.$constructor("ZodMAC", (inst, def) => { - // ZodStringFormat.init(inst, def); - core.$ZodMAC.init(inst, def); - ZodStringFormat.init(inst, def); -}))); -function schemas_mac(params) { - return core._mac(ZodMAC, params); -} -const ZodIPv6 = /*@__PURE__*/ $constructor("ZodIPv6", (inst, def) => { - // ZodStringFormat.init(inst, def); - $ZodIPv6.init(inst, def); - ZodStringFormat.init(inst, def); -}); -function schemas_ipv6(params) { - return core._ipv6(ZodIPv6, params); -} -const ZodCIDRv4 = /*@__PURE__*/ $constructor("ZodCIDRv4", (inst, def) => { - $ZodCIDRv4.init(inst, def); - ZodStringFormat.init(inst, def); -}); -function schemas_cidrv4(params) { - return core._cidrv4(ZodCIDRv4, params); -} -const ZodCIDRv6 = /*@__PURE__*/ $constructor("ZodCIDRv6", (inst, def) => { - $ZodCIDRv6.init(inst, def); - ZodStringFormat.init(inst, def); -}); -function schemas_cidrv6(params) { - return core._cidrv6(ZodCIDRv6, params); -} -const ZodBase64 = /*@__PURE__*/ $constructor("ZodBase64", (inst, def) => { - // ZodStringFormat.init(inst, def); - $ZodBase64.init(inst, def); - ZodStringFormat.init(inst, def); -}); -function schemas_base64(params) { - return core._base64(ZodBase64, params); -} -const ZodBase64URL = /*@__PURE__*/ $constructor("ZodBase64URL", (inst, def) => { - // ZodStringFormat.init(inst, def); - $ZodBase64URL.init(inst, def); - ZodStringFormat.init(inst, def); -}); -function schemas_base64url(params) { - return core._base64url(ZodBase64URL, params); -} -const ZodE164 = /*@__PURE__*/ $constructor("ZodE164", (inst, def) => { - // ZodStringFormat.init(inst, def); - $ZodE164.init(inst, def); - ZodStringFormat.init(inst, def); -}); -function schemas_e164(params) { - return core._e164(ZodE164, params); -} -const ZodCreditCard = /*@__PURE__*/ (/* unused pure expression or super */ null && (core.$constructor("ZodCreditCard", (inst, def) => { - core.$ZodCreditCard.init(inst, def); - ZodStringFormat.init(inst, def); -}))); -function schemas_creditCard(params) { - return core._creditCard(ZodCreditCard, params); -} -const ZodJWT = /*@__PURE__*/ $constructor("ZodJWT", (inst, def) => { - // ZodStringFormat.init(inst, def); - $ZodJWT.init(inst, def); - ZodStringFormat.init(inst, def); -}); -function jwt(params) { - return core._jwt(ZodJWT, params); -} -const ZodCustomStringFormat = /*@__PURE__*/ (/* unused pure expression or super */ null && (core.$constructor("ZodCustomStringFormat", (inst, def) => { - // ZodStringFormat.init(inst, def); - core.$ZodCustomStringFormat.init(inst, def); - ZodStringFormat.init(inst, def); -}))); -function stringFormat(format, fnOrRegex, _params = {}) { - return core._stringFormat(ZodCustomStringFormat, format, fnOrRegex, _params); -} -function schemas_hostname(_params) { - return core._stringFormat(ZodCustomStringFormat, "hostname", core.regexes.hostname, _params); -} -function schemas_hex(_params) { - return core._stringFormat(ZodCustomStringFormat, "hex", core.regexes.hex, _params); -} -function schemas_hash(alg, params) { - const enc = params?.enc ?? "hex"; - const format = `${alg}_${enc}`; - const regex = core.regexes[format]; - if (!regex) - throw new Error(`Unrecognized hash format: ${format}`); - return core._stringFormat(ZodCustomStringFormat, format, regex, params); -} -const ZodNumber = /*@__PURE__*/ $constructor("ZodNumber", (inst, def) => { - $ZodNumber.init(inst, def); - ZodType.init(inst, def); - inst._zod.processJSONSchema = (ctx, json, params) => numberProcessor(inst, ctx, json, params); - const bag = inst._zod.bag; - inst.minValue = - Math.max(bag.minimum ?? Number.NEGATIVE_INFINITY, bag.exclusiveMinimum ?? Number.NEGATIVE_INFINITY) ?? null; - inst.maxValue = - Math.min(bag.maximum ?? Number.POSITIVE_INFINITY, bag.exclusiveMaximum ?? Number.POSITIVE_INFINITY) ?? null; - inst.isInt = (bag.format ?? "").includes("int") || Number.isSafeInteger(bag.multipleOf ?? 0.5); - inst.isFinite = true; - inst.format = bag.format ?? null; -}, { - gt(value, params) { - return this.check(_gt(value, params)); - }, - gte(value, params) { - return this.check(_gte(value, params)); - }, - min(value, params) { - return this.check(_gte(value, params)); - }, - lt(value, params) { - return this.check(_lt(value, params)); - }, - lte(value, params) { - return this.check(_lte(value, params)); - }, - max(value, params) { - return this.check(_lte(value, params)); - }, - int(params) { - return this.check(schemas_int(params)); - }, - safe(params) { - return this.check(schemas_int(params)); - }, - positive(params) { - return this.check(_gt(0, params)); - }, - nonnegative(params) { - return this.check(_gte(0, params)); - }, - negative(params) { - return this.check(_lt(0, params)); - }, - nonpositive(params) { - return this.check(_lte(0, params)); - }, - multipleOf(value, params) { - return this.check(_multipleOf(value, params)); - }, - step(value, params) { - return this.check(_multipleOf(value, params)); - }, - finite() { - return this; - }, -}); -function schemas_number(params) { - return _number(ZodNumber, params); -} -const ZodNumberFormat = /*@__PURE__*/ $constructor("ZodNumberFormat", (inst, def) => { - $ZodNumberFormat.init(inst, def); - ZodNumber.init(inst, def); -}); -function schemas_int(params) { - return _int(ZodNumberFormat, params); -} -function float32(params) { - return core._float32(ZodNumberFormat, params); -} -function float64(params) { - return core._float64(ZodNumberFormat, params); -} -function int32(params) { - return core._int32(ZodNumberFormat, params); -} -function uint32(params) { - return core._uint32(ZodNumberFormat, params); -} -const ZodBoolean = /*@__PURE__*/ $constructor("ZodBoolean", (inst, def) => { - $ZodBoolean.init(inst, def); - ZodType.init(inst, def); - inst._zod.processJSONSchema = (ctx, json, params) => booleanProcessor(inst, ctx, json, params); -}); -function schemas_boolean(params) { - return _boolean(ZodBoolean, params); -} -const ZodBigInt = /*@__PURE__*/ (/* unused pure expression or super */ null && (core.$constructor("ZodBigInt", (inst, def) => { - core.$ZodBigInt.init(inst, def); - ZodType.init(inst, def); - inst._zod.processJSONSchema = (ctx, json, params) => processors.bigintProcessor(inst, ctx, json, params); - const bag = inst._zod.bag; - inst.minValue = bag.minimum ?? null; - inst.maxValue = bag.maximum ?? null; - inst.format = bag.format ?? null; -}, { - gte(value, params) { - return this.check(checks.gte(value, params)); - }, - min(value, params) { - return this.check(checks.gte(value, params)); - }, - gt(value, params) { - return this.check(checks.gt(value, params)); - }, - lt(value, params) { - return this.check(checks.lt(value, params)); - }, - lte(value, params) { - return this.check(checks.lte(value, params)); - }, - max(value, params) { - return this.check(checks.lte(value, params)); - }, - positive(params) { - return this.check(checks.gt(BigInt(0), params)); - }, - negative(params) { - return this.check(checks.lt(BigInt(0), params)); - }, - nonpositive(params) { - return this.check(checks.lte(BigInt(0), params)); - }, - nonnegative(params) { - return this.check(checks.gte(BigInt(0), params)); - }, - multipleOf(value, params) { - return this.check(checks.multipleOf(value, params)); - }, -}))); -function schemas_bigint(params) { - return core._bigint(ZodBigInt, params); -} -const ZodBigIntFormat = /*@__PURE__*/ (/* unused pure expression or super */ null && (core.$constructor("ZodBigIntFormat", (inst, def) => { - core.$ZodBigIntFormat.init(inst, def); - ZodBigInt.init(inst, def); -}))); -function int64(params) { - return core._int64(ZodBigIntFormat, params); -} -function uint64(params) { - return core._uint64(ZodBigIntFormat, params); -} -const ZodSymbol = /*@__PURE__*/ (/* unused pure expression or super */ null && (core.$constructor("ZodSymbol", (inst, def) => { - core.$ZodSymbol.init(inst, def); - ZodType.init(inst, def); - inst._zod.processJSONSchema = (ctx, json, params) => processors.symbolProcessor(inst, ctx, json, params); -}))); -function symbol(params) { - return core._symbol(ZodSymbol, params); -} -const ZodUndefined = /*@__PURE__*/ (/* unused pure expression or super */ null && (core.$constructor("ZodUndefined", (inst, def) => { - core.$ZodUndefined.init(inst, def); - ZodType.init(inst, def); - inst._zod.processJSONSchema = (ctx, json, params) => processors.undefinedProcessor(inst, ctx, json, params); -}))); -function schemas_undefined(params) { - return core._undefined(ZodUndefined, params); -} - -const ZodNull = /*@__PURE__*/ $constructor("ZodNull", (inst, def) => { - $ZodNull.init(inst, def); - ZodType.init(inst, def); - inst._zod.processJSONSchema = (ctx, json, params) => nullProcessor(inst, ctx, json, params); -}); -function schemas_null(params) { - return api_null(ZodNull, params); -} - -const ZodAny = /*@__PURE__*/ $constructor("ZodAny", (inst, def) => { - $ZodAny.init(inst, def); - ZodType.init(inst, def); - inst._zod.processJSONSchema = (ctx, json, params) => anyProcessor(inst, ctx, json, params); -}); -function any() { - return _any(ZodAny); -} -const ZodUnknown = /*@__PURE__*/ $constructor("ZodUnknown", (inst, def) => { - $ZodUnknown.init(inst, def); - ZodType.init(inst, def); - inst._zod.processJSONSchema = (ctx, json, params) => unknownProcessor(inst, ctx, json, params); -}); -function unknown() { - return _unknown(ZodUnknown); -} -const ZodNever = /*@__PURE__*/ $constructor("ZodNever", (inst, def) => { - $ZodNever.init(inst, def); - ZodType.init(inst, def); - inst._zod.processJSONSchema = (ctx, json, params) => neverProcessor(inst, ctx, json, params); -}); -function never(params) { - return _never(ZodNever, params); -} -const ZodVoid = /*@__PURE__*/ (/* unused pure expression or super */ null && (core.$constructor("ZodVoid", (inst, def) => { - core.$ZodVoid.init(inst, def); - ZodType.init(inst, def); - inst._zod.processJSONSchema = (ctx, json, params) => processors.voidProcessor(inst, ctx, json, params); -}))); -function schemas_void(params) { - return core._void(ZodVoid, params); -} - -const ZodDate = /*@__PURE__*/ (/* unused pure expression or super */ null && (core.$constructor("ZodDate", (inst, def) => { - core.$ZodDate.init(inst, def); - ZodType.init(inst, def); - inst._zod.processJSONSchema = (ctx, json, params) => processors.dateProcessor(inst, ctx, json, params); - inst.min = (value, params) => inst.check(checks.gte(value, params)); - inst.max = (value, params) => inst.check(checks.lte(value, params)); - const c = inst._zod.bag; - inst.minDate = c.minimum ? new Date(c.minimum) : null; - inst.maxDate = c.maximum ? new Date(c.maximum) : null; -}))); -function schemas_date(params) { - return core._date(ZodDate, params); -} -const ZodArray = /*@__PURE__*/ $constructor("ZodArray", (inst, def) => { - _ensureDefaultMemoizer(); - $ZodArray.init(inst, def); - ZodType.init(inst, def); - inst._zod.processJSONSchema = (ctx, json, params) => arrayProcessor(inst, ctx, json, params); - inst.element = def.element; -}, { - min(n, params) { - return this.check(_minLength(n, params)); - }, - nonempty(params) { - return this.check(_minLength(1, params)); - }, - max(n, params) { - return this.check(_maxLength(n, params)); - }, - length(n, params) { - return this.check(_length(n, params)); - }, - unwrap() { - return this.element; - }, -}); -function schemas_array(element, params) { - return _array(ZodArray, element, params); -} -// .keyof -function keyof(schema) { - const shape = schema._zod.def.shape; - return schemas_enum(Object.keys(shape)); -} -const ZodObject = /*@__PURE__*/ $constructor("ZodObject", (inst, def) => { - _ensureDefaultMemoizer(); - $ZodObjectJIT.init(inst, def); - ZodType.init(inst, def); - inst._zod.processJSONSchema = (ctx, json, params) => objectProcessor(inst, ctx, json, params); - installLazyProp(inst, "shape", (self) => self._zod.def.shape, false); -}, { - keyof() { - return schemas_enum(Object.keys(this._zod.def.shape)); - }, - catchall(catchall) { - return this.clone({ ...this._zod.def, catchall: catchall }); - }, - passthrough() { - return this.clone({ ...this._zod.def, catchall: unknown() }); - }, - loose() { - return this.clone({ ...this._zod.def, catchall: unknown() }); - }, - strict() { - return this.clone({ ...this._zod.def, catchall: never() }); - }, - strip() { - return this.clone({ ...this._zod.def, catchall: undefined }); - }, - extend(incoming) { - return extend(this, incoming); - }, - safeExtend(incoming) { - return safeExtend(this, incoming); - }, - merge(other) { - return merge(this, other); - }, - pick(mask) { - return pick(this, mask); - }, - omit(mask) { - return omit(this, mask); - }, - partial(...args) { - return partial(ZodOptional, this, args[0]); - }, - exactPartial(...args) { - return partial(ZodExactOptional, this, args[0], "exactPartial"); - }, - required(...args) { - return util_required(ZodNonOptional, this, args[0]); - }, -}); -function schemas_object(shape, params) { - const def = { - type: "object", - shape: shape ?? {}, - ...normalizeParams(params), - }; - return new ZodObject(def); -} -// strictObject -function strictObject(shape, params) { - return new ZodObject({ - type: "object", - shape, - catchall: never(), - ...util.normalizeParams(params), - }); -} -// looseObject -function looseObject(shape, params) { - return new ZodObject({ - type: "object", - shape, - catchall: unknown(), - ...normalizeParams(params), - }); -} -const ZodUnion = /*@__PURE__*/ $constructor("ZodUnion", (inst, def) => { - $ZodUnion.init(inst, def); - ZodType.init(inst, def); - inst._zod.processJSONSchema = (ctx, json, params) => unionProcessor(inst, ctx, json, params); - inst.options = def.options; -}); -function schemas_union(options, params) { - return new ZodUnion({ - type: "union", - options: options, - ...normalizeParams(params), - }); -} -const ZodXor = /*@__PURE__*/ (/* unused pure expression or super */ null && (core.$constructor("ZodXor", (inst, def) => { - ZodUnion.init(inst, def); - core.$ZodXor.init(inst, def); - inst._zod.processJSONSchema = (ctx, json, params) => processors.unionProcessor(inst, ctx, json, params); - inst.options = def.options; -}))); -/** Creates an exclusive union (XOR) where exactly one option must match. - * Unlike regular unions that succeed when any option matches, xor fails if - * zero or more than one option matches the input. */ -function xor(options, params) { - return new ZodXor({ - type: "union", - options: options, - inclusive: false, - ...util.normalizeParams(params), - }); -} -const ZodDiscriminatedUnion = /*@__PURE__*/ $constructor("ZodDiscriminatedUnion", (inst, def) => { - ZodUnion.init(inst, def); - $ZodDiscriminatedUnion.init(inst, def); -}); -function discriminatedUnion(discriminator, options, params) { - // const [options, params] = args; - return new ZodDiscriminatedUnion({ - type: "union", - options: options, - discriminator, - ...normalizeParams(params), - }); -} -const ZodIntersection = /*@__PURE__*/ $constructor("ZodIntersection", (inst, def) => { - $ZodIntersection.init(inst, def); - ZodType.init(inst, def); - inst._zod.processJSONSchema = (ctx, json, params) => intersectionProcessor(inst, ctx, json, params); -}); -function intersection(left, right) { - return new ZodIntersection({ - type: "intersection", - left: left, - right: right, - }); -} -const ZodTuple = /*@__PURE__*/ (/* unused pure expression or super */ null && (core.$constructor("ZodTuple", (inst, def) => { - _ensureDefaultMemoizer(); - core.$ZodTuple.init(inst, def); - ZodType.init(inst, def); - inst._zod.processJSONSchema = (ctx, json, params) => processors.tupleProcessor(inst, ctx, json, params); -}, { - rest(rest) { - return this.clone({ - ...this._zod.def, - rest: rest, - }); - }, - partial() { - const def = this._zod.def; - // a refinement was authored against the full arity; partialing would run it on a shorter array - if (def.checks?.length) - throw new Error(".partial() cannot be used on tuple schemas containing refinements"); - return this.clone({ - ...def, - items: def.items.map((item) => new ZodOptional({ type: "optional", innerType: item })), - }); - }, -}))); -function tuple(items, _paramsOrRest, _params) { - const hasRest = _paramsOrRest instanceof core.$ZodType; - const params = hasRest ? _params : _paramsOrRest; - const rest = hasRest ? _paramsOrRest : null; - return new ZodTuple({ - type: "tuple", - items: items, - rest, - ...util.normalizeParams(params), - }); -} -const ZodRecord = /*@__PURE__*/ $constructor("ZodRecord", (inst, def) => { - _ensureDefaultMemoizer(); - $ZodRecord.init(inst, def); - ZodType.init(inst, def); - inst._zod.processJSONSchema = (ctx, json, params) => recordProcessor(inst, ctx, json, params); - inst.keyType = def.keyType; - inst.valueType = def.valueType; -}); -function schemas_record(keyType, valueType, params) { - // v3-compat: z.record(valueType, params?) — defaults keyType to z.string() - if (!valueType || !valueType._zod) { - return new ZodRecord({ - type: "record", - keyType: schemas_string(), - valueType: keyType, - ...normalizeParams(valueType), - }); - } - return new ZodRecord({ - type: "record", - keyType, - valueType: valueType, - ...normalizeParams(params), - }); -} -// type alksjf = core.output; -function partialRecord(keyType, valueType, params) { - return new ZodRecord({ - type: "record", - keyType, - valueType: valueType, - ...util.normalizeParams(params), - partial: true, - }); -} -function looseRecord(keyType, valueType, params) { - return new ZodRecord({ - type: "record", - keyType, - valueType: valueType, - mode: "loose", - ...util.normalizeParams(params), - }); -} -const ZodMap = /*@__PURE__*/ (/* unused pure expression or super */ null && (core.$constructor("ZodMap", (inst, def) => { - _ensureDefaultMemoizer(); - core.$ZodMap.init(inst, def); - ZodType.init(inst, def); - inst._zod.processJSONSchema = (ctx, json, params) => processors.mapProcessor(inst, ctx, json, params); - inst.keyType = def.keyType; - inst.valueType = def.valueType; - inst.min = (...args) => inst.check(core._minSize(...args)); - inst.nonempty = (params) => inst.check(core._minSize(1, params)); - inst.max = (...args) => inst.check(core._maxSize(...args)); - inst.size = (...args) => inst.check(core._size(...args)); -}))); -function schemas_map(keyType, valueType, params) { - return new ZodMap({ - type: "map", - keyType: keyType, - valueType: valueType, - ...util.normalizeParams(params), - }); -} -const ZodSet = /*@__PURE__*/ (/* unused pure expression or super */ null && (core.$constructor("ZodSet", (inst, def) => { - _ensureDefaultMemoizer(); - core.$ZodSet.init(inst, def); - ZodType.init(inst, def); - inst._zod.processJSONSchema = (ctx, json, params) => processors.setProcessor(inst, ctx, json, params); - inst.min = (...args) => inst.check(core._minSize(...args)); - inst.nonempty = (params) => inst.check(core._minSize(1, params)); - inst.max = (...args) => inst.check(core._maxSize(...args)); - inst.size = (...args) => inst.check(core._size(...args)); -}))); -function schemas_set(valueType, params) { - return new ZodSet({ - type: "set", - valueType: valueType, - ...util.normalizeParams(params), - }); -} -const ZodEnum = /*@__PURE__*/ $constructor("ZodEnum", (inst, def) => { - $ZodEnum.init(inst, def); - ZodType.init(inst, def); - inst._zod.processJSONSchema = (ctx, json, params) => enumProcessor(inst, ctx, json, params); - inst.enum = def.entries; - inst.options = Object.values(def.entries); - const keys = new Set(Object.keys(def.entries)); - inst.extract = (values, params) => { - const newEntries = {}; - for (const value of values) { - if (keys.has(value)) { - newEntries[value] = def.entries[value]; - } - else - throw new Error(`Key ${value} not found in enum`); - } - return new ZodEnum({ - ...def, - checks: [], - ...normalizeParams(params), - entries: newEntries, - }); - }; - inst.exclude = (values, params) => { - const newEntries = { ...def.entries }; - for (const value of values) { - if (keys.has(value)) { - delete newEntries[value]; - } - else - throw new Error(`Key ${value} not found in enum`); - } - return new ZodEnum({ - ...def, - checks: [], - ...normalizeParams(params), - entries: newEntries, - }); - }; -}); -function schemas_enum(values, params) { - const entries = Array.isArray(values) ? Object.fromEntries(values.map((v) => [v, v])) : values; - return new ZodEnum({ - type: "enum", - entries, - ...normalizeParams(params), - }); -} - -/** @deprecated This API has been merged into `z.enum()`. Use `z.enum()` instead. - * - * ```ts - * enum Colors { red, green, blue } - * z.enum(Colors); - * ``` - */ -function nativeEnum(entries, params) { - return new ZodEnum({ - type: "enum", - entries, - ...util.normalizeParams(params), - }); -} -const ZodLiteral = /*@__PURE__*/ $constructor("ZodLiteral", (inst, def) => { - $ZodLiteral.init(inst, def); - ZodType.init(inst, def); - inst._zod.processJSONSchema = (ctx, json, params) => literalProcessor(inst, ctx, json, params); - inst.values = new Set(def.values); - Object.defineProperty(inst, "value", { - get() { - if (def.values.length > 1) { - throw new Error("This schema contains multiple valid literal values. Use `.values` instead."); - } - return def.values[0]; - }, - }); -}); -function literal(value, params) { - return new ZodLiteral({ - type: "literal", - values: Array.isArray(value) ? value : [value], - ...normalizeParams(params), - }); -} -const ZodFile = /*@__PURE__*/ (/* unused pure expression or super */ null && (core.$constructor("ZodFile", (inst, def) => { - core.$ZodFile.init(inst, def); - ZodType.init(inst, def); - inst._zod.processJSONSchema = (ctx, json, params) => processors.fileProcessor(inst, ctx, json, params); - inst.min = (size, params) => inst.check(core._minSize(size, params)); - inst.max = (size, params) => inst.check(core._maxSize(size, params)); - inst.mime = (types, params) => inst.check(core._mime(Array.isArray(types) ? types : [types], params)); -}))); -function schemas_file(params) { - return core._file(ZodFile, params); -} -const ZodTransform = /*@__PURE__*/ $constructor("ZodTransform", (inst, def) => { - _ensureDefaultMemoizer(); - $ZodTransform.init(inst, def); - ZodType.init(inst, def); - inst._zod.processJSONSchema = (ctx, json, params) => transformProcessor(inst, ctx, json, params); - inst._zod.parse = (payload, _ctx) => { - if (_ctx.direction === "backward") { - throw new $ZodEncodeError(inst.constructor.name); - } - payload.addIssue = (issue) => { - if (typeof issue === "string") { - payload.issues.push(util_issue(issue, payload.value, def)); - } - else { - // for Zod 3 backwards compatibility - const _issue = issue; - if (_issue.fatal) - _issue.continue = false; - _issue.code ?? (_issue.code = "custom"); - if (!("input" in _issue)) - _issue.input = payload.value; - _issue.inst ?? (_issue.inst = inst); - // _issue.continue ??= true; - payload.issues.push(util_issue(_issue)); - } - }; - const output = def.transform(payload.value, payload); - if (output instanceof Promise) { - return output.then((output) => { - payload.value = output; - return payload; - }); - } - payload.value = output; - return payload; - }; -}); -function transform(fn) { - return new ZodTransform({ - type: "transform", - transform: fn, - }); -} -const ZodOptional = /*@__PURE__*/ $constructor("ZodOptional", (inst, def) => { - $ZodOptional.init(inst, def); - ZodType.init(inst, def); - inst._zod.processJSONSchema = (ctx, json, params) => optionalProcessor(inst, ctx, json, params); - inst.unwrap = () => inst._zod.def.innerType; -}); -function schemas_optional(innerType) { - return new ZodOptional({ - type: "optional", - innerType: innerType, - }); -} -const ZodExactOptional = /*@__PURE__*/ $constructor("ZodExactOptional", (inst, def) => { - $ZodExactOptional.init(inst, def); - ZodType.init(inst, def); - inst._zod.processJSONSchema = (ctx, json, params) => optionalProcessor(inst, ctx, json, params); - inst.unwrap = () => inst._zod.def.innerType; -}); -function exactOptional(innerType) { - return new ZodExactOptional({ - type: "optional", - innerType: innerType, - }); -} -const ZodNullable = /*@__PURE__*/ $constructor("ZodNullable", (inst, def) => { - $ZodNullable.init(inst, def); - ZodType.init(inst, def); - inst._zod.processJSONSchema = (ctx, json, params) => nullableProcessor(inst, ctx, json, params); - inst.unwrap = () => inst._zod.def.innerType; -}); -function nullable(innerType) { - return new ZodNullable({ - type: "nullable", - innerType: innerType, - }); -} -// nullish -function schemas_nullish(innerType) { - return schemas_optional(nullable(innerType)); -} -const ZodDefault = /*@__PURE__*/ $constructor("ZodDefault", (inst, def) => { - $ZodDefault.init(inst, def); - ZodType.init(inst, def); - inst._zod.processJSONSchema = (ctx, json, params) => defaultProcessor(inst, ctx, json, params); - inst.unwrap = () => inst._zod.def.innerType; - inst.removeDefault = inst.unwrap; -}); -function schemas_default(innerType, defaultValue) { - return new ZodDefault({ - type: "default", - innerType: innerType, - get defaultValue() { - return typeof defaultValue === "function" ? defaultValue() : shallowClone(defaultValue); - }, - }); -} -const ZodPrefault = /*@__PURE__*/ $constructor("ZodPrefault", (inst, def) => { - $ZodPrefault.init(inst, def); - ZodType.init(inst, def); - inst._zod.processJSONSchema = (ctx, json, params) => prefaultProcessor(inst, ctx, json, params); - inst.unwrap = () => inst._zod.def.innerType; -}); -function prefault(innerType, defaultValue) { - return new ZodPrefault({ - type: "prefault", - innerType: innerType, - get defaultValue() { - return typeof defaultValue === "function" ? defaultValue() : shallowClone(defaultValue); - }, - }); -} -const ZodNonOptional = /*@__PURE__*/ $constructor("ZodNonOptional", (inst, def) => { - $ZodNonOptional.init(inst, def); - ZodType.init(inst, def); - inst._zod.processJSONSchema = (ctx, json, params) => nonoptionalProcessor(inst, ctx, json, params); - inst.unwrap = () => inst._zod.def.innerType; -}); -function nonoptional(innerType, params) { - return new ZodNonOptional({ - type: "nonoptional", - innerType: innerType, - ...normalizeParams(params), - }); -} -const ZodSuccess = /*@__PURE__*/ (/* unused pure expression or super */ null && (core.$constructor("ZodSuccess", (inst, def) => { - core.$ZodSuccess.init(inst, def); - ZodType.init(inst, def); - inst._zod.processJSONSchema = (ctx, json, params) => processors.successProcessor(inst, ctx, json, params); - inst.unwrap = () => inst._zod.def.innerType; -}))); -function success(innerType) { - return new ZodSuccess({ - type: "success", - innerType: innerType, - }); -} -const ZodCatch = /*@__PURE__*/ $constructor("ZodCatch", (inst, def) => { - $ZodCatch.init(inst, def); - ZodType.init(inst, def); - inst._zod.processJSONSchema = (ctx, json, params) => catchProcessor(inst, ctx, json, params); - inst.unwrap = () => inst._zod.def.innerType; - inst.removeCatch = inst.unwrap; -}); -function schemas_catch(innerType, catchValue) { - return new ZodCatch({ - type: "catch", - innerType: innerType, - catchValue: (typeof catchValue === "function" ? catchValue : constantCatch(catchValue)), - }); -} - -const ZodNaN = /*@__PURE__*/ (/* unused pure expression or super */ null && (core.$constructor("ZodNaN", (inst, def) => { - core.$ZodNaN.init(inst, def); - ZodType.init(inst, def); - inst._zod.processJSONSchema = (ctx, json, params) => processors.nanProcessor(inst, ctx, json, params); -}))); -function nan(params) { - return core._nan(ZodNaN, params); -} -const ZodPipe = /*@__PURE__*/ $constructor("ZodPipe", (inst, def) => { - $ZodPipe.init(inst, def); - ZodType.init(inst, def); - inst._zod.processJSONSchema = (ctx, json, params) => pipeProcessor(inst, ctx, json, params); - inst.in = def.in; - inst.out = def.out; -}); -function pipe(in_, out) { - return new ZodPipe({ - type: "pipe", - in: in_, - out: out, - // ...util.normalizeParams(params), - }); -} -const ZodCodec = /*@__PURE__*/ (/* unused pure expression or super */ null && (core.$constructor("ZodCodec", (inst, def) => { - ZodPipe.init(inst, def); - core.$ZodCodec.init(inst, def); -}))); -function schemas_codec(in_, out, params) { - return new ZodCodec({ - type: "pipe", - in: in_, - out: out, - transform: params.decode, - reverseTransform: params.encode, - }); -} -function invertCodec(codec) { - const def = codec._zod.def; - return new ZodCodec({ - type: "pipe", - in: def.out, - out: def.in, - transform: def.reverseTransform, - reverseTransform: def.transform, - }); -} -const ZodPreprocess = /*@__PURE__*/ $constructor("ZodPreprocess", (inst, def) => { - ZodPipe.init(inst, def); - $ZodPreprocess.init(inst, def); -}); -const ZodReadonly = /*@__PURE__*/ $constructor("ZodReadonly", (inst, def) => { - $ZodReadonly.init(inst, def); - ZodType.init(inst, def); - inst._zod.processJSONSchema = (ctx, json, params) => readonlyProcessor(inst, ctx, json, params); - inst.unwrap = () => inst._zod.def.innerType; -}); -function readonly(innerType) { - return new ZodReadonly({ - type: "readonly", - innerType: innerType, - }); -} -const ZodTemplateLiteral = /*@__PURE__*/ (/* unused pure expression or super */ null && (core.$constructor("ZodTemplateLiteral", (inst, def) => { - core.$ZodTemplateLiteral.init(inst, def); - ZodType.init(inst, def); - inst._zod.processJSONSchema = (ctx, json, params) => processors.templateLiteralProcessor(inst, ctx, json, params); -}))); -function templateLiteral(parts, params) { - return new ZodTemplateLiteral({ - type: "template_literal", - parts, - ...util.normalizeParams(params), - }); -} -const ZodLazy = /*@__PURE__*/ $constructor("ZodLazy", (inst, def) => { - $ZodLazy.init(inst, def); - ZodType.init(inst, def); - inst._zod.processJSONSchema = (ctx, json, params) => lazyProcessor(inst, ctx, json, params); - inst.unwrap = () => inst._zod.def.getter(); -}); -function lazy(getter) { - return new ZodLazy({ - type: "lazy", - getter: getter, - }); -} -const ZodPromise = /*@__PURE__*/ (/* unused pure expression or super */ null && (core.$constructor("ZodPromise", (inst, def) => { - core.$ZodPromise.init(inst, def); - ZodType.init(inst, def); - inst._zod.processJSONSchema = (ctx, json, params) => processors.promiseProcessor(inst, ctx, json, params); - inst.unwrap = () => inst._zod.def.innerType; -}))); -function schemas_promise(innerType) { - return new ZodPromise({ - type: "promise", - innerType: innerType, - }); -} -const ZodFunction = /*@__PURE__*/ (/* unused pure expression or super */ null && (core.$constructor("ZodFunction", (inst, def) => { - core.$ZodFunction.init(inst, def); - ZodType.init(inst, def); - inst._zod.processJSONSchema = (ctx, json, params) => processors.functionProcessor(inst, ctx, json, params); -}))); -function _function(params) { - return new ZodFunction({ - type: "function", - input: Array.isArray(params?.input) ? tuple(params?.input) : (params?.input ?? schemas_array(unknown())), - output: params?.output ?? unknown(), - }); -} - -const ZodCustom = /*@__PURE__*/ $constructor("ZodCustom", (inst, def) => { - $ZodCustom.init(inst, def); - ZodType.init(inst, def); - inst._zod.processJSONSchema = (ctx, json, params) => customProcessor(inst, ctx, json, params); -}); -// custom checks -function schemas_check(fn) { - const ch = new core.$ZodCheck({ - check: "custom", - // ...util.normalizeParams(params), - }); - ch._zod.check = fn; - return ch; -} -function custom(fn, _params) { - return core._custom(ZodCustom, fn ?? (() => true), _params); -} -function refine(fn, _params = {}) { - return _refine(ZodCustom, fn, _params); -} -// superRefine -function superRefine(fn, params) { - return _superRefine(fn, params); -} -// Re-export describe and meta from core -const schemas_describe = describe; -const schemas_meta = api_meta; -function _instanceof(cls, params = {}) { - const inst = new ZodCustom({ - type: "custom", - check: "custom", - fn: (data) => data instanceof cls, - abort: true, - ...util.normalizeParams(params), - }); - inst._zod.bag.Class = cls; - // Override check to emit invalid_type instead of custom - inst._zod.check = (payload) => { - if (!(payload.value instanceof cls)) { - payload.issues.push({ - code: "invalid_type", - expected: cls.name, - input: payload.value, - inst, - path: [...(inst._zod.def.path ?? [])], - }); - } - }; - return inst; -} - -// stringbool -const stringbool = (...args) => core._stringbool({ - Codec: ZodCodec, - Boolean: ZodBoolean, - String: ZodString, -}, ...args); -function schemas_json(params) { - const jsonSchema = lazy(() => { - return schemas_union([schemas_string(params), schemas_number(), schemas_boolean(), schemas_null(), schemas_array(jsonSchema), schemas_record(schemas_string(), jsonSchema)]); - }); - return jsonSchema; -} -// preprocess -function preprocess(fn, schema) { - return new ZodPreprocess({ - type: "pipe", - in: transform(fn), - out: schema, - }); -} - - - - -function iso_datetime(params) { - return _isoDateTime(ZodISODateTime, params); -} -function iso_date(params) { - return _isoDate(ZodISODate, params); -} -function iso_time(params) { - return core._isoTime(ZodISOTime, params); -} -function iso_duration(params) { - return core._isoDuration(ZodISODuration, params); -} - -// Zod 3 compat layer - -/** @deprecated Use the raw string literal codes instead, e.g. "invalid_type". */ -const ZodIssueCode = { - 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", -}; - -/** @deprecated Use `z.config(params)` instead. */ -function setErrorMap(map) { - core.config({ - customError: map, - }); -} -/** @deprecated Use `z.config()` instead. */ -function getErrorMap() { - return core.config().customError; -} -/** @deprecated Do not use. Stub definition, only included for zod-to-json-schema compatibility. */ -var compat_ZodFirstPartyTypeKind; -(function (ZodFirstPartyTypeKind) { -})(compat_ZodFirstPartyTypeKind || (compat_ZodFirstPartyTypeKind = {})); - - - -function coerce_string(params) { - return core._coercedString(schemas.ZodString, params); -} -function coerce_number(params) { - return _coercedNumber(ZodNumber, params); -} -function coerce_boolean(params) { - return core._coercedBoolean(schemas.ZodBoolean, params); -} -function coerce_bigint(params) { - return core._coercedBigint(schemas.ZodBigInt, params); -} -function coerce_date(params) { - return core._coercedDate(schemas.ZodDate, params); -} - - - -//#region src/constants.ts -const LATEST_PROTOCOL_VERSION = "2025-11-25"; -const auth_CUe6YdwF_DEFAULT_NEGOTIATED_PROTOCOL_VERSION = "2025-03-26"; -const auth_CUe6YdwF_SUPPORTED_PROTOCOL_VERSIONS = [ - LATEST_PROTOCOL_VERSION, - "2025-06-18", - "2025-03-26", - "2024-11-05", - "2024-10-07" -]; -/** -* `_meta` key associating a message with a 2025-11-25 task. -* -* @deprecated 2025-11-25 wire vocabulary with no SDK runtime; kept importable for interoperability only. -*/ -const RELATED_TASK_META_KEY = "io.modelcontextprotocol/related-task"; -/** -* `_meta` key carrying the MCP protocol version governing a request. -* -* For the HTTP transport, the value must match the `MCP-Protocol-Version` header. -*/ -const auth_CUe6YdwF_PROTOCOL_VERSION_META_KEY = "io.modelcontextprotocol/protocolVersion"; -/** -* `_meta` key identifying the client software making a request. -* -* Clients SHOULD include it on every request; the value is self-reported and -* intended for display, logging, and debugging — servers should not rely on -* it for behavior or security decisions. -*/ -const auth_CUe6YdwF_CLIENT_INFO_META_KEY = "io.modelcontextprotocol/clientInfo"; -/** -* `_meta` key identifying the server software producing a response. -* -* Servers SHOULD include it on every response; the value is self-reported and -* intended for display, logging, and debugging — clients should not rely on -* it for behavior or security decisions. -*/ -const auth_CUe6YdwF_SERVER_INFO_META_KEY = "io.modelcontextprotocol/serverInfo"; -/** -* `_meta` key carrying the client's capabilities for a request. -* -* Capabilities are declared per request rather than once at initialization; -* servers must not infer capabilities from prior requests. -*/ -const auth_CUe6YdwF_CLIENT_CAPABILITIES_META_KEY = "io.modelcontextprotocol/clientCapabilities"; -/** -* `_meta` key carrying the JSON-RPC ID of the `subscriptions/listen` request -* that opened the stream a notification was delivered on. -* -* Stamped by the server on every notification delivered via a -* `subscriptions/listen` stream (including the leading -* `notifications/subscriptions/acknowledged`); on stdio, where all messages -* share one channel, clients use it to correlate notifications with their -* originating subscription. The value is the listen request's JSON-RPC ID -* verbatim. -*/ -const auth_CUe6YdwF_SUBSCRIPTION_ID_META_KEY = "io.modelcontextprotocol/subscriptionId"; -/** -* `_meta` key carrying the desired log level for a request. -* -* When absent, the server must not send `notifications/message` notifications -* for the request. -* -* @deprecated Deprecated as of protocol version 2026-07-28 (SEP-2577); remains -* in the specification for at least twelve months. -*/ -const LOG_LEVEL_META_KEY = "io.modelcontextprotocol/logLevel"; -/** -* `_meta` key carrying W3C Trace Context for distributed tracing (SEP-414). -* -* When present, the value MUST follow the W3C `traceparent` header format, -* e.g. `00-4bf92f3577b34da6a3ce929d0e0e4736-00f067aa0ba902b7-01`. -* -* @see https://www.w3.org/TR/trace-context/#traceparent-header -*/ -const TRACEPARENT_META_KEY = "traceparent"; -/** -* `_meta` key carrying vendor-specific trace state for distributed tracing (SEP-414). -* -* When present, the value MUST follow the W3C `tracestate` header format, -* e.g. `vendor1=value1,vendor2=value2`. -* -* @see https://www.w3.org/TR/trace-context/#tracestate-header -*/ -const TRACESTATE_META_KEY = "tracestate"; -/** -* `_meta` key carrying cross-cutting propagation values for distributed tracing (SEP-414). -* -* When present, the value MUST follow the W3C Baggage header format, -* e.g. `userId=alice,serverRegion=us-east-1`. -* -* @see https://www.w3.org/TR/baggage/ -*/ -const BAGGAGE_META_KEY = "baggage"; -const JSONRPC_VERSION = "2.0"; -const PARSE_ERROR = (/* unused pure expression or super */ null && (-32700)); -const INVALID_REQUEST = (/* unused pure expression or super */ null && (-32600)); -const METHOD_NOT_FOUND = (/* unused pure expression or super */ null && (-32601)); -const INVALID_PARAMS = (/* unused pure expression or super */ null && (-32602)); -const INTERNAL_ERROR = (/* unused pure expression or super */ null && (-32603)); - -//#endregion -//#region src/schemas.ts -const JSONValueSchema = lazy(() => schemas_union([ - schemas_string(), - schemas_number(), - schemas_boolean(), - schemas_null(), - schemas_record(schemas_string(), JSONValueSchema), - schemas_array(JSONValueSchema) -])); -const JSONObjectSchema = schemas_record(schemas_string(), JSONValueSchema); -const JSONArraySchema = schemas_array(JSONValueSchema); -/** -* A progress token, used to associate progress notifications with the original request. -*/ -const ProgressTokenSchema = schemas_union([schemas_string(), schemas_number().int()]); -/** -* An opaque token used to represent a cursor for pagination. -*/ -const CursorSchema = schemas_string(); -/** @deprecated 2025-11-25 wire vocabulary with no SDK runtime; kept importable for interoperability only. */ -const TaskMetadataSchema = schemas_object({ ttl: schemas_number().optional() }); -/** -* Metadata for associating messages with a task. -* Include this in the `_meta` field under the key `io.modelcontextprotocol/related-task`. -* -* @deprecated 2025-11-25 wire vocabulary with no SDK runtime; kept importable for interoperability only. -*/ -const RelatedTaskMetadataSchema = schemas_object({ taskId: schemas_string() }); -const RequestMetaSchema = looseObject({ - progressToken: ProgressTokenSchema.optional(), - [RELATED_TASK_META_KEY]: RelatedTaskMetadataSchema.optional() -}); -/** -* Common params for any request. -*/ -const BaseRequestParamsSchema = schemas_object({ _meta: RequestMetaSchema.optional() }); -/** -* Common params for any task-augmented request. -* -* @deprecated 2025-11-25 wire vocabulary with no SDK runtime; kept importable for interoperability only. -*/ -const auth_CUe6YdwF_TaskAugmentedRequestParamsSchema = BaseRequestParamsSchema.extend({ task: TaskMetadataSchema.optional() }); -const RequestSchema = schemas_object({ - method: schemas_string(), - params: BaseRequestParamsSchema.loose().optional() -}); -const NotificationsParamsSchema = schemas_object({ _meta: RequestMetaSchema.optional() }); -const NotificationSchema = schemas_object({ - method: schemas_string(), - params: NotificationsParamsSchema.loose().optional() -}); -/** -* The contents of a result's `_meta` field (the 2026-07-28 `ResultMetaObject`). -* Loose — implementation-specific keys pass through. -* -* The serverInfo key identifies the server software producing the response -* (servers SHOULD include it on every response; the value is self-reported -* and intended for display, logging, and debugging). The getter defers the -* `ImplementationSchema` reference, which is declared later in this file. -*/ -const ResultMetaObjectSchema = looseObject({ get [auth_CUe6YdwF_SERVER_INFO_META_KEY]() { - return ImplementationSchema.optional().catch(void 0); -} }); -const ResultSchema = looseObject({ _meta: ResultMetaObjectSchema.optional() }); -/** -* A uniquely identifying ID for a request in JSON-RPC. -*/ -const RequestIdSchema = schemas_union([schemas_string(), schemas_number().int()]); -/** -* A request that expects a response. -*/ -const JSONRPCRequestSchema = schemas_object({ - jsonrpc: literal(JSONRPC_VERSION), - id: RequestIdSchema, - ...RequestSchema.shape -}).strict(); -/** -* A notification which does not expect a response. -*/ -const JSONRPCNotificationSchema = schemas_object({ - jsonrpc: literal(JSONRPC_VERSION), - ...NotificationSchema.shape -}).strict(); -/** -* A successful (non-error) response to a request. -*/ -const JSONRPCResultResponseSchema = schemas_object({ - jsonrpc: literal(JSONRPC_VERSION), - id: RequestIdSchema, - result: ResultSchema -}).strict(); -/** -* A response to a request that indicates an error occurred. -*/ -const JSONRPCErrorResponseSchema = schemas_object({ - jsonrpc: literal(JSONRPC_VERSION), - id: RequestIdSchema.optional(), - error: schemas_object({ - code: schemas_number().int(), - message: schemas_string(), - data: unknown().optional() - }) -}).strict(); -const auth_CUe6YdwF_JSONRPCMessageSchema = schemas_union([ - JSONRPCRequestSchema, - JSONRPCNotificationSchema, - JSONRPCResultResponseSchema, - JSONRPCErrorResponseSchema -]); -const auth_CUe6YdwF_JSONRPCResponseSchema = schemas_union([JSONRPCResultResponseSchema, JSONRPCErrorResponseSchema]); -/** -* A response that indicates success but carries no data. -*/ -const EmptyResultSchema = ResultSchema.strict(); -const CancelledNotificationParamsSchema = NotificationsParamsSchema.extend({ - requestId: RequestIdSchema.optional(), - reason: schemas_string().optional() -}); -/** -* This notification can be sent by either side to indicate that it is cancelling a previously-issued request. -* -* The request SHOULD still be in-flight, but due to communication latency, it is always possible that this notification MAY arrive after the request has already finished. -* -* This notification indicates that the result will be unused, so any associated processing SHOULD cease. -* -* A client MUST NOT attempt to cancel its {@linkcode InitializeRequest | initialize} request. -*/ -const CancelledNotificationSchema = NotificationSchema.extend({ - method: literal("notifications/cancelled"), - params: CancelledNotificationParamsSchema -}); -/** -* Icon schema for use in {@link Tool | tools}, {@link Prompt | prompts}, {@link Resource | resources}, and {@link Implementation | implementations}. -*/ -const IconSchema = schemas_object({ - src: schemas_string(), - mimeType: schemas_string().optional(), - sizes: schemas_array(schemas_string()).optional(), - theme: schemas_enum(["light", "dark"]).optional() -}); -/** -* Base schema to add `icons` property. -* -*/ -const IconsSchema = schemas_object({ icons: schemas_array(IconSchema).optional() }); -/** -* Base metadata interface for common properties across {@link Resource | resources}, {@link Tool | tools}, {@link Prompt | prompts}, and {@link Implementation | implementations}. -*/ -const BaseMetadataSchema = schemas_object({ - name: schemas_string(), - title: schemas_string().optional() -}); -/** -* Describes the name and version of an MCP implementation. -*/ -const ImplementationSchema = BaseMetadataSchema.extend({ - ...BaseMetadataSchema.shape, - ...IconsSchema.shape, - version: schemas_string(), - websiteUrl: schemas_string().optional(), - description: schemas_string().optional() -}); -const auth_CUe6YdwF_FormElicitationCapabilitySchema = intersection(schemas_object({ applyDefaults: schemas_boolean().optional() }), JSONObjectSchema); -const auth_CUe6YdwF_ElicitationCapabilitySchema = preprocess((value) => { - if (value && typeof value === "object" && !Array.isArray(value) && Object.keys(value).length === 0) return { form: {} }; - return value; -}, intersection(schemas_object({ - form: auth_CUe6YdwF_FormElicitationCapabilitySchema.optional(), - url: JSONObjectSchema.optional() -}), JSONObjectSchema.optional())); -/** -* Task capabilities for clients, indicating which request types support task creation. -* -* @deprecated 2025-11-25 wire vocabulary with no SDK runtime; kept importable for interoperability only. -*/ -const ClientTasksCapabilitySchema = looseObject({ - list: JSONObjectSchema.optional(), - cancel: JSONObjectSchema.optional(), - requests: looseObject({ - sampling: looseObject({ createMessage: JSONObjectSchema.optional() }).optional(), - elicitation: looseObject({ create: JSONObjectSchema.optional() }).optional() - }).optional() -}); -/** -* Task capabilities for servers, indicating which request types support task creation. -* -* @deprecated 2025-11-25 wire vocabulary with no SDK runtime; kept importable for interoperability only. -*/ -const ServerTasksCapabilitySchema = looseObject({ - list: JSONObjectSchema.optional(), - cancel: JSONObjectSchema.optional(), - requests: looseObject({ tools: looseObject({ call: JSONObjectSchema.optional() }).optional() }).optional() -}); -/** -* Capabilities a client may support. Known capabilities are defined here, in this schema, but this is not a closed set: any client can define its own, additional capabilities. -*/ -const ClientCapabilitiesSchema = schemas_object({ - experimental: schemas_record(schemas_string(), JSONObjectSchema).optional(), - sampling: schemas_object({ - context: JSONObjectSchema.optional(), - tools: JSONObjectSchema.optional() - }).optional(), - elicitation: auth_CUe6YdwF_ElicitationCapabilitySchema.optional(), - roots: schemas_object({ listChanged: schemas_boolean().optional() }).optional(), - tasks: ClientTasksCapabilitySchema.optional(), - extensions: schemas_record(schemas_string(), JSONObjectSchema).optional() -}); -const InitializeRequestParamsSchema = BaseRequestParamsSchema.extend({ - protocolVersion: schemas_string(), - capabilities: ClientCapabilitiesSchema, - clientInfo: ImplementationSchema -}); -/** -* This request is sent from the client to the server when it first connects, asking it to begin initialization. -*/ -const auth_CUe6YdwF_InitializeRequestSchema = RequestSchema.extend({ - method: literal("initialize"), - params: InitializeRequestParamsSchema -}); -/** -* Capabilities that a server may support. Known capabilities are defined here, in this schema, but this is not a closed set: any server can define its own, additional capabilities. -*/ -const ServerCapabilitiesSchema = schemas_object({ - experimental: schemas_record(schemas_string(), JSONObjectSchema).optional(), - logging: JSONObjectSchema.optional(), - completions: JSONObjectSchema.optional(), - prompts: schemas_object({ listChanged: schemas_boolean().optional() }).optional(), - resources: schemas_object({ - subscribe: schemas_boolean().optional(), - listChanged: schemas_boolean().optional() - }).optional(), - tools: schemas_object({ listChanged: schemas_boolean().optional() }).optional(), - tasks: ServerTasksCapabilitySchema.optional(), - extensions: schemas_record(schemas_string(), JSONObjectSchema).optional() -}); -/** -* After receiving an initialize request from the client, the server sends this response. -*/ -const InitializeResultSchema = ResultSchema.extend({ - protocolVersion: schemas_string(), - capabilities: ServerCapabilitiesSchema, - serverInfo: ImplementationSchema, - instructions: schemas_string().optional() -}); -/** -* This notification is sent from the client to the server after initialization has finished. -*/ -const auth_CUe6YdwF_InitializedNotificationSchema = NotificationSchema.extend({ - method: literal("notifications/initialized"), - params: NotificationsParamsSchema.optional() -}); -/** -* A request from the client asking the server to advertise its supported protocol -* versions, capabilities, and other metadata (protocol revision 2026-07-28). Servers -* MUST implement `server/discover`. Clients MAY call it but are not required to — -* version negotiation can also happen inline via the per-request `_meta` envelope. -*/ -const DiscoverRequestSchema = RequestSchema.extend({ - method: literal("server/discover"), - params: BaseRequestParamsSchema.optional() -}); -/** -* The result returned by the server for a `server/discover` request. -*/ -const DiscoverResultSchema = ResultSchema.extend({ - supportedVersions: schemas_array(schemas_string()), - capabilities: ServerCapabilitiesSchema, - instructions: schemas_string().optional() -}); -/** -* A ping, issued by either the server or the client, to check that the other party is still alive. The receiver must promptly respond, or else may be disconnected. -*/ -const PingRequestSchema = RequestSchema.extend({ - method: literal("ping"), - params: BaseRequestParamsSchema.optional() -}); -const ProgressSchema = schemas_object({ - progress: schemas_number(), - total: schemas_optional(schemas_number()), - message: schemas_optional(schemas_string()) -}); -const ProgressNotificationParamsSchema = schemas_object({ - ...NotificationsParamsSchema.shape, - ...ProgressSchema.shape, - progressToken: ProgressTokenSchema -}); -/** -* An out-of-band notification used to inform the receiver of a progress update for a long-running request. -* -* @category notifications/progress -*/ -const ProgressNotificationSchema = NotificationSchema.extend({ - method: literal("notifications/progress"), - params: ProgressNotificationParamsSchema -}); -const PaginatedRequestParamsSchema = BaseRequestParamsSchema.extend({ cursor: CursorSchema.optional() }); -const PaginatedRequestSchema = RequestSchema.extend({ params: PaginatedRequestParamsSchema.optional() }); -const PaginatedResultSchema = ResultSchema.extend({ nextCursor: CursorSchema.optional() }); -/** -* The contents of a specific resource or sub-resource. -*/ -const ResourceContentsSchema = schemas_object({ - uri: schemas_string(), - mimeType: schemas_optional(schemas_string()), - _meta: schemas_record(schemas_string(), unknown()).optional() -}); -const TextResourceContentsSchema = ResourceContentsSchema.extend({ text: schemas_string() }); -/** -* A Zod schema for validating Base64 strings that is more performant and -* robust for very large inputs than the default regex-based check. It avoids -* stack overflows by using the native `atob` function for validation. -*/ -const auth_CUe6YdwF_Base64Schema = schemas_string().refine((val) => { - try { - atob(val); - return true; - } catch { - return false; - } -}, { message: "Invalid Base64 string" }); -const BlobResourceContentsSchema = ResourceContentsSchema.extend({ blob: auth_CUe6YdwF_Base64Schema }); -/** -* The sender or recipient of messages and data in a conversation. -*/ -const RoleSchema = schemas_enum(["user", "assistant"]); -/** -* Optional annotations providing clients additional context about a resource. -*/ -const AnnotationsSchema = schemas_object({ - audience: schemas_array(RoleSchema).optional(), - priority: schemas_number().min(0).max(1).optional(), - lastModified: iso_datetime({ offset: true }).optional() -}); -/** -* A known resource that the server is capable of reading. -*/ -const ResourceSchema = schemas_object({ - ...BaseMetadataSchema.shape, - ...IconsSchema.shape, - uri: schemas_string(), - description: schemas_optional(schemas_string()), - mimeType: schemas_optional(schemas_string()), - size: schemas_optional(schemas_number()), - annotations: AnnotationsSchema.optional(), - _meta: schemas_optional(looseObject({})) -}); -/** -* A template description for resources available on the server. -*/ -const ResourceTemplateSchema = schemas_object({ - ...BaseMetadataSchema.shape, - ...IconsSchema.shape, - uriTemplate: schemas_string(), - description: schemas_optional(schemas_string()), - mimeType: schemas_optional(schemas_string()), - annotations: AnnotationsSchema.optional(), - _meta: schemas_optional(looseObject({})) -}); -/** -* Sent from the client to request a list of resources the server has. -*/ -const ListResourcesRequestSchema = PaginatedRequestSchema.extend({ method: literal("resources/list") }); -/** -* The server's response to a {@linkcode ListResourcesRequest | resources/list} request from the client. -*/ -const ListResourcesResultSchema = PaginatedResultSchema.extend({ resources: schemas_array(ResourceSchema) }); -/** -* Sent from the client to request a list of resource templates the server has. -*/ -const ListResourceTemplatesRequestSchema = PaginatedRequestSchema.extend({ method: literal("resources/templates/list") }); -/** -* The server's response to a {@linkcode ListResourceTemplatesRequest | resources/templates/list} request from the client. -*/ -const ListResourceTemplatesResultSchema = PaginatedResultSchema.extend({ resourceTemplates: schemas_array(ResourceTemplateSchema) }); -const ResourceRequestParamsSchema = BaseRequestParamsSchema.extend({ uri: schemas_string() }); -/** -* Parameters for a {@linkcode ReadResourceRequest | resources/read} request. -*/ -const ReadResourceRequestParamsSchema = ResourceRequestParamsSchema; -/** -* Sent from the client to the server, to read a specific resource URI. -*/ -const ReadResourceRequestSchema = RequestSchema.extend({ - method: literal("resources/read"), - params: ReadResourceRequestParamsSchema -}); -/** -* The server's response to a {@linkcode ReadResourceRequest | resources/read} request from the client. -*/ -const ReadResourceResultSchema = ResultSchema.extend({ contents: schemas_array(schemas_union([TextResourceContentsSchema, BlobResourceContentsSchema])) }); -/** -* An optional notification from the server to the client, informing it that the list of resources it can read from has changed. This may be issued by servers without any previous subscription from the client. -*/ -const ResourceListChangedNotificationSchema = NotificationSchema.extend({ - method: literal("notifications/resources/list_changed"), - params: NotificationsParamsSchema.optional() -}); -const SubscribeRequestParamsSchema = ResourceRequestParamsSchema; -/** -* Sent from the client to request `resources/updated` notifications from the server whenever a particular resource changes. -*/ -const SubscribeRequestSchema = RequestSchema.extend({ - method: literal("resources/subscribe"), - params: SubscribeRequestParamsSchema -}); -const UnsubscribeRequestParamsSchema = ResourceRequestParamsSchema; -/** -* Sent from the client to request cancellation of {@linkcode ResourceUpdatedNotification | resources/updated} notifications from the server. This should follow a previous {@linkcode SubscribeRequest | resources/subscribe} request. -*/ -const UnsubscribeRequestSchema = RequestSchema.extend({ - method: literal("resources/unsubscribe"), - params: UnsubscribeRequestParamsSchema -}); -/** -* The set of notification types a client opts in to on a `subscriptions/listen` -* request. Each type is opt-in; the server MUST NOT send a notification type -* the client has not explicitly requested here. -*/ -const SubscriptionFilterSchema = schemas_object({ - toolsListChanged: schemas_boolean().optional(), - promptsListChanged: schemas_boolean().optional(), - resourcesListChanged: schemas_boolean().optional(), - resourceSubscriptions: schemas_array(schemas_string()).optional() -}); -const SubscriptionsListenRequestParamsSchema = BaseRequestParamsSchema.extend({ notifications: SubscriptionFilterSchema }); -/** -* Sent from the client to open a long-lived channel for receiving notifications -* outside the context of a specific request (protocol revision 2026-07-28). -* Replaces the previous HTTP GET endpoint and `resources/subscribe`. -*/ -const SubscriptionsListenRequestSchema = RequestSchema.extend({ - method: literal("subscriptions/listen"), - params: SubscriptionsListenRequestParamsSchema -}); -const SubscriptionsAcknowledgedNotificationParamsSchema = NotificationsParamsSchema.extend({ notifications: SubscriptionFilterSchema }); -/** -* Sent by the server as the first message on a `subscriptions/listen` stream -* to acknowledge that the subscription has been established and report which -* notification types it agreed to honor (protocol revision 2026-07-28). -*/ -const SubscriptionsAcknowledgedNotificationSchema = NotificationSchema.extend({ - method: literal("notifications/subscriptions/acknowledged"), - params: SubscriptionsAcknowledgedNotificationParamsSchema -}); -/** -* `_meta` for a {@linkcode SubscriptionsListenResult}: the listen request's -* JSON-RPC ID under the canonical subscription-id key (mirroring the same key -* on every notification delivered on the stream). Extends -* {@linkcode ResultMetaObjectSchema}, so the optional serverInfo key is typed -* here too. -*/ -const SubscriptionsListenResultMetaSchema = ResultMetaObjectSchema.extend({ [auth_CUe6YdwF_SUBSCRIPTION_ID_META_KEY]: RequestIdSchema }); -/** -* The response to a `subscriptions/listen` request, signalling that the -* subscription has ended gracefully (for example, during server shutdown). -* Because the listen stream is long-lived, this result is sent only when the -* server tears the subscription down; an abrupt transport close carries no -* response. The result body is otherwise empty. -*/ -const SubscriptionsListenResultSchema = ResultSchema.extend({ _meta: SubscriptionsListenResultMetaSchema }); -/** -* Parameters for a {@linkcode ResourceUpdatedNotification | notifications/resources/updated} notification. -*/ -const ResourceUpdatedNotificationParamsSchema = NotificationsParamsSchema.extend({ uri: schemas_string() }); -/** -* A notification from the server to the client, informing it that a resource has changed and may need to be read again. This should only be sent if the client previously sent a {@linkcode SubscribeRequest | resources/subscribe} request. -*/ -const ResourceUpdatedNotificationSchema = NotificationSchema.extend({ - method: literal("notifications/resources/updated"), - params: ResourceUpdatedNotificationParamsSchema -}); -/** -* Describes an argument that a prompt can accept. -*/ -const PromptArgumentSchema = schemas_object({ - name: schemas_string(), - description: schemas_optional(schemas_string()), - required: schemas_optional(schemas_boolean()) -}); -/** -* A prompt or prompt template that the server offers. -*/ -const PromptSchema = schemas_object({ - ...BaseMetadataSchema.shape, - ...IconsSchema.shape, - description: schemas_optional(schemas_string()), - arguments: schemas_optional(schemas_array(PromptArgumentSchema)), - _meta: schemas_optional(looseObject({})) -}); -/** -* Sent from the client to request a list of prompts and prompt templates the server has. -*/ -const ListPromptsRequestSchema = PaginatedRequestSchema.extend({ method: literal("prompts/list") }); -/** -* The server's response to a {@linkcode ListPromptsRequest | prompts/list} request from the client. -*/ -const ListPromptsResultSchema = PaginatedResultSchema.extend({ prompts: schemas_array(PromptSchema) }); -/** -* Parameters for a {@linkcode GetPromptRequest | prompts/get} request. -*/ -const GetPromptRequestParamsSchema = BaseRequestParamsSchema.extend({ - name: schemas_string(), - arguments: schemas_record(schemas_string(), schemas_string()).optional() -}); -/** -* Used by the client to get a prompt provided by the server. -*/ -const GetPromptRequestSchema = RequestSchema.extend({ - method: literal("prompts/get"), - params: GetPromptRequestParamsSchema -}); -/** -* Text provided to or from an LLM. -*/ -const TextContentSchema = schemas_object({ - type: literal("text"), - text: schemas_string(), - annotations: AnnotationsSchema.optional(), - _meta: schemas_record(schemas_string(), unknown()).optional() -}); -/** -* An image provided to or from an LLM. -*/ -const ImageContentSchema = schemas_object({ - type: literal("image"), - data: auth_CUe6YdwF_Base64Schema, - mimeType: schemas_string(), - annotations: AnnotationsSchema.optional(), - _meta: schemas_record(schemas_string(), unknown()).optional() -}); -/** -* Audio content provided to or from an LLM. -*/ -const AudioContentSchema = schemas_object({ - type: literal("audio"), - data: auth_CUe6YdwF_Base64Schema, - mimeType: schemas_string(), - annotations: AnnotationsSchema.optional(), - _meta: schemas_record(schemas_string(), unknown()).optional() -}); -/** -* A tool call request from an assistant (LLM). -* Represents the assistant's request to use a tool. -* -* @deprecated Deprecated as of protocol version 2026-07-28 (SEP-2577); remains -* in the specification for at least twelve months. Migrate to calling LLM -* provider APIs directly. -*/ -const ToolUseContentSchema = schemas_object({ - type: literal("tool_use"), - name: schemas_string(), - id: schemas_string(), - input: schemas_record(schemas_string(), unknown()), - _meta: schemas_record(schemas_string(), unknown()).optional() -}); -/** -* The contents of a resource, embedded into a prompt or tool call result. -*/ -const EmbeddedResourceSchema = schemas_object({ - type: literal("resource"), - resource: schemas_union([TextResourceContentsSchema, BlobResourceContentsSchema]), - annotations: AnnotationsSchema.optional(), - _meta: schemas_record(schemas_string(), unknown()).optional() -}); -/** -* A resource that the server is capable of reading, included in a prompt or tool call result. -* -* Note: resource links returned by tools are not guaranteed to appear in the results of {@linkcode ListResourcesRequest | resources/list} requests. -*/ -const ResourceLinkSchema = ResourceSchema.extend({ type: literal("resource_link") }); -/** -* A content block that can be used in prompts and tool results. -*/ -const ContentBlockSchema = schemas_union([ - TextContentSchema, - ImageContentSchema, - AudioContentSchema, - ResourceLinkSchema, - EmbeddedResourceSchema -]); -/** -* Describes a message returned as part of a prompt. -*/ -const PromptMessageSchema = schemas_object({ - role: RoleSchema, - content: ContentBlockSchema -}); -/** -* The server's response to a {@linkcode GetPromptRequest | prompts/get} request from the client. -*/ -const GetPromptResultSchema = ResultSchema.extend({ - description: schemas_string().optional(), - messages: schemas_array(PromptMessageSchema) -}); -/** -* An optional notification from the server to the client, informing it that the list of prompts it offers has changed. This may be issued by servers without any previous subscription from the client. -*/ -const PromptListChangedNotificationSchema = NotificationSchema.extend({ - method: literal("notifications/prompts/list_changed"), - params: NotificationsParamsSchema.optional() -}); -/** -* Additional properties describing a `Tool` to clients. -* -* NOTE: all properties in {@linkcode ToolAnnotations} are **hints**. -* They are not guaranteed to provide a faithful description of -* tool behavior (including descriptive properties like `title`). -* -* Clients should never make tool use decisions based on `ToolAnnotations` -* received from untrusted servers. -*/ -const ToolAnnotationsSchema = schemas_object({ - title: schemas_string().optional(), - readOnlyHint: schemas_boolean().optional(), - destructiveHint: schemas_boolean().optional(), - idempotentHint: schemas_boolean().optional(), - openWorldHint: schemas_boolean().optional() -}); -/** -* Execution-related properties for a tool. -*/ -const ToolExecutionSchema = schemas_object({ taskSupport: schemas_enum([ - "required", - "optional", - "forbidden" -]).optional() }); -/** -* Definition for a tool the client can call. -*/ -const ToolSchema = schemas_object({ - ...BaseMetadataSchema.shape, - ...IconsSchema.shape, - description: schemas_string().optional(), - inputSchema: schemas_object({ - type: literal("object"), - properties: schemas_record(schemas_string(), JSONValueSchema).optional(), - required: schemas_array(schemas_string()).optional() - }).catchall(unknown()), - outputSchema: looseObject({ $schema: schemas_string().optional() }).optional(), - annotations: ToolAnnotationsSchema.optional(), - execution: ToolExecutionSchema.optional(), - _meta: schemas_record(schemas_string(), unknown()).optional() -}); -/** -* Sent from the client to request a list of tools the server has. -*/ -const ListToolsRequestSchema = PaginatedRequestSchema.extend({ method: literal("tools/list") }); -/** -* The server's response to a {@linkcode ListToolsRequest | tools/list} request from the client. -*/ -const ListToolsResultSchema = PaginatedResultSchema.extend({ tools: schemas_array(ToolSchema) }); -/** -* The server's response to a tool call. -*/ -const auth_CUe6YdwF_CallToolResultSchema = ResultSchema.extend({ - content: schemas_array(ContentBlockSchema).default([]), - structuredContent: unknown().optional(), - isError: schemas_boolean().optional() -}); -/** -* {@linkcode CallToolResultSchema} extended with backwards compatibility to protocol version 2024-10-07. -*/ -const CompatibilityCallToolResultSchema = auth_CUe6YdwF_CallToolResultSchema.or(ResultSchema.extend({ toolResult: unknown() })); -/** -* Parameters for a `tools/call` request. -*/ -const CallToolRequestParamsSchema = auth_CUe6YdwF_TaskAugmentedRequestParamsSchema.extend({ - name: schemas_string(), - arguments: schemas_record(schemas_string(), unknown()).optional() -}); -/** -* Used by the client to invoke a tool provided by the server. -*/ -const CallToolRequestSchema = RequestSchema.extend({ - method: literal("tools/call"), - params: CallToolRequestParamsSchema -}); -/** -* An optional notification from the server to the client, informing it that the list of tools it offers has changed. This may be issued by servers without any previous subscription from the client. -*/ -const ToolListChangedNotificationSchema = NotificationSchema.extend({ - method: literal("notifications/tools/list_changed"), - params: NotificationsParamsSchema.optional() -}); -/** -* Base schema for list changed subscription options (without callback). -* Used internally for Zod validation of `autoRefresh` and `debounceMs`. -*/ -const ListChangedOptionsBaseSchema = schemas_object({ - autoRefresh: schemas_boolean().default(true), - debounceMs: schemas_number().int().nonnegative().default(300) -}); -/** -* The severity of a log message. -* -* @deprecated Deprecated as of protocol version 2026-07-28 (SEP-2577); remains -* in the specification for at least twelve months. Migrate to stderr logging -* (STDIO servers) or OpenTelemetry. -*/ -const LoggingLevelSchema = schemas_enum([ - "debug", - "info", - "notice", - "warning", - "error", - "critical", - "alert", - "emergency" -]); -/** -* Parameters for a `logging/setLevel` request. -* -* @deprecated Deprecated as of protocol version 2026-07-28 (SEP-2577); remains -* in the specification for at least twelve months. Migrate to stderr logging -* (STDIO servers) or OpenTelemetry. -*/ -const SetLevelRequestParamsSchema = BaseRequestParamsSchema.extend({ level: LoggingLevelSchema }); -/** -* A request from the client to the server, to enable or adjust logging. -* -* @deprecated Deprecated as of protocol version 2026-07-28 (SEP-2577); remains -* in the specification for at least twelve months. Migrate to stderr logging -* (STDIO servers) or OpenTelemetry. -*/ -const SetLevelRequestSchema = RequestSchema.extend({ - method: literal("logging/setLevel"), - params: SetLevelRequestParamsSchema -}); -/** -* Parameters for a `notifications/message` notification. -* -* @deprecated Deprecated as of protocol version 2026-07-28 (SEP-2577); remains -* in the specification for at least twelve months. Migrate to stderr logging -* (STDIO servers) or OpenTelemetry. -*/ -const LoggingMessageNotificationParamsSchema = NotificationsParamsSchema.extend({ - level: LoggingLevelSchema, - logger: schemas_string().optional(), - data: unknown() -}); -/** -* Notification of a log message passed from server to client. If no `logging/setLevel` request has been sent from the client, the server MAY decide which messages to send automatically. -* -* @deprecated Deprecated as of protocol version 2026-07-28 (SEP-2577); remains -* in the specification for at least twelve months. Migrate to stderr logging -* (STDIO servers) or OpenTelemetry. -*/ -const LoggingMessageNotificationSchema = NotificationSchema.extend({ - method: literal("notifications/message"), - params: LoggingMessageNotificationParamsSchema -}); -/** -* Hints to use for model selection. -* -* @deprecated Deprecated as of protocol version 2026-07-28 (SEP-2577); remains -* in the specification for at least twelve months. Migrate to calling LLM -* provider APIs directly. -*/ -const ModelHintSchema = schemas_object({ name: schemas_string().optional() }); -/** -* The server's preferences for model selection, requested of the client during sampling. -* -* @deprecated Deprecated as of protocol version 2026-07-28 (SEP-2577); remains -* in the specification for at least twelve months. Migrate to calling LLM -* provider APIs directly. -*/ -const ModelPreferencesSchema = schemas_object({ - hints: schemas_array(ModelHintSchema).optional(), - costPriority: schemas_number().min(0).max(1).optional(), - speedPriority: schemas_number().min(0).max(1).optional(), - intelligencePriority: schemas_number().min(0).max(1).optional() -}); -/** -* Controls tool usage behavior in sampling requests. -* -* @deprecated Deprecated as of protocol version 2026-07-28 (SEP-2577); remains -* in the specification for at least twelve months. Migrate to calling LLM -* provider APIs directly. -*/ -const ToolChoiceSchema = schemas_object({ mode: schemas_enum([ - "auto", - "required", - "none" -]).optional() }); -/** -* The result of a tool execution, provided by the user (server). -* Represents the outcome of invoking a tool requested via `ToolUseContent`. -* -* @deprecated Deprecated as of protocol version 2026-07-28 (SEP-2577); remains -* in the specification for at least twelve months. Migrate to calling LLM -* provider APIs directly. -*/ -const ToolResultContentSchema = schemas_object({ - type: literal("tool_result"), - toolUseId: schemas_string().describe("The unique identifier for the corresponding tool call."), - content: schemas_array(ContentBlockSchema), - structuredContent: unknown().optional(), - isError: schemas_boolean().optional(), - _meta: schemas_record(schemas_string(), unknown()).optional() -}); -/** -* Basic content types for sampling responses (without tool use). -* Used for backwards-compatible {@linkcode CreateMessageResult} when tools are not used. -* -* @deprecated Deprecated as of protocol version 2026-07-28 (SEP-2577); remains -* in the specification for at least twelve months. Migrate to calling LLM -* provider APIs directly. -*/ -const SamplingContentSchema = discriminatedUnion("type", [ - TextContentSchema, - ImageContentSchema, - AudioContentSchema -]); -/** -* Content block types allowed in sampling messages. -* This includes text, image, audio, tool use requests, and tool results. -* -* @deprecated Deprecated as of protocol version 2026-07-28 (SEP-2577); remains -* in the specification for at least twelve months. Migrate to calling LLM -* provider APIs directly. -*/ -const SamplingMessageContentBlockSchema = discriminatedUnion("type", [ - TextContentSchema, - ImageContentSchema, - AudioContentSchema, - ToolUseContentSchema, - ToolResultContentSchema -]); -/** -* Describes a message issued to or received from an LLM API. -* -* @deprecated Deprecated as of protocol version 2026-07-28 (SEP-2577); remains -* in the specification for at least twelve months. Migrate to calling LLM -* provider APIs directly. -*/ -const SamplingMessageSchema = schemas_object({ - role: RoleSchema, - content: schemas_union([SamplingMessageContentBlockSchema, schemas_array(SamplingMessageContentBlockSchema)]), - _meta: schemas_record(schemas_string(), unknown()).optional() -}); -/** -* Parameters for a `sampling/createMessage` request. -* -* @deprecated Deprecated as of protocol version 2026-07-28 (SEP-2577); remains -* in the specification for at least twelve months. Migrate to calling LLM -* provider APIs directly. -*/ -const CreateMessageRequestParamsSchema = auth_CUe6YdwF_TaskAugmentedRequestParamsSchema.extend({ - messages: schemas_array(SamplingMessageSchema), - modelPreferences: ModelPreferencesSchema.optional(), - systemPrompt: schemas_string().optional(), - includeContext: schemas_enum([ - "none", - "thisServer", - "allServers" - ]).optional(), - temperature: schemas_number().optional(), - maxTokens: schemas_number().int(), - stopSequences: schemas_array(schemas_string()).optional(), - metadata: JSONObjectSchema.optional(), - tools: schemas_array(ToolSchema).optional(), - toolChoice: ToolChoiceSchema.optional() -}); -/** -* A request from the server to sample an LLM via the client. The client has full discretion over which model to select. The client should also inform the user before beginning sampling, to allow them to inspect the request (human in the loop) and decide whether to approve it. -* -* @deprecated Deprecated as of protocol version 2026-07-28 (SEP-2577); remains -* in the specification for at least twelve months. Migrate to calling LLM -* provider APIs directly. -*/ -const CreateMessageRequestSchema = RequestSchema.extend({ - method: literal("sampling/createMessage"), - params: CreateMessageRequestParamsSchema -}); -/** -* The client's response to a `sampling/create_message` request from the server. -* This is the backwards-compatible version that returns single content (no arrays). -* Used when the request does not include tools. -* -* @deprecated Deprecated as of protocol version 2026-07-28 (SEP-2577); remains -* in the specification for at least twelve months. Migrate to calling LLM -* provider APIs directly. -*/ -const CreateMessageResultSchema = ResultSchema.extend({ - model: schemas_string(), - stopReason: schemas_optional(schemas_enum([ - "endTurn", - "stopSequence", - "maxTokens" - ]).or(schemas_string())), - role: RoleSchema, - content: SamplingContentSchema -}); -/** -* The client's response to a `sampling/create_message` request when tools were provided. -* This version supports array content for tool use flows. -* -* @deprecated Deprecated as of protocol version 2026-07-28 (SEP-2577); remains -* in the specification for at least twelve months. Migrate to calling LLM -* provider APIs directly. -*/ -const CreateMessageResultWithToolsSchema = ResultSchema.extend({ - model: schemas_string(), - stopReason: schemas_optional(schemas_enum([ - "endTurn", - "stopSequence", - "maxTokens", - "toolUse" - ]).or(schemas_string())), - role: RoleSchema, - content: schemas_union([SamplingMessageContentBlockSchema, schemas_array(SamplingMessageContentBlockSchema)]) -}); -/** -* Primitive schema definition for boolean fields. -*/ -const BooleanSchemaSchema = schemas_object({ - type: literal("boolean"), - title: schemas_string().optional(), - description: schemas_string().optional(), - default: schemas_boolean().optional() -}); -/** -* Primitive schema definition for string fields. -*/ -const StringSchemaSchema = schemas_object({ - type: literal("string"), - title: schemas_string().optional(), - description: schemas_string().optional(), - minLength: schemas_number().optional(), - maxLength: schemas_number().optional(), - format: schemas_enum([ - "email", - "uri", - "date", - "date-time" - ]).optional(), - default: schemas_string().optional() -}); -/** -* Primitive schema definition for number fields. -*/ -const NumberSchemaSchema = schemas_object({ - type: schemas_enum(["number", "integer"]), - title: schemas_string().optional(), - description: schemas_string().optional(), - minimum: schemas_number().optional(), - maximum: schemas_number().optional(), - default: schemas_number().optional() -}); -/** -* Schema for single-selection enumeration without display titles for options. -*/ -const UntitledSingleSelectEnumSchemaSchema = schemas_object({ - type: literal("string"), - title: schemas_string().optional(), - description: schemas_string().optional(), - enum: schemas_array(schemas_string()), - default: schemas_string().optional() -}); -/** -* Schema for single-selection enumeration with display titles for each option. -*/ -const TitledSingleSelectEnumSchemaSchema = schemas_object({ - type: literal("string"), - title: schemas_string().optional(), - description: schemas_string().optional(), - oneOf: schemas_array(schemas_object({ - const: schemas_string(), - title: schemas_string() - })), - default: schemas_string().optional() -}); -/** -* Use {@linkcode TitledSingleSelectEnumSchema} instead. -* This interface will be removed in a future version. -*/ -const LegacyTitledEnumSchemaSchema = schemas_object({ - type: literal("string"), - title: schemas_string().optional(), - description: schemas_string().optional(), - enum: schemas_array(schemas_string()), - enumNames: schemas_array(schemas_string()).optional(), - default: schemas_string().optional() -}); -const SingleSelectEnumSchemaSchema = schemas_union([UntitledSingleSelectEnumSchemaSchema, TitledSingleSelectEnumSchemaSchema]); -/** -* Schema for multiple-selection enumeration without display titles for options. -*/ -const UntitledMultiSelectEnumSchemaSchema = schemas_object({ - type: literal("array"), - title: schemas_string().optional(), - description: schemas_string().optional(), - minItems: schemas_number().optional(), - maxItems: schemas_number().optional(), - items: schemas_object({ - type: literal("string"), - enum: schemas_array(schemas_string()) - }), - default: schemas_array(schemas_string()).optional() -}); -/** -* Schema for multiple-selection enumeration with display titles for each option. -*/ -const TitledMultiSelectEnumSchemaSchema = schemas_object({ - type: literal("array"), - title: schemas_string().optional(), - description: schemas_string().optional(), - minItems: schemas_number().optional(), - maxItems: schemas_number().optional(), - items: schemas_object({ anyOf: schemas_array(schemas_object({ - const: schemas_string(), - title: schemas_string() - })) }), - default: schemas_array(schemas_string()).optional() -}); -/** -* Combined schema for multiple-selection enumeration -*/ -const MultiSelectEnumSchemaSchema = schemas_union([UntitledMultiSelectEnumSchemaSchema, TitledMultiSelectEnumSchemaSchema]); -/** -* Primitive schema definition for enum fields. -*/ -const EnumSchemaSchema = schemas_union([ - LegacyTitledEnumSchemaSchema, - SingleSelectEnumSchemaSchema, - MultiSelectEnumSchemaSchema -]); -/** -* Union of all primitive schema definitions. -*/ -const PrimitiveSchemaDefinitionSchema = schemas_union([ - EnumSchemaSchema, - BooleanSchemaSchema, - StringSchemaSchema, - NumberSchemaSchema -]); -/** -* Parameters for an `elicitation/create` request for form-based elicitation. -*/ -const ElicitRequestFormParamsSchema = auth_CUe6YdwF_TaskAugmentedRequestParamsSchema.extend({ - mode: literal("form").optional(), - message: schemas_string(), - requestedSchema: schemas_object({ - type: literal("object"), - properties: schemas_record(schemas_string(), PrimitiveSchemaDefinitionSchema), - required: schemas_array(schemas_string()).optional() - }).catchall(unknown()) -}); -/** -* Parameters for an {@linkcode ElicitRequest | elicitation/create} request for URL-based elicitation. -*/ -const ElicitRequestURLParamsSchema = auth_CUe6YdwF_TaskAugmentedRequestParamsSchema.extend({ - mode: literal("url"), - message: schemas_string(), - elicitationId: schemas_string(), - url: schemas_string().url() -}); -/** -* The parameters for a request to elicit additional information from the user via the client. -*/ -const ElicitRequestParamsSchema = schemas_union([ElicitRequestFormParamsSchema, ElicitRequestURLParamsSchema]); -/** -* A request from the server to elicit user input via the client. -* The client should present the message and form fields to the user (form mode) -* or navigate to a URL (URL mode). -*/ -const ElicitRequestSchema = RequestSchema.extend({ - method: literal("elicitation/create"), - params: ElicitRequestParamsSchema -}); -/** -* Parameters for a {@linkcode ElicitationCompleteNotification | notifications/elicitation/complete} notification. -* -* @deprecated Removed from the spec by #2891 (2026-07-28). The client learns the outcome -* of an out-of-band interaction by retrying the original request; no server-initiated -* completion signal exists in the 2026-07-28 revision. Kept here for the 2025-era flow -* only. The 2026-07-28 wire codec excludes this notification. -* @category notifications/elicitation/complete -*/ -const ElicitationCompleteNotificationParamsSchema = NotificationsParamsSchema.extend({ elicitationId: schemas_string() }); -/** -* A notification from the server to the client, informing it of a completion of an out-of-band elicitation request. -* -* @deprecated Removed from the spec by #2891 (2026-07-28). The client learns the outcome -* of an out-of-band interaction by retrying the original request; no server-initiated -* completion signal exists in the 2026-07-28 revision. Kept here for the 2025-era flow -* only. The 2026-07-28 wire codec excludes this notification. -* @category notifications/elicitation/complete -*/ -const ElicitationCompleteNotificationSchema = NotificationSchema.extend({ - method: literal("notifications/elicitation/complete"), - params: ElicitationCompleteNotificationParamsSchema -}); -/** -* The client's response to an {@linkcode ElicitRequest | elicitation/create} request from the server. -*/ -const ElicitResultSchema = ResultSchema.extend({ - action: schemas_enum([ - "accept", - "decline", - "cancel" - ]), - content: preprocess((val) => val === null ? void 0 : val, schemas_record(schemas_string(), schemas_union([ - schemas_string(), - schemas_number(), - schemas_boolean(), - schemas_array(schemas_string()) - ])).optional()) -}); -/** -* A reference to a resource or resource template definition. -*/ -const ResourceTemplateReferenceSchema = schemas_object({ - type: literal("ref/resource"), - uri: schemas_string() -}); -/** -* Identifies a prompt. -*/ -const PromptReferenceSchema = schemas_object({ - type: literal("ref/prompt"), - name: schemas_string() -}); -/** -* Parameters for a {@linkcode CompleteRequest | completion/complete} request. -*/ -const CompleteRequestParamsSchema = BaseRequestParamsSchema.extend({ - ref: schemas_union([PromptReferenceSchema, ResourceTemplateReferenceSchema]), - argument: schemas_object({ - name: schemas_string(), - value: schemas_string() - }), - context: schemas_object({ arguments: schemas_record(schemas_string(), schemas_string()).optional() }).optional() -}); -/** -* A request from the client to the server, to ask for completion options. -*/ -const CompleteRequestSchema = RequestSchema.extend({ - method: literal("completion/complete"), - params: CompleteRequestParamsSchema -}); -/** -* The server's response to a {@linkcode CompleteRequest | completion/complete} request -*/ -const CompleteResultSchema = ResultSchema.extend({ completion: looseObject({ - values: schemas_array(schemas_string()).max(100), - total: schemas_optional(schemas_number().int()), - hasMore: schemas_optional(schemas_boolean()) -}) }); -/** -* Represents a root directory or file that the server can operate on. -* -* @deprecated Deprecated as of protocol version 2026-07-28 (SEP-2577); remains -* in the specification for at least twelve months. Migrate to passing paths via -* tool parameters, resource URIs, or configuration. -*/ -const RootSchema = schemas_object({ - uri: schemas_string().startsWith("file://"), - name: schemas_string().optional(), - _meta: schemas_record(schemas_string(), unknown()).optional() -}); -/** -* Sent from the server to request a list of root URIs from the client. -* -* @deprecated Deprecated as of protocol version 2026-07-28 (SEP-2577); remains -* in the specification for at least twelve months. Migrate to passing paths via -* tool parameters, resource URIs, or configuration. -*/ -const ListRootsRequestSchema = RequestSchema.extend({ - method: literal("roots/list"), - params: BaseRequestParamsSchema.optional() -}); -/** -* The client's response to a `roots/list` request from the server. -* -* @deprecated Deprecated as of protocol version 2026-07-28 (SEP-2577); remains -* in the specification for at least twelve months. Migrate to passing paths via -* tool parameters, resource URIs, or configuration. -*/ -const ListRootsResultSchema = ResultSchema.extend({ roots: schemas_array(RootSchema) }); -/** -* A notification from the client to the server, informing it that the list of roots has changed. -* -* @deprecated Deprecated as of protocol version 2026-07-28 (SEP-2577); remains -* in the specification for at least twelve months. Migrate to passing paths via -* tool parameters, resource URIs, or configuration. -*/ -const RootsListChangedNotificationSchema = NotificationSchema.extend({ - method: literal("notifications/roots/list_changed"), - params: NotificationsParamsSchema.optional() -}); -/** -* Task creation parameters, used to ask that the server create a task to represent a request. -* -* @deprecated 2025-11-25 wire vocabulary with no SDK runtime; kept importable for interoperability only. -*/ -const TaskCreationParamsSchema = looseObject({ - ttl: schemas_number().optional(), - pollInterval: schemas_number().optional() -}); -/** -* The status of a task. -* -* @deprecated 2025-11-25 wire vocabulary with no SDK runtime; kept importable for interoperability only. -*/ -const TaskStatusSchema = schemas_enum([ - "working", - "input_required", - "completed", - "failed", - "cancelled" -]); -/** -* A pollable state object associated with a request. -* -* @deprecated 2025-11-25 wire vocabulary with no SDK runtime; kept importable for interoperability only. -*/ -const TaskSchema = schemas_object({ - taskId: schemas_string(), - status: TaskStatusSchema, - ttl: schemas_union([schemas_number(), schemas_null()]), - createdAt: schemas_string(), - lastUpdatedAt: schemas_string(), - pollInterval: schemas_optional(schemas_number()), - statusMessage: schemas_optional(schemas_string()) -}); -/** -* Result returned when a task is created, containing the task data wrapped in a `task` field. -* -* @deprecated 2025-11-25 wire vocabulary with no SDK runtime; kept importable for interoperability only. -*/ -const CreateTaskResultSchema = ResultSchema.extend({ task: TaskSchema }); -/** -* Parameters for task status notification. -* -* @deprecated 2025-11-25 wire vocabulary with no SDK runtime; kept importable for interoperability only. -*/ -const TaskStatusNotificationParamsSchema = NotificationsParamsSchema.merge(TaskSchema); -/** -* A notification sent when a task's status changes. -* -* @deprecated 2025-11-25 wire vocabulary with no SDK runtime; kept importable for interoperability only. -*/ -const TaskStatusNotificationSchema = NotificationSchema.extend({ - method: literal("notifications/tasks/status"), - params: TaskStatusNotificationParamsSchema -}); -/** -* A request to get the state of a specific task. -* -* @deprecated 2025-11-25 wire vocabulary with no SDK runtime; kept importable for interoperability only. -*/ -const GetTaskRequestSchema = RequestSchema.extend({ - method: literal("tasks/get"), - params: BaseRequestParamsSchema.extend({ taskId: schemas_string() }) -}); -/** -* The response to a {@linkcode GetTaskRequest | tasks/get} request. -* -* @deprecated 2025-11-25 wire vocabulary with no SDK runtime; kept importable for interoperability only. -*/ -const GetTaskResultSchema = ResultSchema.merge(TaskSchema); -/** -* A request to get the result of a specific task. -* -* @deprecated 2025-11-25 wire vocabulary with no SDK runtime; kept importable for interoperability only. -*/ -const GetTaskPayloadRequestSchema = RequestSchema.extend({ - method: literal("tasks/result"), - params: BaseRequestParamsSchema.extend({ taskId: schemas_string() }) -}); -/** -* The response to a `tasks/result` request. -* The structure matches the result type of the original request. -* For example, a {@linkcode CallToolRequest | tools/call} task would return the `CallToolResult` structure. -* -* -* @deprecated 2025-11-25 wire vocabulary with no SDK runtime; kept importable for interoperability only. -*/ -const GetTaskPayloadResultSchema = ResultSchema.loose(); -/** -* A request to list tasks. -* -* @deprecated 2025-11-25 wire vocabulary with no SDK runtime; kept importable for interoperability only. -*/ -const ListTasksRequestSchema = PaginatedRequestSchema.extend({ method: literal("tasks/list") }); -/** -* The response to a {@linkcode ListTasksRequest | tasks/list} request. -* -* @deprecated 2025-11-25 wire vocabulary with no SDK runtime; kept importable for interoperability only. -*/ -const ListTasksResultSchema = PaginatedResultSchema.extend({ tasks: schemas_array(TaskSchema) }); -/** -* A request to cancel a specific task. -* -* @deprecated 2025-11-25 wire vocabulary with no SDK runtime; kept importable for interoperability only. -*/ -const CancelTaskRequestSchema = RequestSchema.extend({ - method: literal("tasks/cancel"), - params: BaseRequestParamsSchema.extend({ taskId: schemas_string() }) -}); -/** -* The response to a {@linkcode CancelTaskRequest | tasks/cancel} request. -* -* @deprecated 2025-11-25 wire vocabulary with no SDK runtime; kept importable for interoperability only. -*/ -const CancelTaskResultSchema = ResultSchema.merge(TaskSchema); -const ClientRequestSchema = schemas_union([ - PingRequestSchema, - auth_CUe6YdwF_InitializeRequestSchema, - DiscoverRequestSchema, - CompleteRequestSchema, - SetLevelRequestSchema, - GetPromptRequestSchema, - ListPromptsRequestSchema, - ListResourcesRequestSchema, - ListResourceTemplatesRequestSchema, - ReadResourceRequestSchema, - SubscribeRequestSchema, - UnsubscribeRequestSchema, - SubscriptionsListenRequestSchema, - CallToolRequestSchema, - ListToolsRequestSchema -]); -const ClientNotificationSchema = schemas_union([ - CancelledNotificationSchema, - ProgressNotificationSchema, - auth_CUe6YdwF_InitializedNotificationSchema, - RootsListChangedNotificationSchema -]); -const ClientResultSchema = schemas_union([ - EmptyResultSchema, - CreateMessageResultSchema, - CreateMessageResultWithToolsSchema, - ElicitResultSchema, - ListRootsResultSchema -]); -const ServerRequestSchema = schemas_union([ - PingRequestSchema, - CreateMessageRequestSchema, - ElicitRequestSchema, - ListRootsRequestSchema -]); -const ServerNotificationSchema = schemas_union([ - CancelledNotificationSchema, - ProgressNotificationSchema, - LoggingMessageNotificationSchema, - ResourceUpdatedNotificationSchema, - ResourceListChangedNotificationSchema, - ToolListChangedNotificationSchema, - PromptListChangedNotificationSchema, - SubscriptionsAcknowledgedNotificationSchema, - ElicitationCompleteNotificationSchema -]); -const ServerResultSchema = schemas_union([ - EmptyResultSchema, - InitializeResultSchema, - DiscoverResultSchema, - CompleteResultSchema, - GetPromptResultSchema, - ListPromptsResultSchema, - ListResourcesResultSchema, - ListResourceTemplatesResultSchema, - ReadResourceResultSchema, - auth_CUe6YdwF_CallToolResultSchema, - ListToolsResultSchema, - SubscriptionsListenResultSchema -]); - -//#endregion -//#region src/auth.ts -/** -* Reusable URL validation that disallows `javascript:` scheme -*/ -const SafeUrlSchema = schemas_url().superRefine((val, ctx) => { - if (!URL.canParse(val)) { - ctx.addIssue({ - code: ZodIssueCode.custom, - message: "URL must be parseable", - fatal: true - }); - return NEVER; - } -}).refine((url) => { - const u = new URL(url); - return u.protocol !== "javascript:" && u.protocol !== "data:" && u.protocol !== "vbscript:"; -}, { message: "URL cannot use javascript:, data:, or vbscript: scheme" }); -/** -* RFC 9728 OAuth Protected Resource Metadata -*/ -const OAuthProtectedResourceMetadataSchema = looseObject({ - resource: schemas_string().url(), - authorization_servers: schemas_array(SafeUrlSchema).optional(), - jwks_uri: schemas_string().url().optional(), - scopes_supported: schemas_array(schemas_string()).optional(), - bearer_methods_supported: schemas_array(schemas_string()).optional(), - resource_signing_alg_values_supported: schemas_array(schemas_string()).optional(), - resource_name: schemas_string().optional(), - resource_documentation: schemas_string().optional(), - resource_policy_uri: schemas_string().url().optional(), - resource_tos_uri: schemas_string().url().optional(), - tls_client_certificate_bound_access_tokens: schemas_boolean().optional(), - authorization_details_types_supported: schemas_array(schemas_string()).optional(), - dpop_signing_alg_values_supported: schemas_array(schemas_string()).optional(), - dpop_bound_access_tokens_required: schemas_boolean().optional() -}); -/** -* RFC 8414 OAuth 2.0 Authorization Server Metadata -*/ -const OAuthMetadataSchema = looseObject({ - issuer: schemas_string(), - authorization_endpoint: SafeUrlSchema, - token_endpoint: SafeUrlSchema, - registration_endpoint: SafeUrlSchema.optional(), - scopes_supported: schemas_array(schemas_string()).optional(), - response_types_supported: schemas_array(schemas_string()), - response_modes_supported: schemas_array(schemas_string()).optional(), - grant_types_supported: schemas_array(schemas_string()).optional(), - token_endpoint_auth_methods_supported: schemas_array(schemas_string()).optional(), - token_endpoint_auth_signing_alg_values_supported: schemas_array(schemas_string()).optional(), - service_documentation: SafeUrlSchema.optional(), - revocation_endpoint: SafeUrlSchema.optional(), - revocation_endpoint_auth_methods_supported: schemas_array(schemas_string()).optional(), - revocation_endpoint_auth_signing_alg_values_supported: schemas_array(schemas_string()).optional(), - introspection_endpoint: schemas_string().optional(), - introspection_endpoint_auth_methods_supported: schemas_array(schemas_string()).optional(), - introspection_endpoint_auth_signing_alg_values_supported: schemas_array(schemas_string()).optional(), - code_challenge_methods_supported: schemas_array(schemas_string()).optional(), - client_id_metadata_document_supported: schemas_boolean().optional(), - authorization_response_iss_parameter_supported: schemas_boolean().optional().catch(void 0) -}); -/** -* OpenID Connect Discovery 1.0 Provider Metadata -* -* @see https://openid.net/specs/openid-connect-discovery-1_0.html#ProviderMetadata -*/ -const OpenIdProviderMetadataSchema = looseObject({ - issuer: schemas_string(), - authorization_endpoint: SafeUrlSchema, - token_endpoint: SafeUrlSchema, - userinfo_endpoint: SafeUrlSchema.optional(), - jwks_uri: SafeUrlSchema, - registration_endpoint: SafeUrlSchema.optional(), - scopes_supported: schemas_array(schemas_string()).optional(), - response_types_supported: schemas_array(schemas_string()), - response_modes_supported: schemas_array(schemas_string()).optional(), - grant_types_supported: schemas_array(schemas_string()).optional(), - acr_values_supported: schemas_array(schemas_string()).optional(), - subject_types_supported: schemas_array(schemas_string()), - id_token_signing_alg_values_supported: schemas_array(schemas_string()), - id_token_encryption_alg_values_supported: schemas_array(schemas_string()).optional(), - id_token_encryption_enc_values_supported: schemas_array(schemas_string()).optional(), - userinfo_signing_alg_values_supported: schemas_array(schemas_string()).optional(), - userinfo_encryption_alg_values_supported: schemas_array(schemas_string()).optional(), - userinfo_encryption_enc_values_supported: schemas_array(schemas_string()).optional(), - request_object_signing_alg_values_supported: schemas_array(schemas_string()).optional(), - request_object_encryption_alg_values_supported: schemas_array(schemas_string()).optional(), - request_object_encryption_enc_values_supported: schemas_array(schemas_string()).optional(), - token_endpoint_auth_methods_supported: schemas_array(schemas_string()).optional(), - token_endpoint_auth_signing_alg_values_supported: schemas_array(schemas_string()).optional(), - display_values_supported: schemas_array(schemas_string()).optional(), - claim_types_supported: schemas_array(schemas_string()).optional(), - claims_supported: schemas_array(schemas_string()).optional(), - service_documentation: schemas_string().optional(), - claims_locales_supported: schemas_array(schemas_string()).optional(), - ui_locales_supported: schemas_array(schemas_string()).optional(), - claims_parameter_supported: schemas_boolean().optional(), - request_parameter_supported: schemas_boolean().optional(), - request_uri_parameter_supported: schemas_boolean().optional(), - require_request_uri_registration: schemas_boolean().optional(), - op_policy_uri: SafeUrlSchema.optional(), - op_tos_uri: SafeUrlSchema.optional(), - client_id_metadata_document_supported: schemas_boolean().optional(), - authorization_response_iss_parameter_supported: schemas_boolean().optional().catch(void 0) -}); -/** -* OpenID Connect Discovery metadata that may include OAuth 2.0 fields -* This schema represents the real-world scenario where OIDC providers -* return a mix of OpenID Connect and OAuth 2.0 metadata fields -*/ -const OpenIdProviderDiscoveryMetadataSchema = schemas_object({ - ...OpenIdProviderMetadataSchema.shape, - ...OAuthMetadataSchema.pick({ code_challenge_methods_supported: true }).shape -}); -/** -* OAuth 2.1 token response -*/ -const OAuthTokensSchema = schemas_object({ - access_token: schemas_string(), - id_token: schemas_string().optional(), - token_type: schemas_string(), - expires_in: coerce_number().optional(), - scope: schemas_string().optional(), - refresh_token: schemas_string().optional() -}).strip(); -/** -* RFC 8693 §2.2.1 Token Exchange response for ID-JAG tokens. -* -* `token_type` is intentionally optional: per RFC 8693 §2.2.1 it is informational when -* the issued token is not an access token, and per RFC 6749 §5.1 it is case-insensitive, -* so strict checking rejects conformant IdPs. -*/ -const IdJagTokenExchangeResponseSchema = schemas_object({ - issued_token_type: literal("urn:ietf:params:oauth:token-type:id-jag"), - access_token: schemas_string(), - token_type: schemas_string().optional(), - expires_in: schemas_number().optional(), - scope: schemas_string().optional() -}).strip(); -/** -* OAuth 2.1 error response -*/ -const OAuthErrorResponseSchema = schemas_object({ - error: schemas_string(), - error_description: schemas_string().optional(), - error_uri: schemas_string().optional() -}); -/** -* Optional version of {@linkcode SafeUrlSchema} that allows empty string for backward compatibility on `tos_uri` and `logo_uri` -*/ -const OptionalSafeUrlSchema = SafeUrlSchema.optional().or(literal("").transform(() => void 0)); -/** -* RFC 7591 OAuth 2.0 Dynamic Client Registration metadata -*/ -const OAuthClientMetadataSchema = schemas_object({ - redirect_uris: schemas_array(SafeUrlSchema), - token_endpoint_auth_method: schemas_string().optional(), - grant_types: schemas_array(schemas_string()).optional(), - response_types: schemas_array(schemas_string()).optional(), - application_type: schemas_string().optional(), - client_name: schemas_string().optional(), - client_uri: SafeUrlSchema.optional(), - logo_uri: OptionalSafeUrlSchema, - scope: schemas_string().optional(), - contacts: schemas_array(schemas_string()).optional(), - tos_uri: OptionalSafeUrlSchema, - policy_uri: schemas_string().optional(), - jwks_uri: SafeUrlSchema.optional(), - jwks: any().optional(), - software_id: schemas_string().optional(), - software_version: schemas_string().optional(), - software_statement: schemas_string().optional() -}).strip(); -/** -* RFC 7591 OAuth 2.0 Dynamic Client Registration client information -*/ -const OAuthClientInformationSchema = schemas_object({ - client_id: schemas_string(), - client_secret: schemas_string().optional(), - client_id_issued_at: schemas_number().optional(), - client_secret_expires_at: schemas_number().optional() -}).strip(); -/** -* RFC 7591 OAuth 2.0 Dynamic Client Registration full response (client information plus metadata) -*/ -const OAuthClientInformationFullSchema = OAuthClientMetadataSchema.merge(OAuthClientInformationSchema); -/** -* RFC 7591 OAuth 2.0 Dynamic Client Registration error response -*/ -const OAuthClientRegistrationErrorSchema = schemas_object({ - error: schemas_string(), - error_description: schemas_string().optional() -}).strip(); -/** -* RFC 7009 OAuth 2.0 Token Revocation request -*/ -const OAuthTokenRevocationRequestSchema = schemas_object({ - token: schemas_string(), - token_type_hint: schemas_string().optional() -}).strip(); - -//#endregion - -//# sourceMappingURL=auth-CUe6YdwF.mjs.map - - - - - - - - -//#region ../core-internal/src/errors/crossBundleBrand.ts -/** -* Cross-bundle `instanceof` support for the SDK error classes. -* -* `@modelcontextprotocol/client` and `@modelcontextprotocol/server` each bundle their -* own copy of `core-internal`, so an error constructed by one package fails a -* prototype-identity `instanceof` against the same class re-exported by the other — -* exactly the check a dual-role process (gateway, host, in-process test) writes. -* -* Instead of prototype identity, branded classes stamp every instance with the brand -* strings of its class chain under a registry symbol (`Symbol.for`, shared across -* bundles and realms), and resolve `instanceof` via `Symbol.hasInstance` against the -* brand set. Ordinary prototype-based `instanceof` is kept as a fallback so behavior -* is unchanged for anything unbranded. -* -* A class participates by defining an **own** `mcpBrand` static (via a `static {}` -* block, so nothing reaches the declaration files — a declared `protected static` -* field would make the constructor types nominally incompatible across the bundled -* copies) and (for hierarchy roots) installing {@linkcode brandedHasInstance} as -* `Symbol.hasInstance`. User-defined subclasses that do not declare their own brand -* keep plain prototype semantics — a foreign base-class instance never satisfies -* `instanceof UserSubclass`. -* -* Prior art — the same stamp-and-hook shape ships at scale elsewhere: Node core -* (stream.Writable since 2017, Console via a marker symbol, diagnostics_channel), -* undici's whole error hierarchy (vendored into Node as fetch), googleapis/gaxios -* (GaxiosError, Symbol.for marker), AWS SDK v3's ServiceException (which pairs a -* Symbol.hasInstance override with a static isInstance guard, as we do), and zod v4 -* (Symbol.hasInstance on every schema class for cross-version interop). -* -* Contract notes: -* - Participation criterion: **every error class exported from a public package that -* callers are documented to `instanceof` must be branded.** The per-package -* errorBrandConformance tests walk the export surfaces and fail naming any -* exported Error subclass that has not opted in. -* - Brands assert **identity, not shape**: brand strings are version-less, so an -* instance from one SDK version matches the class of another. Members added to a -* branded class in a later version may be absent on a matched instance — read -* fields defensively, and treat branded classes as additive-only. The escape -* hatch when a release must break a branded class's read contract: change that -* class's brand string in the same release, which cleanly severs cross-version -* matching for that class. The per-package brand pins make the rename -* deliberate: errorSurfacePins.test.ts owns the core-internal brands, and each -* package's errorBrandConformance test pins its package-local ones. -* - Cross-bundle matching requires **both** copies to be at or after the release -* that introduced branding; against an older copy, behavior degrades to plain -* prototype `instanceof` in both directions. -* - A consumer re-bundling the SDK with property mangling (`mangle.props`) would -* break the brand statics; default esbuild/webpack/terser settings do not. -*/ -/** Registry symbol — identical across bundled copies and realms. */ -const BRANDS = Symbol.for("mcp.sdk.errorBrands"); -/** -* Stamp `instance` with the brand of every class in `ctor`'s chain that declares an -* own `mcpBrand`. Call once from the hierarchy root's constructor with `new.target` — -* subclasses inherit the stamping without touching their constructors. -* -* Constructor-time only: never stamp arbitrary objects. A stamped non-instance would -* satisfy `instanceof` while lacking the prototype members (getters like `.status`) -* that callers reach for after the check. -*/ -function stampErrorBrands(instance, ctor) { - const brands = /* @__PURE__ */ new Set(); - let current = ctor; - while (typeof current === "function") { - const brand = current.mcpBrand; - if (Object.prototype.hasOwnProperty.call(current, "mcpBrand") && typeof brand === "string") brands.add(brand); - current = Object.getPrototypeOf(current); - } - if (brands.size === 0) return; - Object.defineProperty(instance, BRANDS, { - value: brands, - enumerable: false, - configurable: true - }); -} -/** -* `Symbol.hasInstance` implementation for branded hierarchy roots. Matches when the -* value carries the **own** brand of the class being tested against (cross-bundle -* path), falling back to ordinary prototype-based `instanceof` otherwise. -*/ -function brandedHasInstance(cls, value) { - try { - if (typeof value === "object" && value !== null && Object.prototype.hasOwnProperty.call(cls, "mcpBrand") && typeof cls.mcpBrand === "string" && Object.prototype.hasOwnProperty.call(value, BRANDS)) { - const carried = value[BRANDS]; - if (carried && typeof carried.has === "function" && carried.has(cls.mcpBrand)) return true; - } - } catch {} - return Function.prototype[Symbol.hasInstance].call(cls, value); -} - -//#endregion -//#region ../core-internal/src/auth/errors.ts -/** -* OAuth error codes as defined by {@link https://datatracker.ietf.org/doc/html/rfc6749#section-5.2 | RFC 6749} -* and extensions. -*/ -let src_CX2iR2pK_OAuthErrorCode = /* @__PURE__ */ (/* unused pure expression or super */ null && (function(OAuthErrorCode$1) { - /** - * The request is missing a required parameter, includes an invalid parameter value, - * includes a parameter more than once, or is otherwise malformed. - */ - OAuthErrorCode$1["InvalidRequest"] = "invalid_request"; - /** - * Client authentication failed (e.g., unknown client, no client authentication included, - * or unsupported authentication method). - */ - OAuthErrorCode$1["InvalidClient"] = "invalid_client"; - /** - * The provided authorization grant or refresh token is invalid, expired, revoked, - * does not match the redirection URI used in the authorization request, or was issued to another client. - */ - OAuthErrorCode$1["InvalidGrant"] = "invalid_grant"; - /** - * The authenticated client is not authorized to use this authorization grant type. - */ - OAuthErrorCode$1["UnauthorizedClient"] = "unauthorized_client"; - /** - * The authorization grant type is not supported by the authorization server. - */ - OAuthErrorCode$1["UnsupportedGrantType"] = "unsupported_grant_type"; - /** - * The requested scope is invalid, unknown, malformed, or exceeds the scope granted by the resource owner. - */ - OAuthErrorCode$1["InvalidScope"] = "invalid_scope"; - /** - * The resource owner or authorization server denied the request. - */ - OAuthErrorCode$1["AccessDenied"] = "access_denied"; - /** - * The authorization server encountered an unexpected condition that prevented it from fulfilling the request. - */ - OAuthErrorCode$1["ServerError"] = "server_error"; - /** - * The authorization server is currently unable to handle the request due to temporary overloading or maintenance. - */ - OAuthErrorCode$1["TemporarilyUnavailable"] = "temporarily_unavailable"; - /** - * The authorization server does not support obtaining an authorization code using this method. - */ - OAuthErrorCode$1["UnsupportedResponseType"] = "unsupported_response_type"; - /** - * The authorization server does not support the requested token type. - */ - OAuthErrorCode$1["UnsupportedTokenType"] = "unsupported_token_type"; - /** - * The access token provided is expired, revoked, malformed, or invalid for other reasons. - */ - OAuthErrorCode$1["InvalidToken"] = "invalid_token"; - /** - * The HTTP method used is not allowed for this endpoint. (Custom, non-standard error) - */ - OAuthErrorCode$1["MethodNotAllowed"] = "method_not_allowed"; - /** - * Rate limit exceeded. (Custom, non-standard error based on RFC 6585) - */ - OAuthErrorCode$1["TooManyRequests"] = "too_many_requests"; - /** - * The client metadata is invalid. (Custom error for dynamic client registration - RFC 7591) - */ - OAuthErrorCode$1["InvalidClientMetadata"] = "invalid_client_metadata"; - /** - * The value of one or more redirection URIs is invalid. (Dynamic client registration - RFC 7591 §3.2.2) - */ - OAuthErrorCode$1["InvalidRedirectUri"] = "invalid_redirect_uri"; - /** - * The request requires higher privileges than provided by the access token. - */ - OAuthErrorCode$1["InsufficientScope"] = "insufficient_scope"; - /** - * The requested resource is invalid, missing, unknown, or malformed. (Custom error for resource indicators - RFC 8707) - */ - OAuthErrorCode$1["InvalidTarget"] = "invalid_target"; - return OAuthErrorCode$1; -}({}))); -/** -* OAuth error class for all OAuth-related errors. -*/ -var src_CX2iR2pK_OAuthError = class OAuthError extends Error { - static { - Object.defineProperty(this, "mcpBrand", { value: "mcp.OAuthError" }); - } - static [Symbol.hasInstance](value) { - return brandedHasInstance(this, value); - } - /** - * Brand-based type guard: equivalent to `value instanceof this`, as an - * explicit static predicate (the axios/AWS-SDK `isInstance` style). Reads - * the caller's own brand via `this`, so every branded subclass gets a - * correctly-scoped guard by inheritance. Must be invoked on the class — - * in callback position write `v => SdkError.isInstance(v)`, not - * `.filter(SdkError.isInstance)` (detached calls throw rather than - * silently matching nothing). - */ - static isInstance(value) { - 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 brandedHasInstance(this, value); - } - constructor(code, message, errorUri) { - super(message); - this.code = code; - this.errorUri = errorUri; - this.name = "OAuthError"; - stampErrorBrands(this, new.target); - } - /** - * Converts the error to a standard OAuth error response object. - */ - toResponseObject() { - const response = { - error: this.code, - error_description: this.message - }; - if (this.errorUri) response.error_uri = this.errorUri; - return response; - } - /** - * Creates an {@linkcode OAuthError} from an OAuth error response. - */ - static fromResponse(response) { - return new OAuthError(response.error, response.error_description ?? response.error, response.error_uri); - } -}; - -//#endregion -//#region ../core-internal/src/errors/sdkErrors.ts -/** -* Error codes for SDK errors (local errors that never cross the wire). -* Unlike {@linkcode ProtocolErrorCode} which uses numeric JSON-RPC codes, `SdkErrorCode` uses -* descriptive string values for better developer experience. -* -* These errors are thrown locally by the SDK and are never serialized as -* JSON-RPC error responses. -*/ -let src_CX2iR2pK_SdkErrorCode = /* @__PURE__ */ function(SdkErrorCode$1) { - /** Transport is not connected */ - SdkErrorCode$1["NotConnected"] = "NOT_CONNECTED"; - /** Transport is already connected */ - SdkErrorCode$1["AlreadyConnected"] = "ALREADY_CONNECTED"; - /** Protocol is not initialized */ - SdkErrorCode$1["NotInitialized"] = "NOT_INITIALIZED"; - /** Required capability is not supported by the remote side */ - SdkErrorCode$1["CapabilityNotSupported"] = "CAPABILITY_NOT_SUPPORTED"; - /** Request timed out waiting for response */ - SdkErrorCode$1["RequestTimeout"] = "REQUEST_TIMEOUT"; - /** Connection was closed */ - SdkErrorCode$1["ConnectionClosed"] = "CONNECTION_CLOSED"; - /** Failed to send message */ - SdkErrorCode$1["SendFailed"] = "SEND_FAILED"; - /** Response result failed local schema validation */ - SdkErrorCode$1["InvalidResult"] = "INVALID_RESULT"; - /** - * The response carried a `resultType` discriminator (protocol revision - * 2026-07-28) naming a result kind this client cannot consume yet, e.g. - * `input_required`. The kind is carried in `data.resultType`. - */ - SdkErrorCode$1["UnsupportedResultType"] = "UNSUPPORTED_RESULT_TYPE"; - /** - * The multi-round-trip auto-fulfilment driver exhausted its round cap - * (`inputRequired.maxRounds`) without the server returning a complete - * result. `data.rounds` carries the cap that was hit and - * `data.lastResult` carries the last `input_required` payload received - * (`{ inputRequests, requestState? }`), so callers can inspect or resume - * the flow manually. - */ - SdkErrorCode$1["InputRequiredRoundsExceeded"] = "INPUT_REQUIRED_ROUNDS_EXCEEDED"; - /** - * The auto-aggregating no-`cursor` `listTools()` / `listPrompts()` / - * `listResources()` / `listResourceTemplates()` walk hit the - * `ClientOptions.listMaxPages` cap without the server's pagination - * converging. `data.method` carries the list verb and - * `data.listMaxPages` the cap that was hit; raise the cap or fall back to - * explicit per-page `{ cursor }` calls. - */ - SdkErrorCode$1["ListPaginationExceeded"] = "LIST_PAGINATION_EXCEEDED"; - /** - * The spec method being sent does not exist on the negotiated protocol - * version's wire era (e.g. `tasks/get` toward a 2026-07-28 peer, or - * `server/discover` toward a 2025-era peer). Raised locally, before - * anything reaches the transport. The method and era are carried in - * `data.method` / `data.era`. - */ - SdkErrorCode$1["MethodNotSupportedByProtocolVersion"] = "METHOD_NOT_SUPPORTED_BY_PROTOCOL_VERSION"; - /** - * Protocol-era negotiation at connect time failed without producing either a - * usable modern (2026-07-28+) era or a definitive legacy fallback signal — - * e.g. the negotiation mode forbids falling back (`pin`), the probe hit a - * network failure, or the server answered the probe with a 5xx (a typed - * connect error, never an era verdict). - * - * Negotiation-phase only: this code is never used once an era is - * established. Auth walls never carry it: a 401/403 rejecting the probe - * uses {@linkcode ClientHttpAuthentication} / {@linkcode ClientHttpForbidden} - * instead, so era-recovery flows keyed on this code (e.g. cached-verdict - * gateways) can never persist a verdict for an unauthorized exchange. - */ - SdkErrorCode$1["EraNegotiationFailed"] = "ERA_NEGOTIATION_FAILED"; - SdkErrorCode$1["ClientHttpNotImplemented"] = "CLIENT_HTTP_NOT_IMPLEMENTED"; - /** - * HTTP 401 authentication failure: the transport's re-auth retry still got - * 401 (`Server returned 401 after re-authentication`), or the version - * negotiation probe was rejected 401 with no `authProvider` configured - * (`Version negotiation failed: the server requires authorization (HTTP 401)`). - * Carried on an {@linkcode SdkHttpError} with `status: 401`. - */ - SdkErrorCode$1["ClientHttpAuthentication"] = "CLIENT_HTTP_AUTHENTICATION"; - /** - * HTTP 403 denial: the step-up re-authorization retry limit was reached, - * or the version negotiation probe was rejected 403 - * (`Version negotiation failed: the server denied access (HTTP 403)`). - * Carried on an {@linkcode SdkHttpError} with `status: 403`. - */ - SdkErrorCode$1["ClientHttpForbidden"] = "CLIENT_HTTP_FORBIDDEN"; - SdkErrorCode$1["ClientHttpUnexpectedContent"] = "CLIENT_HTTP_UNEXPECTED_CONTENT"; - SdkErrorCode$1["ClientHttpFailedToOpenStream"] = "CLIENT_HTTP_FAILED_TO_OPEN_STREAM"; - SdkErrorCode$1["ClientHttpFailedToTerminateSession"] = "CLIENT_HTTP_FAILED_TO_TERMINATE_SESSION"; - return SdkErrorCode$1; -}({}); -/** -* SDK errors are local errors that never cross the wire. -* They are distinct from {@linkcode ProtocolError} which represents JSON-RPC protocol errors -* that are serialized and sent as error responses. -* -* @example -* ```ts source="./sdkErrors.examples.ts#SdkError_basicUsage" -* try { -* // Throwing an SDK error -* throw new SdkError(SdkErrorCode.NotConnected, 'Transport is not connected'); -* } catch (error) { -* // Checking error type by code -* if (error instanceof SdkError && error.code === SdkErrorCode.RequestTimeout) { -* // Handle timeout -* } -* } -* ``` -*/ -var src_CX2iR2pK_SdkError = class extends Error { - static { - Object.defineProperty(this, "mcpBrand", { value: "mcp.SdkError" }); - } - static [Symbol.hasInstance](value) { - return brandedHasInstance(this, value); - } - /** - * Brand-based type guard: equivalent to `value instanceof this`, as an - * explicit static predicate (the axios/AWS-SDK `isInstance` style). Reads - * the caller's own brand via `this`, so every branded subclass gets a - * correctly-scoped guard by inheritance. Must be invoked on the class — - * in callback position write `v => SdkError.isInstance(v)`, not - * `.filter(SdkError.isInstance)` (detached calls throw rather than - * silently matching nothing). - */ - static isInstance(value) { - 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 brandedHasInstance(this, value); - } - constructor(code, message, data) { - super(message); - this.code = code; - this.data = data; - this.name = "SdkError"; - stampErrorBrands(this, new.target); - } -}; -/** -* An {@linkcode SdkError} subclass for HTTP transport failures. -* -* Thrown by the streamable HTTP transport when the server responds with a -* non-OK status code. Narrows {@linkcode SdkError.data | data} to -* {@linkcode SdkHttpErrorData} so consumers can inspect the HTTP status -* without unsafe casting. -* -* @example -* ```ts source="./sdkErrors.examples.ts#SdkHttpError_basicUsage" -* if (error instanceof SdkHttpError) { -* console.log(error.status); // number -* console.log(error.statusText); // string | undefined -* } -* ``` -*/ -var SdkHttpError = class extends src_CX2iR2pK_SdkError { - static { - Object.defineProperty(this, "mcpBrand", { value: "mcp.SdkHttpError" }); - } - constructor(code, message, data) { - super(code, message, data); - this.name = "SdkHttpError"; - } - get status() { - return this.data.status; - } - get statusText() { - return this.data.statusText; - } -}; - -//#endregion -//#region ../core-internal/src/shared/authUtils.ts -/** -* Utilities for handling OAuth resource URIs. -*/ -/** -* Converts a server URL to a resource URL by removing the fragment. -* {@link https://datatracker.ietf.org/doc/html/rfc8707#section-2 | RFC 8707 section 2} -* states that resource URIs "MUST NOT include a fragment component". -* Keeps everything else unchanged (scheme, domain, port, path, query). -*/ -function resourceUrlFromServerUrl(url) { - const resourceURL = typeof url === "string" ? new URL(url) : new URL(url.href); - resourceURL.hash = ""; - return resourceURL; -} -/** -* Checks if a requested resource URL matches a configured resource URL. -* A requested resource matches if it has the same scheme, domain, port, -* and its path starts with the configured resource's path. -* -* @param options - The options object -* @param options.requestedResource - The resource URL being requested -* @param options.configuredResource - The resource URL that has been configured -* @returns true if the requested resource matches the configured resource, false otherwise -*/ -function checkResourceAllowed({ requestedResource, configuredResource }) { - const requested = typeof requestedResource === "string" ? new URL(requestedResource) : new URL(requestedResource.href); - const configured = typeof configuredResource === "string" ? new URL(configuredResource) : new URL(configuredResource.href); - if (requested.origin !== configured.origin) return false; - if (requested.pathname.length < configured.pathname.length) return false; - const requestedPath = requested.pathname.endsWith("/") ? requested.pathname : requested.pathname + "/"; - const configuredPath = configured.pathname.endsWith("/") ? configured.pathname : configured.pathname + "/"; - return requestedPath.startsWith(configuredPath); -} - -//#endregion -//#region ../core-internal/src/shared/clientCapabilityRequirements.ts -/** -* Inbound request methods whose processing structurally requires a client -* capability, keyed by method, valued by the capabilities required. -* -* Currently empty: none of the request methods served on the 2026-07-28 -* registry unconditionally requires a client capability. Entries appear here -* when such methods exist — for example requests whose handling embeds -* elicitation or sampling input requests (the input-request engine), or -* opt-in subscription delivery. Handler-conditional requirements (a specific -* tool that needs sampling) are not expressible as a static method table and -* are enforced at the point the requirement arises instead. -*/ -const REQUIRED_CLIENT_CAPABILITIES_BY_METHOD = (/* unused pure expression or super */ null && ({})); -/** -* The client capabilities a request method structurally requires, or -* `undefined` when the method has no static requirement. -*/ -function src_CX2iR2pK_requiredClientCapabilitiesForRequest(method) { - return Object.hasOwn(REQUIRED_CLIENT_CAPABILITIES_BY_METHOD, method) ? REQUIRED_CLIENT_CAPABILITIES_BY_METHOD[method] : void 0; -} -function isPlainObject$7(value) { - return value !== null && typeof value === "object" && !Array.isArray(value); -} -/** -* Whether a required nested member counts as declared even though it is not -* spelled out: a bare `elicitation: {}` declaration (no mode sub-capability at -* all) is read as form support — the pre-mode (2025) meaning of a bare -* declaration — so an `elicitation.form` requirement treats it as satisfied. -* Declaring any mode explicitly (for example `elicitation: { url: {} }`) -* removes the implication. -*/ -function isImpliedCapabilityMember(capability, member, declaredValue) { - return capability === "elicitation" && member === "form" && declaredValue["form"] === void 0 && declaredValue["url"] === void 0; -} -/** -* The client capabilities an embedded multi-round-trip input request requires -* (call site 2 — the outbound input-request leg): a server MUST NOT send an -* `inputRequests` kind the request's declared client capabilities do not -* cover. Returns `undefined` for entries whose method is not one of the -* embedded input-request kinds (those are a server bug handled separately, -* not a capability question). -* -* The requirement is mode-aware where the capability is: URL-mode elicitation -* requires `elicitation.url`; form-mode (or mode-omitted) elicitation requires -* `elicitation.form` (modes are sub-capabilities, and a server MUST NOT send a -* mode the client did not declare); sampling with `tools`/`toolChoice` -* requires `sampling.tools`. A bare `elicitation: {}` declaration satisfies -* the form requirement — see {@linkcode missingClientCapabilities}. -*/ -function requiredClientCapabilitiesForInputRequest(entry) { - switch (entry.method) { - case "elicitation/create": - if (entry.params?.["mode"] === "url") return { elicitation: { url: {} } }; - return { elicitation: { form: {} } }; - case "sampling/createMessage": { - const params = entry.params; - if (params !== void 0 && (params["tools"] !== void 0 || params["toolChoice"] !== void 0)) return { sampling: { tools: {} } }; - return { sampling: {} }; - } - case "roots/list": return { roots: {} }; - default: return; - } -} -/** -* Computes the subset of `required` client capabilities the client did not -* declare. Returns `undefined` when every required capability is declared; -* otherwise returns an object in the `ClientCapabilities` shape containing -* exactly the missing capabilities (suitable for -* `data.requiredCapabilities` on the `-32021` error). -* -* A capability counts as declared when its top-level key is present on the -* declared capabilities; when the requirement names nested members (for -* example `elicitation: { url: {} }`), each named member must also be present -* under the declared capability. One lenient reading applies: a bare -* `elicitation: {}` declaration (no mode sub-capability at all) counts as -* declaring `elicitation.form` — the pre-mode (2025) meaning of a bare -* declaration. An absent or empty `declared` value means -* nothing is declared — every required capability is missing (the structural -* clean-refusal posture for sessions with no per-request capability view). -*/ -function src_CX2iR2pK_missingClientCapabilities(required, declared) { - const missing = {}; - for (const [capability, requirement] of Object.entries(required)) { - if (requirement === void 0) continue; - const declaredValue = declared === void 0 ? void 0 : declared[capability]; - if (declaredValue === void 0) { - missing[capability] = requirement; - continue; - } - if (isPlainObject$7(requirement) && isPlainObject$7(declaredValue)) { - const missingMembers = {}; - for (const [member, memberRequirement] of Object.entries(requirement)) if (memberRequirement !== void 0 && declaredValue[member] === void 0 && !isImpliedCapabilityMember(capability, member, declaredValue)) missingMembers[member] = memberRequirement; - if (Object.keys(missingMembers).length > 0) missing[capability] = missingMembers; - } - } - return Object.keys(missing).length > 0 ? missing : void 0; -} - -//#endregion -//#region ../core-internal/src/shared/protocolEras.ts -/** -* The first protocol revision of the modern (2026-07-28) era. Revision identifiers -* are ISO dates, so lexicographic comparison orders them chronologically. -*/ -const FIRST_MODERN_PROTOCOL_VERSION = "2026-07-28"; -/** -* Modern-era protocol revisions this SDK can negotiate via `server/discover`. -* Deliberately separate from {@linkcode SUPPORTED_PROTOCOL_VERSIONS} (the legacy -* `initialize` list), so adding a revision here can never leak a modern version -* string into a 2025-era handshake. Internal — not part of the public API surface. -*/ -const src_CX2iR2pK_SUPPORTED_MODERN_PROTOCOL_VERSIONS = (/* unused pure expression or super */ null && ([FIRST_MODERN_PROTOCOL_VERSION])); -/** Whether the given protocol revision belongs to the modern (2026-07-28+) era. */ -function isModernProtocolVersion(version) { - return version >= FIRST_MODERN_PROTOCOL_VERSION; -} -/** The legacy-era (pre-2026-07-28) subset of a supported-versions list, in the list's own preference order. */ -function legacyProtocolVersions(versions) { - return versions.filter((version) => !isModernProtocolVersion(version)); -} -/** The modern-era (2026-07-28+) subset of a supported-versions list, in the list's own preference order. */ -function modernProtocolVersions(versions) { - return versions.filter((version) => isModernProtocolVersion(version)); -} - -//#endregion -//#region ../core-internal/src/wire/textFallback.ts -/** -* SEP-2106 §4.3 TextContent auto-append, era-agnostic, called from BOTH -* codecs' {@link WireCodec.projectCallToolResult}: when `structuredContent` -* is a non-object value (array/primitive/`null`) and the handler authored no -* `type:'text'` block, append `{type:'text', text: JSON.stringify(value)}`. -* Object-shaped (or absent) `structuredContent` returns the same reference. -* -* Leaf module: imported by both era codec modules, so it must NOT import from -* `./codec.js` (which value-imports the rev codecs at top level — that would -* make a runtime cycle and a TDZ hazard for entries that evaluate a rev codec -* module first). -*/ -function appendTextFallbackForNonObject(result) { - const sc = result.structuredContent; - if (sc === void 0) return result; - if (!(typeof sc !== "object" || sc === null || Array.isArray(sc))) return result; - if (result.content?.some((c) => c.type === "text") ?? false) return result; - return { - ...result, - content: [...result.content ?? [], { - type: "text", - text: JSON.stringify(sc) - }] - }; -} - -//#endregion -//#region ../core-internal/src/wire/resultFamilies.ts -/** -* Result-family keys that must never default into a `{content: []}` tools/call -* success. Shared by the 2025 wire-seam schema and server normalization. -* Leaf module (like `textFallback.ts`): imported by registry/server paths, so -* it must NOT import from `./codec.js` — that would close a runtime cycle. -*/ -const TOOL_RESULT_FOREIGN_FAMILY_KEYS = [ - "task", - "inputRequests", - "requestState" -]; -/** -* Single owner of the v1-parity ruling: a plain-object tool result without `content` (and -* without foreign-family keys) gains `content: []`. Shared by the 2025 wire seam and server-side handler normalization. -*/ -function normalizeContentlessToolResult(value) { - if (value === null || typeof value !== "object" || Array.isArray(value) || value.content !== void 0 || TOOL_RESULT_FOREIGN_FAMILY_KEYS.some((key) => key in value)) return value; - return { - ...value, - content: [] - }; -} - -//#endregion -//#region ../core-internal/src/wire/rev2025-11-25/buildSchemas.ts -/** -* Complete frozen 2025-11-25 wire schemas. Self-contained — no imports from -* the public/neutral types/schemas.ts. The neutral layer is the public-API -* superset and is free to evolve (e.g., SEP-2106 widening); this file is the -* 2025 wire-parse contract (Q10-L2 byte-identity) and is BEHAVIOR-FROZEN. -* -* This is the era's complete frozen wire-parse contract — both the 2025-only -* delta (the deprecated task family, the era role unions) AND frozen copies of -* every era-shared shape (Tool, CallToolResult, Initialize*, ContentBlock, -* prompts/resources/completion/elicitation, …). The 2026-era codec -* (`wire/rev2026-07-28/`) is symmetrically self-contained in the same way. -* -* The 2025-only delta (the task message surface, restored types-only by #2248 -* for interop with task-capable 2025 peers) is parsed ONLY through this era's -* registry; the deprecated Task* schemas also live (marked `@deprecated`) in -* the neutral schema layer so the public types stay nameable without a -* cross-layer import — nameability is constant, runtime availability is -* version-keyed — but appear in no API signature. Q1 increment 2 — deletions -* are physical: the -* 2026-era REGISTRY has no Task* methods (its frozen building-block copies do -* carry the deprecated Task* sub-schemas by composition — soft contamination, -* tracked for anchor-exactness adjudication). -* -* The only cross-layer dependency is `import type { JSONObject, JSONValue }` -* from the neutral types barrel — pure structural type aliases with no parse -* behavior. No runtime schema is shared with the neutral layer. -*/ -function build$1() { - const JSONValueSchema$1 = lazy(() => schemas_union([ - schemas_string(), - schemas_number(), - schemas_boolean(), - schemas_null(), - schemas_record(schemas_string(), JSONValueSchema$1), - schemas_array(JSONValueSchema$1) - ])); - const JSONObjectSchema$1 = schemas_record(schemas_string(), JSONValueSchema$1); - /** - * A progress token, used to associate progress notifications with the original request. - */ - const ProgressTokenSchema$1 = schemas_union([schemas_string(), schemas_number().int()]); - /** - * An opaque token used to represent a cursor for pagination. - */ - const CursorSchema$1 = schemas_string(); - /** @deprecated 2025-11-25 wire vocabulary with no SDK runtime; kept importable for interoperability only. */ - const TaskMetadataSchema$1 = schemas_object({ ttl: schemas_number().optional() }); - /** - * Metadata for associating messages with a task. - * Include this in the `_meta` field under the key `io.modelcontextprotocol/related-task`. - * - * @deprecated 2025-11-25 wire vocabulary with no SDK runtime; kept importable for interoperability only. - */ - const RelatedTaskMetadataSchema$1 = schemas_object({ taskId: schemas_string() }); - const RequestMetaSchema$1 = looseObject({ - progressToken: ProgressTokenSchema$1.optional(), - "io.modelcontextprotocol/related-task": RelatedTaskMetadataSchema$1.optional() - }); - /** - * Common params for any request. - */ - const BaseRequestParamsSchema$1 = schemas_object({ _meta: RequestMetaSchema$1.optional() }); - /** - * Common params for any task-augmented request. - * - * @deprecated 2025-11-25 wire vocabulary with no SDK runtime; kept importable for interoperability only. - */ - const TaskAugmentedRequestParamsSchema$1 = BaseRequestParamsSchema$1.extend({ task: TaskMetadataSchema$1.optional() }); - const RequestSchema$1 = schemas_object({ - method: schemas_string(), - params: BaseRequestParamsSchema$1.loose().optional() - }); - const NotificationsParamsSchema$1 = schemas_object({ _meta: RequestMetaSchema$1.optional() }); - const NotificationSchema$1 = schemas_object({ - method: schemas_string(), - params: NotificationsParamsSchema$1.loose().optional() - }); - const ResultSchema$1 = looseObject({ _meta: RequestMetaSchema$1.optional() }); - /** - * A uniquely identifying ID for a request in JSON-RPC. - */ - const RequestIdSchema$1 = schemas_union([schemas_string(), schemas_number().int()]); - /** - * A response that indicates success but carries no data. - */ - const EmptyResultSchema$1 = ResultSchema$1.strict(); - const CancelledNotificationParamsSchema$1 = NotificationsParamsSchema$1.extend({ - requestId: RequestIdSchema$1.optional(), - reason: schemas_string().optional() - }); - /** - * This notification can be sent by either side to indicate that it is cancelling a previously-issued request. - * - * The request SHOULD still be in-flight, but due to communication latency, it is always possible that this notification MAY arrive after the request has already finished. - * - * This notification indicates that the result will be unused, so any associated processing SHOULD cease. - * - * A client MUST NOT attempt to cancel its {@linkcode InitializeRequest | initialize} request. - */ - const CancelledNotificationSchema$1 = NotificationSchema$1.extend({ - method: literal("notifications/cancelled"), - params: CancelledNotificationParamsSchema$1 - }); - /** - * Icon schema for use in {@link Tool | tools}, {@link Prompt | prompts}, {@link Resource | resources}, and {@link Implementation | implementations}. - */ - const IconSchema$1 = schemas_object({ - src: schemas_string(), - mimeType: schemas_string().optional(), - sizes: schemas_array(schemas_string()).optional(), - theme: schemas_enum(["light", "dark"]).optional() - }); - /** - * Base schema to add `icons` property. - * - */ - const IconsSchema$1 = schemas_object({ icons: schemas_array(IconSchema$1).optional() }); - /** - * Base metadata interface for common properties across {@link Resource | resources}, {@link Tool | tools}, {@link Prompt | prompts}, and {@link Implementation | implementations}. - */ - const BaseMetadataSchema$1 = schemas_object({ - name: schemas_string(), - title: schemas_string().optional() - }); - /** - * Describes the name and version of an MCP implementation. - */ - const ImplementationSchema$1 = BaseMetadataSchema$1.extend({ - ...BaseMetadataSchema$1.shape, - ...IconsSchema$1.shape, - version: schemas_string(), - websiteUrl: schemas_string().optional(), - description: schemas_string().optional() - }); - const FormElicitationCapabilitySchema = intersection(schemas_object({ applyDefaults: schemas_boolean().optional() }), JSONObjectSchema$1); - const ElicitationCapabilitySchema = preprocess((value) => { - if (value && typeof value === "object" && !Array.isArray(value) && Object.keys(value).length === 0) return { form: {} }; - return value; - }, intersection(schemas_object({ - form: FormElicitationCapabilitySchema.optional(), - url: JSONObjectSchema$1.optional() - }), JSONObjectSchema$1.optional())); - /** - * Task capabilities for clients, indicating which request types support task creation. - * - * @deprecated 2025-11-25 wire vocabulary with no SDK runtime; kept importable for interoperability only. - */ - const ClientTasksCapabilitySchema$1 = looseObject({ - list: JSONObjectSchema$1.optional(), - cancel: JSONObjectSchema$1.optional(), - requests: looseObject({ - sampling: looseObject({ createMessage: JSONObjectSchema$1.optional() }).optional(), - elicitation: looseObject({ create: JSONObjectSchema$1.optional() }).optional() - }).optional() - }); - /** - * Task capabilities for servers, indicating which request types support task creation. - * - * @deprecated 2025-11-25 wire vocabulary with no SDK runtime; kept importable for interoperability only. - */ - const ServerTasksCapabilitySchema$1 = looseObject({ - list: JSONObjectSchema$1.optional(), - cancel: JSONObjectSchema$1.optional(), - requests: looseObject({ tools: looseObject({ call: JSONObjectSchema$1.optional() }).optional() }).optional() - }); - /** - * Capabilities a client may support. Known capabilities are defined here, in this schema, but this is not a closed set: any client can define its own, additional capabilities. - */ - const ClientCapabilitiesSchema$1 = schemas_object({ - experimental: schemas_record(schemas_string(), JSONObjectSchema$1).optional(), - sampling: schemas_object({ - context: JSONObjectSchema$1.optional(), - tools: JSONObjectSchema$1.optional() - }).optional(), - elicitation: ElicitationCapabilitySchema.optional(), - roots: schemas_object({ listChanged: schemas_boolean().optional() }).optional(), - tasks: ClientTasksCapabilitySchema$1.optional(), - extensions: schemas_record(schemas_string(), JSONObjectSchema$1).optional() - }); - const InitializeRequestParamsSchema$1 = BaseRequestParamsSchema$1.extend({ - protocolVersion: schemas_string(), - capabilities: ClientCapabilitiesSchema$1, - clientInfo: ImplementationSchema$1 - }); - /** - * This request is sent from the client to the server when it first connects, asking it to begin initialization. - */ - const InitializeRequestSchema$1 = RequestSchema$1.extend({ - method: literal("initialize"), - params: InitializeRequestParamsSchema$1 - }); - /** - * Capabilities that a server may support. Known capabilities are defined here, in this schema, but this is not a closed set: any server can define its own, additional capabilities. - */ - const ServerCapabilitiesSchema$1 = schemas_object({ - experimental: schemas_record(schemas_string(), JSONObjectSchema$1).optional(), - logging: JSONObjectSchema$1.optional(), - completions: JSONObjectSchema$1.optional(), - prompts: schemas_object({ listChanged: schemas_boolean().optional() }).optional(), - resources: schemas_object({ - subscribe: schemas_boolean().optional(), - listChanged: schemas_boolean().optional() - }).optional(), - tools: schemas_object({ listChanged: schemas_boolean().optional() }).optional(), - tasks: ServerTasksCapabilitySchema$1.optional(), - extensions: schemas_record(schemas_string(), JSONObjectSchema$1).optional() - }); - /** - * After receiving an initialize request from the client, the server sends this response. - */ - const InitializeResultSchema$1 = ResultSchema$1.extend({ - protocolVersion: schemas_string(), - capabilities: ServerCapabilitiesSchema$1, - serverInfo: ImplementationSchema$1, - instructions: schemas_string().optional() - }); - /** - * This notification is sent from the client to the server after initialization has finished. - */ - const InitializedNotificationSchema$1 = NotificationSchema$1.extend({ - method: literal("notifications/initialized"), - params: NotificationsParamsSchema$1.optional() - }); - /** - * A ping, issued by either the server or the client, to check that the other party is still alive. The receiver must promptly respond, or else may be disconnected. - */ - const PingRequestSchema$1 = RequestSchema$1.extend({ - method: literal("ping"), - params: BaseRequestParamsSchema$1.optional() - }); - const ProgressSchema$1 = schemas_object({ - progress: schemas_number(), - total: schemas_optional(schemas_number()), - message: schemas_optional(schemas_string()) - }); - const ProgressNotificationParamsSchema$1 = schemas_object({ - ...NotificationsParamsSchema$1.shape, - ...ProgressSchema$1.shape, - progressToken: ProgressTokenSchema$1 - }); - /** - * An out-of-band notification used to inform the receiver of a progress update for a long-running request. - * - * @category notifications/progress - */ - const ProgressNotificationSchema$1 = NotificationSchema$1.extend({ - method: literal("notifications/progress"), - params: ProgressNotificationParamsSchema$1 - }); - const PaginatedRequestParamsSchema$1 = BaseRequestParamsSchema$1.extend({ cursor: CursorSchema$1.optional() }); - const PaginatedRequestSchema$1 = RequestSchema$1.extend({ params: PaginatedRequestParamsSchema$1.optional() }); - const PaginatedResultSchema$1 = ResultSchema$1.extend({ nextCursor: CursorSchema$1.optional() }); - /** - * The contents of a specific resource or sub-resource. - */ - const ResourceContentsSchema$1 = schemas_object({ - uri: schemas_string(), - mimeType: schemas_optional(schemas_string()), - _meta: schemas_record(schemas_string(), unknown()).optional() - }); - const TextResourceContentsSchema$1 = ResourceContentsSchema$1.extend({ text: schemas_string() }); - /** - * A Zod schema for validating Base64 strings that is more performant and - * robust for very large inputs than the default regex-based check. It avoids - * stack overflows by using the native `atob` function for validation. - */ - const Base64Schema = schemas_string().refine((val) => { - try { - atob(val); - return true; - } catch { - return false; - } - }, { message: "Invalid Base64 string" }); - const BlobResourceContentsSchema$1 = ResourceContentsSchema$1.extend({ blob: Base64Schema }); - /** - * The sender or recipient of messages and data in a conversation. - */ - const RoleSchema$1 = schemas_enum(["user", "assistant"]); - /** - * Optional annotations providing clients additional context about a resource. - */ - const AnnotationsSchema$1 = schemas_object({ - audience: schemas_array(RoleSchema$1).optional(), - priority: schemas_number().min(0).max(1).optional(), - lastModified: iso_datetime({ offset: true }).optional() - }); - /** - * A known resource that the server is capable of reading. - */ - const ResourceSchema$1 = schemas_object({ - ...BaseMetadataSchema$1.shape, - ...IconsSchema$1.shape, - uri: schemas_string(), - description: schemas_optional(schemas_string()), - mimeType: schemas_optional(schemas_string()), - size: schemas_optional(schemas_number()), - annotations: AnnotationsSchema$1.optional(), - _meta: schemas_optional(looseObject({})) - }); - /** - * A template description for resources available on the server. - */ - const ResourceTemplateSchema$1 = schemas_object({ - ...BaseMetadataSchema$1.shape, - ...IconsSchema$1.shape, - uriTemplate: schemas_string(), - description: schemas_optional(schemas_string()), - mimeType: schemas_optional(schemas_string()), - annotations: AnnotationsSchema$1.optional(), - _meta: schemas_optional(looseObject({})) - }); - /** - * Sent from the client to request a list of resources the server has. - */ - const ListResourcesRequestSchema$1 = PaginatedRequestSchema$1.extend({ method: literal("resources/list") }); - /** - * The server's response to a {@linkcode ListResourcesRequest | resources/list} request from the client. - */ - const ListResourcesResultSchema$1 = PaginatedResultSchema$1.extend({ resources: schemas_array(ResourceSchema$1) }); - /** - * Sent from the client to request a list of resource templates the server has. - */ - const ListResourceTemplatesRequestSchema$1 = PaginatedRequestSchema$1.extend({ method: literal("resources/templates/list") }); - /** - * The server's response to a {@linkcode ListResourceTemplatesRequest | resources/templates/list} request from the client. - */ - const ListResourceTemplatesResultSchema$1 = PaginatedResultSchema$1.extend({ resourceTemplates: schemas_array(ResourceTemplateSchema$1) }); - const ResourceRequestParamsSchema$1 = BaseRequestParamsSchema$1.extend({ uri: schemas_string() }); - /** - * Parameters for a {@linkcode ReadResourceRequest | resources/read} request. - */ - const ReadResourceRequestParamsSchema$1 = ResourceRequestParamsSchema$1; - /** - * Sent from the client to the server, to read a specific resource URI. - */ - const ReadResourceRequestSchema$1 = RequestSchema$1.extend({ - method: literal("resources/read"), - params: ReadResourceRequestParamsSchema$1 - }); - /** - * The server's response to a {@linkcode ReadResourceRequest | resources/read} request from the client. - */ - const ReadResourceResultSchema$1 = ResultSchema$1.extend({ contents: schemas_array(schemas_union([TextResourceContentsSchema$1, BlobResourceContentsSchema$1])) }); - /** - * An optional notification from the server to the client, informing it that the list of resources it can read from has changed. This may be issued by servers without any previous subscription from the client. - */ - const ResourceListChangedNotificationSchema$1 = NotificationSchema$1.extend({ - method: literal("notifications/resources/list_changed"), - params: NotificationsParamsSchema$1.optional() - }); - const SubscribeRequestParamsSchema$1 = ResourceRequestParamsSchema$1; - /** - * Sent from the client to request `resources/updated` notifications from the server whenever a particular resource changes. - */ - const SubscribeRequestSchema$1 = RequestSchema$1.extend({ - method: literal("resources/subscribe"), - params: SubscribeRequestParamsSchema$1 - }); - const UnsubscribeRequestParamsSchema$1 = ResourceRequestParamsSchema$1; - /** - * Sent from the client to request cancellation of {@linkcode ResourceUpdatedNotification | resources/updated} notifications from the server. This should follow a previous {@linkcode SubscribeRequest | resources/subscribe} request. - */ - const UnsubscribeRequestSchema$1 = RequestSchema$1.extend({ - method: literal("resources/unsubscribe"), - params: UnsubscribeRequestParamsSchema$1 - }); - /** - * Parameters for a {@linkcode ResourceUpdatedNotification | notifications/resources/updated} notification. - */ - const ResourceUpdatedNotificationParamsSchema$1 = NotificationsParamsSchema$1.extend({ uri: schemas_string() }); - /** - * A notification from the server to the client, informing it that a resource has changed and may need to be read again. This should only be sent if the client previously sent a {@linkcode SubscribeRequest | resources/subscribe} request. - */ - const ResourceUpdatedNotificationSchema$1 = NotificationSchema$1.extend({ - method: literal("notifications/resources/updated"), - params: ResourceUpdatedNotificationParamsSchema$1 - }); - /** - * Describes an argument that a prompt can accept. - */ - const PromptArgumentSchema$1 = schemas_object({ - name: schemas_string(), - description: schemas_optional(schemas_string()), - required: schemas_optional(schemas_boolean()) - }); - /** - * A prompt or prompt template that the server offers. - */ - const PromptSchema$1 = schemas_object({ - ...BaseMetadataSchema$1.shape, - ...IconsSchema$1.shape, - description: schemas_optional(schemas_string()), - arguments: schemas_optional(schemas_array(PromptArgumentSchema$1)), - _meta: schemas_optional(looseObject({})) - }); - /** - * Sent from the client to request a list of prompts and prompt templates the server has. - */ - const ListPromptsRequestSchema$1 = PaginatedRequestSchema$1.extend({ method: literal("prompts/list") }); - /** - * The server's response to a {@linkcode ListPromptsRequest | prompts/list} request from the client. - */ - const ListPromptsResultSchema$1 = PaginatedResultSchema$1.extend({ prompts: schemas_array(PromptSchema$1) }); - /** - * Parameters for a {@linkcode GetPromptRequest | prompts/get} request. - */ - const GetPromptRequestParamsSchema$1 = BaseRequestParamsSchema$1.extend({ - name: schemas_string(), - arguments: schemas_record(schemas_string(), schemas_string()).optional() - }); - /** - * Used by the client to get a prompt provided by the server. - */ - const GetPromptRequestSchema$1 = RequestSchema$1.extend({ - method: literal("prompts/get"), - params: GetPromptRequestParamsSchema$1 - }); - /** - * Text provided to or from an LLM. - */ - const TextContentSchema$1 = schemas_object({ - type: literal("text"), - text: schemas_string(), - annotations: AnnotationsSchema$1.optional(), - _meta: schemas_record(schemas_string(), unknown()).optional() - }); - /** - * An image provided to or from an LLM. - */ - const ImageContentSchema$1 = schemas_object({ - type: literal("image"), - data: Base64Schema, - mimeType: schemas_string(), - annotations: AnnotationsSchema$1.optional(), - _meta: schemas_record(schemas_string(), unknown()).optional() - }); - /** - * Audio content provided to or from an LLM. - */ - const AudioContentSchema$1 = schemas_object({ - type: literal("audio"), - data: Base64Schema, - mimeType: schemas_string(), - annotations: AnnotationsSchema$1.optional(), - _meta: schemas_record(schemas_string(), unknown()).optional() - }); - /** - * A tool call request from an assistant (LLM). - * Represents the assistant's request to use a tool. - * - * @deprecated Deprecated as of protocol version 2026-07-28 (SEP-2577); remains - * in the specification for at least twelve months. Migrate to calling LLM - * provider APIs directly. - */ - const ToolUseContentSchema$1 = schemas_object({ - type: literal("tool_use"), - name: schemas_string(), - id: schemas_string(), - input: schemas_record(schemas_string(), unknown()), - _meta: schemas_record(schemas_string(), unknown()).optional() - }); - /** - * The contents of a resource, embedded into a prompt or tool call result. - */ - const EmbeddedResourceSchema$1 = schemas_object({ - type: literal("resource"), - resource: schemas_union([TextResourceContentsSchema$1, BlobResourceContentsSchema$1]), - annotations: AnnotationsSchema$1.optional(), - _meta: schemas_record(schemas_string(), unknown()).optional() - }); - /** - * A resource that the server is capable of reading, included in a prompt or tool call result. - * - * Note: resource links returned by tools are not guaranteed to appear in the results of {@linkcode ListResourcesRequest | resources/list} requests. - */ - const ResourceLinkSchema$1 = ResourceSchema$1.extend({ type: literal("resource_link") }); - /** - * A content block that can be used in prompts and tool results. - */ - const ContentBlockSchema$1 = schemas_union([ - TextContentSchema$1, - ImageContentSchema$1, - AudioContentSchema$1, - ResourceLinkSchema$1, - EmbeddedResourceSchema$1 - ]); - /** - * Describes a message returned as part of a prompt. - */ - const PromptMessageSchema$1 = schemas_object({ - role: RoleSchema$1, - content: ContentBlockSchema$1 - }); - /** - * The server's response to a {@linkcode GetPromptRequest | prompts/get} request from the client. - */ - const GetPromptResultSchema$1 = ResultSchema$1.extend({ - description: schemas_string().optional(), - messages: schemas_array(PromptMessageSchema$1) - }); - /** - * An optional notification from the server to the client, informing it that the list of prompts it offers has changed. This may be issued by servers without any previous subscription from the client. - */ - const PromptListChangedNotificationSchema$1 = NotificationSchema$1.extend({ - method: literal("notifications/prompts/list_changed"), - params: NotificationsParamsSchema$1.optional() - }); - /** - * Additional properties describing a `Tool` to clients. - * - * NOTE: all properties in {@linkcode ToolAnnotations} are **hints**. - * They are not guaranteed to provide a faithful description of - * tool behavior (including descriptive properties like `title`). - * - * Clients should never make tool use decisions based on `ToolAnnotations` - * received from untrusted servers. - */ - const ToolAnnotationsSchema$1 = schemas_object({ - title: schemas_string().optional(), - readOnlyHint: schemas_boolean().optional(), - destructiveHint: schemas_boolean().optional(), - idempotentHint: schemas_boolean().optional(), - openWorldHint: schemas_boolean().optional() - }); - /** - * Execution-related properties for a tool. - */ - const ToolExecutionSchema$1 = schemas_object({ taskSupport: schemas_enum([ - "required", - "optional", - "forbidden" - ]).optional() }); - /** - * Definition for a tool the client can call. - */ - const ToolSchema$1 = schemas_object({ - ...BaseMetadataSchema$1.shape, - ...IconsSchema$1.shape, - description: schemas_string().optional(), - inputSchema: schemas_object({ - type: literal("object"), - properties: schemas_record(schemas_string(), JSONValueSchema$1).optional(), - required: schemas_array(schemas_string()).optional() - }).catchall(unknown()), - outputSchema: schemas_object({ - type: literal("object"), - properties: schemas_record(schemas_string(), JSONValueSchema$1).optional(), - required: schemas_array(schemas_string()).optional() - }).catchall(unknown()).optional(), - annotations: ToolAnnotationsSchema$1.optional(), - execution: ToolExecutionSchema$1.optional(), - _meta: schemas_record(schemas_string(), unknown()).optional() - }); - /** - * Sent from the client to request a list of tools the server has. - */ - const ListToolsRequestSchema$1 = PaginatedRequestSchema$1.extend({ method: literal("tools/list") }); - /** - * The server's response to a {@linkcode ListToolsRequest | tools/list} request from the client. - */ - const ListToolsResultSchema$1 = PaginatedResultSchema$1.extend({ tools: schemas_array(ToolSchema$1) }); - /** - * The server's response to a tool call. - */ - const CallToolResultSchema$1 = ResultSchema$1.extend({ - content: schemas_array(ContentBlockSchema$1), - structuredContent: schemas_record(schemas_string(), unknown()).optional(), - isError: schemas_boolean().optional() - }); - /** - * Parameters for a `tools/call` request. - */ - const CallToolRequestParamsSchema$1 = TaskAugmentedRequestParamsSchema$1.extend({ - name: schemas_string(), - arguments: schemas_record(schemas_string(), unknown()).optional() - }); - /** - * Used by the client to invoke a tool provided by the server. - */ - const CallToolRequestSchema$1 = RequestSchema$1.extend({ - method: literal("tools/call"), - params: CallToolRequestParamsSchema$1 - }); - /** - * An optional notification from the server to the client, informing it that the list of tools it offers has changed. This may be issued by servers without any previous subscription from the client. - */ - const ToolListChangedNotificationSchema$1 = NotificationSchema$1.extend({ - method: literal("notifications/tools/list_changed"), - params: NotificationsParamsSchema$1.optional() - }); - /** - * The severity of a log message. - * - * @deprecated Deprecated as of protocol version 2026-07-28 (SEP-2577); remains - * in the specification for at least twelve months. Migrate to stderr logging - * (STDIO servers) or OpenTelemetry. - */ - const LoggingLevelSchema$1 = schemas_enum([ - "debug", - "info", - "notice", - "warning", - "error", - "critical", - "alert", - "emergency" - ]); - /** - * Parameters for a `logging/setLevel` request. - * - * @deprecated Deprecated as of protocol version 2026-07-28 (SEP-2577); remains - * in the specification for at least twelve months. Migrate to stderr logging - * (STDIO servers) or OpenTelemetry. - */ - const SetLevelRequestParamsSchema$1 = BaseRequestParamsSchema$1.extend({ level: LoggingLevelSchema$1 }); - /** - * A request from the client to the server, to enable or adjust logging. - * - * @deprecated Deprecated as of protocol version 2026-07-28 (SEP-2577); remains - * in the specification for at least twelve months. Migrate to stderr logging - * (STDIO servers) or OpenTelemetry. - */ - const SetLevelRequestSchema$1 = RequestSchema$1.extend({ - method: literal("logging/setLevel"), - params: SetLevelRequestParamsSchema$1 - }); - /** - * Parameters for a `notifications/message` notification. - * - * @deprecated Deprecated as of protocol version 2026-07-28 (SEP-2577); remains - * in the specification for at least twelve months. Migrate to stderr logging - * (STDIO servers) or OpenTelemetry. - */ - const LoggingMessageNotificationParamsSchema$1 = NotificationsParamsSchema$1.extend({ - level: LoggingLevelSchema$1, - logger: schemas_string().optional(), - data: unknown() - }); - /** - * Notification of a log message passed from server to client. If no `logging/setLevel` request has been sent from the client, the server MAY decide which messages to send automatically. - * - * @deprecated Deprecated as of protocol version 2026-07-28 (SEP-2577); remains - * in the specification for at least twelve months. Migrate to stderr logging - * (STDIO servers) or OpenTelemetry. - */ - const LoggingMessageNotificationSchema$1 = NotificationSchema$1.extend({ - method: literal("notifications/message"), - params: LoggingMessageNotificationParamsSchema$1 - }); - /** - * Hints to use for model selection. - * - * @deprecated Deprecated as of protocol version 2026-07-28 (SEP-2577); remains - * in the specification for at least twelve months. Migrate to calling LLM - * provider APIs directly. - */ - const ModelHintSchema$1 = schemas_object({ name: schemas_string().optional() }); - /** - * The server's preferences for model selection, requested of the client during sampling. - * - * @deprecated Deprecated as of protocol version 2026-07-28 (SEP-2577); remains - * in the specification for at least twelve months. Migrate to calling LLM - * provider APIs directly. - */ - const ModelPreferencesSchema$1 = schemas_object({ - hints: schemas_array(ModelHintSchema$1).optional(), - costPriority: schemas_number().min(0).max(1).optional(), - speedPriority: schemas_number().min(0).max(1).optional(), - intelligencePriority: schemas_number().min(0).max(1).optional() - }); - /** - * Controls tool usage behavior in sampling requests. - * - * @deprecated Deprecated as of protocol version 2026-07-28 (SEP-2577); remains - * in the specification for at least twelve months. Migrate to calling LLM - * provider APIs directly. - */ - const ToolChoiceSchema$1 = schemas_object({ mode: schemas_enum([ - "auto", - "required", - "none" - ]).optional() }); - /** - * The result of a tool execution, provided by the user (server). - * Represents the outcome of invoking a tool requested via `ToolUseContent`. - * - * @deprecated Deprecated as of protocol version 2026-07-28 (SEP-2577); remains - * in the specification for at least twelve months. Migrate to calling LLM - * provider APIs directly. - */ - const ToolResultContentSchema$1 = schemas_object({ - type: literal("tool_result"), - toolUseId: schemas_string().describe("The unique identifier for the corresponding tool call."), - content: schemas_array(ContentBlockSchema$1), - structuredContent: schemas_object({}).loose().optional(), - isError: schemas_boolean().optional(), - _meta: schemas_record(schemas_string(), unknown()).optional() - }); - /** - * Basic content types for sampling responses (without tool use). - * Used for backwards-compatible {@linkcode CreateMessageResult} when tools are not used. - * - * @deprecated Deprecated as of protocol version 2026-07-28 (SEP-2577); remains - * in the specification for at least twelve months. Migrate to calling LLM - * provider APIs directly. - */ - const SamplingContentSchema$1 = discriminatedUnion("type", [ - TextContentSchema$1, - ImageContentSchema$1, - AudioContentSchema$1 - ]); - /** - * Content block types allowed in sampling messages. - * This includes text, image, audio, tool use requests, and tool results. - * - * @deprecated Deprecated as of protocol version 2026-07-28 (SEP-2577); remains - * in the specification for at least twelve months. Migrate to calling LLM - * provider APIs directly. - */ - const SamplingMessageContentBlockSchema$1 = discriminatedUnion("type", [ - TextContentSchema$1, - ImageContentSchema$1, - AudioContentSchema$1, - ToolUseContentSchema$1, - ToolResultContentSchema$1 - ]); - /** - * Describes a message issued to or received from an LLM API. - * - * @deprecated Deprecated as of protocol version 2026-07-28 (SEP-2577); remains - * in the specification for at least twelve months. Migrate to calling LLM - * provider APIs directly. - */ - const SamplingMessageSchema$1 = schemas_object({ - role: RoleSchema$1, - content: schemas_union([SamplingMessageContentBlockSchema$1, schemas_array(SamplingMessageContentBlockSchema$1)]), - _meta: schemas_record(schemas_string(), unknown()).optional() - }); - /** - * Parameters for a `sampling/createMessage` request. - * - * @deprecated Deprecated as of protocol version 2026-07-28 (SEP-2577); remains - * in the specification for at least twelve months. Migrate to calling LLM - * provider APIs directly. - */ - const CreateMessageRequestParamsSchema$1 = TaskAugmentedRequestParamsSchema$1.extend({ - messages: schemas_array(SamplingMessageSchema$1), - modelPreferences: ModelPreferencesSchema$1.optional(), - systemPrompt: schemas_string().optional(), - includeContext: schemas_enum([ - "none", - "thisServer", - "allServers" - ]).optional(), - temperature: schemas_number().optional(), - maxTokens: schemas_number().int(), - stopSequences: schemas_array(schemas_string()).optional(), - metadata: JSONObjectSchema$1.optional(), - tools: schemas_array(ToolSchema$1).optional(), - toolChoice: ToolChoiceSchema$1.optional() - }); - /** - * A request from the server to sample an LLM via the client. The client has full discretion over which model to select. The client should also inform the user before beginning sampling, to allow them to inspect the request (human in the loop) and decide whether to approve it. - * - * @deprecated Deprecated as of protocol version 2026-07-28 (SEP-2577); remains - * in the specification for at least twelve months. Migrate to calling LLM - * provider APIs directly. - */ - const CreateMessageRequestSchema$1 = RequestSchema$1.extend({ - method: literal("sampling/createMessage"), - params: CreateMessageRequestParamsSchema$1 - }); - /** - * The client's response to a `sampling/create_message` request from the server. - * This is the backwards-compatible version that returns single content (no arrays). - * Used when the request does not include tools. - * - * @deprecated Deprecated as of protocol version 2026-07-28 (SEP-2577); remains - * in the specification for at least twelve months. Migrate to calling LLM - * provider APIs directly. - */ - const CreateMessageResultSchema$1 = ResultSchema$1.extend({ - model: schemas_string(), - stopReason: schemas_optional(schemas_enum([ - "endTurn", - "stopSequence", - "maxTokens" - ]).or(schemas_string())), - role: RoleSchema$1, - content: SamplingContentSchema$1 - }); - /** - * The client's response to a `sampling/create_message` request when tools were provided. - * This version supports array content for tool use flows. - * - * @deprecated Deprecated as of protocol version 2026-07-28 (SEP-2577); remains - * in the specification for at least twelve months. Migrate to calling LLM - * provider APIs directly. - */ - const CreateMessageResultWithToolsSchema$1 = ResultSchema$1.extend({ - model: schemas_string(), - stopReason: schemas_optional(schemas_enum([ - "endTurn", - "stopSequence", - "maxTokens", - "toolUse" - ]).or(schemas_string())), - role: RoleSchema$1, - content: schemas_union([SamplingMessageContentBlockSchema$1, schemas_array(SamplingMessageContentBlockSchema$1)]) - }); - /** - * Primitive schema definition for boolean fields. - */ - const BooleanSchemaSchema$1 = schemas_object({ - type: literal("boolean"), - title: schemas_string().optional(), - description: schemas_string().optional(), - default: schemas_boolean().optional() - }); - /** - * Primitive schema definition for string fields. - */ - const StringSchemaSchema$1 = schemas_object({ - type: literal("string"), - title: schemas_string().optional(), - description: schemas_string().optional(), - minLength: schemas_number().optional(), - maxLength: schemas_number().optional(), - format: schemas_enum([ - "email", - "uri", - "date", - "date-time" - ]).optional(), - default: schemas_string().optional() - }); - /** - * Primitive schema definition for number fields. - */ - const NumberSchemaSchema$1 = schemas_object({ - type: schemas_enum(["number", "integer"]), - title: schemas_string().optional(), - description: schemas_string().optional(), - minimum: schemas_number().optional(), - maximum: schemas_number().optional(), - default: schemas_number().optional() - }); - /** - * Schema for single-selection enumeration without display titles for options. - */ - const UntitledSingleSelectEnumSchemaSchema$1 = schemas_object({ - type: literal("string"), - title: schemas_string().optional(), - description: schemas_string().optional(), - enum: schemas_array(schemas_string()), - default: schemas_string().optional() - }); - /** - * Schema for single-selection enumeration with display titles for each option. - */ - const TitledSingleSelectEnumSchemaSchema$1 = schemas_object({ - type: literal("string"), - title: schemas_string().optional(), - description: schemas_string().optional(), - oneOf: schemas_array(schemas_object({ - const: schemas_string(), - title: schemas_string() - })), - default: schemas_string().optional() - }); - /** - * Use {@linkcode TitledSingleSelectEnumSchema} instead. - * This interface will be removed in a future version. - */ - const LegacyTitledEnumSchemaSchema$1 = schemas_object({ - type: literal("string"), - title: schemas_string().optional(), - description: schemas_string().optional(), - enum: schemas_array(schemas_string()), - enumNames: schemas_array(schemas_string()).optional(), - default: schemas_string().optional() - }); - const SingleSelectEnumSchemaSchema$1 = schemas_union([UntitledSingleSelectEnumSchemaSchema$1, TitledSingleSelectEnumSchemaSchema$1]); - /** - * Schema for multiple-selection enumeration without display titles for options. - */ - const UntitledMultiSelectEnumSchemaSchema$1 = schemas_object({ - type: literal("array"), - title: schemas_string().optional(), - description: schemas_string().optional(), - minItems: schemas_number().optional(), - maxItems: schemas_number().optional(), - items: schemas_object({ - type: literal("string"), - enum: schemas_array(schemas_string()) - }), - default: schemas_array(schemas_string()).optional() - }); - /** - * Schema for multiple-selection enumeration with display titles for each option. - */ - const TitledMultiSelectEnumSchemaSchema$1 = schemas_object({ - type: literal("array"), - title: schemas_string().optional(), - description: schemas_string().optional(), - minItems: schemas_number().optional(), - maxItems: schemas_number().optional(), - items: schemas_object({ anyOf: schemas_array(schemas_object({ - const: schemas_string(), - title: schemas_string() - })) }), - default: schemas_array(schemas_string()).optional() - }); - /** - * Combined schema for multiple-selection enumeration - */ - const MultiSelectEnumSchemaSchema$1 = schemas_union([UntitledMultiSelectEnumSchemaSchema$1, TitledMultiSelectEnumSchemaSchema$1]); - /** - * Primitive schema definition for enum fields. - */ - const EnumSchemaSchema$1 = schemas_union([ - LegacyTitledEnumSchemaSchema$1, - SingleSelectEnumSchemaSchema$1, - MultiSelectEnumSchemaSchema$1 - ]); - /** - * Union of all primitive schema definitions. - */ - const PrimitiveSchemaDefinitionSchema$1 = schemas_union([ - EnumSchemaSchema$1, - BooleanSchemaSchema$1, - StringSchemaSchema$1, - NumberSchemaSchema$1 - ]); - /** - * Parameters for an `elicitation/create` request for form-based elicitation. - */ - const ElicitRequestFormParamsSchema$1 = TaskAugmentedRequestParamsSchema$1.extend({ - mode: literal("form").optional(), - message: schemas_string(), - requestedSchema: schemas_object({ - type: literal("object"), - properties: schemas_record(schemas_string(), PrimitiveSchemaDefinitionSchema$1), - required: schemas_array(schemas_string()).optional() - }).catchall(unknown()) - }); - /** - * Parameters for an {@linkcode ElicitRequest | elicitation/create} request for URL-based elicitation. - */ - const ElicitRequestURLParamsSchema$1 = TaskAugmentedRequestParamsSchema$1.extend({ - mode: literal("url"), - message: schemas_string(), - elicitationId: schemas_string(), - url: schemas_string().url() - }); - /** - * The parameters for a request to elicit additional information from the user via the client. - */ - const ElicitRequestParamsSchema$1 = schemas_union([ElicitRequestFormParamsSchema$1, ElicitRequestURLParamsSchema$1]); - /** - * A request from the server to elicit user input via the client. - * The client should present the message and form fields to the user (form mode) - * or navigate to a URL (URL mode). - */ - const ElicitRequestSchema$1 = RequestSchema$1.extend({ - method: literal("elicitation/create"), - params: ElicitRequestParamsSchema$1 - }); - /** - * Parameters for a {@linkcode ElicitationCompleteNotification | notifications/elicitation/complete} notification. - * - * @category notifications/elicitation/complete - */ - const ElicitationCompleteNotificationParamsSchema$1 = NotificationsParamsSchema$1.extend({ elicitationId: schemas_string() }); - /** - * A notification from the server to the client, informing it of a completion of an out-of-band elicitation request. - * - * @category notifications/elicitation/complete - */ - const ElicitationCompleteNotificationSchema$1 = NotificationSchema$1.extend({ - method: literal("notifications/elicitation/complete"), - params: ElicitationCompleteNotificationParamsSchema$1 - }); - /** - * The client's response to an {@linkcode ElicitRequest | elicitation/create} request from the server. - */ - const ElicitResultSchema$1 = ResultSchema$1.extend({ - action: schemas_enum([ - "accept", - "decline", - "cancel" - ]), - content: preprocess((val) => val === null ? void 0 : val, schemas_record(schemas_string(), schemas_union([ - schemas_string(), - schemas_number(), - schemas_boolean(), - schemas_array(schemas_string()) - ])).optional()) - }); - /** - * A reference to a resource or resource template definition. - */ - const ResourceTemplateReferenceSchema$1 = schemas_object({ - type: literal("ref/resource"), - uri: schemas_string() - }); - /** - * Identifies a prompt. - */ - const PromptReferenceSchema$1 = schemas_object({ - type: literal("ref/prompt"), - name: schemas_string() - }); - /** - * Parameters for a {@linkcode CompleteRequest | completion/complete} request. - */ - const CompleteRequestParamsSchema$1 = BaseRequestParamsSchema$1.extend({ - ref: schemas_union([PromptReferenceSchema$1, ResourceTemplateReferenceSchema$1]), - argument: schemas_object({ - name: schemas_string(), - value: schemas_string() - }), - context: schemas_object({ arguments: schemas_record(schemas_string(), schemas_string()).optional() }).optional() - }); - /** - * A request from the client to the server, to ask for completion options. - */ - const CompleteRequestSchema$1 = RequestSchema$1.extend({ - method: literal("completion/complete"), - params: CompleteRequestParamsSchema$1 - }); - /** - * The server's response to a {@linkcode CompleteRequest | completion/complete} request - */ - const CompleteResultSchema$1 = ResultSchema$1.extend({ completion: looseObject({ - values: schemas_array(schemas_string()).max(100), - total: schemas_optional(schemas_number().int()), - hasMore: schemas_optional(schemas_boolean()) - }) }); - /** - * Represents a root directory or file that the server can operate on. - * - * @deprecated Deprecated as of protocol version 2026-07-28 (SEP-2577); remains - * in the specification for at least twelve months. Migrate to passing paths via - * tool parameters, resource URIs, or configuration. - */ - const RootSchema$1 = schemas_object({ - uri: schemas_string().startsWith("file://"), - name: schemas_string().optional(), - _meta: schemas_record(schemas_string(), unknown()).optional() - }); - /** - * Sent from the server to request a list of root URIs from the client. - * - * @deprecated Deprecated as of protocol version 2026-07-28 (SEP-2577); remains - * in the specification for at least twelve months. Migrate to passing paths via - * tool parameters, resource URIs, or configuration. - */ - const ListRootsRequestSchema$1 = RequestSchema$1.extend({ - method: literal("roots/list"), - params: BaseRequestParamsSchema$1.optional() - }); - /** - * The client's response to a `roots/list` request from the server. - * - * @deprecated Deprecated as of protocol version 2026-07-28 (SEP-2577); remains - * in the specification for at least twelve months. Migrate to passing paths via - * tool parameters, resource URIs, or configuration. - */ - const ListRootsResultSchema$1 = ResultSchema$1.extend({ roots: schemas_array(RootSchema$1) }); - /** - * A notification from the client to the server, informing it that the list of roots has changed. - * - * @deprecated Deprecated as of protocol version 2026-07-28 (SEP-2577); remains - * in the specification for at least twelve months. Migrate to passing paths via - * tool parameters, resource URIs, or configuration. - */ - const RootsListChangedNotificationSchema$1 = NotificationSchema$1.extend({ - method: literal("notifications/roots/list_changed"), - params: NotificationsParamsSchema$1.optional() - }); - /** - * Task creation parameters, used to ask that the server create a task to represent a request. - * - * @deprecated 2025-11-25 wire vocabulary with no SDK runtime; kept importable for interoperability only. - */ - const TaskCreationParamsSchema$1 = looseObject({ - ttl: schemas_number().optional(), - pollInterval: schemas_number().optional() - }); - /** - * The status of a task. - * - * @deprecated 2025-11-25 wire vocabulary with no SDK runtime; kept importable for interoperability only. - */ - const TaskStatusSchema$1 = schemas_enum([ - "working", - "input_required", - "completed", - "failed", - "cancelled" - ]); - /** - * A pollable state object associated with a request. - * - * @deprecated 2025-11-25 wire vocabulary with no SDK runtime; kept importable for interoperability only. - */ - const TaskSchema$1 = schemas_object({ - taskId: schemas_string(), - status: TaskStatusSchema$1, - ttl: schemas_union([schemas_number(), schemas_null()]), - createdAt: schemas_string(), - lastUpdatedAt: schemas_string(), - pollInterval: schemas_optional(schemas_number()), - statusMessage: schemas_optional(schemas_string()) - }); - /** - * Result returned when a task is created, containing the task data wrapped in a `task` field. - * - * @deprecated 2025-11-25 wire vocabulary with no SDK runtime; kept importable for interoperability only. - */ - const CreateTaskResultSchema$1 = ResultSchema$1.extend({ task: TaskSchema$1 }); - /** - * Parameters for task status notification. - * - * @deprecated 2025-11-25 wire vocabulary with no SDK runtime; kept importable for interoperability only. - */ - const TaskStatusNotificationParamsSchema$1 = NotificationsParamsSchema$1.merge(TaskSchema$1); - /** - * A notification sent when a task's status changes. - * - * @deprecated 2025-11-25 wire vocabulary with no SDK runtime; kept importable for interoperability only. - */ - const TaskStatusNotificationSchema$1 = NotificationSchema$1.extend({ - method: literal("notifications/tasks/status"), - params: TaskStatusNotificationParamsSchema$1 - }); - /** - * A request to get the state of a specific task. - * - * @deprecated 2025-11-25 wire vocabulary with no SDK runtime; kept importable for interoperability only. - */ - const GetTaskRequestSchema$1 = RequestSchema$1.extend({ - method: literal("tasks/get"), - params: BaseRequestParamsSchema$1.extend({ taskId: schemas_string() }) - }); - /** - * The response to a {@linkcode GetTaskRequest | tasks/get} request. - * - * @deprecated 2025-11-25 wire vocabulary with no SDK runtime; kept importable for interoperability only. - */ - const GetTaskResultSchema$1 = ResultSchema$1.merge(TaskSchema$1); - /** - * A request to get the result of a specific task. - * - * @deprecated 2025-11-25 wire vocabulary with no SDK runtime; kept importable for interoperability only. - */ - const GetTaskPayloadRequestSchema$1 = RequestSchema$1.extend({ - method: literal("tasks/result"), - params: BaseRequestParamsSchema$1.extend({ taskId: schemas_string() }) - }); - /** - * The response to a `tasks/result` request. - * The structure matches the result type of the original request. - * For example, a {@linkcode CallToolRequest | tools/call} task would return the `CallToolResult` structure. - * - * - * @deprecated 2025-11-25 wire vocabulary with no SDK runtime; kept importable for interoperability only. - */ - const GetTaskPayloadResultSchema$1 = ResultSchema$1.loose(); - /** - * A request to list tasks. - * - * @deprecated 2025-11-25 wire vocabulary with no SDK runtime; kept importable for interoperability only. - */ - const ListTasksRequestSchema$1 = PaginatedRequestSchema$1.extend({ method: literal("tasks/list") }); - /** - * The response to a {@linkcode ListTasksRequest | tasks/list} request. - * - * @deprecated 2025-11-25 wire vocabulary with no SDK runtime; kept importable for interoperability only. - */ - const ListTasksResultSchema$1 = PaginatedResultSchema$1.extend({ tasks: schemas_array(TaskSchema$1) }); - /** - * A request to cancel a specific task. - * - * @deprecated 2025-11-25 wire vocabulary with no SDK runtime; kept importable for interoperability only. - */ - const CancelTaskRequestSchema$1 = RequestSchema$1.extend({ - method: literal("tasks/cancel"), - params: BaseRequestParamsSchema$1.extend({ taskId: schemas_string() }) - }); - return { - JSONValueSchema: JSONValueSchema$1, - JSONObjectSchema: JSONObjectSchema$1, - ProgressTokenSchema: ProgressTokenSchema$1, - CursorSchema: CursorSchema$1, - TaskMetadataSchema: TaskMetadataSchema$1, - RelatedTaskMetadataSchema: RelatedTaskMetadataSchema$1, - RequestMetaSchema: RequestMetaSchema$1, - BaseRequestParamsSchema: BaseRequestParamsSchema$1, - TaskAugmentedRequestParamsSchema: TaskAugmentedRequestParamsSchema$1, - RequestSchema: RequestSchema$1, - NotificationsParamsSchema: NotificationsParamsSchema$1, - NotificationSchema: NotificationSchema$1, - ResultSchema: ResultSchema$1, - RequestIdSchema: RequestIdSchema$1, - EmptyResultSchema: EmptyResultSchema$1, - CancelledNotificationParamsSchema: CancelledNotificationParamsSchema$1, - CancelledNotificationSchema: CancelledNotificationSchema$1, - IconSchema: IconSchema$1, - IconsSchema: IconsSchema$1, - BaseMetadataSchema: BaseMetadataSchema$1, - ImplementationSchema: ImplementationSchema$1, - ClientTasksCapabilitySchema: ClientTasksCapabilitySchema$1, - ServerTasksCapabilitySchema: ServerTasksCapabilitySchema$1, - ClientCapabilitiesSchema: ClientCapabilitiesSchema$1, - InitializeRequestParamsSchema: InitializeRequestParamsSchema$1, - InitializeRequestSchema: InitializeRequestSchema$1, - ServerCapabilitiesSchema: ServerCapabilitiesSchema$1, - InitializeResultSchema: InitializeResultSchema$1, - InitializedNotificationSchema: InitializedNotificationSchema$1, - PingRequestSchema: PingRequestSchema$1, - ProgressSchema: ProgressSchema$1, - ProgressNotificationParamsSchema: ProgressNotificationParamsSchema$1, - ProgressNotificationSchema: ProgressNotificationSchema$1, - PaginatedRequestParamsSchema: PaginatedRequestParamsSchema$1, - PaginatedRequestSchema: PaginatedRequestSchema$1, - PaginatedResultSchema: PaginatedResultSchema$1, - ResourceContentsSchema: ResourceContentsSchema$1, - TextResourceContentsSchema: TextResourceContentsSchema$1, - BlobResourceContentsSchema: BlobResourceContentsSchema$1, - RoleSchema: RoleSchema$1, - AnnotationsSchema: AnnotationsSchema$1, - ResourceSchema: ResourceSchema$1, - ResourceTemplateSchema: ResourceTemplateSchema$1, - ListResourcesRequestSchema: ListResourcesRequestSchema$1, - ListResourcesResultSchema: ListResourcesResultSchema$1, - ListResourceTemplatesRequestSchema: ListResourceTemplatesRequestSchema$1, - ListResourceTemplatesResultSchema: ListResourceTemplatesResultSchema$1, - ResourceRequestParamsSchema: ResourceRequestParamsSchema$1, - ReadResourceRequestParamsSchema: ReadResourceRequestParamsSchema$1, - ReadResourceRequestSchema: ReadResourceRequestSchema$1, - ReadResourceResultSchema: ReadResourceResultSchema$1, - ResourceListChangedNotificationSchema: ResourceListChangedNotificationSchema$1, - SubscribeRequestParamsSchema: SubscribeRequestParamsSchema$1, - SubscribeRequestSchema: SubscribeRequestSchema$1, - UnsubscribeRequestParamsSchema: UnsubscribeRequestParamsSchema$1, - UnsubscribeRequestSchema: UnsubscribeRequestSchema$1, - ResourceUpdatedNotificationParamsSchema: ResourceUpdatedNotificationParamsSchema$1, - ResourceUpdatedNotificationSchema: ResourceUpdatedNotificationSchema$1, - PromptArgumentSchema: PromptArgumentSchema$1, - PromptSchema: PromptSchema$1, - ListPromptsRequestSchema: ListPromptsRequestSchema$1, - ListPromptsResultSchema: ListPromptsResultSchema$1, - GetPromptRequestParamsSchema: GetPromptRequestParamsSchema$1, - GetPromptRequestSchema: GetPromptRequestSchema$1, - TextContentSchema: TextContentSchema$1, - ImageContentSchema: ImageContentSchema$1, - AudioContentSchema: AudioContentSchema$1, - ToolUseContentSchema: ToolUseContentSchema$1, - EmbeddedResourceSchema: EmbeddedResourceSchema$1, - ResourceLinkSchema: ResourceLinkSchema$1, - ContentBlockSchema: ContentBlockSchema$1, - PromptMessageSchema: PromptMessageSchema$1, - GetPromptResultSchema: GetPromptResultSchema$1, - PromptListChangedNotificationSchema: PromptListChangedNotificationSchema$1, - ToolAnnotationsSchema: ToolAnnotationsSchema$1, - ToolExecutionSchema: ToolExecutionSchema$1, - ToolSchema: ToolSchema$1, - ListToolsRequestSchema: ListToolsRequestSchema$1, - ListToolsResultSchema: ListToolsResultSchema$1, - CallToolResultSchema: CallToolResultSchema$1, - CallToolRequestParamsSchema: CallToolRequestParamsSchema$1, - CallToolRequestSchema: CallToolRequestSchema$1, - ToolListChangedNotificationSchema: ToolListChangedNotificationSchema$1, - LoggingLevelSchema: LoggingLevelSchema$1, - SetLevelRequestParamsSchema: SetLevelRequestParamsSchema$1, - SetLevelRequestSchema: SetLevelRequestSchema$1, - LoggingMessageNotificationParamsSchema: LoggingMessageNotificationParamsSchema$1, - LoggingMessageNotificationSchema: LoggingMessageNotificationSchema$1, - ModelHintSchema: ModelHintSchema$1, - ModelPreferencesSchema: ModelPreferencesSchema$1, - ToolChoiceSchema: ToolChoiceSchema$1, - ToolResultContentSchema: ToolResultContentSchema$1, - SamplingContentSchema: SamplingContentSchema$1, - SamplingMessageContentBlockSchema: SamplingMessageContentBlockSchema$1, - SamplingMessageSchema: SamplingMessageSchema$1, - CreateMessageRequestParamsSchema: CreateMessageRequestParamsSchema$1, - CreateMessageRequestSchema: CreateMessageRequestSchema$1, - CreateMessageResultSchema: CreateMessageResultSchema$1, - CreateMessageResultWithToolsSchema: CreateMessageResultWithToolsSchema$1, - BooleanSchemaSchema: BooleanSchemaSchema$1, - StringSchemaSchema: StringSchemaSchema$1, - NumberSchemaSchema: NumberSchemaSchema$1, - UntitledSingleSelectEnumSchemaSchema: UntitledSingleSelectEnumSchemaSchema$1, - TitledSingleSelectEnumSchemaSchema: TitledSingleSelectEnumSchemaSchema$1, - LegacyTitledEnumSchemaSchema: LegacyTitledEnumSchemaSchema$1, - SingleSelectEnumSchemaSchema: SingleSelectEnumSchemaSchema$1, - UntitledMultiSelectEnumSchemaSchema: UntitledMultiSelectEnumSchemaSchema$1, - TitledMultiSelectEnumSchemaSchema: TitledMultiSelectEnumSchemaSchema$1, - MultiSelectEnumSchemaSchema: MultiSelectEnumSchemaSchema$1, - EnumSchemaSchema: EnumSchemaSchema$1, - PrimitiveSchemaDefinitionSchema: PrimitiveSchemaDefinitionSchema$1, - ElicitRequestFormParamsSchema: ElicitRequestFormParamsSchema$1, - ElicitRequestURLParamsSchema: ElicitRequestURLParamsSchema$1, - ElicitRequestParamsSchema: ElicitRequestParamsSchema$1, - ElicitRequestSchema: ElicitRequestSchema$1, - ElicitationCompleteNotificationParamsSchema: ElicitationCompleteNotificationParamsSchema$1, - ElicitationCompleteNotificationSchema: ElicitationCompleteNotificationSchema$1, - ElicitResultSchema: ElicitResultSchema$1, - ResourceTemplateReferenceSchema: ResourceTemplateReferenceSchema$1, - PromptReferenceSchema: PromptReferenceSchema$1, - CompleteRequestParamsSchema: CompleteRequestParamsSchema$1, - CompleteRequestSchema: CompleteRequestSchema$1, - CompleteResultSchema: CompleteResultSchema$1, - RootSchema: RootSchema$1, - ListRootsRequestSchema: ListRootsRequestSchema$1, - ListRootsResultSchema: ListRootsResultSchema$1, - RootsListChangedNotificationSchema: RootsListChangedNotificationSchema$1, - TaskCreationParamsSchema: TaskCreationParamsSchema$1, - TaskStatusSchema: TaskStatusSchema$1, - TaskSchema: TaskSchema$1, - CreateTaskResultSchema: CreateTaskResultSchema$1, - TaskStatusNotificationParamsSchema: TaskStatusNotificationParamsSchema$1, - TaskStatusNotificationSchema: TaskStatusNotificationSchema$1, - GetTaskRequestSchema: GetTaskRequestSchema$1, - GetTaskResultSchema: GetTaskResultSchema$1, - GetTaskPayloadRequestSchema: GetTaskPayloadRequestSchema$1, - GetTaskPayloadResultSchema: GetTaskPayloadResultSchema$1, - ListTasksRequestSchema: ListTasksRequestSchema$1, - ListTasksResultSchema: ListTasksResultSchema$1, - CancelTaskRequestSchema: CancelTaskRequestSchema$1, - CancelTaskResultSchema: ResultSchema$1.merge(TaskSchema$1), - ClientRequestSchema: schemas_union([ - PingRequestSchema$1, - InitializeRequestSchema$1, - CompleteRequestSchema$1, - SetLevelRequestSchema$1, - GetPromptRequestSchema$1, - ListPromptsRequestSchema$1, - ListResourcesRequestSchema$1, - ListResourceTemplatesRequestSchema$1, - ReadResourceRequestSchema$1, - SubscribeRequestSchema$1, - UnsubscribeRequestSchema$1, - CallToolRequestSchema$1, - ListToolsRequestSchema$1, - GetTaskRequestSchema$1, - GetTaskPayloadRequestSchema$1, - ListTasksRequestSchema$1, - CancelTaskRequestSchema$1 - ]), - ClientNotificationSchema: schemas_union([ - CancelledNotificationSchema$1, - ProgressNotificationSchema$1, - InitializedNotificationSchema$1, - RootsListChangedNotificationSchema$1, - TaskStatusNotificationSchema$1 - ]), - ClientResultSchema: schemas_union([ - EmptyResultSchema$1, - CreateMessageResultSchema$1, - CreateMessageResultWithToolsSchema$1, - ElicitResultSchema$1, - ListRootsResultSchema$1, - GetTaskResultSchema$1, - ListTasksResultSchema$1, - CreateTaskResultSchema$1 - ]), - ServerRequestSchema: schemas_union([ - PingRequestSchema$1, - CreateMessageRequestSchema$1, - ElicitRequestSchema$1, - ListRootsRequestSchema$1, - GetTaskRequestSchema$1, - GetTaskPayloadRequestSchema$1, - ListTasksRequestSchema$1, - CancelTaskRequestSchema$1 - ]), - ServerNotificationSchema: schemas_union([ - CancelledNotificationSchema$1, - ProgressNotificationSchema$1, - LoggingMessageNotificationSchema$1, - ResourceUpdatedNotificationSchema$1, - ResourceListChangedNotificationSchema$1, - ToolListChangedNotificationSchema$1, - PromptListChangedNotificationSchema$1, - TaskStatusNotificationSchema$1, - ElicitationCompleteNotificationSchema$1 - ]), - ServerResultSchema: schemas_union([ - EmptyResultSchema$1, - InitializeResultSchema$1, - CompleteResultSchema$1, - GetPromptResultSchema$1, - ListPromptsResultSchema$1, - ListResourcesResultSchema$1, - ListResourceTemplatesResultSchema$1, - ReadResourceResultSchema$1, - CallToolResultSchema$1, - ListToolsResultSchema$1, - GetTaskResultSchema$1, - ListTasksResultSchema$1, - CreateTaskResultSchema$1 - ]), - CallToolResultWireSchema: unknown().superRefine((value, ctx) => { - if (typeof value !== "object" || value === null || Array.isArray(value) || value.content !== void 0) return; - for (const key of TOOL_RESULT_FOREIGN_FAMILY_KEYS) if (key in value) { - ctx.addIssue({ - code: "custom", - message: `content is required when the body carries '${key}' — another result family cannot default into an empty tools/call success` - }); - return; - } - }).transform(normalizeContentlessToolResult).pipe(CallToolResultSchema$1) - }; -} -let memo$1; -/** -* Builds the era wire-schema set on first call and returns the same object -* thereafter. Module evaluation stays construction-free so importing the -* era codec/registry costs nothing until the first validation actually -* needs a schema; the registry, the codec, and the eager `schemas.ts` -* shim all pull through this memo, so reference identity holds across -* every consumer. -*/ -function buildSchemas2025() { - return memo$1 ??= build$1(); -} - -//#endregion -//#region ../core-internal/src/wire/rev2025-11-25/legacyWrap.ts -/** -* SEP-2106 legacy `outputSchema` wrap helpers (2025-era projection only). -* -* The neutral / 2026-07-28 model lets a tool's `outputSchema` carry any JSON -* Schema root. The 2025-11-25 wire shape requires `type:'object'` at the root, -* so when an era-blind handler advertises a non-object root, the 2025 codec's -* `encodeResult('tools/list', …)` projects it down to -* `{type:'object', properties:{result:}, required:['result']}`, and -* `projectCallToolResult` wraps the matching `structuredContent` as -* `{result:}`. The 2026 codec's projections are the identity. -* -* These helpers are wire-layer property — they exist so the projection can -* live behind {@link WireCodec.encodeResult} / {@link WireCodec.projectCallToolResult} -* and never be re-derived in shared/ or server-side code. -*/ -/** -* Whether a JSON Schema's root is non-object: either an explicit non-object -* `type`, or a typeless root such as `{anyOf:[…]}`. Object-shaped typeless -* roots that the schema-conversion layer can prove are objects are stamped -* `type:'object'` upstream, so they reach this predicate as object roots. -*/ -function isNonObjectJsonSchemaRoot(json) { - return json["type"] !== "object"; -} -/** -* Keyword-position keys whose values are instance data (not subschemas). A -* `{$ref:…}` appearing inside one is a literal value, not a JSON Pointer to -* rewrite. Only consulted when the current object is in keyword position — -* a PROPERTY named `default`/`const` (under `properties`/`$defs`/…) is a name -* position whose value IS a subschema and is recursed into. -*/ -const REF_REWRITE_DATA_POSITION_KEYS = new Set([ - "const", - "enum", - "default", - "examples" -]); -/** -* Keyword-position keys whose value is a name→subschema map. Entries inside -* such a map are in NAME position: their keys are author-chosen property -* names (which may collide with JSON Schema keywords), their values are -* subschemas to recurse into. -*/ -const REF_REWRITE_NAME_MAP_KEYS = new Set([ - "properties", - "patternProperties", - "$defs", - "definitions", - "dependentSchemas", - "dependencies" -]); -/** -* Whether a subtree's `$id` establishes a new resolution base. A fragment-only -* `$id` (`"#item"`, the draft-07/06 spelling of 2020-12's `$anchor`) does not -* change the RFC 3986 base URI — same-document pointers inside still resolve -* against the document root and must be rewritten. -*/ -function establishesNewBase(id) { - return id !== void 0 && !(typeof id === "string" && id.startsWith("#")); -} -/** -* Wrap a non-object output schema in the 2025-era envelope: -* `{type:'object', properties:{result:}, required:['result']}`. -* -* Same-document `$ref` / `$dynamicRef` JSON Pointers inside the natural schema -* (e.g. `#/properties/foo` produced by zod for de-duplicated/recursive types) -* are rewritten to account for the new `#/properties/result` root: bare `#` → -* `#/properties/result`, `#/…` → `#/properties/result/…`. Cross-document refs -* (anything not starting with `#`) are left untouched. -* -* The rewrite is position-aware: data-valued keywords -* (`const`/`enum`/`default`/`examples`) in keyword position are NOT descended -* into; the same names appearing as property names under -* `properties`/`patternProperties`/`$defs`/`definitions`/`dependentSchemas`/ -* `dependencies` ARE descended into (they're subschemas). The rewrite is also -* `$id`-scoped: if the natural root carries a base-establishing `$id` no -* pointer is rewritten (same-document refs inside resolve against the embedded -* `$id` base, not the wrapper root), and any subtree that establishes its own -* `$id` is left untouched for the same reason. Fragment-only `$id` (`"#item"`, -* draft-07's anchor spelling) does not establish a base and IS descended into. -*/ -function wrapOutputSchemaForLegacy(natural) { - const $schema = typeof natural["$schema"] === "string" ? natural["$schema"] : void 0; - if (establishesNewBase(natural["$id"])) return { - ...$schema !== void 0 && { $schema }, - type: "object", - properties: { result: natural }, - required: ["result"] - }; - const convertRecursiveRefs = declares2019Dialect(natural["$schema"]) && natural["$recursiveAnchor"] !== true; - const rewriteRefs = (node, parentIsNameMap) => { - if (Array.isArray(node)) return node.map((item) => rewriteRefs(item, false)); - if (node === null || typeof node !== "object") return node; - if (!parentIsNameMap && establishesNewBase(node["$id"])) return node; - const out = {}; - let convertedRecursion = false; - for (const [k, v] of Object.entries(node)) if (parentIsNameMap) out[k] = rewriteRefs(v, false); - else if ((k === "$ref" || k === "$dynamicRef") && typeof v === "string") out[k] = v === "#" ? "#/properties/result" : v.startsWith("#/") ? `#/properties/result${v.slice(1)}` : v; - else if (k === "$recursiveRef" && v === "#" && convertRecursiveRefs) convertedRecursion = true; - else if (REF_REWRITE_DATA_POSITION_KEYS.has(k)) out[k] = v; - else if (REF_REWRITE_NAME_MAP_KEYS.has(k)) out[k] = rewriteRefs(v, true); - else out[k] = rewriteRefs(v, false); - if (convertedRecursion) if ("$ref" in out) out["allOf"] = [...Array.isArray(out["allOf"]) ? out["allOf"] : [], { $ref: "#/properties/result" }]; - else out["$ref"] = "#/properties/result"; - return out; - }; - return { - ...$schema !== void 0 && { $schema }, - type: "object", - properties: { result: rewriteRefs(natural, false) }, - required: ["result"] - }; -} - -//#endregion -//#region ../core-internal/src/wire/rev2025-11-25/registry.ts -const requestMethodKeys$1 = { - 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 -}; -const notificationMethodKeys$1 = { - "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 -}; -const resultMethodKeys = { - 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 -}; -let maps$1; -function registryMaps() { - if (maps$1) return maps$1; - const s = buildSchemas2025(); - maps$1 = { - requestSchemas: { - ping: s.PingRequestSchema, - initialize: s.InitializeRequestSchema, - "completion/complete": s.CompleteRequestSchema, - "logging/setLevel": s.SetLevelRequestSchema, - "prompts/get": s.GetPromptRequestSchema, - "prompts/list": s.ListPromptsRequestSchema, - "resources/list": s.ListResourcesRequestSchema, - "resources/templates/list": s.ListResourceTemplatesRequestSchema, - "resources/read": s.ReadResourceRequestSchema, - "resources/subscribe": s.SubscribeRequestSchema, - "resources/unsubscribe": s.UnsubscribeRequestSchema, - "tools/call": s.CallToolRequestSchema, - "tools/list": s.ListToolsRequestSchema, - "tasks/get": s.GetTaskRequestSchema, - "tasks/result": s.GetTaskPayloadRequestSchema, - "tasks/list": s.ListTasksRequestSchema, - "tasks/cancel": s.CancelTaskRequestSchema, - "sampling/createMessage": s.CreateMessageRequestSchema, - "elicitation/create": s.ElicitRequestSchema, - "roots/list": s.ListRootsRequestSchema - }, - notificationSchemas: { - "notifications/cancelled": s.CancelledNotificationSchema, - "notifications/progress": s.ProgressNotificationSchema, - "notifications/initialized": s.InitializedNotificationSchema, - "notifications/roots/list_changed": s.RootsListChangedNotificationSchema, - "notifications/tasks/status": s.TaskStatusNotificationSchema, - "notifications/message": s.LoggingMessageNotificationSchema, - "notifications/resources/updated": s.ResourceUpdatedNotificationSchema, - "notifications/resources/list_changed": s.ResourceListChangedNotificationSchema, - "notifications/tools/list_changed": s.ToolListChangedNotificationSchema, - "notifications/prompts/list_changed": s.PromptListChangedNotificationSchema, - "notifications/elicitation/complete": s.ElicitationCompleteNotificationSchema - }, - resultSchemas: { - ping: s.EmptyResultSchema, - initialize: s.InitializeResultSchema, - "completion/complete": s.CompleteResultSchema, - "logging/setLevel": s.EmptyResultSchema, - "prompts/get": s.GetPromptResultSchema, - "prompts/list": s.ListPromptsResultSchema, - "resources/list": s.ListResourcesResultSchema, - "resources/templates/list": s.ListResourceTemplatesResultSchema, - "resources/read": s.ReadResourceResultSchema, - "resources/subscribe": s.EmptyResultSchema, - "resources/unsubscribe": s.EmptyResultSchema, - "tools/call": s.CallToolResultWireSchema, - "tools/list": s.ListToolsResultSchema, - "sampling/createMessage": s.CreateMessageResultWithToolsSchema, - "elicitation/create": s.ElicitResultSchema, - "roots/list": s.ListRootsResultSchema - } - }; - return maps$1; -} -/** -* Forces the lazy registry maps (and, through them, the era's schema memo). -* Warm-up hook for `preloadSchemas()` — no-op once the maps exist. -*/ -function warmRegistryMaps2025() { - registryMaps(); -} -/** The 2025-era request-method set (registry membership = the deletion story). */ -function hasRequestMethod2025(method) { - return Object.prototype.hasOwnProperty.call(requestMethodKeys$1, method); -} -/** The 2025-era notification-method set. */ -function hasNotificationMethod2025(method) { - return Object.prototype.hasOwnProperty.call(notificationMethodKeys$1, method); -} -/** Result-map membership: exactly the era's typed-method subset (no task entries, no 2026-only methods). */ -function hasResultMethod(method) { - return Object.prototype.hasOwnProperty.call(resultMethodKeys, method); -} -function getResultSchema(method) { - return hasResultMethod(method) ? registryMaps().resultSchemas[method] : void 0; -} -function getRequestSchema(method) { - return hasRequestMethod2025(method) ? registryMaps().requestSchemas[method] : void 0; -} -function getNotificationSchema(method) { - return hasNotificationMethod2025(method) ? registryMaps().notificationSchemas[method] : void 0; -} -/** Registry method lists (for the spec-method universe and the CI registry-diff oracle). */ -const rev2025RequestMethods = Object.keys(requestMethodKeys$1); -const rev2025NotificationMethods = Object.keys(notificationMethodKeys$1); - -//#endregion -//#region ../core-internal/src/wire/rev2025-11-25/codec.ts -function isPlainObject$6(value) { - return value !== null && typeof value === "object" && !Array.isArray(value); -} -/** Tri-state wrap of an optional Zod schema lookup (the function-only contract). */ -function triState$1(schema, raw) { - if (schema === void 0) return { - ok: false, - reason: "not-in-era" - }; - const parsed = schema.safeParse(raw); - return parsed.success ? { - ok: true, - value: parsed.data - } : { - ok: false, - reason: "invalid", - message: String(parsed.error) - }; -} -const NOT_IN_ERA$1 = { - ok: false, - reason: "not-in-era" -}; -/** Whether a `tools/list` entry advertises a non-object `outputSchema` root that needs the SEP-2106 legacy wrap. */ -function toolNeedsLegacyWrap(t) { - return isPlainObject$6(t) && isPlainObject$6(t["outputSchema"]) && isNonObjectJsonSchemaRoot(t["outputSchema"]); -} -/** The wire→neutral trust boundary: a decoded 2025-era wire result is adopted as the neutral `Result` here (the module's single deliberate assertion). */ -function toNeutralResult(value) { - return value; -} -const rev2025Codec = { - era: "2025-11-25", - hasRequestMethod: hasRequestMethod2025, - hasNotificationMethod: hasNotificationMethod2025, - validateRequest: (method, raw) => triState$1(getRequestSchema(method), raw), - validateResult: (method, raw) => triState$1(getResultSchema(method), raw), - validateNotification: (method, raw) => triState$1(getNotificationSchema(method), raw), - hasInputRequestMethod: () => false, - validateInputRequest: () => NOT_IN_ERA$1, - validateInputResponse: () => NOT_IN_ERA$1, - samplingResultVariant: ((hasTools, raw) => { - const s = buildSchemas2025(); - return triState$1(hasTools ? s.CreateMessageResultWithToolsSchema : s.CreateMessageResultSchema, raw); - }), - outboundEnvelope: (_material) => void 0, - validateEnvelopeMeta: (_meta) => [], - projectCallToolResult(result, advertisedOutputSchema) { - const withText = appendTextFallbackForNonObject(result); - const sc = withText.structuredContent; - if (sc === void 0) return withText; - const valueIsNonObject = typeof sc !== "object" || sc === null || Array.isArray(sc); - const schemaWrapped = advertisedOutputSchema !== void 0 && isNonObjectJsonSchemaRoot(advertisedOutputSchema); - if (!valueIsNonObject && !schemaWrapped) return withText; - return { - ...withText, - structuredContent: { result: sc } - }; - }, - decodeResult(_method, raw) { - if (isPlainObject$6(raw) && "resultType" in raw) { - const stripped = { ...raw }; - delete stripped["resultType"]; - return { - kind: "complete", - result: toNeutralResult(stripped) - }; - } - return { - kind: "complete", - result: toNeutralResult(raw) - }; - }, - encodeResult(method, result) { - if (method !== "tools/list") return result; - const tools = result.tools; - if (!Array.isArray(tools) || !tools.some((t) => toolNeedsLegacyWrap(t))) return result; - return { - ...result, - tools: tools.map((t) => toolNeedsLegacyWrap(t) ? { - ...t, - outputSchema: wrapOutputSchemaForLegacy(t.outputSchema) - } : t) - }; - }, - encodeErrorCode: (code) => code === -32002 ? -32602 : code, - checkInboundEnvelope: (_material) => void 0 -}; - -//#endregion -//#region ../core-internal/src/wire/rev2026-07-28/buildSchemas.ts -/** -* 2026-era wire schemas (protocol revision 2026-07-28). -* -* Fully self-contained — no runtime imports from types/schemas.ts. The -* neutral types/schemas.ts layer is the public-API superset and is free to -* evolve; this file is the 2026 wire-parse contract and is BEHAVIOR-FROZEN -* against the 2026-07-28 anchor. Every era-shared building block (content -* blocks, resources, prompts, capabilities, notifications, …) that the wire -* shapes compose is a frozen LOCAL copy — verbatim from the neutral layer at -* the point this revision was sealed, dependencies first. The only cross-layer -* dependency is `import type { JSONObject, JSONValue }` from the neutral types -* barrel — pure structural type aliases with no parse behavior. -* -* This module is the only place the per-request `_meta` envelope is modeled. -* The envelope is wire-only vocabulary: the protocol layer lifts it off -* inbound requests before any handler runs and surfaces it at -* `ctx.mcpReq.envelope`; the 2026-era codec enforces its requiredness at -* dispatch time (`checkInboundEnvelope`) - the former neutral-schema JSDoc -* deferral ("enforced per request at dispatch time, not here") is now -* discharged by that codec step. -* -* No 2025-era traffic ever touches this module, so requiredness here is -* bare and spec-exact (the shared-schema `.catch` hazards do not apply). -* -* SPEC-CURRENCY RE-SEAL (2026-07-17): the 2026-07-28 revision was re-sealed -* upstream by spec PR #3002 (commit 71e30695, merged 2026-07-15 — after the -* previous anchor pin f68d864a): the envelope's `clientInfo` demoted from -* required to SHOULD, and `DiscoverResult.serverInfo` moved from the result -* body to the new `ResultMetaObject` key -* `_meta['io.modelcontextprotocol/serverInfo']` (optional on every result). -* The shapes below are the re-sealed anchor, exactly — no pre-#3002 shape is -* modeled anywhere (per ruling: the final revision is the only 2026-07-28). -*/ -function build() { - const JSONValueSchema$1 = lazy(() => schemas_union([ - schemas_string(), - schemas_number(), - schemas_boolean(), - schemas_null(), - schemas_record(schemas_string(), JSONValueSchema$1), - schemas_array(JSONValueSchema$1) - ])); - const JSONObjectSchema$1 = schemas_record(schemas_string(), JSONValueSchema$1); - /** - * A progress token, used to associate progress notifications with the original request. - */ - const ProgressTokenSchema$1 = schemas_union([schemas_string(), schemas_number().int()]); - /** - * An opaque token used to represent a cursor for pagination. - */ - const CursorSchema$1 = schemas_string(); - /** - * A uniquely identifying ID for a request in JSON-RPC. - */ - const RequestIdSchema$1 = schemas_union([schemas_string(), schemas_number().int()]); - /** - * The sender or recipient of messages and data in a conversation. - */ - const RoleSchema$1 = schemas_enum(["user", "assistant"]); - /** - * The severity of a log message. - */ - const LoggingLevelSchema$1 = schemas_enum([ - "debug", - "info", - "notice", - "warning", - "error", - "critical", - "alert", - "emergency" - ]); - /** - * A Zod schema for validating Base64 strings that is more performant and - * robust for very large inputs than the default regex-based check. It avoids - * stack overflows by using the native `atob` function for validation. - */ - const Base64Schema = schemas_string().refine((val) => { - try { - atob(val); - return true; - } catch { - return false; - } - }, { message: "Invalid Base64 string" }); - /** @deprecated 2025-11-25 wire vocabulary with no SDK runtime; kept importable for interoperability only. */ - const TaskMetadataSchema$1 = schemas_object({ ttl: schemas_number().optional() }); - /** @deprecated 2025-11-25 wire vocabulary with no SDK runtime; kept importable for interoperability only. */ - const RelatedTaskMetadataSchema$1 = schemas_object({ taskId: schemas_string() }); - const RequestMetaSchema$1 = looseObject({ - progressToken: ProgressTokenSchema$1.optional(), - "io.modelcontextprotocol/related-task": RelatedTaskMetadataSchema$1.optional() - }); - const BaseRequestParamsSchema$1 = schemas_object({ _meta: RequestMetaSchema$1.optional() }); - /** @deprecated 2025-11-25 wire vocabulary with no SDK runtime; kept importable for interoperability only. */ - const TaskAugmentedRequestParamsSchema$1 = BaseRequestParamsSchema$1.extend({ task: TaskMetadataSchema$1.optional() }); - const NotificationsParamsSchema$1 = schemas_object({ _meta: RequestMetaSchema$1.optional() }); - const NotificationSchema$1 = schemas_object({ - method: schemas_string(), - params: NotificationsParamsSchema$1.loose().optional() - }); - const IconSchema$1 = schemas_object({ - src: schemas_string(), - mimeType: schemas_string().optional(), - sizes: schemas_array(schemas_string()).optional(), - theme: schemas_enum(["light", "dark"]).optional() - }); - const IconsSchema$1 = schemas_object({ icons: schemas_array(IconSchema$1).optional() }); - const BaseMetadataSchema$1 = schemas_object({ - name: schemas_string(), - title: schemas_string().optional() - }); - const ImplementationSchema$1 = BaseMetadataSchema$1.extend({ - ...BaseMetadataSchema$1.shape, - ...IconsSchema$1.shape, - version: schemas_string(), - websiteUrl: schemas_string().optional(), - description: schemas_string().optional() - }); - const FormElicitationCapabilitySchema = intersection(schemas_object({ applyDefaults: schemas_boolean().optional() }), JSONObjectSchema$1); - const ElicitationCapabilitySchema = preprocess((value) => { - if (value && typeof value === "object" && !Array.isArray(value) && Object.keys(value).length === 0) return { form: {} }; - return value; - }, intersection(schemas_object({ - form: FormElicitationCapabilitySchema.optional(), - url: JSONObjectSchema$1.optional() - }), JSONObjectSchema$1.optional())); - /** @deprecated 2025-11-25 wire vocabulary with no SDK runtime; kept importable for interoperability only. */ - const ClientTasksCapabilitySchema$1 = looseObject({ - list: JSONObjectSchema$1.optional(), - cancel: JSONObjectSchema$1.optional(), - requests: looseObject({ - sampling: looseObject({ createMessage: JSONObjectSchema$1.optional() }).optional(), - elicitation: looseObject({ create: JSONObjectSchema$1.optional() }).optional() - }).optional() - }); - /** @deprecated 2025-11-25 wire vocabulary with no SDK runtime; kept importable for interoperability only. */ - const ServerTasksCapabilitySchema$1 = looseObject({ - list: JSONObjectSchema$1.optional(), - cancel: JSONObjectSchema$1.optional(), - requests: looseObject({ tools: looseObject({ call: JSONObjectSchema$1.optional() }).optional() }).optional() - }); - const ClientCapabilitiesSchema$1 = schemas_object({ - experimental: schemas_record(schemas_string(), JSONObjectSchema$1).optional(), - sampling: schemas_object({ - context: JSONObjectSchema$1.optional(), - tools: JSONObjectSchema$1.optional() - }).optional(), - elicitation: ElicitationCapabilitySchema.optional(), - roots: schemas_object({ listChanged: schemas_boolean().optional() }).optional(), - tasks: ClientTasksCapabilitySchema$1.optional(), - extensions: schemas_record(schemas_string(), JSONObjectSchema$1).optional() - }); - const ServerCapabilitiesSchema$1 = schemas_object({ - experimental: schemas_record(schemas_string(), JSONObjectSchema$1).optional(), - logging: JSONObjectSchema$1.optional(), - completions: JSONObjectSchema$1.optional(), - prompts: schemas_object({ listChanged: schemas_boolean().optional() }).optional(), - resources: schemas_object({ - subscribe: schemas_boolean().optional(), - listChanged: schemas_boolean().optional() - }).optional(), - tools: schemas_object({ listChanged: schemas_boolean().optional() }).optional(), - tasks: ServerTasksCapabilitySchema$1.optional(), - extensions: schemas_record(schemas_string(), JSONObjectSchema$1).optional() - }); - const ProgressSchema$1 = schemas_object({ - progress: schemas_number(), - total: schemas_optional(schemas_number()), - message: schemas_optional(schemas_string()) - }); - const ProgressNotificationParamsSchema$1 = schemas_object({ - ...NotificationsParamsSchema$1.shape, - ...ProgressSchema$1.shape, - progressToken: ProgressTokenSchema$1 - }); - const ProgressNotificationSchema$1 = NotificationSchema$1.extend({ - method: literal("notifications/progress"), - params: ProgressNotificationParamsSchema$1 - }); - const LoggingMessageNotificationParamsSchema$1 = NotificationsParamsSchema$1.extend({ - level: LoggingLevelSchema$1, - logger: schemas_string().optional(), - data: unknown() - }); - const LoggingMessageNotificationSchema$1 = NotificationSchema$1.extend({ - method: literal("notifications/message"), - params: LoggingMessageNotificationParamsSchema$1 - }); - const ResourceContentsSchema$1 = schemas_object({ - uri: schemas_string(), - mimeType: schemas_optional(schemas_string()), - _meta: schemas_record(schemas_string(), unknown()).optional() - }); - const TextResourceContentsSchema$1 = ResourceContentsSchema$1.extend({ text: schemas_string() }); - const BlobResourceContentsSchema$1 = ResourceContentsSchema$1.extend({ blob: Base64Schema }); - const AnnotationsSchema$1 = schemas_object({ - audience: schemas_array(RoleSchema$1).optional(), - priority: schemas_number().min(0).max(1).optional(), - lastModified: iso_datetime({ offset: true }).optional() - }); - const ResourceSchema$1 = schemas_object({ - ...BaseMetadataSchema$1.shape, - ...IconsSchema$1.shape, - uri: schemas_string(), - description: schemas_optional(schemas_string()), - mimeType: schemas_optional(schemas_string()), - size: schemas_optional(schemas_number()), - annotations: AnnotationsSchema$1.optional(), - _meta: schemas_optional(looseObject({})) - }); - const ResourceTemplateSchema$1 = schemas_object({ - ...BaseMetadataSchema$1.shape, - ...IconsSchema$1.shape, - uriTemplate: schemas_string(), - description: schemas_optional(schemas_string()), - mimeType: schemas_optional(schemas_string()), - annotations: AnnotationsSchema$1.optional(), - _meta: schemas_optional(looseObject({})) - }); - const ResourceListChangedNotificationSchema$1 = NotificationSchema$1.extend({ - method: literal("notifications/resources/list_changed"), - params: NotificationsParamsSchema$1.optional() - }); - const ResourceUpdatedNotificationParamsSchema$1 = NotificationsParamsSchema$1.extend({ uri: schemas_string() }); - const ResourceUpdatedNotificationSchema$1 = NotificationSchema$1.extend({ - method: literal("notifications/resources/updated"), - params: ResourceUpdatedNotificationParamsSchema$1 - }); - const PromptArgumentSchema$1 = schemas_object({ - name: schemas_string(), - description: schemas_optional(schemas_string()), - required: schemas_optional(schemas_boolean()) - }); - const PromptSchema$1 = schemas_object({ - ...BaseMetadataSchema$1.shape, - ...IconsSchema$1.shape, - description: schemas_optional(schemas_string()), - arguments: schemas_optional(schemas_array(PromptArgumentSchema$1)), - _meta: schemas_optional(looseObject({})) - }); - const PromptListChangedNotificationSchema$1 = NotificationSchema$1.extend({ - method: literal("notifications/prompts/list_changed"), - params: NotificationsParamsSchema$1.optional() - }); - const TextContentSchema$1 = schemas_object({ - type: literal("text"), - text: schemas_string(), - annotations: AnnotationsSchema$1.optional(), - _meta: schemas_record(schemas_string(), unknown()).optional() - }); - const ImageContentSchema$1 = schemas_object({ - type: literal("image"), - data: Base64Schema, - mimeType: schemas_string(), - annotations: AnnotationsSchema$1.optional(), - _meta: schemas_record(schemas_string(), unknown()).optional() - }); - const AudioContentSchema$1 = schemas_object({ - type: literal("audio"), - data: Base64Schema, - mimeType: schemas_string(), - annotations: AnnotationsSchema$1.optional(), - _meta: schemas_record(schemas_string(), unknown()).optional() - }); - const ToolUseContentSchema$1 = schemas_object({ - type: literal("tool_use"), - name: schemas_string(), - id: schemas_string(), - input: schemas_record(schemas_string(), unknown()), - _meta: schemas_record(schemas_string(), unknown()).optional() - }); - const EmbeddedResourceSchema$1 = schemas_object({ - type: literal("resource"), - resource: schemas_union([TextResourceContentsSchema$1, BlobResourceContentsSchema$1]), - annotations: AnnotationsSchema$1.optional(), - _meta: schemas_record(schemas_string(), unknown()).optional() - }); - const ResourceLinkSchema$1 = ResourceSchema$1.extend({ type: literal("resource_link") }); - const ContentBlockSchema$1 = schemas_union([ - TextContentSchema$1, - ImageContentSchema$1, - AudioContentSchema$1, - ResourceLinkSchema$1, - EmbeddedResourceSchema$1 - ]); - const PromptMessageSchema$1 = schemas_object({ - role: RoleSchema$1, - content: ContentBlockSchema$1 - }); - const ToolAnnotationsSchema$1 = schemas_object({ - title: schemas_string().optional(), - readOnlyHint: schemas_boolean().optional(), - destructiveHint: schemas_boolean().optional(), - idempotentHint: schemas_boolean().optional(), - openWorldHint: schemas_boolean().optional() - }); - const ToolListChangedNotificationSchema$1 = NotificationSchema$1.extend({ - method: literal("notifications/tools/list_changed"), - params: NotificationsParamsSchema$1.optional() - }); - const ModelHintSchema$1 = schemas_object({ name: schemas_string().optional() }); - const ModelPreferencesSchema$1 = schemas_object({ - hints: schemas_array(ModelHintSchema$1).optional(), - costPriority: schemas_number().min(0).max(1).optional(), - speedPriority: schemas_number().min(0).max(1).optional(), - intelligencePriority: schemas_number().min(0).max(1).optional() - }); - const ToolChoiceSchema$1 = schemas_object({ mode: schemas_enum([ - "auto", - "required", - "none" - ]).optional() }); - const BooleanSchemaSchema$1 = schemas_object({ - type: literal("boolean"), - title: schemas_string().optional(), - description: schemas_string().optional(), - default: schemas_boolean().optional() - }); - const StringSchemaSchema$1 = schemas_object({ - type: literal("string"), - title: schemas_string().optional(), - description: schemas_string().optional(), - minLength: schemas_number().optional(), - maxLength: schemas_number().optional(), - format: schemas_enum([ - "email", - "uri", - "date", - "date-time" - ]).optional(), - default: schemas_string().optional() - }); - const NumberSchemaSchema$1 = schemas_object({ - type: schemas_enum(["number", "integer"]), - title: schemas_string().optional(), - description: schemas_string().optional(), - minimum: schemas_number().optional(), - maximum: schemas_number().optional(), - default: schemas_number().optional() - }); - const UntitledSingleSelectEnumSchemaSchema$1 = schemas_object({ - type: literal("string"), - title: schemas_string().optional(), - description: schemas_string().optional(), - enum: schemas_array(schemas_string()), - default: schemas_string().optional() - }); - const TitledSingleSelectEnumSchemaSchema$1 = schemas_object({ - type: literal("string"), - title: schemas_string().optional(), - description: schemas_string().optional(), - oneOf: schemas_array(schemas_object({ - const: schemas_string(), - title: schemas_string() - })), - default: schemas_string().optional() - }); - const LegacyTitledEnumSchemaSchema$1 = schemas_object({ - type: literal("string"), - title: schemas_string().optional(), - description: schemas_string().optional(), - enum: schemas_array(schemas_string()), - enumNames: schemas_array(schemas_string()).optional(), - default: schemas_string().optional() - }); - const SingleSelectEnumSchemaSchema$1 = schemas_union([UntitledSingleSelectEnumSchemaSchema$1, TitledSingleSelectEnumSchemaSchema$1]); - const UntitledMultiSelectEnumSchemaSchema$1 = schemas_object({ - type: literal("array"), - title: schemas_string().optional(), - description: schemas_string().optional(), - minItems: schemas_number().optional(), - maxItems: schemas_number().optional(), - items: schemas_object({ - type: literal("string"), - enum: schemas_array(schemas_string()) - }), - default: schemas_array(schemas_string()).optional() - }); - const TitledMultiSelectEnumSchemaSchema$1 = schemas_object({ - type: literal("array"), - title: schemas_string().optional(), - description: schemas_string().optional(), - minItems: schemas_number().optional(), - maxItems: schemas_number().optional(), - items: schemas_object({ anyOf: schemas_array(schemas_object({ - const: schemas_string(), - title: schemas_string() - })) }), - default: schemas_array(schemas_string()).optional() - }); - const MultiSelectEnumSchemaSchema$1 = schemas_union([UntitledMultiSelectEnumSchemaSchema$1, TitledMultiSelectEnumSchemaSchema$1]); - const EnumSchemaSchema$1 = schemas_union([ - LegacyTitledEnumSchemaSchema$1, - SingleSelectEnumSchemaSchema$1, - MultiSelectEnumSchemaSchema$1 - ]); - const PrimitiveSchemaDefinitionSchema$1 = schemas_union([ - EnumSchemaSchema$1, - BooleanSchemaSchema$1, - StringSchemaSchema$1, - NumberSchemaSchema$1 - ]); - const ElicitRequestFormParamsSchema$1 = TaskAugmentedRequestParamsSchema$1.extend({ - mode: literal("form").optional(), - message: schemas_string(), - requestedSchema: schemas_object({ - type: literal("object"), - properties: schemas_record(schemas_string(), PrimitiveSchemaDefinitionSchema$1), - required: schemas_array(schemas_string()).optional() - }).catchall(unknown()) - }); - const ResourceTemplateReferenceSchema$1 = schemas_object({ - type: literal("ref/resource"), - uri: schemas_string() - }); - const PromptReferenceSchema$1 = schemas_object({ - type: literal("ref/prompt"), - name: schemas_string() - }); - const RootSchema$1 = schemas_object({ - uri: schemas_string().startsWith("file://"), - name: schemas_string().optional(), - _meta: schemas_record(schemas_string(), unknown()).optional() - }); - const sharedClientCapabilityShape = ClientCapabilitiesSchema$1.shape; - const ClientCapabilities2026Schema = schemas_object({ - experimental: sharedClientCapabilityShape.experimental, - sampling: sharedClientCapabilityShape.sampling, - elicitation: sharedClientCapabilityShape.elicitation, - roots: sharedClientCapabilityShape.roots, - extensions: sharedClientCapabilityShape.extensions - }); - const sharedServerCapabilityShape = ServerCapabilitiesSchema$1.shape; - const ServerCapabilities2026Schema = schemas_object({ - experimental: sharedServerCapabilityShape.experimental, - logging: sharedServerCapabilityShape.logging, - completions: sharedServerCapabilityShape.completions, - prompts: sharedServerCapabilityShape.prompts, - resources: sharedServerCapabilityShape.resources, - tools: sharedServerCapabilityShape.tools, - extensions: sharedServerCapabilityShape.extensions - }); - /** - * The per-request `_meta` envelope carried by every request under protocol revision - * 2026-07-28: the protocol version governing the request, the client implementation - * info, and the client's capabilities — declared per request rather than once at - * initialization — plus the optional log-level opt-in. - * - * This schema models the complete envelope on its own (loose: foreign keys - * pass through - the lift extracts exactly the reserved keys, so enforcement - * never sees extension material). Requiredness is enforced per request at - * dispatch time by the 2026-era codec's `checkInboundEnvelope` step. - */ - const RequestMetaEnvelopeSchema = looseObject({ - progressToken: ProgressTokenSchema$1.optional(), - [auth_CUe6YdwF_PROTOCOL_VERSION_META_KEY]: schemas_string(), - [auth_CUe6YdwF_CLIENT_INFO_META_KEY]: ImplementationSchema$1.optional(), - [auth_CUe6YdwF_CLIENT_CAPABILITIES_META_KEY]: ClientCapabilities2026Schema, - [LOG_LEVEL_META_KEY]: LoggingLevelSchema$1.optional() - }); - /** 2026-era Tool: anchor-exact — no `execution` (deleted vocabulary). */ - const ToolSchema$1 = schemas_object({ - ...BaseMetadataSchema$1.shape, - ...IconsSchema$1.shape, - description: schemas_string().optional(), - inputSchema: looseObject({ - $schema: schemas_string().optional(), - type: literal("object") - }), - outputSchema: looseObject({ $schema: schemas_string().optional() }).optional(), - annotations: ToolAnnotationsSchema$1.optional(), - _meta: schemas_record(schemas_string(), unknown()).optional() - }); - /** 2026-era ToolResultContent (anchor-exact: `structuredContent?: unknown`). */ - const ToolResultContentSchema$1 = schemas_object({ - type: literal("tool_result"), - toolUseId: schemas_string(), - content: schemas_array(ContentBlockSchema$1), - structuredContent: unknown().optional(), - isError: schemas_boolean().optional(), - _meta: schemas_record(schemas_string(), unknown()).optional() - }); - /** 2026-era sampling content union (composes the forked tool-result shape). */ - const SamplingMessageContentBlockSchema$1 = schemas_union([ - TextContentSchema$1, - ImageContentSchema$1, - AudioContentSchema$1, - ToolUseContentSchema$1, - ToolResultContentSchema$1 - ]); - /** 2026-era SamplingMessage (anchor-exact: single block or array). */ - const SamplingMessageSchema$1 = schemas_object({ - role: RoleSchema$1, - content: schemas_union([SamplingMessageContentBlockSchema$1, schemas_array(SamplingMessageContentBlockSchema$1)]), - _meta: schemas_record(schemas_string(), unknown()).optional() - }); - /** Open union per the anchor: 'complete' | 'input_required' | string. */ - const ResultTypeSchema = schemas_string(); - /** - * Result `_meta` (anchor `ResultMetaObject`, added by spec PR #3002): - * loose, with the serverInfo key typed when present; the outbound stamp - * is the encode contract's `stampServerInfoMeta` step. - */ - const ResultMetaSchema = looseObject({ [auth_CUe6YdwF_SERVER_INFO_META_KEY]: ImplementationSchema$1.optional().catch(void 0) }); - const wireMeta = ResultMetaSchema.optional(); - function wireResult(shape) { - return looseObject({ - _meta: wireMeta, - resultType: ResultTypeSchema.default("complete"), - ...shape - }); - } - const ResultSchema$1 = wireResult({}); - const PaginatedResultSchema$1 = wireResult({ nextCursor: CursorSchema$1.optional() }); - const CallToolResultSchema$1 = wireResult({ - content: schemas_array(ContentBlockSchema$1), - structuredContent: unknown().optional(), - isError: schemas_boolean().optional() - }); - const ListToolsResultSchema$1 = wireResult({ - ttlMs: schemas_number().int().min(0), - cacheScope: schemas_enum(["public", "private"]), - tools: schemas_array(ToolSchema$1), - nextCursor: CursorSchema$1.optional() - }); - const ListPromptsResultSchema$1 = wireResult({ - ttlMs: schemas_number().int().min(0), - cacheScope: schemas_enum(["public", "private"]), - prompts: schemas_array(PromptSchema$1), - nextCursor: CursorSchema$1.optional() - }); - const GetPromptResultSchema$1 = wireResult({ - description: schemas_string().optional(), - messages: schemas_array(PromptMessageSchema$1) - }); - const ListResourcesResultSchema$1 = wireResult({ - ttlMs: schemas_number().int().min(0), - cacheScope: schemas_enum(["public", "private"]), - resources: schemas_array(ResourceSchema$1), - nextCursor: CursorSchema$1.optional() - }); - const ListResourceTemplatesResultSchema$1 = wireResult({ - ttlMs: schemas_number().int().min(0), - cacheScope: schemas_enum(["public", "private"]), - resourceTemplates: schemas_array(ResourceTemplateSchema$1), - nextCursor: CursorSchema$1.optional() - }); - const ReadResourceResultSchema$1 = wireResult({ - ttlMs: schemas_number().int().min(0), - cacheScope: schemas_enum(["public", "private"]), - contents: schemas_array(schemas_union([TextResourceContentsSchema$1, BlobResourceContentsSchema$1])) - }); - const CompleteResultSchema$1 = wireResult({ completion: schemas_object({ - values: schemas_array(schemas_string()).max(100), - total: schemas_number().int().optional(), - hasMore: schemas_boolean().optional() - }).loose() }); - /** CacheableResult (SEP-2549): ttlMs and cacheScope REQUIRED per the anchor. */ - const CacheableResultSchema = wireResult({ - ttlMs: schemas_number().int().min(0), - cacheScope: schemas_enum(["public", "private"]) - }); - const DiscoverResultSchema$1 = wireResult({ - ttlMs: schemas_number().int().min(0).catch(0), - cacheScope: schemas_enum(["public", "private"]).catch("private"), - supportedVersions: schemas_array(schemas_string()), - capabilities: ServerCapabilities2026Schema, - instructions: schemas_string().optional() - }); - /** 2026-era CreateMessageRequestParams (anchor-exact: forked SamplingMessage/Tool, no task augmentation). */ - const CreateMessageRequestParamsSchema$1 = schemas_object({ - messages: schemas_array(SamplingMessageSchema$1), - modelPreferences: ModelPreferencesSchema$1.optional(), - systemPrompt: schemas_string().optional(), - includeContext: schemas_enum([ - "none", - "thisServer", - "allServers" - ]).optional(), - temperature: schemas_number().optional(), - maxTokens: schemas_number().int(), - stopSequences: schemas_array(schemas_string()).optional(), - metadata: JSONObjectSchema$1.optional(), - tools: schemas_array(ToolSchema$1).optional(), - toolChoice: ToolChoiceSchema$1.optional() - }); - /** 2026-era embedded sampling request (de-JSON-RPC'd). */ - const CreateMessageRequestSchema$1 = schemas_object({ - method: literal("sampling/createMessage"), - params: CreateMessageRequestParamsSchema$1 - }); - /** - * 2026-era embedded roots listing request (de-JSON-RPC'd). Embedded input - * requests do NOT carry the per-request `_meta` envelope on this revision — - * the anchor declares a bare optional `_meta` on `params`. - */ - const ListRootsRequestSchema$1 = schemas_object({ - method: literal("roots/list"), - params: schemas_object({ _meta: schemas_record(schemas_string(), unknown()).optional() }).optional() - }); - /** 2026-era embedded sampling response (anchor-exact: extends the forked SamplingMessage). */ - const CreateMessageResultSchema$1 = schemas_object({ - ...SamplingMessageSchema$1.shape, - model: schemas_string(), - stopReason: schemas_string().optional() - }); - /** 2026-era embedded roots listing response (anchor-exact: bare `roots` array). */ - const ListRootsResultSchema$1 = schemas_object({ roots: schemas_array(RootSchema$1) }); - /** 2026-era embedded elicitation response (anchor-exact: bare result, restricted content value types). */ - const ElicitResultSchema$1 = schemas_object({ - action: schemas_enum([ - "accept", - "decline", - "cancel" - ]), - content: schemas_record(schemas_string(), schemas_union([ - schemas_string(), - schemas_number(), - schemas_boolean(), - schemas_array(schemas_string()) - ])).optional() - }); - /** - * 2026-era URL-mode elicitation params (anchor-exact fork): the draft removed - * `elicitationId` (and the `notifications/elicitation/complete` channel it - * keyed) — the shared schema keeps the field because it is required on the - * frozen 2025-11-25 revision. - */ - const ElicitRequestURLParamsSchema$1 = schemas_object({ - mode: literal("url"), - message: schemas_string(), - url: schemas_string().url() - }); - /** 2026-era elicitation params (form mode is revision-identical; URL mode is the fork above). */ - const ElicitRequestParamsSchema$1 = schemas_union([ElicitRequestFormParamsSchema$1, ElicitRequestURLParamsSchema$1]); - /** 2026-era embedded elicitation request (de-JSON-RPC'd; see the URL-mode fork above). */ - const ElicitRequestSchema$1 = schemas_object({ - method: literal("elicitation/create"), - params: ElicitRequestParamsSchema$1 - }); - /** A single embedded input request (one of the three demoted server→client requests). */ - const InputRequestSchema = schemas_union([ - CreateMessageRequestSchema$1, - ListRootsRequestSchema$1, - ElicitRequestSchema$1 - ]); - /** A single embedded input response — the BARE result union (never a `{method, result}` wrapper). */ - const InputResponseSchema = schemas_union([ - CreateMessageResultSchema$1, - ListRootsResultSchema$1, - ElicitResultSchema$1 - ]); - /** Map of embedded input requests, keyed by server-assigned identifiers. */ - const InputRequestsSchema = schemas_record(schemas_string(), InputRequestSchema); - /** Map of embedded input responses, keyed by the corresponding request identifiers. */ - const InputResponsesSchema = schemas_record(schemas_string(), InputResponseSchema); - /** - * The wire InputRequiredResult: `resultType: 'input_required'` plus at least - * one of `inputRequests` / `requestState` (the at-least-one rule is enforced - * at the server seam, not by this parse shape). - */ - const InputRequiredResultSchema = wireResult({ - inputRequests: InputRequestsSchema.optional(), - requestState: schemas_string().optional() - }); - /** The retry-channel members carried by client-initiated requests on this revision. */ - const retryParamsShape = { - inputResponses: InputResponsesSchema.optional(), - requestState: schemas_string().optional() - }; - /** Anchor InputResponseRequestParams: the retry channel on top of the required request `_meta` envelope. */ - const InputResponseRequestParamsSchema = schemas_object({ - _meta: RequestMetaEnvelopeSchema, - ...retryParamsShape - }); - /** Post-lift request `_meta` (progressToken + extension keys; loose). */ - const DispatchRequestMetaSchema = looseObject({ progressToken: ProgressTokenSchema$1.optional() }); - function wireRequest(method, paramsShape) { - return schemas_object({ - method: literal(method), - params: schemas_object({ - _meta: RequestMetaEnvelopeSchema, - ...paramsShape - }) - }); - } - function dispatchRequest(method, paramsShape) { - return schemas_object({ - method: literal(method), - params: schemas_object({ - _meta: DispatchRequestMetaSchema.optional(), - ...paramsShape - }).optional() - }); - } - const callToolParamsShape = { - name: schemas_string(), - arguments: schemas_record(schemas_string(), unknown()).optional(), - ...retryParamsShape - }; - const paginatedParamsShape = { cursor: CursorSchema$1.optional() }; - const CallToolRequestSchema$1 = wireRequest("tools/call", callToolParamsShape); - const ListToolsRequestSchema$1 = wireRequest("tools/list", paginatedParamsShape); - const ListPromptsRequestSchema$1 = wireRequest("prompts/list", paginatedParamsShape); - const GetPromptRequestSchema$1 = wireRequest("prompts/get", { - name: schemas_string(), - arguments: schemas_record(schemas_string(), schemas_string()).optional(), - ...retryParamsShape - }); - const ListResourcesRequestSchema$1 = wireRequest("resources/list", paginatedParamsShape); - const ListResourceTemplatesRequestSchema$1 = wireRequest("resources/templates/list", paginatedParamsShape); - const ReadResourceRequestSchema$1 = wireRequest("resources/read", { - uri: schemas_string(), - ...retryParamsShape - }); - const completeParamsShape = { - ref: schemas_union([PromptReferenceSchema$1, ResourceTemplateReferenceSchema$1]), - argument: schemas_object({ - name: schemas_string(), - value: schemas_string() - }), - context: schemas_object({ arguments: schemas_record(schemas_string(), schemas_string()).optional() }).optional() - }; - const CompleteRequestSchema$1 = wireRequest("completion/complete", completeParamsShape); - const DiscoverRequestSchema$1 = wireRequest("server/discover", {}); - /** Anchor SubscriptionFilter (2026-only). */ - const SubscriptionFilterSchema$1 = schemas_object({ - toolsListChanged: schemas_boolean().optional(), - promptsListChanged: schemas_boolean().optional(), - resourcesListChanged: schemas_boolean().optional(), - resourceSubscriptions: schemas_array(schemas_string()).optional() - }); - const subscriptionsListenParamsShape = { notifications: SubscriptionFilterSchema$1 }; - const SubscriptionsListenRequestSchema$1 = wireRequest("subscriptions/listen", subscriptionsListenParamsShape); - /** - * Anchor SubscriptionsListenResultMeta — required subscriptionId stamp on - * the graceful-close result. Extends `ResultMetaObject` since spec PR - * #3002 (composed, so the serverInfo key and its leniency stay single-sourced). - */ - const SubscriptionsListenResultMetaSchema$1 = ResultMetaSchema.extend({ "io.modelcontextprotocol/subscriptionId": RequestIdSchema$1 }); - /** - * Anchor SubscriptionsListenResult (2026-only). The empty `subscriptions/listen` - * response signalling that the subscription has ended gracefully (server - * shutdown). An abrupt transport close carries no response — the client treats - * stream-close-without-result as a disconnect. - */ - const SubscriptionsListenResultSchema$1 = looseObject({ - _meta: SubscriptionsListenResultMetaSchema$1, - resultType: ResultTypeSchema.default("complete") - }); - /** Dispatch (post-lift) request schemas, keyed by method — registry-internal. */ - const dispatchRequestSchemas = { - "tools/call": dispatchRequest("tools/call", callToolParamsShape), - "tools/list": dispatchRequest("tools/list", paginatedParamsShape), - "prompts/get": dispatchRequest("prompts/get", { - name: schemas_string(), - arguments: schemas_record(schemas_string(), schemas_string()).optional() - }), - "prompts/list": dispatchRequest("prompts/list", paginatedParamsShape), - "resources/list": dispatchRequest("resources/list", paginatedParamsShape), - "resources/templates/list": dispatchRequest("resources/templates/list", paginatedParamsShape), - "resources/read": dispatchRequest("resources/read", { uri: schemas_string() }), - "completion/complete": dispatchRequest("completion/complete", completeParamsShape), - "server/discover": dispatchRequest("server/discover", {}), - "subscriptions/listen": dispatchRequest("subscriptions/listen", subscriptionsListenParamsShape) - }; - /** Dispatch (post-lift) result schemas, keyed by method — what the funnel - * validates AFTER `decodeResult` consumed `resultType`. */ - function liftedResult(shape) { - return looseObject({ - _meta: wireMeta, - ...shape - }); - } - const dispatchResultSchemas = { - "tools/call": liftedResult({ - content: schemas_array(ContentBlockSchema$1), - structuredContent: unknown().optional(), - isError: schemas_boolean().optional() - }), - "tools/list": liftedResult({ - ttlMs: schemas_number().int().min(0), - cacheScope: schemas_enum(["public", "private"]), - tools: schemas_array(ToolSchema$1), - nextCursor: CursorSchema$1.optional() - }), - "prompts/get": liftedResult({ - description: schemas_string().optional(), - messages: schemas_array(PromptMessageSchema$1) - }), - "prompts/list": liftedResult({ - ttlMs: schemas_number().int().min(0), - cacheScope: schemas_enum(["public", "private"]), - prompts: schemas_array(PromptSchema$1), - nextCursor: CursorSchema$1.optional() - }), - "resources/list": liftedResult({ - ttlMs: schemas_number().int().min(0), - cacheScope: schemas_enum(["public", "private"]), - resources: schemas_array(ResourceSchema$1), - nextCursor: CursorSchema$1.optional() - }), - "resources/templates/list": liftedResult({ - ttlMs: schemas_number().int().min(0), - cacheScope: schemas_enum(["public", "private"]), - resourceTemplates: schemas_array(ResourceTemplateSchema$1), - nextCursor: CursorSchema$1.optional() - }), - "resources/read": liftedResult({ - ttlMs: schemas_number().int().min(0), - cacheScope: schemas_enum(["public", "private"]), - contents: schemas_array(schemas_union([TextResourceContentsSchema$1, BlobResourceContentsSchema$1])) - }), - "completion/complete": liftedResult({ completion: schemas_object({ - values: schemas_array(schemas_string()).max(100), - total: schemas_number().int().optional(), - hasMore: schemas_boolean().optional() - }).loose() }), - "server/discover": liftedResult({ - ttlMs: schemas_number().int().min(0).catch(0), - cacheScope: schemas_enum(["public", "private"]).catch("private"), - supportedVersions: schemas_array(schemas_string()), - capabilities: ServerCapabilities2026Schema, - instructions: schemas_string().optional() - }), - "subscriptions/listen": liftedResult({}) - }; - /** - * Notification `_meta` (anchor `NotificationMetaObject`): loose, with the - * subscriptions/listen demux key typed when present. Only the anchor-exact - * SHAPE is modeled here — listen delivery itself (filter gating, demux, - * teardown) is #14 scope and not implemented by this module. - */ - const NotificationMetaSchema = looseObject({ "io.modelcontextprotocol/subscriptionId": RequestIdSchema$1.optional() }); - /** Anchor SubscriptionsAcknowledgedNotification (2026-only). */ - const SubscriptionsAcknowledgedNotificationSchema$1 = schemas_object({ - method: literal("notifications/subscriptions/acknowledged"), - params: schemas_object({ - _meta: NotificationMetaSchema.optional(), - notifications: SubscriptionFilterSchema$1 - }) - }); - /** - * 2026-era `notifications/cancelled` params (anchor-exact fork): `requestId` - * is REQUIRED on this revision — the shared schema keeps it optional because - * the frozen 2025-11-25 shape declares it optional (task cancellation goes - * through `tasks/cancel` there). Requiredness is bare because no 2025-era - * traffic touches this module. - */ - const CancelledNotificationParamsSchema$1 = schemas_object({ - _meta: NotificationMetaSchema.optional(), - requestId: RequestIdSchema$1, - reason: schemas_string().optional() - }); - /** 2026-era `notifications/cancelled` (see the params fork above). */ - const CancelledNotificationSchema$1 = schemas_object({ - method: literal("notifications/cancelled"), - params: CancelledNotificationParamsSchema$1 - }); - const notificationSchemas2026 = { - "notifications/cancelled": CancelledNotificationSchema$1, - "notifications/progress": ProgressNotificationSchema$1, - "notifications/message": LoggingMessageNotificationSchema$1, - "notifications/resources/updated": ResourceUpdatedNotificationSchema$1, - "notifications/resources/list_changed": ResourceListChangedNotificationSchema$1, - "notifications/tools/list_changed": ToolListChangedNotificationSchema$1, - "notifications/prompts/list_changed": PromptListChangedNotificationSchema$1, - "notifications/subscriptions/acknowledged": SubscriptionsAcknowledgedNotificationSchema$1 - }; - const wireResultResponse = (result) => schemas_object({ - jsonrpc: literal("2.0"), - id: schemas_union([schemas_string(), schemas_number().int()]), - result - }).strict(); - return { - JSONValueSchema: JSONValueSchema$1, - JSONObjectSchema: JSONObjectSchema$1, - ProgressTokenSchema: ProgressTokenSchema$1, - CursorSchema: CursorSchema$1, - RequestIdSchema: RequestIdSchema$1, - RoleSchema: RoleSchema$1, - LoggingLevelSchema: LoggingLevelSchema$1, - TaskMetadataSchema: TaskMetadataSchema$1, - RelatedTaskMetadataSchema: RelatedTaskMetadataSchema$1, - RequestMetaSchema: RequestMetaSchema$1, - BaseRequestParamsSchema: BaseRequestParamsSchema$1, - TaskAugmentedRequestParamsSchema: TaskAugmentedRequestParamsSchema$1, - NotificationsParamsSchema: NotificationsParamsSchema$1, - NotificationSchema: NotificationSchema$1, - IconSchema: IconSchema$1, - IconsSchema: IconsSchema$1, - BaseMetadataSchema: BaseMetadataSchema$1, - ImplementationSchema: ImplementationSchema$1, - ClientTasksCapabilitySchema: ClientTasksCapabilitySchema$1, - ServerTasksCapabilitySchema: ServerTasksCapabilitySchema$1, - ClientCapabilitiesSchema: ClientCapabilitiesSchema$1, - ServerCapabilitiesSchema: ServerCapabilitiesSchema$1, - ProgressSchema: ProgressSchema$1, - ProgressNotificationParamsSchema: ProgressNotificationParamsSchema$1, - ProgressNotificationSchema: ProgressNotificationSchema$1, - LoggingMessageNotificationParamsSchema: LoggingMessageNotificationParamsSchema$1, - LoggingMessageNotificationSchema: LoggingMessageNotificationSchema$1, - ResourceContentsSchema: ResourceContentsSchema$1, - TextResourceContentsSchema: TextResourceContentsSchema$1, - BlobResourceContentsSchema: BlobResourceContentsSchema$1, - AnnotationsSchema: AnnotationsSchema$1, - ResourceSchema: ResourceSchema$1, - ResourceTemplateSchema: ResourceTemplateSchema$1, - ResourceListChangedNotificationSchema: ResourceListChangedNotificationSchema$1, - ResourceUpdatedNotificationParamsSchema: ResourceUpdatedNotificationParamsSchema$1, - ResourceUpdatedNotificationSchema: ResourceUpdatedNotificationSchema$1, - PromptArgumentSchema: PromptArgumentSchema$1, - PromptSchema: PromptSchema$1, - PromptListChangedNotificationSchema: PromptListChangedNotificationSchema$1, - TextContentSchema: TextContentSchema$1, - ImageContentSchema: ImageContentSchema$1, - AudioContentSchema: AudioContentSchema$1, - ToolUseContentSchema: ToolUseContentSchema$1, - EmbeddedResourceSchema: EmbeddedResourceSchema$1, - ResourceLinkSchema: ResourceLinkSchema$1, - ContentBlockSchema: ContentBlockSchema$1, - PromptMessageSchema: PromptMessageSchema$1, - ToolAnnotationsSchema: ToolAnnotationsSchema$1, - ToolListChangedNotificationSchema: ToolListChangedNotificationSchema$1, - ModelHintSchema: ModelHintSchema$1, - ModelPreferencesSchema: ModelPreferencesSchema$1, - ToolChoiceSchema: ToolChoiceSchema$1, - BooleanSchemaSchema: BooleanSchemaSchema$1, - StringSchemaSchema: StringSchemaSchema$1, - NumberSchemaSchema: NumberSchemaSchema$1, - UntitledSingleSelectEnumSchemaSchema: UntitledSingleSelectEnumSchemaSchema$1, - TitledSingleSelectEnumSchemaSchema: TitledSingleSelectEnumSchemaSchema$1, - LegacyTitledEnumSchemaSchema: LegacyTitledEnumSchemaSchema$1, - SingleSelectEnumSchemaSchema: SingleSelectEnumSchemaSchema$1, - UntitledMultiSelectEnumSchemaSchema: UntitledMultiSelectEnumSchemaSchema$1, - TitledMultiSelectEnumSchemaSchema: TitledMultiSelectEnumSchemaSchema$1, - MultiSelectEnumSchemaSchema: MultiSelectEnumSchemaSchema$1, - EnumSchemaSchema: EnumSchemaSchema$1, - PrimitiveSchemaDefinitionSchema: PrimitiveSchemaDefinitionSchema$1, - ElicitRequestFormParamsSchema: ElicitRequestFormParamsSchema$1, - ResourceTemplateReferenceSchema: ResourceTemplateReferenceSchema$1, - PromptReferenceSchema: PromptReferenceSchema$1, - RootSchema: RootSchema$1, - ClientCapabilities2026Schema, - ServerCapabilities2026Schema, - RequestMetaEnvelopeSchema, - ToolSchema: ToolSchema$1, - ToolResultContentSchema: ToolResultContentSchema$1, - SamplingMessageContentBlockSchema: SamplingMessageContentBlockSchema$1, - SamplingMessageSchema: SamplingMessageSchema$1, - ResultTypeSchema, - ResultMetaSchema, - ResultSchema: ResultSchema$1, - PaginatedResultSchema: PaginatedResultSchema$1, - CallToolResultSchema: CallToolResultSchema$1, - ListToolsResultSchema: ListToolsResultSchema$1, - ListPromptsResultSchema: ListPromptsResultSchema$1, - GetPromptResultSchema: GetPromptResultSchema$1, - ListResourcesResultSchema: ListResourcesResultSchema$1, - ListResourceTemplatesResultSchema: ListResourceTemplatesResultSchema$1, - ReadResourceResultSchema: ReadResourceResultSchema$1, - CompleteResultSchema: CompleteResultSchema$1, - CacheableResultSchema, - DiscoverResultSchema: DiscoverResultSchema$1, - CreateMessageRequestParamsSchema: CreateMessageRequestParamsSchema$1, - CreateMessageRequestSchema: CreateMessageRequestSchema$1, - ListRootsRequestSchema: ListRootsRequestSchema$1, - CreateMessageResultSchema: CreateMessageResultSchema$1, - ListRootsResultSchema: ListRootsResultSchema$1, - ElicitResultSchema: ElicitResultSchema$1, - ElicitRequestURLParamsSchema: ElicitRequestURLParamsSchema$1, - ElicitRequestParamsSchema: ElicitRequestParamsSchema$1, - ElicitRequestSchema: ElicitRequestSchema$1, - InputRequestSchema, - InputResponseSchema, - InputRequestsSchema, - InputResponsesSchema, - InputRequiredResultSchema, - InputResponseRequestParamsSchema, - CallToolRequestSchema: CallToolRequestSchema$1, - ListToolsRequestSchema: ListToolsRequestSchema$1, - ListPromptsRequestSchema: ListPromptsRequestSchema$1, - GetPromptRequestSchema: GetPromptRequestSchema$1, - ListResourcesRequestSchema: ListResourcesRequestSchema$1, - ListResourceTemplatesRequestSchema: ListResourceTemplatesRequestSchema$1, - ReadResourceRequestSchema: ReadResourceRequestSchema$1, - CompleteRequestSchema: CompleteRequestSchema$1, - DiscoverRequestSchema: DiscoverRequestSchema$1, - SubscriptionFilterSchema: SubscriptionFilterSchema$1, - SubscriptionsListenRequestSchema: SubscriptionsListenRequestSchema$1, - SubscriptionsListenResultMetaSchema: SubscriptionsListenResultMetaSchema$1, - SubscriptionsListenResultSchema: SubscriptionsListenResultSchema$1, - dispatchRequestSchemas, - dispatchResultSchemas, - NotificationMetaSchema, - SubscriptionsAcknowledgedNotificationSchema: SubscriptionsAcknowledgedNotificationSchema$1, - CancelledNotificationParamsSchema: CancelledNotificationParamsSchema$1, - CancelledNotificationSchema: CancelledNotificationSchema$1, - notificationSchemas2026, - JSONRPCResultResponseSchema: wireResultResponse(ResultSchema$1), - CallToolResultResponseSchema: wireResultResponse(schemas_union([CallToolResultSchema$1, InputRequiredResultSchema])), - ListToolsResultResponseSchema: wireResultResponse(ListToolsResultSchema$1), - ListPromptsResultResponseSchema: wireResultResponse(ListPromptsResultSchema$1), - GetPromptResultResponseSchema: wireResultResponse(schemas_union([GetPromptResultSchema$1, InputRequiredResultSchema])), - ListResourcesResultResponseSchema: wireResultResponse(ListResourcesResultSchema$1), - ListResourceTemplatesResultResponseSchema: wireResultResponse(ListResourceTemplatesResultSchema$1), - ReadResourceResultResponseSchema: wireResultResponse(schemas_union([ReadResourceResultSchema$1, InputRequiredResultSchema])), - CompleteResultResponseSchema: wireResultResponse(CompleteResultSchema$1), - DiscoverResultResponseSchema: wireResultResponse(DiscoverResultSchema$1) - }; -} -let src_CX2iR2pK_memo; -/** -* Builds the era wire-schema set on first call and returns the same object -* thereafter. Module evaluation stays construction-free so importing the -* era codec/registry costs nothing until the first validation actually -* needs a schema; the registry, the codec, and the eager `schemas.ts` -* shim all pull through this memo, so reference identity holds across -* every consumer. -*/ -function buildSchemas2026() { - return src_CX2iR2pK_memo ??= build(); -} - -//#endregion -//#region ../core-internal/src/shared/resultCacheHints.ts -/** -* The operations whose results are cacheable on the 2026-07-28 revision (the -* `CacheableResult` extenders). This list is closed: no other operation's -* result ever receives cache fields from the SDK. -*/ -const CACHEABLE_RESULT_METHODS = [ - "tools/list", - "prompts/list", - "resources/list", - "resources/templates/list", - "resources/read", - "server/discover" -]; -/** Whether the given method's result is cacheable on the 2026-07-28 revision. */ -function isCacheableResultMethod(method) { - return CACHEABLE_RESULT_METHODS.includes(method); -} -/** -* The symbol-keyed carrier for a configured cache hint on a result object. -* Symbol properties are invisible to JSON serialization, so the carrier can be -* attached era-blind: only the 2026-era encode seam consumes it. -*/ -const RESULT_CACHE_HINT_FALLBACK = Symbol("modelcontextprotocol.resultCacheHintFallback"); -/** -* Attaches a configured cache hint to a result as the encode-time fallback. -* Returns the result unchanged when there is nothing to attach. When a more -* specific hint is already attached, the two hints are combined per field -* (most-specific-author-wins for each of `ttlMs` and `cacheScope`): the -* per-registration hint attached by the feature layer keeps every field it -* sets, and the server-level per-operation hint only fills the fields the -* more specific hint leaves unset. -*/ -function attachCacheHintFallback(result, hint) { - if (hint === void 0) return result; - const attached = result[RESULT_CACHE_HINT_FALLBACK]; - if (attached === void 0) return { - ...result, - [RESULT_CACHE_HINT_FALLBACK]: hint - }; - const merged = {}; - const ttlMs = attached.ttlMs ?? hint.ttlMs; - if (ttlMs !== void 0) merged.ttlMs = ttlMs; - const cacheScope = attached.cacheScope ?? hint.cacheScope; - if (cacheScope !== void 0) merged.cacheScope = cacheScope; - return { - ...result, - [RESULT_CACHE_HINT_FALLBACK]: merged - }; -} -/** Reads the configured cache-hint fallback attached to a result, if any. */ -function cacheHintFallbackOf(result) { - return result[RESULT_CACHE_HINT_FALLBACK]; -} -/** -* Whether a value is a valid `ttlMs`: a non-negative safe integer. Safe -* integers are required because the wire schemas validate `ttlMs` as an -* integer within `Number.MIN_SAFE_INTEGER`/`Number.MAX_SAFE_INTEGER`; a value -* outside that range is treated as invalid here so it falls through to the -* next author instead of being emitted and rejected downstream. -*/ -function isValidCacheTtlMs(value) { - return typeof value === "number" && Number.isSafeInteger(value) && value >= 0; -} -/** Whether a value is a valid `cacheScope`. */ -function isValidCacheScope(value) { - return value === "public" || value === "private"; -} -/** -* Validates a configured cache hint at configuration time. Throws a -* `RangeError` naming the offending field, so misconfiguration fails at -* startup/registration rather than silently degrading at encode time. -*/ -function assertValidCacheHint(hint, context) { - if (hint.ttlMs !== void 0 && !isValidCacheTtlMs(hint.ttlMs)) throw new RangeError(`Invalid cache hint for ${context}: ttlMs must be a non-negative safe integer (got ${String(hint.ttlMs)})`); - if (hint.cacheScope !== void 0 && !isValidCacheScope(hint.cacheScope)) throw new RangeError(`Invalid cache hint for ${context}: cacheScope must be 'public' or 'private' (got ${String(hint.cacheScope)})`); -} - -//#endregion -//#region ../core-internal/src/types/enums.ts -/** -* Error codes for protocol errors that cross the wire as JSON-RPC error responses. -* These follow the JSON-RPC specification and MCP-specific extensions. -*/ -let src_CX2iR2pK_ProtocolErrorCode = /* @__PURE__ */ function(ProtocolErrorCode$1) { - ProtocolErrorCode$1[ProtocolErrorCode$1["ParseError"] = -32700] = "ParseError"; - ProtocolErrorCode$1[ProtocolErrorCode$1["InvalidRequest"] = -32600] = "InvalidRequest"; - ProtocolErrorCode$1[ProtocolErrorCode$1["MethodNotFound"] = -32601] = "MethodNotFound"; - ProtocolErrorCode$1[ProtocolErrorCode$1["InvalidParams"] = -32602] = "InvalidParams"; - ProtocolErrorCode$1[ProtocolErrorCode$1["InternalError"] = -32603] = "InternalError"; - /** - * Resource not found. - * - * Receive-tolerated only: the SDK never EMITS `-32002` — `resources/read` - * misses answer `-32602` (Invalid Params) on every protocol revision per - * the 2026-07-28 spec MUST, and a handler-thrown `-32002` is mapped to - * `-32602` at the era encode seam. The member stays importable so clients - * can recognise `-32002` from peers built on earlier SDK releases (the - * spec's "clients SHOULD also accept `-32002`" backwards-compatibility - * clause). Throw `ResourceNotFoundError` instead. - */ - ProtocolErrorCode$1[ProtocolErrorCode$1["ResourceNotFound"] = -32002] = "ResourceNotFound"; - /** - * Processing the request requires a capability the client did not declare - * in the request's `clientCapabilities` (protocol revision 2026-07-28). - */ - ProtocolErrorCode$1[ProtocolErrorCode$1["MissingRequiredClientCapability"] = -32021] = "MissingRequiredClientCapability"; - /** - * The request's protocol version is unknown to the server or unsupported - * by it (protocol revision 2026-07-28). - */ - ProtocolErrorCode$1[ProtocolErrorCode$1["UnsupportedProtocolVersion"] = -32022] = "UnsupportedProtocolVersion"; - ProtocolErrorCode$1[ProtocolErrorCode$1["UrlElicitationRequired"] = -32042] = "UrlElicitationRequired"; - return ProtocolErrorCode$1; -}({}); - -//#endregion -//#region ../core-internal/src/types/errors.ts -/** -* Protocol errors are JSON-RPC errors that cross the wire as error responses. -* They use numeric error codes from the {@linkcode ProtocolErrorCode} enum. -* -* `instanceof` on this class (and its subclasses) is brand-matched, so it works -* across separately bundled copies of the SDK — e.g. an error constructed by -* `@modelcontextprotocol/client` matches the class re-exported by -* `@modelcontextprotocol/server` in the same process. -*/ -var src_CX2iR2pK_ProtocolError = class ProtocolError extends Error { - static { - Object.defineProperty(this, "mcpBrand", { value: "mcp.ProtocolError" }); - } - static [Symbol.hasInstance](value) { - return brandedHasInstance(this, value); - } - /** - * Brand-based type guard: equivalent to `value instanceof this`, as an - * explicit static predicate (the axios/AWS-SDK `isInstance` style). Reads - * the caller's own brand via `this`, so every branded subclass gets a - * correctly-scoped guard by inheritance. Must be invoked on the class — - * in callback position write `v => SdkError.isInstance(v)`, not - * `.filter(SdkError.isInstance)` (detached calls throw rather than - * silently matching nothing). - */ - static isInstance(value) { - 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 brandedHasInstance(this, value); - } - constructor(code, message, data) { - super(message); - this.code = code; - this.data = data; - this.name = "ProtocolError"; - stampErrorBrands(this, new.target); - } - /** - * Factory method to create the appropriate error type based on the error code and data - */ - static fromError(code, message, data) { - if (code === src_CX2iR2pK_ProtocolErrorCode.UrlElicitationRequired && data) { - const errorData = data; - if (errorData.elicitations) return new UrlElicitationRequiredError(errorData.elicitations, message); - } - if (code === src_CX2iR2pK_ProtocolErrorCode.UnsupportedProtocolVersion && data) { - const errorData = data; - if (Array.isArray(errorData.supported) && typeof errorData.requested === "string") return new src_CX2iR2pK_UnsupportedProtocolVersionError({ - supported: errorData.supported, - requested: errorData.requested - }, message); - } - if (code === src_CX2iR2pK_ProtocolErrorCode.InvalidParams || code === src_CX2iR2pK_ProtocolErrorCode.ResourceNotFound) { - const errorData = data; - if (typeof errorData?.uri === "string" && (code === src_CX2iR2pK_ProtocolErrorCode.ResourceNotFound || Object.keys(errorData).length === 1)) return new ResourceNotFoundError(errorData.uri, message); - } - if (code === src_CX2iR2pK_ProtocolErrorCode.MissingRequiredClientCapability && data) { - const errorData = data; - if (errorData.requiredCapabilities !== null && typeof errorData.requiredCapabilities === "object" && !Array.isArray(errorData.requiredCapabilities)) return new src_CX2iR2pK_MissingRequiredClientCapabilityError({ requiredCapabilities: errorData.requiredCapabilities }, message); - } - return new ProtocolError(code, message, data); - } -}; -/** -* Error type for a `resources/read` miss: the requested resource does not -* exist. The wire code is `-32602` (Invalid Params) on every protocol -* revision — the spec MUST for revision 2026-07-28, and the value the v1.x -* SDK has always emitted on earlier revisions. The error data echoes the -* requested URI. -* -* Recognise this error by checking `error.data` is exactly `{ uri: string }` -* (a `-32602` whose data carries `uri` and nothing else is resource-not-found; -* any other `-32602` is an ordinary Invalid Params). For backwards compatibility, clients should also -* accept `-32002` as resource not found — earlier SDK builds emitted that -* code, and {@linkcode ProtocolError.fromError} reconstructs this class for -* either code **when `error.data` carries `uri`** (a bare `-32002` without -* `data.uri` stays a generic {@linkcode ProtocolError}). `instanceof` checks -* are brand-matched and work across separately bundled copies of the SDK. -*/ -var ResourceNotFoundError = class extends src_CX2iR2pK_ProtocolError { - static { - Object.defineProperty(this, "mcpBrand", { value: "mcp.ResourceNotFoundError" }); - } - constructor(uri, message = `Resource not found: ${uri}`) { - super(src_CX2iR2pK_ProtocolErrorCode.InvalidParams, message, { uri }); - } - /** The URI that was requested and not found. */ - get uri() { - return this.data.uri; - } -}; -/** -* Specialized error type when a tool requires a URL mode elicitation. -* This makes it nicer for the client to handle since there is specific data to work with instead of just a code to check against. -*/ -var UrlElicitationRequiredError = class extends src_CX2iR2pK_ProtocolError { - static { - Object.defineProperty(this, "mcpBrand", { value: "mcp.UrlElicitationRequiredError" }); - } - constructor(elicitations, message = `URL elicitation${elicitations.length > 1 ? "s" : ""} required`) { - super(src_CX2iR2pK_ProtocolErrorCode.UrlElicitationRequired, message, { elicitations }); - } - get elicitations() { - return this.data?.elicitations ?? []; - } -}; -/** -* Error type for the `-32022` UnsupportedProtocolVersion protocol error (protocol -* revision 2026-07-28): the request's protocol version is unknown to the server or -* unsupported by it. -* -* The error data lists the protocol versions the receiver supports (`supported`), -* so the sender can choose a mutually supported version and retry, and echoes the -* version that was requested (`requested`). -*/ -var src_CX2iR2pK_UnsupportedProtocolVersionError = class extends src_CX2iR2pK_ProtocolError { - static { - Object.defineProperty(this, "mcpBrand", { value: "mcp.UnsupportedProtocolVersionError" }); - } - constructor(data, message = `Unsupported protocol version: ${data.requested}`) { - super(src_CX2iR2pK_ProtocolErrorCode.UnsupportedProtocolVersion, message, data); - } - /** - * Protocol versions the receiver supports. - */ - get supported() { - return this.data.supported; - } - /** - * The protocol version that was requested. - */ - get requested() { - return this.data.requested; - } -}; -/** -* Error type for the `-32021` MissingRequiredClientCapability protocol error -* (protocol revision 2026-07-28): processing the request requires a capability -* the client did not declare in the request's `clientCapabilities`. -* -* The error data lists the missing capabilities (`requiredCapabilities`) in -* the `ClientCapabilities` shape, so the client can see exactly what it would -* have to declare for the request to be served. On HTTP, the response status -* is `400 Bad Request`. -* -* Recognize this error by its code and `data.requiredCapabilities`, or by -* `instanceof` — checks are brand-matched and work across separately bundled -* copies of the SDK. -*/ -var src_CX2iR2pK_MissingRequiredClientCapabilityError = class extends src_CX2iR2pK_ProtocolError { - static { - Object.defineProperty(this, "mcpBrand", { value: "mcp.MissingRequiredClientCapabilityError" }); - } - constructor(data, message = `Missing required client capabilities: ${Object.keys(data.requiredCapabilities).join(", ")}`) { - super(src_CX2iR2pK_ProtocolErrorCode.MissingRequiredClientCapability, message, data); - } - /** - * The capabilities the server requires from the client to process the - * request (only the missing capabilities are listed). - */ - get requiredCapabilities() { - return this.data.requiredCapabilities; - } -}; - -//#endregion -//#region ../core-internal/src/wire/rev2026-07-28/encodeContract.ts -/** The default cache policy when neither the handler nor configuration provides one. */ -const DEFAULT_CACHE_TTL_MS = 0; -const DEFAULT_CACHE_SCOPE = "private"; -/** -* Request methods whose spec result vocabulary goes beyond `'complete'` on the -* 2026-07-28 revision: their results may be `input_required` (multi -* round-trip requests), so a handler-provided `resultType` passes through the -* stamp untouched. `subscriptions/listen` is NOT in this set: it never emits -* a JSON-RPC result — termination is stream close (HTTP) or -* `notifications/cancelled` (stdio) per the spec. -*/ -const EXTENDED_RESULT_TYPE_METHODS = [ - "tools/call", - "prompts/get", - "resources/read" -]; -/** -* Step 1 of the encode contract: ensure the outbound result carries the -* required `resultType` discriminator. -* -* - No handler-provided value → stamp `'complete'`. -* - Handler-provided `'complete'` → kept as-is. -* - Handler-provided non-`'complete'` value on a method whose vocabulary -* allows it ({@linkcode EXTENDED_RESULT_TYPE_METHODS}) → passes through. -* The value is forwarded verbatim — the wire vocabulary is an open union and -* the SDK does not validate the string, so emitting a `resultType` the -* negotiated revision does not define is the handler author's -* responsibility. -* - Handler-provided non-`'complete'` value on any other method → internal -* error (loud): the value would be mis-typed on the wire, and silently -* rewriting it would hide a server bug. -*/ -function stampResultType(method, result) { - const provided = result["resultType"]; - if (provided === void 0) return { - ...result, - resultType: "complete" - }; - if (provided === "complete") return result; - if (EXTENDED_RESULT_TYPE_METHODS.includes(method)) return result; - throw new src_CX2iR2pK_ProtocolError(src_CX2iR2pK_ProtocolErrorCode.InternalError, `Handler for ${method} returned resultType '${String(provided)}', but results of ${method} only support 'complete' on protocol revision 2026-07-28`); -} -/** -* Step 2 of the encode contract: fill the required `ttlMs`/`cacheScope` fields -* on cacheable results. -* -* Applies only when the (post-stamp) `resultType` is `'complete'` and the -* method is one of the cacheable operations; everything else is returned -* untouched apart from removing the configured-hint carrier. Field resolution -* is per field, most specific author first: a valid handler-returned value, -* then the configured cache hint attached by the server layer, then the -* defaults. Handler-returned values are validated at encode time (`ttlMs` -* must be a non-negative integer, `cacheScope` must be `'public'` or -* `'private'`); invalid values are ignored rather than emitted. -*/ -function fillCacheFields(method, result) { - const fallback = cacheHintFallbackOf(result); - if (result["resultType"] !== "complete" || !isCacheableResultMethod(method)) return fallback === void 0 ? result : stripCacheHintFallback(result); - const provided = result; - const ttlMs = isValidCacheTtlMs(provided["ttlMs"]) ? provided["ttlMs"] : resolveTtlMs(fallback); - const cacheScope = isValidCacheScope(provided["cacheScope"]) ? provided["cacheScope"] : resolveCacheScope(fallback); - const filled = { - ...provided, - ttlMs, - cacheScope - }; - delete filled[RESULT_CACHE_HINT_FALLBACK]; - return filled; -} -function isPlainObject$5(value) { - return value !== null && typeof value === "object" && !Array.isArray(value); -} -/** -* Step 3 of the encode contract: stamp the server's identity into the -* result's `_meta` under `io.modelcontextprotocol/serverInfo` (spec PR #3002: -* servers SHOULD include it on every response). -* -* - No `serverInfo` supplied (a client instance, or a hand-constructed -* protocol object) → identity function. -* - The result's `_meta` already carries the key → kept as-is (the handler -* is the more specific author; mirrors the cache-fill resolution order). -* - A present-but-non-object `_meta` (a dynamic-caller bug) → kept as-is: -* the stamp never rewrites handler material, and the malformed value fails -* loudly at the peer instead of being silently replaced here. -* - Otherwise → the key is added, preserving any other `_meta` entries. -* -* Runs for every result regardless of `resultType`: the anchor types -* `Result._meta` as `ResultMetaObject` on all results, `input_required` -* included. -*/ -function stampServerInfoMeta(result, serverInfo) { - if (serverInfo === void 0) return result; - const meta = result["_meta"]; - if (meta === void 0) return { - ...result, - _meta: { [auth_CUe6YdwF_SERVER_INFO_META_KEY]: serverInfo } - }; - if (!isPlainObject$5(meta)) return result; - if (meta[auth_CUe6YdwF_SERVER_INFO_META_KEY] !== void 0) return result; - return { - ...result, - _meta: { - ...meta, - [auth_CUe6YdwF_SERVER_INFO_META_KEY]: serverInfo - } - }; -} -function resolveTtlMs(fallback) { - return fallback !== void 0 && isValidCacheTtlMs(fallback.ttlMs) ? fallback.ttlMs : DEFAULT_CACHE_TTL_MS; -} -function resolveCacheScope(fallback) { - return fallback !== void 0 && isValidCacheScope(fallback.cacheScope) ? fallback.cacheScope : DEFAULT_CACHE_SCOPE; -} -function stripCacheHintFallback(result) { - const copy = { ...result }; - delete copy[RESULT_CACHE_HINT_FALLBACK]; - return copy; -} - -//#endregion -//#region ../core-internal/src/wire/rev2026-07-28/inputRequired.ts -/** -* In-band input-request vocabulary of the 2026-07-28 revision (SEP-2322 -* multi round-trip requests), dispatch view. -* -* The three former server→client wire requests (`elicitation/create`, -* `sampling/createMessage`, `roots/list`) are NOT wire request methods on -* this revision — they are demoted to de-JSON-RPC'd payloads embedded in an -* `input_required` result. The multi-round-trip driver dispatches those -* embedded payloads to the client's registered handlers through the normal -* handler machinery, and these are the schemas that dispatch parses them -* with: lenient where the anchor's wire-true artifacts are strict (an -* embedded request never carries the per-request `_meta` envelope), exact -* where the vocabulary forks (the sampling shapes compose the forked -* SamplingMessage/Tool payloads). -* -* Registry membership is intentionally NOT granted here — these methods stay -* absent from the 2026-era request registry (a peer sending one as a wire -* request still gets −32601 by absence). Only the codec's -* `inputRequestSchema`/`inputResponseSchema` accessors expose them. -*/ -/** The embedded input-request methods of the 2026-07-28 revision. */ -const INPUT_REQUEST_METHODS_2026 = [ - "elicitation/create", - "sampling/createMessage", - "roots/list" -]; -let maps; -function inputSchemaMaps() { - if (maps) return maps; - const s = buildSchemas2026(); - maps = { - request: { - "elicitation/create": schemas_object({ - method: literal("elicitation/create"), - params: s.ElicitRequestParamsSchema - }), - "sampling/createMessage": schemas_object({ - method: literal("sampling/createMessage"), - params: s.CreateMessageRequestParamsSchema - }), - "roots/list": schemas_object({ - method: literal("roots/list"), - params: looseObject({}).optional() - }) - }, - response: { - "elicitation/create": s.ElicitResultSchema, - "sampling/createMessage": s.CreateMessageResultSchema, - "roots/list": s.ListRootsResultSchema - } - }; - return maps; -} -/** -* Forces the lazy embedded-request maps (and, through them, the era's schema -* memo). Warm-up hook for `preloadSchemas()` — no-op once the maps exist. -*/ -function warmInputSchemaMaps2026() { - inputSchemaMaps(); -} -function isInputRequestMethod2026(method) { - return INPUT_REQUEST_METHODS_2026.includes(method); -} -function getInputRequestSchema2026(method) { - return isInputRequestMethod2026(method) ? inputSchemaMaps().request[method] : void 0; -} -function getInputResponseSchema2026(method) { - return isInputRequestMethod2026(method) ? inputSchemaMaps().response[method] : void 0; -} - -//#endregion -//#region ../core-internal/src/wire/rev2026-07-28/registry.ts -const requestMethodKeys = { - "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 -}; -const notificationMethodKeys = { - "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 -}; -/** The 2026-era request-method set (registry membership = the deletion story). */ -function hasRequestMethod2026(method) { - return Object.prototype.hasOwnProperty.call(requestMethodKeys, method); -} -/** The 2026-era notification-method set. */ -function hasNotificationMethod2026(method) { - return Object.prototype.hasOwnProperty.call(notificationMethodKeys, method); -} -/** Result-map membership (same key set as the request map on this era). */ -function hasResultMethod2026(method) { - return Object.prototype.hasOwnProperty.call(requestMethodKeys, method); -} -function getRequestSchema2026(method) { - return hasRequestMethod2026(method) ? buildSchemas2026().dispatchRequestSchemas[method] : void 0; -} -function getResultSchema2026(method) { - return hasResultMethod2026(method) ? buildSchemas2026().dispatchResultSchemas[method] : void 0; -} -function getNotificationSchema2026(method) { - return hasNotificationMethod2026(method) ? buildSchemas2026().notificationSchemas2026[method] : void 0; -} -/** Registry method lists (for the spec-method universe and the CI registry-diff oracle). */ -const rev2026RequestMethods = Object.keys(requestMethodKeys); -const rev2026NotificationMethods = Object.keys(notificationMethodKeys); - -//#endregion -//#region ../core-internal/src/wire/rev2026-07-28/codec.ts -function isPlainObject$4(value) { - return value !== null && typeof value === "object" && !Array.isArray(value); -} -/** Tri-state wrap of an optional Zod schema lookup (the function-only contract). */ -function triState(schema, raw) { - if (schema === void 0) return { - ok: false, - reason: "not-in-era" - }; - const parsed = schema.safeParse(raw); - return parsed.success ? { - ok: true, - value: parsed.data - } : { - ok: false, - reason: "invalid", - message: String(parsed.error) - }; -} -const NOT_IN_ERA = { - ok: false, - reason: "not-in-era" -}; -/** -* The reserved `_meta` keys an envelope must carry on this era (in reporting -* order). `clientInfo` is NOT here: spec PR #3002 demoted it to SHOULD, so a -* request without it is accepted (a present-but-malformed value still fails -* the envelope schema parse below). -*/ -const REQUIRED_ENVELOPE_KEYS = [auth_CUe6YdwF_PROTOCOL_VERSION_META_KEY, auth_CUe6YdwF_CLIENT_CAPABILITIES_META_KEY]; -/** Strip the known deleted-field set from an outbound result (Q1-SD3 iii). */ -function enforceDeletedFields(method, result) { - let next = result; - let copied = false; - const copy = () => { - if (!copied) { - next = { ...next }; - copied = true; - } - return next; - }; - const tools = result.tools; - if (method === "tools/list" && Array.isArray(tools) && tools.some((tool) => isPlainObject$4(tool) && "execution" in tool)) copy().tools = tools.map((tool) => { - if (!isPlainObject$4(tool) || !("execution" in tool)) return tool; - const rest = { ...tool }; - delete rest["execution"]; - return rest; - }); - const capabilities = result.capabilities; - if (isPlainObject$4(capabilities) && "tasks" in capabilities) { - const rest = { ...capabilities }; - delete rest["tasks"]; - copy().capabilities = rest; - } - return next; -} -const rev2026Codec = { - era: "2026-07-28", - hasRequestMethod: hasRequestMethod2026, - hasNotificationMethod: hasNotificationMethod2026, - hasInputRequestMethod: (method) => getInputRequestSchema2026(method) !== void 0, - validateRequest: (method, raw) => triState(getRequestSchema2026(method), raw), - validateResult: (method, raw) => triState(getResultSchema2026(method), raw), - validateNotification: (method, raw) => triState(getNotificationSchema2026(method), raw), - validateInputRequest: (method, raw) => triState(getInputRequestSchema2026(method), raw), - validateInputResponse: (method, raw) => triState(getInputResponseSchema2026(method), raw), - samplingResultVariant: () => NOT_IN_ERA, - outboundEnvelope(material) { - return { - [auth_CUe6YdwF_PROTOCOL_VERSION_META_KEY]: material.protocolVersion, - [auth_CUe6YdwF_CLIENT_INFO_META_KEY]: material.clientInfo, - [auth_CUe6YdwF_CLIENT_CAPABILITIES_META_KEY]: material.clientCapabilities, - ...material.logLevel !== void 0 && { [LOG_LEVEL_META_KEY]: material.logLevel } - }; - }, - validateEnvelopeMeta(meta) { - const issues = []; - for (const key of REQUIRED_ENVELOPE_KEYS) if (!(key in meta)) issues.push({ - key, - problem: "missing" - }); - const parsed = buildSchemas2026().RequestMetaEnvelopeSchema.safeParse(meta); - if (!parsed.success) for (const issue of parsed.error.issues) { - const path = issue.path.map(String); - const key = path.length > 0 ? path.join(".") : "_meta"; - if (path.length === 1 && issues.some((existing) => existing.key === key && existing.problem === "missing")) continue; - issues.push({ - key, - problem: issue.message - }); - } - return issues; - }, - projectCallToolResult: (result) => appendTextFallbackForNonObject(result), - inputRequestSchema: getInputRequestSchema2026, - decodeResult(method, raw) { - if (!isPlainObject$4(raw)) return { - kind: "invalid", - error: new src_CX2iR2pK_SdkError(src_CX2iR2pK_SdkErrorCode.InvalidResult, `Invalid result for ${method}: not an object`, { method }) - }; - const rawResultType = raw["resultType"]; - if (rawResultType === void 0) return { - kind: "invalid", - error: new src_CX2iR2pK_SdkError(src_CX2iR2pK_SdkErrorCode.InvalidResult, `Invalid result for ${method}: missing required resultType — servers implementing protocol revision 2026-07-28 MUST include it (the absent-means-complete bridge applies only to earlier-revision servers)`, { - method, - violation: "missing-resultType" - }) - }; - if (typeof rawResultType !== "string") return { - kind: "invalid", - error: new src_CX2iR2pK_SdkError(src_CX2iR2pK_SdkErrorCode.InvalidResult, `Invalid result for ${method}: non-string resultType`, { - method, - resultType: rawResultType - }) - }; - if (rawResultType === "input_required") { - const rawInputRequests = raw["inputRequests"]; - const inputRequests = isPlainObject$4(rawInputRequests) ? rawInputRequests : {}; - const requestState = raw["requestState"]; - if (Object.keys(inputRequests).length === 0 && typeof requestState !== "string") return { - kind: "invalid", - error: new src_CX2iR2pK_SdkError(src_CX2iR2pK_SdkErrorCode.InvalidResult, `Invalid result for ${method}: input_required carries neither inputRequests nor requestState (every input_required result must include at least one of the two)`, { - method, - violation: "input-required-missing-both" - }) - }; - return { - kind: "input_required", - inputRequests, - ...typeof requestState === "string" && { requestState } - }; - } - if (rawResultType !== "complete") return { - kind: "invalid", - error: new src_CX2iR2pK_SdkError(src_CX2iR2pK_SdkErrorCode.UnsupportedResultType, `Unsupported result type '${rawResultType}' for ${method}`, { - resultType: rawResultType, - method - }) - }; - const wireResultSchemas = getWireResultSchemas(); - const wireSchema = Object.hasOwn(wireResultSchemas, method) ? wireResultSchemas[method] : void 0; - if (wireSchema !== void 0) { - const parsed = wireSchema.safeParse(raw); - if (!parsed.success) return { - kind: "invalid", - error: new src_CX2iR2pK_SdkError(src_CX2iR2pK_SdkErrorCode.InvalidResult, `Invalid result for ${method}: ${parsed.error}`, { method }) - }; - } - const lifted = { ...raw }; - delete lifted["resultType"]; - return { - kind: "complete", - result: lifted - }; - }, - encodeResult(method, result, serverInfo) { - return stampServerInfoMeta(fillCacheFields(method, stampResultType(method, enforceDeletedFields(method, result))), serverInfo); - }, - encodeErrorCode: (code) => code === -32002 ? -32602 : code, - checkInboundEnvelope(material) { - if (material.envelope === void 0) return "Request is missing the required _meta envelope for protocol revision 2026-07-28 (io.modelcontextprotocol/protocolVersion, io.modelcontextprotocol/clientCapabilities)"; - const parsed = buildSchemas2026().RequestMetaEnvelopeSchema.safeParse(material.envelope); - if (!parsed.success) return `Invalid _meta envelope for protocol revision 2026-07-28: ${parsed.error.issues.map((issue) => issue.message).join("; ")}`; - } -}; -/** Wire-true result wrappers consulted by decode step 2, keyed by method — -* built once through the era's schema memo on the first decode. */ -let wireResultSchemasMemo; -function getWireResultSchemas() { - if (wireResultSchemasMemo) return wireResultSchemasMemo; - const s = buildSchemas2026(); - wireResultSchemasMemo = { - "tools/call": s.CallToolResultSchema, - "tools/list": s.ListToolsResultSchema, - "prompts/get": s.GetPromptResultSchema, - "prompts/list": s.ListPromptsResultSchema, - "resources/list": s.ListResourcesResultSchema, - "resources/templates/list": s.ListResourceTemplatesResultSchema, - "resources/read": s.ReadResourceResultSchema, - "completion/complete": s.CompleteResultSchema, - "server/discover": s.DiscoverResultSchema - }; - return wireResultSchemasMemo; -} -/** -* Forces the lazy wire-result wrapper map (and, through it, the era's schema -* memo). Warm-up hook for `preloadSchemas()` — no-op once the map exists. -*/ -function warmWireResultSchemas2026() { - getWireResultSchemas(); -} - -//#endregion -//#region ../core-internal/src/wire/codec.ts -/** -* The modern wire revision literal. Internal only — deliberately NOT a public -* constant (G-D2-4: no public modern-version constant ships before era-aware -* list semantics exist). -*/ -const src_CX2iR2pK_MODERN_WIRE_REVISION = "2026-07-28"; -/** -* Era resolution, many-to-one (Q1-SD1): every modern-era revision -* (`>= 2026-07-28`) → the 2026-era codec; every legacy revision (the five -* `SUPPORTED_PROTOCOL_VERSIONS`) and `undefined`/unknown → the 2025-era -* codec (the DV-13 default posture — hand-constructed instances and -* unclassified traffic are legacy-era). This is the same era predicate the -* rest of the SDK uses ({@link isModernProtocolVersion}); a pinned modern -* revision other than the literal '2026-07-28' must still resolve modern. -*/ -function src_CX2iR2pK_codecForVersion(version) { - return version !== void 0 && isModernProtocolVersion(version) ? rev2026Codec : rev2025Codec; -} -/** -* The wire era an edge classification names (Q2 — produced at the -* transport/entry edge; this layer only CONSUMES it). The dispatch funnel no -* longer resolves a codec FROM the classification: era is instance state, and -* a classified inbound message is VALIDATED against the instance era — a -* mismatch is an entry/routing error, never a per-message era switch. The -* exact `revision` wins over the coarse era flag when both are present. -*/ -function classifiedWireEra(classification) { - if (classification.revision !== void 0) return src_CX2iR2pK_codecForVersion(classification.revision).era; - return classification.era === "modern" ? rev2026Codec.era : rev2025Codec.era; -} -/** -* The derived spec-method universe: the union of every codec registry. A -* method in this set is era-gated at dispatch and send time; a method outside -* it is a consumer-owned extension method (era-blind, schema-explicit). -* Derived from the registries — never hand-curated (the LEGACY_ONLY_METHODS -* table class is exactly what registry membership replaces). -*/ -function isSpecRequestMethod(method) { - return ALL_CODECS.some((codec) => codec.hasRequestMethod(method)); -} -function isSpecNotificationMethod(method) { - return ALL_CODECS.some((codec) => codec.hasNotificationMethod(method)); -} -const ALL_CODECS = [rev2025Codec, rev2026Codec]; - -//#endregion -//#region ../core-internal/src/shared/envelope.ts -/** -* Per-request `_meta` envelope claim helpers (protocol revision 2026-07-28). -* -* Pure, value-returning helpers used by the inbound HTTP classifier -* (`classifyInboundRequest`): claim detection and envelope validation with -* self-identifying issues. The envelope schema itself stays the wire layer's -* single source of truth (`RequestMetaEnvelopeSchema`); this module only maps -* its outcomes into the shapes the validation ladder emits. -* -* Claim detection is deliberately narrow: a message claims the 2026-07-28 -* envelope mechanism if and only if the reserved protocol-version `_meta` key -* is present in `params._meta`. Other reserved keys (client info, client -* capabilities, log level), a bare `progressToken`, or unrelated keys under -* the `io.modelcontextprotocol/` prefix do NOT constitute a claim on their -* own — but once the claim key is present, a malformed envelope is a -* validation error, never a silent fall back to legacy handling. -* -* The wire-exact envelope schema, the required-key set, and the per-key issue -* mapping live in the wire layer (the 2026-era codec's `validateEnvelopeMeta`). -* This module never reaches into a per-revision wire module directly. -*/ -function isPlainObject$3(value) { - return value !== null && typeof value === "object" && !Array.isArray(value); -} -/** The `_meta` object of a message's params, when present. */ -function src_CX2iR2pK_requestMetaOf(params) { - if (!isPlainObject$3(params)) return void 0; - const meta = params["_meta"]; - return isPlainObject$3(meta) ? meta : void 0; -} -/** -* Whether a message's params carry the per-request envelope claim: the -* reserved protocol-version `_meta` key is present (regardless of whether the -* rest of the envelope is valid — validation is a separate, later step). -*/ -function src_CX2iR2pK_hasEnvelopeClaim(params) { - const meta = src_CX2iR2pK_requestMetaOf(params); - return meta !== void 0 && PROTOCOL_VERSION_META_KEY in meta; -} -/** -* The protocol version named by a message's envelope claim, when the claim is -* present and carries a string value. A present claim with a non-string value -* still counts as a claim ({@linkcode hasEnvelopeClaim}); it surfaces as a -* validation issue instead of a version. -*/ -function src_CX2iR2pK_envelopeClaimVersion(params) { - const value = src_CX2iR2pK_requestMetaOf(params)?.[PROTOCOL_VERSION_META_KEY]; - return typeof value === "string" ? value : void 0; -} -/** -* Validates a request's `_meta` object as a 2026-07-28 per-request envelope -* and reports problems as self-identifying issues (which key, what problem). -* -* Returns an empty array when the envelope is valid. Missing required keys are -* reported first (as `problem: 'missing'`), then schema violations inside -* present keys, in a stable order. -*/ -function src_CX2iR2pK_validateEnvelopeMeta(meta) { - return src_CX2iR2pK_codecForVersion(src_CX2iR2pK_MODERN_WIRE_REVISION).validateEnvelopeMeta(meta); -} - -//#endregion -//#region ../core-internal/src/types/schemas.ts -var schemas_exports = /* @__PURE__ */ __exportAll({ - AnnotationsSchema: () => AnnotationsSchema, - AudioContentSchema: () => AudioContentSchema, - BaseMetadataSchema: () => BaseMetadataSchema, - BaseRequestParamsSchema: () => BaseRequestParamsSchema, - BlobResourceContentsSchema: () => BlobResourceContentsSchema, - BooleanSchemaSchema: () => BooleanSchemaSchema, - CallToolRequestParamsSchema: () => CallToolRequestParamsSchema, - CallToolRequestSchema: () => CallToolRequestSchema, - CallToolResultSchema: () => auth_CUe6YdwF_CallToolResultSchema, - CancelTaskRequestSchema: () => CancelTaskRequestSchema, - CancelTaskResultSchema: () => CancelTaskResultSchema, - CancelledNotificationParamsSchema: () => CancelledNotificationParamsSchema, - CancelledNotificationSchema: () => CancelledNotificationSchema, - ClientCapabilitiesSchema: () => ClientCapabilitiesSchema, - ClientNotificationSchema: () => ClientNotificationSchema, - ClientRequestSchema: () => ClientRequestSchema, - ClientResultSchema: () => ClientResultSchema, - ClientTasksCapabilitySchema: () => ClientTasksCapabilitySchema, - CompatibilityCallToolResultSchema: () => CompatibilityCallToolResultSchema, - CompleteRequestParamsSchema: () => CompleteRequestParamsSchema, - CompleteRequestSchema: () => CompleteRequestSchema, - CompleteResultSchema: () => CompleteResultSchema, - ContentBlockSchema: () => ContentBlockSchema, - CreateMessageRequestParamsSchema: () => CreateMessageRequestParamsSchema, - CreateMessageRequestSchema: () => CreateMessageRequestSchema, - CreateMessageResultSchema: () => CreateMessageResultSchema, - CreateMessageResultWithToolsSchema: () => CreateMessageResultWithToolsSchema, - CreateTaskResultSchema: () => CreateTaskResultSchema, - CursorSchema: () => CursorSchema, - DiscoverRequestSchema: () => DiscoverRequestSchema, - DiscoverResultSchema: () => DiscoverResultSchema, - ElicitRequestFormParamsSchema: () => ElicitRequestFormParamsSchema, - ElicitRequestParamsSchema: () => ElicitRequestParamsSchema, - ElicitRequestSchema: () => ElicitRequestSchema, - ElicitRequestURLParamsSchema: () => ElicitRequestURLParamsSchema, - ElicitResultSchema: () => ElicitResultSchema, - ElicitationCompleteNotificationParamsSchema: () => ElicitationCompleteNotificationParamsSchema, - ElicitationCompleteNotificationSchema: () => ElicitationCompleteNotificationSchema, - EmbeddedResourceSchema: () => EmbeddedResourceSchema, - EmptyResultSchema: () => EmptyResultSchema, - EnumSchemaSchema: () => EnumSchemaSchema, - GetPromptRequestParamsSchema: () => GetPromptRequestParamsSchema, - GetPromptRequestSchema: () => GetPromptRequestSchema, - GetPromptResultSchema: () => GetPromptResultSchema, - GetTaskPayloadRequestSchema: () => GetTaskPayloadRequestSchema, - GetTaskPayloadResultSchema: () => GetTaskPayloadResultSchema, - GetTaskRequestSchema: () => GetTaskRequestSchema, - GetTaskResultSchema: () => GetTaskResultSchema, - IconSchema: () => IconSchema, - IconsSchema: () => IconsSchema, - ImageContentSchema: () => ImageContentSchema, - ImplementationSchema: () => ImplementationSchema, - InitializeRequestParamsSchema: () => InitializeRequestParamsSchema, - InitializeRequestSchema: () => auth_CUe6YdwF_InitializeRequestSchema, - InitializeResultSchema: () => InitializeResultSchema, - InitializedNotificationSchema: () => auth_CUe6YdwF_InitializedNotificationSchema, - JSONArraySchema: () => JSONArraySchema, - JSONObjectSchema: () => JSONObjectSchema, - JSONRPCErrorResponseSchema: () => JSONRPCErrorResponseSchema, - JSONRPCMessageSchema: () => auth_CUe6YdwF_JSONRPCMessageSchema, - JSONRPCNotificationSchema: () => JSONRPCNotificationSchema, - JSONRPCRequestSchema: () => JSONRPCRequestSchema, - JSONRPCResponseSchema: () => auth_CUe6YdwF_JSONRPCResponseSchema, - JSONRPCResultResponseSchema: () => JSONRPCResultResponseSchema, - JSONValueSchema: () => JSONValueSchema, - LegacyTitledEnumSchemaSchema: () => LegacyTitledEnumSchemaSchema, - ListChangedOptionsBaseSchema: () => ListChangedOptionsBaseSchema, - ListPromptsRequestSchema: () => ListPromptsRequestSchema, - ListPromptsResultSchema: () => ListPromptsResultSchema, - ListResourceTemplatesRequestSchema: () => ListResourceTemplatesRequestSchema, - ListResourceTemplatesResultSchema: () => ListResourceTemplatesResultSchema, - ListResourcesRequestSchema: () => ListResourcesRequestSchema, - ListResourcesResultSchema: () => ListResourcesResultSchema, - ListRootsRequestSchema: () => ListRootsRequestSchema, - ListRootsResultSchema: () => ListRootsResultSchema, - ListTasksRequestSchema: () => ListTasksRequestSchema, - ListTasksResultSchema: () => ListTasksResultSchema, - ListToolsRequestSchema: () => ListToolsRequestSchema, - ListToolsResultSchema: () => ListToolsResultSchema, - LoggingLevelSchema: () => LoggingLevelSchema, - LoggingMessageNotificationParamsSchema: () => LoggingMessageNotificationParamsSchema, - LoggingMessageNotificationSchema: () => LoggingMessageNotificationSchema, - ModelHintSchema: () => ModelHintSchema, - ModelPreferencesSchema: () => ModelPreferencesSchema, - MultiSelectEnumSchemaSchema: () => MultiSelectEnumSchemaSchema, - NotificationSchema: () => NotificationSchema, - NotificationsParamsSchema: () => NotificationsParamsSchema, - NumberSchemaSchema: () => NumberSchemaSchema, - PaginatedRequestParamsSchema: () => PaginatedRequestParamsSchema, - PaginatedRequestSchema: () => PaginatedRequestSchema, - PaginatedResultSchema: () => PaginatedResultSchema, - PingRequestSchema: () => PingRequestSchema, - PrimitiveSchemaDefinitionSchema: () => PrimitiveSchemaDefinitionSchema, - ProgressNotificationParamsSchema: () => ProgressNotificationParamsSchema, - ProgressNotificationSchema: () => ProgressNotificationSchema, - ProgressSchema: () => ProgressSchema, - ProgressTokenSchema: () => ProgressTokenSchema, - PromptArgumentSchema: () => PromptArgumentSchema, - PromptListChangedNotificationSchema: () => PromptListChangedNotificationSchema, - PromptMessageSchema: () => PromptMessageSchema, - PromptReferenceSchema: () => PromptReferenceSchema, - PromptSchema: () => PromptSchema, - ReadResourceRequestParamsSchema: () => ReadResourceRequestParamsSchema, - ReadResourceRequestSchema: () => ReadResourceRequestSchema, - ReadResourceResultSchema: () => ReadResourceResultSchema, - RelatedTaskMetadataSchema: () => RelatedTaskMetadataSchema, - RequestIdSchema: () => RequestIdSchema, - RequestMetaSchema: () => RequestMetaSchema, - RequestSchema: () => RequestSchema, - ResourceContentsSchema: () => ResourceContentsSchema, - ResourceLinkSchema: () => ResourceLinkSchema, - ResourceListChangedNotificationSchema: () => ResourceListChangedNotificationSchema, - ResourceRequestParamsSchema: () => ResourceRequestParamsSchema, - ResourceSchema: () => ResourceSchema, - ResourceTemplateReferenceSchema: () => ResourceTemplateReferenceSchema, - ResourceTemplateSchema: () => ResourceTemplateSchema, - ResourceUpdatedNotificationParamsSchema: () => ResourceUpdatedNotificationParamsSchema, - ResourceUpdatedNotificationSchema: () => ResourceUpdatedNotificationSchema, - ResultMetaObjectSchema: () => ResultMetaObjectSchema, - ResultSchema: () => ResultSchema, - RoleSchema: () => RoleSchema, - RootSchema: () => RootSchema, - RootsListChangedNotificationSchema: () => RootsListChangedNotificationSchema, - SamplingContentSchema: () => SamplingContentSchema, - SamplingMessageContentBlockSchema: () => SamplingMessageContentBlockSchema, - SamplingMessageSchema: () => SamplingMessageSchema, - ServerCapabilitiesSchema: () => ServerCapabilitiesSchema, - ServerNotificationSchema: () => ServerNotificationSchema, - ServerRequestSchema: () => ServerRequestSchema, - ServerResultSchema: () => ServerResultSchema, - ServerTasksCapabilitySchema: () => ServerTasksCapabilitySchema, - SetLevelRequestParamsSchema: () => SetLevelRequestParamsSchema, - SetLevelRequestSchema: () => SetLevelRequestSchema, - SingleSelectEnumSchemaSchema: () => SingleSelectEnumSchemaSchema, - StringSchemaSchema: () => StringSchemaSchema, - SubscribeRequestParamsSchema: () => SubscribeRequestParamsSchema, - SubscribeRequestSchema: () => SubscribeRequestSchema, - SubscriptionFilterSchema: () => SubscriptionFilterSchema, - SubscriptionsAcknowledgedNotificationParamsSchema: () => SubscriptionsAcknowledgedNotificationParamsSchema, - SubscriptionsAcknowledgedNotificationSchema: () => SubscriptionsAcknowledgedNotificationSchema, - SubscriptionsListenRequestParamsSchema: () => SubscriptionsListenRequestParamsSchema, - SubscriptionsListenRequestSchema: () => SubscriptionsListenRequestSchema, - SubscriptionsListenResultMetaSchema: () => SubscriptionsListenResultMetaSchema, - SubscriptionsListenResultSchema: () => SubscriptionsListenResultSchema, - TaskAugmentedRequestParamsSchema: () => auth_CUe6YdwF_TaskAugmentedRequestParamsSchema, - TaskCreationParamsSchema: () => TaskCreationParamsSchema, - TaskMetadataSchema: () => TaskMetadataSchema, - TaskSchema: () => TaskSchema, - TaskStatusNotificationParamsSchema: () => TaskStatusNotificationParamsSchema, - TaskStatusNotificationSchema: () => TaskStatusNotificationSchema, - TaskStatusSchema: () => TaskStatusSchema, - TextContentSchema: () => TextContentSchema, - TextResourceContentsSchema: () => TextResourceContentsSchema, - TitledMultiSelectEnumSchemaSchema: () => TitledMultiSelectEnumSchemaSchema, - TitledSingleSelectEnumSchemaSchema: () => TitledSingleSelectEnumSchemaSchema, - ToolAnnotationsSchema: () => ToolAnnotationsSchema, - ToolChoiceSchema: () => ToolChoiceSchema, - ToolExecutionSchema: () => ToolExecutionSchema, - ToolListChangedNotificationSchema: () => ToolListChangedNotificationSchema, - ToolResultContentSchema: () => ToolResultContentSchema, - ToolSchema: () => ToolSchema, - ToolUseContentSchema: () => ToolUseContentSchema, - UnsubscribeRequestParamsSchema: () => UnsubscribeRequestParamsSchema, - UnsubscribeRequestSchema: () => UnsubscribeRequestSchema, - UntitledMultiSelectEnumSchemaSchema: () => UntitledMultiSelectEnumSchemaSchema, - UntitledSingleSelectEnumSchemaSchema: () => UntitledSingleSelectEnumSchemaSchema -}); - -//#endregion -//#region ../core-internal/src/types/guards.ts -/** -* Validates and parses an unknown value as a JSON-RPC message. -* -* Use this to validate incoming messages in custom transport implementations. -* Throws if the value does not conform to the JSON-RPC message schema. -* -* @param value - The value to validate (typically a parsed JSON object). -* @returns The validated {@linkcode JSONRPCMessage}. -* @throws If validation fails. -*/ -function parseJSONRPCMessage(value) { - return JSONRPCMessageSchema.parse(value); -} -const src_CX2iR2pK_isJSONRPCRequest = (value) => JSONRPCRequestSchema.safeParse(value).success; -const src_CX2iR2pK_isJSONRPCNotification = (value) => JSONRPCNotificationSchema.safeParse(value).success; -/** -* Checks if a value is a valid {@linkcode JSONRPCResultResponse}. -* @param value - The value to check. -* -* @returns True if the value is a valid {@linkcode JSONRPCResultResponse}, false otherwise. -*/ -const src_CX2iR2pK_isJSONRPCResultResponse = (value) => JSONRPCResultResponseSchema.safeParse(value).success; -/** -* Checks if a value is a valid {@linkcode JSONRPCErrorResponse}. -* @param value - The value to check. -* -* @returns True if the value is a valid {@linkcode JSONRPCErrorResponse}, false otherwise. -*/ -const src_CX2iR2pK_isJSONRPCErrorResponse = (value) => JSONRPCErrorResponseSchema.safeParse(value).success; -/** -* Checks if a value is a valid {@linkcode JSONRPCResponse} (either a result or error response). -* @param value - The value to check. -* -* @returns True if the value is a valid {@linkcode JSONRPCResponse}, false otherwise. -*/ -const isJSONRPCResponse = (value) => JSONRPCResponseSchema.safeParse(value).success; -/** -* Checks if a value is a valid {@linkcode CallToolResult}. -* -* This is a consumer-side VALUE check against the neutral model, not a wire -* validator: a raw wire object that additionally carries wire-only members -* (e.g. `resultType`) still passes through the loose index signature. Use a -* transport-level parse to validate raw wire traffic. -* -* @param value - The value to check. -* -* @returns True if the value is a valid {@linkcode CallToolResult}, false otherwise. -*/ -const isCallToolResult = (value) => { - if (typeof value !== "object" || value === null || value.content === void 0) return false; - return CallToolResultSchema.safeParse(value).success; -}; -/** -* Checks whether a value is an input-required result (protocol revision -* 2026-07-28): the multi-round-trip return shape discriminated by -* `resultType: 'input_required'`. -* -* This is a discriminator check, not a full validator — the at-least-one rule -* (`inputRequests` or `requestState`) is enforced by the `inputRequired()` -* builder and re-checked by the server seam for hand-built values. -* -* @param value - The value to check. -* @returns True if the value carries the `input_required` discriminator. -*/ -const isInputRequiredResult = (value) => typeof value === "object" && value !== null && !Array.isArray(value) && value.resultType === "input_required"; -/** -* Checks if a value is a valid {@linkcode TaskAugmentedRequestParams}. -* @param value - The value to check. -* -* @returns True if the value is a valid {@linkcode TaskAugmentedRequestParams}, false otherwise. -* -* @deprecated Recognizes 2025-11-25 task wire vocabulary, which has no SDK -* runtime; kept importable for interoperability only. -*/ -const isTaskAugmentedRequestParams = (value) => TaskAugmentedRequestParamsSchema.safeParse(value).success; -const src_CX2iR2pK_isInitializeRequest = (value) => InitializeRequestSchema.safeParse(value).success; -const isInitializedNotification = (value) => InitializedNotificationSchema.safeParse(value).success; -function assertCompleteRequestPrompt(request) { - if (request.params.ref.type !== "ref/prompt") throw new TypeError(`Expected CompleteRequestPrompt, but got ${request.params.ref.type}`); -} -function assertCompleteRequestResourceTemplate(request) { - if (request.params.ref.type !== "ref/resource") throw new TypeError(`Expected CompleteRequestResourceTemplate, but got ${request.params.ref.type}`); -} - -//#endregion -//#region ../core-internal/src/shared/mcpParamHeaders.ts -/** The fixed prefix every custom-parameter header carries. */ -const MCP_PARAM_HEADER_PREFIX = "Mcp-Param-"; -/** The schema-extension property name a tool's `inputSchema` carries. */ -const X_MCP_HEADER_KEY = "x-mcp-header"; -/** -* RFC 9110 §5.1 `token` syntax (`1*tchar`). Rejects empty, space, control -* characters (including CR/LF), and the listed delimiters. -*/ -const RFC9110_TOKEN = /^[!#$%&'*+\-.^_`|~0-9A-Za-z]+$/; -/** -* JSON Schema `type` values the spec admits on an `x-mcp-header` property. -* -* The spec text names `integer`, `string`, `boolean` and explicitly excludes -* `number`. The published conformance referee at the pinned release ships its -* `http-custom-headers` scenario with two `type: "number"` `x-mcp-header` -* parameters and expects the client to mirror them, so `number` is accepted -* here so that the conformance gate passes; the discrepancy is tracked -* upstream. Everything else (`object`, `array`, `null`, absent) is rejected. -*/ -const PERMITTED_X_MCP_HEADER_TYPES = new Set([ - "string", - "integer", - "boolean", - "number" -]); -/** -* Scan a tool's JSON-serialized `inputSchema` for `x-mcp-header` declarations -* and validate every constraint the spec places on them. Returns either the -* collected declarations (possibly empty) or the first violated constraint. -* -* The walk descends through `properties` at any depth (the spec's "any nesting -* depth" clause). The static-reachability MUST is enforced as a structural -* sweep: every position the chain MUST NOT pass through (`items`/ -* `additionalProperties`, `oneOf`/`anyOf`/`allOf`/`not`, `if`/`then`/`else`, -* `$defs`, `$ref` targets within `$defs`) is visited too, and an -* `x-mcp-header` found anywhere on that path invalidates the schema — "an -* annotation anywhere else makes the tool definition invalid". -*/ -function src_CX2iR2pK_scanXMcpHeaderDeclarations(inputSchema) { - const declarations = []; - const seenLower = /* @__PURE__ */ new Map(); - const visit = (node, path, reachable) => { - if (node === null || typeof node !== "object") return void 0; - const schema = node; - if (X_MCP_HEADER_KEY in schema) { - if (!reachable || path.length === 0) return `${pathName(path)}: x-mcp-header is only permitted on properties statically reachable via a chain of 'properties' keys (not under items, additionalProperties, oneOf/anyOf/allOf/not, if/then/else, or $ref)`; - const raw = schema[X_MCP_HEADER_KEY]; - if (typeof raw !== "string" || raw.length === 0) return `${pathName(path)}: x-mcp-header MUST be a non-empty string`; - if (!RFC9110_TOKEN.test(raw)) return `${pathName(path)}: x-mcp-header '${raw}' is not a valid RFC 9110 token (no spaces, control characters or HTTP delimiters)`; - const type = typeof schema.type === "string" ? schema.type : void 0; - if (type === void 0 || !PERMITTED_X_MCP_HEADER_TYPES.has(type)) return `${pathName(path)}: x-mcp-header is only permitted on primitive-typed properties (string, integer, boolean); got ${type ?? ""}`; - const lower = raw.toLowerCase(); - const prior = seenLower.get(lower); - if (prior !== void 0) return `x-mcp-header '${raw}' is not case-insensitively unique (also declared as '${prior}')`; - seenLower.set(lower, raw); - declarations.push({ - path, - headerName: raw, - type - }); - } - const properties = schema.properties; - if (properties !== null && typeof properties === "object") for (const [key, child] of Object.entries(properties)) { - const fault$1 = visit(child, [...path, key], reachable); - if (fault$1 !== void 0) return fault$1; - } - for (const k of NON_REACHABLE_SUBSCHEMA_KEYWORDS) { - const sub = schema[k]; - if (sub === void 0) continue; - const branches = Array.isArray(sub) ? sub : sub !== null && typeof sub === "object" && OBJECT_VALUED_SUBSCHEMA_KEYWORDS.has(k) ? Object.values(sub) : [sub]; - for (const branch of branches) { - const fault$1 = visit(branch, [...path, `<${k}>`], false); - if (fault$1 !== void 0) return fault$1; - } - } - }; - const fault = visit(inputSchema, [], true); - return fault === void 0 ? { - valid: true, - declarations - } : { - valid: false, - reason: fault - }; -} -/** -* JSON Schema keywords whose subschemas the SEP-2243 static-reachability -* constraint excludes from the `properties`-only chain. An `x-mcp-header` -* found under any of these invalidates the tool definition. -*/ -const NON_REACHABLE_SUBSCHEMA_KEYWORDS = [ - "items", - "prefixItems", - "contains", - "additionalProperties", - "unevaluatedProperties", - "unevaluatedItems", - "propertyNames", - "patternProperties", - "dependentSchemas", - "oneOf", - "anyOf", - "allOf", - "not", - "if", - "then", - "else", - "$defs", - "definitions" -]; -/** -* Subschema-carrying keywords whose value is a `name → subschema` object -* (not a single subschema or array of subschemas). The visit branches over -* `Object.values()` for these. -*/ -const OBJECT_VALUED_SUBSCHEMA_KEYWORDS = new Set([ - "patternProperties", - "dependentSchemas", - "$defs", - "definitions" -]); -function pathName(path) { - return path.length === 0 ? "" : path.join("."); -} -const BASE64_SENTINEL_PREFIX = "=?base64?"; -const BASE64_SENTINEL_SUFFIX = "?="; -const BASE64_CANONICAL = /^(?:[A-Za-z0-9+/]{4})*(?:[A-Za-z0-9+/]{2}==|[A-Za-z0-9+/]{3}=)?$/; -const CANONICAL_DECIMAL = /^-?\d+(\.\d+)?$/; -/** -* Convert a primitive argument value to its string representation per the -* spec's type-conversion rules: strings pass through, integers and numbers -* become their decimal string, booleans become lowercase `'true'` / `'false'`. -* Non-finite numbers and integers outside the safe range are refused (the -* caller treats `undefined` as "do not emit a header for this value"). -*/ -function mcpParamPrimitiveToString(value) { - if (typeof value === "string") return value; - if (typeof value === "boolean") return value ? "true" : "false"; - if (typeof value === "number") { - if (!Number.isFinite(value)) return void 0; - if (Number.isInteger(value) && !Number.isSafeInteger(value)) return void 0; - return String(value); - } -} -function base64ToUtf8(b64) { - const bin = atob(b64); - const bytes = new Uint8Array(bin.length); - for (let i = 0; i < bin.length; i++) bytes[i] = bin.codePointAt(i); - return new TextDecoder("utf-8", { fatal: true }).decode(bytes); -} -/** -* Decode an `Mcp-Param-*` header value: when it carries the Base64 sentinel, -* the payload is decoded as UTF-8; otherwise the value is returned as-is. -* Returns `undefined` when the sentinel is present but the payload is not -* canonical Base64 (or not valid UTF-8) — the spec requires servers to reject -* such values. -*/ -function decodeMcpParamValue(value) { - if (!(value.startsWith(BASE64_SENTINEL_PREFIX) && value.endsWith(BASE64_SENTINEL_SUFFIX))) return value; - const b64 = value.slice(9, value.length - 2); - if (!BASE64_CANONICAL.test(b64)) return void 0; - try { - return base64ToUtf8(b64); - } catch { - return; - } -} -function valueAtPath(root, path) { - let node = root; - for (const key of path) { - if (node === null || typeof node !== "object") return void 0; - node = node[key]; - } - return node; -} -/** -* The header/body comparison the server performs at tool-resolution time. -* -* For each `x-mcp-header` declaration on the named tool: when the body -* `arguments` carries a value, the matching `Mcp-Param-{Name}` header MUST be -* present and decode to an equal value; when the body value is `null` or -* absent the server MUST NOT expect the header (a present header is ignored). -* A sentinel-carrying header whose payload is not canonical Base64 / valid -* UTF-8 is rejected as invalid characters. -* -* Integer-typed declarations are compared numerically (the spec's SHOULD — -* `42.0` and `42` are equal); everything else is compared as decoded strings. -* -* Returns `undefined` when every check passes, or an -* {@linkcode InboundLadderRejection} carrying the same `-32020` -* (`HeaderMismatch`) shape the inbound classifier emits for the -* standard-header cross-checks — `400 Bad Request` with the disagreeing pair -* in `data.mismatch`. -*/ -function src_CX2iR2pK_validateMcpParamHeaders(declarations, args, headers) { - for (const decl of declarations) { - const headerKey = `${MCP_PARAM_HEADER_PREFIX}${decl.headerName}`; - const headerValue = headers.get(headerKey); - const bodyRaw = valueAtPath(args, decl.path); - if (bodyRaw === void 0 || bodyRaw === null) continue; - const bodyString = mcpParamPrimitiveToString(bodyRaw); - if (bodyString === void 0) continue; - if (headerValue === null) return paramHeaderMismatchRejection("param-header-missing", headerKey, `the body carries ${pathName(decl.path)}=${JSON.stringify(bodyRaw)} but the ${headerKey} header is absent`); - const decoded = decodeMcpParamValue(headerValue); - if (decoded === void 0) return paramHeaderMismatchRejection("param-header-invalid-encoding", headerKey, `the ${headerKey} header carries an invalid Base64 sentinel value`); - if (!((decl.type === "integer" || decl.type === "number") && CANONICAL_DECIMAL.test(decoded) && typeof bodyRaw === "number" ? Number(decoded) === bodyRaw : decoded === bodyString)) return paramHeaderMismatchRejection("param-header-mismatch", headerKey, `the ${headerKey} header decodes to ${JSON.stringify(decoded)} but the body carries ${pathName(decl.path)}=${JSON.stringify(bodyRaw)}`); - } -} -/** -* Build the `-32020` (`HeaderMismatch`) rejection for an `Mcp-Param-*` -* disagreement. Same shape as the inbound classifier's standard-header -* cross-check mismatch (HTTP `400`, `data.mismatch` naming the disagreeing -* pair, `settled: true`); only the rung differs because this check runs at the -* pre-dispatch step against a known tool's schema rather than at the edge. -*/ -function paramHeaderMismatchRejection(cell, header, body) { - return { - kind: "reject", - rung: "param-header-validation", - cell, - httpStatus: 400, - code: HEADER_MISMATCH_ERROR_CODE, - message: `Bad Request: the request headers and body disagree: ${body}`, - data: { mismatch: { - header, - body - } }, - settled: true - }; -} - -//#endregion -//#region ../core-internal/src/shared/inboundClassification.ts -/** -* Inbound HTTP request classification and the inbound validation ladder -* (protocol revision 2026-07-28). -* -* `classifyInboundRequest` is the body-primary era predicate for an HTTP -* entry that serves both protocol eras on one endpoint. It is evaluated -* exactly once, at the entry boundary, on the already-parsed request body: -* -* - `initialize` is a legacy-era request by definition (the modern era has no -* `initialize` handshake) — unless it carries a valid envelope claim naming -* a modern revision, in which case the claim wins and the request is -* classified like any other enveloped request (the modern era then answers -* it with method-not-found, exactly like every other method it does not -* define). -* - A request whose `params._meta` carries the reserved protocol-version key -* claims the per-request envelope mechanism and classifies into the era the -* named revision belongs to (a malformed envelope behind a present claim is -* a validation error, never a silent fall back to legacy handling). -* - A request without a claim is legacy-era traffic. -* - The `MCP-Protocol-Version` header is a cross-check only: it never -* upgrades or downgrades a body-derived classification, and a disagreement -* between header and body is an explicit ladder outcome. -* - Notifications carry no envelope claim of their own under the current -* spec, so for notification POSTs without a body claim the modern header is -* determinative; the `Mcp-Method` header is validated against the body when -* the message classifies modern and is never enforced on legacy traffic. -* A notification that does carry a claim is treated body-primary like a -* request, and a malformed claim is rejected the same way a request's -* malformed claim is — never silently resolved against the header. -* The notification-POST header cross-checks here are an SDK-defensive -* posture, not a spec requirement: the spec leaves header rules for posted -* notifications undefined (core client notifications do not occur over -* Streamable HTTP); applying the request rules symmetrically is what an -* ecosystem custom-notification POST expects, and the −32020 cells stay -* passing for them. -* - `GET`/`DELETE` (and any other non-`POST` method) are body-less 2025-era -* session operations: the modern era is `POST`-only, so they are routed to -* legacy serving when it is configured and rejected otherwise. -* - Array (batch) bodies are classified element-wise: an array containing a -* modern-claiming or invalid element is rejected, an all-legacy array is -* legacy traffic unchanged, and a single-element array is still an array. -* -* The classifier returns plain values (it never throws and never touches a -* transport): a routing outcome (`legacy`/`modern`) or a ladder rejection -* carrying the JSON-RPC error to emit and the HTTP status to emit it with. -* Legacy routing outcomes deliberately carry NO `MessageClassification` — -* legacy and hand-wired traffic is never classified, which keeps its -* dispatch behavior byte-identical to today's. -* -* Error codes for the modern-path rejection cells follow the published -* conformance suite (and the spec text it asserts): -* -* - A header/body cross-check mismatch (the `MCP-Protocol-Version` header -* disagreeing with the body, or the `Mcp-Method` header disagreeing with the -* body method) is rejected with `-32020` (`HeaderMismatch`) on HTTP 400. -* - A request whose protocol-version header names a modern revision but whose -* body carries no `_meta` envelope claim — including an envelope present but -* missing the required protocol-version key — is rejected with `-32602` -* (invalid params) naming the missing key(s), on HTTP 400. -* -* Should a future spec revision or conformance release change these -* assignments, the affected cells are re-derived against that release; the -* `settled` flag on {@linkcode InboundLadderRejection} stays available to mark -* a cell provisional again while such a change is in flight. -*/ -/** -* The error code emitted for header/body cross-check mismatches: the -* `MCP-Protocol-Version` header disagreeing with the body's envelope claim (or -* with the body's classification), and the `Mcp-Method` header disagreeing -* with the body method. -* -* `-32020` is the draft schema's `HEADER_MISMATCH` constant (the SEP-2243 -* `HeaderMismatch` code; the spec requires HTTP 400 for it), as also asserted -* by the published conformance suite for header-validation failures. It has no -* {@linkcode ProtocolErrorCode} member because it is not part of the 2025-era -* wire vocabulary; the validation ladder is its only emitter. -*/ -const HEADER_MISMATCH_ERROR_CODE = -32020; -/** -* The inbound validation ladder, expressed as data rather than control flow. -* -* The edge rungs are evaluated by {@linkcode classifyInboundRequest}; the -* dispatch rungs are evaluated by the protocol layer once the classified -* message is injected into a per-request server instance (the era registry -* gate, the envelope requiredness check, and per-method params validation). -* The client-capability rung is evaluated by the HTTP entry itself, -* pre-dispatch, on the validated envelope the classifier produced — see that -* rung's rationale for the ordering caveat. The order is the precedence: a -* request that fails several rungs is answered by the earliest one. -*/ -const INBOUND_VALIDATION_LADDER = [ - { - 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: [src_CX2iR2pK_ProtocolErrorCode.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: [HEADER_MISMATCH_ERROR_CODE, src_CX2iR2pK_ProtocolErrorCode.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: [src_CX2iR2pK_ProtocolErrorCode.InvalidParams], - conformance: ["server-stateless"], - rationale: "A present envelope claim with a malformed envelope — and a missing envelope on a request whose protocol-version header names a modern revision — 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: [src_CX2iR2pK_ProtocolErrorCode.MethodNotFound], - conformance: ["server-stateless"], - rationale: "Method existence outranks parameter validity: a method absent from the negotiated revision’s 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: [src_CX2iR2pK_ProtocolErrorCode.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: [HEADER_MISMATCH_ERROR_CODE], - conformance: ["http-header-validation"], - rationale: "SEP-2243 standard `Mcp-Method` / `Mcp-Name` headers — presence, sentinel decoding, and `Mcp-Name` ↔ body cross-check — are validated by the HTTP entry on a modern-classified request after the supported-revision gate and before dispatch. The classifier’s 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–6) are consulted." - }, - { - rung: "client-capabilities", - order: 8, - evaluatedAt: "pre-dispatch", - codes: [src_CX2iR2pK_ProtocolErrorCode.MissingRequiredClientCapability], - conformance: ["server-stateless"], - rationale: "The capability requirement is checked by the HTTP entry, pre-dispatch, against the validated envelope the classifier produced — 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: [HEADER_MISMATCH_ERROR_CODE], - conformance: ["http-custom-header-server-validation"], - rationale: "SEP-2243 `Mcp-Param-*` headers are validated against the named tool’s `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." - } -]; -/** -* HTTP status for ladder-originated JSON-RPC error codes. -* -* Keyed on origin, not on the bare code: this table only applies to errors -* the ladder (or a pre-handler protocol gate) produced. Errors produced by -* request handlers — whatever their code — stay in-band on HTTP 200, and are -* never mapped to an HTTP status by this table; in particular `-32603` and -* domain-specific codes never become a blanket 500. The single exception is -* `MissingRequiredClientCapability` (-32021) — see -* {@linkcode httpStatusForErrorCode}. -* -* `-32602` (invalid params) deliberately has NO entry: the only invalid-params -* rejection that maps to HTTP 400 is the classifier's own envelope rung -* short-circuit, which carries its HTTP status directly. A dispatch- or -* handler-produced invalid-params error is always in-band. -*/ -const src_CX2iR2pK_LADDER_ERROR_HTTP_STATUS = { - [src_CX2iR2pK_ProtocolErrorCode.ParseError]: 400, - [src_CX2iR2pK_ProtocolErrorCode.InvalidRequest]: 400, - [src_CX2iR2pK_ProtocolErrorCode.MethodNotFound]: 404, - [src_CX2iR2pK_ProtocolErrorCode.UnsupportedProtocolVersion]: 400, - [src_CX2iR2pK_ProtocolErrorCode.MissingRequiredClientCapability]: 400, - [HEADER_MISMATCH_ERROR_CODE]: 400 -}; -/** -* The HTTP status to answer a JSON-RPC error with, keyed on the error's -* origin. `in-band` errors (anything produced by a request handler) are -* HTTP 200 — the JSON-RPC error response is the payload, not an HTTP -* failure — with ONE exception: `MissingRequiredClientCapability` (-32021), -* whose 400 the spec mandates on the error itself with no origin condition, -* and which the SDK genuinely produces after dispatch (the `input_required` -* capability gate). A handler relaying some downstream peer's `-32020`/`-32022` -* is NOT that peer's spec error and stays in-band like every other handler -* code. `ladder` errors map through {@linkcode LADDER_ERROR_HTTP_STATUS}. -* -* The per-request transport intentionally does NOT delegate to this function: -* its `?? 400` ladder fallback is only correct for entry-gate codes known to -* the table, and would wrongly map dispatch-window errors outside it (a -* window `-32602` must stay in-band on 200). The transport indexes the table -* directly; keep the two in agreement when editing either. -*/ -function src_CX2iR2pK_httpStatusForErrorCode(code, origin) { - if (origin === "in-band") return code === src_CX2iR2pK_ProtocolErrorCode.MissingRequiredClientCapability ? 400 : 200; - return src_CX2iR2pK_LADDER_ERROR_HTTP_STATUS[code] ?? 400; -} -function src_CX2iR2pK_rejection(rung, cell, httpStatus, error, settled) { - return { - kind: "reject", - rung, - cell, - httpStatus, - code: error.code, - message: error.message, - ...error.data !== void 0 && { data: error.data }, - settled - }; -} -function crossCheckMismatch(cell, header, body, rung = "era-classification") { - return src_CX2iR2pK_rejection(rung, cell, 400, new src_CX2iR2pK_ProtocolError(HEADER_MISMATCH_ERROR_CODE, `Bad Request: the request headers and body disagree: ${body}`, { mismatch: { - header, - body - } }), true); -} -/** -* The methods whose body carries a `params.name` / `params.uri` value the -* `Mcp-Name` header must mirror, and which body field supplies it (SEP-2243 -* § Standard Request Headers, `Required For` column). -*/ -const MCP_NAME_HEADER_SOURCE = (/* unused pure expression or super */ null && ({ - "tools/call": "name", - "prompts/get": "name", - "resources/read": "uri" -})); -/** Strip RFC 9110 optional whitespace (SP / HTAB) around a field value in linear time. */ -function stripHttpOws(value) { - let start = 0; - while (start < value.length) { - const code = value.codePointAt(start); - if (code !== 9 && code !== 32) break; - start += 1; - } - let end = value.length; - while (end > start) { - const code = value.codePointAt(end - 1); - if (code !== 9 && code !== 32) break; - end -= 1; - } - return start === 0 && end === value.length ? value : value.slice(start, end); -} -/** -* SEP-2243 standard-header server-side validation, evaluated by the HTTP -* entry on a modern-classified request immediately after -* {@linkcode classifyInboundRequest} returns a modern route. -* -* Returns the `-32020` (`HeaderMismatch`) ladder rejection (HTTP `400`, -* `standard-header-validation` rung — the same shape -* {@linkcode classifyInboundRequest} already emits on the edge -* `era-classification` rung for the `MCP-Protocol-Version` and -* `Mcp-Method` *mismatch* cells) when: -* -* - the required `Mcp-Method` header is absent; -* - the required `Mcp-Name` header is absent on a `tools/call`, -* `prompts/get`, or `resources/read` request whose body carries the -* `params.name` / `params.uri` value the header mirrors; -* - the `Mcp-Name` header carries an invalid `=?base64?…?=` sentinel; or -* - the (decoded) `Mcp-Name` value disagrees with the body's -* `params.name` / `params.uri`. -* -* Returns `undefined` (pass) for notifications (the spec table reads -* "All requests"), for methods that have no `Mcp-Name` source, and when the -* headers agree with the body. Never enforced on legacy traffic — the entry -* only calls this on a modern route. -* -* Kept separate from {@linkcode classifyInboundRequest} so that a body-only -* call to the classifier (no headers passed) keeps routing a modern request -* unchanged: the classifier remains a pure body-primary router, and this -* function is the presence/`Mcp-Name` half of the standard-header rung the -* entry layers on top. -*/ -function src_CX2iR2pK_validateStandardRequestHeaders(request, route) { - if (route.messageKind !== "request") return; - const method = route.message.method; - if (request.mcpMethodHeader === void 0) return crossCheckMismatch("method-header-missing", "(missing)", `the body names method ${method} but the required Mcp-Method header is absent`, "standard-header-validation"); - const sourceField = Object.hasOwn(MCP_NAME_HEADER_SOURCE, method) ? MCP_NAME_HEADER_SOURCE[method] : void 0; - if (sourceField === void 0) return; - const sourceValue = route.message.params?.[sourceField]; - const bodyValue = typeof sourceValue === "string" ? sourceValue : void 0; - if (request.mcpNameHeader === void 0) { - if (bodyValue === void 0) return; - return crossCheckMismatch("name-header-missing", "(missing)", `the body carries params.${sourceField}="${bodyValue}" but the required Mcp-Name header is absent`, "standard-header-validation"); - } - const normalizedNameHeader = stripHttpOws(request.mcpNameHeader); - const decoded = decodeMcpParamValue(normalizedNameHeader); - if (decoded === void 0) return crossCheckMismatch("name-header-invalid-encoding", normalizedNameHeader, "the Mcp-Name header carries an invalid Base64 sentinel value", "standard-header-validation"); - if (bodyValue !== void 0 && decoded !== bodyValue) return crossCheckMismatch("name-header-mismatch", normalizedNameHeader, `the body carries params.${sourceField}="${bodyValue}" but the Mcp-Name header names "${decoded}"`, "standard-header-validation"); -} -function isPlainObject$2(value) { - return value !== null && typeof value === "object" && !Array.isArray(value); -} -function classificationForClaim(claimedVersion) { - if (claimedVersion === void 0) return { era: "modern" }; - return { - era: isModernProtocolVersion(claimedVersion) ? "modern" : "legacy", - revision: claimedVersion - }; -} -/** -* Whether a request's params carry a per-request envelope claim that is both -* well-formed and names a modern protocol revision. -* -* Used by the `initialize` precedence rule: only such a claim overrides the -* `initialize` ⇒ legacy-handshake classification — a request carrying a valid -* modern envelope is a modern request regardless of its method name, and the -* modern era then answers `initialize` exactly like any other method it does -* not define (method-not-found). A malformed claim, or one naming a pre-2026 -* revision, keeps the legacy-handshake routing unchanged. -* -* Exported on the core internal barrel for the stdio serving entry, which -* applies the same precedence rule to a connection's opening message; not -* public API. -*/ -function src_CX2iR2pK_carriesValidModernEnvelopeClaim(params) { - if (!src_CX2iR2pK_hasEnvelopeClaim(params)) return false; - const claimedVersion = src_CX2iR2pK_envelopeClaimVersion(params); - if (claimedVersion === void 0 || !isModernProtocolVersion(claimedVersion)) return false; - const meta = src_CX2iR2pK_requestMetaOf(params); - return meta !== void 0 && src_CX2iR2pK_validateEnvelopeMeta(meta).length === 0; -} -function classifyBatch(body) { - if (body.length === 0) return src_CX2iR2pK_rejection("jsonrpc-shape", "empty-batch", 400, new src_CX2iR2pK_ProtocolError(src_CX2iR2pK_ProtocolErrorCode.InvalidRequest, "Bad Request: empty JSON-RPC batch"), true); - for (const element of body) { - if (src_CX2iR2pK_hasEnvelopeClaim(isPlainObject$2(element) ? element["params"] : void 0)) return src_CX2iR2pK_rejection("jsonrpc-shape", "batch-with-modern-element", 400, new src_CX2iR2pK_ProtocolError(src_CX2iR2pK_ProtocolErrorCode.InvalidRequest, "Bad Request: JSON-RPC batches may not contain requests for protocol revision 2026-07-28 or later"), true); - if (!(src_CX2iR2pK_isJSONRPCRequest(element) || src_CX2iR2pK_isJSONRPCNotification(element) || src_CX2iR2pK_isJSONRPCResultResponse(element) || src_CX2iR2pK_isJSONRPCErrorResponse(element))) return src_CX2iR2pK_rejection("jsonrpc-shape", "batch-with-invalid-element", 400, new src_CX2iR2pK_ProtocolError(src_CX2iR2pK_ProtocolErrorCode.InvalidRequest, "Bad Request: JSON-RPC batch contains an invalid message"), true); - } - return { - kind: "legacy", - reason: "batch" - }; -} -function classifyRequestBody(request, body) { - const params = body.params; - const method = body.method; - const headerVersion = request.protocolVersionHeader; - const headerNamesModern = headerVersion !== void 0 && isModernProtocolVersion(headerVersion); - if (method === "initialize" && !src_CX2iR2pK_carriesValidModernEnvelopeClaim(params)) { - if (headerNamesModern) return crossCheckMismatch("initialize-with-modern-header", headerVersion, "an initialize request (legacy handshake) was sent with a modern MCP-Protocol-Version header"); - const requestedVersion = isPlainObject$2(params) && typeof params["protocolVersion"] === "string" ? params["protocolVersion"] : void 0; - return { - kind: "legacy", - reason: "initialize", - ...requestedVersion !== void 0 && { requestedVersion } - }; - } - if (src_CX2iR2pK_hasEnvelopeClaim(params)) { - const meta = src_CX2iR2pK_requestMetaOf(params); - const firstIssue = (meta === void 0 ? [] : src_CX2iR2pK_validateEnvelopeMeta(meta))[0]; - if (firstIssue !== void 0) return src_CX2iR2pK_rejection("envelope", "envelope-invalid", 400, new src_CX2iR2pK_ProtocolError(src_CX2iR2pK_ProtocolErrorCode.InvalidParams, `Invalid _meta envelope for protocol revision 2026-07-28: ${firstIssue.key}: ${firstIssue.problem}`, { envelope: firstIssue }), true); - const claimedVersion = src_CX2iR2pK_envelopeClaimVersion(params); - if (headerVersion !== void 0 && claimedVersion !== void 0 && headerVersion !== claimedVersion) return crossCheckMismatch("header-body-version-mismatch", headerVersion, `the body envelope names protocol version ${claimedVersion} but the MCP-Protocol-Version header names ${headerVersion}`); - if (request.mcpMethodHeader !== void 0 && request.mcpMethodHeader !== method) return crossCheckMismatch("method-header-mismatch", request.mcpMethodHeader, `the body names method ${method} but the Mcp-Method header names ${request.mcpMethodHeader}`); - return { - kind: "modern", - messageKind: "request", - message: body, - classification: classificationForClaim(claimedVersion) - }; - } - if (headerNamesModern) { - const meta = src_CX2iR2pK_requestMetaOf(params); - const missingFromEnvelope = src_CX2iR2pK_validateEnvelopeMeta(meta ?? {}).filter((issue) => issue.problem === "missing").map((issue) => issue.key); - const missing = meta === void 0 ? ["_meta"] : missingFromEnvelope.length > 0 ? missingFromEnvelope : [PROTOCOL_VERSION_META_KEY]; - return src_CX2iR2pK_rejection("envelope", "modern-header-without-claim", 400, new src_CX2iR2pK_ProtocolError(src_CX2iR2pK_ProtocolErrorCode.InvalidParams, `Invalid params: the MCP-Protocol-Version header names protocol revision ${headerVersion}, but the request is missing the required per-request envelope key(s): ${missing.join(", ")}`, { envelope: { missing } }), true); - } - return { - kind: "legacy", - reason: "no-claim", - ...headerVersion !== void 0 && { requestedVersion: headerVersion } - }; -} -function classifyNotificationBody(request, body) { - const params = body.params; - const method = body.method; - const headerVersion = request.protocolVersionHeader; - const headerNamesModern = headerVersion !== void 0 && isModernProtocolVersion(headerVersion); - if (src_CX2iR2pK_hasEnvelopeClaim(params)) { - const claimedVersion = src_CX2iR2pK_envelopeClaimVersion(params); - if (claimedVersion === void 0) { - const meta = src_CX2iR2pK_requestMetaOf(params); - const claimIssue = (meta === void 0 ? [] : src_CX2iR2pK_validateEnvelopeMeta(meta)).find((issue) => issue.key === PROTOCOL_VERSION_META_KEY) ?? { - key: PROTOCOL_VERSION_META_KEY, - problem: "expected a protocol version string" - }; - return src_CX2iR2pK_rejection("envelope", "notification-envelope-invalid", 400, new src_CX2iR2pK_ProtocolError(src_CX2iR2pK_ProtocolErrorCode.InvalidParams, `Invalid _meta envelope for protocol revision 2026-07-28: ${claimIssue.key}: ${claimIssue.problem}`, { envelope: claimIssue }), true); - } - if (headerVersion !== void 0 && headerVersion !== claimedVersion) return crossCheckMismatch("notification-header-body-version-mismatch", headerVersion, `the notification envelope names protocol version ${claimedVersion} but the MCP-Protocol-Version header names ${headerVersion}`); - const classification = classificationForClaim(claimedVersion); - if (classification.era === "modern" && request.mcpMethodHeader !== void 0 && request.mcpMethodHeader !== method) return crossCheckMismatch("notification-method-header-mismatch", request.mcpMethodHeader, `the notification body names method ${method} but the Mcp-Method header names ${request.mcpMethodHeader}`); - return { - kind: "modern", - messageKind: "notification", - message: body, - classification - }; - } - if (headerNamesModern) { - if (request.mcpMethodHeader !== void 0 && request.mcpMethodHeader !== method) return crossCheckMismatch("notification-method-header-mismatch", request.mcpMethodHeader, `the notification body names method ${method} but the Mcp-Method header names ${request.mcpMethodHeader}`); - return { - kind: "modern", - messageKind: "notification", - message: body, - classification: { - era: "modern", - revision: headerVersion - } - }; - } - return { - kind: "legacy", - reason: "notification", - ...headerVersion !== void 0 && { requestedVersion: headerVersion } - }; -} -/** -* Classifies one inbound HTTP request for dual-era serving. -* -* The body-primary predicate, evaluated once at the entry boundary: see the -* module documentation for the rules. Returns a routing outcome (`legacy` or -* `modern`) or a ladder rejection; it never throws. -*/ -function src_CX2iR2pK_classifyInboundRequest(request) { - request = { - ...request, - ...request.protocolVersionHeader !== void 0 && { protocolVersionHeader: stripHttpOws(request.protocolVersionHeader) }, - ...request.mcpMethodHeader !== void 0 && { mcpMethodHeader: stripHttpOws(request.mcpMethodHeader) }, - ...request.mcpNameHeader !== void 0 && { mcpNameHeader: stripHttpOws(request.mcpNameHeader) } - }; - if (request.httpMethod.toUpperCase() !== "POST") return { - kind: "legacy", - reason: "http-method" - }; - const body = request.body; - if (Array.isArray(body)) return classifyBatch(body); - if (src_CX2iR2pK_isJSONRPCResultResponse(body) || src_CX2iR2pK_isJSONRPCErrorResponse(body)) return { - kind: "legacy", - reason: "response" - }; - if (isPlainObject$2(body) && src_CX2iR2pK_isJSONRPCRequest(body)) return classifyRequestBody(request, body); - if (isPlainObject$2(body) && src_CX2iR2pK_isJSONRPCNotification(body)) return classifyNotificationBody(request, body); - return src_CX2iR2pK_rejection("jsonrpc-shape", "invalid-json-rpc-body", 400, new src_CX2iR2pK_ProtocolError(src_CX2iR2pK_ProtocolErrorCode.InvalidRequest, "Bad Request: the request body is not a valid JSON-RPC message"), true); -} -/** -* The rejection a modern-only endpoint (no legacy serving configured) -* answers a legacy-classified request with. -* -* - Envelope-less requests (including `initialize`) are answered with the -* unsupported-protocol-version error carrying the endpoint's supported -* versions and echoing the version the request named (when it named one — -* `requested` is omitted rather than fabricated when the request named no -* version at all), so a legacy client can discover what the endpoint serves -* from the error alone. -* - Posted responses and batch arrays are invalid requests on the modern era. -* - Non-`POST` methods are not allowed. -* - Legacy-classified notifications return `undefined`: the caller answers -* 202 with no body and does not dispatch the notification (accept-and-drop). -*/ -function src_CX2iR2pK_modernOnlyStrictRejection(route, supportedVersions) { - switch (route.reason) { - case "http-method": return src_CX2iR2pK_rejection("http-method", "modern-only-method-not-allowed", 405, new src_CX2iR2pK_ProtocolError(-32e3, "Method not allowed."), true); - case "batch": return src_CX2iR2pK_rejection("jsonrpc-shape", "modern-only-batch-not-supported", 400, new src_CX2iR2pK_ProtocolError(src_CX2iR2pK_ProtocolErrorCode.InvalidRequest, "Bad Request: JSON-RPC batches are not supported by this endpoint"), true); - case "response": return src_CX2iR2pK_rejection("jsonrpc-shape", "modern-only-response-post", 400, new src_CX2iR2pK_ProtocolError(src_CX2iR2pK_ProtocolErrorCode.InvalidRequest, "Bad Request: JSON-RPC responses cannot be posted to this endpoint"), true); - case "notification": return; - case "initialize": - case "no-claim": { - const requested = route.requestedVersion; - return src_CX2iR2pK_rejection("era-classification", "modern-only-missing-envelope", 400, requested === void 0 ? new src_CX2iR2pK_ProtocolError(src_CX2iR2pK_ProtocolErrorCode.UnsupportedProtocolVersion, "Unsupported protocol version: the request did not name a protocol version", { supported: [...supportedVersions] }) : new src_CX2iR2pK_UnsupportedProtocolVersionError({ - supported: [...supportedVersions], - requested - }), true); - } - } -} - -//#endregion -//#region ../core-internal/src/util/schema.ts -/** -* Internal Zod schema utilities for protocol handling. -* These are used internally by the SDK for protocol message validation. -*/ -/** -* Parses data against a Zod schema (synchronous). -* Returns a discriminated union with success/error. -*/ -function parseSchema(schema, data) { - return parse_safeParse(schema, data); -} -/** -* Union of the declared shape keys across several Zod object schemas. -*/ -function shapeKeys(schemas) { - return new Set(schemas.flatMap((schema) => Object.keys(schema.shape))); -} - -//#endregion -//#region ../core-internal/src/util/standardSchema.ts -/** -* Standard Schema utilities for user-provided schemas. -* Supports Zod v4, Valibot, ArkType, and other Standard Schema implementations. -* @see https://standardschema.dev -*/ -function isStandardSchema(schema) { - if (schema == null) return false; - const schemaType = typeof schema; - if (schemaType !== "object" && schemaType !== "function") return false; - if (!("~standard" in schema)) return false; - return typeof schema["~standard"]?.validate === "function"; -} -let warnedZodFallback = false; -/** JSON Schema draft targeted by every conversion; shared so pattern references above stay in lockstep. */ -const JSON_SCHEMA_CONVERSION_TARGET = "draft-2020-12"; -/** -* Converts a StandardSchema to JSON Schema for use as an MCP tool/prompt schema. -* -* MCP requires `type: "object"` at the root of tool `inputSchema` and prompt -* argument schemas; `outputSchema` may have any JSON Schema root (SEP-2106). -* Zod's discriminated unions emit `{oneOf: [...]}` without a top-level `type`, -* so for `io: 'input'` this function defaults `type` to `"object"` when absent -* and throws on an explicit non-object `type` (e.g. `z.string()`). For -* `io: 'output'` a non-object root is returned as-is; the `"object"` default is -* applied only when the root is provably object-shaped. -*/ -function standardSchemaToJsonSchema(schema, io = "input") { - const std = schema["~standard"]; - let result; - if (std.jsonSchema) result = std.jsonSchema[io]({ target: JSON_SCHEMA_CONVERSION_TARGET }); - else if (std.vendor === "zod") { - if (!("_zod" in schema)) 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()."); - if (!warnedZodFallback) { - warnedZodFallback = true; - 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."); - } - result = toJSONSchema(schema, { - target: JSON_SCHEMA_CONVERSION_TARGET, - io - }); - } else throw new Error(`Schema library "${std.vendor}" does not implement StandardJSONSchemaV1 (\`~standard.jsonSchema\`). Upgrade to a version that does, or wrap your JSON Schema with fromJsonSchema().`); - if (io === "output") { - if (result.type !== void 0) return result; - return isProvablyObjectShapedRoot(result) ? { - type: "object", - ...result - } : result; - } - if (result.type !== void 0 && result.type !== "object") throw new Error(`MCP tool and prompt schemas must describe objects (got type: ${JSON.stringify(result.type)}). Wrap your schema in z.object({...}) or equivalent.`); - return { - type: "object", - ...result - }; -} -/** -* A typeless JSON Schema root is "provably object-shaped" when either it carries object keywords -* directly (`properties`/`patternProperties`/`additionalProperties`/`required`), or it is a -* composition (`oneOf`/`anyOf`/`allOf`) whose every member is itself `type:'object'` or recursively -* provably object-shaped (e.g. a nested `discriminatedUnion`). `$ref` is not followed. Used to -* decide whether stamping `type:'object'` is safe (redundant-but-valid) versus self-contradictory. -*/ -function isProvablyObjectShapedRoot(schema) { - if ("properties" in schema || "patternProperties" in schema || "additionalProperties" in schema || "required" in schema) return true; - for (const key of [ - "oneOf", - "anyOf", - "allOf" - ]) { - const members = schema[key]; - if (Array.isArray(members) && members.length > 0) return members.every((m) => m !== null && typeof m === "object" && (m.type === "object" || isProvablyObjectShapedRoot(m))); - } - return false; -} -function formatIssue(issue) { - if (!issue.path?.length) return issue.message; - return `${issue.path.map((p) => String(typeof p === "object" ? p.key : p)).join(".")}: ${issue.message}`; -} -async function validateStandardSchema(schema, data) { - const result = await schema["~standard"].validate(data); - if (result.issues && result.issues.length > 0) return { - success: false, - error: result.issues.map((i) => formatIssue(i)).join(", ") - }; - return { - success: true, - data: result.value - }; -} -function zodEmittedPattern(schema) { - const jsonSchema = toJSONSchema(schema, { - target: JSON_SCHEMA_CONVERSION_TARGET, - io: "input" - }); - return typeof jsonSchema.pattern === "string" ? jsonSchema.pattern : void 0; -} -const DATETIME_FRACTION_DIGITS = /\\\.\\d\{(\d+)\}/; -function datetimeReferenceSchemas(pattern) { - const fractionDigits = DATETIME_FRACTION_DIGITS.exec(pattern); - const precisions = [ - void 0, - -1, - 0 - ]; - if (fractionDigits) precisions.push(Number(fractionDigits[1])); - return [false, true].flatMap((local) => [false, true].flatMap((offset) => precisions.map((precision) => iso_datetime({ - local, - offset, - precision - })))); -} -function referencePatternsForFormat(format, pattern) { - let referenceSchemas; - switch (format) { - case "email": - referenceSchemas = [schemas_email()]; - break; - case "uri": - referenceSchemas = [schemas_url()]; - break; - case "date": - referenceSchemas = [iso_date()]; - break; - case "date-time": - referenceSchemas = datetimeReferenceSchemas(pattern); - break; - } - return new Set(referenceSchemas.map((schema) => zodEmittedPattern(schema)).filter((emitted) => emitted !== void 0)); -} -/** Whether `pattern` is the library's own realization of `format` (droppable) rather than a user customization. */ -function isLibraryFormatPattern(format, pattern, vendor) { - if (vendor !== "zod") return true; - return referencePatternsForFormat(format, pattern).has(pattern); -} -function promptArgumentsFromStandardSchema(schema) { - const jsonSchema = standardSchemaToJsonSchema(schema, "input"); - const properties = jsonSchema.properties || {}; - const required = jsonSchema.required || []; - return Object.entries(properties).map(([name, prop]) => ({ - name, - description: prop?.description, - required: required.includes(name) - })); -} - -//#endregion -//#region ../core-internal/src/shared/elicitation.ts -function isJsonObject(value) { - return typeof value === "object" && value !== null && !Array.isArray(value); -} -function convertStandardElicitationSchema(schema) { - try { - return standardSchemaToJsonSchema(schema, "input"); - } catch (error) { - const detail = error instanceof Error ? error.message : String(error); - throw new src_CX2iR2pK_ProtocolError(src_CX2iR2pK_ProtocolErrorCode.InvalidParams, `Elicitation requestedSchema must describe an object with flat primitive properties: ${detail}`); - } -} -const ANNOTATION_ONLY_JSON_SCHEMA_KEYWORDS = new Set([ - "$comment", - "deprecated", - "description", - "examples", - "readOnly", - "title", - "writeOnly" -]); -function isAnnotationOnlyJsonSchemaKeyword(key) { - return ANNOTATION_ONLY_JSON_SCHEMA_KEYWORDS.has(key) || key.startsWith("x-"); -} -const ROOT_KEYS = new Set(["$schema", ...Object.keys(ElicitRequestFormParamsSchema.shape.requestedSchema.shape)]); -const PROPERTY_KEYS_BY_TYPE = { - string: shapeKeys([ - StringSchemaSchema, - UntitledSingleSelectEnumSchemaSchema, - TitledSingleSelectEnumSchemaSchema, - LegacyTitledEnumSchemaSchema - ]), - number: shapeKeys([NumberSchemaSchema]), - integer: shapeKeys([NumberSchemaSchema]), - boolean: shapeKeys([BooleanSchemaSchema]), - array: shapeKeys([UntitledMultiSelectEnumSchemaSchema, TitledMultiSelectEnumSchemaSchema]) -}; -const SUPPORTED_STRING_FORMATS = new Set(StringSchemaSchema.shape.format.unwrap().options); -/** Walks one property node: keeps grammar keys, drops the library format pattern, rejects unknown constraints. */ -function walkProperty(node, path, vendor, unsupported) { - if (!isJsonObject(node)) return node; - const allowedKeys = typeof node.type === "string" && Object.hasOwn(PROPERTY_KEYS_BY_TYPE, node.type) ? PROPERTY_KEYS_BY_TYPE[node.type] : void 0; - if (allowedKeys === void 0) return node; - const pruned = {}; - for (const [key, value] of Object.entries(node)) if (allowedKeys.has(key) || isAnnotationOnlyJsonSchemaKeyword(key)) pruned[key] = value; - else if (key === "pattern" && node.type === "string" && typeof node.format === "string") { - if (!SUPPORTED_STRING_FORMATS.has(node.format)) pruned[key] = value; - else if (typeof value !== "string" || !isLibraryFormatPattern(node.format, value, vendor)) unsupported.push(`${path}.${key}`); - } else unsupported.push(`${path}.${key}`); - return pruned; -} -/** Walks the schema root: keeps the spec root keys, drops annotations, rejects the rest. */ -function walkRequestedSchema(converted, vendor) { - const pruned = {}; - const unsupported = []; - for (const [key, value] of Object.entries(converted)) if (key === "properties" && isJsonObject(value)) pruned[key] = Object.fromEntries(Object.entries(value).map(([name, node]) => [name, walkProperty(node, `properties.${name}`, vendor, unsupported)])); - else if (ROOT_KEYS.has(key)) pruned[key] = value; - else if (!isAnnotationOnlyJsonSchemaKeyword(key)) unsupported.push(key); - if (unsupported.length > 0) throw new src_CX2iR2pK_ProtocolError(src_CX2iR2pK_ProtocolErrorCode.InvalidParams, `Elicitation requestedSchema contains unsupported JSON Schema constraint(s) after Standard Schema conversion: ${unsupported.join(", ")}`); - return pruned; -} -/** Names the properties that fail value validation, instead of surfacing a raw union dump. */ -function describeUnsupportedProperties(pruned, fallback) { - if (!isJsonObject(pruned.properties)) return fallback; - const offenders = Object.entries(pruned.properties).filter(([, node]) => !parseSchema(PrimitiveSchemaDefinitionSchema, node).success).map(([name]) => `properties.${name}`); - return offenders.length > 0 ? offenders.join(", ") : fallback; -} -function findDroppedConstraintPaths(original, parsed, path = "") { - if (Array.isArray(original) && Array.isArray(parsed)) return original.flatMap((item, index) => findDroppedConstraintPaths(item, parsed[index], `${path}[${index}]`)); - if (!isJsonObject(original) || !isJsonObject(parsed)) return []; - return Object.entries(original).flatMap(([key, value]) => { - const childPath = path ? `${path}.${key}` : key; - if (!Object.prototype.hasOwnProperty.call(parsed, key)) return isAnnotationOnlyJsonSchemaKeyword(key) ? [] : [childPath]; - return findDroppedConstraintPaths(value, parsed[key], childPath); - }); -} -/** Converts an authoring-friendly elicitation input into its wire-ready form. */ -function normalizeElicitInputParams(input) { - if (!isStandardSchema(input.requestedSchema)) return { - ...input, - mode: "form", - requestedSchema: input.requestedSchema - }; - const vendor = input.requestedSchema["~standard"].vendor; - const pruned = walkRequestedSchema(convertStandardElicitationSchema(input.requestedSchema), vendor); - const parsed = parseSchema(ElicitRequestFormParamsSchema.shape.requestedSchema, pruned); - if (!parsed.success) throw new src_CX2iR2pK_ProtocolError(src_CX2iR2pK_ProtocolErrorCode.InvalidParams, `Elicitation requestedSchema only supports flat primitive properties (string, number, integer, boolean, and string enums): ${describeUnsupportedProperties(pruned, parsed.error.message)}`); - const droppedConstraints = findDroppedConstraintPaths(pruned, parsed.data); - if (droppedConstraints.length > 0) throw new src_CX2iR2pK_ProtocolError(src_CX2iR2pK_ProtocolErrorCode.InvalidParams, `Elicitation requestedSchema contains unsupported JSON Schema constraint(s) after Standard Schema conversion: ${droppedConstraints.join(", ")}`); - const danglingRequired = (parsed.data.required ?? []).filter((key) => !Object.prototype.hasOwnProperty.call(parsed.data.properties, key)); - if (danglingRequired.length > 0) throw new src_CX2iR2pK_ProtocolError(src_CX2iR2pK_ProtocolErrorCode.InvalidParams, `Elicitation requestedSchema lists required properties that are not defined in properties: ${danglingRequired.join(", ")}`); - return { - ...input, - mode: "form", - requestedSchema: parsed.data - }; -} - -//#endregion -//#region ../core-internal/src/shared/inputRequired.ts -/** -* Authoring helpers for multi-round-trip requests (protocol revision -* 2026-07-28). -* -* A handler for one of the multi-round-trip methods (`tools/call`, -* `prompts/get`, `resources/read`) requests additional client input by -* returning an {@linkcode InputRequiredResult} instead of a final result. The -* helpers here build that return value and its embedded requests as NEUTRAL -* values; only the 2026-07-28 wire codec maps them to/from the wire. The -* 2025-era codec has no input-required vocabulary — on a 2025-era request the -* server's legacy shim (on by default) fulfils the embedded requests as real -* server→client requests and re-enters the handler, so the same return shape -* serves both eras; `ServerOptions.inputRequired.legacyShim: false` restores -* the pre-shim loud failure. -* -* There is no nominal brand: `resultType: 'input_required'` is the -* discriminator, and hand-built result literals are equally legal — the -* server seam re-checks the at-least-one rule for them. -*/ -function buildInputRequired(spec) { - const hasInputRequests = spec.inputRequests !== void 0 && Object.keys(spec.inputRequests).length > 0; - const hasRequestState = typeof spec.requestState === "string"; - if (!hasInputRequests && !hasRequestState) 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", - ...spec.inputRequests !== void 0 && { inputRequests: spec.inputRequests }, - ...spec.requestState !== void 0 && { requestState: spec.requestState } - }; -} -/** -* Builder for the input-required return value of multi-round-trip handlers, -* with per-kind constructors for the embedded requests -* (`inputRequired.elicit`, `inputRequired.elicitUrl`, -* `inputRequired.createMessage`, `inputRequired.listRoots`). -* -* @example Write-once tool requesting confirmation -* ```ts -* server.registerTool('deploy', { inputSchema: z.object({ env: z.string() }) }, async ({ env }, ctx) => { -* const confirmed = acceptedContent<{ confirm: boolean }>(ctx.mcpReq.inputResponses, 'confirm'); -* if (!confirmed) { -* return inputRequired({ -* inputRequests: { -* confirm: inputRequired.elicit({ -* message: `Deploy to ${env}?`, -* requestedSchema: { type: 'object', properties: { confirm: { type: 'boolean' } }, required: ['confirm'] } -* }) -* } -* }); -* } -* return { content: [{ type: 'text', text: `deployed to ${env}` }] }; -* }); -* ``` -*/ -const inputRequired = Object.assign(buildInputRequired, { - elicit(params) { - try { - return { - method: "elicitation/create", - params: normalizeElicitInputParams(params) - }; - } catch (error) { - throw error instanceof src_CX2iR2pK_ProtocolError ? new TypeError(error.message, { cause: error }) : error; - } - }, - elicitUrl(params) { - return { - method: "elicitation/create", - params: { - ...params, - mode: "url" - } - }; - }, - createMessage(params) { - return { - method: "sampling/createMessage", - params - }; - }, - listRoots() { - return { method: "roots/list" }; - } -}); -function acceptedContent(responses, key, schema) { - const view = inputResponse(responses, key); - if (view.kind !== "elicit" || view.action !== "accept" || view.content === void 0) return void 0; - if (schema === void 0) return view.content; - const outcome = schema["~standard"].validate(view.content); - if (outcome instanceof Promise) throw new TypeError("acceptedContent(responses, key, schema) requires a synchronously-validating schema"); - return outcome.issues === void 0 ? outcome.value : void 0; -} -/** -* Reads one entry of a retried request's `inputResponses` -* (`ctx.mcpReq.inputResponses`) as a discriminated view, covering -* decline/cancel detection and the non-elicitation response kinds that -* {@linkcode acceptedContent} does not surface. -* -* The values arrive from the client and are not re-validated here — treat -* them as untrusted input (validate elicitation content with the -* schema-aware {@linkcode acceptedContent} overload where it matters). -*/ -function inputResponse(responses, key) { - if (responses === void 0 || typeof responses !== "object" || responses === null) return { kind: "missing" }; - const entry = responses[key]; - if (entry === null || typeof entry !== "object" || Array.isArray(entry)) return { kind: "missing" }; - const candidate = entry; - if (candidate["action"] === "accept" || candidate["action"] === "decline" || candidate["action"] === "cancel") { - const content = candidate["content"]; - return { - kind: "elicit", - action: candidate["action"], - ...content !== null && typeof content === "object" && !Array.isArray(content) && { content } - }; - } - if (Array.isArray(candidate["roots"])) return { - kind: "roots", - roots: candidate["roots"] - }; - if (typeof candidate["role"] === "string" && candidate["content"] !== void 0) return { - kind: "sampling", - result: candidate - }; - return { kind: "missing" }; -} - -//#endregion -//#region ../core-internal/src/shared/inputRequiredDriver.ts -/** -* The multi-round-trip auto-fulfilment driver (protocol revision 2026-07-28). -* -* When a request to one of the multi-round-trip methods comes back as -* `input_required`, the driver fulfils the embedded input requests by -* dispatching them to the client's already-registered handlers (elicitation, -* sampling, roots — one generic engine, no per-feature API), then retries the -* original request with the collected `inputResponses` and a byte-exact echo -* of `requestState`, on a fresh request id, until the server returns a -* complete result or the round cap is exhausted. -* -* The driver is a LAYER OVER THE MANUAL PATH: each retry is issued with the -* same primitive a manual caller uses (`allowInputRequired` semantics — the -* retry hands back the next `input_required` payload instead of recursing), -* so the loop, the cap, and the pacing live in one place and disabling -* auto-fulfilment (`inputRequired.autoFulfill: false`) simply skips this -* module. Timeouts ride the EXISTING knobs: the per-leg `timeout` applies to -* every wire leg unchanged, and `maxTotalTimeout` bounds the whole flow by -* shrinking the budget passed to each leg — no new timer system. -*/ -/** -* Fixed pacing applied before retrying a requestState-only (load-shedding) -* leg — a leg that carries no embedded input requests, so nothing slows the -* loop down naturally. Counted in the same round cap. -*/ -const REQUEST_STATE_ONLY_LEG_PACING_MS = 250; -/** -* The message both multi-round-trip loops emit when the round cap is -* exhausted — the client driver as a typed error, the server-side legacy -* shim as its per-family failure. One formatter so the texts cannot drift -* (hosts and models read the tool-result copy verbatim). -*/ -function inputRequiredRoundsExceededMessage(method, maxRounds) { - return `Multi-round-trip request '${method}' still required input after ${maxRounds} rounds (inputRequired.maxRounds)`; -} -/** -* Abortable delay: resolves after `ms`, or rejects with the signal's reason -* (wrapped in an `SdkError` when it isn't already one) if the signal aborts -* first. Aborting after resolution is a no-op. Shared with the server-side -* legacy shim (the pacing semantics must match per era). -*/ -function sleep(ms, signal) { - return new Promise((resolve, reject) => { - if (signal?.aborted) { - reject(signal.reason instanceof src_CX2iR2pK_SdkError ? signal.reason : new src_CX2iR2pK_SdkError(src_CX2iR2pK_SdkErrorCode.RequestTimeout, String(signal.reason))); - return; - } - const timer = setTimeout(() => { - signal?.removeEventListener("abort", onAbort); - resolve(); - }, ms); - const onAbort = () => { - clearTimeout(timer); - reject(signal?.reason instanceof src_CX2iR2pK_SdkError ? signal.reason : new src_CX2iR2pK_SdkError(src_CX2iR2pK_SdkErrorCode.RequestTimeout, String(signal?.reason))); - }; - signal?.addEventListener("abort", onAbort, { once: true }); - }); -} -/** -* A per-round abort linked to the caller's signal: the embedded sibling -* dispatches share it, so the first failure (or a caller abort) cancels the -* others instead of leaving them running. Shared with the server-side legacy -* shim (the abort-linkage semantics must match per era). -*/ -function linkedRoundAbort(outer) { - const controller = new AbortController(); - const onOuterAbort = () => controller.abort(outer?.reason); - outer?.addEventListener("abort", onOuterAbort, { once: true }); - if (outer?.aborted) controller.abort(outer.reason); - return { - signal: controller.signal, - abort: (reason) => controller.abort(reason), - dispose: () => outer?.removeEventListener("abort", onOuterAbort) - }; -} - -//#endregion -//#region ../core-internal/src/types/specTypeSchema.ts -/** -* Explicit allowlist of protocol Zod schemas that correspond to a public spec type in `types.ts`. -* -* This intentionally excludes internal helper schemas exported from `schemas.ts` that have no -* matching public type (e.g. `ListChangedOptionsBaseSchema`, `BaseRequestParamsSchema`, -* `NotificationsParamsSchema`, `ClientTasksCapabilitySchema`, `ServerTasksCapabilitySchema`). -* Keeping the list explicit means new public spec types must be added here deliberately, and -* internals never leak into `SpecTypeName`. -* -* `ResourceTemplateSchema` is included; its public type is exported as `ResourceTemplateType` -* (the bare name collides with the server package's `ResourceTemplate` class), so -* `SpecTypes['ResourceTemplate']` is structurally equal to `ResourceTemplateType` rather than to -* a type literally named `ResourceTemplate`. -*/ -const SPEC_SCHEMA_KEYS = [ - "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" -]; -const authSchemas = { - IdJagTokenExchangeResponseSchema: IdJagTokenExchangeResponseSchema, - OAuthClientInformationFullSchema: OAuthClientInformationFullSchema, - OAuthClientInformationSchema: OAuthClientInformationSchema, - OAuthClientMetadataSchema: OAuthClientMetadataSchema, - OAuthClientRegistrationErrorSchema: OAuthClientRegistrationErrorSchema, - OAuthErrorResponseSchema: OAuthErrorResponseSchema, - OAuthMetadataSchema: OAuthMetadataSchema, - OAuthProtectedResourceMetadataSchema: OAuthProtectedResourceMetadataSchema, - OAuthTokenRevocationRequestSchema: OAuthTokenRevocationRequestSchema, - OAuthTokensSchema: OAuthTokensSchema, - OpenIdProviderDiscoveryMetadataSchema: OpenIdProviderDiscoveryMetadataSchema, - OpenIdProviderMetadataSchema: OpenIdProviderMetadataSchema -}; -const _specTypeSchemas = {}; -const _isSpecType = {}; -function register(key, schema) { - const name = key.slice(0, -6); - _specTypeSchemas[name] = schema; - _isSpecType[name] = (v) => schema.safeParse(v).success; -} -for (const key of SPEC_SCHEMA_KEYS) register(key, schemas_exports[key]); -for (const [key, schema] of Object.entries(authSchemas)) register(key, schema); -/** -* Runtime validators for every MCP spec type, keyed by type name. -* -* Use this when you need to validate a spec-defined shape at a boundary the SDK does not own, for -* example an extension's custom-method payload that embeds a `CallToolResult`, or a value read from -* storage that should be a `Tool`. -* -* Each entry implements the Standard Schema interface, so it composes with any -* Standard-Schema-aware library. For a simple boolean check, use {@linkcode isSpecType} instead. -* -* @example -* ```ts source="./specTypeSchema.examples.ts#specTypeSchemas_basicUsage" -* const result = specTypeSchemas.CallToolResult['~standard'].validate(untrusted); -* if (result.issues === undefined) { -* // result.value is CallToolResult -* } -* ``` -*/ -const specTypeSchemas = Object.freeze(_specTypeSchemas); -/** -* Type predicates for every MCP spec type, keyed by type name. -* -* Returns `true` if the value satisfies the schema's input type (`z.input<>`, before defaults and -* transforms are applied), and narrows to that input type. For schemas with `.default()` or -* `.preprocess()`, this may accept values that do not structurally match the named output type; -* for example `isSpecType.CallToolResult({})` is `true` because `content` has a default. Use -* `specTypeSchemas.X['~standard'].validate(value)` when you need the validated output value. -* -* Each guard is a standalone function, so it can be passed directly as a callback. -* -* @example -* ```ts source="./specTypeSchema.examples.ts#isSpecType_basicUsage" -* if (isSpecType.ContentBlock(value)) { -* // value is ContentBlock -* } -* -* const blocks = mixed.filter(isSpecType.ContentBlock); -* ``` -*/ -const isSpecType = Object.freeze(_isSpecType); - -//#endregion -//#region ../core-internal/src/wire/bootstrap.ts -function bootstrapOutboundCodec(method) { - switch (method) { - case "initialize": - case "notifications/initialized": return src_CX2iR2pK_codecForVersion(void 0); - case "server/discover": return src_CX2iR2pK_codecForVersion(src_CX2iR2pK_MODERN_WIRE_REVISION); - default: return; - } -} - -//#endregion -//#region ../core-internal/src/shared/protocol.ts -/** -* The default request timeout, in milliseconds. -*/ -const DEFAULT_REQUEST_TIMEOUT_MSEC = 6e4; -/** -* The reserved per-request `_meta` envelope keys (protocol revision -* 2026-07-28). The protocol layer lifts these out of inbound `_meta` before -* handlers run and surfaces them at `ctx.mcpReq.envelope` — they are -* wire-level bookkeeping, not handler material. -*/ -const RESERVED_ENVELOPE_META_KEYS = [ - auth_CUe6YdwF_PROTOCOL_VERSION_META_KEY, - auth_CUe6YdwF_CLIENT_INFO_META_KEY, - auth_CUe6YdwF_CLIENT_CAPABILITIES_META_KEY, - LOG_LEVEL_META_KEY -]; -/** -* Top-level params members carrying multi-round-trip driver material -* (protocol revision 2026-07-28). The spec reserves these names on -* client-initiated REQUESTS only — notification params keep them untouched -* (a vendor notification may legitimately use the same names). -*/ -const RETRY_PARAMS_KEYS = ["inputResponses", "requestState"]; -/** -* Lift wire-only material out of an inbound message so handlers see exactly -* the 2025-era shape, and surface it for the protocol layer (requests: via -* `ctx.mcpReq`). What counts as wire-only depends on the message kind: the -* reserved envelope `_meta` keys are reserved on every message, while the -* multi-round-trip retry fields (`inputResponses`/`requestState`) are -* reserved on client-initiated requests only — so notifications get only the -* envelope lift, and their top-level params stay untouched. Messages without -* wire-only material are returned unchanged (same reference). -*/ -function liftWireOnlyMaterial(message, kind) { - const params = message.params; - if (!isPlainObject$1(params)) return { - message, - lifted: {} - }; - const meta = params._meta; - const envelopeKeys = isPlainObject$1(meta) ? RESERVED_ENVELOPE_META_KEYS.filter((key) => key in meta) : []; - const retryKeys = kind === "request" ? RETRY_PARAMS_KEYS.filter((key) => key in params) : []; - if (envelopeKeys.length === 0 && retryKeys.length === 0) return { - message, - lifted: {} - }; - const lifted = {}; - const nextParams = { ...params }; - if (envelopeKeys.length > 0 && isPlainObject$1(meta)) { - const envelope = {}; - const nextMeta = { ...meta }; - for (const key of envelopeKeys) { - envelope[key] = meta[key]; - delete nextMeta[key]; - } - lifted.envelope = envelope; - if (Object.keys(nextMeta).length > 0) nextParams._meta = nextMeta; - else delete nextParams._meta; - } - for (const key of retryKeys) { - if (key === "inputResponses") lifted.inputResponses = nextParams[key]; - if (key === "requestState") lifted.requestState = nextParams[key]; - delete nextParams[key]; - } - return { - message: { - ...message, - params: nextParams - }, - lifted - }; -} -/** -* Standard Schema adapter over the era codec's `validateResult` function (the -* function-only WireCodec contract exposes no schema objects). Used by the -* spec-method `request()` overload so the request funnel keeps a single -* `StandardSchemaV1`-shaped validation seam for both spec and explicit-schema -* paths. -* -* Returns `undefined` when the method has no result entry on this era's -* registry — the caller maps that to the synchronous "pass a result schema" -* TypeError, exactly matching the pre-function-only behavior the -* typedMapAlignment suite pins (the result map deliberately excludes the -* `tasks/*` methods, so the spec-method overload refuses them up front). -*/ -function codecResultValidator(codec, method) { - const probe = codec.validateResult(method, void 0); - if (!probe.ok && probe.reason === "not-in-era") return void 0; - return { "~standard": { - version: 1, - vendor: "mcp-wire-codec", - validate(value) { - const outcome = codec.validateResult(method, value); - if (outcome.ok) return { value: outcome.value }; - return { issues: [{ message: outcome.reason === "invalid" ? outcome.message : `not-in-era: ${method}` }] }; - } - } }; -} -/** -* Builds the `ctx.mcpReq.requestState` accessor for a resolved value. The -* `as T` below is the one place {@linkcode RequestStateAccessor}'s -* caller-asserted typing is implemented — no implementation can produce an -* arbitrary `T` from a runtime value honestly. -*/ -function requestStateAccessor(value) { - return () => value; -} -/** Shared no-state accessor: the common case allocates nothing per request. */ -const NO_REQUEST_STATE = requestStateAccessor(void 0); -/** -* Returns a context whose `requestState` accessor reads the given value — -* how the server seam hands a verify hook's decoded payload (or the legacy -* shim's per-round echo) to the handler without mutating the original -* context. -*/ -function withRequestStateValue(ctx, value) { - return { - ...ctx, - mcpReq: { - ...ctx.mcpReq, - requestState: requestStateAccessor(value) - } - }; -} -let writeNegotiatedProtocolVersion; -/** -* Package-internal write channel for a {@linkcode Protocol} instance's -* negotiated protocol version, for callers outside the class hierarchy: -* tests and the (future) modern-era server entry that marks a factory -* instance modern at binding time. Exported on the core internal barrel -* only — never public API. -*/ -function src_CX2iR2pK_setNegotiatedProtocolVersion(instance, version) { - writeNegotiatedProtocolVersion(instance, version); -} -/** -* Implements MCP protocol framing on top of a pluggable transport, including -* features like request/response linking, notifications, and progress. -* -* `Protocol` is abstract; `Client` and `Server` are the concrete role-specific -* implementations most code should use. -*/ -var Protocol = class { - _transport; - _requestMessageId = 0; - _requestHandlers = /* @__PURE__ */ new Map(); - _requestHandlerAbortControllers = /* @__PURE__ */ new Map(); - _notificationHandlers = /* @__PURE__ */ new Map(); - _responseHandlers = /* @__PURE__ */ new Map(); - _progressHandlers = /* @__PURE__ */ new Map(); - _timeoutInfo = /* @__PURE__ */ new Map(); - _pendingDebouncedNotifications = /* @__PURE__ */ new Set(); - /** - * The protocol version negotiated for the current connection (`undefined` - * before negotiation completes), which determines the wire era this - * instance speaks. Set by the SDK's negotiation and initialize paths - * (`Client.connect`, `Server._oninitialize`). - */ - _negotiatedProtocolVersion; - static { - writeNegotiatedProtocolVersion = (instance, version) => { - instance._negotiatedProtocolVersion = version; - }; - } - _supportedProtocolVersions; - /** - * Callback for when the connection is closed for any reason. - * - * This is invoked when {@linkcode Protocol.close | close()} is called as well. - */ - onclose; - /** - * Callback for when an error occurs. - * - * Note that errors are not necessarily fatal; they are used for reporting any kind of exceptional condition out of band. - */ - onerror; - /** - * A handler to invoke for any request types that do not have their own handler installed. - */ - fallbackRequestHandler; - /** - * A handler to invoke for any notification types that do not have their own handler installed. - */ - fallbackNotificationHandler; - constructor(_options) { - this._options = _options; - this._supportedProtocolVersions = _options?.supportedProtocolVersions ?? auth_CUe6YdwF_SUPPORTED_PROTOCOL_VERSIONS; - this.setNotificationHandler("notifications/cancelled", (notification) => { - this._oncancel(notification); - }); - this.setNotificationHandler("notifications/progress", (notification) => { - this._onprogress(notification); - }); - this.setRequestHandler("ping", (_request) => ({})); - } - /** - * Drop consult for inbound messages whose transport did not classify them - * at the edge — long-lived channels such as stdio, where a role class may - * need to decline traffic the negotiated era has no answer for (the - * client-side inbound-request drop on modern-era connections: the - * 2026-07-28 era has no server→client request channel, and on stdio the - * client must never write JSON-RPC responses). - * - * Consulted ONLY when the transport supplied no - * {@linkcode MessageExtraInfo.classification}: edge-classified traffic - * never reaches the hook. Returning `'drop'` discards the message without - * writing any response (requests are surfaced via `onerror`). The base - * implementation returns `undefined`: unclassified traffic keeps today's - * dispatch path unchanged. Era selection never happens here — era is - * instance state, owned by the serving entry that constructed and - * connected the instance. - */ - _shouldDropInbound(_message) {} - /** - * The per-request `_meta` envelope this instance attaches to every outgoing - * request and notification, when one applies. The base implementation - * returns `undefined` (no envelope — the 2025-era posture, so legacy-era - * outbound traffic is byte-identical to a build without this seam). - * `Client` overrides it on a connection that negotiated a modern (2026-07-28+) - * era to return the reserved protocol-version / client-info / - * client-capabilities keys. User-supplied `_meta` keys take precedence over - * the auto-attached ones. - */ - _outboundMetaEnvelope() {} - /** - * Attach this instance's outbound `_meta` envelope (when one is configured) - * to a request or notification. A no-op when the seam returns `undefined` - * — the message returns by reference, so the legacy-era wire stays - * byte-identical. User-supplied `_meta` keys are spread last so they win - * over the auto-attached envelope keys. - */ - _envelopeOutbound(message) { - const envelope = this._outboundMetaEnvelope(); - if (envelope === void 0) return message; - const params = message.params ?? {}; - return { - ...message, - params: { - ...params, - _meta: { - ...envelope, - ...params._meta - } - } - }; - } - /** - * Extension point for non-`complete` decoded results in the response - * funnel: a result the wire codec discriminated into a kind other than - * `'complete'` or `'invalid'` is handed here for the role class to - * resolve. The base default surfaces it as a typed - * {@linkcode SdkErrorCode.UnsupportedResultType} error (no retry). - * - * Intended consumers (named so the seam stays accountable): - * - the `Client`'s multi-round-trip auto-fulfilment engine, which fulfils - * `'input_required'` results through the registered - * elicitation/sampling/roots handlers and retries via `flow.retry`; - * - a future client-side terminal-result handler for - * `subscriptions/listen`, when the spec defines one. - * - * `Server` instances never receive `input_required` responses on their - * outbound legs and leave the base behavior in place. - */ - _resolveNonCompleteResult(decoded, flow) { - return Promise.reject(new src_CX2iR2pK_SdkError(src_CX2iR2pK_SdkErrorCode.UnsupportedResultType, `Unsupported result type '${decoded.kind}' for ${flow.request.method}`, { - resultType: decoded.kind, - method: flow.request.method - })); - } - /** - * Protected accessor for a registered request handler. Used by role - * classes that dispatch synthesized requests through the same stored - * handler chain (e.g. the `Client` fulfilling an embedded multi-round-trip - * input request). - */ - _getRequestHandler(method) { - return this._requestHandlers.get(method); - } - async _oncancel(notification) { - if (!notification.params.requestId) return; - this._requestHandlerAbortControllers.get(notification.params.requestId)?.abort(notification.params.reason); - } - _setupTimeout(messageId, timeout, maxTotalTimeout, onTimeout, resetTimeoutOnProgress = false) { - this._timeoutInfo.set(messageId, { - timeoutId: setTimeout(onTimeout, timeout), - startTime: Date.now(), - timeout, - maxTotalTimeout, - resetTimeoutOnProgress, - onTimeout - }); - } - _resetTimeout(messageId) { - const info = this._timeoutInfo.get(messageId); - if (!info) return false; - const totalElapsed = Date.now() - info.startTime; - if (info.maxTotalTimeout && totalElapsed >= info.maxTotalTimeout) { - this._timeoutInfo.delete(messageId); - throw new src_CX2iR2pK_SdkError(src_CX2iR2pK_SdkErrorCode.RequestTimeout, "Maximum total timeout exceeded", { - maxTotalTimeout: info.maxTotalTimeout, - totalElapsed - }); - } - clearTimeout(info.timeoutId); - info.timeoutId = setTimeout(info.onTimeout, info.timeout); - return true; - } - _cleanupTimeout(messageId) { - const info = this._timeoutInfo.get(messageId); - if (info) { - clearTimeout(info.timeoutId); - this._timeoutInfo.delete(messageId); - } - } - /** - * Attaches to the given transport, starts it, and starts listening for messages. - * - * The caller assumes ownership of the {@linkcode Transport}, replacing any callbacks that have already been set, and expects that it is the only user of the {@linkcode Transport} instance going forward. - */ - async connect(transport) { - this._transport = transport; - const _onclose = this.transport?.onclose; - this._transport.onclose = () => { - try { - _onclose?.(); - } finally { - this._onclose(); - } - }; - const _onerror = this.transport?.onerror; - this._transport.onerror = (error) => { - _onerror?.(error); - this._onerror(error); - }; - const _onmessage = this._transport?.onmessage; - this._transport.onmessage = (message, extra) => { - _onmessage?.(message, extra); - if (src_CX2iR2pK_isJSONRPCResultResponse(message) || src_CX2iR2pK_isJSONRPCErrorResponse(message)) this._onresponse(message); - else if (src_CX2iR2pK_isJSONRPCRequest(message)) this._onrequest(message, extra); - else if (src_CX2iR2pK_isJSONRPCNotification(message)) this._onnotification(message, extra); - else this._onerror(/* @__PURE__ */ new Error(`Unknown message type: ${JSON.stringify(message)}`)); - }; - transport.setSupportedProtocolVersions?.(this._supportedProtocolVersions); - await this._transport.start(); - } - /** - * Transport-close hook. Subclass overrides MUST call `super._onclose()` - * after their own cleanup — base teardown (response-handler settlement, - * timeout clearing, in-flight request abort) does not run otherwise. - */ - _onclose() { - const responseHandlers = this._responseHandlers; - this._responseHandlers = /* @__PURE__ */ new Map(); - this._progressHandlers.clear(); - this._pendingDebouncedNotifications.clear(); - for (const info of this._timeoutInfo.values()) clearTimeout(info.timeoutId); - this._timeoutInfo.clear(); - const requestHandlerAbortControllers = this._requestHandlerAbortControllers; - this._requestHandlerAbortControllers = /* @__PURE__ */ new Map(); - const error = new src_CX2iR2pK_SdkError(src_CX2iR2pK_SdkErrorCode.ConnectionClosed, "Connection closed"); - this._transport = void 0; - try { - this.onclose?.(); - } finally { - for (const handler of responseHandlers.values()) handler(error); - for (const controller of requestHandlerAbortControllers.values()) controller.abort(error); - } - } - _onerror(error) { - this.onerror?.(error); - } - /** - * Inbound-notification dispatch. Subclass overrides MUST delegate - * unmatched traffic to `super._onnotification(rawNotification, extra)` — - * an override that consumes only what it owns and falls through to base - * dispatch for everything else. - */ - _onnotification(rawNotification, extra) { - const { message: notification } = liftWireOnlyMaterial(rawNotification, "notification"); - const codec = this._negotiatedWireCodec(); - if (extra?.classification === void 0 && this._shouldDropInbound(rawNotification) === "drop") return; - if (extra?.classification !== void 0) { - const classified = classifiedWireEra(extra.classification); - if (classified !== codec.era) { - this._onerror(/* @__PURE__ */ new Error(`Era mismatch on inbound notification '${notification.method}': classified as ${classified} but this instance serves ${codec.era}`)); - return; - } - } - if (isSpecNotificationMethod(notification.method) && !codec.hasNotificationMethod(notification.method)) return; - const handler = this._notificationHandlers.get(notification.method); - const fallback = this.fallbackNotificationHandler; - if (handler === void 0 && fallback === void 0) return; - Promise.resolve().then(() => handler === void 0 ? fallback(notification) : handler(notification, codec)).catch((error) => this._onerror(/* @__PURE__ */ new Error(`Uncaught error in notification handler: ${error}`))); - } - _onrequest(rawRequest, extra) { - const { message: request, lifted } = liftWireOnlyMaterial(rawRequest, "request"); - const codec = this._negotiatedWireCodec(); - if (extra?.classification === void 0 && this._shouldDropInbound(rawRequest) === "drop") { - this._onerror(/* @__PURE__ */ new Error(`Dropped inbound request '${rawRequest.method}': not servable on this connection's protocol era`)); - return; - } - const capturedTransport = this._transport; - const sendErrorResponse = (code, message, data) => { - const errorResponse = { - jsonrpc: "2.0", - id: request.id, - error: { - code, - message, - ...data !== void 0 && { data } - } - }; - capturedTransport?.send(errorResponse).catch((error) => this._onerror(/* @__PURE__ */ new Error(`Failed to send an error response: ${error}`))); - }; - if (extra?.classification !== void 0) { - const classified = classifiedWireEra(extra.classification); - if (classified !== codec.era) { - this._onerror(/* @__PURE__ */ new Error(`Era mismatch on inbound request '${request.method}': classified as ${classified} but this instance serves ${codec.era}`)); - const requested = extra.classification.revision ?? classified; - sendErrorResponse(src_CX2iR2pK_ProtocolErrorCode.UnsupportedProtocolVersion, `Unsupported protocol version: ${requested}`, { - supported: this._supportedProtocolVersions, - requested - }); - return; - } - } - if (isSpecRequestMethod(request.method) && !codec.hasRequestMethod(request.method)) { - sendErrorResponse(src_CX2iR2pK_ProtocolErrorCode.MethodNotFound, "Method not found"); - return; - } - const handler = this._requestHandlers.get(request.method) ?? this.fallbackRequestHandler; - if (handler === void 0) { - sendErrorResponse(src_CX2iR2pK_ProtocolErrorCode.MethodNotFound, "Method not found"); - return; - } - const envelopeError = codec.checkInboundEnvelope(lifted); - if (envelopeError !== void 0) { - sendErrorResponse(src_CX2iR2pK_ProtocolErrorCode.InvalidParams, envelopeError); - return; - } - const sendNotification = (notification, options) => this._notificationViaCodec(this._resolveOutboundCodec(notification.method), notification, { - ...options, - relatedRequestId: request.id - }); - const sendRequest = (r, resultSchema, options) => this._requestWithSchemaViaCodec(this._resolveOutboundCodec(r.method), r, resultSchema, { - ...options, - relatedRequestId: request.id - }); - const abortController = new AbortController(); - this._requestHandlerAbortControllers.set(request.id, abortController); - const partitionedInputResponses = lifted.inputResponses === void 0 ? void 0 : partitionInputResponses(lifted.inputResponses); - const baseCtx = { - sessionId: capturedTransport?.sessionId, - mcpReq: { - id: request.id, - method: request.method, - _meta: request.params?._meta, - ...lifted.envelope !== void 0 && { envelope: lifted.envelope }, - ...partitionedInputResponses !== void 0 && { inputResponses: partitionedInputResponses.accepted }, - ...partitionedInputResponses !== void 0 && partitionedInputResponses.droppedKeys.length > 0 && { droppedInputResponseKeys: partitionedInputResponses.droppedKeys }, - requestState: lifted.requestState === void 0 ? NO_REQUEST_STATE : requestStateAccessor(lifted.requestState), - signal: abortController.signal, - send: ((r, schemaOrOptions, maybeOptions) => { - const sendCodec = this._resolveOutboundCodec(r.method); - this._assertOutboundRequestInEra(sendCodec, r.method); - if (isStandardSchema(schemaOrOptions)) return sendRequest(r, schemaOrOptions, maybeOptions); - const validate = codecResultValidator(sendCodec, r.method); - if (validate === void 0) throw new TypeError(`'${r.method}' is not a spec method; pass a result schema as the second argument to ctx.mcpReq.send().`); - return sendRequest(r, validate, schemaOrOptions); - }), - notify: sendNotification - }, - http: extra?.authInfo ? { authInfo: extra.authInfo } : void 0 - }; - const ctx = this.buildContext(baseCtx, extra); - Promise.resolve().then(() => handler(request, ctx)).then(async (result) => { - if (abortController.signal.aborted) return; - let encoded; - try { - encoded = codec.encodeResult(request.method, result, this._outboundServerInfo()); - } catch (error) { - this._onerror(/* @__PURE__ */ new Error(`Failed to encode result for ${request.method}: ${error}`)); - sendErrorResponse(src_CX2iR2pK_ProtocolErrorCode.InternalError, "Internal error"); - return; - } - const response = { - result: encoded, - jsonrpc: "2.0", - id: request.id - }; - await capturedTransport?.send(response); - }, async (error) => { - if (abortController.signal.aborted) return; - const thrownCode = Number.isSafeInteger(error["code"]) ? error["code"] : src_CX2iR2pK_ProtocolErrorCode.InternalError; - const errorResponse = { - jsonrpc: "2.0", - id: request.id, - error: { - code: codec.encodeErrorCode(thrownCode), - message: error.message ?? "Internal error", - ...error["data"] !== void 0 && { data: error["data"] } - } - }; - await capturedTransport?.send(errorResponse); - }).catch((error) => this._onerror(/* @__PURE__ */ new Error(`Failed to send response: ${error}`))).finally(() => { - if (this._requestHandlerAbortControllers.get(request.id) === abortController) this._requestHandlerAbortControllers.delete(request.id); - }); - } - _onprogress(notification) { - const { progressToken, ...params } = notification.params; - const messageId = Number(progressToken); - const handler = this._progressHandlers.get(messageId); - if (!handler) { - this._onerror(/* @__PURE__ */ new Error(`Received a progress notification for an unknown token: ${JSON.stringify(notification)}`)); - return; - } - const responseHandler = this._responseHandlers.get(messageId); - const timeoutInfo = this._timeoutInfo.get(messageId); - if (timeoutInfo && responseHandler && timeoutInfo.resetTimeoutOnProgress) try { - this._resetTimeout(messageId); - } catch (error) { - this._responseHandlers.delete(messageId); - this._progressHandlers.delete(messageId); - this._cleanupTimeout(messageId); - responseHandler(error); - return; - } - handler(params); - } - /** - * Inbound-response dispatch. Subclass overrides MUST delegate unmatched - * traffic to `super._onresponse(response)` — an override that consumes - * only what it owns and falls through to base dispatch for everything - * else. - */ - _onresponse(response) { - const messageId = Number(response.id); - const handler = this._responseHandlers.get(messageId); - if (handler === void 0) { - this._onerror(/* @__PURE__ */ new Error(`Received a response for an unknown message ID: ${JSON.stringify(response)}`)); - return; - } - this._responseHandlers.delete(messageId); - this._cleanupTimeout(messageId); - this._progressHandlers.delete(messageId); - if (src_CX2iR2pK_isJSONRPCResultResponse(response)) handler(response); - else handler(src_CX2iR2pK_ProtocolError.fromError(response.error.code, response.error.message, response.error.data)); - } - get transport() { - return this._transport; - } - /** - * Closes the connection. - */ - async close() { - await this._transport?.close(); - } - request(request, schemaOrOptions, maybeOptions) { - const codec = this._resolveOutboundCodec(request.method); - this._assertOutboundRequestInEra(codec, request.method); - if (isStandardSchema(schemaOrOptions)) return this._requestWithSchemaViaCodec(codec, request, schemaOrOptions, maybeOptions); - const validate = codecResultValidator(codec, request.method); - if (validate === void 0) throw new TypeError(`'${request.method}' is not a spec method; pass a result schema as the second argument to request().`); - return this._requestWithSchemaViaCodec(codec, request, validate, schemaOrOptions); - } - /** - * The wire codec for this instance's negotiated era — the phase-2 truth: - * everything an established connection sends and receives resolves - * through it. Legacy until a version has been negotiated. - */ - _negotiatedWireCodec() { - return src_CX2iR2pK_codecForVersion(this._negotiatedProtocolVersion); - } - /** - * Protected accessor for the instance's negotiated wire codec, for role - * classes (Client/Server/McpServer) routing era-dependent behavior - * through the codec's function-only surface — `samplingResultVariant`, - * `outboundEnvelope`, `projectCallToolResult` — instead of branching on - * the protocol version themselves. - */ - _wireCodec() { - return this._negotiatedWireCodec(); - } - /** - * Outbound codec resolution: while the negotiated version is still unset - * (the negotiation window), lifecycle messages are bootstrap-pinned BY - * METHOD — they self-identify their era (`initialize` IS the legacy - * handshake, `server/discover` IS the modern probe). Once a version has - * been negotiated, the instance era is authoritative for everything — a - * negotiated session never re-routes a method onto the other era. - */ - _resolveOutboundCodec(method) { - if (this._negotiatedProtocolVersion === void 0) { - const pinned = bootstrapOutboundCodec(method); - if (pinned) return pinned; - } - return this._negotiatedWireCodec(); - } - /** - * Era gate for outbound requests — deletions are physical in BOTH - * directions: sending a spec method that the resolved era does not define - * dies locally with a typed error before anything reaches the transport. - * Methods outside the spec universe are consumer-owned extension methods - * and stay era-blind. - */ - _assertOutboundRequestInEra(codec, method) { - if (isSpecRequestMethod(method) && !codec.hasRequestMethod(method)) throw new src_CX2iR2pK_SdkError(src_CX2iR2pK_SdkErrorCode.MethodNotSupportedByProtocolVersion, `Method '${method}' is not supported by the negotiated protocol version (wire era ${codec.era})`, { - method, - era: codec.era - }); - } - /** - * Sends a request and waits for a response, using the provided schema for - * validation instead of the era registry's method-keyed entry. - * - * This is the internal implementation used by SDK methods whose result - * schema cannot be expressed as a method-keyed registry entry — the one - * surviving case is `server.createMessage`, whose result schema depends - * on the REQUEST params (tools vs no tools) — and by callers passing - * explicit compatibility schemas. Spec methods are still era-gated here: - * an explicit schema never smuggles a deleted method onto the wire. - */ - _requestWithSchema(request, resultSchema, options) { - const codec = this._resolveOutboundCodec(request.method); - this._assertOutboundRequestInEra(codec, request.method); - return this._requestWithSchemaViaCodec(codec, request, resultSchema, options); - } - /** - * The request funnel proper, keyed by the resolved era codec: the codec - * owns result decoding (raw-first `resultType` discrimination — V-1 — - * and the era's lift posture) before the schema validation step. - */ - _requestWithSchemaViaCodec(codec, request, resultSchema, options) { - const { relatedRequestId, resumptionToken, onresumptiontoken, headers } = options ?? {}; - const flowStartedAt = Date.now(); - let onAbort; - let cleanupMessageId; - return new Promise((resolve, reject) => { - const earlyReject = (error) => { - reject(error); - }; - if (!this._transport) { - earlyReject(/* @__PURE__ */ new Error("Not connected")); - return; - } - if (this._options?.enforceStrictCapabilities === true) try { - this.assertCapabilityForMethod(request.method); - } catch (error) { - earlyReject(error); - return; - } - if (options?.signal?.aborted) { - const reason = options.signal.reason; - throw reason instanceof src_CX2iR2pK_SdkError ? reason : new src_CX2iR2pK_SdkError(src_CX2iR2pK_SdkErrorCode.RequestTimeout, String(reason)); - } - const requestAbort = codec.era === src_CX2iR2pK_MODERN_WIRE_REVISION && this._transport.hasPerRequestStream === true ? new AbortController() : void 0; - const messageId = this._requestMessageId++; - cleanupMessageId = messageId; - const jsonrpcRequest = { - ...request, - jsonrpc: "2.0", - id: messageId - }; - if (options?.onprogress) { - this._progressHandlers.set(messageId, options.onprogress); - jsonrpcRequest.params = { - ...request.params, - _meta: { - ...request.params?._meta, - progressToken: messageId - } - }; - } - const outbound = this._envelopeOutbound(jsonrpcRequest); - let responseReceived = false; - const cancel = (reason) => { - if (responseReceived) return; - this._progressHandlers.delete(messageId); - if (requestAbort === void 0) this._transport?.send(this._envelopeOutbound({ - jsonrpc: "2.0", - method: "notifications/cancelled", - params: { - requestId: messageId, - reason: String(reason) - } - }), { - relatedRequestId, - resumptionToken, - onresumptiontoken - }).catch((error) => this._onerror(/* @__PURE__ */ new Error(`Failed to send cancellation: ${error}`))); - else requestAbort.abort(); - reject(reason instanceof src_CX2iR2pK_SdkError ? reason : new src_CX2iR2pK_SdkError(src_CX2iR2pK_SdkErrorCode.RequestTimeout, String(reason))); - }; - this._responseHandlers.set(messageId, (response) => { - if (options?.signal?.aborted) return; - responseReceived = true; - if (response instanceof Error) return reject(response); - let decoded; - try { - decoded = codec.decodeResult(request.method, response.result); - } catch (error) { - return reject(error instanceof Error ? error : new Error(String(error))); - } - if (decoded.kind === "invalid") return reject(decoded.error); - if (decoded.kind === "input_required") { - if (options?.allowInputRequired === true) return resolve(manualInputRequiredValue(decoded)); - const flow = { - codec, - request, - resultSchema, - options, - flowStartedAt, - retry: (params, legOptions) => this._requestWithSchemaViaCodec(codec, params === void 0 ? { method: request.method } : { - method: request.method, - params - }, resultSchema, legOptions) - }; - return resolve(this._resolveNonCompleteResult(decoded, flow)); - } - const result = decoded.result; - validateStandardSchema(resultSchema, result).then((parseResult) => { - if (parseResult.success) resolve(parseResult.data); - else reject(new src_CX2iR2pK_SdkError(src_CX2iR2pK_SdkErrorCode.InvalidResult, `Invalid result for ${request.method}: ${parseResult.error}`)); - }, reject); - }); - onAbort = () => cancel(options?.signal?.reason); - options?.signal?.addEventListener("abort", onAbort, { once: true }); - const timeout = options?.timeout ?? DEFAULT_REQUEST_TIMEOUT_MSEC; - const timeoutHandler = () => cancel(new src_CX2iR2pK_SdkError(src_CX2iR2pK_SdkErrorCode.RequestTimeout, "Request timed out", { timeout })); - this._setupTimeout(messageId, timeout, options?.maxTotalTimeout, timeoutHandler, options?.resetTimeoutOnProgress ?? false); - this._transport.send(outbound, { - relatedRequestId, - resumptionToken, - onresumptiontoken, - headers, - requestSignal: requestAbort?.signal - }).catch((error) => { - this._progressHandlers.delete(messageId); - reject(error); - }); - }).finally(() => { - if (onAbort) options?.signal?.removeEventListener("abort", onAbort); - if (cleanupMessageId !== void 0) { - this._responseHandlers.delete(cleanupMessageId); - this._cleanupTimeout(cleanupMessageId); - } - }); - } - /** - * Emits a notification, which is a one-way message that does not expect a response. - */ - async notification(notification, options) { - return this._notificationViaCodec(this._resolveOutboundCodec(notification.method), notification, options); - } - /** - * The notification funnel proper, keyed by the resolved era codec — - * direct sends and related notifications (`ctx.mcpReq.notify`) alike - * resolve through the instance's negotiated era at send time. - */ - async _notificationViaCodec(codec, notification, options) { - if (!this._transport) throw new src_CX2iR2pK_SdkError(src_CX2iR2pK_SdkErrorCode.NotConnected, "Not connected"); - if (isSpecNotificationMethod(notification.method) && !codec.hasNotificationMethod(notification.method)) throw new src_CX2iR2pK_SdkError(src_CX2iR2pK_SdkErrorCode.MethodNotSupportedByProtocolVersion, `Notification '${notification.method}' is not supported by the negotiated protocol version (wire era ${codec.era})`, { - method: notification.method, - era: codec.era - }); - this.assertNotificationCapability(notification.method); - const jsonrpcNotification = this._envelopeOutbound({ - jsonrpc: "2.0", - ...notification - }); - if ((this._options?.debouncedNotificationMethods ?? []).includes(notification.method) && !notification.params && !options?.relatedRequestId) { - if (this._pendingDebouncedNotifications.has(notification.method)) return; - this._pendingDebouncedNotifications.add(notification.method); - Promise.resolve().then(() => { - this._pendingDebouncedNotifications.delete(notification.method); - if (!this._transport) return; - this._transport?.send(jsonrpcNotification, options).catch((error) => this._onerror(error)); - }); - return; - } - await this._transport.send(jsonrpcNotification, options); - } - setRequestHandler(method, schemasOrHandler, maybeHandler) { - this.assertRequestHandlerCapability(method); - let stored; - if (typeof schemasOrHandler === "function") { - if (!isSpecRequestMethod(method)) throw new TypeError(`'${method}' is not a spec request method; pass schemas as the second argument to setRequestHandler().`); - stored = (request, ctx) => { - const dispatchCodec = this._negotiatedWireCodec(); - let outcome = dispatchCodec.validateRequest(method, request); - if (!outcome.ok && outcome.reason === "not-in-era") outcome = dispatchCodec.validateInputRequest(method, request); - if (!outcome.ok) { - if (outcome.reason === "not-in-era") throw new src_CX2iR2pK_ProtocolError(src_CX2iR2pK_ProtocolErrorCode.InternalError, `No wire schema for ${method} in the resolved era`); - throw new Error(outcome.message); - } - return Promise.resolve(schemasOrHandler(outcome.value, ctx)); - }; - } else if (maybeHandler) stored = async (request, ctx) => { - const parsed = await validateStandardSchema(schemasOrHandler.params, { ...request.params }); - if (!parsed.success) throw new src_CX2iR2pK_ProtocolError(src_CX2iR2pK_ProtocolErrorCode.InvalidParams, `Invalid params for ${method}: ${parsed.error}`); - return maybeHandler(parsed.data, ctx); - }; - else throw new TypeError("setRequestHandler: handler is required"); - this._requestHandlers.set(method, this._wrapHandler(method, stored)); - } - /** - * Hook for subclasses to wrap a registered request handler with role-specific - * validation or behavior (e.g. `Server` validates `tools/call` results, `Client` - * validates `elicitation/create` mode and result). Runs for both the 2-arg and - * 3-arg registration paths. The default implementation is identity. - * - * Subclasses overriding this hook avoid redeclaring `setRequestHandler`'s overload set. - */ - _wrapHandler(_method, handler) { - return handler; - } - /** - * Hook for subclasses to supply the implementation identity the 2026-era - * encode seam stamps into outbound result `_meta` under - * `io.modelcontextprotocol/serverInfo` (spec PR #3002: servers SHOULD - * identify themselves on every response). The default is `undefined` — no - * stamp. Only `Server` overrides this: the key identifies the software - * producing a response, and the 2025-era codec never stamps anything - * regardless (the never-stamp guarantee). - */ - _outboundServerInfo() {} - /** - * Removes the request handler for the given method. - */ - removeRequestHandler(method) { - this._requestHandlers.delete(method); - } - /** - * Asserts that a request handler has not already been set for the given method, in preparation for a new one being automatically installed. - */ - assertCanSetRequestHandler(method) { - if (this._requestHandlers.has(method)) throw new Error(`A request handler for ${method} already exists, which would be overridden`); - } - setNotificationHandler(method, schemasOrHandler, maybeHandler) { - if (typeof schemasOrHandler === "function") { - if (!isSpecNotificationMethod(method)) throw new TypeError(`'${method}' is not a spec notification method; pass schemas as the second argument to setNotificationHandler().`); - this._notificationHandlers.set(method, (notification, codec) => { - const outcome = codec.validateNotification(method, notification); - if (!outcome.ok) { - if (outcome.reason === "not-in-era") throw new src_CX2iR2pK_ProtocolError(src_CX2iR2pK_ProtocolErrorCode.InternalError, `No wire schema for ${method} in the resolved era`); - throw new Error(outcome.message); - } - return Promise.resolve(schemasOrHandler(outcome.value)); - }); - return; - } - if (!maybeHandler) throw new TypeError("setNotificationHandler: handler is required"); - this._notificationHandlers.set(method, async (notification) => { - const parsed = await validateStandardSchema(schemasOrHandler.params, { ...notification.params }); - if (!parsed.success) throw new src_CX2iR2pK_ProtocolError(src_CX2iR2pK_ProtocolErrorCode.InvalidParams, `Invalid params for notification ${method}: ${parsed.error}`); - await maybeHandler(parsed.data, notification); - }); - } - /** - * Removes the notification handler for the given method. - */ - removeNotificationHandler(method) { - this._notificationHandlers.delete(method); - } -}; -function isPlainObject$1(value) { - return value !== null && typeof value === "object" && !Array.isArray(value); -} -function mergeCapabilities(base, additional) { - const result = { ...base }; - for (const key in additional) { - const k = key; - const addValue = additional[k]; - if (addValue === void 0) continue; - const baseValue = result[k]; - result[k] = isPlainObject$1(baseValue) && isPlainObject$1(addValue) ? { - ...baseValue, - ...addValue - } : addValue; - } - return result; -} - -//#endregion -//#region ../core-internal/src/shared/inputRequiredEngine.ts -function src_CX2iR2pK_isPlainObject(value) { - return typeof value === "object" && value !== null && !Array.isArray(value); -} -/** -* Splits a retried request's `inputResponses` map into the BARE response -* entries the spec defines and everything else. The spec's embedded responses -* are the bare result objects (an `ElicitResult`, `CreateMessageResult`, or -* `ListRootsResult`); a wrapped `{method, result}` envelope (a shape some -* peers emit) is never accepted as a response — its key is recorded so the -* handler can re-issue the corresponding input request. -*/ -function partitionInputResponses(inputResponses) { - const accepted = {}; - const droppedKeys = []; - if (!src_CX2iR2pK_isPlainObject(inputResponses)) return { - accepted, - droppedKeys - }; - for (const [key, entry] of Object.entries(inputResponses)) { - if (!src_CX2iR2pK_isPlainObject(entry) || "method" in entry || "result" in entry) { - droppedKeys.push(key); - continue; - } - accepted[key] = entry; - } - return { - accepted, - droppedKeys - }; -} -/** -* Builds the manual-mode {@linkcode InputRequiredResult} value from the -* codec's decoded payload — what an `allowInputRequired: true` caller -* receives instead of the auto-fulfilled complete result. -*/ -function manualInputRequiredValue(decoded) { - return { - resultType: "input_required", - inputRequests: decoded.inputRequests, - ...decoded.requestState !== void 0 && { requestState: decoded.requestState } - }; -} - -//#endregion -//#region ../../node_modules/.pnpm/content-type@1.0.5/node_modules/content-type/index.js -/*! -* content-type -* Copyright(c) 2015 Douglas Christopher Wilson -* MIT Licensed -*/ -var require_content_type = /* @__PURE__ */ __commonJSMin(((exports) => { - /** - * RegExp to match *( ";" parameter ) in RFC 7231 sec 3.1.1.1 - * - * parameter = token "=" ( token / quoted-string ) - * token = 1*tchar - * tchar = "!" / "#" / "$" / "%" / "&" / "'" / "*" - * / "+" / "-" / "." / "^" / "_" / "`" / "|" / "~" - * / DIGIT / ALPHA - * ; any VCHAR, except delimiters - * quoted-string = DQUOTE *( qdtext / quoted-pair ) DQUOTE - * qdtext = HTAB / SP / %x21 / %x23-5B / %x5D-7E / obs-text - * obs-text = %x80-FF - * quoted-pair = "\" ( HTAB / SP / VCHAR / obs-text ) - */ - var PARAM_REGEXP = /; *([!#$%&'*+.^_`|~0-9A-Za-z-]+) *= *("(?:[\u000b\u0020\u0021\u0023-\u005b\u005d-\u007e\u0080-\u00ff]|\\[\u000b\u0020-\u00ff])*"|[!#$%&'*+.^_`|~0-9A-Za-z-]+) */g; - /** - * RegExp to match quoted-pair in RFC 7230 sec 3.2.6 - * - * quoted-pair = "\" ( HTAB / SP / VCHAR / obs-text ) - * obs-text = %x80-FF - */ - var QESC_REGEXP = /\\([\u000b\u0020-\u00ff])/g; - /** - * RegExp to match type in RFC 7231 sec 3.1.1.1 - * - * media-type = type "/" subtype - * type = token - * subtype = token - */ - var TYPE_REGEXP = /^[!#$%&'*+.^_`|~0-9A-Za-z-]+\/[!#$%&'*+.^_`|~0-9A-Za-z-]+$/; - exports.parse = parse; - /** - * Parse media type to object. - * - * @param {string|object} string - * @return {Object} - * @public - */ - function parse(string) { - if (!string) throw new TypeError("argument string is required"); - var header = typeof string === "object" ? getcontenttype(string) : string; - if (typeof header !== "string") throw new TypeError("argument string is required to be a string"); - var index = header.indexOf(";"); - var type = index !== -1 ? header.slice(0, index).trim() : header.trim(); - if (!TYPE_REGEXP.test(type)) throw new TypeError("invalid media type"); - var obj = new ContentType(type.toLowerCase()); - if (index !== -1) { - var key; - var match; - var value; - PARAM_REGEXP.lastIndex = index; - while (match = PARAM_REGEXP.exec(header)) { - if (match.index !== index) throw new TypeError("invalid parameter format"); - index += match[0].length; - key = match[1].toLowerCase(); - value = match[2]; - if (value.charCodeAt(0) === 34) { - value = value.slice(1, -1); - if (value.indexOf("\\") !== -1) value = value.replace(QESC_REGEXP, "$1"); - } - obj.parameters[key] = value; - } - if (index !== header.length) throw new TypeError("invalid parameter format"); - } - return obj; - } - /** - * Get content-type from req/res objects. - * - * @param {object} - * @return {Object} - * @private - */ - function getcontenttype(obj) { - var header; - if (typeof obj.getHeader === "function") header = obj.getHeader("content-type"); - else if (typeof obj.headers === "object") header = obj.headers && obj.headers["content-type"]; - if (typeof header !== "string") throw new TypeError("content-type header is missing from object"); - return header; - } - /** - * Class to represent a content type. - * @private - */ - function ContentType(type) { - this.parameters = Object.create(null); - this.type = type; - } -})); - -//#endregion -//#region ../core-internal/src/shared/mediaType.ts -var import_content_type = /* @__PURE__ */ __toESM(require_content_type(), 1); -/** -* Extracts the media type (the lowercased `type/subtype` pair, without -* parameters) from a raw `Content-Type` header value, or `undefined` when the -* header is missing or empty. -* -* Content-Type comparisons must use the parsed media type, never a substring -* search of the raw header: a value like `text/plain; a=application/json` -* contains the substring `application/json` but its media type is -* `text/plain`, and case variants or parameters make naive string comparison -* wrong in both directions. -* -* "Essence" is the WHATWG MIME Sniffing standard's term for the bare -* `type/subtype` pair (https://mimesniff.spec.whatwg.org/#mime-type-essence); -* the Fetch standard's request classification is defined against it -* (https://fetch.spec.whatwg.org/#cors-safelisted-request-header). -* -* Parsing is RFC 9110 (`content-type` package) first. When the parameter -* section is malformed (`application/json;`, `application/json; charset=`), -* browsers and most HTTP stacks still derive the media type from the segment -* before the first `;` — the fallback matches that widely-implemented -* behavior, so a header whose media type is unambiguous is not rejected for -* a sloppy parameter section. -*/ -function src_CX2iR2pK_mediaTypeEssence(header) { - if (!header) return; - try { - return import_content_type.parse(header).type; - } catch { - const essence = (header.split(";", 1)[0] ?? "").trim().toLowerCase(); - if (essence === "" || header.slice(essence.length).includes(",")) return; - return essence; - } -} -/** -* Whether a raw `Content-Type` header value denotes `application/json`. -* Parameters (for example `charset=utf-8`) are allowed and ignored; malformed -* parameter sections do not reject a header whose media type is unambiguously -* `application/json` (see `mediaTypeEssence` for the exact grammar). -*/ -function src_CX2iR2pK_isJsonContentType(header) { - if (header === "application/json") return true; - return src_CX2iR2pK_mediaTypeEssence(header) === "application/json"; -} - -//#endregion -//#region ../core-internal/src/shared/metadataUtils.ts -/** -* Utilities for working with {@linkcode BaseMetadata} objects. -*/ -/** -* Gets the display name for an object with {@linkcode BaseMetadata}. -* For tools, the precedence is: `title` → {@linkcode index.ToolAnnotations | annotations}.`title` → `name` -* For other objects: `title` → `name` -* This implements the spec requirement: "if no title is provided, name should be used for display purposes" -*/ -function getDisplayName(metadata) { - if (metadata.title !== void 0 && metadata.title !== "") return metadata.title; - if ("annotations" in metadata && metadata.annotations?.title) return metadata.annotations.title; - return metadata.name; -} - -//#endregion -//#region ../core-internal/src/shared/stdio.ts -const STDIO_DEFAULT_MAX_BUFFER_SIZE = 10 * 1024 * 1024; -/** -* Buffers a continuous stdio stream into discrete JSON-RPC messages. -*/ -var ReadBuffer = class { - _buffer; - _maxBufferSize; - constructor(options) { - this._maxBufferSize = options?.maxBufferSize ?? STDIO_DEFAULT_MAX_BUFFER_SIZE; - } - append(chunk) { - if ((this._buffer?.length ?? 0) + chunk.length > this._maxBufferSize) { - this.clear(); - throw new Error(`ReadBuffer exceeded maximum size of ${this._maxBufferSize} bytes`); - } - this._buffer = this._buffer ? Buffer.concat([this._buffer, chunk]) : chunk; - } - readMessage() { - while (this._buffer) { - const index = this._buffer.indexOf("\n"); - if (index === -1) return null; - const line = this._buffer.toString("utf8", 0, index).replace(/\r$/, ""); - this._buffer = this._buffer.subarray(index + 1); - try { - return deserializeMessage(line); - } catch (error) { - if (error instanceof SyntaxError) continue; - throw error; - } - } - return null; - } - clear() { - this._buffer = void 0; - } -}; -function deserializeMessage(line) { - return auth_CUe6YdwF_JSONRPCMessageSchema.parse(JSON.parse(line)); -} -function serializeMessage(message) { - return JSON.stringify(message) + "\n"; -} - -//#endregion -//#region ../core-internal/src/shared/toolNameValidation.ts -/** -* Tool name validation utilities according to SEP: Specify Format for Tool Names -* -* Tool names SHOULD be between 1 and 128 characters in length (inclusive). -* Tool names are case-sensitive. -* Allowed characters: uppercase and lowercase ASCII letters (`A-Z`, `a-z`), digits -* (`0-9`), underscore (`_`), dash (`-`), and dot (`.`). -* Tool names SHOULD NOT contain spaces, commas, or other special characters. -* -* @see {@link https://github.com/modelcontextprotocol/modelcontextprotocol/issues/986 | SEP-986: Specify Format for Tool Names} -*/ -/** -* Regular expression for valid tool names according to SEP-986 specification -*/ -const TOOL_NAME_REGEX = /^[A-Za-z0-9._-]{1,128}$/; -/** -* Validates a tool name according to the SEP specification -* @param name - The tool name to validate -* @returns An object containing validation result and any warnings -*/ -function validateToolName(name) { - const warnings = []; - if (name.length === 0) return { - isValid: false, - warnings: ["Tool name cannot be empty"] - }; - if (name.length > 128) return { - isValid: false, - warnings: [`Tool name exceeds maximum length of 128 characters (current: ${name.length})`] - }; - if (name.includes(" ")) warnings.push("Tool name contains spaces, which may cause parsing issues"); - if (name.includes(",")) warnings.push("Tool name contains commas, which may cause parsing issues"); - if (name.startsWith("-") || name.endsWith("-")) warnings.push("Tool name starts or ends with a dash, which may cause parsing issues in some contexts"); - if (name.startsWith(".") || name.endsWith(".")) warnings.push("Tool name starts or ends with a dot, which may cause parsing issues in some contexts"); - if (!TOOL_NAME_REGEX.test(name)) { - const invalidChars = [...name].filter((char) => !/[A-Za-z0-9._-]/.test(char)).filter((char, index, arr) => arr.indexOf(char) === index); - warnings.push(`Tool name contains invalid characters: ${invalidChars.map((c) => `"${c}"`).join(", ")}`, "Allowed characters are: A-Z, a-z, 0-9, underscore (_), dash (-), and dot (.)"); - return { - isValid: false, - warnings - }; - } - return { - isValid: true, - warnings - }; -} -/** -* Issues warnings for non-conforming tool names -* @param name - The tool name that triggered the warnings -* @param warnings - Array of warning messages -*/ -function issueToolNameWarning(name, warnings) { - if (warnings.length > 0) { - console.warn(`Tool name validation warning for "${name}":`); - for (const warning of warnings) console.warn(` - ${warning}`); - console.warn("Tool registration will proceed, but this may cause compatibility issues."); - console.warn("Consider updating the tool name to conform to the MCP tool naming standard."); - console.warn("See SEP: Specify Format for Tool Names (https://github.com/modelcontextprotocol/modelcontextprotocol/issues/986) for more details."); - } -} -/** -* Validates a tool name and issues warnings for non-conforming names -* @param name - The tool name to validate -* @returns `true` if the name is valid, `false` otherwise -*/ -function validateAndWarnToolName(name) { - const result = validateToolName(name); - issueToolNameWarning(name, result.warnings); - return result.isValid; -} - -//#endregion -//#region ../core-internal/src/shared/transport.ts -/** -* Normalizes `HeadersInit` to a plain `Record` for manipulation. -* Handles `Headers` objects, arrays of tuples, and plain objects. -*/ -function normalizeHeaders(headers) { - if (!headers) return {}; - if (headers instanceof Headers) return Object.fromEntries(headers.entries()); - if (Array.isArray(headers)) return Object.fromEntries(headers); - return { ...headers }; -} -/** -* Creates a fetch function that includes base `RequestInit` options. -* This ensures requests inherit settings like credentials, mode, headers, etc. from the base init. -* -* @param baseFetch - The base fetch function to wrap (defaults to global `fetch`) -* @param baseInit - The base `RequestInit` to merge with each request -* @returns A wrapped fetch function that merges base options with call-specific options -*/ -function createFetchWithInit(baseFetch = fetch, baseInit) { - if (!baseInit) return baseFetch; - return async (url, init) => { - return baseFetch(url, { - ...baseInit, - ...init, - headers: init?.headers ? { - ...normalizeHeaders(baseInit.headers), - ...normalizeHeaders(init.headers) - } : baseInit.headers - }); - }; -} - -//#endregion -//#region ../core-internal/src/shared/uriTemplate.ts -const MAX_TEMPLATE_LENGTH = 1e6; -const MAX_VARIABLE_LENGTH = 1e6; -const MAX_TEMPLATE_EXPRESSIONS = 1e4; -const MAX_REGEX_LENGTH = 1e6; -var src_CX2iR2pK_UriTemplate = class UriTemplate { - /** - * Returns true if the given string contains any URI template expressions. - * A template expression is a sequence of characters enclosed in curly braces, - * like `{foo}` or `{?bar}`. - */ - static isTemplate(str) { - return /\{[^}\s]+\}/.test(str); - } - static validateLength(str, max, context) { - if (str.length > max) throw new Error(`${context} exceeds maximum length of ${max} characters (got ${str.length})`); - } - template; - parts; - get variableNames() { - return this.parts.flatMap((part) => typeof part === "string" ? [] : part.names); - } - constructor(template) { - UriTemplate.validateLength(template, MAX_TEMPLATE_LENGTH, "Template"); - this.template = template; - this.parts = this.parse(template); - } - toString() { - return this.template; - } - parse(template) { - const parts = []; - let currentText = ""; - let i = 0; - let expressionCount = 0; - while (i < template.length) if (template[i] === "{") { - if (currentText) { - parts.push(currentText); - currentText = ""; - } - const end = template.indexOf("}", i); - if (end === -1) throw new Error("Unclosed template expression"); - expressionCount++; - if (expressionCount > MAX_TEMPLATE_EXPRESSIONS) throw new Error(`Template contains too many expressions (max ${MAX_TEMPLATE_EXPRESSIONS})`); - const expr = template.slice(i + 1, end); - const operator = this.getOperator(expr); - const exploded = expr.includes("*"); - const names = this.getNames(expr); - const name = names[0]; - for (const name$1 of names) UriTemplate.validateLength(name$1, MAX_VARIABLE_LENGTH, "Variable name"); - parts.push({ - name, - operator, - names, - exploded - }); - i = end + 1; - } else { - currentText += template[i]; - i++; - } - if (currentText) parts.push(currentText); - return parts; - } - getOperator(expr) { - return [ - "+", - "#", - ".", - "/", - "?", - "&" - ].find((op) => expr.startsWith(op)) || ""; - } - getNames(expr) { - const operator = this.getOperator(expr); - return expr.slice(operator.length).split(",").map((name) => name.replace("*", "").trim()).filter((name) => name.length > 0); - } - encodeValue(value, operator) { - UriTemplate.validateLength(value, MAX_VARIABLE_LENGTH, "Variable value"); - if (operator === "+" || operator === "#") return encodeURI(value); - return encodeURIComponent(value); - } - expandPart(part, variables) { - if (part.operator === "?" || part.operator === "&") { - const pairs = part.names.map((name) => { - const value$1 = variables[name]; - if (value$1 === void 0) return ""; - return `${name}=${Array.isArray(value$1) ? value$1.map((v) => this.encodeValue(v, part.operator)).join(",") : this.encodeValue(value$1.toString(), part.operator)}`; - }).filter((pair) => pair.length > 0); - if (pairs.length === 0) return ""; - return (part.operator === "?" ? "?" : "&") + pairs.join("&"); - } - if (part.names.length > 1) { - const values = part.names.map((name) => variables[name]).filter((v) => v !== void 0); - if (values.length === 0) return ""; - return values.map((v) => Array.isArray(v) ? v[0] : v).join(","); - } - const value = variables[part.name]; - if (value === void 0) return ""; - const encoded = (Array.isArray(value) ? value : [value]).map((v) => this.encodeValue(v, part.operator)); - switch (part.operator) { - case "": return encoded.join(","); - case "+": return encoded.join(","); - case "#": return "#" + encoded.join(","); - case ".": return "." + encoded.join("."); - case "/": return "/" + encoded.join("/"); - default: return encoded.join(","); - } - } - expand(variables) { - let result = ""; - let hasQueryParam = false; - for (const part of this.parts) { - if (typeof part === "string") { - result += part; - continue; - } - const expanded = this.expandPart(part, variables); - if (!expanded) continue; - result += (part.operator === "?" || part.operator === "&") && hasQueryParam ? expanded.replace("?", "&") : expanded; - if (part.operator === "?" || part.operator === "&") hasQueryParam = true; - } - return result; - } - escapeRegExp(str) { - return str.replaceAll(/[.*+?^${}()|[\]\\]/g, String.raw`\$&`); - } - partToRegExp(part) { - const patterns = []; - for (const name$1 of part.names) UriTemplate.validateLength(name$1, MAX_VARIABLE_LENGTH, "Variable name"); - if (part.operator === "?" || part.operator === "&") { - for (let i = 0; i < part.names.length; i++) { - const name$1 = part.names[i]; - const prefix = i === 0 ? "\\" + part.operator : "&"; - patterns.push({ - pattern: prefix + this.escapeRegExp(name$1) + "=([^&]+)", - name: name$1 - }); - } - return patterns; - } - let pattern; - const name = part.name; - switch (part.operator) { - case "": - pattern = part.exploded ? "([^/,]+(?:,[^/,]+)*)" : "([^/,]+)"; - break; - case "+": - case "#": - pattern = "(.+)"; - break; - case ".": - pattern = String.raw`\.([^/,]+)`; - break; - case "/": - pattern = "/" + (part.exploded ? "([^/,]+(?:,[^/,]+)*)" : "([^/,]+)"); - break; - default: pattern = "([^/]+)"; - } - patterns.push({ - pattern, - name - }); - return patterns; - } - match(uri) { - UriTemplate.validateLength(uri, MAX_TEMPLATE_LENGTH, "URI"); - let pattern = "^"; - const names = []; - for (const part of this.parts) if (typeof part === "string") pattern += this.escapeRegExp(part); - else { - const patterns = this.partToRegExp(part); - for (const { pattern: partPattern, name } of patterns) { - pattern += partPattern; - names.push({ - name, - exploded: part.exploded - }); - } - } - pattern += "$"; - UriTemplate.validateLength(pattern, MAX_REGEX_LENGTH, "Generated regex pattern"); - const regex = new RegExp(pattern); - const match = uri.match(regex); - if (!match) return null; - const result = {}; - for (const [i, name_] of names.entries()) { - const { name, exploded } = name_; - const value = match[i + 1]; - const cleanName = name.replace("*", ""); - result[cleanName] = exploded && value.includes(",") ? value.split(",") : value; - } - return result; - } -}; - -//#endregion -//#region ../core-internal/src/util/inMemory.ts -/** -* In-memory transport for creating clients and servers that talk to each other within the same process. -* -* Intended for testing and development. For production in-process connections, use -* `StreamableHTTPClientTransport` against a local server URL. -*/ -var src_CX2iR2pK_InMemoryTransport = class InMemoryTransport { - _otherTransport; - _messageQueue = []; - _closed = false; - onclose; - onerror; - onmessage; - sessionId; - /** - * Creates a pair of linked in-memory transports that can communicate with each other. One should be passed to a {@linkcode @modelcontextprotocol/client!client/client.Client | Client} and one to a {@linkcode @modelcontextprotocol/server!server/server.Server | Server}. - */ - static createLinkedPair() { - const clientTransport = new InMemoryTransport(); - const serverTransport = new InMemoryTransport(); - clientTransport._otherTransport = serverTransport; - serverTransport._otherTransport = clientTransport; - return [clientTransport, serverTransport]; - } - async start() { - while (this._messageQueue.length > 0) { - const queuedMessage = this._messageQueue.shift(); - this.onmessage?.(queuedMessage.message, queuedMessage.extra); - } - } - async close() { - if (this._closed) return; - this._closed = true; - const other = this._otherTransport; - this._otherTransport = void 0; - try { - await other?.close(); - } finally { - this.onclose?.(); - } - } - /** - * Sends a message with optional auth info. - * This is useful for testing authentication scenarios. - */ - async send(message, options) { - if (!this._otherTransport) throw new src_CX2iR2pK_SdkError(src_CX2iR2pK_SdkErrorCode.NotConnected, "Not connected"); - if (this._otherTransport.onmessage) this._otherTransport.onmessage(message, { authInfo: options?.authInfo }); - else this._otherTransport._messageQueue.push({ - message, - extra: { authInfo: options?.authInfo } - }); - } -}; - -//#endregion -//#region ../core-internal/src/util/zodCompat.ts -/** -* Zod-specific helpers for the v1-compat raw-shape shorthand on -* `registerTool`/`registerPrompt`. Kept separate from `standardSchema.ts` so -* that file stays library-agnostic per the Standard Schema spec. -*/ -function isZodV4Schema(v) { - return typeof v === "object" && v !== null && "_zod" in v; -} -function looksLikeZodV3(v) { - return typeof v === "object" && v !== null && !("_zod" in v) && "_def" in v && typeof v._def?.typeName === "string"; -} -/** -* Detects a "raw shape" — a plain object whose values are Zod field schemas, -* e.g. `{ name: z.string() }`. Powers the auto-wrap in -* {@linkcode normalizeRawShapeSchema}, which wraps with `z.object()`, so only -* Zod values are supported. -* -* @internal -*/ -function isZodRawShape(obj) { - if (typeof obj !== "object" || obj === null) return false; - if (isStandardSchema(obj)) return false; - const proto = Object.getPrototypeOf(obj); - if (proto !== Object.prototype && proto !== null) return false; - return Object.values(obj).every((v) => isZodV4Schema(v)); -} -/** -* Accepts either a {@linkcode StandardSchemaWithJSON} or a raw Zod shape -* `{ field: z.string() }` and returns a {@linkcode StandardSchemaWithJSON}. -* Raw shapes are wrapped with `z.object()` so the rest of the pipeline sees a -* uniform schema type; already-wrapped schemas pass through unchanged. -* -* @internal -*/ -function normalizeRawShapeSchema(schema) { - if (schema === void 0) return void 0; - if (isZodRawShape(schema)) return schemas_object(schema); - if (typeof schema === "object" && schema !== null && !isStandardSchema(schema) && Object.values(schema).some((v) => looksLikeZodV3(v))) throw new TypeError("Raw-shape inputSchema/outputSchema/argsSchema fields must be Zod v4 schemas. Got a Zod v3 field schema. Import from `zod/v4` (or upgrade your zod import), or wrap with `z.object({...})` yourself."); - if (!isStandardSchema(schema)) throw new TypeError("inputSchema/outputSchema/argsSchema must be a Standard Schema (e.g. z.object({...})) or a raw Zod shape ({ field: z.string() })."); - return schema; -} - -//#endregion -//#region ../core-internal/src/wire/preload.ts -/** -* Explicit warm-up entry for the lazy wire-schema layers. -* -* The per-revision wire schemas are built lazily: each era's schema set sits -* behind a memoized factory (`buildSchemas2025`/`buildSchemas2026`), and the -* registry/codec lookup maps above those factories are memoized the same way. -* That laziness is the right default on process-per-invocation runtimes (CLI -* tools, dev servers), where module evaluation IS startup latency and most -* short-lived processes never validate a message on both eras. -* -* On platforms that bill request CPU but not module evaluation — isolate-based -* edge/serverless runtimes such as Cloudflare Workers — the trade inverts: -* module-scope work runs during isolate warm-up outside any request, while -* lazy construction lands inside the first request's billed (and latency -* budgeted) CPU. `preloadSchemas()` lets deployments on such platforms move -* the one-time construction cost back to module scope by calling it at module -* scope themselves. The packages' own workerd shims already do this, so -* Workers deployments get eager construction automatically. -*/ -/** -* Eagerly builds every lazily-constructed wire-schema layer, so that no later -* validation pays schema-construction cost. -* -* Synchronous and idempotent: every layer is a memo, so the first call does -* all the work and subsequent calls return immediately. Reference identity is -* unaffected — this forces the same memos every lazy consumer pulls through. -* -* Call it at module scope on platforms that bill per-request CPU but not -* module evaluation (isolate-based edge/serverless runtimes), where deferring -* construction would move it into the first request of every fresh isolate: -* -* ```ts -* // from '@modelcontextprotocol/server' or '@modelcontextprotocol/client' — -* // each package bundles its own schema copy, so warm the one(s) you import. -* preloadSchemas(); // module scope — runs during isolate warm-up -* ``` -* -* On Node CLIs and other process-per-invocation runtimes, prefer the lazy -* default — there, module-scope construction is pure added boot latency. -*/ -function preloadSchemas() { - buildSchemas2025(); - buildSchemas2026(); - warmRegistryMaps2025(); - warmInputSchemaMaps2026(); - warmWireResultSchemas2026(); -} - -//#endregion -//#region ../core-internal/src/validators/fromJsonSchema.ts -/** -* Wrap a raw JSON Schema object as a {@linkcode StandardSchemaWithJSON} so it can be -* passed to `registerTool` / `registerPrompt`. Use this when you already have JSON -* Schema (e.g. from TypeBox, or hand-written) and want to register it without going -* through a Standard Schema library. -* -* The callback arguments will be typed `unknown` (raw JSON Schema has no TypeScript -* types attached). Cast at the call site, or use the generic `fromJsonSchema(...)`. -* -* @param schema - A JSON Schema object describing the expected shape -* @param validator - A validator provider. When importing `fromJsonSchema` from -* `@modelcontextprotocol/server` or `@modelcontextprotocol/client`, a runtime-appropriate -* default is provided automatically (AJV on Node.js, CfWorker on edge runtimes). -* -* @example -* ```ts source="./fromJsonSchema.examples.ts#fromJsonSchema_basicUsage" -* const inputSchema = fromJsonSchema<{ name: string }>( -* { type: 'object', properties: { name: { type: 'string' } }, required: ['name'] }, -* validator -* ); -* // Use with server.registerTool('greet', { inputSchema }, handler) -* ``` -*/ -function fromJsonSchema(schema, validator) { - const check = validator.getValidator(schema); - return { "~standard": { - version: 1, - vendor: "mcp", - jsonSchema: { - input: () => schema, - output: () => schema - }, - validate: (data) => { - const result = check(data); - return result.valid ? { value: result.data } : { issues: [{ message: result.errorMessage }] }; - } - } }; -} - -//#endregion - -//# sourceMappingURL=src-CX2iR2pK.mjs.map - - - -//#region ../../node_modules/.pnpm/ajv@8.18.0/node_modules/ajv/dist/compile/codegen/code.js -var require_code$1 = /* @__PURE__ */ __commonJSMin(((exports) => { - Object.defineProperty(exports, "__esModule", { value: true }); - exports.regexpCode = exports.getEsmExportName = exports.getProperty = exports.safeStringify = exports.stringify = exports.strConcat = exports.addCodeArg = exports.str = exports._ = exports.nil = exports._Code = exports.Name = exports.IDENTIFIER = exports._CodeOrName = void 0; - var _CodeOrName = class {}; - exports._CodeOrName = _CodeOrName; - exports.IDENTIFIER = /^[a-z$_][a-z$_0-9]*$/i; - var Name = class extends _CodeOrName { - constructor(s) { - super(); - if (!exports.IDENTIFIER.test(s)) throw new Error("CodeGen: name must be a valid identifier"); - this.str = s; - } - toString() { - return this.str; - } - emptyStr() { - return false; - } - get names() { - return { [this.str]: 1 }; - } - }; - exports.Name = Name; - var _Code = class extends _CodeOrName { - constructor(code) { - super(); - this._items = typeof code === "string" ? [code] : code; - } - toString() { - return this.str; - } - emptyStr() { - if (this._items.length > 1) return false; - const item = this._items[0]; - return item === "" || item === "\"\""; - } - get str() { - var _a; - return (_a = this._str) !== null && _a !== void 0 ? _a : this._str = this._items.reduce((s, c) => `${s}${c}`, ""); - } - get names() { - var _a; - return (_a = this._names) !== null && _a !== void 0 ? _a : this._names = this._items.reduce((names, c) => { - if (c instanceof Name) names[c.str] = (names[c.str] || 0) + 1; - return names; - }, {}); - } - }; - exports._Code = _Code; - exports.nil = new _Code(""); - function _(strs, ...args) { - const code = [strs[0]]; - let i = 0; - while (i < args.length) { - addCodeArg(code, args[i]); - code.push(strs[++i]); - } - return new _Code(code); - } - exports._ = _; - const plus = new _Code("+"); - function str(strs, ...args) { - const expr = [safeStringify(strs[0])]; - let i = 0; - while (i < args.length) { - expr.push(plus); - addCodeArg(expr, args[i]); - expr.push(plus, safeStringify(strs[++i])); - } - optimize(expr); - return new _Code(expr); - } - exports.str = str; - function addCodeArg(code, arg) { - if (arg instanceof _Code) code.push(...arg._items); - else if (arg instanceof Name) code.push(arg); - else code.push(interpolate(arg)); - } - exports.addCodeArg = addCodeArg; - function optimize(expr) { - let i = 1; - while (i < expr.length - 1) { - if (expr[i] === plus) { - const res = mergeExprItems(expr[i - 1], expr[i + 1]); - if (res !== void 0) { - expr.splice(i - 1, 3, res); - continue; - } - expr[i++] = "+"; - } - i++; - } - } - function mergeExprItems(a, b) { - if (b === "\"\"") return a; - if (a === "\"\"") return b; - if (typeof a == "string") { - if (b instanceof Name || a[a.length - 1] !== "\"") return; - if (typeof b != "string") return `${a.slice(0, -1)}${b}"`; - if (b[0] === "\"") return a.slice(0, -1) + b.slice(1); - return; - } - if (typeof b == "string" && b[0] === "\"" && !(a instanceof Name)) return `"${a}${b.slice(1)}`; - } - function strConcat(c1, c2) { - return c2.emptyStr() ? c1 : c1.emptyStr() ? c2 : str`${c1}${c2}`; - } - exports.strConcat = strConcat; - function interpolate(x) { - return typeof x == "number" || typeof x == "boolean" || x === null ? x : safeStringify(Array.isArray(x) ? x.join(",") : x); - } - function stringify(x) { - return new _Code(safeStringify(x)); - } - exports.stringify = stringify; - function safeStringify(x) { - return JSON.stringify(x).replace(/\u2028/g, "\\u2028").replace(/\u2029/g, "\\u2029"); - } - exports.safeStringify = safeStringify; - function getProperty(key) { - return typeof key == "string" && exports.IDENTIFIER.test(key) ? new _Code(`.${key}`) : _`[${key}]`; - } - exports.getProperty = getProperty; - function getEsmExportName(key) { - if (typeof key == "string" && exports.IDENTIFIER.test(key)) return new _Code(`${key}`); - throw new Error(`CodeGen: invalid export name: ${key}, use explicit $id name mapping`); - } - exports.getEsmExportName = getEsmExportName; - function regexpCode(rx) { - return new _Code(rx.toString()); - } - exports.regexpCode = regexpCode; -})); - -//#endregion -//#region ../../node_modules/.pnpm/ajv@8.18.0/node_modules/ajv/dist/compile/codegen/scope.js -var require_scope = /* @__PURE__ */ __commonJSMin(((exports) => { - Object.defineProperty(exports, "__esModule", { value: true }); - exports.ValueScope = exports.ValueScopeName = exports.Scope = exports.varKinds = exports.UsedValueState = void 0; - const code_1 = require_code$1(); - var ValueError = class extends Error { - constructor(name) { - super(`CodeGen: "code" for ${name} not defined`); - this.value = name.value; - } - }; - var UsedValueState; - (function(UsedValueState) { - UsedValueState[UsedValueState["Started"] = 0] = "Started"; - UsedValueState[UsedValueState["Completed"] = 1] = "Completed"; - })(UsedValueState || (exports.UsedValueState = UsedValueState = {})); - exports.varKinds = { - const: new code_1.Name("const"), - let: new code_1.Name("let"), - var: new code_1.Name("var") - }; - var Scope = class { - constructor({ prefixes, parent } = {}) { - this._names = {}; - this._prefixes = prefixes; - this._parent = parent; - } - toName(nameOrPrefix) { - return nameOrPrefix instanceof code_1.Name ? nameOrPrefix : this.name(nameOrPrefix); - } - name(prefix) { - return new code_1.Name(this._newName(prefix)); - } - _newName(prefix) { - const ng = this._names[prefix] || this._nameGroup(prefix); - return `${prefix}${ng.index++}`; - } - _nameGroup(prefix) { - var _a, _b; - if (((_b = (_a = this._parent) === null || _a === void 0 ? void 0 : _a._prefixes) === null || _b === void 0 ? void 0 : _b.has(prefix)) || this._prefixes && !this._prefixes.has(prefix)) throw new Error(`CodeGen: prefix "${prefix}" is not allowed in this scope`); - return this._names[prefix] = { - prefix, - index: 0 - }; - } - }; - exports.Scope = Scope; - var ValueScopeName = class extends code_1.Name { - constructor(prefix, nameStr) { - super(nameStr); - this.prefix = prefix; - } - setValue(value, { property, itemIndex }) { - this.value = value; - this.scopePath = (0, code_1._)`.${new code_1.Name(property)}[${itemIndex}]`; - } - }; - exports.ValueScopeName = ValueScopeName; - const line = (0, code_1._)`\n`; - var ValueScope = class extends Scope { - constructor(opts) { - super(opts); - this._values = {}; - this._scope = opts.scope; - this.opts = { - ...opts, - _n: opts.lines ? line : code_1.nil - }; - } - get() { - return this._scope; - } - name(prefix) { - return new ValueScopeName(prefix, this._newName(prefix)); - } - value(nameOrPrefix, value) { - var _a; - if (value.ref === void 0) throw new Error("CodeGen: ref must be passed in value"); - const name = this.toName(nameOrPrefix); - const { prefix } = name; - const valueKey = (_a = value.key) !== null && _a !== void 0 ? _a : value.ref; - let vs = this._values[prefix]; - if (vs) { - const _name = vs.get(valueKey); - if (_name) return _name; - } else vs = this._values[prefix] = /* @__PURE__ */ new Map(); - vs.set(valueKey, name); - const s = this._scope[prefix] || (this._scope[prefix] = []); - const itemIndex = s.length; - s[itemIndex] = value.ref; - name.setValue(value, { - property: prefix, - itemIndex - }); - return name; - } - getValue(prefix, keyOrRef) { - const vs = this._values[prefix]; - if (!vs) return; - return vs.get(keyOrRef); - } - scopeRefs(scopeName, values = this._values) { - return this._reduceValues(values, (name) => { - if (name.scopePath === void 0) throw new Error(`CodeGen: name "${name}" has no value`); - return (0, code_1._)`${scopeName}${name.scopePath}`; - }); - } - scopeCode(values = this._values, usedValues, getCode) { - return this._reduceValues(values, (name) => { - if (name.value === void 0) throw new Error(`CodeGen: name "${name}" has no value`); - return name.value.code; - }, usedValues, getCode); - } - _reduceValues(values, valueCode, usedValues = {}, getCode) { - let code = code_1.nil; - for (const prefix in values) { - const vs = values[prefix]; - if (!vs) continue; - const nameSet = usedValues[prefix] = usedValues[prefix] || /* @__PURE__ */ new Map(); - vs.forEach((name) => { - if (nameSet.has(name)) return; - nameSet.set(name, UsedValueState.Started); - let c = valueCode(name); - if (c) { - const def = this.opts.es5 ? exports.varKinds.var : exports.varKinds.const; - code = (0, code_1._)`${code}${def} ${name} = ${c};${this.opts._n}`; - } else if (c = getCode === null || getCode === void 0 ? void 0 : getCode(name)) code = (0, code_1._)`${code}${c}${this.opts._n}`; - else throw new ValueError(name); - nameSet.set(name, UsedValueState.Completed); - }); - } - return code; - } - }; - exports.ValueScope = ValueScope; -})); - -//#endregion -//#region ../../node_modules/.pnpm/ajv@8.18.0/node_modules/ajv/dist/compile/codegen/index.js -var require_codegen = /* @__PURE__ */ __commonJSMin(((exports) => { - Object.defineProperty(exports, "__esModule", { value: true }); - exports.or = exports.and = exports.not = exports.CodeGen = exports.operators = exports.varKinds = exports.ValueScopeName = exports.ValueScope = exports.Scope = exports.Name = exports.regexpCode = exports.stringify = exports.getProperty = exports.nil = exports.strConcat = exports.str = exports._ = void 0; - const code_1 = require_code$1(); - const scope_1 = require_scope(); - var code_2 = require_code$1(); - Object.defineProperty(exports, "_", { - enumerable: true, - get: function() { - return code_2._; - } - }); - Object.defineProperty(exports, "str", { - enumerable: true, - get: function() { - return code_2.str; - } - }); - Object.defineProperty(exports, "strConcat", { - enumerable: true, - get: function() { - return code_2.strConcat; - } - }); - Object.defineProperty(exports, "nil", { - enumerable: true, - get: function() { - return code_2.nil; - } - }); - Object.defineProperty(exports, "getProperty", { - enumerable: true, - get: function() { - return code_2.getProperty; - } - }); - Object.defineProperty(exports, "stringify", { - enumerable: true, - get: function() { - return code_2.stringify; - } - }); - Object.defineProperty(exports, "regexpCode", { - enumerable: true, - get: function() { - return code_2.regexpCode; - } - }); - Object.defineProperty(exports, "Name", { - enumerable: true, - get: function() { - return code_2.Name; - } - }); - var scope_2 = require_scope(); - Object.defineProperty(exports, "Scope", { - enumerable: true, - get: function() { - return scope_2.Scope; - } - }); - Object.defineProperty(exports, "ValueScope", { - enumerable: true, - get: function() { - return scope_2.ValueScope; - } - }); - Object.defineProperty(exports, "ValueScopeName", { - enumerable: true, - get: function() { - return scope_2.ValueScopeName; - } - }); - Object.defineProperty(exports, "varKinds", { - enumerable: true, - get: function() { - return scope_2.varKinds; - } - }); - exports.operators = { - GT: new code_1._Code(">"), - GTE: new code_1._Code(">="), - LT: new code_1._Code("<"), - LTE: new code_1._Code("<="), - EQ: new code_1._Code("==="), - NEQ: new code_1._Code("!=="), - NOT: new code_1._Code("!"), - OR: new code_1._Code("||"), - AND: new code_1._Code("&&"), - ADD: new code_1._Code("+") - }; - var Node = class { - optimizeNodes() { - return this; - } - optimizeNames(_names, _constants) { - return this; - } - }; - var Def = class extends Node { - constructor(varKind, name, rhs) { - super(); - this.varKind = varKind; - this.name = name; - this.rhs = rhs; - } - render({ es5, _n }) { - const varKind = es5 ? scope_1.varKinds.var : this.varKind; - const rhs = this.rhs === void 0 ? "" : ` = ${this.rhs}`; - return `${varKind} ${this.name}${rhs};` + _n; - } - optimizeNames(names, constants) { - if (!names[this.name.str]) return; - if (this.rhs) this.rhs = optimizeExpr(this.rhs, names, constants); - return this; - } - get names() { - return this.rhs instanceof code_1._CodeOrName ? this.rhs.names : {}; - } - }; - var Assign = class extends Node { - constructor(lhs, rhs, sideEffects) { - super(); - this.lhs = lhs; - this.rhs = rhs; - this.sideEffects = sideEffects; - } - render({ _n }) { - return `${this.lhs} = ${this.rhs};` + _n; - } - optimizeNames(names, constants) { - if (this.lhs instanceof code_1.Name && !names[this.lhs.str] && !this.sideEffects) return; - this.rhs = optimizeExpr(this.rhs, names, constants); - return this; - } - get names() { - return addExprNames(this.lhs instanceof code_1.Name ? {} : { ...this.lhs.names }, this.rhs); - } - }; - var AssignOp = class extends Assign { - constructor(lhs, op, rhs, sideEffects) { - super(lhs, rhs, sideEffects); - this.op = op; - } - render({ _n }) { - return `${this.lhs} ${this.op}= ${this.rhs};` + _n; - } - }; - var Label = class extends Node { - constructor(label) { - super(); - this.label = label; - this.names = {}; - } - render({ _n }) { - return `${this.label}:` + _n; - } - }; - var Break = class extends Node { - constructor(label) { - super(); - this.label = label; - this.names = {}; - } - render({ _n }) { - return `break${this.label ? ` ${this.label}` : ""};` + _n; - } - }; - var Throw = class extends Node { - constructor(error) { - super(); - this.error = error; - } - render({ _n }) { - return `throw ${this.error};` + _n; - } - get names() { - return this.error.names; - } - }; - var AnyCode = class extends Node { - constructor(code) { - super(); - this.code = code; - } - render({ _n }) { - return `${this.code};` + _n; - } - optimizeNodes() { - return `${this.code}` ? this : void 0; - } - optimizeNames(names, constants) { - this.code = optimizeExpr(this.code, names, constants); - return this; - } - get names() { - return this.code instanceof code_1._CodeOrName ? this.code.names : {}; - } - }; - var ParentNode = class extends Node { - constructor(nodes = []) { - super(); - this.nodes = nodes; - } - render(opts) { - return this.nodes.reduce((code, n) => code + n.render(opts), ""); - } - optimizeNodes() { - const { nodes } = this; - let i = nodes.length; - while (i--) { - const n = nodes[i].optimizeNodes(); - if (Array.isArray(n)) nodes.splice(i, 1, ...n); - else if (n) nodes[i] = n; - else nodes.splice(i, 1); - } - return nodes.length > 0 ? this : void 0; - } - optimizeNames(names, constants) { - const { nodes } = this; - let i = nodes.length; - while (i--) { - const n = nodes[i]; - if (n.optimizeNames(names, constants)) continue; - subtractNames(names, n.names); - nodes.splice(i, 1); - } - return nodes.length > 0 ? this : void 0; - } - get names() { - return this.nodes.reduce((names, n) => addNames(names, n.names), {}); - } - }; - var BlockNode = class extends ParentNode { - render(opts) { - return "{" + opts._n + super.render(opts) + "}" + opts._n; - } - }; - var Root = class extends ParentNode {}; - var Else = class extends BlockNode {}; - Else.kind = "else"; - var If = class If extends BlockNode { - constructor(condition, nodes) { - super(nodes); - this.condition = condition; - } - render(opts) { - let code = `if(${this.condition})` + super.render(opts); - if (this.else) code += "else " + this.else.render(opts); - return code; - } - optimizeNodes() { - super.optimizeNodes(); - const cond = this.condition; - if (cond === true) return this.nodes; - let e = this.else; - if (e) { - const ns = e.optimizeNodes(); - e = this.else = Array.isArray(ns) ? new Else(ns) : ns; - } - if (e) { - if (cond === false) return e instanceof If ? e : e.nodes; - if (this.nodes.length) return this; - return new If(not(cond), e instanceof If ? [e] : e.nodes); - } - if (cond === false || !this.nodes.length) return void 0; - return this; - } - optimizeNames(names, constants) { - var _a; - this.else = (_a = this.else) === null || _a === void 0 ? void 0 : _a.optimizeNames(names, constants); - if (!(super.optimizeNames(names, constants) || this.else)) return; - this.condition = optimizeExpr(this.condition, names, constants); - return this; - } - get names() { - const names = super.names; - addExprNames(names, this.condition); - if (this.else) addNames(names, this.else.names); - return names; - } - }; - If.kind = "if"; - var For = class extends BlockNode {}; - For.kind = "for"; - var ForLoop = class extends For { - constructor(iteration) { - super(); - this.iteration = iteration; - } - render(opts) { - return `for(${this.iteration})` + super.render(opts); - } - optimizeNames(names, constants) { - if (!super.optimizeNames(names, constants)) return; - this.iteration = optimizeExpr(this.iteration, names, constants); - return this; - } - get names() { - return addNames(super.names, this.iteration.names); - } - }; - var ForRange = class extends For { - constructor(varKind, name, from, to) { - super(); - this.varKind = varKind; - this.name = name; - this.from = from; - this.to = to; - } - render(opts) { - const varKind = opts.es5 ? scope_1.varKinds.var : this.varKind; - const { name, from, to } = this; - return `for(${varKind} ${name}=${from}; ${name}<${to}; ${name}++)` + super.render(opts); - } - get names() { - return addExprNames(addExprNames(super.names, this.from), this.to); - } - }; - var ForIter = class extends For { - constructor(loop, varKind, name, iterable) { - super(); - this.loop = loop; - this.varKind = varKind; - this.name = name; - this.iterable = iterable; - } - render(opts) { - return `for(${this.varKind} ${this.name} ${this.loop} ${this.iterable})` + super.render(opts); - } - optimizeNames(names, constants) { - if (!super.optimizeNames(names, constants)) return; - this.iterable = optimizeExpr(this.iterable, names, constants); - return this; - } - get names() { - return addNames(super.names, this.iterable.names); - } - }; - var Func = class extends BlockNode { - constructor(name, args, async) { - super(); - this.name = name; - this.args = args; - this.async = async; - } - render(opts) { - return `${this.async ? "async " : ""}function ${this.name}(${this.args})` + super.render(opts); - } - }; - Func.kind = "func"; - var Return = class extends ParentNode { - render(opts) { - return "return " + super.render(opts); - } - }; - Return.kind = "return"; - var Try = class extends BlockNode { - render(opts) { - let code = "try" + super.render(opts); - if (this.catch) code += this.catch.render(opts); - if (this.finally) code += this.finally.render(opts); - return code; - } - optimizeNodes() { - var _a, _b; - super.optimizeNodes(); - (_a = this.catch) === null || _a === void 0 || _a.optimizeNodes(); - (_b = this.finally) === null || _b === void 0 || _b.optimizeNodes(); - return this; - } - optimizeNames(names, constants) { - var _a, _b; - super.optimizeNames(names, constants); - (_a = this.catch) === null || _a === void 0 || _a.optimizeNames(names, constants); - (_b = this.finally) === null || _b === void 0 || _b.optimizeNames(names, constants); - return this; - } - get names() { - const names = super.names; - if (this.catch) addNames(names, this.catch.names); - if (this.finally) addNames(names, this.finally.names); - return names; - } - }; - var Catch = class extends BlockNode { - constructor(error) { - super(); - this.error = error; - } - render(opts) { - return `catch(${this.error})` + super.render(opts); - } - }; - Catch.kind = "catch"; - var Finally = class extends BlockNode { - render(opts) { - return "finally" + super.render(opts); - } - }; - Finally.kind = "finally"; - var CodeGen = class { - constructor(extScope, opts = {}) { - this._values = {}; - this._blockStarts = []; - this._constants = {}; - this.opts = { - ...opts, - _n: opts.lines ? "\n" : "" - }; - this._extScope = extScope; - this._scope = new scope_1.Scope({ parent: extScope }); - this._nodes = [new Root()]; - } - toString() { - return this._root.render(this.opts); - } - name(prefix) { - return this._scope.name(prefix); - } - scopeName(prefix) { - return this._extScope.name(prefix); - } - scopeValue(prefixOrName, value) { - const name = this._extScope.value(prefixOrName, value); - (this._values[name.prefix] || (this._values[name.prefix] = /* @__PURE__ */ new Set())).add(name); - return name; - } - getScopeValue(prefix, keyOrRef) { - return this._extScope.getValue(prefix, keyOrRef); - } - scopeRefs(scopeName) { - return this._extScope.scopeRefs(scopeName, this._values); - } - scopeCode() { - return this._extScope.scopeCode(this._values); - } - _def(varKind, nameOrPrefix, rhs, constant) { - const name = this._scope.toName(nameOrPrefix); - if (rhs !== void 0 && constant) this._constants[name.str] = rhs; - this._leafNode(new Def(varKind, name, rhs)); - return name; - } - const(nameOrPrefix, rhs, _constant) { - return this._def(scope_1.varKinds.const, nameOrPrefix, rhs, _constant); - } - let(nameOrPrefix, rhs, _constant) { - return this._def(scope_1.varKinds.let, nameOrPrefix, rhs, _constant); - } - var(nameOrPrefix, rhs, _constant) { - return this._def(scope_1.varKinds.var, nameOrPrefix, rhs, _constant); - } - assign(lhs, rhs, sideEffects) { - return this._leafNode(new Assign(lhs, rhs, sideEffects)); - } - add(lhs, rhs) { - return this._leafNode(new AssignOp(lhs, exports.operators.ADD, rhs)); - } - code(c) { - if (typeof c == "function") c(); - else if (c !== code_1.nil) this._leafNode(new AnyCode(c)); - return this; - } - object(...keyValues) { - const code = ["{"]; - for (const [key, value] of keyValues) { - if (code.length > 1) code.push(","); - code.push(key); - if (key !== value || this.opts.es5) { - code.push(":"); - (0, code_1.addCodeArg)(code, value); - } - } - code.push("}"); - return new code_1._Code(code); - } - if(condition, thenBody, elseBody) { - this._blockNode(new If(condition)); - if (thenBody && elseBody) this.code(thenBody).else().code(elseBody).endIf(); - else if (thenBody) this.code(thenBody).endIf(); - else if (elseBody) throw new Error("CodeGen: \"else\" body without \"then\" body"); - return this; - } - elseIf(condition) { - return this._elseNode(new If(condition)); - } - else() { - return this._elseNode(new Else()); - } - endIf() { - return this._endBlockNode(If, Else); - } - _for(node, forBody) { - this._blockNode(node); - if (forBody) this.code(forBody).endFor(); - return this; - } - for(iteration, forBody) { - return this._for(new ForLoop(iteration), forBody); - } - forRange(nameOrPrefix, from, to, forBody, varKind = this.opts.es5 ? scope_1.varKinds.var : scope_1.varKinds.let) { - const name = this._scope.toName(nameOrPrefix); - return this._for(new ForRange(varKind, name, from, to), () => forBody(name)); - } - forOf(nameOrPrefix, iterable, forBody, varKind = scope_1.varKinds.const) { - const name = this._scope.toName(nameOrPrefix); - if (this.opts.es5) { - const arr = iterable instanceof code_1.Name ? iterable : this.var("_arr", iterable); - return this.forRange("_i", 0, (0, code_1._)`${arr}.length`, (i) => { - this.var(name, (0, code_1._)`${arr}[${i}]`); - forBody(name); - }); - } - return this._for(new ForIter("of", varKind, name, iterable), () => forBody(name)); - } - forIn(nameOrPrefix, obj, forBody, varKind = this.opts.es5 ? scope_1.varKinds.var : scope_1.varKinds.const) { - if (this.opts.ownProperties) return this.forOf(nameOrPrefix, (0, code_1._)`Object.keys(${obj})`, forBody); - const name = this._scope.toName(nameOrPrefix); - return this._for(new ForIter("in", varKind, name, obj), () => forBody(name)); - } - endFor() { - return this._endBlockNode(For); - } - label(label) { - return this._leafNode(new Label(label)); - } - break(label) { - return this._leafNode(new Break(label)); - } - return(value) { - const node = new Return(); - this._blockNode(node); - this.code(value); - if (node.nodes.length !== 1) throw new Error("CodeGen: \"return\" should have one node"); - return this._endBlockNode(Return); - } - try(tryBody, catchCode, finallyCode) { - if (!catchCode && !finallyCode) throw new Error("CodeGen: \"try\" without \"catch\" and \"finally\""); - const node = new Try(); - this._blockNode(node); - this.code(tryBody); - if (catchCode) { - const error = this.name("e"); - this._currNode = node.catch = new Catch(error); - catchCode(error); - } - if (finallyCode) { - this._currNode = node.finally = new Finally(); - this.code(finallyCode); - } - return this._endBlockNode(Catch, Finally); - } - throw(error) { - return this._leafNode(new Throw(error)); - } - block(body, nodeCount) { - this._blockStarts.push(this._nodes.length); - if (body) this.code(body).endBlock(nodeCount); - return this; - } - endBlock(nodeCount) { - const len = this._blockStarts.pop(); - if (len === void 0) throw new Error("CodeGen: not in self-balancing block"); - const toClose = this._nodes.length - len; - if (toClose < 0 || nodeCount !== void 0 && toClose !== nodeCount) throw new Error(`CodeGen: wrong number of nodes: ${toClose} vs ${nodeCount} expected`); - this._nodes.length = len; - return this; - } - func(name, args = code_1.nil, async, funcBody) { - this._blockNode(new Func(name, args, async)); - if (funcBody) this.code(funcBody).endFunc(); - return this; - } - endFunc() { - return this._endBlockNode(Func); - } - optimize(n = 1) { - while (n-- > 0) { - this._root.optimizeNodes(); - this._root.optimizeNames(this._root.names, this._constants); - } - } - _leafNode(node) { - this._currNode.nodes.push(node); - return this; - } - _blockNode(node) { - this._currNode.nodes.push(node); - this._nodes.push(node); - } - _endBlockNode(N1, N2) { - const n = this._currNode; - if (n instanceof N1 || N2 && n instanceof N2) { - this._nodes.pop(); - return this; - } - throw new Error(`CodeGen: not in block "${N2 ? `${N1.kind}/${N2.kind}` : N1.kind}"`); - } - _elseNode(node) { - const n = this._currNode; - if (!(n instanceof If)) throw new Error("CodeGen: \"else\" without \"if\""); - this._currNode = n.else = node; - return this; - } - get _root() { - return this._nodes[0]; - } - get _currNode() { - const ns = this._nodes; - return ns[ns.length - 1]; - } - set _currNode(node) { - const ns = this._nodes; - ns[ns.length - 1] = node; - } - }; - exports.CodeGen = CodeGen; - function addNames(names, from) { - for (const n in from) names[n] = (names[n] || 0) + (from[n] || 0); - return names; - } - function addExprNames(names, from) { - return from instanceof code_1._CodeOrName ? addNames(names, from.names) : names; - } - function optimizeExpr(expr, names, constants) { - if (expr instanceof code_1.Name) return replaceName(expr); - if (!canOptimize(expr)) return expr; - return new code_1._Code(expr._items.reduce((items, c) => { - if (c instanceof code_1.Name) c = replaceName(c); - if (c instanceof code_1._Code) items.push(...c._items); - else items.push(c); - return items; - }, [])); - function replaceName(n) { - const c = constants[n.str]; - if (c === void 0 || names[n.str] !== 1) return n; - delete names[n.str]; - return c; - } - function canOptimize(e) { - return e instanceof code_1._Code && e._items.some((c) => c instanceof code_1.Name && names[c.str] === 1 && constants[c.str] !== void 0); - } - } - function subtractNames(names, from) { - for (const n in from) names[n] = (names[n] || 0) - (from[n] || 0); - } - function not(x) { - return typeof x == "boolean" || typeof x == "number" || x === null ? !x : (0, code_1._)`!${par(x)}`; - } - exports.not = not; - const andCode = mappend(exports.operators.AND); - function and(...args) { - return args.reduce(andCode); - } - exports.and = and; - const orCode = mappend(exports.operators.OR); - function or(...args) { - return args.reduce(orCode); - } - exports.or = or; - function mappend(op) { - return (x, y) => x === code_1.nil ? y : y === code_1.nil ? x : (0, code_1._)`${par(x)} ${op} ${par(y)}`; - } - function par(x) { - return x instanceof code_1.Name ? x : (0, code_1._)`(${x})`; - } -})); - -//#endregion -//#region ../../node_modules/.pnpm/ajv@8.18.0/node_modules/ajv/dist/compile/util.js -var require_util = /* @__PURE__ */ __commonJSMin(((exports) => { - Object.defineProperty(exports, "__esModule", { value: true }); - exports.checkStrictMode = exports.getErrorPath = exports.Type = exports.useFunc = exports.setEvaluated = exports.evaluatedPropsToName = exports.mergeEvaluated = exports.eachItem = exports.unescapeJsonPointer = exports.escapeJsonPointer = exports.escapeFragment = exports.unescapeFragment = exports.schemaRefOrVal = exports.schemaHasRulesButRef = exports.schemaHasRules = exports.checkUnknownRules = exports.alwaysValidSchema = exports.toHash = void 0; - const codegen_1 = require_codegen(); - const code_1 = require_code$1(); - function toHash(arr) { - const hash = {}; - for (const item of arr) hash[item] = true; - return hash; - } - exports.toHash = toHash; - function alwaysValidSchema(it, schema) { - if (typeof schema == "boolean") return schema; - if (Object.keys(schema).length === 0) return true; - checkUnknownRules(it, schema); - return !schemaHasRules(schema, it.self.RULES.all); - } - exports.alwaysValidSchema = alwaysValidSchema; - function checkUnknownRules(it, schema = it.schema) { - const { opts, self } = it; - if (!opts.strictSchema) return; - if (typeof schema === "boolean") return; - const rules = self.RULES.keywords; - for (const key in schema) if (!rules[key]) checkStrictMode(it, `unknown keyword: "${key}"`); - } - exports.checkUnknownRules = checkUnknownRules; - function schemaHasRules(schema, rules) { - if (typeof schema == "boolean") return !schema; - for (const key in schema) if (rules[key]) return true; - return false; - } - exports.schemaHasRules = schemaHasRules; - function schemaHasRulesButRef(schema, RULES) { - if (typeof schema == "boolean") return !schema; - for (const key in schema) if (key !== "$ref" && RULES.all[key]) return true; - return false; - } - exports.schemaHasRulesButRef = schemaHasRulesButRef; - function schemaRefOrVal({ topSchemaRef, schemaPath }, schema, keyword, $data) { - if (!$data) { - if (typeof schema == "number" || typeof schema == "boolean") return schema; - if (typeof schema == "string") return (0, codegen_1._)`${schema}`; - } - return (0, codegen_1._)`${topSchemaRef}${schemaPath}${(0, codegen_1.getProperty)(keyword)}`; - } - exports.schemaRefOrVal = schemaRefOrVal; - function unescapeFragment(str) { - return unescapeJsonPointer(decodeURIComponent(str)); - } - exports.unescapeFragment = unescapeFragment; - function escapeFragment(str) { - return encodeURIComponent(escapeJsonPointer(str)); - } - exports.escapeFragment = escapeFragment; - function escapeJsonPointer(str) { - if (typeof str == "number") return `${str}`; - return str.replace(/~/g, "~0").replace(/\//g, "~1"); - } - exports.escapeJsonPointer = escapeJsonPointer; - function unescapeJsonPointer(str) { - return str.replace(/~1/g, "/").replace(/~0/g, "~"); - } - exports.unescapeJsonPointer = unescapeJsonPointer; - function eachItem(xs, f) { - if (Array.isArray(xs)) for (const x of xs) f(x); - else f(xs); - } - exports.eachItem = eachItem; - function makeMergeEvaluated({ mergeNames, mergeToName, mergeValues, resultToName }) { - return (gen, from, to, toName) => { - const res = to === void 0 ? from : to instanceof codegen_1.Name ? (from instanceof codegen_1.Name ? mergeNames(gen, from, to) : mergeToName(gen, from, to), to) : from instanceof codegen_1.Name ? (mergeToName(gen, to, from), from) : mergeValues(from, to); - return toName === codegen_1.Name && !(res instanceof codegen_1.Name) ? resultToName(gen, res) : res; - }; - } - exports.mergeEvaluated = { - props: makeMergeEvaluated({ - mergeNames: (gen, from, to) => gen.if((0, codegen_1._)`${to} !== true && ${from} !== undefined`, () => { - gen.if((0, codegen_1._)`${from} === true`, () => gen.assign(to, true), () => gen.assign(to, (0, codegen_1._)`${to} || {}`).code((0, codegen_1._)`Object.assign(${to}, ${from})`)); - }), - mergeToName: (gen, from, to) => gen.if((0, codegen_1._)`${to} !== true`, () => { - if (from === true) gen.assign(to, true); - else { - gen.assign(to, (0, codegen_1._)`${to} || {}`); - setEvaluated(gen, to, from); - } - }), - mergeValues: (from, to) => from === true ? true : { - ...from, - ...to - }, - resultToName: evaluatedPropsToName - }), - items: makeMergeEvaluated({ - mergeNames: (gen, from, to) => gen.if((0, codegen_1._)`${to} !== true && ${from} !== undefined`, () => gen.assign(to, (0, codegen_1._)`${from} === true ? true : ${to} > ${from} ? ${to} : ${from}`)), - mergeToName: (gen, from, to) => gen.if((0, codegen_1._)`${to} !== true`, () => gen.assign(to, from === true ? true : (0, codegen_1._)`${to} > ${from} ? ${to} : ${from}`)), - mergeValues: (from, to) => from === true ? true : Math.max(from, to), - resultToName: (gen, items) => gen.var("items", items) - }) - }; - function evaluatedPropsToName(gen, ps) { - if (ps === true) return gen.var("props", true); - const props = gen.var("props", (0, codegen_1._)`{}`); - if (ps !== void 0) setEvaluated(gen, props, ps); - return props; - } - exports.evaluatedPropsToName = evaluatedPropsToName; - function setEvaluated(gen, props, ps) { - Object.keys(ps).forEach((p) => gen.assign((0, codegen_1._)`${props}${(0, codegen_1.getProperty)(p)}`, true)); - } - exports.setEvaluated = setEvaluated; - const snippets = {}; - function useFunc(gen, f) { - return gen.scopeValue("func", { - ref: f, - code: snippets[f.code] || (snippets[f.code] = new code_1._Code(f.code)) - }); - } - exports.useFunc = useFunc; - var Type; - (function(Type) { - Type[Type["Num"] = 0] = "Num"; - Type[Type["Str"] = 1] = "Str"; - })(Type || (exports.Type = Type = {})); - function getErrorPath(dataProp, dataPropType, jsPropertySyntax) { - if (dataProp instanceof codegen_1.Name) { - const isNumber = dataPropType === Type.Num; - return jsPropertySyntax ? isNumber ? (0, codegen_1._)`"[" + ${dataProp} + "]"` : (0, codegen_1._)`"['" + ${dataProp} + "']"` : isNumber ? (0, codegen_1._)`"/" + ${dataProp}` : (0, codegen_1._)`"/" + ${dataProp}.replace(/~/g, "~0").replace(/\\//g, "~1")`; - } - return jsPropertySyntax ? (0, codegen_1.getProperty)(dataProp).toString() : "/" + escapeJsonPointer(dataProp); - } - exports.getErrorPath = getErrorPath; - function checkStrictMode(it, msg, mode = it.opts.strictSchema) { - if (!mode) return; - msg = `strict mode: ${msg}`; - if (mode === true) throw new Error(msg); - it.self.logger.warn(msg); - } - exports.checkStrictMode = checkStrictMode; -})); - -//#endregion -//#region ../../node_modules/.pnpm/ajv@8.18.0/node_modules/ajv/dist/compile/names.js -var require_names = /* @__PURE__ */ __commonJSMin(((exports) => { - Object.defineProperty(exports, "__esModule", { value: true }); - const codegen_1 = require_codegen(); - const names = { - data: new codegen_1.Name("data"), - valCxt: new codegen_1.Name("valCxt"), - instancePath: new codegen_1.Name("instancePath"), - parentData: new codegen_1.Name("parentData"), - parentDataProperty: new codegen_1.Name("parentDataProperty"), - rootData: new codegen_1.Name("rootData"), - dynamicAnchors: new codegen_1.Name("dynamicAnchors"), - vErrors: new codegen_1.Name("vErrors"), - errors: new codegen_1.Name("errors"), - this: new codegen_1.Name("this"), - self: new codegen_1.Name("self"), - scope: new codegen_1.Name("scope"), - json: new codegen_1.Name("json"), - jsonPos: new codegen_1.Name("jsonPos"), - jsonLen: new codegen_1.Name("jsonLen"), - jsonPart: new codegen_1.Name("jsonPart") - }; - exports.default = names; -})); - -//#endregion -//#region ../../node_modules/.pnpm/ajv@8.18.0/node_modules/ajv/dist/compile/errors.js -var require_errors = /* @__PURE__ */ __commonJSMin(((exports) => { - Object.defineProperty(exports, "__esModule", { value: true }); - exports.extendErrors = exports.resetErrorsCount = exports.reportExtraError = exports.reportError = exports.keyword$DataError = exports.keywordError = void 0; - const codegen_1 = require_codegen(); - const util_1 = require_util(); - const names_1 = require_names(); - exports.keywordError = { message: ({ keyword }) => (0, codegen_1.str)`must pass "${keyword}" keyword validation` }; - exports.keyword$DataError = { message: ({ keyword, schemaType }) => schemaType ? (0, codegen_1.str)`"${keyword}" keyword must be ${schemaType} ($data)` : (0, codegen_1.str)`"${keyword}" keyword is invalid ($data)` }; - function reportError(cxt, error = exports.keywordError, errorPaths, overrideAllErrors) { - const { it } = cxt; - const { gen, compositeRule, allErrors } = it; - const errObj = errorObjectCode(cxt, error, errorPaths); - if (overrideAllErrors !== null && overrideAllErrors !== void 0 ? overrideAllErrors : compositeRule || allErrors) addError(gen, errObj); - else returnErrors(it, (0, codegen_1._)`[${errObj}]`); - } - exports.reportError = reportError; - function reportExtraError(cxt, error = exports.keywordError, errorPaths) { - const { it } = cxt; - const { gen, compositeRule, allErrors } = it; - addError(gen, errorObjectCode(cxt, error, errorPaths)); - if (!(compositeRule || allErrors)) returnErrors(it, names_1.default.vErrors); - } - exports.reportExtraError = reportExtraError; - function resetErrorsCount(gen, errsCount) { - gen.assign(names_1.default.errors, errsCount); - gen.if((0, codegen_1._)`${names_1.default.vErrors} !== null`, () => gen.if(errsCount, () => gen.assign((0, codegen_1._)`${names_1.default.vErrors}.length`, errsCount), () => gen.assign(names_1.default.vErrors, null))); - } - exports.resetErrorsCount = resetErrorsCount; - function extendErrors({ gen, keyword, schemaValue, data, errsCount, it }) { - /* istanbul ignore if */ - if (errsCount === void 0) throw new Error("ajv implementation error"); - const err = gen.name("err"); - gen.forRange("i", errsCount, names_1.default.errors, (i) => { - gen.const(err, (0, codegen_1._)`${names_1.default.vErrors}[${i}]`); - gen.if((0, codegen_1._)`${err}.instancePath === undefined`, () => gen.assign((0, codegen_1._)`${err}.instancePath`, (0, codegen_1.strConcat)(names_1.default.instancePath, it.errorPath))); - gen.assign((0, codegen_1._)`${err}.schemaPath`, (0, codegen_1.str)`${it.errSchemaPath}/${keyword}`); - if (it.opts.verbose) { - gen.assign((0, codegen_1._)`${err}.schema`, schemaValue); - gen.assign((0, codegen_1._)`${err}.data`, data); - } - }); - } - exports.extendErrors = extendErrors; - function addError(gen, errObj) { - const err = gen.const("err", errObj); - gen.if((0, codegen_1._)`${names_1.default.vErrors} === null`, () => gen.assign(names_1.default.vErrors, (0, codegen_1._)`[${err}]`), (0, codegen_1._)`${names_1.default.vErrors}.push(${err})`); - gen.code((0, codegen_1._)`${names_1.default.errors}++`); - } - function returnErrors(it, errs) { - const { gen, validateName, schemaEnv } = it; - if (schemaEnv.$async) gen.throw((0, codegen_1._)`new ${it.ValidationError}(${errs})`); - else { - gen.assign((0, codegen_1._)`${validateName}.errors`, errs); - gen.return(false); - } - } - const E = { - keyword: new codegen_1.Name("keyword"), - schemaPath: new codegen_1.Name("schemaPath"), - params: new codegen_1.Name("params"), - propertyName: new codegen_1.Name("propertyName"), - message: new codegen_1.Name("message"), - schema: new codegen_1.Name("schema"), - parentSchema: new codegen_1.Name("parentSchema") - }; - function errorObjectCode(cxt, error, errorPaths) { - const { createErrors } = cxt.it; - if (createErrors === false) return (0, codegen_1._)`{}`; - return errorObject(cxt, error, errorPaths); - } - function errorObject(cxt, error, errorPaths = {}) { - const { gen, it } = cxt; - const keyValues = [errorInstancePath(it, errorPaths), errorSchemaPath(cxt, errorPaths)]; - extraErrorProps(cxt, error, keyValues); - return gen.object(...keyValues); - } - function errorInstancePath({ errorPath }, { instancePath }) { - const instPath = instancePath ? (0, codegen_1.str)`${errorPath}${(0, util_1.getErrorPath)(instancePath, util_1.Type.Str)}` : errorPath; - return [names_1.default.instancePath, (0, codegen_1.strConcat)(names_1.default.instancePath, instPath)]; - } - function errorSchemaPath({ keyword, it: { errSchemaPath } }, { schemaPath, parentSchema }) { - let schPath = parentSchema ? errSchemaPath : (0, codegen_1.str)`${errSchemaPath}/${keyword}`; - if (schemaPath) schPath = (0, codegen_1.str)`${schPath}${(0, util_1.getErrorPath)(schemaPath, util_1.Type.Str)}`; - return [E.schemaPath, schPath]; - } - function extraErrorProps(cxt, { params, message }, keyValues) { - const { keyword, data, schemaValue, it } = cxt; - const { opts, propertyName, topSchemaRef, schemaPath } = it; - keyValues.push([E.keyword, keyword], [E.params, typeof params == "function" ? params(cxt) : params || (0, codegen_1._)`{}`]); - if (opts.messages) keyValues.push([E.message, typeof message == "function" ? message(cxt) : message]); - if (opts.verbose) keyValues.push([E.schema, schemaValue], [E.parentSchema, (0, codegen_1._)`${topSchemaRef}${schemaPath}`], [names_1.default.data, data]); - if (propertyName) keyValues.push([E.propertyName, propertyName]); - } -})); - -//#endregion -//#region ../../node_modules/.pnpm/ajv@8.18.0/node_modules/ajv/dist/compile/validate/boolSchema.js -var require_boolSchema = /* @__PURE__ */ __commonJSMin(((exports) => { - Object.defineProperty(exports, "__esModule", { value: true }); - exports.boolOrEmptySchema = exports.topBoolOrEmptySchema = void 0; - const errors_1 = require_errors(); - const codegen_1 = require_codegen(); - const names_1 = require_names(); - const boolError = { message: "boolean schema is false" }; - function topBoolOrEmptySchema(it) { - const { gen, schema, validateName } = it; - if (schema === false) falseSchemaError(it, false); - else if (typeof schema == "object" && schema.$async === true) gen.return(names_1.default.data); - else { - gen.assign((0, codegen_1._)`${validateName}.errors`, null); - gen.return(true); - } - } - exports.topBoolOrEmptySchema = topBoolOrEmptySchema; - function boolOrEmptySchema(it, valid) { - const { gen, schema } = it; - if (schema === false) { - gen.var(valid, false); - falseSchemaError(it); - } else gen.var(valid, true); - } - exports.boolOrEmptySchema = boolOrEmptySchema; - function falseSchemaError(it, overrideAllErrors) { - const { gen, data } = it; - const cxt = { - gen, - keyword: "false schema", - data, - schema: false, - schemaCode: false, - schemaValue: false, - params: {}, - it - }; - (0, errors_1.reportError)(cxt, boolError, void 0, overrideAllErrors); - } -})); - -//#endregion -//#region ../../node_modules/.pnpm/ajv@8.18.0/node_modules/ajv/dist/compile/rules.js -var require_rules = /* @__PURE__ */ __commonJSMin(((exports) => { - Object.defineProperty(exports, "__esModule", { value: true }); - exports.getRules = exports.isJSONType = void 0; - const jsonTypes = new Set([ - "string", - "number", - "integer", - "boolean", - "null", - "object", - "array" - ]); - function isJSONType(x) { - return typeof x == "string" && jsonTypes.has(x); - } - exports.isJSONType = isJSONType; - function getRules() { - const groups = { - number: { - type: "number", - rules: [] - }, - string: { - type: "string", - rules: [] - }, - array: { - type: "array", - rules: [] - }, - object: { - type: "object", - rules: [] - } - }; - return { - types: { - ...groups, - integer: true, - boolean: true, - null: true - }, - rules: [ - { rules: [] }, - groups.number, - groups.string, - groups.array, - groups.object - ], - post: { rules: [] }, - all: {}, - keywords: {} - }; - } - exports.getRules = getRules; -})); - -//#endregion -//#region ../../node_modules/.pnpm/ajv@8.18.0/node_modules/ajv/dist/compile/validate/applicability.js -var require_applicability = /* @__PURE__ */ __commonJSMin(((exports) => { - Object.defineProperty(exports, "__esModule", { value: true }); - exports.shouldUseRule = exports.shouldUseGroup = exports.schemaHasRulesForType = void 0; - function schemaHasRulesForType({ schema, self }, type) { - const group = self.RULES.types[type]; - return group && group !== true && shouldUseGroup(schema, group); - } - exports.schemaHasRulesForType = schemaHasRulesForType; - function shouldUseGroup(schema, group) { - return group.rules.some((rule) => shouldUseRule(schema, rule)); - } - exports.shouldUseGroup = shouldUseGroup; - function shouldUseRule(schema, rule) { - var _a; - return schema[rule.keyword] !== void 0 || ((_a = rule.definition.implements) === null || _a === void 0 ? void 0 : _a.some((kwd) => schema[kwd] !== void 0)); - } - exports.shouldUseRule = shouldUseRule; -})); - -//#endregion -//#region ../../node_modules/.pnpm/ajv@8.18.0/node_modules/ajv/dist/compile/validate/dataType.js -var require_dataType = /* @__PURE__ */ __commonJSMin(((exports) => { - Object.defineProperty(exports, "__esModule", { value: true }); - exports.reportTypeError = exports.checkDataTypes = exports.checkDataType = exports.coerceAndCheckDataType = exports.getJSONTypes = exports.getSchemaTypes = exports.DataType = void 0; - const rules_1 = require_rules(); - const applicability_1 = require_applicability(); - const errors_1 = require_errors(); - const codegen_1 = require_codegen(); - const util_1 = require_util(); - var DataType; - (function(DataType) { - DataType[DataType["Correct"] = 0] = "Correct"; - DataType[DataType["Wrong"] = 1] = "Wrong"; - })(DataType || (exports.DataType = DataType = {})); - function getSchemaTypes(schema) { - const types = getJSONTypes(schema.type); - if (types.includes("null")) { - if (schema.nullable === false) throw new Error("type: null contradicts nullable: false"); - } else { - if (!types.length && schema.nullable !== void 0) throw new Error("\"nullable\" cannot be used without \"type\""); - if (schema.nullable === true) types.push("null"); - } - return types; - } - exports.getSchemaTypes = getSchemaTypes; - function getJSONTypes(ts) { - const types = Array.isArray(ts) ? ts : ts ? [ts] : []; - if (types.every(rules_1.isJSONType)) return types; - throw new Error("type must be JSONType or JSONType[]: " + types.join(",")); - } - exports.getJSONTypes = getJSONTypes; - function coerceAndCheckDataType(it, types) { - const { gen, data, opts } = it; - const coerceTo = coerceToTypes(types, opts.coerceTypes); - const checkTypes = types.length > 0 && !(coerceTo.length === 0 && types.length === 1 && (0, applicability_1.schemaHasRulesForType)(it, types[0])); - if (checkTypes) { - const wrongType = checkDataTypes(types, data, opts.strictNumbers, DataType.Wrong); - gen.if(wrongType, () => { - if (coerceTo.length) coerceData(it, types, coerceTo); - else reportTypeError(it); - }); - } - return checkTypes; - } - exports.coerceAndCheckDataType = coerceAndCheckDataType; - const COERCIBLE = new Set([ - "string", - "number", - "integer", - "boolean", - "null" - ]); - function coerceToTypes(types, coerceTypes) { - return coerceTypes ? types.filter((t) => COERCIBLE.has(t) || coerceTypes === "array" && t === "array") : []; - } - function coerceData(it, types, coerceTo) { - const { gen, data, opts } = it; - const dataType = gen.let("dataType", (0, codegen_1._)`typeof ${data}`); - const coerced = gen.let("coerced", (0, codegen_1._)`undefined`); - if (opts.coerceTypes === "array") gen.if((0, codegen_1._)`${dataType} == 'object' && Array.isArray(${data}) && ${data}.length == 1`, () => gen.assign(data, (0, codegen_1._)`${data}[0]`).assign(dataType, (0, codegen_1._)`typeof ${data}`).if(checkDataTypes(types, data, opts.strictNumbers), () => gen.assign(coerced, data))); - gen.if((0, codegen_1._)`${coerced} !== undefined`); - for (const t of coerceTo) if (COERCIBLE.has(t) || t === "array" && opts.coerceTypes === "array") coerceSpecificType(t); - gen.else(); - reportTypeError(it); - gen.endIf(); - gen.if((0, codegen_1._)`${coerced} !== undefined`, () => { - gen.assign(data, coerced); - assignParentData(it, coerced); - }); - function coerceSpecificType(t) { - switch (t) { - case "string": - gen.elseIf((0, codegen_1._)`${dataType} == "number" || ${dataType} == "boolean"`).assign(coerced, (0, codegen_1._)`"" + ${data}`).elseIf((0, codegen_1._)`${data} === null`).assign(coerced, (0, codegen_1._)`""`); - return; - case "number": - gen.elseIf((0, codegen_1._)`${dataType} == "boolean" || ${data} === null - || (${dataType} == "string" && ${data} && ${data} == +${data})`).assign(coerced, (0, codegen_1._)`+${data}`); - return; - case "integer": - gen.elseIf((0, codegen_1._)`${dataType} === "boolean" || ${data} === null - || (${dataType} === "string" && ${data} && ${data} == +${data} && !(${data} % 1))`).assign(coerced, (0, codegen_1._)`+${data}`); - return; - case "boolean": - gen.elseIf((0, codegen_1._)`${data} === "false" || ${data} === 0 || ${data} === null`).assign(coerced, false).elseIf((0, codegen_1._)`${data} === "true" || ${data} === 1`).assign(coerced, true); - return; - case "null": - gen.elseIf((0, codegen_1._)`${data} === "" || ${data} === 0 || ${data} === false`); - gen.assign(coerced, null); - return; - case "array": gen.elseIf((0, codegen_1._)`${dataType} === "string" || ${dataType} === "number" - || ${dataType} === "boolean" || ${data} === null`).assign(coerced, (0, codegen_1._)`[${data}]`); - } - } - } - function assignParentData({ gen, parentData, parentDataProperty }, expr) { - gen.if((0, codegen_1._)`${parentData} !== undefined`, () => gen.assign((0, codegen_1._)`${parentData}[${parentDataProperty}]`, expr)); - } - function checkDataType(dataType, data, strictNums, correct = DataType.Correct) { - const EQ = correct === DataType.Correct ? codegen_1.operators.EQ : codegen_1.operators.NEQ; - let cond; - switch (dataType) { - case "null": return (0, codegen_1._)`${data} ${EQ} null`; - case "array": - cond = (0, codegen_1._)`Array.isArray(${data})`; - break; - case "object": - cond = (0, codegen_1._)`${data} && typeof ${data} == "object" && !Array.isArray(${data})`; - break; - case "integer": - cond = numCond((0, codegen_1._)`!(${data} % 1) && !isNaN(${data})`); - break; - case "number": - cond = numCond(); - break; - default: return (0, codegen_1._)`typeof ${data} ${EQ} ${dataType}`; - } - return correct === DataType.Correct ? cond : (0, codegen_1.not)(cond); - function numCond(_cond = codegen_1.nil) { - return (0, codegen_1.and)((0, codegen_1._)`typeof ${data} == "number"`, _cond, strictNums ? (0, codegen_1._)`isFinite(${data})` : codegen_1.nil); - } - } - exports.checkDataType = checkDataType; - function checkDataTypes(dataTypes, data, strictNums, correct) { - if (dataTypes.length === 1) return checkDataType(dataTypes[0], data, strictNums, correct); - let cond; - const types = (0, util_1.toHash)(dataTypes); - if (types.array && types.object) { - const notObj = (0, codegen_1._)`typeof ${data} != "object"`; - cond = types.null ? notObj : (0, codegen_1._)`!${data} || ${notObj}`; - delete types.null; - delete types.array; - delete types.object; - } else cond = codegen_1.nil; - if (types.number) delete types.integer; - for (const t in types) cond = (0, codegen_1.and)(cond, checkDataType(t, data, strictNums, correct)); - return cond; - } - exports.checkDataTypes = checkDataTypes; - const typeError = { - message: ({ schema }) => `must be ${schema}`, - params: ({ schema, schemaValue }) => typeof schema == "string" ? (0, codegen_1._)`{type: ${schema}}` : (0, codegen_1._)`{type: ${schemaValue}}` - }; - function reportTypeError(it) { - const cxt = getTypeErrorContext(it); - (0, errors_1.reportError)(cxt, typeError); - } - exports.reportTypeError = reportTypeError; - function getTypeErrorContext(it) { - const { gen, data, schema } = it; - const schemaCode = (0, util_1.schemaRefOrVal)(it, schema, "type"); - return { - gen, - keyword: "type", - data, - schema: schema.type, - schemaCode, - schemaValue: schemaCode, - parentSchema: schema, - params: {}, - it - }; - } -})); - -//#endregion -//#region ../../node_modules/.pnpm/ajv@8.18.0/node_modules/ajv/dist/compile/validate/defaults.js -var require_defaults = /* @__PURE__ */ __commonJSMin(((exports) => { - Object.defineProperty(exports, "__esModule", { value: true }); - exports.assignDefaults = void 0; - const codegen_1 = require_codegen(); - const util_1 = require_util(); - function assignDefaults(it, ty) { - const { properties, items } = it.schema; - if (ty === "object" && properties) for (const key in properties) assignDefault(it, key, properties[key].default); - else if (ty === "array" && Array.isArray(items)) items.forEach((sch, i) => assignDefault(it, i, sch.default)); - } - exports.assignDefaults = assignDefaults; - function assignDefault(it, prop, defaultValue) { - const { gen, compositeRule, data, opts } = it; - if (defaultValue === void 0) return; - const childData = (0, codegen_1._)`${data}${(0, codegen_1.getProperty)(prop)}`; - if (compositeRule) { - (0, util_1.checkStrictMode)(it, `default is ignored for: ${childData}`); - return; - } - let condition = (0, codegen_1._)`${childData} === undefined`; - if (opts.useDefaults === "empty") condition = (0, codegen_1._)`${condition} || ${childData} === null || ${childData} === ""`; - gen.if(condition, (0, codegen_1._)`${childData} = ${(0, codegen_1.stringify)(defaultValue)}`); - } -})); - -//#endregion -//#region ../../node_modules/.pnpm/ajv@8.18.0/node_modules/ajv/dist/vocabularies/code.js -var require_code = /* @__PURE__ */ __commonJSMin(((exports) => { - Object.defineProperty(exports, "__esModule", { value: true }); - exports.validateUnion = exports.validateArray = exports.usePattern = exports.callValidateCode = exports.schemaProperties = exports.allSchemaProperties = exports.noPropertyInData = exports.propertyInData = exports.isOwnProperty = exports.hasPropFunc = exports.reportMissingProp = exports.checkMissingProp = exports.checkReportMissingProp = void 0; - const codegen_1 = require_codegen(); - const util_1 = require_util(); - const names_1 = require_names(); - const util_2 = require_util(); - function checkReportMissingProp(cxt, prop) { - const { gen, data, it } = cxt; - gen.if(noPropertyInData(gen, data, prop, it.opts.ownProperties), () => { - cxt.setParams({ missingProperty: (0, codegen_1._)`${prop}` }, true); - cxt.error(); - }); - } - exports.checkReportMissingProp = checkReportMissingProp; - function checkMissingProp({ gen, data, it: { opts } }, properties, missing) { - return (0, codegen_1.or)(...properties.map((prop) => (0, codegen_1.and)(noPropertyInData(gen, data, prop, opts.ownProperties), (0, codegen_1._)`${missing} = ${prop}`))); - } - exports.checkMissingProp = checkMissingProp; - function reportMissingProp(cxt, missing) { - cxt.setParams({ missingProperty: missing }, true); - cxt.error(); - } - exports.reportMissingProp = reportMissingProp; - function hasPropFunc(gen) { - return gen.scopeValue("func", { - ref: Object.prototype.hasOwnProperty, - code: (0, codegen_1._)`Object.prototype.hasOwnProperty` - }); - } - exports.hasPropFunc = hasPropFunc; - function isOwnProperty(gen, data, property) { - return (0, codegen_1._)`${hasPropFunc(gen)}.call(${data}, ${property})`; - } - exports.isOwnProperty = isOwnProperty; - function propertyInData(gen, data, property, ownProperties) { - const cond = (0, codegen_1._)`${data}${(0, codegen_1.getProperty)(property)} !== undefined`; - return ownProperties ? (0, codegen_1._)`${cond} && ${isOwnProperty(gen, data, property)}` : cond; - } - exports.propertyInData = propertyInData; - function noPropertyInData(gen, data, property, ownProperties) { - const cond = (0, codegen_1._)`${data}${(0, codegen_1.getProperty)(property)} === undefined`; - return ownProperties ? (0, codegen_1.or)(cond, (0, codegen_1.not)(isOwnProperty(gen, data, property))) : cond; - } - exports.noPropertyInData = noPropertyInData; - function allSchemaProperties(schemaMap) { - return schemaMap ? Object.keys(schemaMap).filter((p) => p !== "__proto__") : []; - } - exports.allSchemaProperties = allSchemaProperties; - function schemaProperties(it, schemaMap) { - return allSchemaProperties(schemaMap).filter((p) => !(0, util_1.alwaysValidSchema)(it, schemaMap[p])); - } - exports.schemaProperties = schemaProperties; - function callValidateCode({ schemaCode, data, it: { gen, topSchemaRef, schemaPath, errorPath }, it }, func, context, passSchema) { - const dataAndSchema = passSchema ? (0, codegen_1._)`${schemaCode}, ${data}, ${topSchemaRef}${schemaPath}` : data; - const valCxt = [ - [names_1.default.instancePath, (0, codegen_1.strConcat)(names_1.default.instancePath, errorPath)], - [names_1.default.parentData, it.parentData], - [names_1.default.parentDataProperty, it.parentDataProperty], - [names_1.default.rootData, names_1.default.rootData] - ]; - if (it.opts.dynamicRef) valCxt.push([names_1.default.dynamicAnchors, names_1.default.dynamicAnchors]); - const args = (0, codegen_1._)`${dataAndSchema}, ${gen.object(...valCxt)}`; - return context !== codegen_1.nil ? (0, codegen_1._)`${func}.call(${context}, ${args})` : (0, codegen_1._)`${func}(${args})`; - } - exports.callValidateCode = callValidateCode; - const newRegExp = (0, codegen_1._)`new RegExp`; - function usePattern({ gen, it: { opts } }, pattern) { - const u = opts.unicodeRegExp ? "u" : ""; - const { regExp } = opts.code; - const rx = regExp(pattern, u); - return gen.scopeValue("pattern", { - key: rx.toString(), - ref: rx, - code: (0, codegen_1._)`${regExp.code === "new RegExp" ? newRegExp : (0, util_2.useFunc)(gen, regExp)}(${pattern}, ${u})` - }); - } - exports.usePattern = usePattern; - function validateArray(cxt) { - const { gen, data, keyword, it } = cxt; - const valid = gen.name("valid"); - if (it.allErrors) { - const validArr = gen.let("valid", true); - validateItems(() => gen.assign(validArr, false)); - return validArr; - } - gen.var(valid, true); - validateItems(() => gen.break()); - return valid; - function validateItems(notValid) { - const len = gen.const("len", (0, codegen_1._)`${data}.length`); - gen.forRange("i", 0, len, (i) => { - cxt.subschema({ - keyword, - dataProp: i, - dataPropType: util_1.Type.Num - }, valid); - gen.if((0, codegen_1.not)(valid), notValid); - }); - } - } - exports.validateArray = validateArray; - function validateUnion(cxt) { - const { gen, schema, keyword, it } = cxt; - /* istanbul ignore if */ - if (!Array.isArray(schema)) throw new Error("ajv implementation error"); - if (schema.some((sch) => (0, util_1.alwaysValidSchema)(it, sch)) && !it.opts.unevaluated) return; - const valid = gen.let("valid", false); - const schValid = gen.name("_valid"); - gen.block(() => schema.forEach((_sch, i) => { - const schCxt = cxt.subschema({ - keyword, - schemaProp: i, - compositeRule: true - }, schValid); - gen.assign(valid, (0, codegen_1._)`${valid} || ${schValid}`); - if (!cxt.mergeValidEvaluated(schCxt, schValid)) gen.if((0, codegen_1.not)(valid)); - })); - cxt.result(valid, () => cxt.reset(), () => cxt.error(true)); - } - exports.validateUnion = validateUnion; -})); - -//#endregion -//#region ../../node_modules/.pnpm/ajv@8.18.0/node_modules/ajv/dist/compile/validate/keyword.js -var require_keyword = /* @__PURE__ */ __commonJSMin(((exports) => { - Object.defineProperty(exports, "__esModule", { value: true }); - exports.validateKeywordUsage = exports.validSchemaType = exports.funcKeywordCode = exports.macroKeywordCode = void 0; - const codegen_1 = require_codegen(); - const names_1 = require_names(); - const code_1 = require_code(); - const errors_1 = require_errors(); - function macroKeywordCode(cxt, def) { - const { gen, keyword, schema, parentSchema, it } = cxt; - const macroSchema = def.macro.call(it.self, schema, parentSchema, it); - const schemaRef = useKeyword(gen, keyword, macroSchema); - if (it.opts.validateSchema !== false) it.self.validateSchema(macroSchema, true); - const valid = gen.name("valid"); - cxt.subschema({ - schema: macroSchema, - schemaPath: codegen_1.nil, - errSchemaPath: `${it.errSchemaPath}/${keyword}`, - topSchemaRef: schemaRef, - compositeRule: true - }, valid); - cxt.pass(valid, () => cxt.error(true)); - } - exports.macroKeywordCode = macroKeywordCode; - function funcKeywordCode(cxt, def) { - var _a; - const { gen, keyword, schema, parentSchema, $data, it } = cxt; - checkAsyncKeyword(it, def); - const validateRef = useKeyword(gen, keyword, !$data && def.compile ? def.compile.call(it.self, schema, parentSchema, it) : def.validate); - const valid = gen.let("valid"); - cxt.block$data(valid, validateKeyword); - cxt.ok((_a = def.valid) !== null && _a !== void 0 ? _a : valid); - function validateKeyword() { - if (def.errors === false) { - assignValid(); - if (def.modifying) modifyData(cxt); - reportErrs(() => cxt.error()); - } else { - const ruleErrs = def.async ? validateAsync() : validateSync(); - if (def.modifying) modifyData(cxt); - reportErrs(() => addErrs(cxt, ruleErrs)); - } - } - function validateAsync() { - const ruleErrs = gen.let("ruleErrs", null); - gen.try(() => assignValid((0, codegen_1._)`await `), (e) => gen.assign(valid, false).if((0, codegen_1._)`${e} instanceof ${it.ValidationError}`, () => gen.assign(ruleErrs, (0, codegen_1._)`${e}.errors`), () => gen.throw(e))); - return ruleErrs; - } - function validateSync() { - const validateErrs = (0, codegen_1._)`${validateRef}.errors`; - gen.assign(validateErrs, null); - assignValid(codegen_1.nil); - return validateErrs; - } - function assignValid(_await = def.async ? (0, codegen_1._)`await ` : codegen_1.nil) { - const passCxt = it.opts.passContext ? names_1.default.this : names_1.default.self; - const passSchema = !("compile" in def && !$data || def.schema === false); - gen.assign(valid, (0, codegen_1._)`${_await}${(0, code_1.callValidateCode)(cxt, validateRef, passCxt, passSchema)}`, def.modifying); - } - function reportErrs(errors) { - var _a$1; - gen.if((0, codegen_1.not)((_a$1 = def.valid) !== null && _a$1 !== void 0 ? _a$1 : valid), errors); - } - } - exports.funcKeywordCode = funcKeywordCode; - function modifyData(cxt) { - const { gen, data, it } = cxt; - gen.if(it.parentData, () => gen.assign(data, (0, codegen_1._)`${it.parentData}[${it.parentDataProperty}]`)); - } - function addErrs(cxt, errs) { - const { gen } = cxt; - gen.if((0, codegen_1._)`Array.isArray(${errs})`, () => { - gen.assign(names_1.default.vErrors, (0, codegen_1._)`${names_1.default.vErrors} === null ? ${errs} : ${names_1.default.vErrors}.concat(${errs})`).assign(names_1.default.errors, (0, codegen_1._)`${names_1.default.vErrors}.length`); - (0, errors_1.extendErrors)(cxt); - }, () => cxt.error()); - } - function checkAsyncKeyword({ schemaEnv }, def) { - if (def.async && !schemaEnv.$async) throw new Error("async keyword in sync schema"); - } - function useKeyword(gen, keyword, result) { - if (result === void 0) throw new Error(`keyword "${keyword}" failed to compile`); - return gen.scopeValue("keyword", typeof result == "function" ? { ref: result } : { - ref: result, - code: (0, codegen_1.stringify)(result) - }); - } - function validSchemaType(schema, schemaType, allowUndefined = false) { - return !schemaType.length || schemaType.some((st) => st === "array" ? Array.isArray(schema) : st === "object" ? schema && typeof schema == "object" && !Array.isArray(schema) : typeof schema == st || allowUndefined && typeof schema == "undefined"); - } - exports.validSchemaType = validSchemaType; - function validateKeywordUsage({ schema, opts, self, errSchemaPath }, def, keyword) { - /* istanbul ignore if */ - if (Array.isArray(def.keyword) ? !def.keyword.includes(keyword) : def.keyword !== keyword) throw new Error("ajv implementation error"); - const deps = def.dependencies; - if (deps === null || deps === void 0 ? void 0 : deps.some((kwd) => !Object.prototype.hasOwnProperty.call(schema, kwd))) throw new Error(`parent schema must have dependencies of ${keyword}: ${deps.join(",")}`); - if (def.validateSchema) { - if (!def.validateSchema(schema[keyword])) { - const msg = `keyword "${keyword}" value is invalid at path "${errSchemaPath}": ` + self.errorsText(def.validateSchema.errors); - if (opts.validateSchema === "log") self.logger.error(msg); - else throw new Error(msg); - } - } - } - exports.validateKeywordUsage = validateKeywordUsage; -})); - -//#endregion -//#region ../../node_modules/.pnpm/ajv@8.18.0/node_modules/ajv/dist/compile/validate/subschema.js -var require_subschema = /* @__PURE__ */ __commonJSMin(((exports) => { - Object.defineProperty(exports, "__esModule", { value: true }); - exports.extendSubschemaMode = exports.extendSubschemaData = exports.getSubschema = void 0; - const codegen_1 = require_codegen(); - const util_1 = require_util(); - function getSubschema(it, { keyword, schemaProp, schema, schemaPath, errSchemaPath, topSchemaRef }) { - if (keyword !== void 0 && schema !== void 0) throw new Error("both \"keyword\" and \"schema\" passed, only one allowed"); - if (keyword !== void 0) { - const sch = it.schema[keyword]; - return schemaProp === void 0 ? { - schema: sch, - schemaPath: (0, codegen_1._)`${it.schemaPath}${(0, codegen_1.getProperty)(keyword)}`, - errSchemaPath: `${it.errSchemaPath}/${keyword}` - } : { - schema: sch[schemaProp], - schemaPath: (0, codegen_1._)`${it.schemaPath}${(0, codegen_1.getProperty)(keyword)}${(0, codegen_1.getProperty)(schemaProp)}`, - errSchemaPath: `${it.errSchemaPath}/${keyword}/${(0, util_1.escapeFragment)(schemaProp)}` - }; - } - if (schema !== void 0) { - if (schemaPath === void 0 || errSchemaPath === void 0 || topSchemaRef === void 0) throw new Error("\"schemaPath\", \"errSchemaPath\" and \"topSchemaRef\" are required with \"schema\""); - return { - schema, - schemaPath, - topSchemaRef, - errSchemaPath - }; - } - throw new Error("either \"keyword\" or \"schema\" must be passed"); - } - exports.getSubschema = getSubschema; - function extendSubschemaData(subschema, it, { dataProp, dataPropType: dpType, data, dataTypes, propertyName }) { - if (data !== void 0 && dataProp !== void 0) throw new Error("both \"data\" and \"dataProp\" passed, only one allowed"); - const { gen } = it; - if (dataProp !== void 0) { - const { errorPath, dataPathArr, opts } = it; - dataContextProps(gen.let("data", (0, codegen_1._)`${it.data}${(0, codegen_1.getProperty)(dataProp)}`, true)); - subschema.errorPath = (0, codegen_1.str)`${errorPath}${(0, util_1.getErrorPath)(dataProp, dpType, opts.jsPropertySyntax)}`; - subschema.parentDataProperty = (0, codegen_1._)`${dataProp}`; - subschema.dataPathArr = [...dataPathArr, subschema.parentDataProperty]; - } - if (data !== void 0) { - dataContextProps(data instanceof codegen_1.Name ? data : gen.let("data", data, true)); - if (propertyName !== void 0) subschema.propertyName = propertyName; - } - if (dataTypes) subschema.dataTypes = dataTypes; - function dataContextProps(_nextData) { - subschema.data = _nextData; - subschema.dataLevel = it.dataLevel + 1; - subschema.dataTypes = []; - it.definedProperties = /* @__PURE__ */ new Set(); - subschema.parentData = it.data; - subschema.dataNames = [...it.dataNames, _nextData]; - } - } - exports.extendSubschemaData = extendSubschemaData; - function extendSubschemaMode(subschema, { jtdDiscriminator, jtdMetadata, compositeRule, createErrors, allErrors }) { - if (compositeRule !== void 0) subschema.compositeRule = compositeRule; - if (createErrors !== void 0) subschema.createErrors = createErrors; - if (allErrors !== void 0) subschema.allErrors = allErrors; - subschema.jtdDiscriminator = jtdDiscriminator; - subschema.jtdMetadata = jtdMetadata; - } - exports.extendSubschemaMode = extendSubschemaMode; -})); - -//#endregion -//#region ../../node_modules/.pnpm/fast-deep-equal@3.1.3/node_modules/fast-deep-equal/index.js -var require_fast_deep_equal = /* @__PURE__ */ __commonJSMin(((exports, module) => { - module.exports = function equal(a, b) { - if (a === b) return true; - if (a && b && typeof a == "object" && typeof b == "object") { - if (a.constructor !== b.constructor) return false; - var length, i, keys; - if (Array.isArray(a)) { - length = a.length; - if (length != b.length) return false; - for (i = length; i-- !== 0;) if (!equal(a[i], b[i])) return false; - return true; - } - if (a.constructor === RegExp) return a.source === b.source && a.flags === b.flags; - if (a.valueOf !== Object.prototype.valueOf) return a.valueOf() === b.valueOf(); - if (a.toString !== Object.prototype.toString) return a.toString() === b.toString(); - keys = Object.keys(a); - length = keys.length; - if (length !== Object.keys(b).length) return false; - for (i = length; i-- !== 0;) if (!Object.prototype.hasOwnProperty.call(b, keys[i])) return false; - for (i = length; i-- !== 0;) { - var key = keys[i]; - if (!equal(a[key], b[key])) return false; - } - return true; - } - return a !== a && b !== b; - }; -})); - -//#endregion -//#region ../../node_modules/.pnpm/json-schema-traverse@1.0.0/node_modules/json-schema-traverse/index.js -var require_json_schema_traverse = /* @__PURE__ */ __commonJSMin(((exports, module) => { - var traverse = module.exports = function(schema, opts, cb) { - if (typeof opts == "function") { - cb = opts; - opts = {}; - } - cb = opts.cb || cb; - var pre = typeof cb == "function" ? cb : cb.pre || function() {}; - var post = cb.post || function() {}; - _traverse(opts, pre, post, schema, "", schema); - }; - traverse.keywords = { - additionalItems: true, - items: true, - contains: true, - additionalProperties: true, - propertyNames: true, - not: true, - if: true, - then: true, - else: true - }; - traverse.arrayKeywords = { - items: true, - allOf: true, - anyOf: true, - oneOf: true - }; - traverse.propsKeywords = { - $defs: true, - definitions: true, - properties: true, - patternProperties: true, - dependencies: true - }; - traverse.skipKeywords = { - default: true, - enum: true, - const: true, - required: true, - maximum: true, - minimum: true, - exclusiveMaximum: true, - exclusiveMinimum: true, - multipleOf: true, - maxLength: true, - minLength: true, - pattern: true, - format: true, - maxItems: true, - minItems: true, - uniqueItems: true, - maxProperties: true, - minProperties: true - }; - function _traverse(opts, pre, post, schema, jsonPtr, rootSchema, parentJsonPtr, parentKeyword, parentSchema, keyIndex) { - if (schema && typeof schema == "object" && !Array.isArray(schema)) { - pre(schema, jsonPtr, rootSchema, parentJsonPtr, parentKeyword, parentSchema, keyIndex); - for (var key in schema) { - var sch = schema[key]; - if (Array.isArray(sch)) { - if (key in traverse.arrayKeywords) for (var i = 0; i < sch.length; i++) _traverse(opts, pre, post, sch[i], jsonPtr + "/" + key + "/" + i, rootSchema, jsonPtr, key, schema, i); - } else if (key in traverse.propsKeywords) { - if (sch && typeof sch == "object") for (var prop in sch) _traverse(opts, pre, post, sch[prop], jsonPtr + "/" + key + "/" + escapeJsonPtr(prop), rootSchema, jsonPtr, key, schema, prop); - } else if (key in traverse.keywords || opts.allKeys && !(key in traverse.skipKeywords)) _traverse(opts, pre, post, sch, jsonPtr + "/" + key, rootSchema, jsonPtr, key, schema); - } - post(schema, jsonPtr, rootSchema, parentJsonPtr, parentKeyword, parentSchema, keyIndex); - } - } - function escapeJsonPtr(str) { - return str.replace(/~/g, "~0").replace(/\//g, "~1"); - } -})); - -//#endregion -//#region ../../node_modules/.pnpm/ajv@8.18.0/node_modules/ajv/dist/compile/resolve.js -var require_resolve = /* @__PURE__ */ __commonJSMin(((exports) => { - Object.defineProperty(exports, "__esModule", { value: true }); - exports.getSchemaRefs = exports.resolveUrl = exports.normalizeId = exports._getFullPath = exports.getFullPath = exports.inlineRef = void 0; - const util_1 = require_util(); - const equal = require_fast_deep_equal(); - const traverse = require_json_schema_traverse(); - const SIMPLE_INLINED = new Set([ - "type", - "format", - "pattern", - "maxLength", - "minLength", - "maxProperties", - "minProperties", - "maxItems", - "minItems", - "maximum", - "minimum", - "uniqueItems", - "multipleOf", - "required", - "enum", - "const" - ]); - function inlineRef(schema, limit = true) { - if (typeof schema == "boolean") return true; - if (limit === true) return !hasRef(schema); - if (!limit) return false; - return countKeys(schema) <= limit; - } - exports.inlineRef = inlineRef; - const REF_KEYWORDS = new Set([ - "$ref", - "$recursiveRef", - "$recursiveAnchor", - "$dynamicRef", - "$dynamicAnchor" - ]); - function hasRef(schema) { - for (const key in schema) { - if (REF_KEYWORDS.has(key)) return true; - const sch = schema[key]; - if (Array.isArray(sch) && sch.some(hasRef)) return true; - if (typeof sch == "object" && hasRef(sch)) return true; - } - return false; - } - function countKeys(schema) { - let count = 0; - for (const key in schema) { - if (key === "$ref") return Infinity; - count++; - if (SIMPLE_INLINED.has(key)) continue; - if (typeof schema[key] == "object") (0, util_1.eachItem)(schema[key], (sch) => count += countKeys(sch)); - if (count === Infinity) return Infinity; - } - return count; - } - function getFullPath(resolver, id = "", normalize) { - if (normalize !== false) id = normalizeId(id); - return _getFullPath(resolver, resolver.parse(id)); - } - exports.getFullPath = getFullPath; - function _getFullPath(resolver, p) { - return resolver.serialize(p).split("#")[0] + "#"; - } - exports._getFullPath = _getFullPath; - const TRAILING_SLASH_HASH = /#\/?$/; - function normalizeId(id) { - return id ? id.replace(TRAILING_SLASH_HASH, "") : ""; - } - exports.normalizeId = normalizeId; - function resolveUrl(resolver, baseId, id) { - id = normalizeId(id); - return resolver.resolve(baseId, id); - } - exports.resolveUrl = resolveUrl; - const ANCHOR = /^[a-z_][-a-z0-9._]*$/i; - function getSchemaRefs(schema, baseId) { - if (typeof schema == "boolean") return {}; - const { schemaId, uriResolver } = this.opts; - const schId = normalizeId(schema[schemaId] || baseId); - const baseIds = { "": schId }; - const pathPrefix = getFullPath(uriResolver, schId, false); - const localRefs = {}; - const schemaRefs = /* @__PURE__ */ new Set(); - traverse(schema, { allKeys: true }, (sch, jsonPtr, _, parentJsonPtr) => { - if (parentJsonPtr === void 0) return; - const fullPath = pathPrefix + jsonPtr; - let innerBaseId = baseIds[parentJsonPtr]; - if (typeof sch[schemaId] == "string") innerBaseId = addRef.call(this, sch[schemaId]); - addAnchor.call(this, sch.$anchor); - addAnchor.call(this, sch.$dynamicAnchor); - baseIds[jsonPtr] = innerBaseId; - function addRef(ref) { - const _resolve = this.opts.uriResolver.resolve; - ref = normalizeId(innerBaseId ? _resolve(innerBaseId, ref) : ref); - if (schemaRefs.has(ref)) throw ambiguos(ref); - schemaRefs.add(ref); - let schOrRef = this.refs[ref]; - if (typeof schOrRef == "string") schOrRef = this.refs[schOrRef]; - if (typeof schOrRef == "object") checkAmbiguosRef(sch, schOrRef.schema, ref); - else if (ref !== normalizeId(fullPath)) if (ref[0] === "#") { - checkAmbiguosRef(sch, localRefs[ref], ref); - localRefs[ref] = sch; - } else this.refs[ref] = fullPath; - return ref; - } - function addAnchor(anchor) { - if (typeof anchor == "string") { - if (!ANCHOR.test(anchor)) throw new Error(`invalid anchor "${anchor}"`); - addRef.call(this, `#${anchor}`); - } - } - }); - return localRefs; - function checkAmbiguosRef(sch1, sch2, ref) { - if (sch2 !== void 0 && !equal(sch1, sch2)) throw ambiguos(ref); - } - function ambiguos(ref) { - return /* @__PURE__ */ new Error(`reference "${ref}" resolves to more than one schema`); - } - } - exports.getSchemaRefs = getSchemaRefs; -})); - -//#endregion -//#region ../../node_modules/.pnpm/ajv@8.18.0/node_modules/ajv/dist/compile/validate/index.js -var require_validate = /* @__PURE__ */ __commonJSMin(((exports) => { - Object.defineProperty(exports, "__esModule", { value: true }); - exports.getData = exports.KeywordCxt = exports.validateFunctionCode = void 0; - const boolSchema_1 = require_boolSchema(); - const dataType_1 = require_dataType(); - const applicability_1 = require_applicability(); - const dataType_2 = require_dataType(); - const defaults_1 = require_defaults(); - const keyword_1 = require_keyword(); - const subschema_1 = require_subschema(); - const codegen_1 = require_codegen(); - const names_1 = require_names(); - const resolve_1 = require_resolve(); - const util_1 = require_util(); - const errors_1 = require_errors(); - function validateFunctionCode(it) { - if (isSchemaObj(it)) { - checkKeywords(it); - if (schemaCxtHasRules(it)) { - topSchemaObjCode(it); - return; - } - } - validateFunction(it, () => (0, boolSchema_1.topBoolOrEmptySchema)(it)); - } - exports.validateFunctionCode = validateFunctionCode; - function validateFunction({ gen, validateName, schema, schemaEnv, opts }, body) { - if (opts.code.es5) gen.func(validateName, (0, codegen_1._)`${names_1.default.data}, ${names_1.default.valCxt}`, schemaEnv.$async, () => { - gen.code((0, codegen_1._)`"use strict"; ${funcSourceUrl(schema, opts)}`); - destructureValCxtES5(gen, opts); - gen.code(body); - }); - else gen.func(validateName, (0, codegen_1._)`${names_1.default.data}, ${destructureValCxt(opts)}`, schemaEnv.$async, () => gen.code(funcSourceUrl(schema, opts)).code(body)); - } - function destructureValCxt(opts) { - return (0, codegen_1._)`{${names_1.default.instancePath}="", ${names_1.default.parentData}, ${names_1.default.parentDataProperty}, ${names_1.default.rootData}=${names_1.default.data}${opts.dynamicRef ? (0, codegen_1._)`, ${names_1.default.dynamicAnchors}={}` : codegen_1.nil}}={}`; - } - function destructureValCxtES5(gen, opts) { - gen.if(names_1.default.valCxt, () => { - gen.var(names_1.default.instancePath, (0, codegen_1._)`${names_1.default.valCxt}.${names_1.default.instancePath}`); - gen.var(names_1.default.parentData, (0, codegen_1._)`${names_1.default.valCxt}.${names_1.default.parentData}`); - gen.var(names_1.default.parentDataProperty, (0, codegen_1._)`${names_1.default.valCxt}.${names_1.default.parentDataProperty}`); - gen.var(names_1.default.rootData, (0, codegen_1._)`${names_1.default.valCxt}.${names_1.default.rootData}`); - if (opts.dynamicRef) gen.var(names_1.default.dynamicAnchors, (0, codegen_1._)`${names_1.default.valCxt}.${names_1.default.dynamicAnchors}`); - }, () => { - gen.var(names_1.default.instancePath, (0, codegen_1._)`""`); - gen.var(names_1.default.parentData, (0, codegen_1._)`undefined`); - gen.var(names_1.default.parentDataProperty, (0, codegen_1._)`undefined`); - gen.var(names_1.default.rootData, names_1.default.data); - if (opts.dynamicRef) gen.var(names_1.default.dynamicAnchors, (0, codegen_1._)`{}`); - }); - } - function topSchemaObjCode(it) { - const { schema, opts, gen } = it; - validateFunction(it, () => { - if (opts.$comment && schema.$comment) commentKeyword(it); - checkNoDefault(it); - gen.let(names_1.default.vErrors, null); - gen.let(names_1.default.errors, 0); - if (opts.unevaluated) resetEvaluated(it); - typeAndKeywords(it); - returnResults(it); - }); - } - function resetEvaluated(it) { - const { gen, validateName } = it; - it.evaluated = gen.const("evaluated", (0, codegen_1._)`${validateName}.evaluated`); - gen.if((0, codegen_1._)`${it.evaluated}.dynamicProps`, () => gen.assign((0, codegen_1._)`${it.evaluated}.props`, (0, codegen_1._)`undefined`)); - gen.if((0, codegen_1._)`${it.evaluated}.dynamicItems`, () => gen.assign((0, codegen_1._)`${it.evaluated}.items`, (0, codegen_1._)`undefined`)); - } - function funcSourceUrl(schema, opts) { - const schId = typeof schema == "object" && schema[opts.schemaId]; - return schId && (opts.code.source || opts.code.process) ? (0, codegen_1._)`/*# sourceURL=${schId} */` : codegen_1.nil; - } - function subschemaCode(it, valid) { - if (isSchemaObj(it)) { - checkKeywords(it); - if (schemaCxtHasRules(it)) { - subSchemaObjCode(it, valid); - return; - } - } - (0, boolSchema_1.boolOrEmptySchema)(it, valid); - } - function schemaCxtHasRules({ schema, self }) { - if (typeof schema == "boolean") return !schema; - for (const key in schema) if (self.RULES.all[key]) return true; - return false; - } - function isSchemaObj(it) { - return typeof it.schema != "boolean"; - } - function subSchemaObjCode(it, valid) { - const { schema, gen, opts } = it; - if (opts.$comment && schema.$comment) commentKeyword(it); - updateContext(it); - checkAsyncSchema(it); - const errsCount = gen.const("_errs", names_1.default.errors); - typeAndKeywords(it, errsCount); - gen.var(valid, (0, codegen_1._)`${errsCount} === ${names_1.default.errors}`); - } - function checkKeywords(it) { - (0, util_1.checkUnknownRules)(it); - checkRefsAndKeywords(it); - } - function typeAndKeywords(it, errsCount) { - if (it.opts.jtd) return schemaKeywords(it, [], false, errsCount); - const types = (0, dataType_1.getSchemaTypes)(it.schema); - schemaKeywords(it, types, !(0, dataType_1.coerceAndCheckDataType)(it, types), errsCount); - } - function checkRefsAndKeywords(it) { - const { schema, errSchemaPath, opts, self } = it; - if (schema.$ref && opts.ignoreKeywordsWithRef && (0, util_1.schemaHasRulesButRef)(schema, self.RULES)) self.logger.warn(`$ref: keywords ignored in schema at path "${errSchemaPath}"`); - } - function checkNoDefault(it) { - const { schema, opts } = it; - if (schema.default !== void 0 && opts.useDefaults && opts.strictSchema) (0, util_1.checkStrictMode)(it, "default is ignored in the schema root"); - } - function updateContext(it) { - const schId = it.schema[it.opts.schemaId]; - if (schId) it.baseId = (0, resolve_1.resolveUrl)(it.opts.uriResolver, it.baseId, schId); - } - function checkAsyncSchema(it) { - if (it.schema.$async && !it.schemaEnv.$async) throw new Error("async schema in sync schema"); - } - function commentKeyword({ gen, schemaEnv, schema, errSchemaPath, opts }) { - const msg = schema.$comment; - if (opts.$comment === true) gen.code((0, codegen_1._)`${names_1.default.self}.logger.log(${msg})`); - else if (typeof opts.$comment == "function") { - const schemaPath = (0, codegen_1.str)`${errSchemaPath}/$comment`; - const rootName = gen.scopeValue("root", { ref: schemaEnv.root }); - gen.code((0, codegen_1._)`${names_1.default.self}.opts.$comment(${msg}, ${schemaPath}, ${rootName}.schema)`); - } - } - function returnResults(it) { - const { gen, schemaEnv, validateName, ValidationError, opts } = it; - if (schemaEnv.$async) gen.if((0, codegen_1._)`${names_1.default.errors} === 0`, () => gen.return(names_1.default.data), () => gen.throw((0, codegen_1._)`new ${ValidationError}(${names_1.default.vErrors})`)); - else { - gen.assign((0, codegen_1._)`${validateName}.errors`, names_1.default.vErrors); - if (opts.unevaluated) assignEvaluated(it); - gen.return((0, codegen_1._)`${names_1.default.errors} === 0`); - } - } - function assignEvaluated({ gen, evaluated, props, items }) { - if (props instanceof codegen_1.Name) gen.assign((0, codegen_1._)`${evaluated}.props`, props); - if (items instanceof codegen_1.Name) gen.assign((0, codegen_1._)`${evaluated}.items`, items); - } - function schemaKeywords(it, types, typeErrors, errsCount) { - const { gen, schema, data, allErrors, opts, self } = it; - const { RULES } = self; - if (schema.$ref && (opts.ignoreKeywordsWithRef || !(0, util_1.schemaHasRulesButRef)(schema, RULES))) { - gen.block(() => keywordCode(it, "$ref", RULES.all.$ref.definition)); - return; - } - if (!opts.jtd) checkStrictTypes(it, types); - gen.block(() => { - for (const group of RULES.rules) groupKeywords(group); - groupKeywords(RULES.post); - }); - function groupKeywords(group) { - if (!(0, applicability_1.shouldUseGroup)(schema, group)) return; - if (group.type) { - gen.if((0, dataType_2.checkDataType)(group.type, data, opts.strictNumbers)); - iterateKeywords(it, group); - if (types.length === 1 && types[0] === group.type && typeErrors) { - gen.else(); - (0, dataType_2.reportTypeError)(it); - } - gen.endIf(); - } else iterateKeywords(it, group); - if (!allErrors) gen.if((0, codegen_1._)`${names_1.default.errors} === ${errsCount || 0}`); - } - } - function iterateKeywords(it, group) { - const { gen, schema, opts: { useDefaults } } = it; - if (useDefaults) (0, defaults_1.assignDefaults)(it, group.type); - gen.block(() => { - for (const rule of group.rules) if ((0, applicability_1.shouldUseRule)(schema, rule)) keywordCode(it, rule.keyword, rule.definition, group.type); - }); - } - function checkStrictTypes(it, types) { - if (it.schemaEnv.meta || !it.opts.strictTypes) return; - checkContextTypes(it, types); - if (!it.opts.allowUnionTypes) checkMultipleTypes(it, types); - checkKeywordTypes(it, it.dataTypes); - } - function checkContextTypes(it, types) { - if (!types.length) return; - if (!it.dataTypes.length) { - it.dataTypes = types; - return; - } - types.forEach((t) => { - if (!includesType(it.dataTypes, t)) strictTypesError(it, `type "${t}" not allowed by context "${it.dataTypes.join(",")}"`); - }); - narrowSchemaTypes(it, types); - } - function checkMultipleTypes(it, ts) { - if (ts.length > 1 && !(ts.length === 2 && ts.includes("null"))) strictTypesError(it, "use allowUnionTypes to allow union type keyword"); - } - function checkKeywordTypes(it, ts) { - const rules = it.self.RULES.all; - for (const keyword in rules) { - const rule = rules[keyword]; - if (typeof rule == "object" && (0, applicability_1.shouldUseRule)(it.schema, rule)) { - const { type } = rule.definition; - if (type.length && !type.some((t) => hasApplicableType(ts, t))) strictTypesError(it, `missing type "${type.join(",")}" for keyword "${keyword}"`); - } - } - } - function hasApplicableType(schTs, kwdT) { - return schTs.includes(kwdT) || kwdT === "number" && schTs.includes("integer"); - } - function includesType(ts, t) { - return ts.includes(t) || t === "integer" && ts.includes("number"); - } - function narrowSchemaTypes(it, withTypes) { - const ts = []; - for (const t of it.dataTypes) if (includesType(withTypes, t)) ts.push(t); - else if (withTypes.includes("integer") && t === "number") ts.push("integer"); - it.dataTypes = ts; - } - function strictTypesError(it, msg) { - const schemaPath = it.schemaEnv.baseId + it.errSchemaPath; - msg += ` at "${schemaPath}" (strictTypes)`; - (0, util_1.checkStrictMode)(it, msg, it.opts.strictTypes); - } - var KeywordCxt = class { - constructor(it, def, keyword) { - (0, keyword_1.validateKeywordUsage)(it, def, keyword); - this.gen = it.gen; - this.allErrors = it.allErrors; - this.keyword = keyword; - this.data = it.data; - this.schema = it.schema[keyword]; - this.$data = def.$data && it.opts.$data && this.schema && this.schema.$data; - this.schemaValue = (0, util_1.schemaRefOrVal)(it, this.schema, keyword, this.$data); - this.schemaType = def.schemaType; - this.parentSchema = it.schema; - this.params = {}; - this.it = it; - this.def = def; - if (this.$data) this.schemaCode = it.gen.const("vSchema", getData(this.$data, it)); - else { - this.schemaCode = this.schemaValue; - if (!(0, keyword_1.validSchemaType)(this.schema, def.schemaType, def.allowUndefined)) throw new Error(`${keyword} value must be ${JSON.stringify(def.schemaType)}`); - } - if ("code" in def ? def.trackErrors : def.errors !== false) this.errsCount = it.gen.const("_errs", names_1.default.errors); - } - result(condition, successAction, failAction) { - this.failResult((0, codegen_1.not)(condition), successAction, failAction); - } - failResult(condition, successAction, failAction) { - this.gen.if(condition); - if (failAction) failAction(); - else this.error(); - if (successAction) { - this.gen.else(); - successAction(); - if (this.allErrors) this.gen.endIf(); - } else if (this.allErrors) this.gen.endIf(); - else this.gen.else(); - } - pass(condition, failAction) { - this.failResult((0, codegen_1.not)(condition), void 0, failAction); - } - fail(condition) { - if (condition === void 0) { - this.error(); - if (!this.allErrors) this.gen.if(false); - return; - } - this.gen.if(condition); - this.error(); - if (this.allErrors) this.gen.endIf(); - else this.gen.else(); - } - fail$data(condition) { - if (!this.$data) return this.fail(condition); - const { schemaCode } = this; - this.fail((0, codegen_1._)`${schemaCode} !== undefined && (${(0, codegen_1.or)(this.invalid$data(), condition)})`); - } - error(append, errorParams, errorPaths) { - if (errorParams) { - this.setParams(errorParams); - this._error(append, errorPaths); - this.setParams({}); - return; - } - this._error(append, errorPaths); - } - _error(append, errorPaths) { - (append ? errors_1.reportExtraError : errors_1.reportError)(this, this.def.error, errorPaths); - } - $dataError() { - (0, errors_1.reportError)(this, this.def.$dataError || errors_1.keyword$DataError); - } - reset() { - if (this.errsCount === void 0) throw new Error("add \"trackErrors\" to keyword definition"); - (0, errors_1.resetErrorsCount)(this.gen, this.errsCount); - } - ok(cond) { - if (!this.allErrors) this.gen.if(cond); - } - setParams(obj, assign) { - if (assign) Object.assign(this.params, obj); - else this.params = obj; - } - block$data(valid, codeBlock, $dataValid = codegen_1.nil) { - this.gen.block(() => { - this.check$data(valid, $dataValid); - codeBlock(); - }); - } - check$data(valid = codegen_1.nil, $dataValid = codegen_1.nil) { - if (!this.$data) return; - const { gen, schemaCode, schemaType, def } = this; - gen.if((0, codegen_1.or)((0, codegen_1._)`${schemaCode} === undefined`, $dataValid)); - if (valid !== codegen_1.nil) gen.assign(valid, true); - if (schemaType.length || def.validateSchema) { - gen.elseIf(this.invalid$data()); - this.$dataError(); - if (valid !== codegen_1.nil) gen.assign(valid, false); - } - gen.else(); - } - invalid$data() { - const { gen, schemaCode, schemaType, def, it } = this; - return (0, codegen_1.or)(wrong$DataType(), invalid$DataSchema()); - function wrong$DataType() { - if (schemaType.length) { - /* istanbul ignore if */ - if (!(schemaCode instanceof codegen_1.Name)) throw new Error("ajv implementation error"); - const st = Array.isArray(schemaType) ? schemaType : [schemaType]; - return (0, codegen_1._)`${(0, dataType_2.checkDataTypes)(st, schemaCode, it.opts.strictNumbers, dataType_2.DataType.Wrong)}`; - } - return codegen_1.nil; - } - function invalid$DataSchema() { - if (def.validateSchema) { - const validateSchemaRef = gen.scopeValue("validate$data", { ref: def.validateSchema }); - return (0, codegen_1._)`!${validateSchemaRef}(${schemaCode})`; - } - return codegen_1.nil; - } - } - subschema(appl, valid) { - const subschema = (0, subschema_1.getSubschema)(this.it, appl); - (0, subschema_1.extendSubschemaData)(subschema, this.it, appl); - (0, subschema_1.extendSubschemaMode)(subschema, appl); - const nextContext = { - ...this.it, - ...subschema, - items: void 0, - props: void 0 - }; - subschemaCode(nextContext, valid); - return nextContext; - } - mergeEvaluated(schemaCxt, toName) { - const { it, gen } = this; - if (!it.opts.unevaluated) return; - if (it.props !== true && schemaCxt.props !== void 0) it.props = util_1.mergeEvaluated.props(gen, schemaCxt.props, it.props, toName); - if (it.items !== true && schemaCxt.items !== void 0) it.items = util_1.mergeEvaluated.items(gen, schemaCxt.items, it.items, toName); - } - mergeValidEvaluated(schemaCxt, valid) { - const { it, gen } = this; - if (it.opts.unevaluated && (it.props !== true || it.items !== true)) { - gen.if(valid, () => this.mergeEvaluated(schemaCxt, codegen_1.Name)); - return true; - } - } - }; - exports.KeywordCxt = KeywordCxt; - function keywordCode(it, keyword, def, ruleType) { - const cxt = new KeywordCxt(it, def, keyword); - if ("code" in def) def.code(cxt, ruleType); - else if (cxt.$data && def.validate) (0, keyword_1.funcKeywordCode)(cxt, def); - else if ("macro" in def) (0, keyword_1.macroKeywordCode)(cxt, def); - else if (def.compile || def.validate) (0, keyword_1.funcKeywordCode)(cxt, def); - } - const JSON_POINTER = /^\/(?:[^~]|~0|~1)*$/; - const RELATIVE_JSON_POINTER = /^([0-9]+)(#|\/(?:[^~]|~0|~1)*)?$/; - function getData($data, { dataLevel, dataNames, dataPathArr }) { - let jsonPointer; - let data; - if ($data === "") return names_1.default.rootData; - if ($data[0] === "/") { - if (!JSON_POINTER.test($data)) throw new Error(`Invalid JSON-pointer: ${$data}`); - jsonPointer = $data; - data = names_1.default.rootData; - } else { - const matches = RELATIVE_JSON_POINTER.exec($data); - if (!matches) throw new Error(`Invalid JSON-pointer: ${$data}`); - const up = +matches[1]; - jsonPointer = matches[2]; - if (jsonPointer === "#") { - if (up >= dataLevel) throw new Error(errorMsg("property/index", up)); - return dataPathArr[dataLevel - up]; - } - if (up > dataLevel) throw new Error(errorMsg("data", up)); - data = dataNames[dataLevel - up]; - if (!jsonPointer) return data; - } - let expr = data; - const segments = jsonPointer.split("/"); - for (const segment of segments) if (segment) { - data = (0, codegen_1._)`${data}${(0, codegen_1.getProperty)((0, util_1.unescapeJsonPointer)(segment))}`; - expr = (0, codegen_1._)`${expr} && ${data}`; - } - return expr; - function errorMsg(pointerType, up) { - return `Cannot access ${pointerType} ${up} levels up, current level is ${dataLevel}`; - } - } - exports.getData = getData; -})); - -//#endregion -//#region ../../node_modules/.pnpm/ajv@8.18.0/node_modules/ajv/dist/runtime/validation_error.js -var require_validation_error = /* @__PURE__ */ __commonJSMin(((exports) => { - Object.defineProperty(exports, "__esModule", { value: true }); - var ValidationError = class extends Error { - constructor(errors) { - super("validation failed"); - this.errors = errors; - this.ajv = this.validation = true; - } - }; - exports.default = ValidationError; -})); - -//#endregion -//#region ../../node_modules/.pnpm/ajv@8.18.0/node_modules/ajv/dist/compile/ref_error.js -var require_ref_error = /* @__PURE__ */ __commonJSMin(((exports) => { - Object.defineProperty(exports, "__esModule", { value: true }); - const resolve_1 = require_resolve(); - var MissingRefError = class extends Error { - constructor(resolver, baseId, ref, msg) { - super(msg || `can't resolve reference ${ref} from id ${baseId}`); - this.missingRef = (0, resolve_1.resolveUrl)(resolver, baseId, ref); - this.missingSchema = (0, resolve_1.normalizeId)((0, resolve_1.getFullPath)(resolver, this.missingRef)); - } - }; - exports.default = MissingRefError; -})); - -//#endregion -//#region ../../node_modules/.pnpm/ajv@8.18.0/node_modules/ajv/dist/compile/index.js -var require_compile = /* @__PURE__ */ __commonJSMin(((exports) => { - Object.defineProperty(exports, "__esModule", { value: true }); - exports.resolveSchema = exports.getCompilingSchema = exports.resolveRef = exports.compileSchema = exports.SchemaEnv = void 0; - const codegen_1 = require_codegen(); - const validation_error_1 = require_validation_error(); - const names_1 = require_names(); - const resolve_1 = require_resolve(); - const util_1 = require_util(); - const validate_1 = require_validate(); - var SchemaEnv = class { - constructor(env) { - var _a; - this.refs = {}; - this.dynamicAnchors = {}; - let schema; - if (typeof env.schema == "object") schema = env.schema; - this.schema = env.schema; - this.schemaId = env.schemaId; - this.root = env.root || this; - this.baseId = (_a = env.baseId) !== null && _a !== void 0 ? _a : (0, resolve_1.normalizeId)(schema === null || schema === void 0 ? void 0 : schema[env.schemaId || "$id"]); - this.schemaPath = env.schemaPath; - this.localRefs = env.localRefs; - this.meta = env.meta; - this.$async = schema === null || schema === void 0 ? void 0 : schema.$async; - this.refs = {}; - } - }; - exports.SchemaEnv = SchemaEnv; - function compileSchema(sch) { - const _sch = getCompilingSchema.call(this, sch); - if (_sch) return _sch; - const rootId = (0, resolve_1.getFullPath)(this.opts.uriResolver, sch.root.baseId); - const { es5, lines } = this.opts.code; - const { ownProperties } = this.opts; - const gen = new codegen_1.CodeGen(this.scope, { - es5, - lines, - ownProperties - }); - let _ValidationError; - if (sch.$async) _ValidationError = gen.scopeValue("Error", { - ref: validation_error_1.default, - code: (0, codegen_1._)`require("ajv/dist/runtime/validation_error").default` - }); - const validateName = gen.scopeName("validate"); - sch.validateName = validateName; - const schemaCxt = { - gen, - allErrors: this.opts.allErrors, - data: names_1.default.data, - parentData: names_1.default.parentData, - parentDataProperty: names_1.default.parentDataProperty, - dataNames: [names_1.default.data], - dataPathArr: [codegen_1.nil], - dataLevel: 0, - dataTypes: [], - definedProperties: /* @__PURE__ */ new Set(), - topSchemaRef: gen.scopeValue("schema", this.opts.code.source === true ? { - ref: sch.schema, - code: (0, codegen_1.stringify)(sch.schema) - } : { ref: sch.schema }), - validateName, - ValidationError: _ValidationError, - schema: sch.schema, - schemaEnv: sch, - rootId, - baseId: sch.baseId || rootId, - schemaPath: codegen_1.nil, - errSchemaPath: sch.schemaPath || (this.opts.jtd ? "" : "#"), - errorPath: (0, codegen_1._)`""`, - opts: this.opts, - self: this - }; - let sourceCode; - try { - this._compilations.add(sch); - (0, validate_1.validateFunctionCode)(schemaCxt); - gen.optimize(this.opts.code.optimize); - const validateCode = gen.toString(); - sourceCode = `${gen.scopeRefs(names_1.default.scope)}return ${validateCode}`; - if (this.opts.code.process) sourceCode = this.opts.code.process(sourceCode, sch); - const validate = new Function(`${names_1.default.self}`, `${names_1.default.scope}`, sourceCode)(this, this.scope.get()); - this.scope.value(validateName, { ref: validate }); - validate.errors = null; - validate.schema = sch.schema; - validate.schemaEnv = sch; - if (sch.$async) validate.$async = true; - if (this.opts.code.source === true) validate.source = { - validateName, - validateCode, - scopeValues: gen._values - }; - if (this.opts.unevaluated) { - const { props, items } = schemaCxt; - validate.evaluated = { - props: props instanceof codegen_1.Name ? void 0 : props, - items: items instanceof codegen_1.Name ? void 0 : items, - dynamicProps: props instanceof codegen_1.Name, - dynamicItems: items instanceof codegen_1.Name - }; - if (validate.source) validate.source.evaluated = (0, codegen_1.stringify)(validate.evaluated); - } - sch.validate = validate; - return sch; - } catch (e) { - delete sch.validate; - delete sch.validateName; - if (sourceCode) this.logger.error("Error compiling schema, function code:", sourceCode); - throw e; - } finally { - this._compilations.delete(sch); - } - } - exports.compileSchema = compileSchema; - function resolveRef(root, baseId, ref) { - var _a; - ref = (0, resolve_1.resolveUrl)(this.opts.uriResolver, baseId, ref); - const schOrFunc = root.refs[ref]; - if (schOrFunc) return schOrFunc; - let _sch = resolve.call(this, root, ref); - if (_sch === void 0) { - const schema = (_a = root.localRefs) === null || _a === void 0 ? void 0 : _a[ref]; - const { schemaId } = this.opts; - if (schema) _sch = new SchemaEnv({ - schema, - schemaId, - root, - baseId - }); - } - if (_sch === void 0) return; - return root.refs[ref] = inlineOrCompile.call(this, _sch); - } - exports.resolveRef = resolveRef; - function inlineOrCompile(sch) { - if ((0, resolve_1.inlineRef)(sch.schema, this.opts.inlineRefs)) return sch.schema; - return sch.validate ? sch : compileSchema.call(this, sch); - } - function getCompilingSchema(schEnv) { - for (const sch of this._compilations) if (sameSchemaEnv(sch, schEnv)) return sch; - } - exports.getCompilingSchema = getCompilingSchema; - function sameSchemaEnv(s1, s2) { - return s1.schema === s2.schema && s1.root === s2.root && s1.baseId === s2.baseId; - } - function resolve(root, ref) { - let sch; - while (typeof (sch = this.refs[ref]) == "string") ref = sch; - return sch || this.schemas[ref] || resolveSchema.call(this, root, ref); - } - function resolveSchema(root, ref) { - const p = this.opts.uriResolver.parse(ref); - const refPath = (0, resolve_1._getFullPath)(this.opts.uriResolver, p); - let baseId = (0, resolve_1.getFullPath)(this.opts.uriResolver, root.baseId, void 0); - if (Object.keys(root.schema).length > 0 && refPath === baseId) return getJsonPointer.call(this, p, root); - const id = (0, resolve_1.normalizeId)(refPath); - const schOrRef = this.refs[id] || this.schemas[id]; - if (typeof schOrRef == "string") { - const sch = resolveSchema.call(this, root, schOrRef); - if (typeof (sch === null || sch === void 0 ? void 0 : sch.schema) !== "object") return; - return getJsonPointer.call(this, p, sch); - } - if (typeof (schOrRef === null || schOrRef === void 0 ? void 0 : schOrRef.schema) !== "object") return; - if (!schOrRef.validate) compileSchema.call(this, schOrRef); - if (id === (0, resolve_1.normalizeId)(ref)) { - const { schema } = schOrRef; - const { schemaId } = this.opts; - const schId = schema[schemaId]; - if (schId) baseId = (0, resolve_1.resolveUrl)(this.opts.uriResolver, baseId, schId); - return new SchemaEnv({ - schema, - schemaId, - root, - baseId - }); - } - return getJsonPointer.call(this, p, schOrRef); - } - exports.resolveSchema = resolveSchema; - const PREVENT_SCOPE_CHANGE = new Set([ - "properties", - "patternProperties", - "enum", - "dependencies", - "definitions" - ]); - function getJsonPointer(parsedRef, { baseId, schema, root }) { - var _a; - if (((_a = parsedRef.fragment) === null || _a === void 0 ? void 0 : _a[0]) !== "/") return; - for (const part of parsedRef.fragment.slice(1).split("/")) { - if (typeof schema === "boolean") return; - const partSchema = schema[(0, util_1.unescapeFragment)(part)]; - if (partSchema === void 0) return; - schema = partSchema; - const schId = typeof schema === "object" && schema[this.opts.schemaId]; - if (!PREVENT_SCOPE_CHANGE.has(part) && schId) baseId = (0, resolve_1.resolveUrl)(this.opts.uriResolver, baseId, schId); - } - let env; - if (typeof schema != "boolean" && schema.$ref && !(0, util_1.schemaHasRulesButRef)(schema, this.RULES)) { - const $ref = (0, resolve_1.resolveUrl)(this.opts.uriResolver, baseId, schema.$ref); - env = resolveSchema.call(this, root, $ref); - } - const { schemaId } = this.opts; - env = env || new SchemaEnv({ - schema, - schemaId, - root, - baseId - }); - if (env.schema !== env.root.schema) return env; - } -})); - -//#endregion -//#region ../../node_modules/.pnpm/ajv@8.18.0/node_modules/ajv/dist/refs/data.json -var require_data = /* @__PURE__ */ __commonJSMin(((exports, module) => { - module.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": false - }; -})); - -//#endregion -//#region ../../node_modules/.pnpm/fast-uri@3.1.0/node_modules/fast-uri/lib/utils.js -var require_utils = /* @__PURE__ */ __commonJSMin(((exports, module) => { - /** @type {(value: string) => boolean} */ - const isUUID = RegExp.prototype.test.bind(/^[\da-f]{8}-[\da-f]{4}-[\da-f]{4}-[\da-f]{4}-[\da-f]{12}$/iu); - /** @type {(value: string) => boolean} */ - const isIPv4 = 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); - /** - * @param {Array} input - * @returns {string} - */ - function stringArrayToHexStripped(input) { - let acc = ""; - let code = 0; - let i = 0; - for (i = 0; i < input.length; i++) { - code = input[i].charCodeAt(0); - if (code === 48) continue; - if (!(code >= 48 && code <= 57 || code >= 65 && code <= 70 || code >= 97 && code <= 102)) return ""; - acc += input[i]; - break; - } - for (i += 1; i < input.length; i++) { - code = input[i].charCodeAt(0); - if (!(code >= 48 && code <= 57 || code >= 65 && code <= 70 || code >= 97 && code <= 102)) return ""; - acc += input[i]; - } - return acc; - } - /** - * @typedef {Object} GetIPV6Result - * @property {boolean} error - Indicates if there was an error parsing the IPv6 address. - * @property {string} address - The parsed IPv6 address. - * @property {string} [zone] - The zone identifier, if present. - */ - /** - * @param {string} value - * @returns {boolean} - */ - const nonSimpleDomain = RegExp.prototype.test.bind(/[^!"$&'()*+,\-.;=_`a-z{}~]/u); - /** - * @param {Array} buffer - * @returns {boolean} - */ - function consumeIsZone(buffer) { - buffer.length = 0; - return true; - } - /** - * @param {Array} buffer - * @param {Array} address - * @param {GetIPV6Result} output - * @returns {boolean} - */ - function consumeHextets(buffer, address, output) { - if (buffer.length) { - const hex = stringArrayToHexStripped(buffer); - if (hex !== "") address.push(hex); - else { - output.error = true; - return false; - } - buffer.length = 0; - } - return true; - } - /** - * @param {string} input - * @returns {GetIPV6Result} - */ - function getIPV6(input) { - let tokenCount = 0; - const output = { - error: false, - address: "", - zone: "" - }; - /** @type {Array} */ - const address = []; - /** @type {Array} */ - const buffer = []; - let endipv6Encountered = false; - let endIpv6 = false; - let consume = consumeHextets; - for (let i = 0; i < input.length; i++) { - const cursor = input[i]; - if (cursor === "[" || cursor === "]") continue; - if (cursor === ":") { - if (endipv6Encountered === true) endIpv6 = true; - if (!consume(buffer, address, output)) break; - if (++tokenCount > 7) { - output.error = true; - break; - } - if (i > 0 && input[i - 1] === ":") endipv6Encountered = true; - address.push(":"); - continue; - } else if (cursor === "%") { - if (!consume(buffer, address, output)) break; - consume = consumeIsZone; - } else { - buffer.push(cursor); - continue; - } - } - if (buffer.length) if (consume === consumeIsZone) output.zone = buffer.join(""); - else if (endIpv6) address.push(buffer.join("")); - else address.push(stringArrayToHexStripped(buffer)); - output.address = address.join(""); - return output; - } - /** - * @typedef {Object} NormalizeIPv6Result - * @property {string} host - The normalized host. - * @property {string} [escapedHost] - The escaped host. - * @property {boolean} isIPV6 - Indicates if the host is an IPv6 address. - */ - /** - * @param {string} host - * @returns {NormalizeIPv6Result} - */ - function normalizeIPv6(host) { - if (findToken(host, ":") < 2) return { - host, - isIPV6: false - }; - const ipv6 = getIPV6(host); - if (!ipv6.error) { - let newHost = ipv6.address; - let escapedHost = ipv6.address; - if (ipv6.zone) { - newHost += "%" + ipv6.zone; - escapedHost += "%25" + ipv6.zone; - } - return { - host: newHost, - isIPV6: true, - escapedHost - }; - } else return { - host, - isIPV6: false - }; - } - /** - * @param {string} str - * @param {string} token - * @returns {number} - */ - function findToken(str, token) { - let ind = 0; - for (let i = 0; i < str.length; i++) if (str[i] === token) ind++; - return ind; - } - /** - * @param {string} path - * @returns {string} - * - * @see https://datatracker.ietf.org/doc/html/rfc3986#section-5.2.4 - */ - function removeDotSegments(path) { - let input = path; - const output = []; - let nextSlash = -1; - let len = 0; - while (len = input.length) { - if (len === 1) if (input === ".") break; - else if (input === "/") { - output.push("/"); - break; - } else { - output.push(input); - break; - } - else if (len === 2) { - if (input[0] === ".") { - if (input[1] === ".") break; - else if (input[1] === "/") { - input = input.slice(2); - continue; - } - } else if (input[0] === "/") { - if (input[1] === "." || input[1] === "/") { - output.push("/"); - break; - } - } - } else if (len === 3) { - if (input === "/..") { - if (output.length !== 0) output.pop(); - output.push("/"); - break; - } - } - if (input[0] === ".") { - if (input[1] === ".") { - if (input[2] === "/") { - input = input.slice(3); - continue; - } - } else if (input[1] === "/") { - input = input.slice(2); - continue; - } - } else if (input[0] === "/") { - if (input[1] === ".") { - if (input[2] === "/") { - input = input.slice(2); - continue; - } else if (input[2] === ".") { - if (input[3] === "/") { - input = input.slice(3); - if (output.length !== 0) output.pop(); - continue; - } - } - } - } - if ((nextSlash = input.indexOf("/", 1)) === -1) { - output.push(input); - break; - } else { - output.push(input.slice(0, nextSlash)); - input = input.slice(nextSlash); - } - } - return output.join(""); - } - /** - * @param {import('../types/index').URIComponent} component - * @param {boolean} esc - * @returns {import('../types/index').URIComponent} - */ - function normalizeComponentEncoding(component, esc) { - const func = esc !== true ? escape : unescape; - if (component.scheme !== void 0) component.scheme = func(component.scheme); - if (component.userinfo !== void 0) component.userinfo = func(component.userinfo); - if (component.host !== void 0) component.host = func(component.host); - if (component.path !== void 0) component.path = func(component.path); - if (component.query !== void 0) component.query = func(component.query); - if (component.fragment !== void 0) component.fragment = func(component.fragment); - return component; - } - /** - * @param {import('../types/index').URIComponent} component - * @returns {string|undefined} - */ - function recomposeAuthority(component) { - const uriTokens = []; - if (component.userinfo !== void 0) { - uriTokens.push(component.userinfo); - uriTokens.push("@"); - } - if (component.host !== void 0) { - let host = unescape(component.host); - if (!isIPv4(host)) { - const ipV6res = normalizeIPv6(host); - if (ipV6res.isIPV6 === true) host = `[${ipV6res.escapedHost}]`; - else host = component.host; - } - uriTokens.push(host); - } - if (typeof component.port === "number" || typeof component.port === "string") { - uriTokens.push(":"); - uriTokens.push(String(component.port)); - } - return uriTokens.length ? uriTokens.join("") : void 0; - } - module.exports = { - nonSimpleDomain, - recomposeAuthority, - normalizeComponentEncoding, - removeDotSegments, - isIPv4, - isUUID, - normalizeIPv6, - stringArrayToHexStripped - }; -})); - -//#endregion -//#region ../../node_modules/.pnpm/fast-uri@3.1.0/node_modules/fast-uri/lib/schemes.js -var require_schemes = /* @__PURE__ */ __commonJSMin(((exports, module) => { - const { isUUID } = require_utils(); - const URN_REG = /([\da-z][\d\-a-z]{0,31}):((?:[\w!$'()*+,\-.:;=@]|%[\da-f]{2})+)/iu; - const supportedSchemeNames = [ - "http", - "https", - "ws", - "wss", - "urn", - "urn:uuid" - ]; - /** @typedef {supportedSchemeNames[number]} SchemeName */ - /** - * @param {string} name - * @returns {name is SchemeName} - */ - function isValidSchemeName(name) { - return supportedSchemeNames.indexOf(name) !== -1; - } - /** - * @callback SchemeFn - * @param {import('../types/index').URIComponent} component - * @param {import('../types/index').Options} options - * @returns {import('../types/index').URIComponent} - */ - /** - * @typedef {Object} SchemeHandler - * @property {SchemeName} scheme - The scheme name. - * @property {boolean} [domainHost] - Indicates if the scheme supports domain hosts. - * @property {SchemeFn} parse - Function to parse the URI component for this scheme. - * @property {SchemeFn} serialize - Function to serialize the URI component for this scheme. - * @property {boolean} [skipNormalize] - Indicates if normalization should be skipped for this scheme. - * @property {boolean} [absolutePath] - Indicates if the scheme uses absolute paths. - * @property {boolean} [unicodeSupport] - Indicates if the scheme supports Unicode. - */ - /** - * @param {import('../types/index').URIComponent} wsComponent - * @returns {boolean} - */ - function wsIsSecure(wsComponent) { - if (wsComponent.secure === true) return true; - else if (wsComponent.secure === false) return false; - else if (wsComponent.scheme) return wsComponent.scheme.length === 3 && (wsComponent.scheme[0] === "w" || wsComponent.scheme[0] === "W") && (wsComponent.scheme[1] === "s" || wsComponent.scheme[1] === "S") && (wsComponent.scheme[2] === "s" || wsComponent.scheme[2] === "S"); - else return false; - } - /** @type {SchemeFn} */ - function httpParse(component) { - if (!component.host) component.error = component.error || "HTTP URIs must have a host."; - return component; - } - /** @type {SchemeFn} */ - function httpSerialize(component) { - const secure = String(component.scheme).toLowerCase() === "https"; - if (component.port === (secure ? 443 : 80) || component.port === "") component.port = void 0; - if (!component.path) component.path = "/"; - return component; - } - /** @type {SchemeFn} */ - function wsParse(wsComponent) { - wsComponent.secure = wsIsSecure(wsComponent); - wsComponent.resourceName = (wsComponent.path || "/") + (wsComponent.query ? "?" + wsComponent.query : ""); - wsComponent.path = void 0; - wsComponent.query = void 0; - return wsComponent; - } - /** @type {SchemeFn} */ - function wsSerialize(wsComponent) { - if (wsComponent.port === (wsIsSecure(wsComponent) ? 443 : 80) || wsComponent.port === "") wsComponent.port = void 0; - if (typeof wsComponent.secure === "boolean") { - wsComponent.scheme = wsComponent.secure ? "wss" : "ws"; - wsComponent.secure = void 0; - } - if (wsComponent.resourceName) { - const [path, query] = wsComponent.resourceName.split("?"); - wsComponent.path = path && path !== "/" ? path : void 0; - wsComponent.query = query; - wsComponent.resourceName = void 0; - } - wsComponent.fragment = void 0; - return wsComponent; - } - /** @type {SchemeFn} */ - function urnParse(urnComponent, options) { - if (!urnComponent.path) { - urnComponent.error = "URN can not be parsed"; - return urnComponent; - } - const matches = urnComponent.path.match(URN_REG); - if (matches) { - const scheme = options.scheme || urnComponent.scheme || "urn"; - urnComponent.nid = matches[1].toLowerCase(); - urnComponent.nss = matches[2]; - const schemeHandler = getSchemeHandler(`${scheme}:${options.nid || urnComponent.nid}`); - urnComponent.path = void 0; - if (schemeHandler) urnComponent = schemeHandler.parse(urnComponent, options); - } else urnComponent.error = urnComponent.error || "URN can not be parsed."; - return urnComponent; - } - /** @type {SchemeFn} */ - function urnSerialize(urnComponent, options) { - if (urnComponent.nid === void 0) throw new Error("URN without nid cannot be serialized"); - const scheme = options.scheme || urnComponent.scheme || "urn"; - const nid = urnComponent.nid.toLowerCase(); - const schemeHandler = getSchemeHandler(`${scheme}:${options.nid || nid}`); - if (schemeHandler) urnComponent = schemeHandler.serialize(urnComponent, options); - const uriComponent = urnComponent; - const nss = urnComponent.nss; - uriComponent.path = `${nid || options.nid}:${nss}`; - options.skipEscape = true; - return uriComponent; - } - /** @type {SchemeFn} */ - function urnuuidParse(urnComponent, options) { - const uuidComponent = urnComponent; - uuidComponent.uuid = uuidComponent.nss; - uuidComponent.nss = void 0; - if (!options.tolerant && (!uuidComponent.uuid || !isUUID(uuidComponent.uuid))) uuidComponent.error = uuidComponent.error || "UUID is not valid."; - return uuidComponent; - } - /** @type {SchemeFn} */ - function urnuuidSerialize(uuidComponent) { - const urnComponent = uuidComponent; - urnComponent.nss = (uuidComponent.uuid || "").toLowerCase(); - return urnComponent; - } - const http = { - scheme: "http", - domainHost: true, - parse: httpParse, - serialize: httpSerialize - }; - const https = { - scheme: "https", - domainHost: http.domainHost, - parse: httpParse, - serialize: httpSerialize - }; - const ws = { - scheme: "ws", - domainHost: true, - parse: wsParse, - serialize: wsSerialize - }; - const wss = { - scheme: "wss", - domainHost: ws.domainHost, - parse: ws.parse, - serialize: ws.serialize - }; - const urn = { - scheme: "urn", - parse: urnParse, - serialize: urnSerialize, - skipNormalize: true - }; - const urnuuid = { - scheme: "urn:uuid", - parse: urnuuidParse, - serialize: urnuuidSerialize, - skipNormalize: true - }; - const SCHEMES = { - http, - https, - ws, - wss, - urn, - "urn:uuid": urnuuid - }; - Object.setPrototypeOf(SCHEMES, null); - /** - * @param {string|undefined} scheme - * @returns {SchemeHandler|undefined} - */ - function getSchemeHandler(scheme) { - return scheme && (SCHEMES[scheme] || SCHEMES[scheme.toLowerCase()]) || void 0; - } - module.exports = { - wsIsSecure, - SCHEMES, - isValidSchemeName, - getSchemeHandler - }; -})); - -//#endregion -//#region ../../node_modules/.pnpm/fast-uri@3.1.0/node_modules/fast-uri/index.js -var require_fast_uri = /* @__PURE__ */ __commonJSMin(((exports, module) => { - const { normalizeIPv6, removeDotSegments, recomposeAuthority, normalizeComponentEncoding, isIPv4, nonSimpleDomain } = require_utils(); - const { SCHEMES, getSchemeHandler } = require_schemes(); - /** - * @template {import('./types/index').URIComponent|string} T - * @param {T} uri - * @param {import('./types/index').Options} [options] - * @returns {T} - */ - function normalize(uri, options) { - if (typeof uri === "string") uri = serialize(parse(uri, options), options); - else if (typeof uri === "object") uri = parse(serialize(uri, options), options); - return uri; - } - /** - * @param {string} baseURI - * @param {string} relativeURI - * @param {import('./types/index').Options} [options] - * @returns {string} - */ - function resolve(baseURI, relativeURI, options) { - const schemelessOptions = options ? Object.assign({ scheme: "null" }, options) : { scheme: "null" }; - const resolved = resolveComponent(parse(baseURI, schemelessOptions), parse(relativeURI, schemelessOptions), schemelessOptions, true); - schemelessOptions.skipEscape = true; - return serialize(resolved, schemelessOptions); - } - /** - * @param {import ('./types/index').URIComponent} base - * @param {import ('./types/index').URIComponent} relative - * @param {import('./types/index').Options} [options] - * @param {boolean} [skipNormalization=false] - * @returns {import ('./types/index').URIComponent} - */ - function resolveComponent(base, relative, options, skipNormalization) { - /** @type {import('./types/index').URIComponent} */ - const target = {}; - if (!skipNormalization) { - base = parse(serialize(base, options), options); - relative = parse(serialize(relative, options), options); - } - options = options || {}; - if (!options.tolerant && relative.scheme) { - target.scheme = relative.scheme; - target.userinfo = relative.userinfo; - target.host = relative.host; - target.port = relative.port; - target.path = removeDotSegments(relative.path || ""); - target.query = relative.query; - } else { - if (relative.userinfo !== void 0 || relative.host !== void 0 || relative.port !== void 0) { - target.userinfo = relative.userinfo; - target.host = relative.host; - target.port = relative.port; - target.path = removeDotSegments(relative.path || ""); - target.query = relative.query; - } else { - if (!relative.path) { - target.path = base.path; - if (relative.query !== void 0) target.query = relative.query; - else target.query = base.query; - } else { - if (relative.path[0] === "/") target.path = removeDotSegments(relative.path); - else { - if ((base.userinfo !== void 0 || base.host !== void 0 || base.port !== void 0) && !base.path) target.path = "/" + relative.path; - else if (!base.path) target.path = relative.path; - else target.path = base.path.slice(0, base.path.lastIndexOf("/") + 1) + relative.path; - target.path = removeDotSegments(target.path); - } - target.query = relative.query; - } - target.userinfo = base.userinfo; - target.host = base.host; - target.port = base.port; - } - target.scheme = base.scheme; - } - target.fragment = relative.fragment; - return target; - } - /** - * @param {import ('./types/index').URIComponent|string} uriA - * @param {import ('./types/index').URIComponent|string} uriB - * @param {import ('./types/index').Options} options - * @returns {boolean} - */ - function equal(uriA, uriB, options) { - if (typeof uriA === "string") { - uriA = unescape(uriA); - uriA = serialize(normalizeComponentEncoding(parse(uriA, options), true), { - ...options, - skipEscape: true - }); - } else if (typeof uriA === "object") uriA = serialize(normalizeComponentEncoding(uriA, true), { - ...options, - skipEscape: true - }); - if (typeof uriB === "string") { - uriB = unescape(uriB); - uriB = serialize(normalizeComponentEncoding(parse(uriB, options), true), { - ...options, - skipEscape: true - }); - } else if (typeof uriB === "object") uriB = serialize(normalizeComponentEncoding(uriB, true), { - ...options, - skipEscape: true - }); - return uriA.toLowerCase() === uriB.toLowerCase(); - } - /** - * @param {Readonly} cmpts - * @param {import('./types/index').Options} [opts] - * @returns {string} - */ - function serialize(cmpts, opts) { - const component = { - host: cmpts.host, - scheme: cmpts.scheme, - userinfo: cmpts.userinfo, - port: cmpts.port, - path: cmpts.path, - query: cmpts.query, - nid: cmpts.nid, - nss: cmpts.nss, - uuid: cmpts.uuid, - fragment: cmpts.fragment, - reference: cmpts.reference, - resourceName: cmpts.resourceName, - secure: cmpts.secure, - error: "" - }; - const options = Object.assign({}, opts); - const uriTokens = []; - const schemeHandler = getSchemeHandler(options.scheme || component.scheme); - if (schemeHandler && schemeHandler.serialize) schemeHandler.serialize(component, options); - if (component.path !== void 0) if (!options.skipEscape) { - component.path = escape(component.path); - if (component.scheme !== void 0) component.path = component.path.split("%3A").join(":"); - } else component.path = unescape(component.path); - if (options.reference !== "suffix" && component.scheme) uriTokens.push(component.scheme, ":"); - const authority = recomposeAuthority(component); - if (authority !== void 0) { - if (options.reference !== "suffix") uriTokens.push("//"); - uriTokens.push(authority); - if (component.path && component.path[0] !== "/") uriTokens.push("/"); - } - if (component.path !== void 0) { - let s = component.path; - if (!options.absolutePath && (!schemeHandler || !schemeHandler.absolutePath)) s = removeDotSegments(s); - if (authority === void 0 && s[0] === "/" && s[1] === "/") s = "/%2F" + s.slice(2); - uriTokens.push(s); - } - if (component.query !== void 0) uriTokens.push("?", component.query); - if (component.fragment !== void 0) uriTokens.push("#", component.fragment); - return uriTokens.join(""); - } - const URI_PARSE = /^(?:([^#/:?]+):)?(?:\/\/((?:([^#/?@]*)@)?(\[[^#/?\]]+\]|[^#/:?]*)(?::(\d*))?))?([^#?]*)(?:\?([^#]*))?(?:#((?:.|[\n\r])*))?/u; - /** - * @param {string} uri - * @param {import('./types/index').Options} [opts] - * @returns - */ - function parse(uri, opts) { - const options = Object.assign({}, opts); - /** @type {import('./types/index').URIComponent} */ - const parsed = { - scheme: void 0, - userinfo: void 0, - host: "", - port: void 0, - path: "", - query: void 0, - fragment: void 0 - }; - let isIP = false; - if (options.reference === "suffix") if (options.scheme) uri = options.scheme + ":" + uri; - else uri = "//" + uri; - const matches = uri.match(URI_PARSE); - if (matches) { - parsed.scheme = matches[1]; - parsed.userinfo = matches[3]; - parsed.host = matches[4]; - parsed.port = parseInt(matches[5], 10); - parsed.path = matches[6] || ""; - parsed.query = matches[7]; - parsed.fragment = matches[8]; - if (isNaN(parsed.port)) parsed.port = matches[5]; - if (parsed.host) if (isIPv4(parsed.host) === false) { - const ipv6result = normalizeIPv6(parsed.host); - parsed.host = ipv6result.host.toLowerCase(); - isIP = ipv6result.isIPV6; - } else isIP = true; - if (parsed.scheme === void 0 && parsed.userinfo === void 0 && parsed.host === void 0 && parsed.port === void 0 && parsed.query === void 0 && !parsed.path) parsed.reference = "same-document"; - else if (parsed.scheme === void 0) parsed.reference = "relative"; - else if (parsed.fragment === void 0) parsed.reference = "absolute"; - else parsed.reference = "uri"; - if (options.reference && options.reference !== "suffix" && options.reference !== parsed.reference) parsed.error = parsed.error || "URI is not a " + options.reference + " reference."; - const schemeHandler = getSchemeHandler(options.scheme || parsed.scheme); - if (!options.unicodeSupport && (!schemeHandler || !schemeHandler.unicodeSupport)) { - if (parsed.host && (options.domainHost || schemeHandler && schemeHandler.domainHost) && isIP === false && nonSimpleDomain(parsed.host)) try { - parsed.host = URL.domainToASCII(parsed.host.toLowerCase()); - } catch (e) { - parsed.error = parsed.error || "Host's domain name can not be converted to ASCII: " + e; - } - } - if (!schemeHandler || schemeHandler && !schemeHandler.skipNormalize) { - if (uri.indexOf("%") !== -1) { - if (parsed.scheme !== void 0) parsed.scheme = unescape(parsed.scheme); - if (parsed.host !== void 0) parsed.host = unescape(parsed.host); - } - if (parsed.path) parsed.path = escape(unescape(parsed.path)); - if (parsed.fragment) parsed.fragment = encodeURI(decodeURIComponent(parsed.fragment)); - } - if (schemeHandler && schemeHandler.parse) schemeHandler.parse(parsed, options); - } else parsed.error = parsed.error || "URI can not be parsed."; - return parsed; - } - const fastUri = { - SCHEMES, - normalize, - resolve, - resolveComponent, - equal, - serialize, - parse - }; - module.exports = fastUri; - module.exports.default = fastUri; - module.exports.fastUri = fastUri; -})); - -//#endregion -//#region ../../node_modules/.pnpm/ajv@8.18.0/node_modules/ajv/dist/runtime/uri.js -var require_uri = /* @__PURE__ */ __commonJSMin(((exports) => { - Object.defineProperty(exports, "__esModule", { value: true }); - const uri = require_fast_uri(); - uri.code = "require(\"ajv/dist/runtime/uri\").default"; - exports.default = uri; -})); - -//#endregion -//#region ../../node_modules/.pnpm/ajv@8.18.0/node_modules/ajv/dist/core.js -var require_core$3 = /* @__PURE__ */ __commonJSMin(((exports) => { - Object.defineProperty(exports, "__esModule", { value: true }); - exports.CodeGen = exports.Name = exports.nil = exports.stringify = exports.str = exports._ = exports.KeywordCxt = void 0; - var validate_1 = require_validate(); - Object.defineProperty(exports, "KeywordCxt", { - enumerable: true, - get: function() { - return validate_1.KeywordCxt; - } - }); - var codegen_1 = require_codegen(); - Object.defineProperty(exports, "_", { - enumerable: true, - get: function() { - return codegen_1._; - } - }); - Object.defineProperty(exports, "str", { - enumerable: true, - get: function() { - return codegen_1.str; - } - }); - Object.defineProperty(exports, "stringify", { - enumerable: true, - get: function() { - return codegen_1.stringify; - } - }); - Object.defineProperty(exports, "nil", { - enumerable: true, - get: function() { - return codegen_1.nil; - } - }); - Object.defineProperty(exports, "Name", { - enumerable: true, - get: function() { - return codegen_1.Name; - } - }); - Object.defineProperty(exports, "CodeGen", { - enumerable: true, - get: function() { - return codegen_1.CodeGen; - } - }); - const validation_error_1 = require_validation_error(); - const ref_error_1 = require_ref_error(); - const rules_1 = require_rules(); - const compile_1 = require_compile(); - const codegen_2 = require_codegen(); - const resolve_1 = require_resolve(); - const dataType_1 = require_dataType(); - const util_1 = require_util(); - const $dataRefSchema = require_data(); - const uri_1 = require_uri(); - const defaultRegExp = (str, flags) => new RegExp(str, flags); - defaultRegExp.code = "new RegExp"; - const META_IGNORE_OPTIONS = [ - "removeAdditional", - "useDefaults", - "coerceTypes" - ]; - const EXT_SCOPE_NAMES = new Set([ - "validate", - "serialize", - "parse", - "wrapper", - "root", - "schema", - "keyword", - "pattern", - "formats", - "validate$data", - "func", - "obj", - "Error" - ]); - const removedOptions = { - 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." - }; - const deprecatedOptions = { - ignoreKeywordsWithRef: "", - jsPropertySyntax: "", - unicode: "\"minLength\"/\"maxLength\" account for unicode characters by default." - }; - const MAX_EXPRESSION = 200; - function requiredOptions(o) { - var _a, _b, _c, _d, _e, _f, _g, _h, _j, _k, _l, _m, _o, _p, _q, _r, _s, _t, _u, _v, _w, _x, _y, _z, _0; - const s = o.strict; - const _optz = (_a = o.code) === null || _a === void 0 ? void 0 : _a.optimize; - const optimize = _optz === true || _optz === void 0 ? 1 : _optz || 0; - const regExp = (_c = (_b = o.code) === null || _b === void 0 ? void 0 : _b.regExp) !== null && _c !== void 0 ? _c : defaultRegExp; - const uriResolver = (_d = o.uriResolver) !== null && _d !== void 0 ? _d : uri_1.default; - return { - strictSchema: (_f = (_e = o.strictSchema) !== null && _e !== void 0 ? _e : s) !== null && _f !== void 0 ? _f : true, - strictNumbers: (_h = (_g = o.strictNumbers) !== null && _g !== void 0 ? _g : s) !== null && _h !== void 0 ? _h : true, - strictTypes: (_k = (_j = o.strictTypes) !== null && _j !== void 0 ? _j : s) !== null && _k !== void 0 ? _k : "log", - strictTuples: (_m = (_l = o.strictTuples) !== null && _l !== void 0 ? _l : s) !== null && _m !== void 0 ? _m : "log", - strictRequired: (_p = (_o = o.strictRequired) !== null && _o !== void 0 ? _o : s) !== null && _p !== void 0 ? _p : false, - code: o.code ? { - ...o.code, - optimize, - regExp - } : { - optimize, - regExp - }, - loopRequired: (_q = o.loopRequired) !== null && _q !== void 0 ? _q : MAX_EXPRESSION, - loopEnum: (_r = o.loopEnum) !== null && _r !== void 0 ? _r : MAX_EXPRESSION, - meta: (_s = o.meta) !== null && _s !== void 0 ? _s : true, - messages: (_t = o.messages) !== null && _t !== void 0 ? _t : true, - inlineRefs: (_u = o.inlineRefs) !== null && _u !== void 0 ? _u : true, - schemaId: (_v = o.schemaId) !== null && _v !== void 0 ? _v : "$id", - addUsedSchema: (_w = o.addUsedSchema) !== null && _w !== void 0 ? _w : true, - validateSchema: (_x = o.validateSchema) !== null && _x !== void 0 ? _x : true, - validateFormats: (_y = o.validateFormats) !== null && _y !== void 0 ? _y : true, - unicodeRegExp: (_z = o.unicodeRegExp) !== null && _z !== void 0 ? _z : true, - int32range: (_0 = o.int32range) !== null && _0 !== void 0 ? _0 : true, - uriResolver - }; - } - var Ajv = class { - constructor(opts = {}) { - this.schemas = {}; - this.refs = {}; - this.formats = {}; - this._compilations = /* @__PURE__ */ new Set(); - this._loading = {}; - this._cache = /* @__PURE__ */ new Map(); - opts = this.opts = { - ...opts, - ...requiredOptions(opts) - }; - const { es5, lines } = this.opts.code; - this.scope = new codegen_2.ValueScope({ - scope: {}, - prefixes: EXT_SCOPE_NAMES, - es5, - lines - }); - this.logger = getLogger(opts.logger); - const formatOpt = opts.validateFormats; - opts.validateFormats = false; - this.RULES = (0, rules_1.getRules)(); - checkOptions.call(this, removedOptions, opts, "NOT SUPPORTED"); - checkOptions.call(this, deprecatedOptions, opts, "DEPRECATED", "warn"); - this._metaOpts = getMetaSchemaOptions.call(this); - if (opts.formats) addInitialFormats.call(this); - this._addVocabularies(); - this._addDefaultMetaSchema(); - if (opts.keywords) addInitialKeywords.call(this, opts.keywords); - if (typeof opts.meta == "object") this.addMetaSchema(opts.meta); - addInitialSchemas.call(this); - opts.validateFormats = formatOpt; - } - _addVocabularies() { - this.addKeyword("$async"); - } - _addDefaultMetaSchema() { - const { $data, meta, schemaId } = this.opts; - let _dataRefSchema = $dataRefSchema; - if (schemaId === "id") { - _dataRefSchema = { ...$dataRefSchema }; - _dataRefSchema.id = _dataRefSchema.$id; - delete _dataRefSchema.$id; - } - if (meta && $data) this.addMetaSchema(_dataRefSchema, _dataRefSchema[schemaId], false); - } - defaultMeta() { - const { meta, schemaId } = this.opts; - return this.opts.defaultMeta = typeof meta == "object" ? meta[schemaId] || meta : void 0; - } - validate(schemaKeyRef, data) { - let v; - if (typeof schemaKeyRef == "string") { - v = this.getSchema(schemaKeyRef); - if (!v) throw new Error(`no schema with key or ref "${schemaKeyRef}"`); - } else v = this.compile(schemaKeyRef); - const valid = v(data); - if (!("$async" in v)) this.errors = v.errors; - return valid; - } - compile(schema, _meta) { - const sch = this._addSchema(schema, _meta); - return sch.validate || this._compileSchemaEnv(sch); - } - compileAsync(schema, meta) { - if (typeof this.opts.loadSchema != "function") throw new Error("options.loadSchema should be a function"); - const { loadSchema } = this.opts; - return runCompileAsync.call(this, schema, meta); - async function runCompileAsync(_schema, _meta) { - await loadMetaSchema.call(this, _schema.$schema); - const sch = this._addSchema(_schema, _meta); - return sch.validate || _compileAsync.call(this, sch); - } - async function loadMetaSchema($ref) { - if ($ref && !this.getSchema($ref)) await runCompileAsync.call(this, { $ref }, true); - } - async function _compileAsync(sch) { - try { - return this._compileSchemaEnv(sch); - } catch (e) { - if (!(e instanceof ref_error_1.default)) throw e; - checkLoaded.call(this, e); - await loadMissingSchema.call(this, e.missingSchema); - return _compileAsync.call(this, sch); - } - } - function checkLoaded({ missingSchema: ref, missingRef }) { - if (this.refs[ref]) throw new Error(`AnySchema ${ref} is loaded but ${missingRef} cannot be resolved`); - } - async function loadMissingSchema(ref) { - const _schema = await _loadSchema.call(this, ref); - if (!this.refs[ref]) await loadMetaSchema.call(this, _schema.$schema); - if (!this.refs[ref]) this.addSchema(_schema, ref, meta); - } - async function _loadSchema(ref) { - const p = this._loading[ref]; - if (p) return p; - try { - return await (this._loading[ref] = loadSchema(ref)); - } finally { - delete this._loading[ref]; - } - } - } - addSchema(schema, key, _meta, _validateSchema = this.opts.validateSchema) { - if (Array.isArray(schema)) { - for (const sch of schema) this.addSchema(sch, void 0, _meta, _validateSchema); - return this; - } - let id; - if (typeof schema === "object") { - const { schemaId } = this.opts; - id = schema[schemaId]; - if (id !== void 0 && typeof id != "string") throw new Error(`schema ${schemaId} must be string`); - } - key = (0, resolve_1.normalizeId)(key || id); - this._checkUnique(key); - this.schemas[key] = this._addSchema(schema, _meta, key, _validateSchema, true); - return this; - } - addMetaSchema(schema, key, _validateSchema = this.opts.validateSchema) { - this.addSchema(schema, key, true, _validateSchema); - return this; - } - validateSchema(schema, throwOrLogError) { - if (typeof schema == "boolean") return true; - let $schema; - $schema = schema.$schema; - if ($schema !== void 0 && typeof $schema != "string") throw new Error("$schema must be a string"); - $schema = $schema || this.opts.defaultMeta || this.defaultMeta(); - if (!$schema) { - this.logger.warn("meta-schema not available"); - this.errors = null; - return true; - } - const valid = this.validate($schema, schema); - if (!valid && throwOrLogError) { - const message = "schema is invalid: " + this.errorsText(); - if (this.opts.validateSchema === "log") this.logger.error(message); - else throw new Error(message); - } - return valid; - } - getSchema(keyRef) { - let sch; - while (typeof (sch = getSchEnv.call(this, keyRef)) == "string") keyRef = sch; - if (sch === void 0) { - const { schemaId } = this.opts; - const root = new compile_1.SchemaEnv({ - schema: {}, - schemaId - }); - sch = compile_1.resolveSchema.call(this, root, keyRef); - if (!sch) return; - this.refs[keyRef] = sch; - } - return sch.validate || this._compileSchemaEnv(sch); - } - removeSchema(schemaKeyRef) { - if (schemaKeyRef instanceof RegExp) { - this._removeAllSchemas(this.schemas, schemaKeyRef); - this._removeAllSchemas(this.refs, schemaKeyRef); - return this; - } - switch (typeof schemaKeyRef) { - case "undefined": - this._removeAllSchemas(this.schemas); - this._removeAllSchemas(this.refs); - this._cache.clear(); - return this; - case "string": { - const sch = getSchEnv.call(this, schemaKeyRef); - if (typeof sch == "object") this._cache.delete(sch.schema); - delete this.schemas[schemaKeyRef]; - delete this.refs[schemaKeyRef]; - return this; - } - case "object": { - const cacheKey = schemaKeyRef; - this._cache.delete(cacheKey); - let id = schemaKeyRef[this.opts.schemaId]; - if (id) { - id = (0, resolve_1.normalizeId)(id); - delete this.schemas[id]; - delete this.refs[id]; - } - return this; - } - default: throw new Error("ajv.removeSchema: invalid parameter"); - } - } - addVocabulary(definitions) { - for (const def of definitions) this.addKeyword(def); - return this; - } - addKeyword(kwdOrDef, def) { - let keyword; - if (typeof kwdOrDef == "string") { - keyword = kwdOrDef; - if (typeof def == "object") { - this.logger.warn("these parameters are deprecated, see docs for addKeyword"); - def.keyword = keyword; - } - } else if (typeof kwdOrDef == "object" && def === void 0) { - def = kwdOrDef; - keyword = def.keyword; - if (Array.isArray(keyword) && !keyword.length) throw new Error("addKeywords: keyword must be string or non-empty array"); - } else throw new Error("invalid addKeywords parameters"); - checkKeyword.call(this, keyword, def); - if (!def) { - (0, util_1.eachItem)(keyword, (kwd) => addRule.call(this, kwd)); - return this; - } - keywordMetaschema.call(this, def); - const definition = { - ...def, - type: (0, dataType_1.getJSONTypes)(def.type), - schemaType: (0, dataType_1.getJSONTypes)(def.schemaType) - }; - (0, util_1.eachItem)(keyword, definition.type.length === 0 ? (k) => addRule.call(this, k, definition) : (k) => definition.type.forEach((t) => addRule.call(this, k, definition, t))); - return this; - } - getKeyword(keyword) { - const rule = this.RULES.all[keyword]; - return typeof rule == "object" ? rule.definition : !!rule; - } - removeKeyword(keyword) { - const { RULES } = this; - delete RULES.keywords[keyword]; - delete RULES.all[keyword]; - for (const group of RULES.rules) { - const i = group.rules.findIndex((rule) => rule.keyword === keyword); - if (i >= 0) group.rules.splice(i, 1); - } - return this; - } - addFormat(name, format) { - if (typeof format == "string") format = new RegExp(format); - this.formats[name] = format; - return this; - } - errorsText(errors = this.errors, { separator = ", ", dataVar = "data" } = {}) { - if (!errors || errors.length === 0) return "No errors"; - return errors.map((e) => `${dataVar}${e.instancePath} ${e.message}`).reduce((text, msg) => text + separator + msg); - } - $dataMetaSchema(metaSchema, keywordsJsonPointers) { - const rules = this.RULES.all; - metaSchema = JSON.parse(JSON.stringify(metaSchema)); - for (const jsonPointer of keywordsJsonPointers) { - const segments = jsonPointer.split("/").slice(1); - let keywords = metaSchema; - for (const seg of segments) keywords = keywords[seg]; - for (const key in rules) { - const rule = rules[key]; - if (typeof rule != "object") continue; - const { $data } = rule.definition; - const schema = keywords[key]; - if ($data && schema) keywords[key] = schemaOrData(schema); - } - } - return metaSchema; - } - _removeAllSchemas(schemas, regex) { - for (const keyRef in schemas) { - const sch = schemas[keyRef]; - if (!regex || regex.test(keyRef)) { - if (typeof sch == "string") delete schemas[keyRef]; - else if (sch && !sch.meta) { - this._cache.delete(sch.schema); - delete schemas[keyRef]; - } - } - } - } - _addSchema(schema, meta, baseId, validateSchema = this.opts.validateSchema, addSchema = this.opts.addUsedSchema) { - let id; - const { schemaId } = this.opts; - if (typeof schema == "object") id = schema[schemaId]; - else if (this.opts.jtd) throw new Error("schema must be object"); - else if (typeof schema != "boolean") throw new Error("schema must be object or boolean"); - let sch = this._cache.get(schema); - if (sch !== void 0) return sch; - baseId = (0, resolve_1.normalizeId)(id || baseId); - const localRefs = resolve_1.getSchemaRefs.call(this, schema, baseId); - sch = new compile_1.SchemaEnv({ - schema, - schemaId, - meta, - baseId, - localRefs - }); - this._cache.set(sch.schema, sch); - if (addSchema && !baseId.startsWith("#")) { - if (baseId) this._checkUnique(baseId); - this.refs[baseId] = sch; - } - if (validateSchema) this.validateSchema(schema, true); - return sch; - } - _checkUnique(id) { - if (this.schemas[id] || this.refs[id]) throw new Error(`schema with key or id "${id}" already exists`); - } - _compileSchemaEnv(sch) { - if (sch.meta) this._compileMetaSchema(sch); - else compile_1.compileSchema.call(this, sch); - /* istanbul ignore if */ - if (!sch.validate) throw new Error("ajv implementation error"); - return sch.validate; - } - _compileMetaSchema(sch) { - const currentOpts = this.opts; - this.opts = this._metaOpts; - try { - compile_1.compileSchema.call(this, sch); - } finally { - this.opts = currentOpts; - } - } - }; - Ajv.ValidationError = validation_error_1.default; - Ajv.MissingRefError = ref_error_1.default; - exports.default = Ajv; - function checkOptions(checkOpts, options, msg, log = "error") { - for (const key in checkOpts) { - const opt = key; - if (opt in options) this.logger[log](`${msg}: option ${key}. ${checkOpts[opt]}`); - } - } - function getSchEnv(keyRef) { - keyRef = (0, resolve_1.normalizeId)(keyRef); - return this.schemas[keyRef] || this.refs[keyRef]; - } - function addInitialSchemas() { - const optsSchemas = this.opts.schemas; - if (!optsSchemas) return; - if (Array.isArray(optsSchemas)) this.addSchema(optsSchemas); - else for (const key in optsSchemas) this.addSchema(optsSchemas[key], key); - } - function addInitialFormats() { - for (const name in this.opts.formats) { - const format = this.opts.formats[name]; - if (format) this.addFormat(name, format); - } - } - function addInitialKeywords(defs) { - if (Array.isArray(defs)) { - this.addVocabulary(defs); - return; - } - this.logger.warn("keywords option as map is deprecated, pass array"); - for (const keyword in defs) { - const def = defs[keyword]; - if (!def.keyword) def.keyword = keyword; - this.addKeyword(def); - } - } - function getMetaSchemaOptions() { - const metaOpts = { ...this.opts }; - for (const opt of META_IGNORE_OPTIONS) delete metaOpts[opt]; - return metaOpts; - } - const noLogs = { - log() {}, - warn() {}, - error() {} - }; - function getLogger(logger) { - if (logger === false) return noLogs; - if (logger === void 0) return console; - if (logger.log && logger.warn && logger.error) return logger; - throw new Error("logger must implement log, warn and error methods"); - } - const KEYWORD_NAME = /^[a-z_$][a-z0-9_$:-]*$/i; - function checkKeyword(keyword, def) { - const { RULES } = this; - (0, util_1.eachItem)(keyword, (kwd) => { - if (RULES.keywords[kwd]) throw new Error(`Keyword ${kwd} is already defined`); - if (!KEYWORD_NAME.test(kwd)) throw new Error(`Keyword ${kwd} has invalid name`); - }); - if (!def) return; - if (def.$data && !("code" in def || "validate" in def)) throw new Error("$data keyword must have \"code\" or \"validate\" function"); - } - function addRule(keyword, definition, dataType) { - var _a; - const post = definition === null || definition === void 0 ? void 0 : definition.post; - if (dataType && post) throw new Error("keyword with \"post\" flag cannot have \"type\""); - const { RULES } = this; - let ruleGroup = post ? RULES.post : RULES.rules.find(({ type: t }) => t === dataType); - if (!ruleGroup) { - ruleGroup = { - type: dataType, - rules: [] - }; - RULES.rules.push(ruleGroup); - } - RULES.keywords[keyword] = true; - if (!definition) return; - const rule = { - keyword, - definition: { - ...definition, - type: (0, dataType_1.getJSONTypes)(definition.type), - schemaType: (0, dataType_1.getJSONTypes)(definition.schemaType) - } - }; - if (definition.before) addBeforeRule.call(this, ruleGroup, rule, definition.before); - else ruleGroup.rules.push(rule); - RULES.all[keyword] = rule; - (_a = definition.implements) === null || _a === void 0 || _a.forEach((kwd) => this.addKeyword(kwd)); - } - function addBeforeRule(ruleGroup, rule, before) { - const i = ruleGroup.rules.findIndex((_rule) => _rule.keyword === before); - if (i >= 0) ruleGroup.rules.splice(i, 0, rule); - else { - ruleGroup.rules.push(rule); - this.logger.warn(`rule ${before} is not defined`); - } - } - function keywordMetaschema(def) { - let { metaSchema } = def; - if (metaSchema === void 0) return; - if (def.$data && this.opts.$data) metaSchema = schemaOrData(metaSchema); - def.validateSchema = this.compile(metaSchema, true); - } - const $dataRef = { $ref: "https://raw.githubusercontent.com/ajv-validator/ajv/master/lib/refs/data.json#" }; - function schemaOrData(schema) { - return { anyOf: [schema, $dataRef] }; - } -})); - -//#endregion -//#region ../../node_modules/.pnpm/ajv@8.18.0/node_modules/ajv/dist/vocabularies/core/id.js -var require_id = /* @__PURE__ */ __commonJSMin(((exports) => { - Object.defineProperty(exports, "__esModule", { value: true }); - const def = { - keyword: "id", - code() { - throw new Error("NOT SUPPORTED: keyword \"id\", use \"$id\" for schema ID"); - } - }; - exports.default = def; -})); - -//#endregion -//#region ../../node_modules/.pnpm/ajv@8.18.0/node_modules/ajv/dist/vocabularies/core/ref.js -var require_ref = /* @__PURE__ */ __commonJSMin(((exports) => { - Object.defineProperty(exports, "__esModule", { value: true }); - exports.callRef = exports.getValidate = void 0; - const ref_error_1 = require_ref_error(); - const code_1 = require_code(); - const codegen_1 = require_codegen(); - const names_1 = require_names(); - const compile_1 = require_compile(); - const util_1 = require_util(); - const def = { - keyword: "$ref", - schemaType: "string", - code(cxt) { - const { gen, schema: $ref, it } = cxt; - const { baseId, schemaEnv: env, validateName, opts, self } = it; - const { root } = env; - if (($ref === "#" || $ref === "#/") && baseId === root.baseId) return callRootRef(); - const schOrEnv = compile_1.resolveRef.call(self, root, baseId, $ref); - if (schOrEnv === void 0) throw new ref_error_1.default(it.opts.uriResolver, baseId, $ref); - if (schOrEnv instanceof compile_1.SchemaEnv) return callValidate(schOrEnv); - return inlineRefSchema(schOrEnv); - function callRootRef() { - if (env === root) return callRef(cxt, validateName, env, env.$async); - const rootName = gen.scopeValue("root", { ref: root }); - return callRef(cxt, (0, codegen_1._)`${rootName}.validate`, root, root.$async); - } - function callValidate(sch) { - callRef(cxt, getValidate(cxt, sch), sch, sch.$async); - } - function inlineRefSchema(sch) { - const schName = gen.scopeValue("schema", opts.code.source === true ? { - ref: sch, - code: (0, codegen_1.stringify)(sch) - } : { ref: sch }); - const valid = gen.name("valid"); - const schCxt = cxt.subschema({ - schema: sch, - dataTypes: [], - schemaPath: codegen_1.nil, - topSchemaRef: schName, - errSchemaPath: $ref - }, valid); - cxt.mergeEvaluated(schCxt); - cxt.ok(valid); - } - } - }; - function getValidate(cxt, sch) { - const { gen } = cxt; - return sch.validate ? gen.scopeValue("validate", { ref: sch.validate }) : (0, codegen_1._)`${gen.scopeValue("wrapper", { ref: sch })}.validate`; - } - exports.getValidate = getValidate; - function callRef(cxt, v, sch, $async) { - const { gen, it } = cxt; - const { allErrors, schemaEnv: env, opts } = it; - const passCxt = opts.passContext ? names_1.default.this : codegen_1.nil; - if ($async) callAsyncRef(); - else callSyncRef(); - function callAsyncRef() { - if (!env.$async) throw new Error("async schema referenced by sync schema"); - const valid = gen.let("valid"); - gen.try(() => { - gen.code((0, codegen_1._)`await ${(0, code_1.callValidateCode)(cxt, v, passCxt)}`); - addEvaluatedFrom(v); - if (!allErrors) gen.assign(valid, true); - }, (e) => { - gen.if((0, codegen_1._)`!(${e} instanceof ${it.ValidationError})`, () => gen.throw(e)); - addErrorsFrom(e); - if (!allErrors) gen.assign(valid, false); - }); - cxt.ok(valid); - } - function callSyncRef() { - cxt.result((0, code_1.callValidateCode)(cxt, v, passCxt), () => addEvaluatedFrom(v), () => addErrorsFrom(v)); - } - function addErrorsFrom(source) { - const errs = (0, codegen_1._)`${source}.errors`; - gen.assign(names_1.default.vErrors, (0, codegen_1._)`${names_1.default.vErrors} === null ? ${errs} : ${names_1.default.vErrors}.concat(${errs})`); - gen.assign(names_1.default.errors, (0, codegen_1._)`${names_1.default.vErrors}.length`); - } - function addEvaluatedFrom(source) { - var _a; - if (!it.opts.unevaluated) return; - const schEvaluated = (_a = sch === null || sch === void 0 ? void 0 : sch.validate) === null || _a === void 0 ? void 0 : _a.evaluated; - if (it.props !== true) if (schEvaluated && !schEvaluated.dynamicProps) { - if (schEvaluated.props !== void 0) it.props = util_1.mergeEvaluated.props(gen, schEvaluated.props, it.props); - } else { - const props = gen.var("props", (0, codegen_1._)`${source}.evaluated.props`); - it.props = util_1.mergeEvaluated.props(gen, props, it.props, codegen_1.Name); - } - if (it.items !== true) if (schEvaluated && !schEvaluated.dynamicItems) { - if (schEvaluated.items !== void 0) it.items = util_1.mergeEvaluated.items(gen, schEvaluated.items, it.items); - } else { - const items = gen.var("items", (0, codegen_1._)`${source}.evaluated.items`); - it.items = util_1.mergeEvaluated.items(gen, items, it.items, codegen_1.Name); - } - } - } - exports.callRef = callRef; - exports.default = def; -})); - -//#endregion -//#region ../../node_modules/.pnpm/ajv@8.18.0/node_modules/ajv/dist/vocabularies/core/index.js -var require_core$2 = /* @__PURE__ */ __commonJSMin(((exports) => { - Object.defineProperty(exports, "__esModule", { value: true }); - const id_1 = require_id(); - const ref_1 = require_ref(); - const core = [ - "$schema", - "$id", - "$defs", - "$vocabulary", - { keyword: "$comment" }, - "definitions", - id_1.default, - ref_1.default - ]; - exports.default = core; -})); - -//#endregion -//#region ../../node_modules/.pnpm/ajv@8.18.0/node_modules/ajv/dist/vocabularies/validation/limitNumber.js -var require_limitNumber = /* @__PURE__ */ __commonJSMin(((exports) => { - Object.defineProperty(exports, "__esModule", { value: true }); - const codegen_1 = require_codegen(); - const ops = codegen_1.operators; - const KWDs = { - maximum: { - okStr: "<=", - ok: ops.LTE, - fail: ops.GT - }, - minimum: { - okStr: ">=", - ok: ops.GTE, - fail: ops.LT - }, - exclusiveMaximum: { - okStr: "<", - ok: ops.LT, - fail: ops.GTE - }, - exclusiveMinimum: { - okStr: ">", - ok: ops.GT, - fail: ops.LTE - } - }; - const def = { - keyword: Object.keys(KWDs), - type: "number", - schemaType: "number", - $data: true, - error: { - message: ({ keyword, schemaCode }) => (0, codegen_1.str)`must be ${KWDs[keyword].okStr} ${schemaCode}`, - params: ({ keyword, schemaCode }) => (0, codegen_1._)`{comparison: ${KWDs[keyword].okStr}, limit: ${schemaCode}}` - }, - code(cxt) { - const { keyword, data, schemaCode } = cxt; - cxt.fail$data((0, codegen_1._)`${data} ${KWDs[keyword].fail} ${schemaCode} || isNaN(${data})`); - } - }; - exports.default = def; -})); - -//#endregion -//#region ../../node_modules/.pnpm/ajv@8.18.0/node_modules/ajv/dist/vocabularies/validation/multipleOf.js -var require_multipleOf = /* @__PURE__ */ __commonJSMin(((exports) => { - Object.defineProperty(exports, "__esModule", { value: true }); - const codegen_1 = require_codegen(); - const def = { - keyword: "multipleOf", - type: "number", - schemaType: "number", - $data: true, - error: { - message: ({ schemaCode }) => (0, codegen_1.str)`must be multiple of ${schemaCode}`, - params: ({ schemaCode }) => (0, codegen_1._)`{multipleOf: ${schemaCode}}` - }, - code(cxt) { - const { gen, data, schemaCode, it } = cxt; - const prec = it.opts.multipleOfPrecision; - const res = gen.let("res"); - const invalid = prec ? (0, codegen_1._)`Math.abs(Math.round(${res}) - ${res}) > 1e-${prec}` : (0, codegen_1._)`${res} !== parseInt(${res})`; - cxt.fail$data((0, codegen_1._)`(${schemaCode} === 0 || (${res} = ${data}/${schemaCode}, ${invalid}))`); - } - }; - exports.default = def; -})); - -//#endregion -//#region ../../node_modules/.pnpm/ajv@8.18.0/node_modules/ajv/dist/runtime/ucs2length.js -var require_ucs2length = /* @__PURE__ */ __commonJSMin(((exports) => { - Object.defineProperty(exports, "__esModule", { value: true }); - function ucs2length(str) { - const len = str.length; - let length = 0; - let pos = 0; - let value; - while (pos < len) { - length++; - value = str.charCodeAt(pos++); - if (value >= 55296 && value <= 56319 && pos < len) { - value = str.charCodeAt(pos); - if ((value & 64512) === 56320) pos++; - } - } - return length; - } - exports.default = ucs2length; - ucs2length.code = "require(\"ajv/dist/runtime/ucs2length\").default"; -})); - -//#endregion -//#region ../../node_modules/.pnpm/ajv@8.18.0/node_modules/ajv/dist/vocabularies/validation/limitLength.js -var require_limitLength = /* @__PURE__ */ __commonJSMin(((exports) => { - Object.defineProperty(exports, "__esModule", { value: true }); - const codegen_1 = require_codegen(); - const util_1 = require_util(); - const ucs2length_1 = require_ucs2length(); - const def = { - keyword: ["maxLength", "minLength"], - type: "string", - schemaType: "number", - $data: true, - error: { - message({ keyword, schemaCode }) { - const comp = keyword === "maxLength" ? "more" : "fewer"; - return (0, codegen_1.str)`must NOT have ${comp} than ${schemaCode} characters`; - }, - params: ({ schemaCode }) => (0, codegen_1._)`{limit: ${schemaCode}}` - }, - code(cxt) { - const { keyword, data, schemaCode, it } = cxt; - const op = keyword === "maxLength" ? codegen_1.operators.GT : codegen_1.operators.LT; - const len = it.opts.unicode === false ? (0, codegen_1._)`${data}.length` : (0, codegen_1._)`${(0, util_1.useFunc)(cxt.gen, ucs2length_1.default)}(${data})`; - cxt.fail$data((0, codegen_1._)`${len} ${op} ${schemaCode}`); - } - }; - exports.default = def; -})); - -//#endregion -//#region ../../node_modules/.pnpm/ajv@8.18.0/node_modules/ajv/dist/vocabularies/validation/pattern.js -var require_pattern = /* @__PURE__ */ __commonJSMin(((exports) => { - Object.defineProperty(exports, "__esModule", { value: true }); - const code_1 = require_code(); - const util_1 = require_util(); - const codegen_1 = require_codegen(); - const def = { - keyword: "pattern", - type: "string", - schemaType: "string", - $data: true, - error: { - message: ({ schemaCode }) => (0, codegen_1.str)`must match pattern "${schemaCode}"`, - params: ({ schemaCode }) => (0, codegen_1._)`{pattern: ${schemaCode}}` - }, - code(cxt) { - const { gen, data, $data, schema, schemaCode, it } = cxt; - const u = it.opts.unicodeRegExp ? "u" : ""; - if ($data) { - const { regExp } = it.opts.code; - const regExpCode = regExp.code === "new RegExp" ? (0, codegen_1._)`new RegExp` : (0, util_1.useFunc)(gen, regExp); - const valid = gen.let("valid"); - gen.try(() => gen.assign(valid, (0, codegen_1._)`${regExpCode}(${schemaCode}, ${u}).test(${data})`), () => gen.assign(valid, false)); - cxt.fail$data((0, codegen_1._)`!${valid}`); - } else { - const regExp = (0, code_1.usePattern)(cxt, schema); - cxt.fail$data((0, codegen_1._)`!${regExp}.test(${data})`); - } - } - }; - exports.default = def; -})); - -//#endregion -//#region ../../node_modules/.pnpm/ajv@8.18.0/node_modules/ajv/dist/vocabularies/validation/limitProperties.js -var require_limitProperties = /* @__PURE__ */ __commonJSMin(((exports) => { - Object.defineProperty(exports, "__esModule", { value: true }); - const codegen_1 = require_codegen(); - const def = { - keyword: ["maxProperties", "minProperties"], - type: "object", - schemaType: "number", - $data: true, - error: { - message({ keyword, schemaCode }) { - const comp = keyword === "maxProperties" ? "more" : "fewer"; - return (0, codegen_1.str)`must NOT have ${comp} than ${schemaCode} properties`; - }, - params: ({ schemaCode }) => (0, codegen_1._)`{limit: ${schemaCode}}` - }, - code(cxt) { - const { keyword, data, schemaCode } = cxt; - const op = keyword === "maxProperties" ? codegen_1.operators.GT : codegen_1.operators.LT; - cxt.fail$data((0, codegen_1._)`Object.keys(${data}).length ${op} ${schemaCode}`); - } - }; - exports.default = def; -})); - -//#endregion -//#region ../../node_modules/.pnpm/ajv@8.18.0/node_modules/ajv/dist/vocabularies/validation/required.js -var require_required = /* @__PURE__ */ __commonJSMin(((exports) => { - Object.defineProperty(exports, "__esModule", { value: true }); - const code_1 = require_code(); - const codegen_1 = require_codegen(); - const util_1 = require_util(); - const def = { - keyword: "required", - type: "object", - schemaType: "array", - $data: true, - error: { - message: ({ params: { missingProperty } }) => (0, codegen_1.str)`must have required property '${missingProperty}'`, - params: ({ params: { missingProperty } }) => (0, codegen_1._)`{missingProperty: ${missingProperty}}` - }, - code(cxt) { - const { gen, schema, schemaCode, data, $data, it } = cxt; - const { opts } = it; - if (!$data && schema.length === 0) return; - const useLoop = schema.length >= opts.loopRequired; - if (it.allErrors) allErrorsMode(); - else exitOnErrorMode(); - if (opts.strictRequired) { - const props = cxt.parentSchema.properties; - const { definedProperties } = cxt.it; - for (const requiredKey of schema) if ((props === null || props === void 0 ? void 0 : props[requiredKey]) === void 0 && !definedProperties.has(requiredKey)) { - const msg = `required property "${requiredKey}" is not defined at "${it.schemaEnv.baseId + it.errSchemaPath}" (strictRequired)`; - (0, util_1.checkStrictMode)(it, msg, it.opts.strictRequired); - } - } - function allErrorsMode() { - if (useLoop || $data) cxt.block$data(codegen_1.nil, loopAllRequired); - else for (const prop of schema) (0, code_1.checkReportMissingProp)(cxt, prop); - } - function exitOnErrorMode() { - const missing = gen.let("missing"); - if (useLoop || $data) { - const valid = gen.let("valid", true); - cxt.block$data(valid, () => loopUntilMissing(missing, valid)); - cxt.ok(valid); - } else { - gen.if((0, code_1.checkMissingProp)(cxt, schema, missing)); - (0, code_1.reportMissingProp)(cxt, missing); - gen.else(); - } - } - function loopAllRequired() { - gen.forOf("prop", schemaCode, (prop) => { - cxt.setParams({ missingProperty: prop }); - gen.if((0, code_1.noPropertyInData)(gen, data, prop, opts.ownProperties), () => cxt.error()); - }); - } - function loopUntilMissing(missing, valid) { - cxt.setParams({ missingProperty: missing }); - gen.forOf(missing, schemaCode, () => { - gen.assign(valid, (0, code_1.propertyInData)(gen, data, missing, opts.ownProperties)); - gen.if((0, codegen_1.not)(valid), () => { - cxt.error(); - gen.break(); - }); - }, codegen_1.nil); - } - } - }; - exports.default = def; -})); - -//#endregion -//#region ../../node_modules/.pnpm/ajv@8.18.0/node_modules/ajv/dist/vocabularies/validation/limitItems.js -var require_limitItems = /* @__PURE__ */ __commonJSMin(((exports) => { - Object.defineProperty(exports, "__esModule", { value: true }); - const codegen_1 = require_codegen(); - const def = { - keyword: ["maxItems", "minItems"], - type: "array", - schemaType: "number", - $data: true, - error: { - message({ keyword, schemaCode }) { - const comp = keyword === "maxItems" ? "more" : "fewer"; - return (0, codegen_1.str)`must NOT have ${comp} than ${schemaCode} items`; - }, - params: ({ schemaCode }) => (0, codegen_1._)`{limit: ${schemaCode}}` - }, - code(cxt) { - const { keyword, data, schemaCode } = cxt; - const op = keyword === "maxItems" ? codegen_1.operators.GT : codegen_1.operators.LT; - cxt.fail$data((0, codegen_1._)`${data}.length ${op} ${schemaCode}`); - } - }; - exports.default = def; -})); - -//#endregion -//#region ../../node_modules/.pnpm/ajv@8.18.0/node_modules/ajv/dist/runtime/equal.js -var require_equal = /* @__PURE__ */ __commonJSMin(((exports) => { - Object.defineProperty(exports, "__esModule", { value: true }); - const equal = require_fast_deep_equal(); - equal.code = "require(\"ajv/dist/runtime/equal\").default"; - exports.default = equal; -})); - -//#endregion -//#region ../../node_modules/.pnpm/ajv@8.18.0/node_modules/ajv/dist/vocabularies/validation/uniqueItems.js -var require_uniqueItems = /* @__PURE__ */ __commonJSMin(((exports) => { - Object.defineProperty(exports, "__esModule", { value: true }); - const dataType_1 = require_dataType(); - const codegen_1 = require_codegen(); - const util_1 = require_util(); - const equal_1 = require_equal(); - const def = { - keyword: "uniqueItems", - type: "array", - schemaType: "boolean", - $data: true, - error: { - message: ({ params: { i, j } }) => (0, codegen_1.str)`must NOT have duplicate items (items ## ${j} and ${i} are identical)`, - params: ({ params: { i, j } }) => (0, codegen_1._)`{i: ${i}, j: ${j}}` - }, - code(cxt) { - const { gen, data, $data, schema, parentSchema, schemaCode, it } = cxt; - if (!$data && !schema) return; - const valid = gen.let("valid"); - const itemTypes = parentSchema.items ? (0, dataType_1.getSchemaTypes)(parentSchema.items) : []; - cxt.block$data(valid, validateUniqueItems, (0, codegen_1._)`${schemaCode} === false`); - cxt.ok(valid); - function validateUniqueItems() { - const i = gen.let("i", (0, codegen_1._)`${data}.length`); - const j = gen.let("j"); - cxt.setParams({ - i, - j - }); - gen.assign(valid, true); - gen.if((0, codegen_1._)`${i} > 1`, () => (canOptimize() ? loopN : loopN2)(i, j)); - } - function canOptimize() { - return itemTypes.length > 0 && !itemTypes.some((t) => t === "object" || t === "array"); - } - function loopN(i, j) { - const item = gen.name("item"); - const wrongType = (0, dataType_1.checkDataTypes)(itemTypes, item, it.opts.strictNumbers, dataType_1.DataType.Wrong); - const indices = gen.const("indices", (0, codegen_1._)`{}`); - gen.for((0, codegen_1._)`;${i}--;`, () => { - gen.let(item, (0, codegen_1._)`${data}[${i}]`); - gen.if(wrongType, (0, codegen_1._)`continue`); - if (itemTypes.length > 1) gen.if((0, codegen_1._)`typeof ${item} == "string"`, (0, codegen_1._)`${item} += "_"`); - gen.if((0, codegen_1._)`typeof ${indices}[${item}] == "number"`, () => { - gen.assign(j, (0, codegen_1._)`${indices}[${item}]`); - cxt.error(); - gen.assign(valid, false).break(); - }).code((0, codegen_1._)`${indices}[${item}] = ${i}`); - }); - } - function loopN2(i, j) { - const eql = (0, util_1.useFunc)(gen, equal_1.default); - const outer = gen.name("outer"); - gen.label(outer).for((0, codegen_1._)`;${i}--;`, () => gen.for((0, codegen_1._)`${j} = ${i}; ${j}--;`, () => gen.if((0, codegen_1._)`${eql}(${data}[${i}], ${data}[${j}])`, () => { - cxt.error(); - gen.assign(valid, false).break(outer); - }))); - } - } - }; - exports.default = def; -})); - -//#endregion -//#region ../../node_modules/.pnpm/ajv@8.18.0/node_modules/ajv/dist/vocabularies/validation/const.js -var require_const = /* @__PURE__ */ __commonJSMin(((exports) => { - Object.defineProperty(exports, "__esModule", { value: true }); - const codegen_1 = require_codegen(); - const util_1 = require_util(); - const equal_1 = require_equal(); - const def = { - keyword: "const", - $data: true, - error: { - message: "must be equal to constant", - params: ({ schemaCode }) => (0, codegen_1._)`{allowedValue: ${schemaCode}}` - }, - code(cxt) { - const { gen, data, $data, schemaCode, schema } = cxt; - if ($data || schema && typeof schema == "object") cxt.fail$data((0, codegen_1._)`!${(0, util_1.useFunc)(gen, equal_1.default)}(${data}, ${schemaCode})`); - else cxt.fail((0, codegen_1._)`${schema} !== ${data}`); - } - }; - exports.default = def; -})); - -//#endregion -//#region ../../node_modules/.pnpm/ajv@8.18.0/node_modules/ajv/dist/vocabularies/validation/enum.js -var require_enum = /* @__PURE__ */ __commonJSMin(((exports) => { - Object.defineProperty(exports, "__esModule", { value: true }); - const codegen_1 = require_codegen(); - const util_1 = require_util(); - const equal_1 = require_equal(); - const def = { - keyword: "enum", - schemaType: "array", - $data: true, - error: { - message: "must be equal to one of the allowed values", - params: ({ schemaCode }) => (0, codegen_1._)`{allowedValues: ${schemaCode}}` - }, - code(cxt) { - const { gen, data, $data, schema, schemaCode, it } = cxt; - if (!$data && schema.length === 0) throw new Error("enum must have non-empty array"); - const useLoop = schema.length >= it.opts.loopEnum; - let eql; - const getEql = () => eql !== null && eql !== void 0 ? eql : eql = (0, util_1.useFunc)(gen, equal_1.default); - let valid; - if (useLoop || $data) { - valid = gen.let("valid"); - cxt.block$data(valid, loopEnum); - } else { - /* istanbul ignore if */ - if (!Array.isArray(schema)) throw new Error("ajv implementation error"); - const vSchema = gen.const("vSchema", schemaCode); - valid = (0, codegen_1.or)(...schema.map((_x, i) => equalCode(vSchema, i))); - } - cxt.pass(valid); - function loopEnum() { - gen.assign(valid, false); - gen.forOf("v", schemaCode, (v) => gen.if((0, codegen_1._)`${getEql()}(${data}, ${v})`, () => gen.assign(valid, true).break())); - } - function equalCode(vSchema, i) { - const sch = schema[i]; - return typeof sch === "object" && sch !== null ? (0, codegen_1._)`${getEql()}(${data}, ${vSchema}[${i}])` : (0, codegen_1._)`${data} === ${sch}`; - } - } - }; - exports.default = def; -})); - -//#endregion -//#region ../../node_modules/.pnpm/ajv@8.18.0/node_modules/ajv/dist/vocabularies/validation/index.js -var require_validation$2 = /* @__PURE__ */ __commonJSMin(((exports) => { - Object.defineProperty(exports, "__esModule", { value: true }); - const limitNumber_1 = require_limitNumber(); - const multipleOf_1 = require_multipleOf(); - const limitLength_1 = require_limitLength(); - const pattern_1 = require_pattern(); - const limitProperties_1 = require_limitProperties(); - const required_1 = require_required(); - const limitItems_1 = require_limitItems(); - const uniqueItems_1 = require_uniqueItems(); - const const_1 = require_const(); - const enum_1 = require_enum(); - const validation = [ - limitNumber_1.default, - multipleOf_1.default, - limitLength_1.default, - pattern_1.default, - limitProperties_1.default, - required_1.default, - limitItems_1.default, - uniqueItems_1.default, - { - keyword: "type", - schemaType: ["string", "array"] - }, - { - keyword: "nullable", - schemaType: "boolean" - }, - const_1.default, - enum_1.default - ]; - exports.default = validation; -})); - -//#endregion -//#region ../../node_modules/.pnpm/ajv@8.18.0/node_modules/ajv/dist/vocabularies/applicator/additionalItems.js -var require_additionalItems = /* @__PURE__ */ __commonJSMin(((exports) => { - Object.defineProperty(exports, "__esModule", { value: true }); - exports.validateAdditionalItems = void 0; - const codegen_1 = require_codegen(); - const util_1 = require_util(); - const def = { - keyword: "additionalItems", - type: "array", - schemaType: ["boolean", "object"], - before: "uniqueItems", - error: { - message: ({ params: { len } }) => (0, codegen_1.str)`must NOT have more than ${len} items`, - params: ({ params: { len } }) => (0, codegen_1._)`{limit: ${len}}` - }, - code(cxt) { - const { parentSchema, it } = cxt; - const { items } = parentSchema; - if (!Array.isArray(items)) { - (0, util_1.checkStrictMode)(it, "\"additionalItems\" is ignored when \"items\" is not an array of schemas"); - return; - } - validateAdditionalItems(cxt, items); - } - }; - function validateAdditionalItems(cxt, items) { - const { gen, schema, data, keyword, it } = cxt; - it.items = true; - const len = gen.const("len", (0, codegen_1._)`${data}.length`); - if (schema === false) { - cxt.setParams({ len: items.length }); - cxt.pass((0, codegen_1._)`${len} <= ${items.length}`); - } else if (typeof schema == "object" && !(0, util_1.alwaysValidSchema)(it, schema)) { - const valid = gen.var("valid", (0, codegen_1._)`${len} <= ${items.length}`); - gen.if((0, codegen_1.not)(valid), () => validateItems(valid)); - cxt.ok(valid); - } - function validateItems(valid) { - gen.forRange("i", items.length, len, (i) => { - cxt.subschema({ - keyword, - dataProp: i, - dataPropType: util_1.Type.Num - }, valid); - if (!it.allErrors) gen.if((0, codegen_1.not)(valid), () => gen.break()); - }); - } - } - exports.validateAdditionalItems = validateAdditionalItems; - exports.default = def; -})); - -//#endregion -//#region ../../node_modules/.pnpm/ajv@8.18.0/node_modules/ajv/dist/vocabularies/applicator/items.js -var require_items = /* @__PURE__ */ __commonJSMin(((exports) => { - Object.defineProperty(exports, "__esModule", { value: true }); - exports.validateTuple = void 0; - const codegen_1 = require_codegen(); - const util_1 = require_util(); - const code_1 = require_code(); - const def = { - keyword: "items", - type: "array", - schemaType: [ - "object", - "array", - "boolean" - ], - before: "uniqueItems", - code(cxt) { - const { schema, it } = cxt; - if (Array.isArray(schema)) return validateTuple(cxt, "additionalItems", schema); - it.items = true; - if ((0, util_1.alwaysValidSchema)(it, schema)) return; - cxt.ok((0, code_1.validateArray)(cxt)); - } - }; - function validateTuple(cxt, extraItems, schArr = cxt.schema) { - const { gen, parentSchema, data, keyword, it } = cxt; - checkStrictTuple(parentSchema); - if (it.opts.unevaluated && schArr.length && it.items !== true) it.items = util_1.mergeEvaluated.items(gen, schArr.length, it.items); - const valid = gen.name("valid"); - const len = gen.const("len", (0, codegen_1._)`${data}.length`); - schArr.forEach((sch, i) => { - if ((0, util_1.alwaysValidSchema)(it, sch)) return; - gen.if((0, codegen_1._)`${len} > ${i}`, () => cxt.subschema({ - keyword, - schemaProp: i, - dataProp: i - }, valid)); - cxt.ok(valid); - }); - function checkStrictTuple(sch) { - const { opts, errSchemaPath } = it; - const l = schArr.length; - const fullTuple = l === sch.minItems && (l === sch.maxItems || sch[extraItems] === false); - if (opts.strictTuples && !fullTuple) { - const msg = `"${keyword}" is ${l}-tuple, but minItems or maxItems/${extraItems} are not specified or different at path "${errSchemaPath}"`; - (0, util_1.checkStrictMode)(it, msg, opts.strictTuples); - } - } - } - exports.validateTuple = validateTuple; - exports.default = def; -})); - -//#endregion -//#region ../../node_modules/.pnpm/ajv@8.18.0/node_modules/ajv/dist/vocabularies/applicator/prefixItems.js -var require_prefixItems = /* @__PURE__ */ __commonJSMin(((exports) => { - Object.defineProperty(exports, "__esModule", { value: true }); - const items_1 = require_items(); - const def = { - keyword: "prefixItems", - type: "array", - schemaType: ["array"], - before: "uniqueItems", - code: (cxt) => (0, items_1.validateTuple)(cxt, "items") - }; - exports.default = def; -})); - -//#endregion -//#region ../../node_modules/.pnpm/ajv@8.18.0/node_modules/ajv/dist/vocabularies/applicator/items2020.js -var require_items2020 = /* @__PURE__ */ __commonJSMin(((exports) => { - Object.defineProperty(exports, "__esModule", { value: true }); - const codegen_1 = require_codegen(); - const util_1 = require_util(); - const code_1 = require_code(); - const additionalItems_1 = require_additionalItems(); - const def = { - keyword: "items", - type: "array", - schemaType: ["object", "boolean"], - before: "uniqueItems", - error: { - message: ({ params: { len } }) => (0, codegen_1.str)`must NOT have more than ${len} items`, - params: ({ params: { len } }) => (0, codegen_1._)`{limit: ${len}}` - }, - code(cxt) { - const { schema, parentSchema, it } = cxt; - const { prefixItems } = parentSchema; - it.items = true; - if ((0, util_1.alwaysValidSchema)(it, schema)) return; - if (prefixItems) (0, additionalItems_1.validateAdditionalItems)(cxt, prefixItems); - else cxt.ok((0, code_1.validateArray)(cxt)); - } - }; - exports.default = def; -})); - -//#endregion -//#region ../../node_modules/.pnpm/ajv@8.18.0/node_modules/ajv/dist/vocabularies/applicator/contains.js -var require_contains = /* @__PURE__ */ __commonJSMin(((exports) => { - Object.defineProperty(exports, "__esModule", { value: true }); - const codegen_1 = require_codegen(); - const util_1 = require_util(); - const def = { - keyword: "contains", - type: "array", - schemaType: ["object", "boolean"], - before: "uniqueItems", - trackErrors: true, - error: { - message: ({ params: { min, max } }) => max === void 0 ? (0, codegen_1.str)`must contain at least ${min} valid item(s)` : (0, codegen_1.str)`must contain at least ${min} and no more than ${max} valid item(s)`, - params: ({ params: { min, max } }) => max === void 0 ? (0, codegen_1._)`{minContains: ${min}}` : (0, codegen_1._)`{minContains: ${min}, maxContains: ${max}}` - }, - code(cxt) { - const { gen, schema, parentSchema, data, it } = cxt; - let min; - let max; - const { minContains, maxContains } = parentSchema; - if (it.opts.next) { - min = minContains === void 0 ? 1 : minContains; - max = maxContains; - } else min = 1; - const len = gen.const("len", (0, codegen_1._)`${data}.length`); - cxt.setParams({ - min, - max - }); - if (max === void 0 && min === 0) { - (0, util_1.checkStrictMode)(it, `"minContains" == 0 without "maxContains": "contains" keyword ignored`); - return; - } - if (max !== void 0 && min > max) { - (0, util_1.checkStrictMode)(it, `"minContains" > "maxContains" is always invalid`); - cxt.fail(); - return; - } - if ((0, util_1.alwaysValidSchema)(it, schema)) { - let cond = (0, codegen_1._)`${len} >= ${min}`; - if (max !== void 0) cond = (0, codegen_1._)`${cond} && ${len} <= ${max}`; - cxt.pass(cond); - return; - } - it.items = true; - const valid = gen.name("valid"); - if (max === void 0 && min === 1) validateItems(valid, () => gen.if(valid, () => gen.break())); - else if (min === 0) { - gen.let(valid, true); - if (max !== void 0) gen.if((0, codegen_1._)`${data}.length > 0`, validateItemsWithCount); - } else { - gen.let(valid, false); - validateItemsWithCount(); - } - cxt.result(valid, () => cxt.reset()); - function validateItemsWithCount() { - const schValid = gen.name("_valid"); - const count = gen.let("count", 0); - validateItems(schValid, () => gen.if(schValid, () => checkLimits(count))); - } - function validateItems(_valid, block) { - gen.forRange("i", 0, len, (i) => { - cxt.subschema({ - keyword: "contains", - dataProp: i, - dataPropType: util_1.Type.Num, - compositeRule: true - }, _valid); - block(); - }); - } - function checkLimits(count) { - gen.code((0, codegen_1._)`${count}++`); - if (max === void 0) gen.if((0, codegen_1._)`${count} >= ${min}`, () => gen.assign(valid, true).break()); - else { - gen.if((0, codegen_1._)`${count} > ${max}`, () => gen.assign(valid, false).break()); - if (min === 1) gen.assign(valid, true); - else gen.if((0, codegen_1._)`${count} >= ${min}`, () => gen.assign(valid, true)); - } - } - } - }; - exports.default = def; -})); - -//#endregion -//#region ../../node_modules/.pnpm/ajv@8.18.0/node_modules/ajv/dist/vocabularies/applicator/dependencies.js -var require_dependencies = /* @__PURE__ */ __commonJSMin(((exports) => { - Object.defineProperty(exports, "__esModule", { value: true }); - exports.validateSchemaDeps = exports.validatePropertyDeps = exports.error = void 0; - const codegen_1 = require_codegen(); - const util_1 = require_util(); - const code_1 = require_code(); - exports.error = { - message: ({ params: { property, depsCount, deps } }) => { - const property_ies = depsCount === 1 ? "property" : "properties"; - return (0, codegen_1.str)`must have ${property_ies} ${deps} when property ${property} is present`; - }, - params: ({ params: { property, depsCount, deps, missingProperty } }) => (0, codegen_1._)`{property: ${property}, - missingProperty: ${missingProperty}, - depsCount: ${depsCount}, - deps: ${deps}}` - }; - const def = { - keyword: "dependencies", - type: "object", - schemaType: "object", - error: exports.error, - code(cxt) { - const [propDeps, schDeps] = splitDependencies(cxt); - validatePropertyDeps(cxt, propDeps); - validateSchemaDeps(cxt, schDeps); - } - }; - function splitDependencies({ schema }) { - const propertyDeps = {}; - const schemaDeps = {}; - for (const key in schema) { - if (key === "__proto__") continue; - const deps = Array.isArray(schema[key]) ? propertyDeps : schemaDeps; - deps[key] = schema[key]; - } - return [propertyDeps, schemaDeps]; - } - function validatePropertyDeps(cxt, propertyDeps = cxt.schema) { - const { gen, data, it } = cxt; - if (Object.keys(propertyDeps).length === 0) return; - const missing = gen.let("missing"); - for (const prop in propertyDeps) { - const deps = propertyDeps[prop]; - if (deps.length === 0) continue; - const hasProperty = (0, code_1.propertyInData)(gen, data, prop, it.opts.ownProperties); - cxt.setParams({ - property: prop, - depsCount: deps.length, - deps: deps.join(", ") - }); - if (it.allErrors) gen.if(hasProperty, () => { - for (const depProp of deps) (0, code_1.checkReportMissingProp)(cxt, depProp); - }); - else { - gen.if((0, codegen_1._)`${hasProperty} && (${(0, code_1.checkMissingProp)(cxt, deps, missing)})`); - (0, code_1.reportMissingProp)(cxt, missing); - gen.else(); - } - } - } - exports.validatePropertyDeps = validatePropertyDeps; - function validateSchemaDeps(cxt, schemaDeps = cxt.schema) { - const { gen, data, keyword, it } = cxt; - const valid = gen.name("valid"); - for (const prop in schemaDeps) { - if ((0, util_1.alwaysValidSchema)(it, schemaDeps[prop])) continue; - gen.if((0, code_1.propertyInData)(gen, data, prop, it.opts.ownProperties), () => { - const schCxt = cxt.subschema({ - keyword, - schemaProp: prop - }, valid); - cxt.mergeValidEvaluated(schCxt, valid); - }, () => gen.var(valid, true)); - cxt.ok(valid); - } - } - exports.validateSchemaDeps = validateSchemaDeps; - exports.default = def; -})); - -//#endregion -//#region ../../node_modules/.pnpm/ajv@8.18.0/node_modules/ajv/dist/vocabularies/applicator/propertyNames.js -var require_propertyNames = /* @__PURE__ */ __commonJSMin(((exports) => { - Object.defineProperty(exports, "__esModule", { value: true }); - const codegen_1 = require_codegen(); - const util_1 = require_util(); - const def = { - keyword: "propertyNames", - type: "object", - schemaType: ["object", "boolean"], - error: { - message: "property name must be valid", - params: ({ params }) => (0, codegen_1._)`{propertyName: ${params.propertyName}}` - }, - code(cxt) { - const { gen, schema, data, it } = cxt; - if ((0, util_1.alwaysValidSchema)(it, schema)) return; - const valid = gen.name("valid"); - gen.forIn("key", data, (key) => { - cxt.setParams({ propertyName: key }); - cxt.subschema({ - keyword: "propertyNames", - data: key, - dataTypes: ["string"], - propertyName: key, - compositeRule: true - }, valid); - gen.if((0, codegen_1.not)(valid), () => { - cxt.error(true); - if (!it.allErrors) gen.break(); - }); - }); - cxt.ok(valid); - } - }; - exports.default = def; -})); - -//#endregion -//#region ../../node_modules/.pnpm/ajv@8.18.0/node_modules/ajv/dist/vocabularies/applicator/additionalProperties.js -var require_additionalProperties = /* @__PURE__ */ __commonJSMin(((exports) => { - Object.defineProperty(exports, "__esModule", { value: true }); - const code_1 = require_code(); - const codegen_1 = require_codegen(); - const names_1 = require_names(); - const util_1 = require_util(); - const def = { - keyword: "additionalProperties", - type: ["object"], - schemaType: ["boolean", "object"], - allowUndefined: true, - trackErrors: true, - error: { - message: "must NOT have additional properties", - params: ({ params }) => (0, codegen_1._)`{additionalProperty: ${params.additionalProperty}}` - }, - code(cxt) { - const { gen, schema, parentSchema, data, errsCount, it } = cxt; - /* istanbul ignore if */ - if (!errsCount) throw new Error("ajv implementation error"); - const { allErrors, opts } = it; - it.props = true; - if (opts.removeAdditional !== "all" && (0, util_1.alwaysValidSchema)(it, schema)) return; - const props = (0, code_1.allSchemaProperties)(parentSchema.properties); - const patProps = (0, code_1.allSchemaProperties)(parentSchema.patternProperties); - checkAdditionalProperties(); - cxt.ok((0, codegen_1._)`${errsCount} === ${names_1.default.errors}`); - function checkAdditionalProperties() { - gen.forIn("key", data, (key) => { - if (!props.length && !patProps.length) additionalPropertyCode(key); - else gen.if(isAdditional(key), () => additionalPropertyCode(key)); - }); - } - function isAdditional(key) { - let definedProp; - if (props.length > 8) { - const propsSchema = (0, util_1.schemaRefOrVal)(it, parentSchema.properties, "properties"); - definedProp = (0, code_1.isOwnProperty)(gen, propsSchema, key); - } else if (props.length) definedProp = (0, codegen_1.or)(...props.map((p) => (0, codegen_1._)`${key} === ${p}`)); - else definedProp = codegen_1.nil; - if (patProps.length) definedProp = (0, codegen_1.or)(definedProp, ...patProps.map((p) => (0, codegen_1._)`${(0, code_1.usePattern)(cxt, p)}.test(${key})`)); - return (0, codegen_1.not)(definedProp); - } - function deleteAdditional(key) { - gen.code((0, codegen_1._)`delete ${data}[${key}]`); - } - function additionalPropertyCode(key) { - if (opts.removeAdditional === "all" || opts.removeAdditional && schema === false) { - deleteAdditional(key); - return; - } - if (schema === false) { - cxt.setParams({ additionalProperty: key }); - cxt.error(); - if (!allErrors) gen.break(); - return; - } - if (typeof schema == "object" && !(0, util_1.alwaysValidSchema)(it, schema)) { - const valid = gen.name("valid"); - if (opts.removeAdditional === "failing") { - applyAdditionalSchema(key, valid, false); - gen.if((0, codegen_1.not)(valid), () => { - cxt.reset(); - deleteAdditional(key); - }); - } else { - applyAdditionalSchema(key, valid); - if (!allErrors) gen.if((0, codegen_1.not)(valid), () => gen.break()); - } - } - } - function applyAdditionalSchema(key, valid, errors) { - const subschema = { - keyword: "additionalProperties", - dataProp: key, - dataPropType: util_1.Type.Str - }; - if (errors === false) Object.assign(subschema, { - compositeRule: true, - createErrors: false, - allErrors: false - }); - cxt.subschema(subschema, valid); - } - } - }; - exports.default = def; -})); - -//#endregion -//#region ../../node_modules/.pnpm/ajv@8.18.0/node_modules/ajv/dist/vocabularies/applicator/properties.js -var require_properties = /* @__PURE__ */ __commonJSMin(((exports) => { - Object.defineProperty(exports, "__esModule", { value: true }); - const validate_1 = require_validate(); - const code_1 = require_code(); - const util_1 = require_util(); - const additionalProperties_1 = require_additionalProperties(); - const def = { - keyword: "properties", - type: "object", - schemaType: "object", - code(cxt) { - const { gen, schema, parentSchema, data, it } = cxt; - if (it.opts.removeAdditional === "all" && parentSchema.additionalProperties === void 0) additionalProperties_1.default.code(new validate_1.KeywordCxt(it, additionalProperties_1.default, "additionalProperties")); - const allProps = (0, code_1.allSchemaProperties)(schema); - for (const prop of allProps) it.definedProperties.add(prop); - if (it.opts.unevaluated && allProps.length && it.props !== true) it.props = util_1.mergeEvaluated.props(gen, (0, util_1.toHash)(allProps), it.props); - const properties = allProps.filter((p) => !(0, util_1.alwaysValidSchema)(it, schema[p])); - if (properties.length === 0) return; - const valid = gen.name("valid"); - for (const prop of properties) { - if (hasDefault(prop)) applyPropertySchema(prop); - else { - gen.if((0, code_1.propertyInData)(gen, data, prop, it.opts.ownProperties)); - applyPropertySchema(prop); - if (!it.allErrors) gen.else().var(valid, true); - gen.endIf(); - } - cxt.it.definedProperties.add(prop); - cxt.ok(valid); - } - function hasDefault(prop) { - return it.opts.useDefaults && !it.compositeRule && schema[prop].default !== void 0; - } - function applyPropertySchema(prop) { - cxt.subschema({ - keyword: "properties", - schemaProp: prop, - dataProp: prop - }, valid); - } - } - }; - exports.default = def; -})); - -//#endregion -//#region ../../node_modules/.pnpm/ajv@8.18.0/node_modules/ajv/dist/vocabularies/applicator/patternProperties.js -var require_patternProperties = /* @__PURE__ */ __commonJSMin(((exports) => { - Object.defineProperty(exports, "__esModule", { value: true }); - const code_1 = require_code(); - const codegen_1 = require_codegen(); - const util_1 = require_util(); - const util_2 = require_util(); - const def = { - keyword: "patternProperties", - type: "object", - schemaType: "object", - code(cxt) { - const { gen, schema, data, parentSchema, it } = cxt; - const { opts } = it; - const patterns = (0, code_1.allSchemaProperties)(schema); - const alwaysValidPatterns = patterns.filter((p) => (0, util_1.alwaysValidSchema)(it, schema[p])); - if (patterns.length === 0 || alwaysValidPatterns.length === patterns.length && (!it.opts.unevaluated || it.props === true)) return; - const checkProperties = opts.strictSchema && !opts.allowMatchingProperties && parentSchema.properties; - const valid = gen.name("valid"); - if (it.props !== true && !(it.props instanceof codegen_1.Name)) it.props = (0, util_2.evaluatedPropsToName)(gen, it.props); - const { props } = it; - validatePatternProperties(); - function validatePatternProperties() { - for (const pat of patterns) { - if (checkProperties) checkMatchingProperties(pat); - if (it.allErrors) validateProperties(pat); - else { - gen.var(valid, true); - validateProperties(pat); - gen.if(valid); - } - } - } - function checkMatchingProperties(pat) { - for (const prop in checkProperties) if (new RegExp(pat).test(prop)) (0, util_1.checkStrictMode)(it, `property ${prop} matches pattern ${pat} (use allowMatchingProperties)`); - } - function validateProperties(pat) { - gen.forIn("key", data, (key) => { - gen.if((0, codegen_1._)`${(0, code_1.usePattern)(cxt, pat)}.test(${key})`, () => { - const alwaysValid = alwaysValidPatterns.includes(pat); - if (!alwaysValid) cxt.subschema({ - keyword: "patternProperties", - schemaProp: pat, - dataProp: key, - dataPropType: util_2.Type.Str - }, valid); - if (it.opts.unevaluated && props !== true) gen.assign((0, codegen_1._)`${props}[${key}]`, true); - else if (!alwaysValid && !it.allErrors) gen.if((0, codegen_1.not)(valid), () => gen.break()); - }); - }); - } - } - }; - exports.default = def; -})); - -//#endregion -//#region ../../node_modules/.pnpm/ajv@8.18.0/node_modules/ajv/dist/vocabularies/applicator/not.js -var require_not = /* @__PURE__ */ __commonJSMin(((exports) => { - Object.defineProperty(exports, "__esModule", { value: true }); - const util_1 = require_util(); - const def = { - keyword: "not", - schemaType: ["object", "boolean"], - trackErrors: true, - code(cxt) { - const { gen, schema, it } = cxt; - if ((0, util_1.alwaysValidSchema)(it, schema)) { - cxt.fail(); - return; - } - const valid = gen.name("valid"); - cxt.subschema({ - keyword: "not", - compositeRule: true, - createErrors: false, - allErrors: false - }, valid); - cxt.failResult(valid, () => cxt.reset(), () => cxt.error()); - }, - error: { message: "must NOT be valid" } - }; - exports.default = def; -})); - -//#endregion -//#region ../../node_modules/.pnpm/ajv@8.18.0/node_modules/ajv/dist/vocabularies/applicator/anyOf.js -var require_anyOf = /* @__PURE__ */ __commonJSMin(((exports) => { - Object.defineProperty(exports, "__esModule", { value: true }); - const def = { - keyword: "anyOf", - schemaType: "array", - trackErrors: true, - code: require_code().validateUnion, - error: { message: "must match a schema in anyOf" } - }; - exports.default = def; -})); - -//#endregion -//#region ../../node_modules/.pnpm/ajv@8.18.0/node_modules/ajv/dist/vocabularies/applicator/oneOf.js -var require_oneOf = /* @__PURE__ */ __commonJSMin(((exports) => { - Object.defineProperty(exports, "__esModule", { value: true }); - const codegen_1 = require_codegen(); - const util_1 = require_util(); - const def = { - keyword: "oneOf", - schemaType: "array", - trackErrors: true, - error: { - message: "must match exactly one schema in oneOf", - params: ({ params }) => (0, codegen_1._)`{passingSchemas: ${params.passing}}` - }, - code(cxt) { - const { gen, schema, parentSchema, it } = cxt; - /* istanbul ignore if */ - if (!Array.isArray(schema)) throw new Error("ajv implementation error"); - if (it.opts.discriminator && parentSchema.discriminator) return; - const schArr = schema; - const valid = gen.let("valid", false); - const passing = gen.let("passing", null); - const schValid = gen.name("_valid"); - cxt.setParams({ passing }); - gen.block(validateOneOf); - cxt.result(valid, () => cxt.reset(), () => cxt.error(true)); - function validateOneOf() { - schArr.forEach((sch, i) => { - let schCxt; - if ((0, util_1.alwaysValidSchema)(it, sch)) gen.var(schValid, true); - else schCxt = cxt.subschema({ - keyword: "oneOf", - schemaProp: i, - compositeRule: true - }, schValid); - if (i > 0) gen.if((0, codegen_1._)`${schValid} && ${valid}`).assign(valid, false).assign(passing, (0, codegen_1._)`[${passing}, ${i}]`).else(); - gen.if(schValid, () => { - gen.assign(valid, true); - gen.assign(passing, i); - if (schCxt) cxt.mergeEvaluated(schCxt, codegen_1.Name); - }); - }); - } - } - }; - exports.default = def; -})); - -//#endregion -//#region ../../node_modules/.pnpm/ajv@8.18.0/node_modules/ajv/dist/vocabularies/applicator/allOf.js -var require_allOf = /* @__PURE__ */ __commonJSMin(((exports) => { - Object.defineProperty(exports, "__esModule", { value: true }); - const util_1 = require_util(); - const def = { - keyword: "allOf", - schemaType: "array", - code(cxt) { - const { gen, schema, it } = cxt; - /* istanbul ignore if */ - if (!Array.isArray(schema)) throw new Error("ajv implementation error"); - const valid = gen.name("valid"); - schema.forEach((sch, i) => { - if ((0, util_1.alwaysValidSchema)(it, sch)) return; - const schCxt = cxt.subschema({ - keyword: "allOf", - schemaProp: i - }, valid); - cxt.ok(valid); - cxt.mergeEvaluated(schCxt); - }); - } - }; - exports.default = def; -})); - -//#endregion -//#region ../../node_modules/.pnpm/ajv@8.18.0/node_modules/ajv/dist/vocabularies/applicator/if.js -var require_if = /* @__PURE__ */ __commonJSMin(((exports) => { - Object.defineProperty(exports, "__esModule", { value: true }); - const codegen_1 = require_codegen(); - const util_1 = require_util(); - const def = { - keyword: "if", - schemaType: ["object", "boolean"], - trackErrors: true, - error: { - message: ({ params }) => (0, codegen_1.str)`must match "${params.ifClause}" schema`, - params: ({ params }) => (0, codegen_1._)`{failingKeyword: ${params.ifClause}}` - }, - code(cxt) { - const { gen, parentSchema, it } = cxt; - if (parentSchema.then === void 0 && parentSchema.else === void 0) (0, util_1.checkStrictMode)(it, "\"if\" without \"then\" and \"else\" is ignored"); - const hasThen = hasSchema(it, "then"); - const hasElse = hasSchema(it, "else"); - if (!hasThen && !hasElse) return; - const valid = gen.let("valid", true); - const schValid = gen.name("_valid"); - validateIf(); - cxt.reset(); - if (hasThen && hasElse) { - const ifClause = gen.let("ifClause"); - cxt.setParams({ ifClause }); - gen.if(schValid, validateClause("then", ifClause), validateClause("else", ifClause)); - } else if (hasThen) gen.if(schValid, validateClause("then")); - else gen.if((0, codegen_1.not)(schValid), validateClause("else")); - cxt.pass(valid, () => cxt.error(true)); - function validateIf() { - const schCxt = cxt.subschema({ - keyword: "if", - compositeRule: true, - createErrors: false, - allErrors: false - }, schValid); - cxt.mergeEvaluated(schCxt); - } - function validateClause(keyword, ifClause) { - return () => { - const schCxt = cxt.subschema({ keyword }, schValid); - gen.assign(valid, schValid); - cxt.mergeValidEvaluated(schCxt, valid); - if (ifClause) gen.assign(ifClause, (0, codegen_1._)`${keyword}`); - else cxt.setParams({ ifClause: keyword }); - }; - } - } - }; - function hasSchema(it, keyword) { - const schema = it.schema[keyword]; - return schema !== void 0 && !(0, util_1.alwaysValidSchema)(it, schema); - } - exports.default = def; -})); - -//#endregion -//#region ../../node_modules/.pnpm/ajv@8.18.0/node_modules/ajv/dist/vocabularies/applicator/thenElse.js -var require_thenElse = /* @__PURE__ */ __commonJSMin(((exports) => { - Object.defineProperty(exports, "__esModule", { value: true }); - const util_1 = require_util(); - const def = { - keyword: ["then", "else"], - schemaType: ["object", "boolean"], - code({ keyword, parentSchema, it }) { - if (parentSchema.if === void 0) (0, util_1.checkStrictMode)(it, `"${keyword}" without "if" is ignored`); - } - }; - exports.default = def; -})); - -//#endregion -//#region ../../node_modules/.pnpm/ajv@8.18.0/node_modules/ajv/dist/vocabularies/applicator/index.js -var require_applicator$2 = /* @__PURE__ */ __commonJSMin(((exports) => { - Object.defineProperty(exports, "__esModule", { value: true }); - const additionalItems_1 = require_additionalItems(); - const prefixItems_1 = require_prefixItems(); - const items_1 = require_items(); - const items2020_1 = require_items2020(); - const contains_1 = require_contains(); - const dependencies_1 = require_dependencies(); - const propertyNames_1 = require_propertyNames(); - const additionalProperties_1 = require_additionalProperties(); - const properties_1 = require_properties(); - const patternProperties_1 = require_patternProperties(); - const not_1 = require_not(); - const anyOf_1 = require_anyOf(); - const oneOf_1 = require_oneOf(); - const allOf_1 = require_allOf(); - const if_1 = require_if(); - const thenElse_1 = require_thenElse(); - function getApplicator(draft2020 = false) { - const applicator = [ - not_1.default, - anyOf_1.default, - oneOf_1.default, - allOf_1.default, - if_1.default, - thenElse_1.default, - propertyNames_1.default, - additionalProperties_1.default, - dependencies_1.default, - properties_1.default, - patternProperties_1.default - ]; - if (draft2020) applicator.push(prefixItems_1.default, items2020_1.default); - else applicator.push(additionalItems_1.default, items_1.default); - applicator.push(contains_1.default); - return applicator; - } - exports.default = getApplicator; -})); - -//#endregion -//#region ../../node_modules/.pnpm/ajv@8.18.0/node_modules/ajv/dist/vocabularies/format/format.js -var require_format$2 = /* @__PURE__ */ __commonJSMin(((exports) => { - Object.defineProperty(exports, "__esModule", { value: true }); - const codegen_1 = require_codegen(); - const def = { - keyword: "format", - type: ["number", "string"], - schemaType: "string", - $data: true, - error: { - message: ({ schemaCode }) => (0, codegen_1.str)`must match format "${schemaCode}"`, - params: ({ schemaCode }) => (0, codegen_1._)`{format: ${schemaCode}}` - }, - code(cxt, ruleType) { - const { gen, data, $data, schema, schemaCode, it } = cxt; - const { opts, errSchemaPath, schemaEnv, self } = it; - if (!opts.validateFormats) return; - if ($data) validate$DataFormat(); - else validateFormat(); - function validate$DataFormat() { - const fmts = gen.scopeValue("formats", { - ref: self.formats, - code: opts.code.formats - }); - const fDef = gen.const("fDef", (0, codegen_1._)`${fmts}[${schemaCode}]`); - const fType = gen.let("fType"); - const format = gen.let("format"); - gen.if((0, codegen_1._)`typeof ${fDef} == "object" && !(${fDef} instanceof RegExp)`, () => gen.assign(fType, (0, codegen_1._)`${fDef}.type || "string"`).assign(format, (0, codegen_1._)`${fDef}.validate`), () => gen.assign(fType, (0, codegen_1._)`"string"`).assign(format, fDef)); - cxt.fail$data((0, codegen_1.or)(unknownFmt(), invalidFmt())); - function unknownFmt() { - if (opts.strictSchema === false) return codegen_1.nil; - return (0, codegen_1._)`${schemaCode} && !${format}`; - } - function invalidFmt() { - const callFormat = schemaEnv.$async ? (0, codegen_1._)`(${fDef}.async ? await ${format}(${data}) : ${format}(${data}))` : (0, codegen_1._)`${format}(${data})`; - const validData = (0, codegen_1._)`(typeof ${format} == "function" ? ${callFormat} : ${format}.test(${data}))`; - return (0, codegen_1._)`${format} && ${format} !== true && ${fType} === ${ruleType} && !${validData}`; - } - } - function validateFormat() { - const formatDef = self.formats[schema]; - if (!formatDef) { - unknownFormat(); - return; - } - if (formatDef === true) return; - const [fmtType, format, fmtRef] = getFormat(formatDef); - if (fmtType === ruleType) cxt.pass(validCondition()); - function unknownFormat() { - if (opts.strictSchema === false) { - self.logger.warn(unknownMsg()); - return; - } - throw new Error(unknownMsg()); - function unknownMsg() { - return `unknown format "${schema}" ignored in schema at path "${errSchemaPath}"`; - } - } - function getFormat(fmtDef) { - const code = fmtDef instanceof RegExp ? (0, codegen_1.regexpCode)(fmtDef) : opts.code.formats ? (0, codegen_1._)`${opts.code.formats}${(0, codegen_1.getProperty)(schema)}` : void 0; - const fmt = gen.scopeValue("formats", { - key: schema, - ref: fmtDef, - code - }); - if (typeof fmtDef == "object" && !(fmtDef instanceof RegExp)) return [ - fmtDef.type || "string", - fmtDef.validate, - (0, codegen_1._)`${fmt}.validate` - ]; - return [ - "string", - fmtDef, - fmt - ]; - } - function validCondition() { - if (typeof formatDef == "object" && !(formatDef instanceof RegExp) && formatDef.async) { - if (!schemaEnv.$async) throw new Error("async format in sync schema"); - return (0, codegen_1._)`await ${fmtRef}(${data})`; - } - return typeof format == "function" ? (0, codegen_1._)`${fmtRef}(${data})` : (0, codegen_1._)`${fmtRef}.test(${data})`; - } - } - } - }; - exports.default = def; -})); - -//#endregion -//#region ../../node_modules/.pnpm/ajv@8.18.0/node_modules/ajv/dist/vocabularies/format/index.js -var require_format$1 = /* @__PURE__ */ __commonJSMin(((exports) => { - Object.defineProperty(exports, "__esModule", { value: true }); - const format = [require_format$2().default]; - exports.default = format; -})); - -//#endregion -//#region ../../node_modules/.pnpm/ajv@8.18.0/node_modules/ajv/dist/vocabularies/metadata.js -var require_metadata = /* @__PURE__ */ __commonJSMin(((exports) => { - Object.defineProperty(exports, "__esModule", { value: true }); - exports.contentVocabulary = exports.metadataVocabulary = void 0; - exports.metadataVocabulary = [ - "title", - "description", - "default", - "deprecated", - "readOnly", - "writeOnly", - "examples" - ]; - exports.contentVocabulary = [ - "contentMediaType", - "contentEncoding", - "contentSchema" - ]; -})); - -//#endregion -//#region ../../node_modules/.pnpm/ajv@8.18.0/node_modules/ajv/dist/vocabularies/draft7.js -var require_draft7 = /* @__PURE__ */ __commonJSMin(((exports) => { - Object.defineProperty(exports, "__esModule", { value: true }); - const core_1 = require_core$2(); - const validation_1 = require_validation$2(); - const applicator_1 = require_applicator$2(); - const format_1 = require_format$1(); - const metadata_1 = require_metadata(); - const draft7Vocabularies = [ - core_1.default, - validation_1.default, - (0, applicator_1.default)(), - format_1.default, - metadata_1.metadataVocabulary, - metadata_1.contentVocabulary - ]; - exports.default = draft7Vocabularies; -})); - -//#endregion -//#region ../../node_modules/.pnpm/ajv@8.18.0/node_modules/ajv/dist/vocabularies/discriminator/types.js -var require_types = /* @__PURE__ */ __commonJSMin(((exports) => { - Object.defineProperty(exports, "__esModule", { value: true }); - exports.DiscrError = void 0; - var DiscrError; - (function(DiscrError) { - DiscrError["Tag"] = "tag"; - DiscrError["Mapping"] = "mapping"; - })(DiscrError || (exports.DiscrError = DiscrError = {})); -})); - -//#endregion -//#region ../../node_modules/.pnpm/ajv@8.18.0/node_modules/ajv/dist/vocabularies/discriminator/index.js -var require_discriminator = /* @__PURE__ */ __commonJSMin(((exports) => { - Object.defineProperty(exports, "__esModule", { value: true }); - const codegen_1 = require_codegen(); - const types_1 = require_types(); - const compile_1 = require_compile(); - const ref_error_1 = require_ref_error(); - const util_1 = require_util(); - const def = { - keyword: "discriminator", - type: "object", - schemaType: "object", - error: { - message: ({ params: { discrError, tagName } }) => discrError === types_1.DiscrError.Tag ? `tag "${tagName}" must be string` : `value of tag "${tagName}" must be in oneOf`, - params: ({ params: { discrError, tag, tagName } }) => (0, codegen_1._)`{error: ${discrError}, tag: ${tagName}, tagValue: ${tag}}` - }, - code(cxt) { - const { gen, data, schema, parentSchema, it } = cxt; - const { oneOf } = parentSchema; - if (!it.opts.discriminator) throw new Error("discriminator: requires discriminator option"); - const tagName = schema.propertyName; - if (typeof tagName != "string") throw new Error("discriminator: requires propertyName"); - if (schema.mapping) throw new Error("discriminator: mapping is not supported"); - if (!oneOf) throw new Error("discriminator: requires oneOf keyword"); - const valid = gen.let("valid", false); - const tag = gen.const("tag", (0, codegen_1._)`${data}${(0, codegen_1.getProperty)(tagName)}`); - gen.if((0, codegen_1._)`typeof ${tag} == "string"`, () => validateMapping(), () => cxt.error(false, { - discrError: types_1.DiscrError.Tag, - tag, - tagName - })); - cxt.ok(valid); - function validateMapping() { - const mapping = getMapping(); - gen.if(false); - for (const tagValue in mapping) { - gen.elseIf((0, codegen_1._)`${tag} === ${tagValue}`); - gen.assign(valid, applyTagSchema(mapping[tagValue])); - } - gen.else(); - cxt.error(false, { - discrError: types_1.DiscrError.Mapping, - tag, - tagName - }); - gen.endIf(); - } - function applyTagSchema(schemaProp) { - const _valid = gen.name("valid"); - const schCxt = cxt.subschema({ - keyword: "oneOf", - schemaProp - }, _valid); - cxt.mergeEvaluated(schCxt, codegen_1.Name); - return _valid; - } - function getMapping() { - var _a; - const oneOfMapping = {}; - const topRequired = hasRequired(parentSchema); - let tagRequired = true; - for (let i = 0; i < oneOf.length; i++) { - let sch = oneOf[i]; - if ((sch === null || sch === void 0 ? void 0 : sch.$ref) && !(0, util_1.schemaHasRulesButRef)(sch, it.self.RULES)) { - const ref = sch.$ref; - sch = compile_1.resolveRef.call(it.self, it.schemaEnv.root, it.baseId, ref); - if (sch instanceof compile_1.SchemaEnv) sch = sch.schema; - if (sch === void 0) throw new ref_error_1.default(it.opts.uriResolver, it.baseId, ref); - } - const propSch = (_a = sch === null || sch === void 0 ? void 0 : sch.properties) === null || _a === void 0 ? void 0 : _a[tagName]; - if (typeof propSch != "object") throw new Error(`discriminator: oneOf subschemas (or referenced schemas) must have "properties/${tagName}"`); - tagRequired = tagRequired && (topRequired || hasRequired(sch)); - addMappings(propSch, i); - } - if (!tagRequired) throw new Error(`discriminator: "${tagName}" must be required`); - return oneOfMapping; - function hasRequired({ required }) { - return Array.isArray(required) && required.includes(tagName); - } - function addMappings(sch, i) { - if (sch.const) addMapping(sch.const, i); - else if (sch.enum) for (const tagValue of sch.enum) addMapping(tagValue, i); - else throw new Error(`discriminator: "properties/${tagName}" must have "const" or "enum"`); - } - function addMapping(tagValue, i) { - if (typeof tagValue != "string" || tagValue in oneOfMapping) throw new Error(`discriminator: "${tagName}" values must be unique strings`); - oneOfMapping[tagValue] = i; - } - } - } - }; - exports.default = def; -})); - -//#endregion -//#region ../../node_modules/.pnpm/ajv@8.18.0/node_modules/ajv/dist/refs/json-schema-draft-07.json -var require_json_schema_draft_07 = /* @__PURE__ */ __commonJSMin(((exports, module) => { - module.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": true, - "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": true, - "readOnly": { - "type": "boolean", - "default": false - }, - "examples": { - "type": "array", - "items": true - }, - "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": true - }, - "maxItems": { "$ref": "#/definitions/nonNegativeInteger" }, - "minItems": { "$ref": "#/definitions/nonNegativeIntegerDefault0" }, - "uniqueItems": { - "type": "boolean", - "default": false - }, - "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": true, - "enum": { - "type": "array", - "items": true, - "minItems": 1, - "uniqueItems": true - }, - "type": { "anyOf": [{ "$ref": "#/definitions/simpleTypes" }, { - "type": "array", - "items": { "$ref": "#/definitions/simpleTypes" }, - "minItems": 1, - "uniqueItems": true - }] }, - "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": true - }; -})); - -//#endregion -//#region ../../node_modules/.pnpm/ajv@8.18.0/node_modules/ajv/dist/ajv.js -var require_ajv = /* @__PURE__ */ __commonJSMin(((exports, module) => { - Object.defineProperty(exports, "__esModule", { value: true }); - exports.MissingRefError = exports.ValidationError = exports.CodeGen = exports.Name = exports.nil = exports.stringify = exports.str = exports._ = exports.KeywordCxt = exports.Ajv = void 0; - const core_1 = require_core$3(); - const draft7_1 = require_draft7(); - const discriminator_1 = require_discriminator(); - const draft7MetaSchema = require_json_schema_draft_07(); - const META_SUPPORT_DATA = ["/properties"]; - const META_SCHEMA_ID = "http://json-schema.org/draft-07/schema"; - var Ajv = class extends core_1.default { - _addVocabularies() { - super._addVocabularies(); - draft7_1.default.forEach((v) => this.addVocabulary(v)); - if (this.opts.discriminator) this.addKeyword(discriminator_1.default); - } - _addDefaultMetaSchema() { - super._addDefaultMetaSchema(); - if (!this.opts.meta) return; - const metaSchema = this.opts.$data ? this.$dataMetaSchema(draft7MetaSchema, META_SUPPORT_DATA) : draft7MetaSchema; - this.addMetaSchema(metaSchema, META_SCHEMA_ID, false); - this.refs["http://json-schema.org/schema"] = META_SCHEMA_ID; - } - defaultMeta() { - return this.opts.defaultMeta = super.defaultMeta() || (this.getSchema(META_SCHEMA_ID) ? META_SCHEMA_ID : void 0); - } - }; - exports.Ajv = Ajv; - module.exports = exports = Ajv; - module.exports.Ajv = Ajv; - Object.defineProperty(exports, "__esModule", { value: true }); - exports.default = Ajv; - var validate_1 = require_validate(); - Object.defineProperty(exports, "KeywordCxt", { - enumerable: true, - get: function() { - return validate_1.KeywordCxt; - } - }); - var codegen_1 = require_codegen(); - Object.defineProperty(exports, "_", { - enumerable: true, - get: function() { - return codegen_1._; - } - }); - Object.defineProperty(exports, "str", { - enumerable: true, - get: function() { - return codegen_1.str; - } - }); - Object.defineProperty(exports, "stringify", { - enumerable: true, - get: function() { - return codegen_1.stringify; - } - }); - Object.defineProperty(exports, "nil", { - enumerable: true, - get: function() { - return codegen_1.nil; - } - }); - Object.defineProperty(exports, "Name", { - enumerable: true, - get: function() { - return codegen_1.Name; - } - }); - Object.defineProperty(exports, "CodeGen", { - enumerable: true, - get: function() { - return codegen_1.CodeGen; - } - }); - var validation_error_1 = require_validation_error(); - Object.defineProperty(exports, "ValidationError", { - enumerable: true, - get: function() { - return validation_error_1.default; - } - }); - var ref_error_1 = require_ref_error(); - Object.defineProperty(exports, "MissingRefError", { - enumerable: true, - get: function() { - return ref_error_1.default; - } - }); -})); - -//#endregion -//#region ../../node_modules/.pnpm/ajv@8.18.0/node_modules/ajv/dist/vocabularies/dynamic/dynamicAnchor.js -var require_dynamicAnchor = /* @__PURE__ */ __commonJSMin(((exports) => { - Object.defineProperty(exports, "__esModule", { value: true }); - exports.dynamicAnchor = void 0; - const codegen_1 = require_codegen(); - const names_1 = require_names(); - const compile_1 = require_compile(); - const ref_1 = require_ref(); - const def = { - keyword: "$dynamicAnchor", - schemaType: "string", - code: (cxt) => dynamicAnchor(cxt, cxt.schema) - }; - function dynamicAnchor(cxt, anchor) { - const { gen, it } = cxt; - it.schemaEnv.root.dynamicAnchors[anchor] = true; - const v = (0, codegen_1._)`${names_1.default.dynamicAnchors}${(0, codegen_1.getProperty)(anchor)}`; - const validate = it.errSchemaPath === "#" ? it.validateName : _getValidate(cxt); - gen.if((0, codegen_1._)`!${v}`, () => gen.assign(v, validate)); - } - exports.dynamicAnchor = dynamicAnchor; - function _getValidate(cxt) { - const { schemaEnv, schema, self } = cxt.it; - const { root, baseId, localRefs, meta } = schemaEnv.root; - const { schemaId } = self.opts; - const sch = new compile_1.SchemaEnv({ - schema, - schemaId, - root, - baseId, - localRefs, - meta - }); - compile_1.compileSchema.call(self, sch); - return (0, ref_1.getValidate)(cxt, sch); - } - exports.default = def; -})); - -//#endregion -//#region ../../node_modules/.pnpm/ajv@8.18.0/node_modules/ajv/dist/vocabularies/dynamic/dynamicRef.js -var require_dynamicRef = /* @__PURE__ */ __commonJSMin(((exports) => { - Object.defineProperty(exports, "__esModule", { value: true }); - exports.dynamicRef = void 0; - const codegen_1 = require_codegen(); - const names_1 = require_names(); - const ref_1 = require_ref(); - const def = { - keyword: "$dynamicRef", - schemaType: "string", - code: (cxt) => dynamicRef(cxt, cxt.schema) - }; - function dynamicRef(cxt, ref) { - const { gen, keyword, it } = cxt; - if (ref[0] !== "#") throw new Error(`"${keyword}" only supports hash fragment reference`); - const anchor = ref.slice(1); - if (it.allErrors) _dynamicRef(); - else { - const valid = gen.let("valid", false); - _dynamicRef(valid); - cxt.ok(valid); - } - function _dynamicRef(valid) { - if (it.schemaEnv.root.dynamicAnchors[anchor]) { - const v = gen.let("_v", (0, codegen_1._)`${names_1.default.dynamicAnchors}${(0, codegen_1.getProperty)(anchor)}`); - gen.if(v, _callRef(v, valid), _callRef(it.validateName, valid)); - } else _callRef(it.validateName, valid)(); - } - function _callRef(validate, valid) { - return valid ? () => gen.block(() => { - (0, ref_1.callRef)(cxt, validate); - gen.let(valid, true); - }) : () => (0, ref_1.callRef)(cxt, validate); - } - } - exports.dynamicRef = dynamicRef; - exports.default = def; -})); - -//#endregion -//#region ../../node_modules/.pnpm/ajv@8.18.0/node_modules/ajv/dist/vocabularies/dynamic/recursiveAnchor.js -var require_recursiveAnchor = /* @__PURE__ */ __commonJSMin(((exports) => { - Object.defineProperty(exports, "__esModule", { value: true }); - const dynamicAnchor_1 = require_dynamicAnchor(); - const util_1 = require_util(); - const def = { - keyword: "$recursiveAnchor", - schemaType: "boolean", - code(cxt) { - if (cxt.schema) (0, dynamicAnchor_1.dynamicAnchor)(cxt, ""); - else (0, util_1.checkStrictMode)(cxt.it, "$recursiveAnchor: false is ignored"); - } - }; - exports.default = def; -})); - -//#endregion -//#region ../../node_modules/.pnpm/ajv@8.18.0/node_modules/ajv/dist/vocabularies/dynamic/recursiveRef.js -var require_recursiveRef = /* @__PURE__ */ __commonJSMin(((exports) => { - Object.defineProperty(exports, "__esModule", { value: true }); - const dynamicRef_1 = require_dynamicRef(); - const def = { - keyword: "$recursiveRef", - schemaType: "string", - code: (cxt) => (0, dynamicRef_1.dynamicRef)(cxt, cxt.schema) - }; - exports.default = def; -})); - -//#endregion -//#region ../../node_modules/.pnpm/ajv@8.18.0/node_modules/ajv/dist/vocabularies/dynamic/index.js -var require_dynamic = /* @__PURE__ */ __commonJSMin(((exports) => { - Object.defineProperty(exports, "__esModule", { value: true }); - const dynamicAnchor_1 = require_dynamicAnchor(); - const dynamicRef_1 = require_dynamicRef(); - const recursiveAnchor_1 = require_recursiveAnchor(); - const recursiveRef_1 = require_recursiveRef(); - const dynamic = [ - dynamicAnchor_1.default, - dynamicRef_1.default, - recursiveAnchor_1.default, - recursiveRef_1.default - ]; - exports.default = dynamic; -})); - -//#endregion -//#region ../../node_modules/.pnpm/ajv@8.18.0/node_modules/ajv/dist/vocabularies/validation/dependentRequired.js -var require_dependentRequired = /* @__PURE__ */ __commonJSMin(((exports) => { - Object.defineProperty(exports, "__esModule", { value: true }); - const dependencies_1 = require_dependencies(); - const def = { - keyword: "dependentRequired", - type: "object", - schemaType: "object", - error: dependencies_1.error, - code: (cxt) => (0, dependencies_1.validatePropertyDeps)(cxt) - }; - exports.default = def; -})); - -//#endregion -//#region ../../node_modules/.pnpm/ajv@8.18.0/node_modules/ajv/dist/vocabularies/applicator/dependentSchemas.js -var require_dependentSchemas = /* @__PURE__ */ __commonJSMin(((exports) => { - Object.defineProperty(exports, "__esModule", { value: true }); - const dependencies_1 = require_dependencies(); - const def = { - keyword: "dependentSchemas", - type: "object", - schemaType: "object", - code: (cxt) => (0, dependencies_1.validateSchemaDeps)(cxt) - }; - exports.default = def; -})); - -//#endregion -//#region ../../node_modules/.pnpm/ajv@8.18.0/node_modules/ajv/dist/vocabularies/validation/limitContains.js -var require_limitContains = /* @__PURE__ */ __commonJSMin(((exports) => { - Object.defineProperty(exports, "__esModule", { value: true }); - const util_1 = require_util(); - const def = { - keyword: ["maxContains", "minContains"], - type: "array", - schemaType: "number", - code({ keyword, parentSchema, it }) { - if (parentSchema.contains === void 0) (0, util_1.checkStrictMode)(it, `"${keyword}" without "contains" is ignored`); - } - }; - exports.default = def; -})); - -//#endregion -//#region ../../node_modules/.pnpm/ajv@8.18.0/node_modules/ajv/dist/vocabularies/next.js -var require_next = /* @__PURE__ */ __commonJSMin(((exports) => { - Object.defineProperty(exports, "__esModule", { value: true }); - const dependentRequired_1 = require_dependentRequired(); - const dependentSchemas_1 = require_dependentSchemas(); - const limitContains_1 = require_limitContains(); - const next = [ - dependentRequired_1.default, - dependentSchemas_1.default, - limitContains_1.default - ]; - exports.default = next; -})); - -//#endregion -//#region ../../node_modules/.pnpm/ajv@8.18.0/node_modules/ajv/dist/vocabularies/unevaluated/unevaluatedProperties.js -var require_unevaluatedProperties = /* @__PURE__ */ __commonJSMin(((exports) => { - Object.defineProperty(exports, "__esModule", { value: true }); - const codegen_1 = require_codegen(); - const util_1 = require_util(); - const names_1 = require_names(); - const def = { - keyword: "unevaluatedProperties", - type: "object", - schemaType: ["boolean", "object"], - trackErrors: true, - error: { - message: "must NOT have unevaluated properties", - params: ({ params }) => (0, codegen_1._)`{unevaluatedProperty: ${params.unevaluatedProperty}}` - }, - code(cxt) { - const { gen, schema, data, errsCount, it } = cxt; - /* istanbul ignore if */ - if (!errsCount) throw new Error("ajv implementation error"); - const { allErrors, props } = it; - if (props instanceof codegen_1.Name) gen.if((0, codegen_1._)`${props} !== true`, () => gen.forIn("key", data, (key) => gen.if(unevaluatedDynamic(props, key), () => unevaluatedPropCode(key)))); - else if (props !== true) gen.forIn("key", data, (key) => props === void 0 ? unevaluatedPropCode(key) : gen.if(unevaluatedStatic(props, key), () => unevaluatedPropCode(key))); - it.props = true; - cxt.ok((0, codegen_1._)`${errsCount} === ${names_1.default.errors}`); - function unevaluatedPropCode(key) { - if (schema === false) { - cxt.setParams({ unevaluatedProperty: key }); - cxt.error(); - if (!allErrors) gen.break(); - return; - } - if (!(0, util_1.alwaysValidSchema)(it, schema)) { - const valid = gen.name("valid"); - cxt.subschema({ - keyword: "unevaluatedProperties", - dataProp: key, - dataPropType: util_1.Type.Str - }, valid); - if (!allErrors) gen.if((0, codegen_1.not)(valid), () => gen.break()); - } - } - function unevaluatedDynamic(evaluatedProps, key) { - return (0, codegen_1._)`!${evaluatedProps} || !${evaluatedProps}[${key}]`; - } - function unevaluatedStatic(evaluatedProps, key) { - const ps = []; - for (const p in evaluatedProps) if (evaluatedProps[p] === true) ps.push((0, codegen_1._)`${key} !== ${p}`); - return (0, codegen_1.and)(...ps); - } - } - }; - exports.default = def; -})); - -//#endregion -//#region ../../node_modules/.pnpm/ajv@8.18.0/node_modules/ajv/dist/vocabularies/unevaluated/unevaluatedItems.js -var require_unevaluatedItems = /* @__PURE__ */ __commonJSMin(((exports) => { - Object.defineProperty(exports, "__esModule", { value: true }); - const codegen_1 = require_codegen(); - const util_1 = require_util(); - const def = { - keyword: "unevaluatedItems", - type: "array", - schemaType: ["boolean", "object"], - error: { - message: ({ params: { len } }) => (0, codegen_1.str)`must NOT have more than ${len} items`, - params: ({ params: { len } }) => (0, codegen_1._)`{limit: ${len}}` - }, - code(cxt) { - const { gen, schema, data, it } = cxt; - const items = it.items || 0; - if (items === true) return; - const len = gen.const("len", (0, codegen_1._)`${data}.length`); - if (schema === false) { - cxt.setParams({ len: items }); - cxt.fail((0, codegen_1._)`${len} > ${items}`); - } else if (typeof schema == "object" && !(0, util_1.alwaysValidSchema)(it, schema)) { - const valid = gen.var("valid", (0, codegen_1._)`${len} <= ${items}`); - gen.if((0, codegen_1.not)(valid), () => validateItems(valid, items)); - cxt.ok(valid); - } - it.items = true; - function validateItems(valid, from) { - gen.forRange("i", from, len, (i) => { - cxt.subschema({ - keyword: "unevaluatedItems", - dataProp: i, - dataPropType: util_1.Type.Num - }, valid); - if (!it.allErrors) gen.if((0, codegen_1.not)(valid), () => gen.break()); - }); - } - } - }; - exports.default = def; -})); - -//#endregion -//#region ../../node_modules/.pnpm/ajv@8.18.0/node_modules/ajv/dist/vocabularies/unevaluated/index.js -var require_unevaluated$1 = /* @__PURE__ */ __commonJSMin(((exports) => { - Object.defineProperty(exports, "__esModule", { value: true }); - const unevaluatedProperties_1 = require_unevaluatedProperties(); - const unevaluatedItems_1 = require_unevaluatedItems(); - const unevaluated = [unevaluatedProperties_1.default, unevaluatedItems_1.default]; - exports.default = unevaluated; -})); - -//#endregion -//#region ../../node_modules/.pnpm/ajv@8.18.0/node_modules/ajv/dist/refs/json-schema-2019-09/schema.json -var require_schema$1 = /* @__PURE__ */ __commonJSMin(((exports, module) => { - module.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": true, - "https://json-schema.org/draft/2019-09/vocab/applicator": true, - "https://json-schema.org/draft/2019-09/vocab/validation": true, - "https://json-schema.org/draft/2019-09/vocab/meta-data": true, - "https://json-schema.org/draft/2019-09/vocab/format": false, - "https://json-schema.org/draft/2019-09/vocab/content": true - }, - "$recursiveAnchor": true, - "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" }] } - } - } - }; -})); - -//#endregion -//#region ../../node_modules/.pnpm/ajv@8.18.0/node_modules/ajv/dist/refs/json-schema-2019-09/meta/applicator.json -var require_applicator$1 = /* @__PURE__ */ __commonJSMin(((exports, module) => { - module.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": true }, - "$recursiveAnchor": true, - "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": "#" } - } } - }; -})); - -//#endregion -//#region ../../node_modules/.pnpm/ajv@8.18.0/node_modules/ajv/dist/refs/json-schema-2019-09/meta/content.json -var require_content$1 = /* @__PURE__ */ __commonJSMin(((exports, module) => { - module.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": true }, - "$recursiveAnchor": true, - "title": "Content vocabulary meta-schema", - "type": ["object", "boolean"], - "properties": { - "contentMediaType": { "type": "string" }, - "contentEncoding": { "type": "string" }, - "contentSchema": { "$recursiveRef": "#" } - } - }; -})); - -//#endregion -//#region ../../node_modules/.pnpm/ajv@8.18.0/node_modules/ajv/dist/refs/json-schema-2019-09/meta/core.json -var require_core$1 = /* @__PURE__ */ __commonJSMin(((exports, module) => { - module.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": true }, - "$recursiveAnchor": true, - "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": false - }, - "$vocabulary": { - "type": "object", - "propertyNames": { - "type": "string", - "format": "uri" - }, - "additionalProperties": { "type": "boolean" } - }, - "$comment": { "type": "string" }, - "$defs": { - "type": "object", - "additionalProperties": { "$recursiveRef": "#" }, - "default": {} - } - } - }; -})); - -//#endregion -//#region ../../node_modules/.pnpm/ajv@8.18.0/node_modules/ajv/dist/refs/json-schema-2019-09/meta/format.json -var require_format = /* @__PURE__ */ __commonJSMin(((exports, module) => { - module.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": true }, - "$recursiveAnchor": true, - "title": "Format vocabulary meta-schema", - "type": ["object", "boolean"], - "properties": { "format": { "type": "string" } } - }; -})); - -//#endregion -//#region ../../node_modules/.pnpm/ajv@8.18.0/node_modules/ajv/dist/refs/json-schema-2019-09/meta/meta-data.json -var require_meta_data$1 = /* @__PURE__ */ __commonJSMin(((exports, module) => { - module.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": true }, - "$recursiveAnchor": true, - "title": "Meta-data vocabulary meta-schema", - "type": ["object", "boolean"], - "properties": { - "title": { "type": "string" }, - "description": { "type": "string" }, - "default": true, - "deprecated": { - "type": "boolean", - "default": false - }, - "readOnly": { - "type": "boolean", - "default": false - }, - "writeOnly": { - "type": "boolean", - "default": false - }, - "examples": { - "type": "array", - "items": true - } - } - }; -})); - -//#endregion -//#region ../../node_modules/.pnpm/ajv@8.18.0/node_modules/ajv/dist/refs/json-schema-2019-09/meta/validation.json -var require_validation$1 = /* @__PURE__ */ __commonJSMin(((exports, module) => { - module.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": true }, - "$recursiveAnchor": true, - "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": false - }, - "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": true, - "enum": { - "type": "array", - "items": true - }, - "type": { "anyOf": [{ "$ref": "#/$defs/simpleTypes" }, { - "type": "array", - "items": { "$ref": "#/$defs/simpleTypes" }, - "minItems": 1, - "uniqueItems": true - }] } - }, - "$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": true, - "default": [] - } - } - }; -})); - -//#endregion -//#region ../../node_modules/.pnpm/ajv@8.18.0/node_modules/ajv/dist/refs/json-schema-2019-09/index.js -var require_json_schema_2019_09 = /* @__PURE__ */ __commonJSMin(((exports) => { - Object.defineProperty(exports, "__esModule", { value: true }); - const metaSchema = require_schema$1(); - const applicator = require_applicator$1(); - const content = require_content$1(); - const core = require_core$1(); - const format = require_format(); - const metadata = require_meta_data$1(); - const validation = require_validation$1(); - const META_SUPPORT_DATA = ["/properties"]; - function addMetaSchema2019($data) { - [ - metaSchema, - applicator, - content, - core, - with$data(this, format), - metadata, - with$data(this, validation) - ].forEach((sch) => this.addMetaSchema(sch, void 0, false)); - return this; - function with$data(ajv, sch) { - return $data ? ajv.$dataMetaSchema(sch, META_SUPPORT_DATA) : sch; - } - } - exports.default = addMetaSchema2019; -})); - -//#endregion -//#region ../../node_modules/.pnpm/ajv@8.18.0/node_modules/ajv/dist/2019.js -var require__2019 = /* @__PURE__ */ __commonJSMin(((exports, module) => { - Object.defineProperty(exports, "__esModule", { value: true }); - exports.MissingRefError = exports.ValidationError = exports.CodeGen = exports.Name = exports.nil = exports.stringify = exports.str = exports._ = exports.KeywordCxt = exports.Ajv2019 = void 0; - const core_1 = require_core$3(); - const draft7_1 = require_draft7(); - const dynamic_1 = require_dynamic(); - const next_1 = require_next(); - const unevaluated_1 = require_unevaluated$1(); - const discriminator_1 = require_discriminator(); - const json_schema_2019_09_1 = require_json_schema_2019_09(); - const META_SCHEMA_ID = "https://json-schema.org/draft/2019-09/schema"; - var Ajv2019 = class extends core_1.default { - constructor(opts = {}) { - super({ - ...opts, - dynamicRef: true, - next: true, - unevaluated: true - }); - } - _addVocabularies() { - super._addVocabularies(); - this.addVocabulary(dynamic_1.default); - draft7_1.default.forEach((v) => this.addVocabulary(v)); - this.addVocabulary(next_1.default); - this.addVocabulary(unevaluated_1.default); - if (this.opts.discriminator) this.addKeyword(discriminator_1.default); - } - _addDefaultMetaSchema() { - super._addDefaultMetaSchema(); - const { $data, meta } = this.opts; - if (!meta) return; - json_schema_2019_09_1.default.call(this, $data); - this.refs["http://json-schema.org/schema"] = META_SCHEMA_ID; - } - defaultMeta() { - return this.opts.defaultMeta = super.defaultMeta() || (this.getSchema(META_SCHEMA_ID) ? META_SCHEMA_ID : void 0); - } - }; - exports.Ajv2019 = Ajv2019; - module.exports = exports = Ajv2019; - module.exports.Ajv2019 = Ajv2019; - Object.defineProperty(exports, "__esModule", { value: true }); - exports.default = Ajv2019; - var validate_1 = require_validate(); - Object.defineProperty(exports, "KeywordCxt", { - enumerable: true, - get: function() { - return validate_1.KeywordCxt; - } - }); - var codegen_1 = require_codegen(); - Object.defineProperty(exports, "_", { - enumerable: true, - get: function() { - return codegen_1._; - } - }); - Object.defineProperty(exports, "str", { - enumerable: true, - get: function() { - return codegen_1.str; - } - }); - Object.defineProperty(exports, "stringify", { - enumerable: true, - get: function() { - return codegen_1.stringify; - } - }); - Object.defineProperty(exports, "nil", { - enumerable: true, - get: function() { - return codegen_1.nil; - } - }); - Object.defineProperty(exports, "Name", { - enumerable: true, - get: function() { - return codegen_1.Name; - } - }); - Object.defineProperty(exports, "CodeGen", { - enumerable: true, - get: function() { - return codegen_1.CodeGen; - } - }); - var validation_error_1 = require_validation_error(); - Object.defineProperty(exports, "ValidationError", { - enumerable: true, - get: function() { - return validation_error_1.default; - } - }); - var ref_error_1 = require_ref_error(); - Object.defineProperty(exports, "MissingRefError", { - enumerable: true, - get: function() { - return ref_error_1.default; - } - }); -})); - -//#endregion -//#region ../../node_modules/.pnpm/ajv@8.18.0/node_modules/ajv/dist/vocabularies/draft2020.js -var require_draft2020 = /* @__PURE__ */ __commonJSMin(((exports) => { - Object.defineProperty(exports, "__esModule", { value: true }); - const core_1 = require_core$2(); - const validation_1 = require_validation$2(); - const applicator_1 = require_applicator$2(); - const dynamic_1 = require_dynamic(); - const next_1 = require_next(); - const unevaluated_1 = require_unevaluated$1(); - const format_1 = require_format$1(); - const metadata_1 = require_metadata(); - const draft2020Vocabularies = [ - dynamic_1.default, - core_1.default, - validation_1.default, - (0, applicator_1.default)(true), - format_1.default, - metadata_1.metadataVocabulary, - metadata_1.contentVocabulary, - next_1.default, - unevaluated_1.default - ]; - exports.default = draft2020Vocabularies; -})); - -//#endregion -//#region ../../node_modules/.pnpm/ajv@8.18.0/node_modules/ajv/dist/refs/json-schema-2020-12/schema.json -var require_schema = /* @__PURE__ */ __commonJSMin(((exports, module) => { - module.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": true, - "https://json-schema.org/draft/2020-12/vocab/applicator": true, - "https://json-schema.org/draft/2020-12/vocab/unevaluated": true, - "https://json-schema.org/draft/2020-12/vocab/validation": true, - "https://json-schema.org/draft/2020-12/vocab/meta-data": true, - "https://json-schema.org/draft/2020-12/vocab/format-annotation": true, - "https://json-schema.org/draft/2020-12/vocab/content": true - }, - "$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": true, - "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": true, - "default": {} - }, - "$recursiveAnchor": { - "$comment": "\"$recursiveAnchor\" has been replaced by \"$dynamicAnchor\".", - "$ref": "meta/core#/$defs/anchorString", - "deprecated": true - }, - "$recursiveRef": { - "$comment": "\"$recursiveRef\" has been replaced by \"$dynamicRef\".", - "$ref": "meta/core#/$defs/uriReferenceString", - "deprecated": true - } - } - }; -})); - -//#endregion -//#region ../../node_modules/.pnpm/ajv@8.18.0/node_modules/ajv/dist/refs/json-schema-2020-12/meta/applicator.json -var require_applicator = /* @__PURE__ */ __commonJSMin(((exports, module) => { - module.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": true }, - "$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" } - } } - }; -})); - -//#endregion -//#region ../../node_modules/.pnpm/ajv@8.18.0/node_modules/ajv/dist/refs/json-schema-2020-12/meta/unevaluated.json -var require_unevaluated = /* @__PURE__ */ __commonJSMin(((exports, module) => { - module.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": true }, - "$dynamicAnchor": "meta", - "title": "Unevaluated applicator vocabulary meta-schema", - "type": ["object", "boolean"], - "properties": { - "unevaluatedItems": { "$dynamicRef": "#meta" }, - "unevaluatedProperties": { "$dynamicRef": "#meta" } - } - }; -})); - -//#endregion -//#region ../../node_modules/.pnpm/ajv@8.18.0/node_modules/ajv/dist/refs/json-schema-2020-12/meta/content.json -var require_content = /* @__PURE__ */ __commonJSMin(((exports, module) => { - module.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": true }, - "$dynamicAnchor": "meta", - "title": "Content vocabulary meta-schema", - "type": ["object", "boolean"], - "properties": { - "contentEncoding": { "type": "string" }, - "contentMediaType": { "type": "string" }, - "contentSchema": { "$dynamicRef": "#meta" } - } - }; -})); - -//#endregion -//#region ../../node_modules/.pnpm/ajv@8.18.0/node_modules/ajv/dist/refs/json-schema-2020-12/meta/core.json -var require_core = /* @__PURE__ */ __commonJSMin(((exports, module) => { - module.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": true }, - "$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" - } - } - }; -})); - -//#endregion -//#region ../../node_modules/.pnpm/ajv@8.18.0/node_modules/ajv/dist/refs/json-schema-2020-12/meta/format-annotation.json -var require_format_annotation = /* @__PURE__ */ __commonJSMin(((exports, module) => { - module.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": true }, - "$dynamicAnchor": "meta", - "title": "Format vocabulary meta-schema for annotation results", - "type": ["object", "boolean"], - "properties": { "format": { "type": "string" } } - }; -})); - -//#endregion -//#region ../../node_modules/.pnpm/ajv@8.18.0/node_modules/ajv/dist/refs/json-schema-2020-12/meta/meta-data.json -var require_meta_data = /* @__PURE__ */ __commonJSMin(((exports, module) => { - module.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": true }, - "$dynamicAnchor": "meta", - "title": "Meta-data vocabulary meta-schema", - "type": ["object", "boolean"], - "properties": { - "title": { "type": "string" }, - "description": { "type": "string" }, - "default": true, - "deprecated": { - "type": "boolean", - "default": false - }, - "readOnly": { - "type": "boolean", - "default": false - }, - "writeOnly": { - "type": "boolean", - "default": false - }, - "examples": { - "type": "array", - "items": true - } - } - }; -})); - -//#endregion -//#region ../../node_modules/.pnpm/ajv@8.18.0/node_modules/ajv/dist/refs/json-schema-2020-12/meta/validation.json -var require_validation = /* @__PURE__ */ __commonJSMin(((exports, module) => { - module.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": true }, - "$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": true - }] }, - "const": true, - "enum": { - "type": "array", - "items": true - }, - "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": false - }, - "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": true, - "default": [] - } - } - }; -})); - -//#endregion -//#region ../../node_modules/.pnpm/ajv@8.18.0/node_modules/ajv/dist/refs/json-schema-2020-12/index.js -var require_json_schema_2020_12 = /* @__PURE__ */ __commonJSMin(((exports) => { - Object.defineProperty(exports, "__esModule", { value: true }); - const metaSchema = require_schema(); - const applicator = require_applicator(); - const unevaluated = require_unevaluated(); - const content = require_content(); - const core = require_core(); - const format = require_format_annotation(); - const metadata = require_meta_data(); - const validation = require_validation(); - const META_SUPPORT_DATA = ["/properties"]; - function addMetaSchema2020($data) { - [ - metaSchema, - applicator, - unevaluated, - content, - core, - with$data(this, format), - metadata, - with$data(this, validation) - ].forEach((sch) => this.addMetaSchema(sch, void 0, false)); - return this; - function with$data(ajv, sch) { - return $data ? ajv.$dataMetaSchema(sch, META_SUPPORT_DATA) : sch; - } - } - exports.default = addMetaSchema2020; -})); - -//#endregion -//#region ../../node_modules/.pnpm/ajv@8.18.0/node_modules/ajv/dist/2020.js -var require__2020 = /* @__PURE__ */ __commonJSMin(((exports, module) => { - Object.defineProperty(exports, "__esModule", { value: true }); - exports.MissingRefError = exports.ValidationError = exports.CodeGen = exports.Name = exports.nil = exports.stringify = exports.str = exports._ = exports.KeywordCxt = exports.Ajv2020 = void 0; - const core_1 = require_core$3(); - const draft2020_1 = require_draft2020(); - const discriminator_1 = require_discriminator(); - const json_schema_2020_12_1 = require_json_schema_2020_12(); - const META_SCHEMA_ID = "https://json-schema.org/draft/2020-12/schema"; - var Ajv2020 = class extends core_1.default { - constructor(opts = {}) { - super({ - ...opts, - dynamicRef: true, - next: true, - unevaluated: true - }); - } - _addVocabularies() { - super._addVocabularies(); - draft2020_1.default.forEach((v) => this.addVocabulary(v)); - if (this.opts.discriminator) this.addKeyword(discriminator_1.default); - } - _addDefaultMetaSchema() { - super._addDefaultMetaSchema(); - const { $data, meta } = this.opts; - if (!meta) return; - json_schema_2020_12_1.default.call(this, $data); - this.refs["http://json-schema.org/schema"] = META_SCHEMA_ID; - } - defaultMeta() { - return this.opts.defaultMeta = super.defaultMeta() || (this.getSchema(META_SCHEMA_ID) ? META_SCHEMA_ID : void 0); - } - }; - exports.Ajv2020 = Ajv2020; - module.exports = exports = Ajv2020; - module.exports.Ajv2020 = Ajv2020; - Object.defineProperty(exports, "__esModule", { value: true }); - exports.default = Ajv2020; - var validate_1 = require_validate(); - Object.defineProperty(exports, "KeywordCxt", { - enumerable: true, - get: function() { - return validate_1.KeywordCxt; - } - }); - var codegen_1 = require_codegen(); - Object.defineProperty(exports, "_", { - enumerable: true, - get: function() { - return codegen_1._; - } - }); - Object.defineProperty(exports, "str", { - enumerable: true, - get: function() { - return codegen_1.str; - } - }); - Object.defineProperty(exports, "stringify", { - enumerable: true, - get: function() { - return codegen_1.stringify; - } - }); - Object.defineProperty(exports, "nil", { - enumerable: true, - get: function() { - return codegen_1.nil; - } - }); - Object.defineProperty(exports, "Name", { - enumerable: true, - get: function() { - return codegen_1.Name; - } - }); - Object.defineProperty(exports, "CodeGen", { - enumerable: true, - get: function() { - return codegen_1.CodeGen; - } - }); - var validation_error_1 = require_validation_error(); - Object.defineProperty(exports, "ValidationError", { - enumerable: true, - get: function() { - return validation_error_1.default; - } - }); - var ref_error_1 = require_ref_error(); - Object.defineProperty(exports, "MissingRefError", { - enumerable: true, - get: function() { - return ref_error_1.default; - } - }); -})); - -//#endregion -//#region ../../node_modules/.pnpm/ajv-formats@3.0.1_ajv@8.18.0/node_modules/ajv-formats/dist/formats.js -var require_formats = /* @__PURE__ */ __commonJSMin(((exports) => { - Object.defineProperty(exports, "__esModule", { value: true }); - exports.formatNames = exports.fastFormats = exports.fullFormats = void 0; - function fmtDef(validate, compare) { - return { - validate, - compare - }; - } - exports.fullFormats = { - date: fmtDef(date, compareDate), - time: fmtDef(getTime(true), compareTime), - "date-time": fmtDef(getDateTime(true), compareDateTime), - "iso-time": fmtDef(getTime(), compareIsoTime), - "iso-date-time": fmtDef(getDateTime(), compareIsoDateTime), - duration: /^P(?!$)((\d+Y)?(\d+M)?(\d+D)?(T(?=\d)(\d+H)?(\d+M)?(\d+S)?)?|(\d+W)?)$/, - uri, - "uri-reference": /^(?:[a-z][a-z0-9+\-.]*:)?(?:\/?\/(?:(?:[a-z0-9\-._~!$&'()*+,;=:]|%[0-9a-f]{2})*@)?(?:\[(?:(?:(?:(?:[0-9a-f]{1,4}:){6}|::(?:[0-9a-f]{1,4}:){5}|(?:[0-9a-f]{1,4})?::(?:[0-9a-f]{1,4}:){4}|(?:(?:[0-9a-f]{1,4}:){0,1}[0-9a-f]{1,4})?::(?:[0-9a-f]{1,4}:){3}|(?:(?:[0-9a-f]{1,4}:){0,2}[0-9a-f]{1,4})?::(?:[0-9a-f]{1,4}:){2}|(?:(?:[0-9a-f]{1,4}:){0,3}[0-9a-f]{1,4})?::[0-9a-f]{1,4}:|(?:(?:[0-9a-f]{1,4}:){0,4}[0-9a-f]{1,4})?::)(?:[0-9a-f]{1,4}:[0-9a-f]{1,4}|(?:(?:25[0-5]|2[0-4]\d|[01]?\d\d?)\.){3}(?:25[0-5]|2[0-4]\d|[01]?\d\d?))|(?:(?:[0-9a-f]{1,4}:){0,5}[0-9a-f]{1,4})?::[0-9a-f]{1,4}|(?:(?:[0-9a-f]{1,4}:){0,6}[0-9a-f]{1,4})?::)|[Vv][0-9a-f]+\.[a-z0-9\-._~!$&'()*+,;=:]+)\]|(?:(?:25[0-5]|2[0-4]\d|[01]?\d\d?)\.){3}(?:25[0-5]|2[0-4]\d|[01]?\d\d?)|(?:[a-z0-9\-._~!$&'"()*+,;=]|%[0-9a-f]{2})*)(?::\d*)?(?:\/(?:[a-z0-9\-._~!$&'"()*+,;=:@]|%[0-9a-f]{2})*)*|\/(?:(?:[a-z0-9\-._~!$&'"()*+,;=:@]|%[0-9a-f]{2})+(?:\/(?:[a-z0-9\-._~!$&'"()*+,;=:@]|%[0-9a-f]{2})*)*)?|(?:[a-z0-9\-._~!$&'"()*+,;=:@]|%[0-9a-f]{2})+(?:\/(?:[a-z0-9\-._~!$&'"()*+,;=:@]|%[0-9a-f]{2})*)*)?(?:\?(?:[a-z0-9\-._~!$&'"()*+,;=:@/?]|%[0-9a-f]{2})*)?(?:#(?:[a-z0-9\-._~!$&'"()*+,;=:@/?]|%[0-9a-f]{2})*)?$/i, - "uri-template": /^(?:(?:[^\x00-\x20"'<>%\\^`{|}]|%[0-9a-f]{2})|\{[+#./;?&=,!@|]?(?:[a-z0-9_]|%[0-9a-f]{2})+(?::[1-9][0-9]{0,3}|\*)?(?:,(?:[a-z0-9_]|%[0-9a-f]{2})+(?::[1-9][0-9]{0,3}|\*)?)*\})*$/i, - url: /^(?:https?|ftp):\/\/(?:\S+(?::\S*)?@)?(?:(?!(?:10|127)(?:\.\d{1,3}){3})(?!(?:169\.254|192\.168)(?:\.\d{1,3}){2})(?!172\.(?:1[6-9]|2\d|3[0-1])(?:\.\d{1,3}){2})(?:[1-9]\d?|1\d\d|2[01]\d|22[0-3])(?:\.(?:1?\d{1,2}|2[0-4]\d|25[0-5])){2}(?:\.(?:[1-9]\d?|1\d\d|2[0-4]\d|25[0-4]))|(?:(?:[a-z0-9\u{00a1}-\u{ffff}]+-)*[a-z0-9\u{00a1}-\u{ffff}]+)(?:\.(?:[a-z0-9\u{00a1}-\u{ffff}]+-)*[a-z0-9\u{00a1}-\u{ffff}]+)*(?:\.(?:[a-z\u{00a1}-\u{ffff}]{2,})))(?::\d{2,5})?(?:\/[^\s]*)?$/iu, - email: /^[a-z0-9!#$%&'*+/=?^_`{|}~-]+(?:\.[a-z0-9!#$%&'*+/=?^_`{|}~-]+)*@(?:[a-z0-9](?:[a-z0-9-]*[a-z0-9])?\.)+[a-z0-9](?:[a-z0-9-]*[a-z0-9])?$/i, - hostname: /^(?=.{1,253}\.?$)[a-z0-9](?:[a-z0-9-]{0,61}[a-z0-9])?(?:\.[a-z0-9](?:[-0-9a-z]{0,61}[0-9a-z])?)*\.?$/i, - ipv4: /^(?:(?:25[0-5]|2[0-4]\d|1\d\d|[1-9]?\d)\.){3}(?:25[0-5]|2[0-4]\d|1\d\d|[1-9]?\d)$/, - ipv6: /^((([0-9a-f]{1,4}:){7}([0-9a-f]{1,4}|:))|(([0-9a-f]{1,4}:){6}(:[0-9a-f]{1,4}|((25[0-5]|2[0-4]\d|1\d\d|[1-9]?\d)(\.(25[0-5]|2[0-4]\d|1\d\d|[1-9]?\d)){3})|:))|(([0-9a-f]{1,4}:){5}(((:[0-9a-f]{1,4}){1,2})|:((25[0-5]|2[0-4]\d|1\d\d|[1-9]?\d)(\.(25[0-5]|2[0-4]\d|1\d\d|[1-9]?\d)){3})|:))|(([0-9a-f]{1,4}:){4}(((:[0-9a-f]{1,4}){1,3})|((:[0-9a-f]{1,4})?:((25[0-5]|2[0-4]\d|1\d\d|[1-9]?\d)(\.(25[0-5]|2[0-4]\d|1\d\d|[1-9]?\d)){3}))|:))|(([0-9a-f]{1,4}:){3}(((:[0-9a-f]{1,4}){1,4})|((:[0-9a-f]{1,4}){0,2}:((25[0-5]|2[0-4]\d|1\d\d|[1-9]?\d)(\.(25[0-5]|2[0-4]\d|1\d\d|[1-9]?\d)){3}))|:))|(([0-9a-f]{1,4}:){2}(((:[0-9a-f]{1,4}){1,5})|((:[0-9a-f]{1,4}){0,3}:((25[0-5]|2[0-4]\d|1\d\d|[1-9]?\d)(\.(25[0-5]|2[0-4]\d|1\d\d|[1-9]?\d)){3}))|:))|(([0-9a-f]{1,4}:){1}(((:[0-9a-f]{1,4}){1,6})|((:[0-9a-f]{1,4}){0,4}:((25[0-5]|2[0-4]\d|1\d\d|[1-9]?\d)(\.(25[0-5]|2[0-4]\d|1\d\d|[1-9]?\d)){3}))|:))|(:(((:[0-9a-f]{1,4}){1,7})|((:[0-9a-f]{1,4}){0,5}:((25[0-5]|2[0-4]\d|1\d\d|[1-9]?\d)(\.(25[0-5]|2[0-4]\d|1\d\d|[1-9]?\d)){3}))|:)))$/i, - regex, - 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, - int32: { - type: "number", - validate: validateInt32 - }, - int64: { - type: "number", - validate: validateInt64 - }, - float: { - type: "number", - validate: validateNumber - }, - double: { - type: "number", - validate: validateNumber - }, - password: true, - binary: true - }; - exports.fastFormats = { - ...exports.fullFormats, - date: fmtDef(/^\d\d\d\d-[0-1]\d-[0-3]\d$/, compareDate), - time: fmtDef(/^(?:[0-2]\d:[0-5]\d:[0-5]\d|23:59:60)(?:\.\d+)?(?:z|[+-]\d\d(?::?\d\d)?)$/i, compareTime), - "date-time": fmtDef(/^\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, compareDateTime), - "iso-time": fmtDef(/^(?:[0-2]\d:[0-5]\d:[0-5]\d|23:59:60)(?:\.\d+)?(?:z|[+-]\d\d(?::?\d\d)?)?$/i, compareIsoTime), - "iso-date-time": fmtDef(/^\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, compareIsoDateTime), - uri: /^(?:[a-z][a-z0-9+\-.]*:)(?:\/?\/)?[^\s]*$/i, - "uri-reference": /^(?:(?:[a-z][a-z0-9+\-.]*:)?\/?\/)?(?:[^\\\s#][^\s#]*)?(?:#[^\\\s]*)?$/i, - email: /^[a-z0-9.!#$%&'*+/=?^_`{|}~-]+@[a-z0-9](?:[a-z0-9-]{0,61}[a-z0-9])?(?:\.[a-z0-9](?:[a-z0-9-]{0,61}[a-z0-9])?)*$/i - }; - exports.formatNames = Object.keys(exports.fullFormats); - function isLeapYear(year) { - return year % 4 === 0 && (year % 100 !== 0 || year % 400 === 0); - } - const DATE = /^(\d\d\d\d)-(\d\d)-(\d\d)$/; - const DAYS = [ - 0, - 31, - 28, - 31, - 30, - 31, - 30, - 31, - 31, - 30, - 31, - 30, - 31 - ]; - function date(str) { - const matches = DATE.exec(str); - if (!matches) return false; - const year = +matches[1]; - const month = +matches[2]; - const day = +matches[3]; - return month >= 1 && month <= 12 && day >= 1 && day <= (month === 2 && isLeapYear(year) ? 29 : DAYS[month]); - } - function compareDate(d1, d2) { - if (!(d1 && d2)) return void 0; - if (d1 > d2) return 1; - if (d1 < d2) return -1; - return 0; - } - const TIME = /^(\d\d):(\d\d):(\d\d(?:\.\d+)?)(z|([+-])(\d\d)(?::?(\d\d))?)?$/i; - function getTime(strictTimeZone) { - return function time(str) { - const matches = TIME.exec(str); - if (!matches) return false; - const hr = +matches[1]; - const min = +matches[2]; - const sec = +matches[3]; - const tz = matches[4]; - const tzSign = matches[5] === "-" ? -1 : 1; - const tzH = +(matches[6] || 0); - const tzM = +(matches[7] || 0); - if (tzH > 23 || tzM > 59 || strictTimeZone && !tz) return false; - if (hr <= 23 && min <= 59 && sec < 60) return true; - const utcMin = min - tzM * tzSign; - const utcHr = hr - tzH * tzSign - (utcMin < 0 ? 1 : 0); - return (utcHr === 23 || utcHr === -1) && (utcMin === 59 || utcMin === -1) && sec < 61; - }; - } - function compareTime(s1, s2) { - if (!(s1 && s2)) return void 0; - const t1 = (/* @__PURE__ */ new Date("2020-01-01T" + s1)).valueOf(); - const t2 = (/* @__PURE__ */ new Date("2020-01-01T" + s2)).valueOf(); - if (!(t1 && t2)) return void 0; - return t1 - t2; - } - function compareIsoTime(t1, t2) { - if (!(t1 && t2)) return void 0; - const a1 = TIME.exec(t1); - const a2 = TIME.exec(t2); - if (!(a1 && a2)) return void 0; - t1 = a1[1] + a1[2] + a1[3]; - t2 = a2[1] + a2[2] + a2[3]; - if (t1 > t2) return 1; - if (t1 < t2) return -1; - return 0; - } - const DATE_TIME_SEPARATOR = /t|\s/i; - function getDateTime(strictTimeZone) { - const time = getTime(strictTimeZone); - return function date_time(str) { - const dateTime = str.split(DATE_TIME_SEPARATOR); - return dateTime.length === 2 && date(dateTime[0]) && time(dateTime[1]); - }; - } - function compareDateTime(dt1, dt2) { - if (!(dt1 && dt2)) return void 0; - const d1 = new Date(dt1).valueOf(); - const d2 = new Date(dt2).valueOf(); - if (!(d1 && d2)) return void 0; - return d1 - d2; - } - function compareIsoDateTime(dt1, dt2) { - if (!(dt1 && dt2)) return void 0; - const [d1, t1] = dt1.split(DATE_TIME_SEPARATOR); - const [d2, t2] = dt2.split(DATE_TIME_SEPARATOR); - const res = compareDate(d1, d2); - if (res === void 0) return void 0; - return res || compareTime(t1, t2); - } - const NOT_URI_FRAGMENT = /\/|:/; - const URI = /^(?:[a-z][a-z0-9+\-.]*:)(?:\/?\/(?:(?:[a-z0-9\-._~!$&'()*+,;=:]|%[0-9a-f]{2})*@)?(?:\[(?:(?:(?:(?:[0-9a-f]{1,4}:){6}|::(?:[0-9a-f]{1,4}:){5}|(?:[0-9a-f]{1,4})?::(?:[0-9a-f]{1,4}:){4}|(?:(?:[0-9a-f]{1,4}:){0,1}[0-9a-f]{1,4})?::(?:[0-9a-f]{1,4}:){3}|(?:(?:[0-9a-f]{1,4}:){0,2}[0-9a-f]{1,4})?::(?:[0-9a-f]{1,4}:){2}|(?:(?:[0-9a-f]{1,4}:){0,3}[0-9a-f]{1,4})?::[0-9a-f]{1,4}:|(?:(?:[0-9a-f]{1,4}:){0,4}[0-9a-f]{1,4})?::)(?:[0-9a-f]{1,4}:[0-9a-f]{1,4}|(?:(?:25[0-5]|2[0-4]\d|[01]?\d\d?)\.){3}(?:25[0-5]|2[0-4]\d|[01]?\d\d?))|(?:(?:[0-9a-f]{1,4}:){0,5}[0-9a-f]{1,4})?::[0-9a-f]{1,4}|(?:(?:[0-9a-f]{1,4}:){0,6}[0-9a-f]{1,4})?::)|[Vv][0-9a-f]+\.[a-z0-9\-._~!$&'()*+,;=:]+)\]|(?:(?:25[0-5]|2[0-4]\d|[01]?\d\d?)\.){3}(?:25[0-5]|2[0-4]\d|[01]?\d\d?)|(?:[a-z0-9\-._~!$&'()*+,;=]|%[0-9a-f]{2})*)(?::\d*)?(?:\/(?:[a-z0-9\-._~!$&'()*+,;=:@]|%[0-9a-f]{2})*)*|\/(?:(?:[a-z0-9\-._~!$&'()*+,;=:@]|%[0-9a-f]{2})+(?:\/(?:[a-z0-9\-._~!$&'()*+,;=:@]|%[0-9a-f]{2})*)*)?|(?:[a-z0-9\-._~!$&'()*+,;=:@]|%[0-9a-f]{2})+(?:\/(?:[a-z0-9\-._~!$&'()*+,;=:@]|%[0-9a-f]{2})*)*)(?:\?(?:[a-z0-9\-._~!$&'()*+,;=:@/?]|%[0-9a-f]{2})*)?(?:#(?:[a-z0-9\-._~!$&'()*+,;=:@/?]|%[0-9a-f]{2})*)?$/i; - function uri(str) { - return NOT_URI_FRAGMENT.test(str) && URI.test(str); - } - const BYTE = /^(?:[A-Za-z0-9+/]{4})*(?:[A-Za-z0-9+/]{2}==|[A-Za-z0-9+/]{3}=)?$/gm; - function byte(str) { - BYTE.lastIndex = 0; - return BYTE.test(str); - } - const MIN_INT32 = -(2 ** 31); - const MAX_INT32 = 2 ** 31 - 1; - function validateInt32(value) { - return Number.isInteger(value) && value <= MAX_INT32 && value >= MIN_INT32; - } - function validateInt64(value) { - return Number.isInteger(value); - } - function validateNumber() { - return true; - } - const Z_ANCHOR = /[^\\]\\Z/; - function regex(str) { - if (Z_ANCHOR.test(str)) return false; - try { - new RegExp(str); - return true; - } catch (e) { - return false; - } - } -})); - -//#endregion -//#region ../../node_modules/.pnpm/ajv-formats@3.0.1_ajv@8.18.0/node_modules/ajv-formats/dist/limit.js -var require_limit = /* @__PURE__ */ __commonJSMin(((exports) => { - Object.defineProperty(exports, "__esModule", { value: true }); - exports.formatLimitDefinition = void 0; - const ajv_1 = require_ajv(); - const codegen_1 = require_codegen(); - const ops = codegen_1.operators; - const KWDs = { - formatMaximum: { - okStr: "<=", - ok: ops.LTE, - fail: ops.GT - }, - formatMinimum: { - okStr: ">=", - ok: ops.GTE, - fail: ops.LT - }, - formatExclusiveMaximum: { - okStr: "<", - ok: ops.LT, - fail: ops.GTE - }, - formatExclusiveMinimum: { - okStr: ">", - ok: ops.GT, - fail: ops.LTE - } - }; - const error = { - message: ({ keyword, schemaCode }) => (0, codegen_1.str)`should be ${KWDs[keyword].okStr} ${schemaCode}`, - params: ({ keyword, schemaCode }) => (0, codegen_1._)`{comparison: ${KWDs[keyword].okStr}, limit: ${schemaCode}}` - }; - exports.formatLimitDefinition = { - keyword: Object.keys(KWDs), - type: "string", - schemaType: "string", - $data: true, - error, - code(cxt) { - const { gen, data, schemaCode, keyword, it } = cxt; - const { opts, self } = it; - if (!opts.validateFormats) return; - const fCxt = new ajv_1.KeywordCxt(it, self.RULES.all.format.definition, "format"); - if (fCxt.$data) validate$DataFormat(); - else validateFormat(); - function validate$DataFormat() { - const fmts = gen.scopeValue("formats", { - ref: self.formats, - code: opts.code.formats - }); - const fmt = gen.const("fmt", (0, codegen_1._)`${fmts}[${fCxt.schemaCode}]`); - cxt.fail$data((0, codegen_1.or)((0, codegen_1._)`typeof ${fmt} != "object"`, (0, codegen_1._)`${fmt} instanceof RegExp`, (0, codegen_1._)`typeof ${fmt}.compare != "function"`, compareCode(fmt))); - } - function validateFormat() { - const format = fCxt.schema; - const fmtDef = self.formats[format]; - if (!fmtDef || fmtDef === true) return; - if (typeof fmtDef != "object" || fmtDef instanceof RegExp || typeof fmtDef.compare != "function") throw new Error(`"${keyword}": format "${format}" does not define "compare" function`); - const fmt = gen.scopeValue("formats", { - key: format, - ref: fmtDef, - code: opts.code.formats ? (0, codegen_1._)`${opts.code.formats}${(0, codegen_1.getProperty)(format)}` : void 0 - }); - cxt.fail$data(compareCode(fmt)); - } - function compareCode(fmt) { - return (0, codegen_1._)`${fmt}.compare(${data}, ${schemaCode}) ${KWDs[keyword].fail} 0`; - } - }, - dependencies: ["format"] - }; - const formatLimitPlugin = (ajv) => { - ajv.addKeyword(exports.formatLimitDefinition); - return ajv; - }; - exports.default = formatLimitPlugin; -})); - -//#endregion -//#region ../../node_modules/.pnpm/ajv-formats@3.0.1_ajv@8.18.0/node_modules/ajv-formats/dist/index.js -var require_dist = /* @__PURE__ */ __commonJSMin(((exports, module) => { - Object.defineProperty(exports, "__esModule", { value: true }); - const formats_1 = require_formats(); - const limit_1 = require_limit(); - const codegen_1 = require_codegen(); - const fullName = new codegen_1.Name("fullFormats"); - const fastName = new codegen_1.Name("fastFormats"); - const formatsPlugin = (ajv, opts = { keywords: true }) => { - if (Array.isArray(opts)) { - addFormats(ajv, opts, formats_1.fullFormats, fullName); - return ajv; - } - const [formats, exportName] = opts.mode === "fast" ? [formats_1.fastFormats, fastName] : [formats_1.fullFormats, fullName]; - addFormats(ajv, opts.formats || formats_1.formatNames, formats, exportName); - if (opts.keywords) (0, limit_1.default)(ajv); - return ajv; - }; - formatsPlugin.get = (name, mode = "full") => { - const f = (mode === "fast" ? formats_1.fastFormats : formats_1.fullFormats)[name]; - if (!f) throw new Error(`Unknown format "${name}"`); - return f; - }; - function addFormats(ajv, list, fs, exportName) { - var _a; - var _b; - (_a = (_b = ajv.opts.code).formats) !== null && _a !== void 0 || (_b.formats = (0, codegen_1._)`require("ajv-formats/dist/formats").${exportName}`); - for (const f of list) ajv.addFormat(f, fs[f]); - } - module.exports = exports = formatsPlugin; - Object.defineProperty(exports, "__esModule", { value: true }); - exports.default = formatsPlugin; -})); - -//#endregion -//#region ../core-internal/src/validators/ajvProvider.ts -var import_ajv = require_ajv(); -var import__2019 = require__2019(); -var import__2020 = require__2020(); -var import_dist = /* @__PURE__ */ __toESM(require_dist(), 1); -/** `ajv-formats` default export, normalised through the CJS/ESM interop wrapper. */ -const ajvProvider_CEoC_sr_addFormats = import_dist.default; -function createDefaultAjvInstance(engineClass) { - const ajv = new engineClass({ - strict: false, - validateFormats: true, - validateSchema: false, - allErrors: true - }); - ajvProvider_CEoC_sr_addFormats(ajv); - return ajv; -} -/** -* AJV-backed JSON Schema validator. See `@modelcontextprotocol/{client,server}/validators/ajv` -* for the customisation entry point (re-exports `Ajv` and `addFormats` from the bundled copy). -* -* Default dispatches on the schema's declared dialect: no `$schema` or 2020-12 → `Ajv2020` -* (SEP-1613); 2019-09 → `Ajv2019`; draft-07 or draft-06 → the classic draft-07 `Ajv` class -* (draft-07's changes over draft-06 are additive, so one engine covers both). Known draft-07 deviation: classic Ajv -* evaluates keywords adjacent to `$ref` (stricter than draft-07's ignore-siblings rule, matching -* v1's default engine), while the cfworker provider ignores them per spec. -* Schemas declaring any other `$schema` are -* rejected with a plain `Error`; pass a pre-configured Ajv instance to validate -* other dialects. The SDK bundles ajv internally but does not re-export `Ajv2020` (its type -* graph tips downstream declaration bundling — see #2339). To construct a custom 2020-12 -* instance, add `ajv` to your own dependencies (matching the SDK's pinned version) and -* `import { Ajv2020 } from 'ajv/dist/2020.js'` — `new Ajv(...)` is the draft-07 class and would -* silently downgrade dialect. -* -* @example Use with default configuration -* ```ts source="./ajvProvider.examples.ts#AjvJsonSchemaValidator_default" -* const validator = new AjvJsonSchemaValidator(); -* ``` -* -* @example Use with a custom AJV instance -* ```ts source="./ajvProvider.examples.ts#AjvJsonSchemaValidator_customInstance" -* // import { Ajv2020 } from 'ajv/dist/2020.js'; -* const ajv = new Ajv2020({ strict: false, validateSchema: false, allErrors: true }); -* const validator = new AjvJsonSchemaValidator(ajv); -* ``` -* -* @example Register ajv-formats -* ```ts source="./ajvProvider.examples.ts#AjvJsonSchemaValidator_withFormats" -* // import { Ajv2020 } from 'ajv/dist/2020.js'; -* const ajv = new Ajv2020({ strict: false, validateSchema: false, allErrors: true }); -* addFormats(ajv); -* const validator = new AjvJsonSchemaValidator(ajv); -* ``` -*/ -var AjvJsonSchemaValidator = class { - _ajv; - /** Lazy classic (draft-07) engine, built on the first draft-07/draft-06-declared schema. */ - _ajvDraft7; - /** Lazy 2019-09 engine, built on the first 2019-09-declared schema. */ - _ajv2019; - /** True iff the constructor received a caller-supplied engine; the `$schema` dispatch is skipped. */ - _userAjv; - /** - * @param ajv - Optional pre-configured AJV-compatible instance. When supplied, this instance is - * used for **every** schema regardless of its declared `$schema` (the caller owns dialect - * choice). When omitted, the provider constructs per-dialect engines (`Ajv2020`, `Ajv2019`, - * and the classic draft-07 `Ajv` for draft-07/06-declared schemas) with - * `strict: false`, `validateFormats: true`, `validateSchema: false`, `allErrors: true`, and - * `ajv-formats` registered — **lazily, on the first {@linkcode getValidator} call needing each**, so - * constructing the provider (e.g. as the default validator of a `Client`/`Server` that never - * validates a JSON Schema) does not pay the ajv + ajv-formats instantiation cost. The parameter - * is typed structurally so consumers who don't pass an instance need not have `ajv` installed. - */ - constructor(ajv) { - this._userAjv = ajv !== void 0; - this._ajv = ajv; - } - /** The underlying 2020-12 engine — the default instance is created on first use. */ - get ajv() { - return this._ajv ??= createDefaultAjvInstance(import__2020.Ajv2020); - } - /** - * Pick the engine for a schema's declared dialect. A caller-supplied engine is used for - * every schema — do not second-guess by `$schema` (bring-your-own-validator means - * bring-your-own-dialect). Otherwise: no `$schema` or 2020-12 → `Ajv2020`; 2019-09 → - * `Ajv2019`; draft-07 or draft-06 → classic `Ajv`; anything else → `Error`. - */ - _engineFor(schema) { - if (this._userAjv) return this.ajv; - const dialect = declaredDialect(schema, "pass a pre-configured Ajv instance to AjvJsonSchemaValidator(ajv) to validate other dialects."); - if (dialect === "2020-12") return this.ajv; - if (dialect === "2019-09") return this._ajv2019 ??= createDefaultAjvInstance(import__2019.Ajv2019); - return this._ajvDraft7 ??= createDefaultAjvInstance(import_ajv.Ajv); - } - getValidator(schema) { - const engine = this._engineFor(schema); - const ajvValidator = "$id" in schema && typeof schema.$id === "string" ? engine.getSchema(schema.$id) ?? engine.compile(schema) : engine.compile(schema); - return (input) => { - return ajvValidator(input) ? { - valid: true, - data: input, - errorMessage: void 0 - } : { - valid: false, - data: void 0, - errorMessage: engine.errorsText(ajvValidator.errors) - }; - }; - } -}; -/** -* Draft-07 AJV class, re-exported for consumers who need to opt back to the pre-SEP-1613 default. -* The full v1-equivalent construction is: -* -* ```ts -* const ajv = new Ajv({ strict: false, validateFormats: true, validateSchema: false, allErrors: true }); -* addFormats(ajv); -* new AjvJsonSchemaValidator(ajv); -* ``` -* -* (omitting `validateSchema: false` makes a 2020-12-stamped `$schema` fail with an opaque -* "no schema with key or ref …" engine error; omitting `addFormats` silently drops `format` -* validation that the v1 default had). -* -* The SDK bundles ajv internally but does not re-export `Ajv2020` (its type graph tips downstream -* declaration bundling — see #2339). To construct a custom 2020-12 instance, add `ajv` to your own -* dependencies (matching the SDK's pinned version) and `import { Ajv2020 } from 'ajv/dist/2020.js'`. -*/ -const ajvProvider_CEoC_sr_Ajv = import_ajv.Ajv; - -//#endregion - -//# sourceMappingURL=ajvProvider-CEoC__sr.mjs.map - - - - - - - - -//#region src/server/completable.ts -const COMPLETABLE_SYMBOL = Symbol.for("mcp.completable"); -/** -* Wraps a schema to provide autocompletion capabilities. Useful for, e.g., prompt arguments in MCP. -* -* @example -* ```ts source="./completable.examples.ts#completable_basicUsage" -* server.registerPrompt( -* 'review-code', -* { -* title: 'Code Review', -* argsSchema: z.object({ -* language: completable(z.string().describe('Programming language'), value => -* ['typescript', 'javascript', 'python', 'rust', 'go'].filter(lang => lang.startsWith(value)) -* ) -* }) -* }, -* ({ language }) => ({ -* messages: [ -* { -* role: 'user' as const, -* content: { -* type: 'text' as const, -* text: `Review this ${language} code.` -* } -* } -* ] -* }) -* ); -* ``` -* -* @see {@linkcode server/mcp.McpServer.registerPrompt | McpServer.registerPrompt} for using completable schemas in prompt argument definitions -*/ -function completable(schema, complete) { - Object.defineProperty(schema, COMPLETABLE_SYMBOL, { - value: { complete }, - enumerable: false, - writable: false, - configurable: false - }); - return schema; -} -/** -* Checks if a schema is completable (has completion metadata). -*/ -function isCompletable(schema) { - return !!schema && typeof schema === "object" && COMPLETABLE_SYMBOL in schema; -} -/** -* Gets the completer callback from a completable schema, if it exists. -*/ -function getCompleter(schema) { - return schema[COMPLETABLE_SYMBOL]?.complete; -} - -//#endregion -//#region src/server/sseKeepAlive.ts -/** Default interval between SSE keep-alive comment frames. */ -const mcp_DXXb3Vv3_DEFAULT_SSE_KEEP_ALIVE_MS = 15e3; -const MAX_TIMER_DELAY_MS = (/* unused pure expression or super */ null && (2 ** 31 - 1)); -/** Arms an unref'd timer, or disables keep-alive for invalid delays. */ -function mcp_DXXb3Vv3_armSseKeepAlive(intervalMs, onTick) { - if (!Number.isFinite(intervalMs) || intervalMs < 1) return; - const timer = setInterval(onTick, Math.min(intervalMs, MAX_TIMER_DELAY_MS)); - timer.unref?.(); - return timer; -} - -//#endregion -//#region src/server/serverEventBus.ts -/** -* A `ServerEventBus` backed by an in-process listener set. -* -* `publish()` delivers synchronously to the live listener set (a listener -* unsubscribing itself mid-dispatch is safe; the entry's listen-router -* listeners never unsubscribe peers). A throwing listener does not stop -* delivery to the others. -*/ -var mcp_DXXb3Vv3_InMemoryServerEventBus = class { - _listeners = /* @__PURE__ */ new Set(); - /** - * @param onerror - Optional callback for errors thrown by listeners - * during dispatch. - */ - constructor(onerror) { - this.onerror = onerror; - } - publish(event) { - for (const listener of this._listeners) try { - listener(event); - } catch (error) { - this.onerror?.(error instanceof Error ? error : new Error(String(error))); - } - } - subscribe(listener) { - this._listeners.add(listener); - let live = true; - return () => { - if (!live) return; - live = false; - this._listeners.delete(listener); - }; - } - /** The number of currently registered listeners (test/introspection only — the routers track capacity via their own open-subscription set). */ - get listenerCount() { - return this._listeners.size; - } -}; -/** Build a {@linkcode ServerNotifier} over a bus. */ -function mcp_DXXb3Vv3_createServerNotifier(bus) { - return { - toolsChanged: () => bus.publish({ kind: "tools_list_changed" }), - promptsChanged: () => bus.publish({ kind: "prompts_list_changed" }), - resourcesChanged: () => bus.publish({ kind: "resources_list_changed" }), - resourceUpdated: (uri) => bus.publish({ - kind: "resource_updated", - uri - }) - }; -} -/** -* Whether a `subscriptions/listen` filter accepts a given change event. -* -* Pure: no I/O, no mutation. The filter governs ONLY the four -* subscription-gated change types — non-gated notifications never reach the -* bus and are not modeled here. -* -* `resource_updated` matches only when `resourceSubscriptions` is present and -* contains the event's URI exactly (per the spec: "for these resource URIs"). -*/ -function listenFilterAccepts(filter, event) { - switch (event.kind) { - case "tools_list_changed": return filter.toolsListChanged === true; - case "prompts_list_changed": return filter.promptsListChanged === true; - case "resources_list_changed": return filter.resourcesListChanged === true; - case "resource_updated": return filter.resourceSubscriptions !== void 0 && filter.resourceSubscriptions.includes(event.uri); - } -} -/** -* The honored subset of a requested filter: keeps only the fields the client -* explicitly opted in to (drops `false` and absent fields), narrowed against -* the server's declared capabilities when supplied. The serving entry sends -* this back in `notifications/subscriptions/acknowledged` so the ack reflects -* what the server can actually deliver. -* -* - `toolsListChanged` is honored only when `capabilities.tools.listChanged` -* is advertised; likewise `promptsListChanged` / `resourcesListChanged`. -* - `resourceSubscriptions` is honored only when -* `capabilities.resources.subscribe` is advertised. -* -* `capabilities` is optional on this pure helper for test convenience only — -* both wired routers REQUIRE capabilities at the call site (the HTTP router's -* `serve()` takes a required parameter; `StdioListenRouter.serve()` throws -* before `setServerCapabilities()` was called), so the fail-open -* `undefined → honor everything` branch is never reachable on a wired entry. -*/ -function honoredSubset(requested, capabilities) { - const honored = {}; - const allow = (bit) => capabilities === void 0 || bit === true; - if (requested.toolsListChanged === true && allow(capabilities?.tools?.listChanged)) honored.toolsListChanged = true; - if (requested.promptsListChanged === true && allow(capabilities?.prompts?.listChanged)) honored.promptsListChanged = true; - if (requested.resourcesListChanged === true && allow(capabilities?.resources?.listChanged)) honored.resourcesListChanged = true; - if (requested.resourceSubscriptions !== void 0 && requested.resourceSubscriptions.length > 0 && allow(capabilities?.resources?.subscribe)) honored.resourceSubscriptions = [...requested.resourceSubscriptions]; - return honored; -} -/** Map a {@linkcode ServerEvent} onto its wire notification `{method, params}`. */ -function serverEventToNotification(event) { - switch (event.kind) { - case "tools_list_changed": return { method: "notifications/tools/list_changed" }; - case "prompts_list_changed": return { method: "notifications/prompts/list_changed" }; - case "resources_list_changed": return { method: "notifications/resources/list_changed" }; - case "resource_updated": return { - method: "notifications/resources/updated", - params: { uri: event.uri } - }; - } -} - -//#endregion -//#region src/server/listenRouter.ts -/** Default capacity guard: refuse a new subscription when this many are already open. */ -const mcp_DXXb3Vv3_DEFAULT_MAX_SUBSCRIPTIONS = 1024; -function jsonRpcError(id, code, message) { - return Response.json({ - jsonrpc: "2.0", - error: { - code, - message - }, - id - }, { status: 200 }); -} -/** Stamp the subscription id onto a notification's `_meta`. Non-mutating. */ -function stampSubscriptionId(notification, subscriptionId) { - return { - method: notification.method, - params: { - ...notification.params, - _meta: { - ...notification.params?._meta, - [SUBSCRIPTION_ID_META_KEY]: subscriptionId - } - } - }; -} -/** -* Read the requested filter off a `subscriptions/listen` request body. -* Returns the validated filter, or `undefined` when `params.notifications` -* is absent or fails the schema (the caller answers `-32602` — the spec -* marks `notifications` REQUIRED on the listen request). -*/ -function parseListenFilter(message) { - const outcome = codecForVersion(MODERN_WIRE_REVISION).validateRequest("subscriptions/listen", message); - return outcome.ok ? outcome.value.params?.notifications : void 0; -} -function mcp_DXXb3Vv3_createListenRouter(options) { - const { bus, onerror } = options; - const maxSubscriptions = options.maxSubscriptions ?? mcp_DXXb3Vv3_DEFAULT_MAX_SUBSCRIPTIONS; - const keepAliveMs = options.keepAliveMs ?? mcp_DXXb3Vv3_DEFAULT_SSE_KEEP_ALIVE_MS; - const open = /* @__PURE__ */ new Set(); - function serve(message, signal, capabilities, serverInfo) { - if (open.size >= maxSubscriptions) { - onerror?.(/* @__PURE__ */ new Error(`subscriptions/listen refused: subscription limit reached (${maxSubscriptions})`)); - return jsonRpcError(message.id, -32603, "Subscription limit reached"); - } - const filter = parseListenFilter(message); - if (filter === void 0) return jsonRpcError(message.id, -32602, "Invalid params: 'notifications' is required and must be a valid SubscriptionFilter"); - const honored = honoredSubset(filter, capabilities); - const subscriptionId = message.id; - const encoder = new TextEncoder(); - let controller; - let closed = false; - let unsubscribe; - let keepAliveTimer; - let abortCleanup; - const writeFrame = (frame) => { - if (closed) return; - try { - controller.enqueue(encoder.encode(frame)); - } catch (error) { - onerror?.(error instanceof Error ? error : new Error(String(error))); - } - }; - const writeNotification = (method, params) => { - writeFrame(`event: message\ndata: ${JSON.stringify({ - jsonrpc: "2.0", - method, - params - })}\n\n`); - }; - const teardown = (graceful) => { - if (closed) return; - if (graceful) writeFrame(`event: message\ndata: ${JSON.stringify({ - jsonrpc: "2.0", - id: subscriptionId, - result: { - resultType: "complete", - _meta: { - [SUBSCRIPTION_ID_META_KEY]: subscriptionId, - [SERVER_INFO_META_KEY]: serverInfo - } - } - })}\n\n`); - closed = true; - try { - unsubscribe?.(); - } catch (error) { - onerror?.(error instanceof Error ? error : new Error(String(error))); - } - if (keepAliveTimer !== void 0) clearInterval(keepAliveTimer); - abortCleanup?.(); - open.delete(teardown); - try { - controller.close(); - } catch {} - }; - const readable = new ReadableStream({ - start(streamController) { - controller = streamController; - const ack = stampSubscriptionId({ - method: "notifications/subscriptions/acknowledged", - params: { notifications: honored } - }, subscriptionId); - writeNotification(ack.method, ack.params); - unsubscribe = bus.subscribe((event) => { - if (closed || !listenFilterAccepts(honored, event)) return; - const note = stampSubscriptionId(serverEventToNotification(event), subscriptionId); - writeNotification(note.method, note.params); - }); - keepAliveTimer = mcp_DXXb3Vv3_armSseKeepAlive(keepAliveMs, () => writeFrame(": keepalive\n\n")); - open.add(teardown); - }, - cancel() { - teardown(false); - } - }); - if (signal !== void 0) if (signal.aborted) teardown(false); - else { - const onAbort = () => teardown(false); - signal.addEventListener("abort", onAbort, { once: true }); - abortCleanup = () => signal.removeEventListener("abort", onAbort); - } - return new Response(readable, { - status: 200, - headers: { - "Content-Type": "text/event-stream", - "Cache-Control": "no-cache, no-transform", - Connection: "keep-alive", - "X-Accel-Buffering": "no" - } - }); - } - return { - serve, - closeAll() { - for (const teardown of open) teardown(true); - }, - get openCount() { - return open.size; - } - }; -} -const CHANGE_NOTIFICATION_METHODS = new Set([ - "notifications/tools/list_changed", - "notifications/prompts/list_changed", - "notifications/resources/list_changed", - "notifications/resources/updated" -]); -/** -* Per-connection listen state for the stdio entry. One instance is held by -* `serveStdio` for the connection lifetime; it routes inbound -* `subscriptions/listen` / `notifications/cancelled` and rewrites outbound -* change notifications onto the active subscriptions. No bus — the long-lived -* pinned instance's existing `send*ListChanged()` calls feed straight into -* `routeOutbound()`. -*/ -var mcp_DXXb3Vv3_StdioListenRouter = class { - /** Active subscriptions, keyed by the listen request's JSON-RPC id verbatim. */ - _subs = /* @__PURE__ */ new Map(); - /** - * The serving instance's declared capabilities. Filled in by the entry - * once the modern instance is constructed (the router is created before - * the instance exists), so the acknowledged filter is narrowed against - * what the server can actually deliver. - */ - _serverCapabilities; - /** - * The serving instance's identity, stamped onto the graceful-close - * results' `_meta` (the spec's `SubscriptionsListenResultMeta` extends - * `ResultMetaObject`). Handed over together with the capabilities. - */ - _serverInfo; - constructor(_maxSubscriptions = mcp_DXXb3Vv3_DEFAULT_MAX_SUBSCRIPTIONS, serverCapabilities, serverInfo) { - this._maxSubscriptions = _maxSubscriptions; - this._serverCapabilities = serverCapabilities; - this._serverInfo = serverInfo; - } - /** - * Record the serving instance's declared capabilities and identity once - * it has been constructed. Called by `serveStdio`'s connect path; - * subsequent `serve()` calls narrow the honored filter against the - * capabilities, and `teardownAll()` stamps the identity. - */ - setServerCapabilities(capabilities, serverInfo) { - this._serverCapabilities = capabilities; - if (serverInfo !== void 0) this._serverInfo = serverInfo; - } - /** Whether `id` is an active listen subscription on this connection. */ - has(id) { - return this._subs.has(id); - } - /** - * Serve one inbound `subscriptions/listen` request: registers the - * subscription and returns the stamped acknowledged notification (or, on - * capacity / params rejection, the in-band JSON-RPC error response). - * - * @throws when called before {@linkcode setServerCapabilities} (or the - * constructor) has supplied the serving instance's capabilities. Honoring a - * filter without knowing the server's advertised capabilities would fail - * open (deliver unadvertised types); the entry guarantees capabilities are - * set before any listen request is routed here. - */ - serve(message) { - if (this._serverCapabilities === void 0) throw new Error("StdioListenRouter.serve() called before setServerCapabilities(); refusing to honor a filter without capabilities"); - if (this._subs.size >= this._maxSubscriptions) return { - jsonrpc: "2.0", - id: message.id, - error: { - code: -32603, - message: "Subscription limit reached" - } - }; - const filter = parseListenFilter(message); - if (filter === void 0) return { - jsonrpc: "2.0", - id: message.id, - error: { - code: -32602, - message: "Invalid params: 'notifications' is required and must be a valid SubscriptionFilter" - } - }; - const honored = honoredSubset(filter, this._serverCapabilities); - this._subs.set(message.id, honored); - return stampSubscriptionId({ - method: "notifications/subscriptions/acknowledged", - params: { notifications: honored } - }, message.id); - } - /** - * Tear down one subscription (inbound `notifications/cancelled`). Returns - * `true` when a subscription was removed. After this call NOTHING further - * is delivered for that subscription id (the post-cancel hardening). - */ - cancel(id) { - return this._subs.delete(id); - } - /** - * Route an outbound notification through the active subscriptions. - * - * - For a subscription-gated change notification, returns one stamped copy - * per subscription that opted in to it (an empty array means it is - * dropped — the modern era never delivers an un-requested change type). - * - For any other outbound message, returns `'passthrough'` (the entry - * forwards it as-is). - */ - routeOutbound(message) { - if (!CHANGE_NOTIFICATION_METHODS.has(message.method)) return "passthrough"; - const uriParam = message.params?.["uri"]; - const uri = typeof uriParam === "string" ? uriParam : void 0; - const event = notificationToServerEvent(message.method, uri); - const out = []; - for (const [subscriptionId, filter] of this._subs) if (listenFilterAccepts(filter, event)) out.push(stampSubscriptionId({ - method: message.method, - params: message.params ?? {} - }, subscriptionId)); - return out; - } - /** - * Server-side graceful teardown of every active subscription: returns the - * empty `subscriptions/listen` JSON-RPC result for each subscription id — - * the spec's graceful-close signal, `_meta` carrying the subscription id - * and the serving instance's identity — for the entry to emit before - * closing the wire. Clears the set so nothing further is delivered. - */ - teardownAll() { - const out = []; - for (const id of this._subs.keys()) out.push({ - jsonrpc: "2.0", - id, - result: { - resultType: "complete", - _meta: { - [SUBSCRIPTION_ID_META_KEY]: id, - ...this._serverInfo !== void 0 && { [SERVER_INFO_META_KEY]: this._serverInfo } - } - } - }); - this._subs.clear(); - return out; - } -}; -function notificationToServerEvent(method, uri) { - switch (method) { - case "notifications/tools/list_changed": return { kind: "tools_list_changed" }; - case "notifications/prompts/list_changed": return { kind: "prompts_list_changed" }; - case "notifications/resources/list_changed": return { kind: "resources_list_changed" }; - default: return { - kind: "resource_updated", - uri: uri ?? "" - }; - } -} - -//#endregion -//#region src/server/legacyInputRequiredShim.ts -/** -* Default handler re-entries per originating request — tighter than the -* client driver's 10 because the shim holds a live wire request open. -*/ -const DEFAULT_LEGACY_SHIM_MAX_ROUNDS = 8; -/** Default per-leg timeout: legs are human-paced, so the 60s protocol default is wrong. */ -const DEFAULT_LEGACY_SHIM_ROUND_TIMEOUT_MS = 6e5; -/** Resolves and validates `ServerOptions.inputRequired`, failing loudly at construction time. */ -function resolveLegacyShimOptions(options) { - if (options?.maxRounds !== void 0 && (!Number.isInteger(options.maxRounds) || options.maxRounds < 1)) throw new RangeError(`inputRequired.maxRounds must be a positive integer (got ${options.maxRounds})`); - if (options?.roundTimeoutMs !== void 0 && (!Number.isFinite(options.roundTimeoutMs) || options.roundTimeoutMs <= 0)) throw new RangeError(`inputRequired.roundTimeoutMs must be a positive number (got ${options.roundTimeoutMs})`); - return { - maxRounds: options?.maxRounds ?? DEFAULT_LEGACY_SHIM_MAX_ROUNDS, - roundTimeoutMs: options?.roundTimeoutMs ?? DEFAULT_LEGACY_SHIM_ROUND_TIMEOUT_MS, - legacyShim: options?.legacyShim ?? true - }; -} -/** -* Validates one `inputRequests` entry: malformed or unknown kinds are server -* bugs and fail loudly on both eras. Shared by the modern seam's capability -* check and the shim's gate. -*/ -function coerceEmbeddedInputRequest(method, key, entry) { - if (entry === null || typeof entry !== "object" || typeof entry.method !== "string") throw new src_CX2iR2pK_ProtocolError(src_CX2iR2pK_ProtocolErrorCode.InternalError, `Handler for ${method} returned an invalid input request '${key}': each inputRequests entry must be an embedded elicitation/create, sampling/createMessage, or roots/list request`); - const embedded = entry; - const required = requiredClientCapabilitiesForInputRequest(embedded); - if (required === void 0) throw new src_CX2iR2pK_ProtocolError(src_CX2iR2pK_ProtocolErrorCode.InternalError, `Handler for ${method} returned an input request '${key}' of kind '${embedded.method}', which is not an embedded request the 2026-07-28 revision defines`); - return { - embedded, - required - }; -} -/** -* The 2025-11-25 URL-mode wire shape requires an `elicitationId`; the 2026 -* in-band shape has none, so URL legs mint one (CSPRNG-backed, with a -* getRandomValues fallback for runtimes without `randomUUID`). -*/ -function syntheticElicitationId() { - const webCrypto = globalThis.crypto; - if (webCrypto?.randomUUID !== void 0) return webCrypto.randomUUID(); - const bytes = new Uint8Array(16); - webCrypto.getRandomValues(bytes); - bytes[6] = bytes[6] & 15 | 64; - bytes[8] = bytes[8] & 63 | 128; - const hex = [...bytes].map((byte) => byte.toString(16).padStart(2, "0")).join(""); - return `${hex.slice(0, 8)}-${hex.slice(8, 12)}-${hex.slice(12, 16)}-${hex.slice(16, 20)}-${hex.slice(20)}`; -} -/** Per-family surfacing: tools/call → isError result (the 2025 idiom); prompts/resources → JSON-RPC error. */ -function legacyShimFailure(method, message) { - if (method === "tools/call") return { - content: [{ - type: "text", - text: message - }], - isError: true - }; - throw new src_CX2iR2pK_ProtocolError(src_CX2iR2pK_ProtocolErrorCode.InternalError, message); -} -/** The fulfilment loop — see the module doc for the contract. */ -var LegacyInputRequiredShim = class { - constructor(_host) { - this._host = _host; - } - async fulfill(method, handler, request, ctx, firstResult) { - const { maxRounds, roundTimeoutMs } = this._host; - const outerSignal = ctx.mcpReq.signal; - let current = firstResult; - let round = 0; - while (true) { - round += 1; - if (round > maxRounds) return legacyShimFailure(method, inputRequiredRoundsExceededMessage(method, maxRounds)); - const inputRequests = current.inputRequests; - const hasInputRequests = inputRequests != null && Object.keys(inputRequests).length > 0; - const requestState = typeof current.requestState === "string" ? current.requestState : void 0; - if (!hasInputRequests && requestState === void 0) throw new src_CX2iR2pK_ProtocolError(src_CX2iR2pK_ProtocolErrorCode.InternalError, `Handler for ${method} returned an input-required result with neither inputRequests nor requestState (every InputRequiredResult must include at least one of the two)`); - let responses; - if (hasInputRequests) { - const declared = this._host.resolvedClientCapabilities(ctx); - const coerced = []; - for (const [key, entry] of Object.entries(inputRequests)) { - const { embedded, required } = coerceEmbeddedInputRequest(method, key, entry); - if (embedded.method !== "roots/list" && embedded.params === void 0) throw new src_CX2iR2pK_ProtocolError(src_CX2iR2pK_ProtocolErrorCode.InternalError, `Handler for ${method} returned an input request '${key}' of kind '${embedded.method}' without params`); - if (src_CX2iR2pK_missingClientCapabilities(required, declared) !== void 0) return legacyShimFailure(method, `Cannot request input '${key}' (${embedded.method}): the client on this 2025-era connection did not declare the required capability${declared === void 0 ? " (no client capabilities are available on this connection — per-request legacy serving cannot receive server-to-client requests)" : ""}`); - coerced.push([key, embedded]); - } - const roundAbort = linkedRoundAbort(outerSignal); - try { - const legOptions = { - relatedRequestId: ctx.mcpReq.id, - timeout: roundTimeoutMs, - resetTimeoutOnProgress: true, - onprogress: () => {}, - signal: roundAbort.signal - }; - const fulfilled = await Promise.all(coerced.map(async ([key, embedded]) => { - try { - return [key, await this._dispatchLeg(embedded, legOptions)]; - } catch (error) { - roundAbort.abort(error); - throw error; - } - })); - responses = Object.fromEntries(fulfilled); - } catch (error) { - if (outerSignal.aborted) throw error; - return legacyShimFailure(method, `Fulfilling input required by '${method}' failed: ${error instanceof Error ? error.message : String(error)}`); - } finally { - roundAbort.dispose(); - } - } else await sleep((/* inlined export .C */250), outerSignal); - let ctxNext = { - ...ctx, - mcpReq: { - ...ctx.mcpReq, - inputResponses: responses, - droppedInputResponseKeys: void 0, - requestState: requestStateAccessor(requestState) - } - }; - if (requestState !== void 0) { - const decoded = await this._host.verifyRequestState(requestState, ctxNext, method); - if (decoded !== void 0) ctxNext = withRequestStateValue(ctxNext, decoded); - } - const next = await handler(request, ctxNext); - if (!isInputRequiredResult(next)) return next; - current = next; - } - } - /** Routes one embedded request through the host's existing 2025-era senders (gate already ran). */ - async _dispatchLeg(embedded, options) { - switch (embedded.method) { - case "elicitation/create": { - let params = embedded.params; - if (params.mode === "url" && params.elicitationId === void 0) params = { - ...params, - elicitationId: syntheticElicitationId() - }; - return await this._host.sendElicitation(params, options); - } - case "sampling/createMessage": return await this._host.sendSampling(embedded.params, options); - case "roots/list": return await this._host.listRoots(embedded.params, options); - } - } -}; - -//#endregion -//#region src/server/server.ts -/** -* The request methods whose 2026-07-28 result vocabulary includes -* `input_required` (the multi round-trip methods). Returning an -* input-required result from any other handler is a server bug. -*/ -const INPUT_REQUIRED_CAPABLE_METHODS = new Set([ - "tools/call", - "prompts/get", - "resources/read" -]); -let writeClientIdentity; -let installDiscoverHandler; -let readServerIdentity; -/** -* Package-internal: backfills the connection-scoped client-identity fields of a -* per-request server instance from the request's validated `_meta` envelope, so the -* (deprecated) {@linkcode Server.getClientCapabilities} / {@linkcode Server.getClientVersion} -* accessors keep answering on instances that never see an `initialize` handshake. -* Not public API. -*/ -function mcp_DXXb3Vv3_seedClientIdentityFromEnvelope(server, identity) { - writeClientIdentity(server, identity); -} -/** -* Package-internal: installs the modern-only `server/discover` handler on an instance -* the HTTP entry has marked as serving the 2026-07-28 era, and makes sure the modern -* revisions the entry serves appear in the instance's supported-versions list (so the -* discover advertisement and version-mismatch errors name them). Idempotent. -* Hand-constructed instances are unaffected: nothing else calls this, so they keep -* answering `-32601` unless their own supported-versions list opts into a modern -* revision. Not public API. -*/ -function mcp_DXXb3Vv3_installModernOnlyHandlers(server, servedModernVersions) { - installDiscoverHandler(server, servedModernVersions); -} -/** -* Package-internal: the instance's implementation identity, for the serving -* entries to stamp onto entry-built results (the `subscriptions/listen` -* graceful-close result — built outside the encode seam, but the spec's -* `SubscriptionsListenResultMeta` extends `ResultMetaObject`, so it carries -* the serverInfo SHOULD like every other result). Not public API. -*/ -function mcp_DXXb3Vv3_serverIdentityOf(server) { - return readServerIdentity(server); -} -/** -* An MCP server on top of a pluggable transport. -* -* This server will automatically respond to the initialization flow as initiated from the client. -* -* @deprecated Use {@linkcode server/mcp.McpServer | McpServer} instead for the high-level API. Only use `Server` for advanced use cases. -*/ -var Server = class extends Protocol { - _clientCapabilities; - _clientVersion; - static { - writeClientIdentity = (server, identity) => { - if (identity.clientCapabilities !== void 0) server._clientCapabilities = identity.clientCapabilities; - if (identity.clientInfo !== void 0) server._clientVersion = identity.clientInfo; - }; - installDiscoverHandler = (server, servedModernVersions) => { - const missing = servedModernVersions.filter((version) => !server._supportedProtocolVersions.includes(version)); - if (missing.length > 0) server._supportedProtocolVersions = [...server._supportedProtocolVersions, ...missing]; - server.setRequestHandler("server/discover", () => server._ondiscover()); - }; - readServerIdentity = (server) => server._serverInfo; - } - _capabilities; - _instructions; - _jsonSchemaValidator; - _cacheHints; - _requestStateVerify; - _inputRequiredServing; - _legacyShim; - /** Lazily-built legacy shim; the loop lives in legacyInputRequiredShim.ts behind a narrow host contract. */ - _legacyInputRequiredShim() { - return this._legacyShim ??= new LegacyInputRequiredShim({ - maxRounds: this._inputRequiredServing.maxRounds, - roundTimeoutMs: this._inputRequiredServing.roundTimeoutMs, - resolvedClientCapabilities: (ctx) => this._inputRequestCapabilityView(ctx), - verifyRequestState: (state, ctx, method) => this._verifyRequestState(state, ctx, method), - sendElicitation: (params, options) => this._sendElicitationLeg(params, options, { validateAcceptedContent: false }), - sendSampling: (params, options) => this.createMessage(params, options), - listRoots: (params, options) => this.listRoots(params, options) - }); - } - /** - * Callback for when initialization has fully completed (i.e., the client has sent an `notifications/initialized` notification). - */ - oninitialized; - /** - * Initializes this server with the given name and version information. - */ - constructor(_serverInfo, options) { - super(options); - this._serverInfo = _serverInfo; - this._capabilities = options?.capabilities ? { ...options.capabilities } : {}; - this._instructions = options?.instructions; - this._jsonSchemaValidator = options?.jsonSchemaValidator ?? new AjvJsonSchemaValidator(); - this._requestStateVerify = options?.requestState?.verify; - this._inputRequiredServing = resolveLegacyShimOptions(options?.inputRequired); - if (options?.cacheHints !== void 0) { - for (const [operation, hint] of Object.entries(options.cacheHints)) if (hint !== void 0) assertValidCacheHint(hint, `cacheHints['${operation}']`); - this._cacheHints = options.cacheHints; - } - this.setRequestHandler("initialize", (request) => this._oninitialize(request)); - this.setNotificationHandler("notifications/initialized", () => this.oninitialized?.()); - if (modernProtocolVersions(this._supportedProtocolVersions).length > 0) this.setRequestHandler("server/discover", () => this._ondiscover()); - if (this._capabilities.logging) this._registerLoggingHandler(); - } - /** - * Registers the built-in `logging/setLevel` request handler. - * - * @deprecated Deprecated as of protocol version 2026-07-28 (SEP-2577). - * Remains functional during the deprecation window (at least twelve months). - * Migrate to stderr logging (STDIO servers) or OpenTelemetry. - */ - _registerLoggingHandler() { - this.setRequestHandler("logging/setLevel", async (request, ctx) => { - const transportSessionId = ctx.sessionId || ctx.http?.req?.headers.get("mcp-session-id") || void 0; - const { level } = request.params; - const parseResult = parseSchema(LoggingLevelSchema, level); - if (parseResult.success) this._loggingLevels.set(transportSessionId, parseResult.data); - return {}; - }); - } - buildContext(ctx, transportInfo) { - const hasHttpInfo = ctx.http || transportInfo?.request || transportInfo?.closeSSEStream || transportInfo?.closeStandaloneSSEStream; - return { - ...ctx, - mcpReq: { - ...ctx.mcpReq, - log: (level, data, logger) => { - if (!this._capabilities.logging) return Promise.resolve(); - let threshold; - if (this._servedModernEra()) { - threshold = ctx.mcpReq.envelope?.[LOG_LEVEL_META_KEY]; - if (threshold === void 0) return Promise.resolve(); - } else threshold = this._loggingLevels.get(ctx.sessionId) ?? this._loggingLevels.get(void 0); - if (threshold !== void 0 && this.LOG_LEVEL_SEVERITY.get(level) < this.LOG_LEVEL_SEVERITY.get(threshold)) return Promise.resolve(); - return ctx.mcpReq.notify({ - method: "notifications/message", - params: { - level, - data, - logger - } - }); - }, - elicitInput: (params, options) => this.elicitInput(params, options), - requestSampling: (params, options) => this.createMessage(params, options) - }, - http: hasHttpInfo ? { - ...ctx.http, - req: transportInfo?.request, - closeSSE: transportInfo?.closeSSEStream, - closeStandaloneSSE: transportInfo?.closeStandaloneSSEStream - } : void 0 - }; - } - _loggingLevels = /* @__PURE__ */ new Map(); - LOG_LEVEL_SEVERITY = new Map(LoggingLevelSchema.options.map((level, index) => [level, index])); - isMessageIgnored = (level, sessionId) => { - const currentLevel = this._loggingLevels.get(sessionId); - return currentLevel ? this.LOG_LEVEL_SEVERITY.get(level) < this.LOG_LEVEL_SEVERITY.get(currentLevel) : false; - }; - /** - * Registers new capabilities. This can only be called before connecting to a transport. - * - * The new capabilities will be merged with any existing capabilities previously given (e.g., at initialization). - */ - registerCapabilities(capabilities) { - if (this.transport) throw new src_CX2iR2pK_SdkError(src_CX2iR2pK_SdkErrorCode.AlreadyConnected, "Cannot register capabilities after connecting to transport"); - const hadLogging = !!this._capabilities.logging; - this._capabilities = mergeCapabilities(this._capabilities, capabilities); - if (!hadLogging && this._capabilities.logging) this._registerLoggingHandler(); - } - /** - * Enforces server-side validation for `tools/call` results regardless of how the - * handler was registered, attaches the configured per-operation cache hint - * (when one exists) so the 2026-07-28 encode seam can fill `ttlMs`/`cacheScope` - * for results that do not provide their own, and owns the multi-round-trip - * seam: on the methods whose 2026-07-28 result vocabulary includes - * `input_required` (`tools/call`, `prompts/get`, `resources/read`) an - * input-required return skips result-schema validation and is checked - * against the served era, the at-least-one rule, and the request's own - * declared client capabilities; on every other method an input-required - * return is a server bug and fails loudly. The hint rides a symbol-keyed - * property that is never serialized, so 2025-era responses are unaffected. - */ - _wrapHandler(method, handler) { - if (method !== "tools/call") { - const cacheHint = this._cacheHints?.[method]; - const isInputRequiredCapable = INPUT_REQUIRED_CAPABLE_METHODS.has(method); - if (cacheHint === void 0 && !isInputRequiredCapable) return async (request, ctx) => { - const result = await handler(request, ctx); - if (isInputRequiredResult(result)) throw new src_CX2iR2pK_ProtocolError(src_CX2iR2pK_ProtocolErrorCode.InternalError, `Handler for ${method} returned an input-required result, but only tools/call, prompts/get and resources/read support input_required (protocol revision 2026-07-28)`); - return result; - }; - return async (request, ctx) => { - const result = isInputRequiredCapable ? await this._invokeInputRequiredCapableHandler(method, handler, request, ctx) : await handler(request, ctx); - if (isInputRequiredResult(result)) { - if (!isInputRequiredCapable) throw new src_CX2iR2pK_ProtocolError(src_CX2iR2pK_ProtocolErrorCode.InternalError, `Handler for ${method} returned an input-required result, but only tools/call, prompts/get and resources/read support input_required (protocol revision 2026-07-28)`); - return result; - } - return cacheHint === void 0 ? result : attachCacheHintFallback(result, cacheHint); - }; - } - return async (request, ctx) => { - const codec = src_CX2iR2pK_codecForVersion(this._negotiatedProtocolVersion); - const validatedRequest = codec.validateRequest("tools/call", request); - if (!validatedRequest.ok) throw new src_CX2iR2pK_ProtocolError(validatedRequest.reason === "not-in-era" ? src_CX2iR2pK_ProtocolErrorCode.InternalError : src_CX2iR2pK_ProtocolErrorCode.InvalidParams, validatedRequest.reason === "not-in-era" ? "No wire schema for tools/call in the resolved era" : `Invalid tools/call request: ${validatedRequest.message}`); - const result = await this._invokeInputRequiredCapableHandler("tools/call", handler, request, ctx); - if (isInputRequiredResult(result)) return result; - const normalizedResult = normalizeContentlessToolResult(result); - const validationResult = codec.validateResult("tools/call", normalizedResult); - if (!validationResult.ok) throw new src_CX2iR2pK_ProtocolError(validationResult.reason === "not-in-era" ? src_CX2iR2pK_ProtocolErrorCode.InternalError : src_CX2iR2pK_ProtocolErrorCode.InvalidParams, validationResult.reason === "not-in-era" ? "No wire schema for tools/call in the resolved era" : `Invalid tools/call result: ${validationResult.message}`); - return validationResult.value; - }; - } - /** - * Whether this instance is bound to a 2026-07-28-or-later protocol - * revision. Era is instance state — a serving entry (`createMcpHandler`, - * `serveStdio`) marks the instance modern at construction; a 2025-era - * `initialize` handshake binds it legacy. The multi-round-trip seam reads - * this directly: there is no per-request era consult. - */ - _servedModernEra() { - return this._negotiatedProtocolVersion !== void 0 && isModernProtocolVersion(this._negotiatedProtocolVersion); - } - /** - * Invokes a handler for one of the multi-round-trip methods and applies - * the input-required seam: - * - * - a `UrlElicitationRequiredError` (or any 2025-style server→client - * request idiom) escaping the handler on a request served on the - * 2026-07-28 era fails LOUDLY with a clear steer to - * `inputRequired.elicitUrl(...)` — the `-32042` error never reaches the - * 2026-07-28 wire and the throw is not silently converted. Requests - * served on the 2025 era keep today's `-32042` behavior byte-exact (the - * error is rethrown unchanged). - * - an input-required RETURN toward a 2026-07-28 request must satisfy - * the at-least-one rule, and every embedded request must be covered by - * the capabilities declared on the request's envelope (violations - * answer the typed `-32021` error). Toward a 2025-era request the - * return is fulfilled by the default-on legacy shim, whose own gate - * consults the initialize-declared capabilities and surfaces - * violations per family; `inputRequired.legacyShim: false` restores - * the pre-shim loud failure. - */ - async _invokeInputRequiredCapableHandler(method, handler, request, ctx) { - const servedModern = this._servedModernEra(); - const rawRequestState = ctx.mcpReq.requestState(); - if (rawRequestState !== void 0 && typeof rawRequestState !== "string") throw new src_CX2iR2pK_ProtocolError(src_CX2iR2pK_ProtocolErrorCode.InvalidParams, "Invalid or expired requestState", { reason: "invalid_request_state" }); - let ctxForHandler = ctx; - if (typeof rawRequestState === "string") { - const decoded = await this._verifyRequestState(rawRequestState, ctx, method); - if (decoded !== void 0) ctxForHandler = withRequestStateValue(ctx, decoded); - } - let result; - try { - result = await handler(request, ctxForHandler); - } catch (error) { - if (error instanceof src_CX2iR2pK_ProtocolError && error.code === src_CX2iR2pK_ProtocolErrorCode.UrlElicitationRequired) { - if (!servedModern) throw error; - throw new src_CX2iR2pK_ProtocolError(src_CX2iR2pK_ProtocolErrorCode.InternalError, `URL elicitation cannot be signalled by throwing UrlElicitationRequiredError on protocol revision ${this._negotiatedProtocolVersion}: return inputRequired({ inputRequests: { …: inputRequired.elicitUrl(...) } }) from the handler instead. The urlElicitationRequired error (-32042) of earlier revisions is not available on this revision.`); - } - throw error; - } - if (!isInputRequiredResult(result)) return result; - if (!servedModern) { - if (!this._inputRequiredServing.legacyShim) throw new src_CX2iR2pK_ProtocolError(src_CX2iR2pK_ProtocolErrorCode.InternalError, `Handler for ${method} returned an input-required result, but this request is served on protocol revision ${this._negotiatedProtocolVersion ?? LATEST_PROTOCOL_VERSION}, which has no input_required vocabulary`); - return await this._legacyInputRequiredShim().fulfill(method, handler, request, ctxForHandler, result); - } - const inputRequests = result.inputRequests; - const hasInputRequests = inputRequests != null && Object.keys(inputRequests).length > 0; - const hasRequestState = typeof result.requestState === "string"; - if (!hasInputRequests && !hasRequestState) throw new src_CX2iR2pK_ProtocolError(src_CX2iR2pK_ProtocolErrorCode.InternalError, `Handler for ${method} returned an input-required result with neither inputRequests nor requestState (every InputRequiredResult must include at least one of the two)`); - if (hasInputRequests) { - const declared = this._inputRequestCapabilityView(ctx); - for (const [key, entry] of Object.entries(inputRequests)) { - const { embedded, required } = coerceEmbeddedInputRequest(method, key, entry); - const missing = src_CX2iR2pK_missingClientCapabilities(required, declared); - if (missing !== void 0) throw new src_CX2iR2pK_MissingRequiredClientCapabilityError({ requiredCapabilities: missing }, `Cannot request input '${key}' (${embedded.method}): the request's client capabilities do not declare the required capability`); - } - } - return result; - } - /** - * Runs the configured `requestState.verify` hook and returns its - * resolved value (`undefined` when unconfigured or the hook returns - * nothing). Deny-on-error: any hook failure answers the frozen `-32602`; - * the reason goes to `onerror` only. - */ - async _verifyRequestState(state, ctx, method) { - if (this._requestStateVerify === void 0) return; - try { - return await this._requestStateVerify(state, ctx); - } catch (error) { - this.onerror?.(/* @__PURE__ */ new Error(`requestState verification rejected ${method}: ${error instanceof Error ? error.message : String(error)}`)); - throw new src_CX2iR2pK_ProtocolError(src_CX2iR2pK_ProtocolErrorCode.InvalidParams, "Invalid or expired requestState", { reason: "invalid_request_state" }); - } - } - /** - * The per-request resolved client-capabilities view: the request's own - * `_meta` envelope on the 2026 era; the `initialize`-declared state on a - * 2025-era connection. Per-request instances that never saw an - * initialize (stateless legacy) hold nothing, so gates refuse there. - */ - _inputRequestCapabilityView(ctx) { - return this._servedModernEra() ? ctx.mcpReq.envelope?.[auth_CUe6YdwF_CLIENT_CAPABILITIES_META_KEY] : this._clientCapabilities; - } - /** - * Guard for the push-style server→client request APIs ({@linkcode createMessage}, - * {@linkcode elicitInput}, {@linkcode listRoots}, {@linkcode ping}) on a - * modern-era instance: the 2026-07-28 revision has no server→client request - * channel, so the call fails before any wire traffic with a typed error - * whose message steers to `inputRequired(...)`. The base era gate would - * also reject it; this guard runs first to carry the steer. - */ - _assertPushApiInServedEra(method) { - if (this._servedModernEra()) throw new src_CX2iR2pK_SdkError(src_CX2iR2pK_SdkErrorCode.MethodNotSupportedByProtocolVersion, `Server-to-client requests are not available on protocol revision ${this._negotiatedProtocolVersion}: '${method}' cannot be sent while serving a request on that revision. Return inputRequired({ ... }) from the handler instead — the client fulfils the embedded requests and retries the original request (multi round-trip requests).`, { - method, - era: "2026-07-28" - }); - } - assertCapabilityForMethod(method) { - switch (method) { - case "sampling/createMessage": - if (!this._clientCapabilities?.sampling) throw new src_CX2iR2pK_SdkError(src_CX2iR2pK_SdkErrorCode.CapabilityNotSupported, `Client does not support sampling (required for ${method})`); - break; - case "elicitation/create": - if (!this._clientCapabilities?.elicitation) throw new src_CX2iR2pK_SdkError(src_CX2iR2pK_SdkErrorCode.CapabilityNotSupported, `Client does not support elicitation (required for ${method})`); - break; - case "roots/list": - if (!this._clientCapabilities?.roots) throw new src_CX2iR2pK_SdkError(src_CX2iR2pK_SdkErrorCode.CapabilityNotSupported, `Client does not support listing roots (required for ${method})`); - break; - case "ping": break; - } - } - assertNotificationCapability(method) { - switch (method) { - case "notifications/message": - if (!this._capabilities.logging) throw new src_CX2iR2pK_SdkError(src_CX2iR2pK_SdkErrorCode.CapabilityNotSupported, `Server does not support logging (required for ${method})`); - break; - case "notifications/resources/updated": - case "notifications/resources/list_changed": - if (!this._capabilities.resources) throw new src_CX2iR2pK_SdkError(src_CX2iR2pK_SdkErrorCode.CapabilityNotSupported, `Server does not support notifying about resources (required for ${method})`); - break; - case "notifications/tools/list_changed": - if (!this._capabilities.tools) throw new src_CX2iR2pK_SdkError(src_CX2iR2pK_SdkErrorCode.CapabilityNotSupported, `Server does not support notifying of tool list changes (required for ${method})`); - break; - case "notifications/prompts/list_changed": - if (!this._capabilities.prompts) throw new src_CX2iR2pK_SdkError(src_CX2iR2pK_SdkErrorCode.CapabilityNotSupported, `Server does not support notifying of prompt list changes (required for ${method})`); - break; - case "notifications/elicitation/complete": - if (!this._clientCapabilities?.elicitation?.url) throw new src_CX2iR2pK_SdkError(src_CX2iR2pK_SdkErrorCode.CapabilityNotSupported, `Client does not support URL elicitation (required for ${method})`); - break; - case "notifications/cancelled": break; - case "notifications/progress": break; - } - } - assertRequestHandlerCapability(method) { - switch (method) { - case "completion/complete": - if (!this._capabilities.completions) throw new src_CX2iR2pK_SdkError(src_CX2iR2pK_SdkErrorCode.CapabilityNotSupported, `Server does not support completions (required for ${method})`); - break; - case "logging/setLevel": - if (!this._capabilities.logging) throw new src_CX2iR2pK_SdkError(src_CX2iR2pK_SdkErrorCode.CapabilityNotSupported, `Server does not support logging (required for ${method})`); - break; - case "prompts/get": - case "prompts/list": - if (!this._capabilities.prompts) throw new src_CX2iR2pK_SdkError(src_CX2iR2pK_SdkErrorCode.CapabilityNotSupported, `Server does not support prompts (required for ${method})`); - break; - case "resources/list": - case "resources/templates/list": - case "resources/read": - if (!this._capabilities.resources) throw new src_CX2iR2pK_SdkError(src_CX2iR2pK_SdkErrorCode.CapabilityNotSupported, `Server does not support resources (required for ${method})`); - break; - case "tools/call": - case "tools/list": - if (!this._capabilities.tools) throw new src_CX2iR2pK_SdkError(src_CX2iR2pK_SdkErrorCode.CapabilityNotSupported, `Server does not support tools (required for ${method})`); - break; - case "ping": - case "initialize": break; - } - } - async _oninitialize(request) { - const requestedVersion = request.params.protocolVersion; - this._clientCapabilities = request.params.capabilities; - this._clientVersion = request.params.clientInfo; - const legacyVersions = legacyProtocolVersions(this._supportedProtocolVersions); - const protocolVersion = legacyVersions.includes(requestedVersion) ? requestedVersion : legacyVersions[0] ?? LATEST_PROTOCOL_VERSION; - this._negotiatedProtocolVersion = protocolVersion; - this.transport?.setProtocolVersion?.(protocolVersion); - return { - protocolVersion, - capabilities: this.getCapabilities(), - serverInfo: this._serverInfo, - ...this._instructions && { instructions: this._instructions } - }; - } - /** - * Answers `server/discover` (protocol revision 2026-07-28). `supportedVersions` - * lists only modern revisions (2025-era versions are negotiated via `initialize`); - * the capabilities are advertised as-is, listChanged/subscribe bits included - * (see {@linkcode discoverAdvertisedCapabilities}). - */ - _ondiscover() { - return { - supportedVersions: modernProtocolVersions(this._supportedProtocolVersions), - capabilities: discoverAdvertisedCapabilities(this.getCapabilities()), - ...this._instructions && { instructions: this._instructions } - }; - } - /** - * The identity the 2026-era encode seam stamps into every outbound - * result's `_meta` under `io.modelcontextprotocol/serverInfo` (spec PR - * #3002: servers SHOULD identify themselves on every response). - */ - _outboundServerInfo() { - return this._serverInfo; - } - /** - * After initialization has completed, this will be populated with the client's reported capabilities. - * - * @deprecated Read client identity from the per-request handler context instead: on - * 2026-07-28 (per-request envelope) requests `ctx.mcpReq.envelope` carries the client's - * declared capabilities, while on 2025-era connections this accessor keeps returning the - * `initialize`-scoped value. The accessor remains functional — instances serving the - * 2026-07-28 era are backfilled per request from the validated envelope. - */ - getClientCapabilities() { - return this._clientCapabilities; - } - /** - * After initialization has completed, this will be populated with information about the client's name and version. - * - * @deprecated Read client identity from the per-request handler context instead: on - * 2026-07-28 (per-request envelope) requests `ctx.mcpReq.envelope` carries the client's - * name and version, while on 2025-era connections this accessor keeps returning the - * `initialize`-scoped value. The accessor remains functional — instances serving the - * 2026-07-28 era are backfilled per request from the validated envelope. - */ - getClientVersion() { - return this._clientVersion; - } - /** - * After initialization has completed, this will be populated with the protocol version negotiated - * with the client (the version the server responded with during the initialize handshake), or - * `undefined` before initialization. - * - * @deprecated Read the protocol revision from the per-request handler context instead: on - * 2026-07-28 (per-request envelope) requests `ctx.mcpReq.envelope` names the revision the - * request was sent for, while on 2025-era connections this accessor keeps returning the - * `initialize`-negotiated version. The accessor remains functional — instances serving the - * 2026-07-28 era report that revision. - */ - getNegotiatedProtocolVersion() { - return this._negotiatedProtocolVersion; - } - /** - * Project a `tools/call` result through this instance's negotiated wire - * codec — the era-agnostic SEP-2106 §4.3 TextContent auto-append, plus on - * the 2025 era the `{result:…}` wrap when `structuredContent` is a - * non-object value or the advertised `outputSchema` had a non-object root. - * Identity for object-shaped `structuredContent` on the 2026 era. - * - * `McpServer`'s built-in `tools/call` handler routes through this method. - * Low-level `setRequestHandler('tools/call', …)` authors call it - * themselves so the projection lives in one place (the codec) and the - * server-side handler stays era-blind. - * - * This is the only codec function exposed on `Server` — the full - * `WireCodec` is intentionally not part of the public surface. - */ - projectCallToolResult(result, advertisedOutputSchema) { - return this._wireCodec().projectCallToolResult(result, advertisedOutputSchema); - } - /** - * Returns the current server capabilities. - */ - getCapabilities() { - return this._capabilities; - } - /** - * Sends a `ping` request to the connected client. - * - * @deprecated The 2026-07-28 protocol removed ping; it throws on a 2026-07-28-era instance. - * If your factory serves both eras, this only works on the legacy path. - */ - async ping() { - this._assertPushApiInServedEra("ping"); - return this.request({ method: "ping" }); - } - async createMessage(params, options) { - this._assertPushApiInServedEra("sampling/createMessage"); - if ((params.tools || params.toolChoice) && !this._clientCapabilities?.sampling?.tools) throw new src_CX2iR2pK_SdkError(src_CX2iR2pK_SdkErrorCode.CapabilityNotSupported, "Client does not support sampling tools capability."); - if (params.messages.length > 0) { - const lastMessage = params.messages.at(-1); - const lastContent = Array.isArray(lastMessage.content) ? lastMessage.content : [lastMessage.content]; - const hasToolResults = lastContent.some((c) => c.type === "tool_result"); - const previousMessage = params.messages.length > 1 ? params.messages.at(-2) : void 0; - const previousContent = previousMessage ? Array.isArray(previousMessage.content) ? previousMessage.content : [previousMessage.content] : []; - const hasPreviousToolUse = previousContent.some((c) => c.type === "tool_use"); - if (hasToolResults) { - if (lastContent.some((c) => c.type !== "tool_result")) throw new src_CX2iR2pK_ProtocolError(src_CX2iR2pK_ProtocolErrorCode.InvalidParams, "The last message must contain only tool_result content if any is present"); - if (!hasPreviousToolUse) throw new src_CX2iR2pK_ProtocolError(src_CX2iR2pK_ProtocolErrorCode.InvalidParams, "tool_result blocks are not matching any tool_use from the previous message"); - } - if (hasPreviousToolUse) { - const toolUseIds = new Set(previousContent.filter((c) => c.type === "tool_use").map((c) => c.id)); - const toolResultIds = new Set(lastContent.filter((c) => c.type === "tool_result").map((c) => c.toolUseId)); - if (toolUseIds.size !== toolResultIds.size || ![...toolUseIds].every((id) => toolResultIds.has(id))) throw new src_CX2iR2pK_ProtocolError(src_CX2iR2pK_ProtocolErrorCode.InvalidParams, "ids of tool_result blocks and tool_use blocks from previous message do not match"); - } - } - const hasTools = Boolean(params.tools || params.toolChoice); - const wide = await this.request({ - method: "sampling/createMessage", - params - }, options); - const outcome = this._wireCodec().samplingResultVariant(hasTools, wide); - if (!outcome.ok) throw new src_CX2iR2pK_SdkError(src_CX2iR2pK_SdkErrorCode.InvalidResult, `Invalid sampling/createMessage result: ${outcome.reason === "invalid" ? outcome.message : outcome.reason}`); - return outcome.value; - } - /** - * Creates an elicitation request for the given parameters. - * For backwards compatibility, `mode` may be omitted for form requests and will default to `"form"`. - * @param params The parameters for the elicitation request. - * @param options Optional request options. - * @returns The result of the elicitation request. - * - * @deprecated Throws on a 2026-07-28-era request — use {@link index.inputRequired | inputRequired} (multi-round-trip) - * instead. The 2025 push-style server-to-client request model is replaced by input_required - * results in the 2026-07-28 protocol. If your factory serves both eras, this only works on the - * legacy path. - */ - async elicitInput(params, options) { - this._assertPushApiInServedEra("elicitation/create"); - switch (params.mode ?? "form") { - case "url": - if (!this._clientCapabilities?.elicitation?.url) throw new src_CX2iR2pK_SdkError(src_CX2iR2pK_SdkErrorCode.CapabilityNotSupported, "Client does not support url elicitation."); - break; - case "form": - if (!this._clientCapabilities?.elicitation?.form) throw new src_CX2iR2pK_SdkError(src_CX2iR2pK_SdkErrorCode.CapabilityNotSupported, "Client does not support form elicitation."); - break; - } - return this._sendElicitationLeg(params, options); - } - /** - * The capability-check-free core of {@linkcode elicitInput}. The shim - * uses it because its gate differs from the public checks: a bare - * `elicitation: {}` counts as form support (the pre-mode rule), and - * accepted content passes through unvalidated for parity with the - * modern client driver (handlers validate via the schema-aware - * `acceptedContent` overload and can re-ask). - */ - async _sendElicitationLeg(params, options, behavior) { - const mode = params.mode ?? "form"; - const validateAcceptedContent = behavior?.validateAcceptedContent ?? true; - switch (mode) { - case "url": { - const urlParams = params; - return this.request({ - method: "elicitation/create", - params: urlParams - }, options); - } - case "form": { - const formParams = params.mode === "form" ? params : { - ...params, - mode: "form" - }; - const result = await this.request({ - method: "elicitation/create", - params: formParams - }, options); - if (validateAcceptedContent && result.action === "accept" && result.content && formParams.requestedSchema) try { - const validationResult = this._jsonSchemaValidator.getValidator(formParams.requestedSchema)(result.content); - if (!validationResult.valid) throw new src_CX2iR2pK_ProtocolError(src_CX2iR2pK_ProtocolErrorCode.InvalidParams, `Elicitation response content does not match requested schema: ${validationResult.errorMessage}`); - } catch (error) { - if (error instanceof src_CX2iR2pK_ProtocolError) throw error; - throw new src_CX2iR2pK_ProtocolError(src_CX2iR2pK_ProtocolErrorCode.InternalError, `Error validating elicitation response: ${error instanceof Error ? error.message : String(error)}`); - } - return result; - } - } - } - /** - * Creates a reusable callback that, when invoked, will send a `notifications/elicitation/complete` - * notification for the specified elicitation ID. - * - * The notification (and the `elicitationId` it references) exists only on protocol revision - * 2025-11-25 — the 2026-07-28 revision removed both. On a connection negotiated at 2026-07-28 the - * returned callback rejects with a typed local error before anything reaches the transport - * (the method is not part of that revision's wire registry). - * - * @param elicitationId The ID of the elicitation to mark as complete. - * @param options Optional notification options. Useful when the completion notification should be related to a prior request. - * @returns A function that emits the completion notification when awaited. - */ - createElicitationCompletionNotifier(elicitationId, options) { - if (!this._clientCapabilities?.elicitation?.url) throw new src_CX2iR2pK_SdkError(src_CX2iR2pK_SdkErrorCode.CapabilityNotSupported, "Client does not support URL elicitation (required for notifications/elicitation/complete)"); - return () => this.notification({ - method: "notifications/elicitation/complete", - params: { elicitationId } - }, options); - } - /** - * Requests the list of roots from the client. - * - * @deprecated Deprecated as of protocol version 2026-07-28 (SEP-2577). - * Throws on a 2026-07-28-era request — use {@link index.inputRequired | inputRequired} (multi-round-trip) instead, - * or migrate to passing paths via tool parameters, resource URIs, or configuration. The 2025 - * push-style server-to-client request model is replaced by input_required results in the - * 2026-07-28 protocol. If your factory serves both eras, this only works on the legacy path. - */ - async listRoots(params, options) { - this._assertPushApiInServedEra("roots/list"); - return this.request({ - method: "roots/list", - params - }, options); - } - /** - * Sends a logging message to the client, if connected. - * Note: You only need to send the parameters object, not the entire JSON-RPC message. - * @see {@linkcode LoggingMessageNotification} - * @param params - * @param sessionId Optional for stateless transports and backward compatibility. - * - * @deprecated Deprecated as of protocol version 2026-07-28 (SEP-2577). - * Remains functional during the deprecation window (at least twelve months). - * Migrate to stderr logging (STDIO servers) or OpenTelemetry. - */ - async sendLoggingMessage(params, sessionId) { - if (this._capabilities.logging && !this.isMessageIgnored(params.level, sessionId)) return this.notification({ - method: "notifications/message", - params - }); - } - async sendResourceUpdated(params) { - return this.notification({ - method: "notifications/resources/updated", - params - }); - } - 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" }); - } -}; -/** -* The capability set a server advertises on `server/discover`. Pure — never -* mutates the input; the legacy `initialize` advertisement is untouched. -* -* The serving entries serve `subscriptions/listen` themselves, so the -* `listChanged` and `resources.subscribe` capability bits are advertised -* as-is: a modern-era client uses them to decide which notification types to -* request on its listen filter. -*/ -function discoverAdvertisedCapabilities(capabilities) { - return { ...capabilities }; -} - -//#endregion -//#region src/server/mcp.ts -/** -* High-level MCP server that provides a simpler API for working with resources, tools, and prompts. -* For advanced usage (like sending notifications or setting custom request handlers), use the underlying -* {@linkcode Server} instance available via the {@linkcode McpServer.server | server} property. -* -* @example -* ```ts source="./mcp.examples.ts#McpServer_basicUsage" -* const server = new McpServer({ -* name: 'my-server', -* version: '1.0.0' -* }); -* ``` -*/ -var mcp_DXXb3Vv3_McpServer = class { - /** - * The underlying {@linkcode Server} instance, useful for advanced operations like sending notifications. - */ - server; - _registeredResources = {}; - _registeredResourceTemplates = {}; - _registeredTools = {}; - _registeredPrompts = {}; - /** - * Per-tool JSON-converted `inputSchema`, memoized so the SEP-2243 - * registration-time scan and the pre-dispatch validation step share one - * conversion instead of paying it twice per request under the - * per-request-factory `createMcpHandler` model. - */ - _toolInputSchemaJson = {}; - /** - * The JSON-serialized `inputSchema` of a registered tool, or `undefined` - * when no such tool is registered. Used by the HTTP entry's pre-dispatch - * SEP-2243 `Mcp-Param-*` validation step (which needs the same JSON Schema - * `tools/list` would emit, before dispatch reaches the handler). - * - * @internal - */ - toolInputSchemaJson(name) { - const tool = this._registeredTools[name]; - if (tool === void 0 || !tool.enabled) return void 0; - if (Object.hasOwn(this._toolInputSchemaJson, name)) return this._toolInputSchemaJson[name]; - if (tool.inputSchema === void 0) return EMPTY_OBJECT_JSON_SCHEMA; - try { - const json = standardSchemaToJsonSchema(tool.inputSchema, "input"); - this._toolInputSchemaJson[name] = json; - return json; - } catch { - return; - } - } - constructor(serverInfo, options) { - this.server = new Server(serverInfo, options); - if (options?.capabilities?.tools) this.setToolRequestHandlers(); - if (options?.capabilities?.resources) this.setResourceRequestHandlers(); - if (options?.capabilities?.prompts) this.setPromptRequestHandlers(); - } - /** - * Attaches to the given transport, starts it, and starts listening for messages. - * - * The `server` object assumes ownership of the {@linkcode Transport}, replacing any callbacks that have already been set, and expects that it is the only user of the {@linkcode Transport} instance going forward. - * - * @example - * ```ts source="./mcp.examples.ts#McpServer_connect_stdio" - * const server = new McpServer({ name: 'my-server', version: '1.0.0' }); - * const transport = new StdioServerTransport(); - * await server.connect(transport); - * ``` - */ - async connect(transport) { - return await this.server.connect(transport); - } - /** - * Closes the connection. - */ - async close() { - await this.server.close(); - } - _toolHandlersInitialized = false; - setToolRequestHandlers() { - if (this._toolHandlersInitialized) return; - this.server.assertCanSetRequestHandler("tools/list"); - this.server.assertCanSetRequestHandler("tools/call"); - this.server.registerCapabilities({ tools: { listChanged: this.server.getCapabilities().tools?.listChanged ?? true } }); - this.server.setRequestHandler("tools/list", () => ({ tools: Object.entries(this._registeredTools).filter(([, tool]) => tool.enabled).map(([name, tool]) => { - const toolDefinition = { - name, - title: tool.title, - description: tool.description, - inputSchema: tool.inputSchema ? standardSchemaToJsonSchema(tool.inputSchema, "input") : EMPTY_OBJECT_JSON_SCHEMA, - annotations: tool.annotations, - icons: tool.icons, - execution: tool.execution, - _meta: tool._meta - }; - if (tool.outputSchema) toolDefinition.outputSchema = standardSchemaToJsonSchema(tool.outputSchema, "output"); - return toolDefinition; - }) })); - this.server.setRequestHandler("tools/call", async (request, ctx) => { - const tool = this._registeredTools[request.params.name]; - if (!tool) throw new src_CX2iR2pK_ProtocolError(src_CX2iR2pK_ProtocolErrorCode.InvalidParams, `Tool ${request.params.name} not found`); - if (!tool.enabled) throw new src_CX2iR2pK_ProtocolError(src_CX2iR2pK_ProtocolErrorCode.InvalidParams, `Tool ${request.params.name} disabled`); - try { - const args = await this.validateToolInput(tool, request.params.arguments, request.params.name); - const result = await this.executeToolHandler(tool, args, ctx); - await this.validateToolOutput(tool, result, request.params.name); - if (isInputRequiredResult(result)) return result; - return this.server.projectCallToolResult(result, tool.outputSchemaJson); - } catch (error) { - if (error instanceof src_CX2iR2pK_ProtocolError && error.code === src_CX2iR2pK_ProtocolErrorCode.UrlElicitationRequired) throw error; - return this.createToolError(error instanceof Error ? error.message : String(error)); - } - }); - this._toolHandlersInitialized = true; - } - /** - * Creates a tool error result. - * - * @param errorMessage - The error message. - * @returns The tool error result. - */ - createToolError(errorMessage) { - return { - content: [{ - type: "text", - text: errorMessage - }], - isError: true - }; - } - /** - * Validates tool input arguments against the tool's input schema. - */ - async validateToolInput(tool, args, toolName) { - if (!tool.inputSchema) return; - const parseResult = await validateStandardSchema(tool.inputSchema, args ?? {}); - if (!parseResult.success) throw new src_CX2iR2pK_ProtocolError(src_CX2iR2pK_ProtocolErrorCode.InvalidParams, `Input validation error: Invalid arguments for tool ${toolName}: ${parseResult.error}`); - return parseResult.data; - } - /** - * Validates tool output against the tool's output schema. - */ - async validateToolOutput(tool, result, toolName) { - if (!tool.outputSchema) return; - if (isInputRequiredResult(result)) return; - if (result.isError) return; - if (result.structuredContent === void 0) throw new src_CX2iR2pK_ProtocolError(src_CX2iR2pK_ProtocolErrorCode.InvalidParams, `Output validation error: Tool ${toolName} has an output schema but no structured content was provided`); - const parseResult = await validateStandardSchema(tool.outputSchema, result.structuredContent); - if (!parseResult.success) throw new src_CX2iR2pK_ProtocolError(src_CX2iR2pK_ProtocolErrorCode.InvalidParams, `Output validation error: Invalid structured content for tool ${toolName}: ${parseResult.error}`); - } - /** - * Executes a tool handler. - */ - async executeToolHandler(tool, args, ctx) { - return tool.executor(args, ctx); - } - _completionHandlerInitialized = false; - setCompletionRequestHandler() { - if (this._completionHandlerInitialized) return; - this.server.assertCanSetRequestHandler("completion/complete"); - this.server.registerCapabilities({ completions: {} }); - this.server.setRequestHandler("completion/complete", async (request) => { - switch (request.params.ref.type) { - case "ref/prompt": - assertCompleteRequestPrompt(request); - return this.handlePromptCompletion(request, request.params.ref); - case "ref/resource": - assertCompleteRequestResourceTemplate(request); - return this.handleResourceCompletion(request, request.params.ref); - default: throw new src_CX2iR2pK_ProtocolError(src_CX2iR2pK_ProtocolErrorCode.InvalidParams, `Invalid completion reference: ${request.params.ref}`); - } - }); - this._completionHandlerInitialized = true; - } - async handlePromptCompletion(request, ref) { - const prompt = this._registeredPrompts[ref.name]; - if (!prompt) throw new src_CX2iR2pK_ProtocolError(src_CX2iR2pK_ProtocolErrorCode.InvalidParams, `Prompt ${ref.name} not found`); - if (!prompt.enabled) throw new src_CX2iR2pK_ProtocolError(src_CX2iR2pK_ProtocolErrorCode.InvalidParams, `Prompt ${ref.name} disabled`); - if (!prompt.argsSchema) return EMPTY_COMPLETION_RESULT; - const field = unwrapOptionalSchema(getSchemaShape(prompt.argsSchema)?.[request.params.argument.name]); - if (!isCompletable(field)) return EMPTY_COMPLETION_RESULT; - const completer = getCompleter(field); - if (!completer) return EMPTY_COMPLETION_RESULT; - return createCompletionResult(await completer(request.params.argument.value, request.params.context)); - } - async handleResourceCompletion(request, ref) { - const template = Object.values(this._registeredResourceTemplates).find((t) => t.resourceTemplate.uriTemplate.toString() === ref.uri); - if (!template) { - if (this._registeredResources[ref.uri]) return EMPTY_COMPLETION_RESULT; - throw new src_CX2iR2pK_ProtocolError(src_CX2iR2pK_ProtocolErrorCode.InvalidParams, `Resource template ${request.params.ref.uri} not found`); - } - const completer = template.resourceTemplate.completeCallback(request.params.argument.name); - if (!completer) return EMPTY_COMPLETION_RESULT; - return createCompletionResult(await completer(request.params.argument.value, request.params.context)); - } - _resourceHandlersInitialized = false; - setResourceRequestHandlers() { - if (this._resourceHandlersInitialized) return; - this.server.assertCanSetRequestHandler("resources/list"); - this.server.assertCanSetRequestHandler("resources/templates/list"); - this.server.assertCanSetRequestHandler("resources/read"); - this.server.registerCapabilities({ resources: { listChanged: this.server.getCapabilities().resources?.listChanged ?? true } }); - this.server.setRequestHandler("resources/list", async (_request, ctx) => { - const resources = Object.entries(this._registeredResources).filter(([_, resource]) => resource.enabled).map(([uri, resource]) => ({ - uri, - name: resource.name, - ...resource.metadata - })); - const templateResources = []; - for (const template of Object.values(this._registeredResourceTemplates)) { - if (!template.resourceTemplate.listCallback) continue; - const result = await template.resourceTemplate.listCallback(ctx); - for (const resource of result.resources) templateResources.push({ - ...template.metadata, - ...resource - }); - } - return { resources: [...resources, ...templateResources] }; - }); - this.server.setRequestHandler("resources/templates/list", async () => { - return { resourceTemplates: Object.entries(this._registeredResourceTemplates).map(([name, template]) => ({ - name, - uriTemplate: template.resourceTemplate.uriTemplate.toString(), - ...template.metadata - })) }; - }); - this.server.setRequestHandler("resources/read", async (request, ctx) => { - let uri; - try { - uri = new URL(request.params.uri); - } catch { - throw new src_CX2iR2pK_ProtocolError(src_CX2iR2pK_ProtocolErrorCode.InvalidParams, `Resource URI ${request.params.uri} is invalid`, { - uri: request.params.uri, - reason: "invalid_uri" - }); - } - const resource = this._registeredResources[uri.toString()]; - if (resource) { - if (!resource.enabled) throw new src_CX2iR2pK_ProtocolError(src_CX2iR2pK_ProtocolErrorCode.InvalidParams, `Resource ${uri} disabled`); - return attachCacheHintFallback(await resource.readCallback(uri, ctx), resource.cacheHint); - } - for (const template of Object.values(this._registeredResourceTemplates)) { - const variables = template.resourceTemplate.uriTemplate.match(uri.toString()); - if (variables) return attachCacheHintFallback(await template.readCallback(uri, variables, ctx), template.cacheHint); - } - throw new ResourceNotFoundError(request.params.uri); - }); - this._resourceHandlersInitialized = true; - } - _promptHandlersInitialized = false; - setPromptRequestHandlers() { - if (this._promptHandlersInitialized) return; - this.server.assertCanSetRequestHandler("prompts/list"); - this.server.assertCanSetRequestHandler("prompts/get"); - this.server.registerCapabilities({ prompts: { listChanged: this.server.getCapabilities().prompts?.listChanged ?? true } }); - this.server.setRequestHandler("prompts/list", () => ({ prompts: Object.entries(this._registeredPrompts).filter(([, prompt]) => prompt.enabled).map(([name, prompt]) => { - return { - name, - title: prompt.title, - description: prompt.description, - arguments: prompt.argsSchema ? promptArgumentsFromStandardSchema(prompt.argsSchema) : void 0, - icons: prompt.icons, - _meta: prompt._meta - }; - }) })); - this.server.setRequestHandler("prompts/get", async (request, ctx) => { - const prompt = this._registeredPrompts[request.params.name]; - if (!prompt) throw new src_CX2iR2pK_ProtocolError(src_CX2iR2pK_ProtocolErrorCode.InvalidParams, `Prompt ${request.params.name} not found`); - if (!prompt.enabled) throw new src_CX2iR2pK_ProtocolError(src_CX2iR2pK_ProtocolErrorCode.InvalidParams, `Prompt ${request.params.name} disabled`); - return prompt.handler(request.params.arguments, ctx); - }); - this._promptHandlersInitialized = true; - } - registerResource(name, uriOrTemplate, config, readCallback) { - const cacheHint = config.cacheHint; - let metadata = config; - if (cacheHint !== void 0) { - assertValidCacheHint(cacheHint, `resource ${name}`); - const rest = { ...config }; - delete rest.cacheHint; - metadata = rest; - } - if (typeof uriOrTemplate === "string") { - if (this._registeredResources[uriOrTemplate]) throw new Error(`Resource ${uriOrTemplate} is already registered`); - const registeredResource = this._createRegisteredResource(name, config.title, uriOrTemplate, metadata, readCallback); - if (cacheHint !== void 0) registeredResource.cacheHint = cacheHint; - this.setResourceRequestHandlers(); - this.sendResourceListChanged(); - return registeredResource; - } else { - if (this._registeredResourceTemplates[name]) throw new Error(`Resource template ${name} is already registered`); - const registeredResourceTemplate = this._createRegisteredResourceTemplate(name, config.title, uriOrTemplate, metadata, readCallback); - if (cacheHint !== void 0) registeredResourceTemplate.cacheHint = cacheHint; - this.setResourceRequestHandlers(); - this.sendResourceListChanged(); - return registeredResourceTemplate; - } - } - _createRegisteredResource(name, title, uri, metadata, readCallback) { - const registeredResource = { - name, - title, - metadata, - readCallback, - enabled: true, - disable: () => registeredResource.update({ enabled: false }), - enable: () => registeredResource.update({ enabled: true }), - remove: () => registeredResource.update({ uri: null }), - update: (updates) => { - if (updates.uri !== void 0 && updates.uri !== uri) { - delete this._registeredResources[uri]; - if (updates.uri) this._registeredResources[updates.uri] = registeredResource; - } - if (updates.name !== void 0) registeredResource.name = updates.name; - if (updates.title !== void 0) registeredResource.title = updates.title; - if (updates.metadata !== void 0) registeredResource.metadata = updates.metadata; - if (updates.callback !== void 0) registeredResource.readCallback = updates.callback; - if (updates.enabled !== void 0) registeredResource.enabled = updates.enabled; - this.sendResourceListChanged(); - } - }; - this._registeredResources[uri] = registeredResource; - return registeredResource; - } - _createRegisteredResourceTemplate(name, title, template, metadata, readCallback) { - const registeredResourceTemplate = { - resourceTemplate: template, - title, - metadata, - readCallback, - enabled: true, - disable: () => registeredResourceTemplate.update({ enabled: false }), - enable: () => registeredResourceTemplate.update({ enabled: true }), - remove: () => registeredResourceTemplate.update({ name: null }), - update: (updates) => { - if (updates.name !== void 0 && updates.name !== name) { - delete this._registeredResourceTemplates[name]; - if (updates.name) this._registeredResourceTemplates[updates.name] = registeredResourceTemplate; - } - if (updates.title !== void 0) registeredResourceTemplate.title = updates.title; - if (updates.template !== void 0) registeredResourceTemplate.resourceTemplate = updates.template; - if (updates.metadata !== void 0) registeredResourceTemplate.metadata = updates.metadata; - if (updates.callback !== void 0) registeredResourceTemplate.readCallback = updates.callback; - if (updates.enabled !== void 0) registeredResourceTemplate.enabled = updates.enabled; - this.sendResourceListChanged(); - } - }; - this._registeredResourceTemplates[name] = registeredResourceTemplate; - const variableNames = template.uriTemplate.variableNames; - if (Array.isArray(variableNames) && variableNames.some((v) => !!template.completeCallback(v))) this.setCompletionRequestHandler(); - return registeredResourceTemplate; - } - _createRegisteredPrompt(name, title, description, argsSchema, callback, icons, _meta) { - let currentArgsSchema = argsSchema; - let currentCallback = callback; - const registeredPrompt = { - title, - description, - argsSchema, - icons, - _meta, - handler: createPromptHandler(name, argsSchema, callback), - enabled: true, - disable: () => registeredPrompt.update({ enabled: false }), - enable: () => registeredPrompt.update({ enabled: true }), - remove: () => registeredPrompt.update({ name: null }), - update: (updates) => { - if (updates.name !== void 0 && updates.name !== name) { - delete this._registeredPrompts[name]; - if (updates.name) this._registeredPrompts[updates.name] = registeredPrompt; - } - if (updates.title !== void 0) registeredPrompt.title = updates.title; - if (updates.description !== void 0) registeredPrompt.description = updates.description; - if (updates.icons !== void 0) registeredPrompt.icons = updates.icons; - if (updates._meta !== void 0) registeredPrompt._meta = updates._meta; - let needsHandlerRegen = false; - if (updates.argsSchema !== void 0) { - registeredPrompt.argsSchema = updates.argsSchema; - currentArgsSchema = updates.argsSchema; - needsHandlerRegen = true; - } - if (updates.callback !== void 0) { - currentCallback = updates.callback; - needsHandlerRegen = true; - } - if (needsHandlerRegen) registeredPrompt.handler = createPromptHandler(name, currentArgsSchema, currentCallback); - if (updates.enabled !== void 0) registeredPrompt.enabled = updates.enabled; - this.sendPromptListChanged(); - } - }; - this._registeredPrompts[name] = registeredPrompt; - if (argsSchema) { - const shape = getSchemaShape(argsSchema); - if (shape) { - if (Object.values(shape).some((field) => { - return isCompletable(unwrapOptionalSchema(field)); - })) this.setCompletionRequestHandler(); - } - } - return registeredPrompt; - } - _createRegisteredTool(name, title, description, inputSchema, outputSchema, annotations, icons, execution, _meta, handler) { - validateAndWarnToolName(name); - if (inputSchema !== void 0) try { - const json = standardSchemaToJsonSchema(inputSchema, "input"); - this._toolInputSchemaJson[name] = json; - const scan = src_CX2iR2pK_scanXMcpHeaderDeclarations(json); - if (!scan.valid) console.warn(`[mcp-sdk] tool '${name}' carries an invalid x-mcp-header declaration and will be excluded by conforming Streamable HTTP clients: ${scan.reason}`); - } catch {} - let currentHandler = handler; - const registeredTool = { - title, - description, - inputSchema, - outputSchema, - outputSchemaJson: convertOutputSchemaJson(outputSchema), - annotations, - icons, - execution, - _meta, - handler, - executor: createToolExecutor(inputSchema, handler), - enabled: true, - disable: () => registeredTool.update({ enabled: false }), - enable: () => registeredTool.update({ enabled: true }), - remove: () => registeredTool.update({ name: null }), - update: (updates) => { - if (updates.name !== void 0 && updates.name !== name) { - if (typeof updates.name === "string") validateAndWarnToolName(updates.name); - delete this._registeredTools[name]; - delete this._toolInputSchemaJson[name]; - if (updates.name) { - delete this._toolInputSchemaJson[updates.name]; - this._registeredTools[updates.name] = registeredTool; - name = updates.name; - } - } - if (updates.title !== void 0) registeredTool.title = updates.title; - if (updates.description !== void 0) registeredTool.description = updates.description; - let needsExecutorRegen = false; - if (updates.paramsSchema !== void 0) { - registeredTool.inputSchema = updates.paramsSchema; - delete this._toolInputSchemaJson[name]; - needsExecutorRegen = true; - } - if (updates.callback !== void 0) { - registeredTool.handler = updates.callback; - currentHandler = updates.callback; - needsExecutorRegen = true; - } - if (needsExecutorRegen) registeredTool.executor = createToolExecutor(registeredTool.inputSchema, currentHandler); - if (updates.outputSchema !== void 0) { - registeredTool.outputSchema = updates.outputSchema; - registeredTool.outputSchemaJson = convertOutputSchemaJson(updates.outputSchema); - } - if (updates.annotations !== void 0) registeredTool.annotations = updates.annotations; - if (updates.icons !== void 0) registeredTool.icons = updates.icons; - if (updates._meta !== void 0) registeredTool._meta = updates._meta; - if (updates.enabled !== void 0) registeredTool.enabled = updates.enabled; - this.sendToolListChanged(); - } - }; - this._registeredTools[name] = registeredTool; - this.setToolRequestHandlers(); - this.sendToolListChanged(); - return registeredTool; - } - registerTool(name, config, cb) { - if (this._registeredTools[name]) throw new Error(`Tool ${name} is already registered`); - const { title, description, inputSchema, outputSchema, annotations, icons, _meta } = config; - return this._createRegisteredTool(name, title, description, normalizeRawShapeSchema(inputSchema), normalizeRawShapeSchema(outputSchema), annotations, icons, void 0, _meta, cb); - } - registerPrompt(name, config, cb) { - if (this._registeredPrompts[name]) throw new Error(`Prompt ${name} is already registered`); - const { title, description, argsSchema, icons, _meta } = config; - const registeredPrompt = this._createRegisteredPrompt(name, title, description, normalizeRawShapeSchema(argsSchema), cb, icons, _meta); - this.setPromptRequestHandlers(); - this.sendPromptListChanged(); - return registeredPrompt; - } - /** - * Checks if the server is connected to a transport. - * @returns `true` if the server is connected - */ - isConnected() { - return this.server.transport !== void 0; - } - /** - * Sends a logging message to the client, if connected. - * Note: You only need to send the parameters object, not the entire JSON-RPC message. - * @see {@linkcode LoggingMessageNotification} - * @param params - * @param sessionId Optional for stateless transports and backward compatibility. - * - * @example - * ```ts source="./mcp.examples.ts#McpServer_sendLoggingMessage_basic" - * await server.sendLoggingMessage({ - * level: 'info', - * data: 'Processing complete' - * }); - * ``` - * - * @deprecated Deprecated as of protocol version 2026-07-28 (SEP-2577). - * Remains functional during the deprecation window (at least twelve months). - * Migrate to stderr logging (STDIO servers) or OpenTelemetry. - */ - async sendLoggingMessage(params, sessionId) { - return this.server.sendLoggingMessage(params, sessionId); - } - /** - * Sends a resource list changed event to the client, if connected. - */ - sendResourceListChanged() { - if (this.isConnected()) this.server.sendResourceListChanged(); - } - /** - * Sends a tool list changed event to the client, if connected. - */ - sendToolListChanged() { - if (this.isConnected()) this.server.sendToolListChanged(); - } - /** - * Sends a prompt list changed event to the client, if connected. - */ - sendPromptListChanged() { - if (this.isConnected()) this.server.sendPromptListChanged(); - } -}; -/** -* A resource template combines a URI pattern with optional functionality to enumerate -* all resources matching that pattern. -*/ -var ResourceTemplate = class { - _uriTemplate; - constructor(uriTemplate, _callbacks) { - this._callbacks = _callbacks; - this._uriTemplate = typeof uriTemplate === "string" ? new UriTemplate(uriTemplate) : uriTemplate; - } - /** - * Gets the URI template pattern. - */ - get uriTemplate() { - return this._uriTemplate; - } - /** - * Gets the list callback, if one was provided. - */ - get listCallback() { - return this._callbacks.list; - } - /** - * Gets the callback for completing a specific URI template variable, if one was provided. - */ - completeCallback(variable) { - return this._callbacks.complete?.[variable]; - } -}; -/** -* Creates an executor that invokes the handler with the appropriate arguments. -* When `inputSchema` is defined, the handler is called with `(args, ctx)`. -* When `inputSchema` is undefined, the handler is called with just `(ctx)`. -*/ -function createToolExecutor(inputSchema, handler) { - if (inputSchema) { - const callback$1 = handler; - return async (args, ctx) => callback$1(args, ctx); - } - const callback = handler; - return async (_args, ctx) => callback(ctx); -} -const EMPTY_OBJECT_JSON_SCHEMA = { - type: "object", - properties: {} -}; -/** -* Convert a registered `outputSchema` to JSON Schema, memoised on {@link RegisteredTool.outputSchemaJson} -* so `tools/call` passes the SAME advertised schema to the wire codec's `projectCallToolResult` that -* `tools/list` emits (and that the 2025 codec's `encodeResult('tools/list', …)` may wrap). A conversion -* failure yields `undefined` so the failure surfaces where it always has (`tools/list`). -*/ -function convertOutputSchemaJson(outputSchema) { - if (outputSchema === void 0) return void 0; - try { - return standardSchemaToJsonSchema(outputSchema, "output"); - } catch { - return; - } -} -/** -* Creates a type-safe prompt handler that captures the schema and callback in a closure. -* This eliminates the need for type assertions at the call site. -*/ -function createPromptHandler(name, argsSchema, callback) { - if (argsSchema) { - const typedCallback = callback; - return async (args, ctx) => { - const parseResult = await validateStandardSchema(argsSchema, args); - if (!parseResult.success) throw new src_CX2iR2pK_ProtocolError(src_CX2iR2pK_ProtocolErrorCode.InvalidParams, `Invalid arguments for prompt ${name}: ${parseResult.error}`); - return typedCallback(parseResult.data, ctx); - }; - } else { - const typedCallback = callback; - return async (_args, ctx) => { - return typedCallback(ctx); - }; - } -} -function createCompletionResult(suggestions) { - return { completion: { - values: suggestions.map(String).slice(0, 100), - total: suggestions.length, - hasMore: suggestions.length > 100 - } }; -} -const EMPTY_COMPLETION_RESULT = { completion: { - values: [], - hasMore: false -} }; -/** @internal Gets the shape of a Zod object schema */ -function getSchemaShape(schema) { - const candidate = schema; - if (candidate.shape && typeof candidate.shape === "object") return candidate.shape; -} -/** @internal Checks if a Zod schema is optional */ -function isOptionalSchema(schema) { - return schema?.type === "optional"; -} -/** @internal Unwraps an optional Zod schema */ -function unwrapOptionalSchema(schema) { - if (!isOptionalSchema(schema)) return schema; - return schema.def?.innerType ?? schema; -} - -//#endregion - -//# sourceMappingURL=mcp-DXXb3Vv3.mjs.map - - - - -//#region src/server/perRequestTransport.ts -/** -* The per-request micro-transport: a real, connected `Transport` whose whole -* lifetime is one HTTP exchange. See the module documentation for the -* response shapes it produces. -*/ -var PerRequestHTTPServerTransport = class { - onclose; - onerror; - onmessage; - _classification; - _responseMode; - _started = false; - _used = false; - _closed = false; - _terminalDelivered = false; - /** - * `true` only while the inbound message is being delivered synchronously - * to the connected protocol layer. The pre-handler gates (the era - * registry gate, the edge→instance handoff check, the missing-handler - * rejection) answer inside this window; request handlers always run - * after it (the protocol layer defers them to a microtask). An error - * sent inside the window is therefore ladder-originated, and an error - * sent after it is handler-produced. - */ - _dispatchWindowOpen = false; - _requestId; - _deferredResponse; - _sse; - _abortCleanup; - _keepAliveMs; - constructor(options) { - this._classification = options.classification; - this._responseMode = options.responseMode ?? "auto"; - this._keepAliveMs = options.keepAliveMs ?? DEFAULT_SSE_KEEP_ALIVE_MS; - } - async start() { - if (this._started) throw new Error("PerRequestHTTPServerTransport is already started"); - this._started = true; - } - /** - * Serves the single exchange: delivers the classified message to the - * connected server instance and resolves with the HTTP response. - * - * Throws when called a second time (the transport is strictly - * single-use), or before a server has been connected to the transport. - * The returned promise rejects with a connection-closed error when the - * transport is closed before a response was produced (for example because - * the client disconnected). - */ - async handleMessage(message, extra) { - if (this._used) throw new Error("PerRequestHTTPServerTransport serves exactly one exchange; construct a new transport per request"); - if (!this._started || this.onmessage === void 0) throw new Error("PerRequestHTTPServerTransport is not connected: connect a server to this transport before handling a message"); - if (this._closed) throw new Error("PerRequestHTTPServerTransport is closed"); - this._used = true; - const signal = extra?.request?.signal; - if (signal?.aborted) { - await this.close(); - throw new SdkError(SdkErrorCode.ConnectionClosed, "The request was aborted before it could be handled"); - } - const messageExtra = { - classification: this._classification, - ...extra?.request !== void 0 && { request: extra.request }, - ...extra?.authInfo !== void 0 && { authInfo: extra.authInfo } - }; - if (isJSONRPCRequest(message)) { - this._requestId = message.id; - let resolve; - let reject; - const promise = new Promise((promiseResolve, promiseReject) => { - resolve = promiseResolve; - reject = promiseReject; - }); - this._deferredResponse = { - promise, - resolve, - reject, - settled: false - }; - if (signal !== void 0) { - const onAbort = () => void this.close(); - signal.addEventListener("abort", onAbort, { once: true }); - this._abortCleanup = () => signal.removeEventListener("abort", onAbort); - } - this._dispatchWindowOpen = true; - try { - this.onmessage(message, messageExtra); - } finally { - this._dispatchWindowOpen = false; - } - if (this._responseMode === "sse" && !this._closed && !this._deferredResponse.settled) this.upgradeToSse(); - return promise; - } - this.onmessage(message, messageExtra); - return new Response(null, { status: 202 }); - } - async send(message, options) { - if (this._closed) return; - const isResponse = isJSONRPCResultResponse(message) || isJSONRPCErrorResponse(message); - const relatedId = isResponse ? message.id : options?.relatedRequestId; - if (this._requestId === void 0 || relatedId === void 0 || relatedId !== this._requestId) { - if (isResponse) this.onerror?.(/* @__PURE__ */ new Error(`Received a response for an unknown request id: ${String(message.id)}`)); - return; - } - if (isResponse) { - if (this._terminalDelivered) return; - this._terminalDelivered = true; - const errorCode = isJSONRPCErrorResponse(message) ? message.error.code : void 0; - const ladderStatus = errorCode !== void 0 && (this._dispatchWindowOpen || errorCode === ProtocolErrorCode.MissingRequiredClientCapability) ? LADDER_ERROR_HTTP_STATUS[errorCode] : void 0; - if (ladderStatus !== void 0 && this._sse === void 0) { - this.settleResponse(Response.json(message, { - status: ladderStatus, - headers: { "Content-Type": "application/json" } - })); - queueMicrotask(() => void this.close()); - return; - } - if (this._sse !== void 0 || this._responseMode === "sse") { - if (this._sse === void 0) this.upgradeToSse(); - this.writeMessageFrame(message); - this.finalizeStream(); - return; - } - this.settleResponse(Response.json(message, { - status: 200, - headers: { "Content-Type": "application/json" } - })); - queueMicrotask(() => void this.close()); - return; - } - if (this._responseMode === "json") return; - if (this._sse === void 0) this.upgradeToSse(); - this.writeMessageFrame(message); - } - /** - * Writes an SSE comment frame (a keep-alive heartbeat). Dropped when the - * exchange is not currently streaming. - */ - writeCommentFrame(comment) { - if (this._closed || this._sse === void 0 || this._sse.closed) return; - const frame = comment.split("\n").map((line) => `: ${line}`).join("\n"); - this.writeFrame(`${frame}\n\n`); - } - async close() { - if (this._closed) return; - this._closed = true; - this._abortCleanup?.(); - this._abortCleanup = void 0; - if (this._sse?.keepAliveTimer !== void 0) clearInterval(this._sse.keepAliveTimer); - if (this._sse !== void 0 && !this._sse.closed) { - this._sse.closed = true; - try { - this._sse.controller.close(); - } catch {} - } - if (this._deferredResponse !== void 0 && !this._deferredResponse.settled) { - this._deferredResponse.settled = true; - this._deferredResponse.reject(new SdkError(SdkErrorCode.ConnectionClosed, "Connection closed before a response was produced")); - } - this.onclose?.(); - } - settleResponse(response) { - if (this._deferredResponse === void 0 || this._deferredResponse.settled) return; - this._deferredResponse.settled = true; - this._deferredResponse.resolve(response); - } - upgradeToSse() { - let controller; - const readable = new ReadableStream({ - start: (streamController) => { - controller = streamController; - }, - cancel: () => { - this.close(); - } - }); - this._sse = { - controller, - encoder: new TextEncoder(), - closed: false - }; - this._sse.keepAliveTimer = armSseKeepAlive(this._keepAliveMs, () => this.writeCommentFrame("keepalive")); - this.settleResponse(new Response(readable, { - status: 200, - headers: { - "Content-Type": "text/event-stream", - "Cache-Control": "no-cache, no-transform", - Connection: "keep-alive", - "X-Accel-Buffering": "no" - } - })); - } - finalizeStream() { - if (this._sse?.keepAliveTimer !== void 0) clearInterval(this._sse.keepAliveTimer); - if (this._sse !== void 0 && !this._sse.closed) { - this._sse.closed = true; - try { - this._sse.controller.close(); - } catch {} - } - queueMicrotask(() => void this.close()); - } - writeMessageFrame(message) { - this.writeFrame(`event: message\ndata: ${JSON.stringify(message)}\n\n`); - } - writeFrame(frame) { - if (this._sse === void 0 || this._sse.closed) return; - try { - this._sse.controller.enqueue(this._sse.encoder.encode(frame)); - } catch (error) { - this.onerror?.(/* @__PURE__ */ new Error(`Failed to write to the response stream: ${error}`)); - } - } -}; - -//#endregion -//#region src/server/invoke.ts -/** -* Serves one classified inbound message on the given server instance and -* returns the HTTP response for the exchange. -* -* The instance is connected to a fresh single-exchange transport, the message -* is injected through the normal transport message path, and whatever the -* dispatch layer produces (the handler result, a protocol-level rejection, or -* streamed related messages followed by the result) is captured as the -* returned `Response`. For request exchanges, teardown rides the transport's -* close chain once the terminal response has been delivered; notification -* exchanges resolve with the 202 response immediately and do NOT run the -* close chain — the transport stays connected until the caller closes it or -* drops the per-request instance, which is the caller's choice either way. -*/ -async function invoke(server, message, ctx) { - const transport = new PerRequestHTTPServerTransport({ - classification: ctx.classification, - ...ctx.responseMode !== void 0 && { responseMode: ctx.responseMode }, - ...ctx.keepAliveMs !== void 0 && { keepAliveMs: ctx.keepAliveMs } - }); - await server.connect(transport); - return transport.handleMessage(message, { - ...ctx.request !== void 0 && { request: ctx.request }, - ...ctx.authInfo !== void 0 && { authInfo: ctx.authInfo } - }); -} - -//#endregion -//#region src/server/streamableHttp.ts -/** -* Server transport for Web Standards Streamable HTTP: this implements the MCP Streamable HTTP transport specification -* using Web Standard APIs (`Request`, `Response`, `ReadableStream`). -* -* This transport works on any runtime that supports Web Standards: Node.js 18+, Cloudflare Workers, Deno, Bun, etc. -* -* In stateful mode: -* - Session ID is generated and included in response headers -* - Session ID is always included in initialization responses -* - Requests with invalid session IDs are rejected with `404 Not Found` -* - Non-initialization requests without a session ID are rejected with `400 Bad Request` -* - State is maintained in-memory (connections, message history) -* -* In stateless mode: -* - No Session ID is included in any responses -* - No session validation is performed -* -* @example Stateful setup -* ```ts source="./streamableHttp.examples.ts#WebStandardStreamableHTTPServerTransport_stateful" -* const server = new McpServer({ name: 'my-server', version: '1.0.0' }); -* -* const transport = new WebStandardStreamableHTTPServerTransport({ -* sessionIdGenerator: () => crypto.randomUUID() -* }); -* -* await server.connect(transport); -* ``` -* -* @example Stateless setup -* ```ts source="./streamableHttp.examples.ts#WebStandardStreamableHTTPServerTransport_stateless" -* const transport = new WebStandardStreamableHTTPServerTransport({ -* sessionIdGenerator: undefined -* }); -* ``` -* -* @example Hono.js -* ```ts source="./streamableHttp.examples.ts#WebStandardStreamableHTTPServerTransport_hono" -* app.all('/mcp', async c => { -* return transport.handleRequest(c.req.raw); -* }); -* ``` -* -* @example Cloudflare Workers -* ```ts source="./streamableHttp.examples.ts#WebStandardStreamableHTTPServerTransport_workers" -* const worker = { -* async fetch(request: Request): Promise { -* return transport.handleRequest(request); -* } -* }; -* ``` -*/ -var WebStandardStreamableHTTPServerTransport = class { - sessionIdGenerator; - _started = false; - _closed = false; - _streamMapping = /* @__PURE__ */ new Map(); - _requestToStreamMapping = /* @__PURE__ */ new Map(); - _requestResponseMap = /* @__PURE__ */ new Map(); - _initialized = false; - _enableJsonResponse = false; - _standaloneSseStreamId = "_GET_stream"; - _eventStore; - _onsessioninitialized; - _onsessionclosed; - _allowedHosts; - _allowedOrigins; - _enableDnsRebindingProtection; - _retryInterval; - _supportedProtocolVersions; - _keepAliveMs; - sessionId; - onclose; - onerror; - onmessage; - constructor(options = {}) { - this.sessionIdGenerator = options.sessionIdGenerator; - this._enableJsonResponse = options.enableJsonResponse ?? false; - this._eventStore = options.eventStore; - this._onsessioninitialized = options.onsessioninitialized; - this._onsessionclosed = options.onsessionclosed; - this._allowedHosts = options.allowedHosts; - this._allowedOrigins = options.allowedOrigins; - this._enableDnsRebindingProtection = options.enableDnsRebindingProtection ?? false; - this._retryInterval = options.retryInterval; - this._supportedProtocolVersions = options.supportedProtocolVersions ?? SUPPORTED_PROTOCOL_VERSIONS; - this._keepAliveMs = options.keepAliveMs ?? DEFAULT_SSE_KEEP_ALIVE_MS; - } - startKeepAlive(controller, encoder) { - if (this._closed) return void 0; - const timer = armSseKeepAlive(this._keepAliveMs, () => { - try { - controller.enqueue(encoder.encode(": keepalive\n\n")); - } catch { - if (timer !== void 0) clearInterval(timer); - } - }); - return timer; - } - /** - * Starts the transport. This is required by the {@linkcode Transport} interface but is a no-op - * for the Streamable HTTP transport as connections are managed per-request. - */ - async start() { - if (this._started) throw new Error("Transport already started"); - this._started = true; - } - /** - * Sets the supported protocol versions for header validation. - * Called by the server during {@linkcode server/server.Server.connect | connect()} to pass its supported versions. - */ - setSupportedProtocolVersions(versions) { - this._supportedProtocolVersions = versions; - } - /** - * Helper to create a JSON error response - */ - createJsonErrorResponse(status, code, message, options) { - const error = { - code, - message - }; - if (options?.data !== void 0) error.data = options.data; - return Response.json({ - jsonrpc: "2.0", - error, - id: null - }, { - status, - headers: { - "Content-Type": "application/json", - ...options?.headers - } - }); - } - /** - * Validates request headers for DNS rebinding protection. - * @returns Error response if validation fails, `undefined` if validation passes. - */ - validateRequestHeaders(req) { - if (!this._enableDnsRebindingProtection) return; - if (this._allowedHosts && this._allowedHosts.length > 0) { - const hostHeader = req.headers.get("host"); - if (!hostHeader || !this._allowedHosts.includes(hostHeader)) { - const error = `Invalid Host header: ${hostHeader}`; - this.onerror?.(new Error(error)); - return this.createJsonErrorResponse(403, -32e3, error); - } - } - if (this._allowedOrigins && this._allowedOrigins.length > 0) { - const originHeader = req.headers.get("origin"); - if (originHeader && !this._allowedOrigins.includes(originHeader)) { - const error = `Invalid Origin header: ${originHeader}`; - this.onerror?.(new Error(error)); - return this.createJsonErrorResponse(403, -32e3, error); - } - } - } - /** - * Handles an incoming HTTP request, whether `GET`, `POST`, or `DELETE` - * Returns a `Response` object (Web Standard) - */ - async handleRequest(req, options) { - if (this._closed) return this.createJsonErrorResponse(404, -32001, "Session not found"); - const validationError = this.validateRequestHeaders(req); - if (validationError) return validationError; - switch (req.method) { - case "POST": return this.handlePostRequest(req, options); - case "GET": return this.handleGetRequest(req); - case "DELETE": return this.handleDeleteRequest(req); - default: return this.handleUnsupportedRequest(); - } - } - /** - * Returns true if the client's protocol version supports empty SSE data in - * priming events (the fix shipped with protocol version `2025-11-25`). - * - * The version is checked for membership in this transport instance's - * supported protocol versions rather than with an open-ended - * `>= '2025-11-25'` comparison: the value may come from an `initialize` - * request body, which (unlike the `MCP-Protocol-Version` header) is not - * validated against `supportedProtocolVersions` before reaching this - * check. An unknown future version string must not silently enable - * behavior reserved for versions this transport actually supports. - */ - supportsEmptySSEData(protocolVersion) { - return this._supportedProtocolVersions.includes(protocolVersion) && protocolVersion >= "2025-11-25"; - } - /** - * Writes a priming event to establish resumption capability. - * Only sends if `eventStore` is configured (opt-in for resumability) and - * the client's protocol version supports empty SSE data (a supported - * version that is >= `2025-11-25`). - */ - async writePrimingEvent(controller, encoder, streamId, protocolVersion) { - if (!this._eventStore) return; - if (!this.supportsEmptySSEData(protocolVersion)) return; - const primingEventId = await this._eventStore.storeEvent(streamId, {}); - let primingEvent = `id: ${primingEventId}\ndata: \n\n`; - if (this._retryInterval !== void 0) primingEvent = `id: ${primingEventId}\nretry: ${this._retryInterval}\ndata: \n\n`; - controller.enqueue(encoder.encode(primingEvent)); - } - /** - * Handles `GET` requests for SSE stream - */ - async handleGetRequest(req) { - if (!req.headers.get("accept")?.includes("text/event-stream")) { - this.onerror?.(/* @__PURE__ */ new Error("Not Acceptable: Client must accept text/event-stream")); - return this.createJsonErrorResponse(406, -32e3, "Not Acceptable: Client must accept text/event-stream"); - } - const sessionError = this.validateSession(req); - if (sessionError) return sessionError; - const protocolError = this.validateProtocolVersion(req); - if (protocolError) return protocolError; - if (this._eventStore) { - const lastEventId = req.headers.get("last-event-id"); - if (lastEventId) return this.replayEvents(lastEventId); - } - if (this._streamMapping.get(this._standaloneSseStreamId) !== void 0) { - this.onerror?.(/* @__PURE__ */ new Error("Conflict: Only one SSE stream is allowed per session")); - return this.createJsonErrorResponse(409, -32e3, "Conflict: Only one SSE stream is allowed per session"); - } - const encoder = new TextEncoder(); - let streamController; - let keepAliveTimer; - const readable = new ReadableStream({ - start: (controller) => { - streamController = controller; - }, - cancel: () => { - if (keepAliveTimer !== void 0) clearInterval(keepAliveTimer); - if (this._streamMapping.get(this._standaloneSseStreamId)?.controller === streamController) this._streamMapping.delete(this._standaloneSseStreamId); - } - }); - const headers = { - "Content-Type": "text/event-stream", - "Cache-Control": "no-cache, no-transform", - Connection: "keep-alive", - "X-Accel-Buffering": "no" - }; - if (this.sessionId !== void 0) headers["mcp-session-id"] = this.sessionId; - this._streamMapping.set(this._standaloneSseStreamId, { - controller: streamController, - encoder, - cleanup: () => { - if (keepAliveTimer !== void 0) clearInterval(keepAliveTimer); - this._streamMapping.delete(this._standaloneSseStreamId); - try { - streamController.close(); - } catch {} - } - }); - keepAliveTimer = this.startKeepAlive(streamController, encoder); - return new Response(readable, { headers }); - } - /** - * Replays events that would have been sent after the specified event ID - * Only used when resumability is enabled - */ - async replayEvents(lastEventId) { - if (!this._eventStore) { - this.onerror?.(/* @__PURE__ */ new Error("Event store not configured")); - return this.createJsonErrorResponse(400, -32e3, "Event store not configured"); - } - try { - let streamId; - if (this._eventStore.getStreamIdForEventId) { - streamId = await this._eventStore.getStreamIdForEventId(lastEventId); - if (!streamId) { - this.onerror?.(/* @__PURE__ */ new Error("Invalid event ID format")); - return this.createJsonErrorResponse(400, -32e3, "Invalid event ID format"); - } - if (this._streamMapping.get(streamId) !== void 0) { - this.onerror?.(/* @__PURE__ */ new Error("Conflict: Stream already has an active connection")); - return this.createJsonErrorResponse(409, -32e3, "Conflict: Stream already has an active connection"); - } - } - const headers = { - "Content-Type": "text/event-stream", - "Cache-Control": "no-cache, no-transform", - Connection: "keep-alive", - "X-Accel-Buffering": "no" - }; - if (this.sessionId !== void 0) headers["mcp-session-id"] = this.sessionId; - const encoder = new TextEncoder(); - let streamController; - let keepAliveTimer; - let cancelled = false; - let replayedStreamId; - const readable = new ReadableStream({ - start: (controller) => { - streamController = controller; - }, - cancel: () => { - cancelled = true; - if (keepAliveTimer !== void 0) clearInterval(keepAliveTimer); - if (replayedStreamId !== void 0 && this._streamMapping.get(replayedStreamId)?.controller === streamController) this._streamMapping.delete(replayedStreamId); - } - }); - const replayedEventIds = /* @__PURE__ */ new Set(); - replayedStreamId = await this._eventStore.replayEventsAfter(lastEventId, { send: async (eventId, message) => { - replayedEventIds.add(eventId); - if (!this.writeSSEEvent(streamController, encoder, message, eventId)) try { - streamController.close(); - } catch {} - } }); - if (this._closed || cancelled) { - try { - streamController.close(); - } catch {} - return this.createJsonErrorResponse(404, -32001, "Session not found"); - } - this._streamMapping.get(replayedStreamId)?.cleanup(); - this._streamMapping.set(replayedStreamId, { - controller: streamController, - encoder, - replayedEventIds, - cleanup: () => { - if (keepAliveTimer !== void 0) clearInterval(keepAliveTimer); - this._streamMapping.delete(replayedStreamId); - try { - streamController.close(); - } catch {} - } - }); - if (replayedStreamId !== this._standaloneSseStreamId) { - if (![...this._requestToStreamMapping.values()].includes(replayedStreamId)) { - this._streamMapping.delete(replayedStreamId); - try { - streamController.close(); - } catch {} - } - } - if (this._streamMapping.get(replayedStreamId)?.controller === streamController) keepAliveTimer = this.startKeepAlive(streamController, encoder); - return new Response(readable, { headers }); - } catch (error) { - this.onerror?.(error); - return this.createJsonErrorResponse(500, -32e3, "Error replaying events"); - } - } - /** - * Writes an event to an SSE stream via controller with proper formatting - */ - writeSSEEvent(controller, encoder, message, eventId) { - try { - let eventData = `event: message\n`; - if (eventId) eventData += `id: ${eventId}\n`; - eventData += `data: ${JSON.stringify(message)}\n\n`; - controller.enqueue(encoder.encode(eventData)); - return true; - } catch (error) { - this.onerror?.(error); - return false; - } - } - /** - * Handles unsupported requests (`PUT`, `PATCH`, etc.) - */ - handleUnsupportedRequest() { - this.onerror?.(/* @__PURE__ */ new Error("Method not allowed.")); - return Response.json({ - jsonrpc: "2.0", - error: { - code: -32e3, - message: "Method not allowed." - }, - id: null - }, { - status: 405, - headers: { - Allow: "GET, POST, DELETE", - "Content-Type": "application/json" - } - }); - } - /** - * Handles `POST` requests containing JSON-RPC messages - */ - async handlePostRequest(req, options) { - try { - const acceptHeader = req.headers.get("accept"); - if (!acceptHeader?.includes("application/json") || !acceptHeader.includes("text/event-stream")) { - this.onerror?.(/* @__PURE__ */ new Error("Not Acceptable: Client must accept both application/json and text/event-stream")); - return this.createJsonErrorResponse(406, -32e3, "Not Acceptable: Client must accept both application/json and text/event-stream"); - } - if (!isJsonContentType(req.headers.get("content-type"))) { - this.onerror?.(/* @__PURE__ */ new Error("Unsupported Media Type: Content-Type must be application/json")); - return this.createJsonErrorResponse(415, -32e3, "Unsupported Media Type: Content-Type must be application/json"); - } - const request = req; - let rawMessage; - if (options?.parsedBody === void 0) try { - rawMessage = await req.json(); - } catch (error) { - this.onerror?.(error); - return this.createJsonErrorResponse(400, -32700, "Parse error: Invalid JSON"); - } - else rawMessage = options.parsedBody; - let messages; - try { - messages = Array.isArray(rawMessage) ? rawMessage.map((msg) => JSONRPCMessageSchema.parse(msg)) : [JSONRPCMessageSchema.parse(rawMessage)]; - } catch (error) { - this.onerror?.(error); - return this.createJsonErrorResponse(400, -32700, "Parse error: Invalid JSON-RPC message"); - } - if (this._closed) return this.createJsonErrorResponse(404, -32001, "Session not found"); - const isInitializationRequest = messages.some((element) => isInitializeRequest(element)); - if (isInitializationRequest) { - if (this._initialized && this.sessionId !== void 0) { - this.onerror?.(/* @__PURE__ */ new Error("Invalid Request: Server already initialized")); - return this.createJsonErrorResponse(400, -32600, "Invalid Request: Server already initialized"); - } - if (messages.length > 1) { - this.onerror?.(/* @__PURE__ */ new Error("Invalid Request: Only one initialization request is allowed")); - return this.createJsonErrorResponse(400, -32600, "Invalid Request: Only one initialization request is allowed"); - } - this.sessionId = this.sessionIdGenerator?.(); - this._initialized = true; - if (this.sessionId && this._onsessioninitialized) await Promise.resolve(this._onsessioninitialized(this.sessionId)); - } - if (!isInitializationRequest) { - const sessionError = this.validateSession(req); - if (sessionError) return sessionError; - const protocolError = this.validateProtocolVersion(req); - if (protocolError) return protocolError; - } - if (this._closed) return this.createJsonErrorResponse(404, -32001, "Session not found"); - if (!messages.some((element) => isJSONRPCRequest(element))) { - for (const message of messages) this.onmessage?.(message, { - authInfo: options?.authInfo, - request - }); - return new Response(null, { status: 202 }); - } - const streamId = crypto.randomUUID(); - const initRequest = messages.find((m) => isInitializeRequest(m)); - const clientProtocolVersion = initRequest ? initRequest.params.protocolVersion : req.headers.get("mcp-protocol-version") ?? DEFAULT_NEGOTIATED_PROTOCOL_VERSION; - if (this._enableJsonResponse) return new Promise((resolve) => { - this._streamMapping.set(streamId, { - resolveJson: resolve, - cleanup: () => { - this._streamMapping.delete(streamId); - } - }); - for (const message of messages) if (isJSONRPCRequest(message)) this._requestToStreamMapping.set(message.id, streamId); - for (const message of messages) this.onmessage?.(message, { - authInfo: options?.authInfo, - request - }); - }); - const encoder = new TextEncoder(); - let streamController; - let keepAliveTimer; - const readable = new ReadableStream({ - start: (controller) => { - streamController = controller; - }, - cancel: () => { - if (keepAliveTimer !== void 0) clearInterval(keepAliveTimer); - if (this._streamMapping.get(streamId)?.controller === streamController) this._streamMapping.delete(streamId); - } - }); - const headers = { - "Content-Type": "text/event-stream", - "Cache-Control": "no-cache, no-transform", - Connection: "keep-alive", - "X-Accel-Buffering": "no" - }; - if (this.sessionId !== void 0) headers["mcp-session-id"] = this.sessionId; - for (const message of messages) if (isJSONRPCRequest(message)) { - this._streamMapping.set(streamId, { - controller: streamController, - encoder, - cleanup: () => { - if (keepAliveTimer !== void 0) clearInterval(keepAliveTimer); - this._streamMapping.delete(streamId); - try { - streamController.close(); - } catch {} - } - }); - this._requestToStreamMapping.set(message.id, streamId); - } - await this.writePrimingEvent(streamController, encoder, streamId, clientProtocolVersion); - for (const message of messages) { - let closeSSEStream; - let closeStandaloneSSEStream; - if (isJSONRPCRequest(message) && this._eventStore && this.supportsEmptySSEData(clientProtocolVersion)) { - closeSSEStream = () => { - this.closeSSEStream(message.id); - }; - closeStandaloneSSEStream = () => { - this.closeStandaloneSSEStream(); - }; - } - this.onmessage?.(message, { - authInfo: options?.authInfo, - request, - closeSSEStream, - closeStandaloneSSEStream - }); - } - if (this._streamMapping.get(streamId)?.controller === streamController) keepAliveTimer = this.startKeepAlive(streamController, encoder); - return new Response(readable, { - status: 200, - headers - }); - } catch (error) { - this.onerror?.(error); - return this.createJsonErrorResponse(400, -32700, "Parse error", { data: String(error) }); - } - } - /** - * Handles `DELETE` requests to terminate sessions - */ - async handleDeleteRequest(req) { - const sessionError = this.validateSession(req); - if (sessionError) return sessionError; - const protocolError = this.validateProtocolVersion(req); - if (protocolError) return protocolError; - try { - await Promise.resolve(this._onsessionclosed?.(this.sessionId)); - return new Response(null, { status: 200 }); - } finally { - await this.close(); - } - } - /** - * Validates session ID for non-initialization requests. - * Returns `Response` error if invalid, `undefined` otherwise - */ - validateSession(req) { - if (this.sessionIdGenerator === void 0) return; - if (!this._initialized) { - this.onerror?.(/* @__PURE__ */ new Error("Bad Request: Server not initialized")); - return this.createJsonErrorResponse(400, -32e3, "Bad Request: Server not initialized"); - } - const sessionId = req.headers.get("mcp-session-id"); - if (!sessionId) { - this.onerror?.(/* @__PURE__ */ new Error("Bad Request: Mcp-Session-Id header is required")); - return this.createJsonErrorResponse(400, -32e3, "Bad Request: Mcp-Session-Id header is required"); - } - if (sessionId !== this.sessionId) { - this.onerror?.(/* @__PURE__ */ new Error("Session not found")); - return this.createJsonErrorResponse(404, -32001, "Session not found"); - } - } - /** - * Validates the `MCP-Protocol-Version` header on incoming requests. - * - * For initialization: Version negotiation handles unknown versions gracefully - * (server responds with its supported version). - * - * For subsequent requests with `MCP-Protocol-Version` header: - * - Accept if in supported list - * - 400 if unsupported - * - * For HTTP requests without the `MCP-Protocol-Version` header: - * - Accept and default to the version negotiated at initialization - */ - validateProtocolVersion(req) { - const protocolVersion = req.headers.get("mcp-protocol-version"); - if (protocolVersion !== null && !this._supportedProtocolVersions.includes(protocolVersion)) { - const error = `Bad Request: Unsupported protocol version: ${protocolVersion} (supported versions: ${this._supportedProtocolVersions.join(", ")})`; - this.onerror?.(new Error(error)); - return this.createJsonErrorResponse(400, -32e3, error); - } - } - async close() { - if (this._closed) return; - this._closed = true; - for (const { cleanup } of this._streamMapping.values()) cleanup(); - this._streamMapping.clear(); - this._requestResponseMap.clear(); - this.onclose?.(); - } - /** - * Close an SSE stream for a specific request, triggering client reconnection. - * Use this to implement polling behavior during long-running operations - - * client will reconnect after the retry interval specified in the priming event. - */ - closeSSEStream(requestId) { - const streamId = this._requestToStreamMapping.get(requestId); - if (!streamId) return; - const stream = this._streamMapping.get(streamId); - if (stream) stream.cleanup(); - } - /** - * Close the standalone `GET` SSE stream, triggering client reconnection. - * Use this to implement polling behavior for server-initiated notifications. - */ - closeStandaloneSSEStream() { - const stream = this._streamMapping.get(this._standaloneSseStreamId); - if (stream) stream.cleanup(); - } - async send(message, options) { - let requestId = options?.relatedRequestId; - if (isJSONRPCResultResponse(message) || isJSONRPCErrorResponse(message)) requestId = message.id; - if (requestId === void 0) { - if (isJSONRPCResultResponse(message) || isJSONRPCErrorResponse(message)) throw new Error("Cannot send a response on a standalone SSE stream unless resuming a previous client request"); - let eventId; - if (this._eventStore) eventId = await this._eventStore.storeEvent(this._standaloneSseStreamId, message); - const standaloneSse = this._streamMapping.get(this._standaloneSseStreamId); - if (standaloneSse === void 0) return; - if (standaloneSse.controller && standaloneSse.encoder && (eventId === void 0 || !standaloneSse.replayedEventIds?.has(eventId))) this.writeSSEEvent(standaloneSse.controller, standaloneSse.encoder, message, eventId); - return; - } - const streamId = this._requestToStreamMapping.get(requestId); - if (!streamId) throw new Error(`No connection established for request ID: ${String(requestId)}`); - let stream = this._streamMapping.get(streamId); - if (!this._enableJsonResponse) { - let eventId; - if (this._eventStore) { - eventId = await this._eventStore.storeEvent(streamId, message); - stream = this._streamMapping.get(streamId); - } - if (stream?.controller && stream?.encoder && (eventId === void 0 || !stream.replayedEventIds?.has(eventId))) this.writeSSEEvent(stream.controller, stream.encoder, message, eventId); - } - if (isJSONRPCResultResponse(message) || isJSONRPCErrorResponse(message)) { - this._requestResponseMap.set(requestId, message); - const relatedIds = [...this._requestToStreamMapping.entries()].filter(([_, sid]) => sid === streamId).map(([id]) => id); - if (relatedIds.every((id) => this._requestResponseMap.has(id))) { - if (!stream) { - if (this._enableJsonResponse) throw new Error(`No connection established for request ID: ${String(requestId)}`); - if (!this._eventStore) { - this.onerror?.(/* @__PURE__ */ new Error(`Response for request ID ${String(requestId)} is undeliverable: per-request stream is disconnected and no eventStore is configured`)); - for (const id of relatedIds) { - this._requestResponseMap.delete(id); - this._requestToStreamMapping.delete(id); - } - return; - } - for (const id of relatedIds) { - this._requestResponseMap.delete(id); - this._requestToStreamMapping.delete(id); - } - return; - } - if (this._enableJsonResponse && stream.resolveJson) { - const headers = { "Content-Type": "application/json" }; - if (this.sessionId !== void 0) headers["mcp-session-id"] = this.sessionId; - const responses = relatedIds.map((id) => this._requestResponseMap.get(id)); - if (responses.length === 1) stream.resolveJson(Response.json(responses[0], { - status: 200, - headers - })); - else stream.resolveJson(Response.json(responses, { - status: 200, - headers - })); - stream.cleanup(); - } else stream.cleanup(); - for (const id of relatedIds) { - this._requestResponseMap.delete(id); - this._requestToStreamMapping.delete(id); - } - } - } - } -}; - -//#endregion -//#region src/server/createMcpHandler.ts -/** -* The JSON-RPC id to echo on an entry-built error response: the body's `id` -* when the body is a single JSON-RPC request whose id is a string or number, -* `null` otherwise. Error responses must carry the id of the request they -* correspond to whenever it could be read; `null` is reserved for the cases -* where no single request id is determinable — unparseable bodies, body-less -* methods, notifications, posted responses and batch arrays. -*/ -function echoableRequestId(body) { - if (body === null || typeof body !== "object" || Array.isArray(body)) return null; - const { method, id } = body; - if (typeof method !== "string") return null; - return typeof id === "string" || typeof id === "number" ? id : null; -} -function jsonRpcErrorResponse(httpStatus, code, message, data, id = null) { - return Response.json({ - jsonrpc: "2.0", - error: { - code, - message, - ...data !== void 0 && { data } - }, - id - }, { status: httpStatus }); -} -function rejectionResponse(rejection, id = null) { - return jsonRpcErrorResponse(rejection.httpStatus, rejection.code, rejection.message, rejection.data, id); -} -function toError(value) { - return value instanceof Error ? value : new Error(String(value)); -} -function internalServerErrorResponse(id = null) { - return jsonRpcErrorResponse(500, -32603, "Internal server error", void 0, id); -} -/** -* The entry's default legacy serving (`legacy: 'stateless'`): per-request -* stateless serving of 2025-era traffic using the same factory as the modern -* path. Exported as a standalone building block for hand-wired compositions -* (for example mounting legacy stateless serving on its own route next to a -* strict modern endpoint). -* -* Each POST is served by a fresh instance from the factory connected to a -* fresh streamable HTTP transport constructed with only -* `sessionIdGenerator: undefined` — the established stateless idiom, unchanged. -* Because serving is per-request and stateless, GET and DELETE (2025 session -* operations) are answered with `405` / `Method not allowed.`, exactly like the -* canonical stateless example. -* -* The optional `onerror` callback receives factory and serving failures on -* this leg (reporting only — the response stays the 500 internal-error body). -* The entry passes its own `onerror` here when expanding the default, so -* legacy-leg failures are never silently swallowed. -*/ -function createLegacyStatelessFallback(factory, onerror, keepAliveMs) { - return async (request, options) => { - if (request.method.toUpperCase() !== "POST") return jsonRpcErrorResponse(405, -32e3, "Method not allowed."); - try { - const product = await factory({ - era: "legacy", - ...options?.authInfo !== void 0 && { authInfo: options.authInfo }, - requestInfo: request - }); - const transport = new WebStandardStreamableHTTPServerTransport({ - sessionIdGenerator: void 0, - ...keepAliveMs !== void 0 && { keepAliveMs } - }); - await product.connect(transport); - const teardown = () => { - transport.close().catch(() => {}); - product.close().catch(() => {}); - }; - request.signal?.addEventListener("abort", teardown, { once: true }); - const response = await transport.handleRequest(request, { - ...options?.authInfo !== void 0 && { authInfo: options.authInfo }, - ...options?.parsedBody !== void 0 && { parsedBody: options.parsedBody } - }); - if (response.body === null || mediaTypeEssence(response.headers.get("content-type")) !== "text/event-stream") { - teardown(); - return response; - } - const reader = response.body.getReader(); - let toreDown = false; - const completeExchange = () => { - if (!toreDown) { - toreDown = true; - teardown(); - } - }; - const monitoredBody = new ReadableStream({ - pull: async (controller) => { - try { - const { done, value } = await reader.read(); - if (done) { - completeExchange(); - controller.close(); - return; - } - if (value !== void 0) controller.enqueue(value); - } catch (error) { - completeExchange(); - controller.error(error); - } - }, - cancel: (reason) => { - completeExchange(); - return reader.cancel(reason).catch(() => {}); - } - }); - return new Response(monitoredBody, { - status: response.status, - statusText: response.statusText, - headers: response.headers - }); - } catch (error) { - try { - onerror?.(toError(error)); - } catch {} - return internalServerErrorResponse(echoableRequestId(options?.parsedBody)); - } - }; -} -function legacyStatelessFallback(factory, onerror) { - return createLegacyStatelessFallback(factory, onerror); -} -/** -* The entry's classification step: read the request body exactly once (unless -* a pre-parsed body is supplied) and classify the request with -* {@linkcode classifyInboundRequest}. This is the single code path behind both -* {@linkcode createMcpHandler}'s routing and the exported -* {@linkcode isLegacyRequest} predicate, so the two can never disagree. -* -* Pass `needsForward: false` when the caller never reads `forwardRequest` — -* the body-preserving clone is then skipped and `forwardRequest` is the -* (consumed) input request. -*/ -async function classifyEntryRequest(request, providedParsedBody, needsForward = true) { - const httpMethod = request.method.toUpperCase(); - let body; - let parsedBody = providedParsedBody; - let forwardRequest = request; - let unparseable = false; - if (httpMethod === "POST") { - if (parsedBody === void 0) { - if (needsForward) forwardRequest = request.clone(); - let bodyText; - try { - bodyText = await request.text(); - } catch { - return { step: "unreadable-body" }; - } - try { - body = bodyText.length === 0 ? void 0 : JSON.parse(bodyText); - } catch { - unparseable = true; - } - if (!unparseable && body !== void 0) parsedBody = body; - } else body = parsedBody; - if (unparseable || body === void 0) return { - step: "no-json-body", - forwardRequest - }; - } - return { - step: "classified", - outcome: classifyInboundRequest({ - httpMethod, - protocolVersionHeader: request.headers.get("mcp-protocol-version") ?? void 0, - mcpMethodHeader: request.headers.get("mcp-method") ?? void 0, - mcpNameHeader: request.headers.get("mcp-name") ?? void 0, - ...body !== void 0 && { body } - }), - body, - parsedBody, - forwardRequest - }; -} -/** -* Whether {@linkcode createMcpHandler} would route this request to its legacy -* (2025-era) serving rather than the modern (2026-07-28) path. -* -* Call it with just the request: `await isLegacyRequest(request)`. For a -* `POST` the body is read from an internal clone, so the request you pass -* stays fully readable for whichever handler you route it to — no second -* argument is needed. (In a Node `(req, res)` handler, build that `Request` -* with `toWebRequest(req)` from `@modelcontextprotocol/node`; behind a body -* parser, which has already drained the Node stream, build it as -* `toWebRequest(req, req.body)` so the bytes come from the parsed body — -* either way the predicate still takes just the request.) The optional -* `parsedBody` is a perf escape hatch for a body you already hold parsed: -* pass it and the predicate classifies from the value directly, reading and -* cloning nothing. It is needed, not just faster, when the request's own -* body was already read — the internal clone is then impossible (cloning a -* used body throws a `TypeError`), so such a single-argument call rejects -* instead of guessing. -* -* This is the entry's own classification step exported as a predicate — it -* runs exactly the code `createMcpHandler` runs to make the routing decision, -* not a re-implementation — so a hand-wired composition that branches on it -* can never disagree with the entry. It is classification only: hand-wired -* compositions must validate Content-Type themselves (415 for POSTs whose -* media type is not `application/json`, via {@linkcode isJsonContentType}) -* before dispatching either leg — routing the legacy leg into the SDK -* transports gets their built-in check, but a custom modern leg has none. Use it to keep an existing legacy -* deployment (for example a sessionful streamable HTTP wiring) serving 2025 -* traffic next to a strict modern endpoint, now that the entry has no -* handler-valued `legacy` option: -* -* ```ts -* import { createMcpHandler, isLegacyRequest } from '@modelcontextprotocol/server'; -* -* const modern = createMcpHandler(factory, { legacy: 'reject' }); -* -* export default { -* async fetch(request: Request): Promise { -* if (await isLegacyRequest(request)) { -* // e.g. an existing sessionful WebStandardStreamableHTTPServerTransport wiring -* return myExistingLegacyHandler(request); -* } -* return modern.fetch(request); -* } -* }; -* ``` -* -* Semantics (identical to the entry's routing): -* -* - Returns `true` only for requests with no per-request `_meta` envelope -* claim: claim-less POSTs (including the `initialize` handshake and 2025-era -* notification POSTs without a modern protocol-version header), body-less -* GET/DELETE session operations, all-legacy JSON-RPC batch arrays, posted -* JSON-RPC responses, and POSTs whose body is empty or not valid JSON. -* - Returns `false` for everything the modern path answers, including its -* validation-ladder rejections: a request carrying the envelope claim (even -* one naming a revision the endpoint does not serve — the modern path -* answers it with the unsupported-protocol-version error), a malformed -* envelope behind a present claim (answered `-32602`), a request whose -* `MCP-Protocol-Version` header names a modern revision but that lacks the -* envelope (`-32602`), and header/body mismatches (`-32020`). Consumers -* routing on the predicate must send `false` traffic to the modern handler, -* never to a legacy handler — the modern path owns those error answers. -* - `server/discover` probes sent by negotiating clients always carry the -* envelope claim, so they are never legacy; a hand-built claim-less POST to -* a method named `server/discover` has no claim and classifies legacy, -* exactly as the entry itself routes it. -*/ -async function isLegacyRequest(request, parsedBody) { - const classified = await classifyEntryRequest(parsedBody === void 0 && request.method.toUpperCase() === "POST" ? request.clone() : request, parsedBody, false); - return classified.step === "no-json-body" || classified.step === "classified" && classified.outcome.kind === "legacy"; -} -/** -* Creates an HTTP handler that serves the 2026-07-28 protocol revision from a -* per-request server factory and, by default, falls back to old-school -* stateless serving for 2025-era traffic. Pass `legacy: 'reject'` for a -* modern-only strict endpoint. -* -* Mounting: `handler.fetch` is the web-standard face (Cloudflare Workers, -* Deno, Bun, Hono's `c.req.raw`); for Express/Fastify/plain `node:http`, wrap -* the handler once with `toNodeHandler(handler)` from -* `@modelcontextprotocol/node`. When mounting bare on a fetch-native runtime, -* put Origin/Host validation in front of the handler — the entry itself is -* deliberately validation-free: -* -* ```ts -* import { hostHeaderValidationResponse, originValidationResponse, localhostAllowedHostnames, localhostAllowedOrigins } from '@modelcontextprotocol/server'; -* -* export default { -* async fetch(request: Request): Promise { -* const rejected = -* hostHeaderValidationResponse(request, localhostAllowedHostnames()) ?? -* originValidationResponse(request, localhostAllowedOrigins()); -* return rejected ?? handler.fetch(request); -* } -* }; -* ``` -* -* Use ONE factory for both legs: the same tools/resources/prompts definition -* backs the modern path and the stateless legacy fallback, so the two eras can -* never drift apart. To keep an existing legacy deployment (for example a -* sessionful streamable HTTP wiring) serving 2025 traffic instead of the -* stateless fallback, route in user land with {@linkcode isLegacyRequest} in -* front of a strict handler — see that predicate's documentation for the -* pattern. Power users composing transport-neutral routing can also use the -* exported building blocks directly: {@linkcode classifyInboundRequest} for -* the era decision and `PerRequestHTTPServerTransport` for single-exchange -* serving — such compositions must reject POSTs whose Content-Type media type -* is not `application/json` (415) before parsing the body, using -* {@linkcode isJsonContentType}; neither building block performs this -* validation itself. -* -* The entry performs no token verification: `authInfo` given to `fetch` is -* passed through to handlers and the factory as-is and is never derived from -* request headers. -*/ -function createMcpHandler(factory, options = {}) { - const { legacy, onerror, responseMode } = options; - if (typeof legacy === "function") throw new TypeError("The 'legacy' option only accepts 'stateless' or 'reject', not a handler function. To serve 2025-era traffic with your own handler, route in user land with the exported isLegacyRequest(request) predicate in front of a strict (legacy: 'reject') handler."); - /** Modern per-request instances with an exchange still in flight (close() tears these down). */ - const inflight = /* @__PURE__ */ new Set(); - let closed = false; - const reportError = (error) => { - try { - onerror?.(error); - } catch {} - }; - const bus = options.bus ?? new InMemoryServerEventBus(reportError); - const notify = createServerNotifier(bus); - const listenRouter = createListenRouter({ - bus, - maxSubscriptions: options.maxSubscriptions ?? DEFAULT_MAX_SUBSCRIPTIONS, - keepAliveMs: options.keepAliveMs ?? DEFAULT_SSE_KEEP_ALIVE_MS, - onerror: reportError - }); - if (responseMode === "json") console.warn("responseMode: 'json' drops mid-call notifications. subscriptions/listen streams are always served over SSE regardless; other notifications emitted before a result are dropped."); - const legacyHandler = legacy === "reject" ? void 0 : createLegacyStatelessFallback(factory, reportError, options.keepAliveMs); - async function serveModern(route, request, authInfo) { - const claimedRevision = route.classification.revision; - if (claimedRevision === void 0 || !SUPPORTED_MODERN_PROTOCOL_VERSIONS.includes(claimedRevision)) { - const error = new UnsupportedProtocolVersionError({ - supported: [...SUPPORTED_MODERN_PROTOCOL_VERSIONS], - requested: claimedRevision ?? "unknown" - }); - reportError(error); - return jsonRpcErrorResponse(400, error.code, error.message, error.data, echoableRequestId(route.message)); - } - const stdHeaderRejection = validateStandardRequestHeaders({ - httpMethod: request.method, - mcpMethodHeader: request.headers.get("mcp-method") ?? void 0, - mcpNameHeader: request.headers.get("mcp-name") ?? void 0 - }, route); - if (stdHeaderRejection !== void 0) { - reportError(/* @__PURE__ */ new Error(`Rejected inbound request (${stdHeaderRejection.cell}): ${stdHeaderRejection.message}`)); - return rejectionResponse(stdHeaderRejection, echoableRequestId(route.message)); - } - const meta = route.messageKind === "request" ? requestMetaOf(route.message.params) : void 0; - const declaredClientCapabilities = meta?.[CLIENT_CAPABILITIES_META_KEY]; - if (route.messageKind === "request") { - const required = requiredClientCapabilitiesForRequest(route.message.method); - if (required !== void 0) { - const missing = missingClientCapabilities(required, declaredClientCapabilities); - if (missing !== void 0) { - const error = new MissingRequiredClientCapabilityError({ requiredCapabilities: missing }); - reportError(error); - return jsonRpcErrorResponse(httpStatusForErrorCode(error.code, "ladder"), error.code, error.message, error.data, route.message.id); - } - } - } - const product = await factory({ - era: "modern", - ...authInfo !== void 0 && { authInfo }, - requestInfo: request - }); - const server = product instanceof McpServer ? product.server : product; - if (route.messageKind === "request" && route.message.method === "subscriptions/listen") { - const capabilities = server.getCapabilities(); - const serverInfo = serverIdentityOf(server); - product.close().catch(reportError); - return listenRouter.serve(route.message, request.signal, capabilities, serverInfo); - } - if (route.messageKind === "request" && route.message.method === "tools/call" && product instanceof McpServer) { - const callParams = route.message.params; - const toolName = typeof callParams?.name === "string" ? callParams.name : void 0; - const inputSchema = toolName === void 0 ? void 0 : product.toolInputSchemaJson(toolName); - if (inputSchema !== void 0) { - const scan = scanXMcpHeaderDeclarations(inputSchema); - if (scan.valid && scan.declarations.length > 0) { - const rejection = validateMcpParamHeaders(scan.declarations, callParams?.arguments, request.headers); - if (rejection !== void 0) { - product.close().catch(reportError); - reportError(/* @__PURE__ */ new Error(`Rejected inbound request (${rejection.cell}): ${rejection.message}`)); - return rejectionResponse(rejection, route.message.id); - } - } - } - } - setNegotiatedProtocolVersion(server, claimedRevision); - installModernOnlyHandlers(server, SUPPORTED_MODERN_PROTOCOL_VERSIONS); - if (meta !== void 0) seedClientIdentityFromEnvelope(server, { - clientInfo: meta[CLIENT_INFO_META_KEY], - clientCapabilities: declaredClientCapabilities - }); - const previousOnClose = server.onclose; - inflight.add(server); - server.onclose = () => { - inflight.delete(server); - previousOnClose?.(); - }; - try { - const response = await invoke(product, route.message, { - classification: route.classification, - request, - ...authInfo !== void 0 && { authInfo }, - ...responseMode !== void 0 && { responseMode }, - ...options.keepAliveMs !== void 0 && { keepAliveMs: options.keepAliveMs } - }); - if (route.messageKind === "notification") queueMicrotask(() => void server.close().catch(() => {})); - return response; - } catch (error) { - if (error instanceof SdkError && error.code === SdkErrorCode.ConnectionClosed) return new Response(null, { status: 499 }); - await server.close().catch(() => {}); - inflight.delete(server); - reportError(toError(error)); - return internalServerErrorResponse(echoableRequestId(route.message)); - } - } - async function serveLegacyRoute(route, forwardRequest, authInfo, parsedBody) { - if (legacyHandler !== void 0) return legacyHandler(forwardRequest, { - ...authInfo !== void 0 && { authInfo }, - ...parsedBody !== void 0 && { parsedBody } - }); - const strict = modernOnlyStrictRejection(route, SUPPORTED_MODERN_PROTOCOL_VERSIONS); - if (strict === void 0) return new Response(null, { status: 202 }); - reportError(/* @__PURE__ */ new Error(`Rejected 2025-era request on a modern-only endpoint (${strict.cell}): ${strict.message}`)); - return rejectionResponse(strict, echoableRequestId(parsedBody)); - } - async function handle(request, requestOptions) { - const authInfo = requestOptions?.authInfo; - if (request.method.toUpperCase() === "POST" && !isJsonContentType(request.headers.get("content-type"))) { - reportError(/* @__PURE__ */ new Error("Unsupported Media Type: Content-Type must be application/json")); - return jsonRpcErrorResponse(415, -32e3, "Unsupported Media Type: Content-Type must be application/json"); - } - const classified = await classifyEntryRequest(request, requestOptions?.parsedBody); - if (classified.step === "unreadable-body") return jsonRpcErrorResponse(400, -32700, "Parse error: the request body could not be read"); - if (classified.step === "no-json-body") { - if (legacyHandler !== void 0) return legacyHandler(classified.forwardRequest, { ...authInfo !== void 0 && { authInfo } }); - return jsonRpcErrorResponse(400, -32700, "Parse error: the request body is not valid JSON"); - } - const { outcome, body, parsedBody, forwardRequest } = classified; - try { - switch (outcome.kind) { - case "reject": - reportError(/* @__PURE__ */ new Error(`Rejected inbound request (${outcome.cell}): ${outcome.message}`)); - return rejectionResponse(outcome, echoableRequestId(body)); - case "modern": return await serveModern(outcome, request, authInfo); - case "legacy": return await serveLegacyRoute(outcome, forwardRequest, authInfo, parsedBody); - } - } catch (error) { - reportError(toError(error)); - return internalServerErrorResponse(echoableRequestId(body)); - } - } - const fetchFace = async (request, requestOptions) => { - if (closed) throw new Error("This MCP handler has been closed"); - try { - return await handle(request, requestOptions); - } catch (error) { - reportError(toError(error)); - return internalServerErrorResponse(echoableRequestId(requestOptions?.parsedBody)); - } - }; - return { - fetch: fetchFace, - notify, - bus, - close: async () => { - closed = true; - listenRouter.closeAll(); - const closing = [...inflight].map((server) => server.close().catch(() => {})); - inflight.clear(); - await Promise.all(closing); - } - }; -} - -//#endregion -//#region src/server/middleware/bearerAuth.ts -function headerQuotedValue(value) { - return value.replaceAll(/[\\"]/g, String.raw`\$&`).replaceAll(/[^\u0020-\u007E]/g, " "); -} -function buildWwwAuthenticateHeader(errorCode, description, requiredScopes, resourceMetadataUrl) { - let header = `Bearer error="${headerQuotedValue(errorCode)}", error_description="${headerQuotedValue(description)}"`; - if (requiredScopes.length > 0) header += `, scope="${requiredScopes.join(" ")}"`; - if (resourceMetadataUrl) header += `, resource_metadata="${resourceMetadataUrl}"`; - return header; -} -/** -* Validate a raw `Authorization` header value as a Bearer token and return -* the verified {@link AuthInfo}. -* -* The runtime-neutral core of Bearer authentication: it parses the header, -* runs the verifier, enforces `requiredScopes`, and rejects tokens without an -* expiration or past it. On any failure it throws an {@link OAuthError} — -* pass that to {@link bearerAuthChallengeResponse} for the matching HTTP -* answer, or use {@link requireBearerAuth} to get both steps as one call. -* -* Framework adapters build on this: `requireBearerAuth` from -* `@modelcontextprotocol/express` feeds it `req.headers.authorization`. -*/ -async function verifyBearerToken(authorizationHeader, options) { - const { verifier, requiredScopes = [] } = options; - if (!authorizationHeader) throw new OAuthError(OAuthErrorCode.InvalidToken, "Missing Authorization header"); - const [type, token] = authorizationHeader.split(" "); - if (type?.toLowerCase() !== "bearer" || !token) throw new OAuthError(OAuthErrorCode.InvalidToken, "Invalid Authorization header format, expected 'Bearer TOKEN'"); - const authInfo = await verifier.verifyAccessToken(token); - if (requiredScopes.length > 0) { - if (!requiredScopes.every((scope) => authInfo.scopes.includes(scope))) throw new OAuthError(OAuthErrorCode.InsufficientScope, "Insufficient scope"); - } - if (typeof authInfo.expiresAt !== "number" || Number.isNaN(authInfo.expiresAt)) throw new OAuthError(OAuthErrorCode.InvalidToken, "Token has no expiration time"); - else if (authInfo.expiresAt < Date.now() / 1e3) throw new OAuthError(OAuthErrorCode.InvalidToken, "Token has expired"); - return authInfo; -} -/** -* Build the HTTP answer for a Bearer authentication failure. -* -* Maps an {@link OAuthError} to its status — `401` for `invalid_token` and -* `403` for `insufficient_scope` (both carrying the `WWW-Authenticate: Bearer …` -* challenge, with `resource_metadata` when configured so clients can discover -* the Authorization Server), `500` for `server_error`, `400` for anything -* else. A non-`OAuthError` value answers `500 server_error`. The body is the -* OAuth error JSON. -*/ -function bearerAuthChallengeResponse(error, options) { - const { requiredScopes = [], resourceMetadataUrl } = options ?? {}; - if (!(error instanceof OAuthError)) { - const serverError = new OAuthError(OAuthErrorCode.ServerError, "Internal Server Error"); - return Response.json(serverError.toResponseObject(), { status: 500 }); - } - switch (error.code) { - case OAuthErrorCode.InvalidToken: { - const challenge = buildWwwAuthenticateHeader(error.code, error.message, requiredScopes, resourceMetadataUrl); - return Response.json(error.toResponseObject(), { - status: 401, - headers: { "WWW-Authenticate": challenge } - }); - } - case OAuthErrorCode.InsufficientScope: { - const challenge = buildWwwAuthenticateHeader(error.code, error.message, requiredScopes, resourceMetadataUrl); - return Response.json(error.toResponseObject(), { - status: 403, - headers: { "WWW-Authenticate": challenge } - }); - } - case OAuthErrorCode.ServerError: return Response.json(error.toResponseObject(), { status: 500 }); - default: return Response.json(error.toResponseObject(), { status: 400 }); - } -} -/** -* Require a valid Bearer token on web-standard requests. -* -* The framework-free counterpart of `requireBearerAuth` from -* `@modelcontextprotocol/express`, for hosts whose HTTP surface is a -* `fetch(request)` handler — Cloudflare Workers, Deno, Bun, Hono. The -* returned gate resolves to the verified {@link AuthInfo}, or to the -* ready-to-return challenge `Response` when the request must be refused. -* -* @example -* ```ts source="./bearerAuth.examples.ts#requireBearerAuth_fetchGate" -* const gate = requireBearerAuth({ verifier, requiredScopes: ['mcp'] }); -* -* async function fetchHandler(request: Request): Promise { -* const auth: AuthInfo | Response = await gate(request); -* if (auth instanceof Response) return auth; -* return handler.fetch(request, { authInfo: auth }); -* } -* ``` -*/ -function requireBearerAuth(options) { - const { verifier, requiredScopes = [], resourceMetadataUrl } = options; - const resolved = { - verifier, - requiredScopes, - resourceMetadataUrl - }; - return async (request) => { - const [authorizationHeader] = (request.headers.get("authorization") ?? "").split(","); - try { - return await verifyBearerToken(authorizationHeader || void 0, resolved); - } catch (error) { - return bearerAuthChallengeResponse(error, resolved); - } - }; -} - -//#endregion -//#region src/server/middleware/hostHeaderValidation.ts -/** -* Parse and validate a `Host` header against an allowlist of hostnames (port-agnostic). -* -* - Input host header may include a port (e.g. `localhost:3000`) or IPv6 brackets (e.g. `[::1]:3000`). -* - Allowlist items should be hostnames only (no ports). For IPv6, include brackets (e.g. `[::1]`). -*/ -function validateHostHeader(hostHeader, allowedHostnames) { - if (!hostHeader) return { - ok: false, - errorCode: "missing_host", - message: "Missing Host header" - }; - let hostname; - try { - hostname = new URL(`http://${hostHeader}`).hostname; - } catch { - return { - ok: false, - errorCode: "invalid_host_header", - message: `Invalid Host header: ${hostHeader}`, - hostHeader - }; - } - if (!allowedHostnames.includes(hostname)) return { - ok: false, - errorCode: "invalid_host", - message: `Invalid Host: ${hostname}`, - hostHeader, - hostname - }; - return { - ok: true, - hostname - }; -} -/** -* Convenience allowlist for `localhost` DNS rebinding protection. -*/ -function localhostAllowedHostnames() { - return [ - "localhost", - "127.0.0.1", - "[::1]" - ]; -} -/** -* Web-standard `Request` helper for DNS rebinding protection. -* @example -* ```ts source="./hostHeaderValidation.examples.ts#hostHeaderValidationResponse_basicUsage" -* const result = validateHostHeader(req.headers.get('host'), ['localhost']); -* ``` -*/ -function hostHeaderValidationResponse(req, allowedHostnames) { - const result = validateHostHeader(req.headers.get("host"), allowedHostnames); - if (result.ok) return void 0; - return Response.json({ - jsonrpc: "2.0", - error: { - code: -32e3, - message: result.message - }, - id: null - }, { - status: 403, - headers: { "Content-Type": "application/json" } - }); -} - -//#endregion -//#region src/server/middleware/oauthMetadata.ts -function checkIssuerUrl(issuer, allowInsecure) { - if (issuer.protocol !== "https:" && issuer.hostname !== "localhost" && issuer.hostname !== "127.0.0.1" && !allowInsecure) throw new Error("Issuer URL must be HTTPS"); - if (issuer.hash) throw new Error(`Issuer URL must not have a fragment: ${issuer}`); - if (issuer.search) throw new Error(`Issuer URL must not have a query string: ${issuer}`); -} -/** -* Derive the RFC 9728 Protected Resource Metadata document from -* {@link AuthMetadataOptions}, validating the Authorization Server issuer URL -* (HTTPS required outside localhost) in the process. -* -* `oauthMetadataResponse` and the Express `mcpAuthMetadataRouter` both build -* on this; use it directly when serving the document through your own -* routing — or call it once at startup to fail fast on a misconfigured -* issuer before any request arrives. -*/ -function buildOAuthProtectedResourceMetadata(options) { - checkIssuerUrl(new URL(options.oauthMetadata.issuer), options.dangerouslyAllowInsecureIssuerUrl); - return { - resource: options.resourceServerUrl.href, - authorization_servers: [options.oauthMetadata.issuer], - scopes_supported: options.scopesSupported, - resource_name: options.resourceName, - resource_documentation: options.serviceDocumentationUrl?.href - }; -} -/** -* Builds the RFC 9728 Protected Resource Metadata URL for a given MCP server -* URL by inserting `/.well-known/oauth-protected-resource` ahead of the path. -* -* @example -* ```ts -* getOAuthProtectedResourceMetadataUrl(new URL('https://api.example.com/mcp')) -* // → 'https://api.example.com/.well-known/oauth-protected-resource/mcp' -* ``` -*/ -function getOAuthProtectedResourceMetadataUrl(serverUrl) { - return new URL(protectedResourceMetadataPath(serverUrl), serverUrl).href; -} -/** The RFC 9728 path-aware well-known path for a resource URL. */ -function protectedResourceMetadataPath(resourceServerUrl) { - const rsPath = stripTrailingSlash(resourceServerUrl.pathname); - return `/.well-known/oauth-protected-resource${rsPath === "/" ? "" : rsPath}`; -} -function stripTrailingSlash(path) { - return path.length > 1 && path.endsWith("/") ? path.slice(0, -1) : path; -} -const ALLOWED_METHODS = "GET, HEAD, OPTIONS"; -function metadataDocumentResponse(request, metadata) { - if (request.method === "OPTIONS") { - const requestedHeaders = request.headers.get("access-control-request-headers"); - return new Response(null, { - status: 204, - headers: { - "Access-Control-Allow-Origin": "*", - "Access-Control-Allow-Methods": ALLOWED_METHODS, - ...requestedHeaders === null ? {} : { - "Access-Control-Allow-Headers": requestedHeaders, - Vary: "Access-Control-Request-Headers" - } - } - }); - } - if (request.method !== "GET" && request.method !== "HEAD") { - const error = new OAuthError(OAuthErrorCode.MethodNotAllowed, `The method ${request.method} is not allowed for this endpoint`); - return Response.json(error.toResponseObject(), { - status: 405, - headers: { - Allow: ALLOWED_METHODS, - "Access-Control-Allow-Origin": "*" - } - }); - } - const response = Response.json(metadata, { headers: { "Access-Control-Allow-Origin": "*" } }); - return request.method === "HEAD" ? new Response(null, { - status: response.status, - headers: response.headers - }) : response; -} -/** -* Serve the two OAuth discovery documents an MCP server acting as a Resource -* Server exposes, from a web-standard `fetch(request)` handler: -* -* - `/.well-known/oauth-protected-resource[/]` — RFC 9728 Protected -* Resource Metadata, derived from the supplied options (path-aware: the -* resource URL's path is reflected in the route). -* - `/.well-known/oauth-authorization-server` — RFC 8414 Authorization -* Server Metadata, passed through verbatim. -* -* Returns the matched document `Response` (JSON with permissive CORS, `405` -* with an `Allow` header for non-GET methods, `204` for CORS preflight), or -* `undefined` when the request path is neither well-known route — fall -* through to your own routing. The framework-free counterpart of -* `mcpAuthMetadataRouter` from `@modelcontextprotocol/express`; pair it with -* `requireBearerAuth` and `getOAuthProtectedResourceMetadataUrl` so -* unauthenticated clients can discover the AS from the `401` challenge. -* -* @example -* ```ts source="./oauthMetadata.examples.ts#oauthMetadataResponse_fetchHandler" -* async function fetchHandler(request: Request): Promise { -* return oauthMetadataResponse(request, options) ?? serveMcp(request); -* } -* ``` -*/ -function oauthMetadataResponse(request, options) { - const requestPath = stripTrailingSlash(new URL(request.url).pathname); - if (requestPath === protectedResourceMetadataPath(options.resourceServerUrl)) return metadataDocumentResponse(request, buildOAuthProtectedResourceMetadata(options)); - if (requestPath === "/.well-known/oauth-authorization-server") { - buildOAuthProtectedResourceMetadata(options); - return metadataDocumentResponse(request, options.oauthMetadata); - } -} - -//#endregion -//#region src/server/middleware/originValidation.ts -/** -* Validate an `Origin` header against an allowlist of hostnames (port-agnostic). -* -* - A missing/empty `Origin` header passes: non-browser clients do not send one, -* and only browser-originated requests carry the header this check defends against. -* - Allowlist items are hostnames only (no scheme, no port), the same convention as -* `validateHostHeader`. For IPv6, include brackets (e.g. `[::1]`). -* - Any present value that cannot be parsed as an origin URL — including the literal -* `null` origin browsers send for opaque contexts — is rejected (deny on failure). -*/ -function validateOriginHeader(originHeader, allowedOriginHostnames) { - if (originHeader === null || originHeader === void 0 || originHeader === "") return { ok: true }; - let hostname; - try { - hostname = new URL(originHeader).hostname; - } catch { - return { - ok: false, - errorCode: "invalid_origin_header", - message: `Invalid Origin header: ${originHeader}`, - originHeader - }; - } - if (hostname === "") return { - ok: false, - errorCode: "invalid_origin_header", - message: `Invalid Origin header: ${originHeader}`, - originHeader - }; - if (!allowedOriginHostnames.includes(hostname)) return { - ok: false, - errorCode: "invalid_origin", - message: `Invalid Origin: ${hostname}`, - originHeader, - hostname - }; - return { - ok: true, - origin: originHeader, - hostname - }; -} -/** -* Convenience allowlist of localhost-class origin hostnames, mirroring -* `localhostAllowedHostnames`. -*/ -function localhostAllowedOrigins() { - return [ - "localhost", - "127.0.0.1", - "[::1]" - ]; -} -/** -* Web-standard `Request` helper for Origin validation: returns a `403` JSON-RPC -* error response when the request's `Origin` header is not allowed, and -* `undefined` when the request may proceed. -* -* ```ts -* const rejected = originValidationResponse(request, localhostAllowedOrigins()); -* if (rejected) return rejected; -* ``` -*/ -function originValidationResponse(req, allowedOriginHostnames) { - const result = validateOriginHeader(req.headers.get("origin"), allowedOriginHostnames); - if (result.ok) return void 0; - return Response.json({ - jsonrpc: "2.0", - error: { - code: -32e3, - message: result.message - }, - id: null - }, { - status: 403, - headers: { "Content-Type": "application/json" } - }); -} - -//#endregion -//#region src/server/requestStateCodec.ts -const PREFIX = "v1."; -function bytesToBase64Url(bytes) { - let bin = ""; - for (const b of bytes) bin += String.fromCodePoint(b); - return btoa(bin).replaceAll("+", "-").replaceAll("/", "_").replace(/=+$/, ""); -} -function constantTimeTagEqual(a, b) { - if (a.length !== b.length) return false; - let r = 0; - for (let i = 0; i < a.length; i++) r |= a.codePointAt(i) ^ b.codePointAt(i); - return r === 0; -} -function base64UrlToBytes(s) { - const b64 = s.replaceAll("-", "+").replaceAll("_", "/"); - const bin = atob(b64); - const bytes = new Uint8Array(bin.length); - for (let i = 0; i < bin.length; i++) bytes[i] = bin.codePointAt(i); - return bytes; -} -/** -* Create an opt-in HMAC-SHA256 codec for the multi-round-trip `requestState` -* (protocol revision 2026-07-28). -* -* `requestState` round-trips through the client and is attacker-controlled -* input on re-entry. The SDK applies no protection of its own; this helper is -* the convenience implementation of the spec's integrity MUST so authors don't -* hand-roll HMAC. Wire shape: -* -* "v1." b64url({"p":,"exp":,"b":?}) "." b64url(mac) -* -* where `bindTag` is `b64url(HMAC(key, "mcp.requestState.bind:" + bind(ctx))[:16])` -* — the binding value is never embedded raw. -* -* The codec is **signed, not encrypted**: the body is integrity-protected but -* the client can base64url-decode it and read the payload (`p`) in clear. Do -* not put secrets in the payload; use an AEAD construction if confidentiality -* is required. The handler reads its payload back via the typed -* `ctx.mcpReq.requestState()` accessor — the seam has already run `verify` -* (integrity proven, payload decoded) by the time the handler is entered. -* -* Verification is fail-closed and constant-time (WebCrypto `subtle.verify` for -* the body MAC; a fixed-length XOR-accumulator compare for the bind tag). -* See `examples/mrtr/server.ts` for a worked end-to-end example. -* -* Design comparison (mcp.d `secureRequestState`, the peer SDK's reference -* implementation): mcp.d additionally offers an AES-256-GCM encrypted mode and -* derives independent cipher / bind-HMAC sub-keys from the operator secret via -* HKDF-SHA256, with an auto-generated per-process ephemeral key when none is -* supplied. This codec deliberately ships only the signed mode and a single -* keyed HMAC (domain-separated by input prefix) — HKDF sub-key derivation and -* an encrypted mode are intentionally out of scope for the initial release. -*/ -function createRequestStateCodec(options) { - const subtle = globalThis.crypto?.subtle; - if (subtle === void 0) throw new TypeError("createRequestStateCodec requires the Web Crypto API (globalThis.crypto.subtle); see https://ts.sdk.modelcontextprotocol.io/v2/troubleshooting for the Node.js polyfill instructions"); - const keyBytes = typeof options.key === "string" ? new TextEncoder().encode(options.key) : Uint8Array.from(options.key); - if (keyBytes.byteLength < 32) throw new RangeError(`createRequestStateCodec: key must be at least 32 bytes (got ${keyBytes.byteLength})`); - const ttlSeconds = options.ttlSeconds ?? 600; - if (!Number.isFinite(ttlSeconds)) throw new RangeError("createRequestStateCodec: ttlSeconds must be a finite number"); - const bind = options.bind; - let cryptoKey; - const importedKey = () => cryptoKey ??= subtle.importKey("raw", keyBytes, { - name: "HMAC", - hash: "SHA-256" - }, false, ["sign", "verify"]); - const utf8 = new TextEncoder(); - const BIND_LABEL = "mcp.requestState.bind:"; - const bindTag = async (value) => { - return bytesToBase64Url(new Uint8Array(await subtle.sign("HMAC", await importedKey(), utf8.encode(BIND_LABEL + value))).slice(0, 16)); - }; - return { - async mint(payload, ctx) { - const envelope = { - p: payload, - exp: Math.floor(Date.now() / 1e3) + ttlSeconds - }; - if (bind !== void 0) { - if (ctx === void 0) throw new TypeError("createRequestStateCodec: mint() requires ctx when a bind callback is configured"); - envelope.b = await bindTag(bind(ctx)); - } - const body = bytesToBase64Url(utf8.encode(JSON.stringify(envelope))); - return `${PREFIX}${body}.${bytesToBase64Url(new Uint8Array(await subtle.sign("HMAC", await importedKey(), utf8.encode(PREFIX + body))))}`; - }, - async verify(state, ctx) { - const dot = state.lastIndexOf("."); - if (!state.startsWith(PREFIX) || dot <= 3) throw new Error("malformed"); - const body = state.slice(3, dot); - let macBytes; - try { - macBytes = base64UrlToBytes(state.slice(dot + 1)); - } catch { - throw new Error("malformed"); - } - if (!await subtle.verify("HMAC", await importedKey(), macBytes, utf8.encode(PREFIX + body))) throw new Error("mac"); - let envelope; - try { - envelope = JSON.parse(new TextDecoder("utf-8", { fatal: true }).decode(base64UrlToBytes(body))); - } catch { - throw new Error("malformed"); - } - if (typeof envelope.exp !== "number" || envelope.exp < Math.floor(Date.now() / 1e3)) throw new Error("expired"); - if (bind !== void 0) { - const expected = await bindTag(bind(ctx)); - if (envelope.b === void 0 || !constantTimeTagEqual(envelope.b, expected)) throw new Error("bind"); - } else if (envelope.b !== void 0) throw new Error("bind"); - return envelope.p; - } - }; -} - -//#endregion -//#region src/fromJsonSchema.ts -let _defaultValidator; -function dist_fromJsonSchema(schema, validator) { - return fromJsonSchema$1(schema, validator ?? (_defaultValidator ??= new DefaultJsonSchemaValidator())); -} - -//#endregion - -//# sourceMappingURL=index.mjs.map -const mcpApps = Object.freeze([]); - -/* export default */ const mcp_status_073c1634_0 = (mcpApps); - -// Generated by agent-bundle. Do not edit. -const meta_name = "mcp-app-example"; -const packageName = "@agent-bundle-example/mcp-app"; -const packageVersion = undefined; -const meta_version = "1.0.0"; -const meta_meta = Object.freeze({ - name: meta_name, - packageName: packageName, - packageVersion: packageVersion, - version: meta_version -}); -/* export default */ const _agent_bundle_virtual_meta = ((/* unused pure expression or super */ null && (meta_meta))); - -const healthyCompilerStatus = Object.freeze({ - checks: Object.freeze([ - Object.freeze({ - label: 'Availability', - status: 'passing' - }), - Object.freeze({ - label: 'Build queue', - status: 'passing' - }) - ]), - service: 'compiler', - status: 'healthy', - summary: 'Compiler service is ready for release.' -}); -const isRecord = (value)=>value !== null && typeof value === 'object' && !Array.isArray(value); -const isHealthyCompilerFixture = (value)=>{ - if (!isRecord(value) || value.service !== healthyCompilerStatus.service || value.status !== healthyCompilerStatus.status || value.summary !== healthyCompilerStatus.summary || !Array.isArray(value.checks) || value.checks.length !== healthyCompilerStatus.checks.length) { - return false; - } - return healthyCompilerStatus.checks.every((expected, index)=>{ - const received = value.checks[index]; - return isRecord(received) && received.label === expected.label && received.status === expected.status; - }); -}; - - - - - - -const app = mcp_status_073c1634_0["0"]; -if (app === undefined) throw new Error('Expected the status MCP App.'); -const serviceCatalog = Object.freeze({ - compiler: healthyCompilerStatus, - 'payments-api': Object.freeze({ - checks: Object.freeze([ - Object.freeze({ - label: 'Availability', - status: 'passing' - }), - Object.freeze({ - label: 'P95 latency', - status: 'failing' - }) - ]), - service: 'payments-api', - status: 'degraded', - summary: 'Payment latency is above the release threshold.' - }) -}); -const createStatusServer = ()=>{ - // The compiler stamps this project's identity into `agent-bundle/meta`, so - // the wire identity cannot drift from the config or package.json. - const server = new mcp_DXXb3Vv3_McpServer({ - name: meta_name, - version: (/* inlined export .version */"1.0.0") - }); - server.registerResource(app.name, app.resourceUri, { - _meta: { - ui: { - resourceUri: app.resourceUri - } - }, - mimeType: app.mimeType - }, async (uri)=>({ - contents: [ - { - mimeType: app.mimeType, - text: app.html, - uri: uri.href - } - ] - })); - server.registerTool('show-status', { - _meta: { - ui: { - resourceUri: app.resourceUri - } - }, - description: 'Show the health of one example service.', - inputSchema: schemas_object({ - service: schemas_enum([ - 'compiler', - 'payments-api' - ]) - }) - }, async ({ service })=>{ - const result = serviceCatalog[service]; - return { - _meta: { - ui: { - resourceUri: app.resourceUri - } - }, - content: [ - { - text: result.summary, - type: 'text' - } - ], - structuredContent: result - }; - }); - return server; -}; -/** - * Default-exported server factory: `agent-bundle build` detects it and wraps - * this entry in the framework stdio lifecycle shell (console-to-stderr guard, - * SIGINT/SIGTERM handling, stdin-EOF exit, bounded shutdown, heartbeat). - */ /* export default */ const mcp_status = (createStatusServer); - - - - - -//#region src/server/stdio.ts -/** -* Server transport for stdio: this communicates with an MCP client by reading from the current process' `stdin` and writing to `stdout`. -* -* This transport is only available in Node.js environments. -* -* @example -* ```ts source="./stdio.examples.ts#StdioServerTransport_basicUsage" -* const server = new McpServer({ name: 'my-server', version: '1.0.0' }); -* const transport = new StdioServerTransport(); -* await server.connect(transport); -* ``` -*/ -var stdio_StdioServerTransport = class { - _readBuffer; - _started = false; - _closed = false; - constructor(_stdin = node_process.stdin, _stdout = node_process.stdout, options) { - this._stdin = _stdin; - this._stdout = _stdout; - this._readBuffer = new ReadBuffer({ maxBufferSize: options?.maxBufferSize }); - } - onclose; - onerror; - onmessage; - _ondata = (chunk) => { - try { - this._readBuffer.append(chunk); - this.processReadBuffer(); - } catch (error) { - this.onerror?.(error); - this.close().catch(() => {}); - } - }; - _onerror = (error) => { - this.onerror?.(error); - }; - _onstdouterror = (error) => { - this.onerror?.(error); - this.close().catch(() => {}); - }; - /** - * Starts listening for messages on `stdin`. - */ - async start() { - if (this._started) throw new Error("StdioServerTransport already started! If using Server class, note that connect() calls start() automatically."); - this._started = true; - this._stdin.on("data", this._ondata); - this._stdin.on("error", this._onerror); - this._stdout.on("error", this._onstdouterror); - } - processReadBuffer() { - while (true) try { - const message = this._readBuffer.readMessage(); - if (message === null) break; - this.onmessage?.(message); - } catch (error) { - this.onerror?.(error); - } - } - async close() { - if (this._closed) return; - this._closed = true; - this._stdin.off("data", this._ondata); - this._stdin.off("error", this._onerror); - this._stdout.off("error", this._onstdouterror); - if (this._stdin.listenerCount("data") === 0) this._stdin.pause(); - this._readBuffer.clear(); - this.onclose?.(); - } - send(message) { - if (this._closed) return Promise.reject(/* @__PURE__ */ new Error("StdioServerTransport is closed")); - return new Promise((resolve, reject) => { - const json = serializeMessage(message); - let settled = false; - const onError = (error) => { - if (settled) return; - settled = true; - this._stdout.off("error", onError); - this._stdout.off("drain", onDrain); - reject(error); - }; - const onDrain = () => { - if (settled) return; - settled = true; - this._stdout.off("error", onError); - this._stdout.off("drain", onDrain); - resolve(); - }; - this._stdout.once("error", onError); - if (this._stdout.write(json)) { - if (settled) return; - settled = true; - this._stdout.off("error", onError); - resolve(); - } else if (!settled) this._stdout.once("drain", onDrain); - }); - } -}; - -//#endregion -//#region src/server/serveStdio.ts -/** -* How long the probe-discard path waits for the probe instance to answer the -* requests it was delivered before closing it. The wait normally settles as -* soon as the DiscoverResult is handed to the wire (or immediately, when a -* delivered cancellation already settled the probe); the bound is a backstop -* so no edge can ever hold the connection's inbound pump indefinitely behind -* the discard. -*/ -const DISCARD_ANSWER_TIMEOUT_MS = 3e3; -/** -* The transport a pinned instance is connected to: a thin channel that writes -* through to the entry-owned wire transport and receives the messages the -* entry forwards. The wire transport itself is never handed to an instance — -* that is what lets the entry discard an optimistic probe instance (close the -* channel) without tearing down the connection. -*/ -var StdioConnectionChannel = class { - onclose; - onerror; - onmessage; - _closed = false; - /** Request ids the entry delivered to the instance that the instance has not yet answered. */ - _pendingRequests = /* @__PURE__ */ new Set(); - _drainWaiters = []; - constructor(_wire, _onInstanceClose, _outboundIntercept) { - this._wire = _wire; - this._onInstanceClose = _onInstanceClose; - this._outboundIntercept = _outboundIntercept; - } - async start() {} - async send(message, options) { - if (isJSONRPCResultResponse(message) || isJSONRPCErrorResponse(message)) { - const { id } = message; - if (id !== void 0) this._settle(id); - } - if (this._closed) return; - if (this._outboundIntercept?.(message) === "handled") return; - return this._wire.send(message, options); - } - setProtocolVersion = (version) => { - this._wire.setProtocolVersion?.(version); - }; - /** Forwards one inbound message to the connected instance. */ - deliver(message, extra) { - if (this._closed) return; - if (isJSONRPCRequest(message)) this._pendingRequests.add(message.id); - else if (isJSONRPCNotification(message) && message.method === "notifications/cancelled") { - const cancelledId = message.params?.requestId; - if (cancelledId !== void 0) this._settle(cancelledId); - } - this.onmessage?.(message, extra); - } - /** - * Resolves once every request delivered to the instance has been answered - * through {@linkcode send}, settled by a delivered cancellation, or the - * channel has been closed and nothing further can be answered. The wait is - * bounded by `timeoutMs` as a backstop so no edge can hold the caller - * indefinitely; resolves `false` only when the bound elapsed with requests - * still unanswered. Used by the probe-discard path so a probe request the - * entry accepted is never silently dropped. - */ - async whenRequestsAnswered(timeoutMs) { - if (this._closed || this._pendingRequests.size === 0) return true; - return await new Promise((resolve) => { - const waiter = () => { - clearTimeout(timer); - resolve(true); - }; - const timer = setTimeout(() => { - this._drainWaiters = this._drainWaiters.filter((pending) => pending !== waiter); - resolve(false); - }, timeoutMs); - this._drainWaiters.push(waiter); - }); - } - async close() { - if (this._closed) return; - this._closed = true; - this._pendingRequests.clear(); - this._releaseDrainWaiters(); - try { - this._onInstanceClose(); - } finally { - this.onclose?.(); - } - } - _settle(id) { - this._pendingRequests.delete(id); - if (this._pendingRequests.size === 0) this._releaseDrainWaiters(); - } - _releaseDrainWaiters() { - const waiters = this._drainWaiters; - this._drainWaiters = []; - for (const waiter of waiters) waiter(); - } -}; -/** -* Classifies one message of the opening exchange with the same body-primary -* rules the HTTP entry applies per request: `initialize` is the legacy -* handshake unless it carries a valid modern envelope claim; a present claim -* is validated (never silently ignored); a claim-less message is 2025-era -* traffic. There is no header layer on stdio, so the body is the only signal. -*/ -function classifyOpeningMessage(message) { - const params = message.params; - if (message.method === "initialize" && !carriesValidModernEnvelopeClaim(params)) { - const requestedVersion = params !== null && typeof params === "object" && typeof params.protocolVersion === "string" ? params.protocolVersion : void 0; - return { - kind: "legacy", - reason: "initialize", - ...requestedVersion !== void 0 && { requestedVersion } - }; - } - if (!hasEnvelopeClaim(params)) return { - kind: "legacy", - reason: "no-claim" - }; - const meta = requestMetaOf(params); - const firstIssue = (meta === void 0 ? [] : validateEnvelopeMeta(meta))[0]; - if (firstIssue !== void 0) return { - kind: "invalid-envelope", - issue: firstIssue - }; - const claimedVersion = envelopeClaimVersion(params); - if (claimedVersion === void 0 || !SUPPORTED_MODERN_PROTOCOL_VERSIONS.includes(claimedVersion)) return { - kind: "unsupported-revision", - requested: claimedVersion ?? "unknown" - }; - return { - kind: "modern", - revision: claimedVersion, - classification: { - era: "modern", - revision: claimedVersion - } - }; -} -/** -* Serves MCP over stdio from a server factory, owning the era decision for -* the connection: the opening exchange selects the era, ONE instance from the -* factory is pinned for the connection lifetime, and everything after passes -* straight through to it. See the module documentation for the opening rules. -* -* ```ts -* import { serveStdio } from '@modelcontextprotocol/server/stdio'; -* -* serveStdio(() => { -* const server = new McpServer({ name: 'my-server', version: '1.0.0' }, { capabilities: { tools: {} } }); -* // register tools/resources/prompts once — the same factory serves both eras -* return server; -* }); -* ``` -*/ -function serveStdio(factory, options = {}) { - const legacyMode = options.legacy ?? "serve"; - const wire = options.transport ?? new stdio_StdioServerTransport(); - let state = { phase: "opening" }; - /** Channel currently being discarded (its close must not tear the connection down). */ - let discarding; - let closing = false; - /** - * Whether the connection has been torn down (`handle.close()` or the wire - * closing). The opening arms re-check this after every await: a close can - * race factory construction, and the continuation must neither resurrect - * the connection state nor keep a late-resolved instance around. - */ - const isTornDown = () => closing || state.phase === "closed"; - const reportError = (error) => { - try { - options.onerror?.(error); - } catch {} - }; - const writeErrorResponse = (id, code, message, data) => wire.send({ - jsonrpc: "2.0", - id, - error: { - code, - message, - ...data !== void 0 && { data } - } - }).catch((error) => reportError(stdio_toError(error))); - /** - * Entry-handled `subscriptions/listen` for this connection: holds the - * active subscriptions, serves inbound listen / cancelled-of-listen - * before the pinned instance is consulted, and rewrites the instance's - * outbound change notifications onto the active subscriptions. Only - * consulted on a modern-pinned connection — on a legacy connection - * change notifications pass straight through (the 2025 unsolicited - * delivery model is unchanged). - */ - const listenRouter = new StdioListenRouter(options.maxSubscriptions ?? DEFAULT_MAX_SUBSCRIPTIONS); - /** Outbound intercept installed on a modern instance's channel. */ - const modernOutboundIntercept = (message) => { - if (!isJSONRPCNotification(message)) return void 0; - const routed = listenRouter.routeOutbound(message); - if (routed === "passthrough") return void 0; - for (const stamped of routed) wire.send({ - jsonrpc: "2.0", - ...stamped - }).catch((error) => reportError(stdio_toError(error))); - return "handled"; - }; - /** - * Entry-handled inbound listen routing for a modern-pinned connection. - * Returns `true` when the message was served at the entry and must NOT - * be delivered to the pinned instance. - */ - const tryServeListen = async (message) => { - if (isJSONRPCRequest(message) && message.method === "subscriptions/listen") { - const meta = requestMetaOf(message.params); - const issue = hasEnvelopeClaim(message.params) ? (meta === void 0 ? [] : validateEnvelopeMeta(meta))[0] : { - key: "_meta", - problem: "the per-request envelope is required on protocol revision 2026-07-28" - }; - const claimedVersion = envelopeClaimVersion(message.params); - let reply; - if (issue !== void 0) reply = { - jsonrpc: "2.0", - id: message.id, - error: { - code: -32602, - message: `Invalid _meta envelope: ${issue.key}: ${issue.problem}` - } - }; - else if (claimedVersion === void 0 || !SUPPORTED_MODERN_PROTOCOL_VERSIONS.includes(claimedVersion)) { - const error = new UnsupportedProtocolVersionError({ - supported: [...SUPPORTED_MODERN_PROTOCOL_VERSIONS], - requested: claimedVersion ?? "unknown" - }); - reply = { - jsonrpc: "2.0", - id: message.id, - error: { - code: error.code, - message: error.message, - data: error.data - } - }; - } else reply = listenRouter.serve(message); - await wire.send("error" in reply ? reply : { - jsonrpc: "2.0", - method: reply.method, - params: reply.params - }).catch((error) => reportError(stdio_toError(error))); - return true; - } - if (isJSONRPCNotification(message) && message.method === "notifications/cancelled") { - const cancelledId = message.params?.requestId; - if (cancelledId !== void 0 && listenRouter.cancel(cancelledId)) return true; - } - return false; - }; - /** Answers a 2025-era request the entry will not serve (the modern-only rejection cells). */ - const answerLegacyRejection = (request, reason, requestedVersion) => { - const rejection = modernOnlyStrictRejection({ - kind: "legacy", - reason, - ...requestedVersion !== void 0 && { requestedVersion } - }, SUPPORTED_MODERN_PROTOCOL_VERSIONS); - if (rejection === void 0) return Promise.resolve(); - reportError(/* @__PURE__ */ new Error(`Rejected 2025-era request on a modern-only stdio connection (${rejection.cell}): ${rejection.message}`)); - return writeErrorResponse(request.id, rejection.code, rejection.message, rejection.data); - }; - const onInstanceClosed = (channel) => { - if (closing || channel === discarding) return; - closeAll(); - }; - const connectInstance = async (era, revision) => { - const product = await factory({ era }); - const server = product instanceof McpServer ? product.server : product; - if (era === "modern") { - setNegotiatedProtocolVersion(server, revision); - installModernOnlyHandlers(server, SUPPORTED_MODERN_PROTOCOL_VERSIONS); - listenRouter.setServerCapabilities(server.getCapabilities(), serverIdentityOf(server)); - } - const channel = new StdioConnectionChannel(wire, () => onInstanceClosed(channel), era === "modern" ? modernOutboundIntercept : void 0); - await product.connect(channel); - return { - product, - channel - }; - }; - /** Closes an instance whose factory resolved only after the connection was torn down. */ - const disposeLateInstance = (instance) => instance.product.close().catch((error) => reportError(stdio_toError(error))); - const discardProbeInstance = async (instance) => { - discarding = instance.channel; - try { - if (!await instance.channel.whenRequestsAnswered(DISCARD_ANSWER_TIMEOUT_MS)) reportError(/* @__PURE__ */ new Error(`Discarded the probe instance with requests still unanswered after ${DISCARD_ANSWER_TIMEOUT_MS}ms; continuing with the fallback`)); - await instance.product.close(); - } catch (error) { - reportError(stdio_toError(error)); - } finally { - discarding = void 0; - } - }; - const processMessage = async (message) => { - if (state.phase === "closed") return; - if (state.phase === "pinned") { - if (state.era === "modern" && isJSONRPCRequest(message) && message.method === "initialize" && !carriesValidModernEnvelopeClaim(message.params)) { - await answerLegacyRejection(message, "initialize", message.params !== null && typeof message.params === "object" && typeof message.params.protocolVersion === "string" ? message.params.protocolVersion : void 0); - return; - } - if (state.era === "modern" && await tryServeListen(message)) return; - state.instance.channel.deliver(message); - return; - } - if (!isJSONRPCRequest(message) && !isJSONRPCNotification(message)) { - reportError(/* @__PURE__ */ new Error("Discarded a JSON-RPC response received before the connection negotiated an era")); - return; - } - const opening = classifyOpeningMessage(message); - switch (opening.kind) { - case "invalid-envelope": { - const detail = `Invalid _meta envelope for protocol revision 2026-07-28: ${opening.issue.key}: ${opening.issue.problem}`; - if (isJSONRPCRequest(message)) await writeErrorResponse(message.id, ProtocolErrorCode.InvalidParams, detail, { envelope: opening.issue }); - else reportError(/* @__PURE__ */ new Error(`Discarded a notification with a malformed envelope: ${detail}`)); - return; - } - case "unsupported-revision": - if (isJSONRPCRequest(message)) { - const error = new UnsupportedProtocolVersionError({ - supported: [...SUPPORTED_MODERN_PROTOCOL_VERSIONS], - requested: opening.requested - }); - reportError(error); - await writeErrorResponse(message.id, error.code, error.message, error.data); - } else reportError(/* @__PURE__ */ new Error(`Discarded a notification claiming unsupported protocol revision ${opening.requested}`)); - return; - case "modern": - if (isJSONRPCRequest(message) && message.method === "server/discover") { - if (state.phase === "probe") { - state.instance.channel.deliver(message, { classification: opening.classification }); - return; - } - const instance = await connectInstance("modern", opening.revision); - if (isTornDown()) { - await disposeLateInstance(instance); - return; - } - state = { - phase: "probe", - instance - }; - instance.channel.deliver(message, { classification: opening.classification }); - return; - } - if (state.phase === "probe") { - if (isJSONRPCNotification(message)) { - state.instance.channel.deliver(message, { classification: opening.classification }); - return; - } - state = { - phase: "pinned", - era: "modern", - instance: state.instance - }; - } else { - const instance = await connectInstance("modern", opening.revision); - if (isTornDown()) { - await disposeLateInstance(instance); - return; - } - state = { - phase: "pinned", - era: "modern", - instance - }; - } - if (await tryServeListen(message)) return; - state.instance.channel.deliver(message, { classification: opening.classification }); - return; - case "legacy": { - if (legacyMode === "reject") { - if (isJSONRPCRequest(message)) await answerLegacyRejection(message, opening.reason, opening.requestedVersion); - return; - } - if (state.phase === "probe") { - await discardProbeInstance(state.instance); - if (isTornDown()) return; - state = { phase: "opening" }; - } - const instance = await connectInstance("legacy"); - if (isTornDown()) { - await disposeLateInstance(instance); - return; - } - state = { - phase: "pinned", - era: "legacy", - instance - }; - state.instance.channel.deliver(message); - return; - } - } - }; - const queue = []; - let pumping = false; - const pump = async () => { - if (pumping) return; - pumping = true; - try { - while (queue.length > 0) { - const message = queue.shift(); - try { - await processMessage(message); - } catch (error) { - if (isJSONRPCRequest(message)) await writeErrorResponse(message.id, ProtocolErrorCode.InternalError, "Internal server error"); - reportError(stdio_toError(error)); - } - } - } finally { - pumping = false; - } - }; - const closeAll = async () => { - if (closing || state.phase === "closed") return; - closing = true; - const current = state; - state = { phase: "closed" }; - for (const result of listenRouter.teardownAll()) await wire.send(result).catch((error) => reportError(stdio_toError(error))); - if (current.phase === "probe" || current.phase === "pinned") await current.instance.product.close().catch((error) => reportError(stdio_toError(error))); - await wire.close().catch((error) => reportError(stdio_toError(error))); - }; - wire.onmessage = (message) => { - queue.push(message); - pump(); - }; - wire.onerror = (error) => { - reportError(error); - if (state.phase === "probe" || state.phase === "pinned") state.instance.channel.onerror?.(error); - }; - wire.onclose = () => { - if (closing || state.phase === "closed") return; - closing = true; - const current = state; - state = { phase: "closed" }; - if (current.phase === "probe" || current.phase === "pinned") current.instance.product.close().catch((error) => reportError(stdio_toError(error))); - }; - const started = wire.start().catch((error) => { - reportError(stdio_toError(error)); - throw error; - }); - started.catch(() => {}); - return { close: async () => { - await started.catch(() => {}); - await closeAll(); - } }; -} -function stdio_toError(value) { - return value instanceof Error ? value : new Error(String(value)); -} - -//#endregion - -//# sourceMappingURL=stdio.mjs.map -const defaultHeartbeatIntervalMs = 300000; -const defaultActivityThrottleMs = 60000; -const defaultShutdownTimeoutMs = 5000; -const defaultHeartbeatName = 'agent-bundle'; -const redirectConsoleToStderr = ()=>{ - const originalStdoutWrite = process.stdout.write.bind(process.stdout); - const stderrConsole = new console.Console({ - stderr: process.stderr, - stdout: process.stderr - }); - const methods = [ - 'debug', - 'dir', - 'error', - 'info', - 'log', - 'trace', - 'warn' - ]; - for (const method of methods)console[method] = stderrConsole[method].bind(stderrConsole); - process.stdout.write = (chunk, encoding, callback)=>process.stderr.write(chunk, encoding, callback); - return Object.freeze({ - restoreProtocolStdout: ()=>{ - process.stdout.write = originalStdoutWrite; - } - }); -}; -const createHeartbeat = ({ activityThrottleMs = defaultActivityThrottleMs, intervalMs = defaultHeartbeatIntervalMs, name = defaultHeartbeatName, writeLine })=>{ - const startedAt = Date.now(); - let lastActivityAt = startedAt; - let lastActivityLogAt = 0; - const log = (reason)=>{ - const uptimeSeconds = Math.round((Date.now() - startedAt) / 1000); - const idleSeconds = Math.round((Date.now() - lastActivityAt) / 1000); - writeLine(`[${name}] stdio heartbeat (${reason}) pid=${process.pid} uptime=${uptimeSeconds}s idle=${idleSeconds}s`); - }; - const timer = setInterval(()=>log('interval'), intervalMs); - timer.unref?.(); - return Object.freeze({ - log, - noteActivity: ()=>{ - lastActivityAt = Date.now(); - if (lastActivityAt - lastActivityLogAt >= activityThrottleMs) { - lastActivityLogAt = lastActivityAt; - log('activity'); - } - }, - stop: ()=>clearInterval(timer) - }); -}; -const runStdioServer = async ({ activityThrottleMs, exit = (code)=>process.exit(code), heartbeat: heartbeatEnabled = true, heartbeatIntervalMs, server, serverName, shutdownTimeoutMs = defaultShutdownTimeoutMs, signals = process, stdin = process.stdin, transport, writeLine = (line)=>void process.stderr.write(`${line}\n`) })=>{ - const heartbeat = createHeartbeat({ - ...void 0 === activityThrottleMs ? {} : { - activityThrottleMs - }, - ...void 0 === heartbeatIntervalMs ? {} : { - intervalMs: heartbeatIntervalMs - }, - ...void 0 === serverName ? {} : { - name: serverName - }, - writeLine: heartbeatEnabled ? writeLine : ()=>void 0 - }); - const keepalive = setInterval(()=>void 0, 60000); - keepalive.unref?.(); - let shuttingDown = false; - const shutdown = async (exitCode = 0)=>{ - if (shuttingDown) return; - shuttingDown = true; - signals.off('SIGINT', handleSigint); - signals.off('SIGTERM', handleSigterm); - stdin.off?.('end', handleStdinEnd); - clearInterval(keepalive); - heartbeat.stop(); - await Promise.race([ - Promise.allSettled([ - Promise.resolve().then(()=>transport.close()), - Promise.resolve().then(()=>server.close()) - ]), - new Promise((resolve)=>setTimeout(resolve, shutdownTimeoutMs)) - ]); - exit(exitCode); - }; - const handleSigint = ()=>{ - shutdown(130); - }; - const handleSigterm = ()=>{ - shutdown(143); - }; - const handleStdinEnd = ()=>{ - shutdown(0); - }; - signals.on('SIGINT', handleSigint); - signals.on('SIGTERM', handleSigterm); - stdin.once?.('end', handleStdinEnd); - transport.onclose = ()=>{ - shutdown(0); - }; - await server.connect(transport); - const originalOnMessage = transport.onmessage; - transport.onmessage = (message, extra)=>{ - heartbeat.noteActivity(); - originalOnMessage?.(message, extra); - }; - return Object.freeze({ - heartbeat, - shutdown - }); -}; -const runGeneratedStdioMcpEntry = async (options)=>{ - const guard = redirectConsoleToStderr(); - const entry = await options.loadEntry(); - const factory = entry.default; - if ('function' != typeof factory) throw new TypeError(`Generated stdio entry for MCP server ${JSON.stringify(options.serverName)} must default-export a server factory.`); - const server = await factory(); - const { StdioServerTransport } = await Promise.resolve(stdio_namespaceObject); - guard.restoreProtocolStdout(); - const transport = new StdioServerTransport(); - return runStdioServer({ - ...options.lifecycle, - server, - serverName: options.serverName, - transport: transport - }); -}; - - - -await runGeneratedStdioMcpEntry({ - loadEntry: ()=>Promise.resolve(status_namespaceObject), - serverName: "status" -}); - -export {}; diff --git a/examples/mcp-app/artifact/codex/scripts/check-service-fixture.mjs b/examples/mcp-app/artifact/codex/scripts/check-service-fixture.mjs deleted file mode 100644 index a059060bb..000000000 --- a/examples/mcp-app/artifact/codex/scripts/check-service-fixture.mjs +++ /dev/null @@ -1,60 +0,0 @@ -import { readFile } from "node:fs/promises"; - - - - -const healthyCompilerStatus = Object.freeze({ - checks: Object.freeze([ - Object.freeze({ - label: 'Availability', - status: 'passing' - }), - Object.freeze({ - label: 'Build queue', - status: 'passing' - }) - ]), - service: 'compiler', - status: 'healthy', - summary: 'Compiler service is ready for release.' -}); -const isRecord = (value)=>value !== null && typeof value === 'object' && !Array.isArray(value); -const isHealthyCompilerFixture = (value)=>{ - if (!isRecord(value) || value.service !== healthyCompilerStatus.service || value.status !== healthyCompilerStatus.status || value.summary !== healthyCompilerStatus.summary || !Array.isArray(value.checks) || value.checks.length !== healthyCompilerStatus.checks.length) { - return false; - } - return healthyCompilerStatus.checks.every((expected, index)=>{ - const received = value.checks[index]; - return isRecord(received) && received.label === expected.label && received.status === expected.status; - }); -}; - - - -const fixturePath = new URL('../assets/evals/fixtures/status/result.json', import.meta.url); -/** - * `agent-bundle build` detects the `main` export and generates the process - * envelope (argv, awaiting, numeric-return exit-code adoption) around it. - */ const main = async ()=>{ - try { - const fixture = JSON.parse(await readFile(fixturePath, 'utf8')); - if (!isHealthyCompilerFixture(fixture)) { - throw new Error('compiler fixture must contain the exact healthy compiler status'); - } - process.stdout.write('Compiler fixture is healthy.\n'); - return 0; - } catch (error) { - process.stderr.write(`Unable to verify service fixture: ${error instanceof Error ? error.message : String(error)}\n`); - return 1; - } -}; - - -const check_service_fixture_entry_main = main; -if (typeof check_service_fixture_entry_main !== 'function') { - throw new TypeError('Executable entry must export a main function: ' + "/fast/projects/agent-bundle-worktrees/host-test/examples/mcp-app/src/scripts/check-service-fixture.ts"); -} -const code = await check_service_fixture_entry_main(process.argv.slice(2)); -if (typeof code === 'number') process.exitCode = code; - -export {}; diff --git a/examples/mcp-app/artifact/codex/skills/service-readiness/SKILL.md b/examples/mcp-app/artifact/codex/skills/service-readiness/SKILL.md deleted file mode 100644 index 8f91a79d7..000000000 --- a/examples/mcp-app/artifact/codex/skills/service-readiness/SKILL.md +++ /dev/null @@ -1,33 +0,0 @@ ---- -name: service-readiness -description: Reviews service health evidence and records an auditable readiness decision. ---- -# Service readiness - -## When to use - -Use this Skill when a release, incident decision, or service handoff needs a -clear health verdict backed by named checks and current evidence. - -## Required resources - -- Apply [the service status policy](references/status-policy.md) before - classifying a healthy, degraded, or blocked result. -- Deliver the decision with [the readiness report](assets/readiness-report.md). - -## Workflow - -1. Identify the service and collect its current summary and every labelled - check. Record the command, time, result, and evidence source. -2. Classify any failing check with the status policy. A degraded service is not - release-ready until its failing check has an approved mitigation. -3. State the readiness verdict only after confirming availability and the - service-specific release threshold. -4. Complete the report with the status, checks, evidence, owner, and next - action. Do not omit a failing check from the final decision. - -## Final report requirements - -State `ready`, `degraded`, `blocked`, or `needs evidence`; reproduce the -service summary; list each labelled check and its status; identify the owner -and due date for every non-passing check; and name the next required action. diff --git a/examples/mcp-app/artifact/codex/skills/service-readiness/assets/readiness-report.md b/examples/mcp-app/artifact/codex/skills/service-readiness/assets/readiness-report.md deleted file mode 100644 index 3da5d52ea..000000000 --- a/examples/mcp-app/artifact/codex/skills/service-readiness/assets/readiness-report.md +++ /dev/null @@ -1,22 +0,0 @@ -# Service readiness report - -## Verdict - -State `ready`, `degraded`, `blocked`, or `needs evidence` and name the service. - -## Evidence - -Record the collection time, command or artifact, service summary, and source. - -## Checks - -List every labelled check with its observed status and release threshold. - -## Findings and mitigation - -For each non-passing check, record the impact, owner, mitigation, due date, -and the evidence required to clear it. - -## Next action - -Name the decision owner and the next verification or release action. diff --git a/examples/mcp-app/artifact/codex/skills/service-readiness/references/status-policy.md b/examples/mcp-app/artifact/codex/skills/service-readiness/references/status-policy.md deleted file mode 100644 index 7e5766172..000000000 --- a/examples/mcp-app/artifact/codex/skills/service-readiness/references/status-policy.md +++ /dev/null @@ -1,22 +0,0 @@ -# Service status policy - -## Evidence standard - -Readiness evidence must identify the service, collection time, check label, -observed status, and source command or artifact. Missing or stale evidence is -not a passing check. - -## Status classification - -- **Healthy**: every required release check is passing. -- **Degraded**: availability remains sufficient, but a release threshold such - as P95 latency is failing. Record an owner and mitigation before release. -- **Blocked**: availability or a critical safety check is failing. Do not - release until new passing evidence is collected. -- **Needs evidence**: the service or any required check cannot be verified. - -## Release decision - -Issue `ready` only for a healthy service with current evidence. A degraded -service needs an explicit mitigation decision; a blocked service cannot pass; -and missing evidence requires a new check rather than an assumption. diff --git a/examples/mcp-app/artifact/portable/INSTALL.md b/examples/mcp-app/artifact/portable/INSTALL.md deleted file mode 100644 index 5ba00d88e..000000000 --- a/examples/mcp-app/artifact/portable/INSTALL.md +++ /dev/null @@ -1,19 +0,0 @@ -# Install mcp-app-example - -A unified service-readiness assistant with MCP, Skills, Hooks, scripts, and evaluation. - -Version: `1.0.0` - -Run these commands from this bundle directory. - -## Portable Agent Plugin - -Portable is a distribution profile, not a host runtime with one universal install location. -This bundle follows the Agent Plugins open standard (Agent Plugins 1.0.0, https://agent-plugins.org). -Cursor loads this format natively from `~/.cursor/plugins/local/`; restart Cursor or run -`Developer: Reload Window` after copying it. Codex, VS Code, GitHub Copilot, Kiro, and ChatGPT -are also native clients. The bundled installer provides the Cursor local copy: - -```sh -node ./install.mjs -``` diff --git a/examples/mcp-app/artifact/portable/assets/evals/fixtures/status/result.json b/examples/mcp-app/artifact/portable/assets/evals/fixtures/status/result.json deleted file mode 100644 index a765aa4b5..000000000 --- a/examples/mcp-app/artifact/portable/assets/evals/fixtures/status/result.json +++ /dev/null @@ -1,9 +0,0 @@ -{ - "service": "compiler", - "status": "healthy", - "summary": "Compiler service is ready for release.", - "checks": [ - { "label": "Availability", "status": "passing" }, - { "label": "Build queue", "status": "passing" } - ] -} diff --git a/examples/mcp-app/artifact/portable/install.mjs b/examples/mcp-app/artifact/portable/install.mjs deleted file mode 100644 index 1d942a81a..000000000 --- a/examples/mcp-app/artifact/portable/install.mjs +++ /dev/null @@ -1,80 +0,0 @@ -#!/usr/bin/env node -import { createHash } from 'node:crypto'; -import { cp, lstat, mkdir, mkdtemp, readFile, readdir, rename, rm } from 'node:fs/promises'; -import { homedir } from 'node:os'; -import { basename, join, resolve } from 'node:path'; -import { fileURLToPath } from 'node:url'; - -const pluginName = "mcp-app-example"; -const pluginVersion = "1.0.0"; -const source = resolve(fileURLToPath(new URL('.', import.meta.url))); -const cursorRoot = join(homedir(), '.cursor'); -const installRoot = join(cursorRoot, 'plugins', 'local'); -const destination = join(installRoot, pluginName); - -const exists = async (path) => { - try { await lstat(path); return true; } - catch (error) { if (error?.code === 'ENOENT') return false; throw error; } -}; - -const treeHash = async (root, prefix = '') => { - const rootMetadata = await lstat(root); - if (rootMetadata.isSymbolicLink() || !rootMetadata.isDirectory()) { - throw new Error('Refusing unsupported filesystem entry ".".'); - } - const hash = createHash('sha256'); - const visit = async (relative) => { - const absolute = join(root, relative); - const metadata = await lstat(absolute); - if (metadata.isSymbolicLink() || (!metadata.isDirectory() && !metadata.isFile())) { - throw new Error(`Refusing unsupported filesystem entry ${JSON.stringify(relative || '.')}.`); - } - if (metadata.isDirectory()) { - for (const name of (await readdir(absolute)).sort()) await visit(join(relative, name)); - return; - } - hash.update(relative.replaceAll('\\', '/')); - hash.update('\0'); - hash.update(await readFile(absolute)); - hash.update('\0'); - }; - for (const name of (await readdir(root)).sort()) await visit(join(prefix, name)); - return hash.digest('hex'); -}; - -const installedVersion = async () => { - for (const manifest of ['.cursor-plugin/plugin.json', 'plugin.json']) { - try { - const value = JSON.parse(await readFile(join(destination, manifest), 'utf8')); - if (typeof value.version === 'string') return value.version; - } catch (error) { if (error?.code !== 'ENOENT') throw error; } - } - return undefined; -}; - -if (!(await exists(cursorRoot)) || !(await lstat(cursorRoot)).isDirectory()) { - throw new Error(`Cursor is not installed in ${cursorRoot}.`); -} -await mkdir(installRoot, { recursive: true }); -if (await exists(destination)) { - const currentVersion = await installedVersion(); - if (currentVersion !== undefined && currentVersion !== pluginVersion) { - throw new Error(`Refusing version collision at ${destination}: found ${currentVersion}, requested ${pluginVersion}.`); - } - if (source === destination || await treeHash(source) === await treeHash(destination)) { - console.log(`Already installed ${pluginName}@${pluginVersion} at ${destination}`); - process.exit(0); - } - throw new Error(`Refusing content collision at ${destination}.`); -} - -const stageParent = await mkdtemp(join(installRoot, `.${basename(destination)}.stage-`)); -const stage = join(stageParent, 'bundle'); -try { - await cp(source, stage, { errorOnExist: true, force: false, recursive: true, verbatimSymlinks: true }); - await treeHash(stage); - await rename(stage, destination); - console.log(`Installed ${pluginName}@${pluginVersion} at ${destination}`); -} finally { - await rm(stageParent, { force: true, recursive: true }); -} diff --git a/examples/mcp-app/artifact/portable/mcp-apps/status.html b/examples/mcp-app/artifact/portable/mcp-apps/status.html deleted file mode 100644 index 4d949f09e..000000000 --- a/examples/mcp-app/artifact/portable/mcp-apps/status.html +++ /dev/null @@ -1,154 +0,0 @@ - - - - - - Service status - - - -
      -
      MCP App example
      -

      No service selected

      -
      unknown
      -

      Invoke the readiness tool to inspect a service.

      -
        - - - - -

        -
        - - diff --git a/examples/mcp-app/artifact/portable/mcp.json b/examples/mcp-app/artifact/portable/mcp.json deleted file mode 100644 index ac9282f22..000000000 --- a/examples/mcp-app/artifact/portable/mcp.json +++ /dev/null @@ -1 +0,0 @@ -{"$schema":"https://agent-plugins.org/schemas/1.0.0/mcp.schema.json","mcpServers":{"status":{"args":["mcp/mcp-status-073c1634.mjs"],"command":"node","cwd":"${PLUGIN_ROOT}","env":{"AGENT_BUNDLE_PLUGIN_ROOT":"${PLUGIN_ROOT}"},"type":"stdio"}}} diff --git a/examples/mcp-app/artifact/portable/mcp/mcp-status-073c1634.mjs b/examples/mcp-app/artifact/portable/mcp/mcp-status-073c1634.mjs deleted file mode 100644 index 8a8e6ecb4..000000000 --- a/examples/mcp-app/artifact/portable/mcp/mcp-status-073c1634.mjs +++ /dev/null @@ -1,30768 +0,0 @@ -import node_process from "node:process"; - -// The require scope -var __webpack_require__ = {}; - -// webpack/runtime/define_property_getters -(() => { -__webpack_require__.d = (exports, getters, values) => { - var define = (defs, kind) => { - for(var key in defs) { - if(__webpack_require__.o(defs, key) && !__webpack_require__.o(exports, key)) { - Object.defineProperty(exports, key, { enumerable: true, [kind]: defs[key] }); - } - } - }; - define(getters, "get"); - define(values, "value"); -}; -})(); -// webpack/runtime/has_own_property -(() => { -__webpack_require__.o = (obj, prop) => (Object.prototype.hasOwnProperty.call(obj, prop)) -})(); -// webpack/runtime/make_namespace_object -(() => { -// define __esModule on exports -__webpack_require__.r = (exports) => { - if(typeof Symbol !== 'undefined' && Symbol.toStringTag) { - Object.defineProperty(exports, Symbol.toStringTag, { value: 'Module' }); - } - Object.defineProperty(exports, '__esModule', { value: true }); -}; -})(); - -// NAMESPACE OBJECT: ./src/mcp/status.ts -var status_namespaceObject = {}; -__webpack_require__.r(status_namespaceObject); -__webpack_require__.d(status_namespaceObject, { - createStatusServer: () => (createStatusServer), - "default": () => (mcp_status) }); - - -// NAMESPACE OBJECT: ../../node_modules/.pnpm/@modelcontextprotocol+server@2.0.0/node_modules/@modelcontextprotocol/server/dist/stdio.mjs -var stdio_namespaceObject = {}; -__webpack_require__.r(stdio_namespaceObject); -__webpack_require__.d(stdio_namespaceObject, { - StdioServerTransport: () => (stdio_StdioServerTransport) }); - - -//#region rolldown:runtime -var __create = Object.create; -var __defProp = Object.defineProperty; -var __getOwnPropDesc = Object.getOwnPropertyDescriptor; -var __getOwnPropNames = Object.getOwnPropertyNames; -var __getProtoOf = Object.getPrototypeOf; -var __hasOwnProp = Object.prototype.hasOwnProperty; -var __commonJSMin = (cb, mod) => () => (mod || cb((mod = { exports: {} }).exports, mod), mod.exports); -var __exportAll = (all, symbols) => { - let target = {}; - for (var name in all) { - __defProp(target, name, { - get: all[name], - enumerable: true - }); - } - if (symbols) { - __defProp(target, Symbol.toStringTag, { value: "Module" }); - } - return target; -}; -var __copyProps = (to, from, except, desc) => { - if (from && typeof from === "object" || typeof from === "function") { - for (var keys = __getOwnPropNames(from), i = 0, n = keys.length, key; i < n; i++) { - key = keys[i]; - if (!__hasOwnProp.call(to, key) && key !== except) { - __defProp(to, key, { - get: ((k) => from[k]).bind(null, key), - enumerable: !(desc = __getOwnPropDesc(from, key)) || desc.enumerable - }); - } - } - } - return to; -}; -var __toESM = (mod, isNodeMode, target) => (target = mod != null ? __create(__getProtoOf(mod)) : {}, __copyProps(isNodeMode || !mod || !mod.__esModule ? __defProp(target, "default", { - value: mod, - enumerable: true -}) : target, mod)); - -//#endregion - -//#region ../core-internal/src/validators/dialects.ts -/** -* Canonical `$schema` URIs per supported dialect (http + https variants, trailing-`#` stripped). -*/ -const DRAFT_2020_12_URIS = new Set(["https://json-schema.org/draft/2020-12/schema", "http://json-schema.org/draft/2020-12/schema"]); -const DRAFT_2019_09_URIS = new Set(["https://json-schema.org/draft/2019-09/schema", "http://json-schema.org/draft/2019-09/schema"]); -const DRAFT_07_URIS = new Set(["https://json-schema.org/draft-07/schema", "http://json-schema.org/draft-07/schema"]); -const DRAFT_06_URIS = new Set(["https://json-schema.org/draft-06/schema", "http://json-schema.org/draft-06/schema"]); -/** -* Whether a `$schema` value declares the 2019-09 dialect — the only supported dialect with -* `$recursiveRef`/`$recursiveAnchor`. Non-throwing (unlike {@linkcode declaredDialect}) so -* wire-layer callers can consult it for documents whose dialect may be unsupported. -*/ -function declares2019Dialect($schema) { - return typeof $schema === "string" && DRAFT_2019_09_URIS.has($schema.replace(/#$/, "")); -} -/** -* Classify a schema's declared `$schema` dialect. No `$schema` (or a non-string one) means -* 2020-12. Any other dialect throws a plain `Error` with a clear message rather than letting the -* engine crash on an opaque internal error or silently mis-validate; `remedy` names the calling -* provider's escape hatch in that message. -*/ -function declaredDialect(schema, remedy) { - if (!("$schema" in schema) || typeof schema.$schema !== "string") return "2020-12"; - const declared = schema.$schema.replace(/#$/, ""); - if (DRAFT_2020_12_URIS.has(declared)) return "2020-12"; - if (DRAFT_2019_09_URIS.has(declared)) return "2019-09"; - if (DRAFT_07_URIS.has(declared) || DRAFT_06_URIS.has(declared)) return "draft-7"; - throw new Error(`JSON Schema declares an unsupported dialect ("$schema": "${schema.$schema.slice(0, 200)}"). The default validator supports JSON Schema 2020-12, 2019-09, draft-07, and draft-06; ${remedy}`); -} - -//#endregion - -//# sourceMappingURL=dialects-DoSzNhcb.mjs.map - -// functions -function assertEqual(val) { - return val; -} -function assertNotEqual(val) { - return val; -} -function toZod() { - return (schema) => schema; -} -function assertIs(_arg) { } -function assertNever(_x) { - throw new Error("Unexpected value in exhaustive check"); -} -function assert(_) { } -function getEnumValues(entries) { - const numericValues = Object.values(entries).filter((v) => typeof v === "number"); - const values = Object.entries(entries) - .filter(([k, _]) => numericValues.indexOf(+k) === -1) - .map(([_, v]) => v); - return values; -} -function joinValues(array, separator = "|") { - return array.map((val) => stringifyPrimitive(val)).join(separator); -} -function jsonStringifyReplacer(_, value) { - if (typeof value === "bigint") - return value.toString(); - return value; -} -function util_cached(getter) { - const set = false; - return { - get value() { - if (!set) { - const value = getter(); - Object.defineProperty(this, "value", { value }); - return value; - } - throw new Error("cached value already set"); - }, - }; -} -function nullish(input) { - return input === null || input === undefined; -} -function cleanRegex(source) { - const start = source.startsWith("^") ? 1 : 0; - const end = source.endsWith("$") ? source.length - 1 : source.length; - return source.slice(start, end); -} -function floatSafeRemainder(val, step) { - const ratio = val / step; - const roundedRatio = Math.round(ratio); - // `val` and `step` each round to a double before the division rounds again, so a true decimal multiple's quotient can sit up to 1.5 of these scaled epsilons from the integer. A 1x tolerance therefore rejected 2.03 as a multiple of 0.07; 4x covers the worst case with margin. - const tolerance = 4 * Number.EPSILON * Math.max(Math.abs(ratio), 1); - if (Math.abs(ratio - roundedRatio) < tolerance) - return 0; - return ratio - roundedRatio; -} -const EVALUATING = /* @__PURE__*/ Symbol("evaluating"); -function defineLazy(object, key, getter) { - let value = undefined; - Object.defineProperty(object, key, { - get() { - if (value === EVALUATING) { - // Circular reference detected, return undefined to break the cycle - return undefined; - } - if (value === undefined) { - value = EVALUATING; - value = getter(); - } - return value; - }, - set(v) { - Object.defineProperty(object, key, { - value: v, - // configurable: true, - }); - // object[key] = v; - }, - configurable: true, - }); -} -function objectClone(obj) { - return Object.create(Object.getPrototypeOf(obj), Object.getOwnPropertyDescriptors(obj)); -} -function assignProp(target, prop, value) { - Object.defineProperty(target, prop, { - value, - writable: true, - enumerable: true, - configurable: true, - }); -} -function mergeDefs(...defs) { - const mergedDescriptors = {}; - for (const def of defs) { - const descriptors = Object.getOwnPropertyDescriptors(def); - Object.assign(mergedDescriptors, descriptors); - } - return Object.defineProperties({}, mergedDescriptors); -} -function cloneDef(schema) { - return mergeDefs(schema._zod.def); -} -function getElementAtPath(obj, path) { - if (!path) - return obj; - return path.reduce((acc, key) => acc?.[key], obj); -} -function promiseAllObject(promisesObj) { - const keys = Object.keys(promisesObj); - const promises = keys.map((key) => promisesObj[key]); - return Promise.all(promises).then((results) => { - const resolvedObj = {}; - for (let i = 0; i < keys.length; i++) { - resolvedObj[keys[i]] = results[i]; - } - return resolvedObj; - }); -} -function randomString(length = 10) { - const chars = "abcdefghijklmnopqrstuvwxyz"; - let str = ""; - for (let i = 0; i < length; i++) { - str += chars[Math.floor(Math.random() * chars.length)]; - } - return str; -} -function util_esc(str) { - return JSON.stringify(str); -} -function slugify(input) { - return input - .toLowerCase() - .trim() - .replace(/[^\w\s-]/g, "") - .replace(/[\s_-]+/g, "-") - .replace(/^-+|-+$/g, ""); -} -const captureStackTrace = ("captureStackTrace" in Error ? Error.captureStackTrace : (..._args) => { }); -function util_isObject(data) { - return typeof data === "object" && data !== null && !Array.isArray(data); -} -const util_allowsEval = /* @__PURE__*/ util_cached(() => { - // Skip the probe under `jitless`: strict CSPs report the caught `new Function` as a `securitypolicyviolation` even though the throw is swallowed. - if (globalConfig.jitless) { - return false; - } - // @ts-ignore - if (typeof navigator !== "undefined" && navigator?.userAgent?.includes("Cloudflare")) { - return false; - } - try { - const F = Function; - new F(""); - return true; - } - catch (_) { - return false; - } -}); -function isPlainObject(o) { - if (util_isObject(o) === false) - return false; - // modified constructor - const ctor = o.constructor; - if (ctor === undefined) - return true; - if (typeof ctor !== "function") - return true; - // modified prototype - const prot = ctor.prototype; - if (util_isObject(prot) === false) - return false; - // ctor doesn't have static `isPrototypeOf` - if (Object.prototype.hasOwnProperty.call(prot, "isPrototypeOf") === false) { - return false; - } - return true; -} -function shallowClone(o) { - if (isPlainObject(o)) - return { ...o }; - if (Array.isArray(o)) - return [...o]; - if (o instanceof Map) - return new Map(o); - if (o instanceof Set) - return new Set(o); - return o; -} -function numKeys(data) { - let keyCount = 0; - for (const key in data) { - if (Object.prototype.hasOwnProperty.call(data, key)) { - keyCount++; - } - } - return keyCount; -} -const getParsedType = (data) => { - const t = typeof data; - switch (t) { - case "undefined": - return "undefined"; - case "string": - return "string"; - case "number": - return Number.isNaN(data) ? "nan" : "number"; - case "boolean": - return "boolean"; - case "function": - return "function"; - case "bigint": - return "bigint"; - case "symbol": - return "symbol"; - case "object": - if (Array.isArray(data)) { - return "array"; - } - if (data === null) { - return "null"; - } - if (data.then && typeof data.then === "function" && data.catch && typeof data.catch === "function") { - return "promise"; - } - if (typeof Map !== "undefined" && data instanceof Map) { - return "map"; - } - if (typeof Set !== "undefined" && data instanceof Set) { - return "set"; - } - if (typeof Date !== "undefined" && data instanceof Date) { - return "date"; - } - // @ts-ignore - if (typeof File !== "undefined" && data instanceof File) { - return "file"; - } - return "object"; - default: - throw new Error(`Unknown data type: ${t}`); - } -}; -const propertyKeyTypes = /* @__PURE__*/ new Set(["string", "number", "symbol"]); -const primitiveTypes = /* @__PURE__*/ (/* unused pure expression or super */ null && (new Set([ - "string", - "number", - "bigint", - "boolean", - "symbol", - "undefined", -]))); -function escapeRegex(str) { - return str.replace(/[.*+?^${}()|[\]\\]/g, "\\$&"); -} -// zod-specific utils -function clone(inst, def, params) { - const cl = new inst._zod.constr(def ?? inst._zod.def); - if (!def || params?.parent) - cl._zod.parent = inst; - return cl; -} -function normalizeParams(_params) { - const params = _params; - if (!params) - return {}; - if (typeof params === "string") - return { error: () => params }; - if (params?.message !== undefined) { - if (params?.error !== undefined) - throw new Error("Cannot specify both `message` and `error` params"); - params.error = params.message; - } - delete params.message; - if (typeof params.error === "string") - return { ...params, error: () => params.error }; - return params; -} -function createTransparentProxy(getter) { - let target; - return new Proxy({}, { - get(_, prop, receiver) { - target ?? (target = getter()); - return Reflect.get(target, prop, receiver); - }, - set(_, prop, value, receiver) { - target ?? (target = getter()); - return Reflect.set(target, prop, value, receiver); - }, - has(_, prop) { - target ?? (target = getter()); - return Reflect.has(target, prop); - }, - deleteProperty(_, prop) { - target ?? (target = getter()); - return Reflect.deleteProperty(target, prop); - }, - ownKeys(_) { - target ?? (target = getter()); - return Reflect.ownKeys(target); - }, - getOwnPropertyDescriptor(_, prop) { - target ?? (target = getter()); - return Reflect.getOwnPropertyDescriptor(target, prop); - }, - defineProperty(_, prop, descriptor) { - target ?? (target = getter()); - return Reflect.defineProperty(target, prop, descriptor); - }, - }); -} -function stringifyPrimitive(value) { - if (typeof value === "bigint") - return value.toString() + "n"; - if (typeof value === "string") - return `"${value}"`; - return `${value}`; -} -function optionalKeys(shape) { - return Object.keys(shape).filter((k) => { - return shape[k]._zod.optin !== undefined && shape[k]._zod.optout === "optional"; - }); -} -// Wrapped in a `@__PURE__` IIFE: esbuild never tree-shakes a top-level initializer that contains a member access on `Number`, so the bare object literal survived into every bundle. -const NUMBER_FORMAT_RANGES = /*@__PURE__*/ (() => ({ - safeint: [Number.MIN_SAFE_INTEGER, Number.MAX_SAFE_INTEGER], - int32: [-2147483648, 2147483647], - uint32: [0, 4294967295], - float32: [-3.4028234663852886e38, 3.4028234663852886e38], - float64: [-Number.MAX_VALUE, Number.MAX_VALUE], -}))(); -const BIGINT_FORMAT_RANGES = { - int64: [/* @__PURE__*/ BigInt("-9223372036854775808"), /* @__PURE__*/ BigInt("9223372036854775807")], - uint64: [/* @__PURE__*/ BigInt(0), /* @__PURE__*/ BigInt("18446744073709551615")], -}; -function pick(schema, mask) { - const currDef = schema._zod.def; - const checks = currDef.checks; - const hasChecks = checks && checks.length > 0; - if (hasChecks) { - throw new Error(".pick() cannot be used on object schemas containing refinements"); - } - const def = mergeDefs(schema._zod.def, { - get shape() { - const newShape = {}; - // `for...in` skips symbols, so a symbol in the mask would select nothing - for (const key of Reflect.ownKeys(mask)) { - if (!Object.prototype.hasOwnProperty.call(currDef.shape, key)) { - throw new Error(`Unrecognized key: "${String(key)}"`); - } - if (!mask[key]) - continue; - assignProp(newShape, key, currDef.shape[key]); - } - assignProp(this, "shape", newShape); // self-caching - return newShape; - }, - checks: [], - }); - return clone(schema, def); -} -function omit(schema, mask) { - const currDef = schema._zod.def; - const checks = currDef.checks; - const hasChecks = checks && checks.length > 0; - if (hasChecks) { - throw new Error(".omit() cannot be used on object schemas containing refinements"); - } - const def = mergeDefs(schema._zod.def, { - get shape() { - const newShape = { ...schema._zod.def.shape }; - for (const key of Reflect.ownKeys(mask)) { - if (!Object.prototype.hasOwnProperty.call(currDef.shape, key)) { - throw new Error(`Unrecognized key: "${String(key)}"`); - } - if (!mask[key]) - continue; - delete newShape[key]; - } - assignProp(this, "shape", newShape); // self-caching - return newShape; - }, - checks: [], - }); - return clone(schema, def); -} -function extend(schema, shape) { - if (!isPlainObject(shape)) { - throw new Error("Invalid input to extend: expected a plain object"); - } - const checks = schema._zod.def.checks; - const hasChecks = checks && checks.length > 0; - if (hasChecks) { - // Only throw if new shape overlaps with existing shape. Use getOwnPropertyDescriptor to check key existence without accessing values - const existingShape = schema._zod.def.shape; - for (const key of Reflect.ownKeys(shape)) { - if (Object.getOwnPropertyDescriptor(existingShape, key) !== undefined) { - throw new Error("Cannot overwrite keys on object schemas containing refinements. Use `.safeExtend()` instead."); - } - } - } - const def = mergeDefs(schema._zod.def, { - get shape() { - const _shape = { ...schema._zod.def.shape, ...shape }; - assignProp(this, "shape", _shape); // self-caching - return _shape; - }, - }); - return clone(schema, def); -} -function safeExtend(schema, shape) { - if (!isPlainObject(shape)) { - throw new Error("Invalid input to safeExtend: expected a plain object"); - } - const def = mergeDefs(schema._zod.def, { - get shape() { - const _shape = { ...schema._zod.def.shape, ...shape }; - assignProp(this, "shape", _shape); // self-caching - return _shape; - }, - }); - return clone(schema, def); -} -function merge(a, b) { - if (!b?._zod?.def) { - throw new Error("Invalid input to merge: expected an object schema. To merge a plain shape, use `.extend()`."); - } - if (a._zod.def.checks?.length) { - throw new Error(".merge() cannot be used on object schemas containing refinements. Use .safeExtend() instead."); - } - const def = mergeDefs(a._zod.def, { - get shape() { - const _shape = { ...a._zod.def.shape, ...b._zod.def.shape }; - assignProp(this, "shape", _shape); // self-caching - return _shape; - }, - get catchall() { - return b._zod.def.catchall; - }, - checks: b._zod.def.checks ?? [], - }); - return clone(a, def); -} -function partial(Class, schema, mask, name = "partial") { - const currDef = schema._zod.def; - const checks = currDef.checks; - const hasChecks = checks && checks.length > 0; - if (hasChecks) { - throw new Error(`.${name}() cannot be used on object schemas containing refinements`); - } - const def = mergeDefs(schema._zod.def, { - get shape() { - const oldShape = schema._zod.def.shape; - const shape = { ...oldShape }; - if (mask) { - for (const key of Reflect.ownKeys(mask)) { - if (!Object.prototype.hasOwnProperty.call(oldShape, key)) { - throw new Error(`Unrecognized key: "${String(key)}"`); - } - if (!mask[key]) - continue; - // if (oldShape[key]!._zod.optin === "optional") continue; - shape[key] = Class - ? new Class({ - type: "optional", - innerType: oldShape[key], - }) - : oldShape[key]; - } - } - else { - // the spread copies symbol keys; `for...in` would not reach them - for (const key of Reflect.ownKeys(oldShape)) { - // if (oldShape[key]!._zod.optin === "optional") continue; - shape[key] = Class - ? new Class({ - type: "optional", - innerType: oldShape[key], - }) - : oldShape[key]; - } - } - assignProp(this, "shape", shape); // self-caching - return shape; - }, - checks: [], - }); - return clone(schema, def); -} -function util_required(Class, schema, mask) { - const def = mergeDefs(schema._zod.def, { - get shape() { - const oldShape = schema._zod.def.shape; - const shape = { ...oldShape }; - if (mask) { - for (const key of Reflect.ownKeys(mask)) { - if (!Object.prototype.hasOwnProperty.call(shape, key)) { - throw new Error(`Unrecognized key: "${String(key)}"`); - } - if (!mask[key]) - continue; - // overwrite with non-optional - shape[key] = new Class({ - type: "nonoptional", - innerType: oldShape[key], - }); - } - } - else { - for (const key of Reflect.ownKeys(oldShape)) { - // overwrite with non-optional - shape[key] = new Class({ - type: "nonoptional", - innerType: oldShape[key], - }); - } - } - assignProp(this, "shape", shape); // self-caching - return shape; - }, - }); - return clone(schema, def); -} -// invalid_type | too_big | too_small | invalid_format | not_multiple_of | unrecognized_keys | invalid_union | invalid_key | invalid_element | invalid_value | custom -function aborted(x, startIndex = 0) { - if (x.aborted === true) - return true; - for (let i = startIndex; i < x.issues.length; i++) { - if (x.issues[i]?.continue !== true) { - return true; - } - } - return false; -} -// Checks for explicit abort (continue === false), as opposed to implicit abort (continue === undefined). Used to respect `abort: true` in .refine() even for checks that have a `when` function. -function explicitlyAborted(x, startIndex = 0) { - if (x.aborted === true) - return true; - for (let i = startIndex; i < x.issues.length; i++) { - if (x.issues[i]?.continue === false) { - return true; - } - } - return false; -} -function prefixIssues(path, issues) { - return issues.map((iss) => { - var _a; - (_a = iss).path ?? (_a.path = []); - iss.path.unshift(path); - return iss; - }); -} -function unwrapMessage(message) { - return typeof message === "string" ? message : message?.message; -} -/* A check holds no link back to the schema it is attached to — the same check instance is shared by every clone of that schema — so the owner is stamped onto the issues a check just raised, at the only point where both are in scope. Runs on the failure path only; `start` is the issue count from before the check ran. */ -function attachSchema(issues, start, inst) { - var _a; - for (let i = start; i < issues.length; i++) { - (_a = issues[i]).schema ?? (_a.schema = inst); - } -} -function finalizeIssue(iss, ctx, config) { - var _a; - // A schema that raised an issue itself owns it outright, and outranks any stamp an enclosing check left in `attachSchema`. String formats and z.custom() are schema and check at once, so when they act as a check they defer to that stamp instead. - const traits = iss.inst?._zod?.traits; - if (traits?.has("$ZodType")) { - if (traits.has("$ZodCheck")) - (_a = iss).schema ?? (_a.schema = iss.inst); - else - iss.schema = iss.inst; - } - // Decreasing specificity, first map to return a message wins. `inst` is whatever raised the issue, so a check's own map outranks the owning schema's. - const schemaError = iss.schema !== iss.inst ? iss.schema?._zod.def?.error : undefined; - const message = iss.message - ? iss.message - : (unwrapMessage(iss.inst?._zod.def?.error?.(iss)) ?? - unwrapMessage(schemaError?.(iss)) ?? - unwrapMessage(ctx?.error?.(iss)) ?? - unwrapMessage(config.customError?.(iss)) ?? - unwrapMessage(config.localeError?.(iss)) ?? - "Invalid input"); - const { inst: _inst, schema: _schema, continue: _continue, input: _input, ...rest } = iss; - rest.path ?? (rest.path = []); - rest.message = message; - if (ctx?.reportInput) { - rest.input = _input; - } - return rest; -} -function getSizableOrigin(input) { - if (input instanceof Set) - return "set"; - if (input instanceof Map) - return "map"; - // @ts-ignore - if (input instanceof File) - return "file"; - return "unknown"; -} -const highSurrogate = /[\uD800-\uDBFF]/; -// Code points in `str`: a surrogate pair counts once, a lone surrogate as itself. Hand-rolled because the string iterator allocates and runs ~250x slower on this path; the regex probe exits ~50x quicker for a string with no astral characters. -function codePointLength(str) { - const units = str.length; - if (!highSurrogate.test(str)) - return units; - let count = units; - for (let i = 0; i < units - 1; i++) { - if ((str.charCodeAt(i) & 0xfc00) === 0xd800 && (str.charCodeAt(i + 1) & 0xfc00) === 0xdc00) { - count--; - i++; - } - } - return count; -} -function getLengthableOrigin(input) { - if (Array.isArray(input)) - return "array"; - if (typeof input === "string") - return "string"; - return "unknown"; -} -function parsedType(data) { - const t = typeof data; - switch (t) { - case "number": { - return Number.isNaN(data) ? "nan" : "number"; - } - case "object": { - if (data === null) { - return "null"; - } - if (Array.isArray(data)) { - return "array"; - } - const obj = data; - if (obj && Object.getPrototypeOf(obj) !== Object.prototype && "constructor" in obj && obj.constructor) { - return obj.constructor.name; - } - } - } - return t; -} -function util_issue(...args) { - const [iss, input, inst] = args; - if (typeof iss === "string") { - return { - message: iss, - code: "custom", - input, - inst, - }; - } - return { ...iss }; -} -function cleanEnum(obj) { - return Object.entries(obj) - .filter(([k, _]) => { - // return true if NaN, meaning it's not a number, thus a string key - return Number.isNaN(Number.parseInt(k, 10)); - }) - .map((el) => el[1]); -} -// Codec utility functions -function base64ToUint8Array(base64) { - const binaryString = atob(base64); - const bytes = new Uint8Array(binaryString.length); - for (let i = 0; i < binaryString.length; i++) { - bytes[i] = binaryString.charCodeAt(i); - } - return bytes; -} -function uint8ArrayToBase64(bytes) { - let binaryString = ""; - for (let i = 0; i < bytes.length; i++) { - binaryString += String.fromCharCode(bytes[i]); - } - return btoa(binaryString); -} -function base64urlToUint8Array(base64url) { - const base64 = base64url.replace(/-/g, "+").replace(/_/g, "/"); - const padding = "=".repeat((4 - (base64.length % 4)) % 4); - return base64ToUint8Array(base64 + padding); -} -function uint8ArrayToBase64url(bytes) { - return uint8ArrayToBase64(bytes).replace(/\+/g, "-").replace(/\//g, "_").replace(/=/g, ""); -} -function hexToUint8Array(hex) { - const cleanHex = hex.replace(/^0x/, ""); - if (cleanHex.length % 2 !== 0) { - throw new Error("Invalid hex string length"); - } - const bytes = new Uint8Array(cleanHex.length / 2); - for (let i = 0; i < cleanHex.length; i += 2) { - bytes[i / 2] = Number.parseInt(cleanHex.slice(i, i + 2), 16); - } - return bytes; -} -function uint8ArrayToHex(bytes) { - return Array.from(bytes) - .map((b) => b.toString(16).padStart(2, "0")) - .join(""); -} -// instanceof -class util_Class { - constructor(..._args) { } -} -////////// PROTOTYPE INSTALLERS ////////// -// -// Members live on the prototype and materialize per instance on first read, which keeps own-property count under the step where V8 stops using inline slots. Changing anything here means re-measuring runtime, memory and bundle size together — see "The three axes" in AGENTS.md. -/** - * Installs a trait's members on its prototype. Each value builds that member for the instance on first read; the built value shadows the accessor as an own property, so a detached `const { parse } = schema` keeps working. - * - * Call this from a `proto` initializer, which runs once per prototype — never per instance. - */ -function util_members(proto, table) { - for (const key in table) { - const desc = Object.getOwnPropertyDescriptor(table, key); - // a getter installs as written, so it stays live: `description` reads through to the registry on every access. not enumerable: an object literal's is, and a prototype member never was - if (desc.get) - Object.defineProperty(proto, key, { ...desc, enumerable: false }); - // a method materializes bound on first read, which is what keeps a detached member working: `const opt = schema.optional; opt()` - else - defineBound(proto, key, desc.value); - } -} -/** Shadows a prototype member with an own value, so a getter that builds from the instance runs once. */ -function util_own(inst, key, value, enumerable = true) { - Object.defineProperty(inst, key, { configurable: true, writable: true, enumerable, value }); - return value; -} -/** Like {@link own}, for a member that was never an own data property and has to stay out of `Object.keys`. */ -function hide(inst, key, value) { - return util_own(inst, key, value, false); -} -function defineBound(proto, key, fn) { - Object.defineProperty(proto, key, { - configurable: true, - get() { - // vitest's spyOn calls a prototype getter bare to find the function it wraps, so a nullish receiver answers the raw method - return this == null ? fn : util_own(this, key, fn.bind(this)); - }, - set(value) { - util_own(this, key, value); - }, - }); -} -/** Returns the prototype to install on, or `undefined` if this group is already installed on it. */ -function claim(inst, sentinel) { - const proto = Object.getPrototypeOf(inst); - // Runs on every construction, so `in` rather than the costlier `hasOwnProperty.call`. Sentinels are keys the group itself defines. - return sentinel in proto ? undefined : proto; -} -// The internals whose init chain is installing. A second call for the same one is a derived constructor overriding its base, so it must not construct another schema in between or the override is dropped. -let installing; -// Set while a getter is running, so a value that resolved through a recursion break is not memoized. One shared descriptor shadows the key for the duration, which costs no per-key allocation. -let broke = false; -const breaker = { - configurable: true, - get() { - broke = true; - return undefined; - }, -}; -/** - * Installs a lazily-derived internal on the `_zod` prototype of `inst`'s - * constructor, computed from the internals object itself and cached there on - * first read. One accessor per constructor rather than one per instance. - */ -function defineLazyInternal(inst, key, compute) { - const proto = Object.getPrototypeOf(inst._zod); - if (key in proto && installing !== inst._zod) { - // A repeat construction: everything is installed already. Cleared here so the reference is not held past the first construction of every type. - installing = undefined; - return; - } - installing = inst._zod; - Object.defineProperty(proto, key, { - configurable: true, - get() { - // Shadowed before computing so a re-entrant read from a recursive schema resolves to undefined instead of running the getter again. - Object.defineProperty(this, key, breaker); - const outer = broke; - broke = false; - try { - const value = compute(this); - // A result that resolved through a recursion break is recomputed once the graph is complete; everything else memoizes, undefined included. - if (broke) - delete this[key]; - else - Object.defineProperty(this, key, { configurable: true, writable: true, value }); - broke = broke || outer; - return value; - } - catch (err) { - // A compute that threw memoizes nothing, so a later read runs it again and fails the same way. The shadow goes with it, since leaving it installed would answer undefined for every later read. - delete this[key]; - broke = broke || outer; - throw err; - } - }, - set(value) { - Object.defineProperty(this, key, { configurable: true, writable: true, value }); - }, - }); -} -/** - * Installs `key` on `inst`'s prototype, computed by `make` on first read and cached there as an own - * data property. One accessor per constructor rather than one per instance, because an own accessor - * puts every instance after the first into v8 dictionary mode. The key doubles as the sentinel. - */ -function installLazyProp(inst, key, make, enumerable) { - const proto = claim(inst, key); - if (!proto) - return; - Object.defineProperty(proto, key, { - configurable: true, - get() { - // Shadowed before computing, so a re-entrant read from a self-referential shape resolves to undefined instead of running the getter again. A data property rather than an accessor: an own accessor is the dictionary-mode transition this exists to avoid. - const desc = { configurable: true, writable: true, enumerable, value: undefined }; - Object.defineProperty(this, key, desc); - // a compute that throws leaves the shadow behind, so later reads answer undefined instead of re-throwing; `defineLazy` did the same, and `defineLazyInternal`'s delete-on-catch would cost bytes in every bundle for a case only a throwing user getter reaches - desc.value = make(this); - Object.defineProperty(this, key, desc); - return desc.value; - }, - set(value) { - Object.defineProperty(this, key, { configurable: true, writable: true, enumerable, value }); - }, - }); -} -/** Marks the thunk `_catch` synthesises for a constant catch value. `Function.length` cannot tell that thunk from a user callback — rest and defaulted parameters both report arity 0 — and a user callback reads `ctx.error`, whose issues only finalize correctly against the caller's per-parse error map. Provenance can say what arity cannot. A plain string key rather than `Symbol.for`, whose call at module scope no bundler can prove pure — the same shape that anchored `urlCanParse` into every build. */ -const CONSTANT_CATCH = "~constantCatch"; -/** Wraps a constant catch value in a thunk tagged with {@link CONSTANT_CATCH}. */ -function constantCatch(value) { - const fn = () => value; - fn[CONSTANT_CATCH] = true; - return fn; -} - -var core_a; - -/** A special constant with type `never` */ -const NEVER = /*@__PURE__*/ Object.freeze({ - status: "aborted", -}); -/* Shared descriptor for installing `_zod`; defineProperty reads it - * synchronously, so reusing one object avoids a per-instance allocation. */ -const _zodDesc = { value: undefined, enumerable: false }; -// null where suppressing the capture would be unrecoverable: `parse()` puts the frames back with `captureStackTrace`, so without it the throw would lose its stack. also latched to null once `stackTraceLimit` proves unassignable, which a realm can do at any point by hardening Error -let _E = "captureStackTrace" in Error ? Error : null; -// v8 captures a stack trace inside the Error constructor, which dominates a failed parse; costs only the frames, and parse() restores those. the constructor must RUN: Object.create is cheaper and passes instanceof, but Error.isError and util.types.isNativeError check an internal slot -function newError(Definition) { - const E = _E; - if (E) { - const saved = E.stackTraceLimit; - if (typeof saved === "number") { - try { - E.stackTraceLimit = 0; - } - catch { - _E = null; - return new Definition(); - } - try { - return new Definition(); - } - finally { - E.stackTraceLimit = saved; - } - } - } - return new Definition(); -} -function $constructor(name, initializer, -/** This trait's members, installed once on every prototype that composes it. They cannot be declared in the initializer above: that runs per instance, and the prototype is shared. */ -proto, params) { - // Prototype for this constructor's `_zod` internals. Lazily-derived fields (`values`, `pattern`, `optin`, …) install here once rather than as an accessor on every instance. - const zodProto = {}; - // Assigning the fields in the constructor body is what gives instances in-object slots; building the object literally and reparenting it costs a second allocation and a generic property copy. - function Internals(def) { - this.def = def; - this.constr = _; - this.traits = new Set(); - } - Internals.prototype = zodProto; - const protoMembers = proto; - // One trait's members land on every prototype whose chain composes it, so the answer is per prototype rather than per trait. - const initialized = protoMembers && new WeakSet(); - function init(inst, def) { - if (!inst._zod) { - _zodDesc.value = new Internals(def); - try { - Object.defineProperty(inst, "_zod", _zodDesc); - } - finally { - // Cleared even on throw, so the shared descriptor never leaks one instance's internals into the next. - _zodDesc.value = undefined; - } - } - if (inst._zod.traits.has(name)) { - return; - } - inst._zod.traits.add(name); - initializer(inst, def); - if (initialized) { - // `super(def)` from a user subclass gives `this` a prototype the subclass owns, and installing there would overwrite whatever the subclass declared. `constr` built the instance, so its prototype is the one below the subclass's that should carry the members. A receiver whose chain never reaches that prototype installs on its own, which for a plain object handed straight to `init` means `Object.prototype` — unchanged from before. - const own = Object.getPrototypeOf(inst); - const ctorProto = inst._zod.constr.prototype; - let up = own; - while (up && up !== ctorProto) - up = Object.getPrototypeOf(up); - const target = up ?? own; - if (!initialized.has(target)) { - initialized.add(target); - util_members(target, protoMembers); - } - } - // support prototype modifications; for-in avoids the array allocation of Object.keys on the (usually empty) prototype - const proto = _.prototype; - for (const k in proto) { - if (!Object.prototype.hasOwnProperty.call(proto, k)) - continue; - if (!(k in inst)) { - inst[k] = proto[k].bind(inst); - } - } - } - // doesn't work if Parent has a constructor with arguments - const Parent = params?.Parent ?? Object; - class Definition extends Parent { - } - Object.defineProperty(Definition, "name", { value: name }); - function _(def) { - const inst = params?.Parent ? newError(Definition) : this; - init(inst, def); - const deferred = inst._zod.deferred; - if (deferred) { - for (const fn of deferred) { - fn(); - } - // Released: initializers run once, and the list would otherwise be retained for the schema's lifetime. - inst._zod.deferred = undefined; - } - // Global post-processor hook. Internal: installed by `import "zod/compile"` to enable AOT compilation for every constructed schema. Runs last, once the instance is fully built, because it hands the instance to compile(). The post-processor is expected to be reentrancy-guarded by its own implementation. - const pp = globalThis.__zod_globalConfig?.postProcessor; - if (pp) - pp(inst); - return inst; - } - Object.defineProperty(_, "init", { value: init }); - Object.defineProperty(_, Symbol.hasInstance, { - value: (inst) => { - if (params?.Parent && inst instanceof params.Parent) - return true; - return inst?._zod?.traits?.has(name); - }, - }); - Object.defineProperty(_, "name", { value: name }); - return _; -} -////////////////////////////// UTILITIES /////////////////////////////////////// -const $brand = /*@__PURE__*/ (/* unused pure expression or super */ null && (Symbol("zod_brand"))); -class $ZodAsyncError extends Error { - constructor() { - super(`Encountered Promise during synchronous parse. Use .parseAsync() instead.`); - } -} -class $ZodEncodeError extends Error { - constructor(name) { - super(`Encountered unidirectional transform during encode: ${name}`); - this.name = "ZodEncodeError"; - } -} -(core_a = globalThis).__zod_globalConfig ?? (core_a.__zod_globalConfig = {}); -const globalConfig = globalThis.__zod_globalConfig; -function core_config(newConfig) { - if (newConfig) - Object.assign(globalConfig, newConfig); - return globalConfig; -} - -class $ZodCyclicError extends Error { - constructor() { - super(`Cannot parse a reference cycle that closes through a transform`); - this.name = "ZodCyclicError"; - } -} -/** Keyed off the context object every schema in one parse call already shares. */ -const STATE = "~memo"; -const NO_ISSUES = []; -// Receivers prefix paths in place, so the cache and every hand-out need their own copies. -function cloneIssues(issues) { - return issues.map((iss) => (iss.path ? { ...iss, path: iss.path.slice() } : { ...iss })); -} -const recursive = /*@__PURE__*/ new WeakMap(); -/** Whether this schema's subtree contains a cycle, so one parse can re-enter it. */ -function isRecursive(inst, stack) { - const cached = recursive.get(inst); - if (cached !== undefined) - return cached; - // Relative to the walk in progress, so not cached. - if (stack.has(inst)) - return true; - stack.add(inst); - let result = false; - const check = (child) => { - if (!result && child?._zod && isRecursive(child, stack)) - result = true; - }; - const def = inst._zod.def; - const kind = def.type; - switch (kind) { - case "object": { - // `Reflect.ownKeys` rather than `Object.keys`, so a cycle through a declared symbol key is still seen - for (const key of Reflect.ownKeys(def.shape)) - check(def.shape[key]); - check(def.catchall); - break; - } - case "array": - check(def.element); - break; - case "tuple": - for (const el of def.items) - check(el); - check(def.rest); - break; - case "record": - case "map": - check(def.keyType); - check(def.valueType); - break; - case "set": - check(def.valueType); - break; - case "union": - for (const el of def.options) - check(el); - break; - case "intersection": - check(def.left); - check(def.right); - break; - case "optional": - case "nullable": - case "default": - case "prefault": - case "catch": - case "readonly": - case "nonoptional": - case "promise": - case "success": - check(def.innerType); - break; - case "pipe": - check(def.in); - check(def.out); - break; - case "function": - check(def.input); - check(def.output); - break; - // reading `_zod.innerType` resolves the getter once and caches it - case "lazy": - check(inst._zod.innerType); - break; - // a leaf by choice: `parts` are regex fragments, not data positions - case "template_literal": - // leaves - case "string": - case "number": - case "int": - case "boolean": - case "bigint": - case "symbol": - case "undefined": - case "null": - case "void": - case "never": - case "any": - case "unknown": - case "date": - case "nan": - case "enum": - case "literal": - case "file": - case "transform": - case "custom": - break; - default: { - // a new built-in kind becomes a compile error here - kind; - // a user-defined kind can still hold children, and only its author knows where, so fall back to scanning the def — skipping accessors, since reading one can run user code - for (const key in def) { - const desc = Object.getOwnPropertyDescriptor(def, key); - if (!desc || desc.get) - continue; - const value = desc.value; - if (!value || typeof value !== "object") - continue; - if (value._zod) - check(value); - else if (Array.isArray(value)) - for (const el of value) - check(el); - } - } - } - stack.delete(inst); - recursive.set(inst, result); - return result; -} -/** - * Whether one parse can re-enter this schema, i.e. its subtree contains a cycle. - * Exported for `z.compile`, which refuses to compile such a schema: cycle - * breaking is driven from here off state keyed on the parse context, and a - * generated fast path has no context to key on. - */ -function isRecursiveSchema(inst) { - return isRecursive(inst, new Set()); -} -function bucketFor(state, inst) { - let bucket = state.buckets.get(inst); - if (!bucket) { - bucket = new Map(); - state.buckets.set(inst, bucket); - } - return bucket; -} -// Set immediately before delegating to core and cleared immediately after, so `alloc` registers only for a visit this module is driving. -let handoff; -// Allocated but unfinished entries. `alloc` and the matching pop both happen in the synchronous part of a parse, so they nest even when children are async, and one stack serves every schema. -const memoizer_open = []; -const memoizer_memo = { - alloc(_inst, payload, empty) { - const bucket = handoff; - if (!bucket) - return empty; - handoff = undefined; - const entry = { value: empty, issues: null }; - bucket.set(payload.value, entry); - memoizer_open.push(entry); - return empty; - }, - guard(inst) { - var _a; - (_a = inst._zod).deferred ?? (_a.deferred = []); - inst._zod.deferred.push(() => { - const base = inst._zod.parse; - const wrapped = (payload, ctx) => { - // The value is a placeholder a back-edge is still waiting on, so the cycle closes through this transform. Its output can't exist in time to bind. - if (ctx.direction !== "backward" && isBackEdge(ctx, payload.value)) - throw new $ZodCyclicError(); - return base(payload, ctx); - }; - inst._zod.parse = wrapped; - if (inst._zod.run === base) - inst._zod.run = wrapped; - }); - }, - attach(inst) { - var _a; - let isRecursiveInst; - // `bucket` memoized for one parse; a recursive schema is re-entered many times and its bucket never changes - let lastCtx; - let lastBucket; - // Wraps `parse` in a deferred so it sees the container's final parse. Core's own deferred copies `parse` into `run` when there are no checks, and it ran first, so `run` is patched to match; with checks, `run` reads `parse` dynamically. - (_a = inst._zod).deferred ?? (_a.deferred = []); - inst._zod.deferred.push(() => { - const base = inst._zod.parse; - const wrapped = (payload, ctx) => { - if (isRecursiveInst === undefined) { - isRecursiveInst = isRecursive(inst, new Set()); - if (!isRecursiveInst) { - // Nothing here can ever fire, so take it back out. - inst._zod.parse = base; - if (inst._zod.run === wrapped) - inst._zod.run = base; - return base(payload, ctx); - } - } - const input = payload.value; - if (input === null || typeof input !== "object") - return base(payload, ctx); - let state = ctx[STATE]; - if (!state) { - state = { buckets: new Map(), backEdges: undefined }; - ctx[STATE] = state; - } - let bucket; - if (lastCtx === ctx) { - bucket = lastBucket; - } - else { - bucket = bucketFor(state, inst); - lastCtx = ctx; - lastBucket = bucket; - } - const hit = bucket.get(input); - if (hit) { - payload.value = hit.value; - if (hit.issues) { - if (hit.issues.length) - payload.issues.push(...cloneIssues(hit.issues)); - } - else { - // Still being parsed: its own checks cover it, so skip them here. - payload.memo = true; - state.backEdges ?? (state.backEdges = new Set()); - state.backEdges.add(hit.value); - } - return payload; - } - handoff = bucket; - const depth = memoizer_open.length; - const result = base(payload, ctx); - handoff = undefined; - // A container that rejected its input outright allocated nothing. - const entry = memoizer_open.length > depth ? memoizer_open.pop() : undefined; - // Both paths written out so the sync one allocates no closure. It runs once per node, and capturing here cost more than everything else combined. - if (result instanceof Promise) { - return result.then((r) => { - if (entry) - entry.issues = r.issues.length ? cloneIssues(r.issues) : NO_ISSUES; - return r; - }); - } - if (entry) - entry.issues = result.issues.length ? cloneIssues(result.issues) : NO_ISSUES; - return result; - }; - inst._zod.parse = wrapped; - if (inst._zod.run === base) - inst._zod.run = wrapped; - }); - }, -}; -/** The memoizer that gives containers cycle support. `zod` installs it by default; `zod/mini` opts in with `config({ memoizer: memoizer() })`. */ -function memoizer() { - return memoizer_memo; -} -/** Whether this value is a node a back-edge resolved to before it finished. */ -function isBackEdge(ctx, value) { - const backEdges = ctx[STATE]?.backEdges; - return backEdges !== undefined && value !== null && typeof value === "object" && backEdges.has(value); -} - - -/** - * @deprecated CUID v1 is deprecated by its authors due to information leakage - * (timestamps embedded in the id). Use {@link cuid2} instead. - * See https://github.com/paralleldrive/cuid. - */ -const cuid = /^[cC][0-9a-z]{6,}$/; -const cuid2 = /^[0-9a-z]+$/; -const ulid = /^[0-7][0-9A-HJKMNP-TV-Za-hjkmnp-tv-z]{25}$/; -const xid = /^[0-9a-vA-V]{20}$/; -const ksuid = /^[A-Za-z0-9]{27}$/; -const nanoid = /^[a-zA-Z0-9_-]{21}$/; -function nanoidOfLength(length) { - return new RegExp(`^[a-zA-Z0-9_-]{${length}}$`); -} -/** ISO 8601-1 duration regex. Does not support the 8601-2 extensions like negative durations or fractional/negative components. */ -const duration = /^P(?:(\d+W)|(?!.*W)(?=\d|T\d)(\d+Y)?(\d+M)?(\d+D)?(T(?=\d)(\d+H)?(\d+M)?(\d+([.,]\d+)?S)?)?)$/; -/** Implements ISO 8601-2 extensions like explicit +- prefixes, mixing weeks with other units, and fractional/negative components. */ -const extendedDuration = /^[-+]?P(?!$)(?:(?:[-+]?\d+Y)|(?:[-+]?\d+[.,]\d+Y$))?(?:(?:[-+]?\d+M)|(?:[-+]?\d+[.,]\d+M$))?(?:(?:[-+]?\d+W)|(?:[-+]?\d+[.,]\d+W$))?(?:(?:[-+]?\d+D)|(?:[-+]?\d+[.,]\d+D$))?(?:T(?=[\d+-])(?:(?:[-+]?\d+H)|(?:[-+]?\d+[.,]\d+H$))?(?:(?:[-+]?\d+M)|(?:[-+]?\d+[.,]\d+M$))?(?:[-+]?\d+(?:[.,]\d+)?S)?)??$/; -/** A regex for any UUID-like identifier: 8-4-4-4-12 hex pattern */ -const guid = /^([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})$/; -/** Returns a regex for validating an RFC 9562/4122 UUID. - * - * @param version Optionally specify a version 1-8. If no version is specified, all versions are supported. */ -const uuid = (version) => { - if (!version) - return /^([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)$/; - return new RegExp(`^([0-9a-fA-F]{8}-[0-9a-fA-F]{4}-${version}[0-9a-fA-F]{3}-[89abAB][0-9a-fA-F]{3}-[0-9a-fA-F]{12})$`); -}; -const uuid4 = /*@__PURE__*/ (/* unused pure expression or super */ null && (uuid(4))); -const uuid6 = /*@__PURE__*/ (/* unused pure expression or super */ null && (uuid(6))); -const uuid7 = /*@__PURE__*/ (/* unused pure expression or super */ null && (uuid(7))); -/** Practical email validation */ -const email = /^(?!\.)(?!.*\.\.)([A-Za-z0-9_'+\-\.]*)[A-Za-z0-9_+-]@([A-Za-z0-9][A-Za-z0-9\-]*\.)+[A-Za-z]{2,}$/; -/** Equivalent to the HTML5 input[type=email] validation implemented by browsers. Source: https://developer.mozilla.org/en-US/docs/Web/HTML/Element/input/email */ -const html5Email = /^[a-zA-Z0-9.!#$%&'*+/=?^_`{|}~-]+@[a-zA-Z0-9](?:[a-zA-Z0-9-]{0,61}[a-zA-Z0-9])?(?:\.[a-zA-Z0-9](?:[a-zA-Z0-9-]{0,61}[a-zA-Z0-9])?)*$/; -/** The classic emailregex.com regex for RFC 5322-compliant emails */ -const rfc5322Email = /^(([^<>()\[\]\\.,;:\s@"]+(\.[^<>()\[\]\\.,;:\s@"]+)*)|(".+"))@((\[[0-9]{1,3}\.[0-9]{1,3}\.[0-9]{1,3}\.[0-9]{1,3}])|(([a-zA-Z\-0-9]+\.)+[a-zA-Z]{2,}))$/; -/** A loose regex that allows Unicode characters, enforces length limits, and that's about it. */ -const unicodeEmail = /^[^\s@"]{1,64}@[^\s@]{1,255}$/u; -const idnEmail = (/* unused pure expression or super */ null && (unicodeEmail)); -const browserEmail = /^[a-zA-Z0-9.!#$%&'*+/=?^_`{|}~-]+@[a-zA-Z0-9](?:[a-zA-Z0-9-]{0,61}[a-zA-Z0-9])?(?:\.[a-zA-Z0-9](?:[a-zA-Z0-9-]{0,61}[a-zA-Z0-9])?)*$/; -// from https://thekevinscott.com/emojis-in-javascript/#writing-a-regular-expression -// Single character class, not an alternation: the two properties overlap (U+1F9B0-U+1F9B3), so `(A|B)+` backtracks exponentially on a failed match. -const _emoji = `^[\\p{Extended_Pictographic}\\p{Emoji_Component}]+$`; -function emoji() { - return new RegExp(_emoji, "u"); -} -const ipv4 = /^(?:(?: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])$/; -const regexes_ipv6 = /^(([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}|:))$/; -const mac = (delimiter) => { - const escapedDelim = util.escapeRegex(delimiter ?? ":"); - return new RegExp(`^(?:[0-9A-F]{2}${escapedDelim}){5}[0-9A-F]{2}$|^(?:[0-9a-f]{2}${escapedDelim}){5}[0-9a-f]{2}$`); -}; -const cidrv4 = /^((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])$/; -const cidrv6 = /^(([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}|:))\/(12[0-8]|1[01][0-9]|[1-9]?[0-9])$/; -// https://stackoverflow.com/questions/7860392/determine-if-string-is-in-base64-using-javascript -const regexes_base64 = /^$|^(?:[0-9a-zA-Z+/]{4})*(?:(?:[0-9a-zA-Z+/]{2}==)|(?:[0-9a-zA-Z+/]{3}=))?$/; -const regexes_base64url = /^[A-Za-z0-9_-]*$/; -// based on https://stackoverflow.com/questions/106179/regular-expression-to-match-dns-hostname-or-ip-address -// export const hostname: RegExp = /^([a-zA-Z0-9-]+\.)*[a-zA-Z0-9-]+$/; -const regexes_hostname = /^(?=.{1,253}\.?$)[a-zA-Z0-9](?:[a-zA-Z0-9-]{0,61}[a-zA-Z0-9])?(?:\.[a-zA-Z0-9](?:[-0-9a-zA-Z]{0,61}[0-9a-zA-Z])?)*\.?$/; -const domain = /^(?=.{1,253}$)([a-zA-Z0-9](?:[a-zA-Z0-9-]{0,61}[a-zA-Z0-9])?\.)+[a-zA-Z]{2,63}$/; -const httpProtocol = /^https?$/; -// https://blog.stevenlevithan.com/archives/validate-phone-number#r4-3 (regex sans spaces) E.164: leading digit must be 1-9; total digits (excluding '+') between 7-15 -const e164 = /^\+[1-9]\d{6,14}$/; -// Credit card shape: 12–19 digits, optionally separated by single spaces or single hyphens. ISO/IEC 7812 caps the PAN at 19 digits; 12 is the shortest issued length (Maestro). -const creditCard = /^\d(?:[ -]?\d){11,18}$/; -const dateSource = `(?:(?:\\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])))`; -/** Anchors a pattern source. The interpolation lives here rather than at the call site because - * esbuild will not drop a `@__PURE__` call whose own argument interpolates a variable, but it - * will drop `anchor(dateSource)`. Keeping it inline pinned `date` into every bundle. */ -function regexes_anchor(source) { - return new RegExp(`^${source}$`); -} -const regexes_date = /*@__PURE__*/ regexes_anchor(dateSource); -function timeSource(args) { - const hhmm = `(?:[01]\\d|2[0-3]):[0-5]\\d`; - const regex = typeof args.precision === "number" - ? args.precision === -1 - ? `${hhmm}` - : args.precision === 0 - ? `${hhmm}:[0-5]\\d` - : `${hhmm}:[0-5]\\d\\.\\d{${args.precision}}` - : args.seconds - ? `${hhmm}:[0-5]\\d(?:\\.\\d+)?` - : `${hhmm}(?::[0-5]\\d(?:\\.\\d+)?)?`; - return regex; -} -function regexes_time(args) { - return new RegExp(`^${timeSource(args)}$`); -} -// Adapted from https://stackoverflow.com/a/3143231 -function datetime(args) { - const opts = ["Z"]; - // if (args.offset) opts.push(`([+-]\\d{2}:\\d{2})`); - if (args.offset) - opts.push(`([+-](?:[01]\\d|2[0-3]):[0-5]\\d)`); - // RFC 3339 mandates seconds wherever the time carries a `Z` or an offset, so only the unqualified form `local` adds may omit them - const qualified = `${timeSource({ precision: args.precision, seconds: true })}(?:${opts.join("|")})`; - const timeRegex = args.local ? `${qualified}|${timeSource({ precision: args.precision })}` : qualified; - return new RegExp(`^${dateSource}T(?:${timeRegex})$`); -} -const regexes_string = (params) => { - const regex = params ? `[\\s\\S]{${params?.minimum ?? 0},${params?.maximum ?? ""}}` : `[\\s\\S]*`; - return new RegExp(`^${regex}$`); -}; -const bigint = /^-?\d+n?$/; -const integer = /^-?\d+$/; -const number = /^-?\d+(?:\.\d+)?$/; -const regexes_boolean = /^(?:true|false)$/i; -const _null = /^null$/i; - -const _undefined = /^undefined$/i; - -// regex for string with no uppercase letters -const lowercase = /^[^A-Z]*$/; -// regex for string with no lowercase letters -const uppercase = /^[^a-z]*$/; -// regex for hexadecimal strings (any length) -const regexes_hex = /^[0-9a-fA-F]*$/; -// Hash regexes for different algorithms and encodings -// Helper function to create base64 regex with exact length and padding -function fixedBase64(bodyLength, padding) { - return new RegExp(`^[A-Za-z0-9+/]{${bodyLength}}${padding}$`); -} -// Helper function to create base64url regex with exact length (no padding) -function fixedBase64url(length) { - return new RegExp(`^[A-Za-z0-9_-]{${length}}$`); -} -// MD5 (16 bytes): base64 = 24 chars total (22 + "==") -const md5_hex = /^[0-9a-fA-F]{32}$/; -const md5_base64 = /*@__PURE__*/ (/* unused pure expression or super */ null && (fixedBase64(22, "=="))); -const md5_base64url = /*@__PURE__*/ (/* unused pure expression or super */ null && (fixedBase64url(22))); -// SHA1 (20 bytes): base64 = 28 chars total (27 + "=") -const sha1_hex = /^[0-9a-fA-F]{40}$/; -const sha1_base64 = /*@__PURE__*/ (/* unused pure expression or super */ null && (fixedBase64(27, "="))); -const sha1_base64url = /*@__PURE__*/ (/* unused pure expression or super */ null && (fixedBase64url(27))); -// SHA256 (32 bytes): base64 = 44 chars total (43 + "=") -const sha256_hex = /^[0-9a-fA-F]{64}$/; -const sha256_base64 = /*@__PURE__*/ (/* unused pure expression or super */ null && (fixedBase64(43, "="))); -const sha256_base64url = /*@__PURE__*/ (/* unused pure expression or super */ null && (fixedBase64url(43))); -// SHA384 (48 bytes): base64 = 64 chars total (no padding) -const sha384_hex = /^[0-9a-fA-F]{96}$/; -const sha384_base64 = /*@__PURE__*/ (/* unused pure expression or super */ null && (fixedBase64(64, ""))); -const sha384_base64url = /*@__PURE__*/ (/* unused pure expression or super */ null && (fixedBase64url(64))); -// SHA512 (64 bytes): base64 = 88 chars total (86 + "==") -const sha512_hex = /^[0-9a-fA-F]{128}$/; -const sha512_base64 = /*@__PURE__*/ (/* unused pure expression or super */ null && (fixedBase64(86, "=="))); -const sha512_base64url = /*@__PURE__*/ (/* unused pure expression or super */ null && (fixedBase64url(86))); - -// import { $ZodType } from "./schemas.js"; - - - -const $ZodCheck = /*@__PURE__*/ $constructor("$ZodCheck", (inst, def) => { - var _a; - inst._zod ?? (inst._zod = {}); - inst._zod.def = def; - (_a = inst._zod).onattach ?? (_a.onattach = []); -}); -/** Default `when` for size-based checks: run only on non-nullish values with a `size`. */ -const _whenHasSize = (payload) => { - const val = payload.value; - return !util.nullish(val) && val.size !== undefined; -}; -/** Default `when` for length-based checks: run only on non-nullish values with a `length`. */ -const _whenHasLength = (payload) => { - const val = payload.value; - return !nullish(val) && val.length !== undefined; -}; -const numericOriginMap = { - number: "number", - bigint: "bigint", - object: "date", -}; -const $ZodCheckLessThan = /*@__PURE__*/ $constructor("$ZodCheckLessThan", (inst, def) => { - $ZodCheck.init(inst, def); - const origin = numericOriginMap[typeof def.value]; - inst._zod.onattach.push((inst) => { - const bag = inst._zod.bag; - const curr = (def.inclusive ? bag.maximum : bag.exclusiveMaximum) ?? Number.POSITIVE_INFINITY; - if (def.value < curr) { - if (def.inclusive) - bag.maximum = def.value; - else - bag.exclusiveMaximum = def.value; - } - }); - inst._zod.check = (payload) => { - if (def.inclusive ? payload.value <= def.value : payload.value < def.value) { - return; - } - payload.issues.push({ - origin: numericOriginMap[typeof payload.value] ?? origin, - code: "too_big", - maximum: typeof def.value === "object" ? def.value.getTime() : def.value, - input: payload.value, - inclusive: def.inclusive, - inst, - continue: !def.abort, - }); - }; -}); -const $ZodCheckGreaterThan = /*@__PURE__*/ $constructor("$ZodCheckGreaterThan", (inst, def) => { - $ZodCheck.init(inst, def); - const origin = numericOriginMap[typeof def.value]; - inst._zod.onattach.push((inst) => { - const bag = inst._zod.bag; - const curr = (def.inclusive ? bag.minimum : bag.exclusiveMinimum) ?? Number.NEGATIVE_INFINITY; - if (def.value > curr) { - if (def.inclusive) - bag.minimum = def.value; - else - bag.exclusiveMinimum = def.value; - } - }); - inst._zod.check = (payload) => { - if (def.inclusive ? payload.value >= def.value : payload.value > def.value) { - return; - } - payload.issues.push({ - origin: numericOriginMap[typeof payload.value] ?? origin, - code: "too_small", - minimum: typeof def.value === "object" ? def.value.getTime() : def.value, - input: payload.value, - inclusive: def.inclusive, - inst, - continue: !def.abort, - }); - }; -}); -const $ZodCheckMultipleOf = -/*@__PURE__*/ $constructor("$ZodCheckMultipleOf", (inst, def) => { - $ZodCheck.init(inst, def); - inst._zod.onattach.push((inst) => { - var _a; - (_a = inst._zod.bag).multipleOf ?? (_a.multipleOf = def.value); - }); - inst._zod.check = (payload) => { - if (typeof payload.value !== typeof def.value) - throw new Error("Cannot mix number and bigint in multiple_of check."); - const isMultiple = typeof payload.value === "bigint" - ? // `value % 0n` throws, and nothing is a multiple of zero — the number branch already fails this way via NaN - def.value !== BigInt(0) && payload.value % def.value === BigInt(0) - : floatSafeRemainder(payload.value, def.value) === 0; - if (isMultiple) - return; - payload.issues.push({ - origin: typeof payload.value, - code: "not_multiple_of", - divisor: def.value, - input: payload.value, - inst, - continue: !def.abort, - }); - }; -}); -const $ZodCheckNumberFormat = /*@__PURE__*/ $constructor("$ZodCheckNumberFormat", (inst, def) => { - $ZodCheck.init(inst, def); // no format checks - def.format = def.format || "float64"; - const isInt = def.format?.includes("int"); - const origin = isInt ? "int" : "number"; - const [minimum, maximum] = NUMBER_FORMAT_RANGES[def.format]; - inst._zod.onattach.push((inst) => { - const bag = inst._zod.bag; - bag.format = def.format; - bag.minimum = minimum; - bag.maximum = maximum; - if (isInt) - bag.pattern = integer; - }); - inst._zod.check = (payload) => { - const input = payload.value; - if (isInt) { - if (!Number.isInteger(input)) { - // invalid_format issue - // payload.issues.push({ - // expected: def.format, - // format: def.format, - // code: "invalid_format", - // input, - // inst, - // }); - // invalid_type issue - payload.issues.push({ - expected: origin, - format: def.format, - code: "invalid_type", - continue: false, - input, - inst, - }); - return; - // not_multiple_of issue - // payload.issues.push({ - // code: "not_multiple_of", - // origin: "number", - // input, - // inst, - // divisor: 1, - // }); - } - if (!Number.isSafeInteger(input)) { - if (input > 0) { - // too_big - payload.issues.push({ - input, - code: "too_big", - maximum: Number.MAX_SAFE_INTEGER, - note: "Integers must be within the safe integer range.", - inst, - origin, - inclusive: true, - continue: !def.abort, - }); - } - else { - // too_small - payload.issues.push({ - input, - code: "too_small", - minimum: Number.MIN_SAFE_INTEGER, - note: "Integers must be within the safe integer range.", - inst, - origin, - inclusive: true, - continue: !def.abort, - }); - } - return; - } - } - if (input < minimum) { - payload.issues.push({ - origin: "number", - input, - code: "too_small", - minimum, - inclusive: true, - inst, - continue: !def.abort, - }); - } - if (input > maximum) { - payload.issues.push({ - origin: "number", - input, - code: "too_big", - maximum, - inclusive: true, - inst, - continue: !def.abort, - }); - } - }; -}); -const $ZodCheckBigIntFormat = /*@__PURE__*/ (/* unused pure expression or super */ null && (core.$constructor("$ZodCheckBigIntFormat", (inst, def) => { - $ZodCheck.init(inst, def); // no format checks - const [minimum, maximum] = util.BIGINT_FORMAT_RANGES[def.format]; - inst._zod.onattach.push((inst) => { - const bag = inst._zod.bag; - bag.format = def.format; - bag.minimum = minimum; - bag.maximum = maximum; - }); - inst._zod.check = (payload) => { - const input = payload.value; - if (input < minimum) { - payload.issues.push({ - origin: "bigint", - input, - code: "too_small", - minimum: minimum, - inclusive: true, - inst, - continue: !def.abort, - }); - } - if (input > maximum) { - payload.issues.push({ - origin: "bigint", - input, - code: "too_big", - maximum, - inclusive: true, - inst, - continue: !def.abort, - }); - } - }; -}))); -const $ZodCheckMaxSize = /*@__PURE__*/ (/* unused pure expression or super */ null && (core.$constructor("$ZodCheckMaxSize", (inst, def) => { - var _a; - $ZodCheck.init(inst, def); - (_a = inst._zod.def).when ?? (_a.when = _whenHasSize); - inst._zod.onattach.push((inst) => { - const curr = (inst._zod.bag.maximum ?? Number.POSITIVE_INFINITY); - if (def.maximum < curr) - inst._zod.bag.maximum = def.maximum; - }); - inst._zod.check = (payload) => { - const input = payload.value; - const size = input.size; - if (size <= def.maximum) - return; - payload.issues.push({ - origin: util.getSizableOrigin(input), - code: "too_big", - maximum: def.maximum, - inclusive: true, - input, - inst, - continue: !def.abort, - }); - }; -}))); -const $ZodCheckMinSize = /*@__PURE__*/ (/* unused pure expression or super */ null && (core.$constructor("$ZodCheckMinSize", (inst, def) => { - var _a; - $ZodCheck.init(inst, def); - (_a = inst._zod.def).when ?? (_a.when = _whenHasSize); - inst._zod.onattach.push((inst) => { - const curr = (inst._zod.bag.minimum ?? Number.NEGATIVE_INFINITY); - if (def.minimum > curr) - inst._zod.bag.minimum = def.minimum; - }); - inst._zod.check = (payload) => { - const input = payload.value; - const size = input.size; - if (size >= def.minimum) - return; - payload.issues.push({ - origin: util.getSizableOrigin(input), - code: "too_small", - minimum: def.minimum, - inclusive: true, - input, - inst, - continue: !def.abort, - }); - }; -}))); -const $ZodCheckSizeEquals = /*@__PURE__*/ (/* unused pure expression or super */ null && (core.$constructor("$ZodCheckSizeEquals", (inst, def) => { - var _a; - $ZodCheck.init(inst, def); - (_a = inst._zod.def).when ?? (_a.when = _whenHasSize); - inst._zod.onattach.push((inst) => { - const bag = inst._zod.bag; - bag.minimum = def.size; - bag.maximum = def.size; - bag.size = def.size; - }); - inst._zod.check = (payload) => { - const input = payload.value; - const size = input.size; - if (size === def.size) - return; - const tooBig = size > def.size; - payload.issues.push({ - origin: util.getSizableOrigin(input), - ...(tooBig ? { code: "too_big", maximum: def.size } : { code: "too_small", minimum: def.size }), - inclusive: true, - exact: true, - input: payload.value, - inst, - continue: !def.abort, - }); - }; -}))); -const $ZodCheckMaxLength = /*@__PURE__*/ $constructor("$ZodCheckMaxLength", (inst, def) => { - var _a; - $ZodCheck.init(inst, def); - (_a = inst._zod.def).when ?? (_a.when = _whenHasLength); - inst._zod.onattach.push((inst) => { - const curr = (inst._zod.bag.maximum ?? Number.POSITIVE_INFINITY); - if (def.maximum < curr) - inst._zod.bag.maximum = def.maximum; - }); - inst._zod.check = (payload) => { - const input = payload.value; - const units = input.length; - // Strings are measured in Unicode code points, not UTF-16 units. A code point is at most two units, so a string that already fits in units fits in code points; only an overflow has to be counted. - const length = typeof input === "string" && units > def.maximum ? codePointLength(input) : units; - if (length <= def.maximum) - return; - const origin = getLengthableOrigin(input); - payload.issues.push({ - origin, - code: "too_big", - maximum: def.maximum, - inclusive: true, - input, - inst, - continue: !def.abort, - }); - }; -}); -const $ZodCheckMinLength = /*@__PURE__*/ $constructor("$ZodCheckMinLength", (inst, def) => { - var _a; - $ZodCheck.init(inst, def); - (_a = inst._zod.def).when ?? (_a.when = _whenHasLength); - inst._zod.onattach.push((inst) => { - const curr = (inst._zod.bag.minimum ?? Number.NEGATIVE_INFINITY); - if (def.minimum > curr) - inst._zod.bag.minimum = def.minimum; - }); - inst._zod.check = (payload) => { - const input = payload.value; - const units = input.length; - // A code point is one or two UTF-16 units, so fewer units than the floor can never reach it and twice the floor always clears it. Only in between is the exact count in doubt. - const length = typeof input === "string" && units >= def.minimum && units < def.minimum * 2 - ? codePointLength(input) - : units; - if (length >= def.minimum) - return; - const origin = getLengthableOrigin(input); - payload.issues.push({ - origin, - code: "too_small", - minimum: def.minimum, - inclusive: true, - input, - inst, - continue: !def.abort, - }); - }; -}); -const $ZodCheckLengthEquals = /*@__PURE__*/ $constructor("$ZodCheckLengthEquals", (inst, def) => { - var _a; - $ZodCheck.init(inst, def); - (_a = inst._zod.def).when ?? (_a.when = _whenHasLength); - inst._zod.onattach.push((inst) => { - const bag = inst._zod.bag; - bag.minimum = def.length; - bag.maximum = def.length; - bag.length = def.length; - }); - inst._zod.check = (payload) => { - const input = payload.value; - const units = input.length; - // A code point is one or two UTF-16 units, so outside `[length, length * 2]` units the target is missed either way — and missed in the same direction in both measures. - const length = typeof input === "string" && units >= def.length && units <= def.length * 2 - ? codePointLength(input) - : units; - if (length === def.length) - return; - const origin = getLengthableOrigin(input); - const tooBig = length > def.length; - payload.issues.push({ - origin, - ...(tooBig ? { code: "too_big", maximum: def.length } : { code: "too_small", minimum: def.length }), - inclusive: true, - exact: true, - input: payload.value, - inst, - continue: !def.abort, - }); - }; -}); -const $ZodCheckStringFormat = /*@__PURE__*/ $constructor("$ZodCheckStringFormat", (inst, def) => { - var _a, _b; - $ZodCheck.init(inst, def); - inst._zod.onattach.push((inst) => { - const bag = inst._zod.bag; - bag.format = def.format; - if (def.pattern) { - bag.patterns ?? (bag.patterns = new Set()); - bag.patterns.add(def.pattern); - } - }); - if (def.pattern) - (_a = inst._zod).check ?? (_a.check = (payload) => { - def.pattern.lastIndex = 0; - if (def.pattern.test(payload.value)) - return; - payload.issues.push({ - origin: "string", - code: "invalid_format", - format: def.format, - input: payload.value, - ...(def.pattern ? { pattern: def.pattern.toString() } : {}), - inst, - continue: !def.abort, - }); - }); - else - (_b = inst._zod).check ?? (_b.check = () => { }); -}); -const $ZodCheckRegex = /*@__PURE__*/ $constructor("$ZodCheckRegex", (inst, def) => { - $ZodCheckStringFormat.init(inst, def); - inst._zod.check = (payload) => { - def.pattern.lastIndex = 0; - if (def.pattern.test(payload.value)) - return; - payload.issues.push({ - origin: "string", - code: "invalid_format", - format: "regex", - input: payload.value, - pattern: def.pattern.toString(), - inst, - continue: !def.abort, - }); - }; -}); -const $ZodCheckLowerCase = /*@__PURE__*/ $constructor("$ZodCheckLowerCase", (inst, def) => { - def.pattern ?? (def.pattern = lowercase); - $ZodCheckStringFormat.init(inst, def); -}); -const $ZodCheckUpperCase = /*@__PURE__*/ $constructor("$ZodCheckUpperCase", (inst, def) => { - def.pattern ?? (def.pattern = uppercase); - $ZodCheckStringFormat.init(inst, def); -}); -const $ZodCheckIncludes = /*@__PURE__*/ $constructor("$ZodCheckIncludes", (inst, def) => { - $ZodCheck.init(inst, def); - const escapedRegex = escapeRegex(def.includes); - // `String.prototype.includes(sub, position)` matches `sub` at `position` - // OR LATER, so the pattern must allow at least `position` leading chars - // (`{N,}`), not exactly `position` chars (`{N}`). - const pattern = new RegExp(typeof def.position === "number" ? `^.{${def.position},}${escapedRegex}` : escapedRegex); - def.pattern = pattern; - inst._zod.onattach.push((inst) => { - const bag = inst._zod.bag; - bag.patterns ?? (bag.patterns = new Set()); - bag.patterns.add(pattern); - }); - inst._zod.check = (payload) => { - if (payload.value.includes(def.includes, def.position)) - return; - payload.issues.push({ - origin: "string", - code: "invalid_format", - format: "includes", - includes: def.includes, - input: payload.value, - inst, - continue: !def.abort, - }); - }; -}); -const $ZodCheckStartsWith = /*@__PURE__*/ $constructor("$ZodCheckStartsWith", (inst, def) => { - $ZodCheck.init(inst, def); - const pattern = new RegExp(`^${escapeRegex(def.prefix)}.*`); - def.pattern ?? (def.pattern = pattern); - inst._zod.onattach.push((inst) => { - const bag = inst._zod.bag; - bag.patterns ?? (bag.patterns = new Set()); - bag.patterns.add(pattern); - }); - inst._zod.check = (payload) => { - if (payload.value.startsWith(def.prefix)) - return; - payload.issues.push({ - origin: "string", - code: "invalid_format", - format: "starts_with", - prefix: def.prefix, - input: payload.value, - inst, - continue: !def.abort, - }); - }; -}); -const $ZodCheckEndsWith = /*@__PURE__*/ $constructor("$ZodCheckEndsWith", (inst, def) => { - $ZodCheck.init(inst, def); - const pattern = new RegExp(`.*${escapeRegex(def.suffix)}$`); - def.pattern ?? (def.pattern = pattern); - inst._zod.onattach.push((inst) => { - const bag = inst._zod.bag; - bag.patterns ?? (bag.patterns = new Set()); - bag.patterns.add(pattern); - }); - inst._zod.check = (payload) => { - if (payload.value.endsWith(def.suffix)) - return; - payload.issues.push({ - origin: "string", - code: "invalid_format", - format: "ends_with", - suffix: def.suffix, - input: payload.value, - inst, - continue: !def.abort, - }); - }; -}); -/////////////////////////////////// -///// $ZodCheckProperty ///// -/////////////////////////////////// -function handleCheckPropertyResult(result, payload, property) { - if (result.issues.length) { - payload.issues.push(...util.prefixIssues(property, result.issues)); - } -} -const $ZodCheckProperty = /*@__PURE__*/ (/* unused pure expression or super */ null && (core.$constructor("$ZodCheckProperty", (inst, def) => { - $ZodCheck.init(inst, def); - inst._zod.check = (payload) => { - const result = def.schema._zod.run({ - value: payload.value[def.property], - issues: [], - }, {}); - if (result instanceof Promise) { - return result.then((result) => handleCheckPropertyResult(result, payload, def.property)); - } - handleCheckPropertyResult(result, payload, def.property); - return; - }; -}))); -const $ZodCheckMimeType = /*@__PURE__*/ (/* unused pure expression or super */ null && (core.$constructor("$ZodCheckMimeType", (inst, def) => { - $ZodCheck.init(inst, def); - const mimeSet = new Set(def.mime); - inst._zod.onattach.push((inst) => { - inst._zod.bag.mime = def.mime; - }); - inst._zod.check = (payload) => { - if (mimeSet.has(payload.value.type)) - return; - payload.issues.push({ - code: "invalid_value", - values: def.mime, - input: payload.value.type, - inst, - continue: !def.abort, - }); - }; -}))); -const $ZodCheckOverwrite = /*@__PURE__*/ $constructor("$ZodCheckOverwrite", (inst, def) => { - $ZodCheck.init(inst, def); - inst._zod.check = (payload) => { - payload.value = def.tx(payload.value); - }; -}); - -class Doc { - constructor(args = [], closed = {}) { - this.content = []; - this.indent = 0; - this.args = args; - this.closed = closed; - } - indented(fn) { - this.indent += 1; - fn(this); - this.indent -= 1; - } - write(arg) { - if (typeof arg === "function") { - arg(this, { execution: "sync" }); - arg(this, { execution: "async" }); - return; - } - const content = arg; - const lines = content.split("\n").filter((x) => x); - const minIndent = Math.min(...lines.map((x) => x.length - x.trimStart().length)); - const dedented = lines.map((x) => x.slice(minIndent)).map((x) => " ".repeat(this.indent * 2) + x); - for (const line of dedented) { - this.content.push(line); - } - } - compile() { - const F = Function; - const content = this?.content ?? [``]; - const factory = new F(...Object.keys(this.closed), `return function (${this.args.join(", ")}) {\n${content.join("\n")}\n};`); - return factory(...Object.values(this.closed)); - } -} - - - -/* Computing the message eagerly is expensive (pretty-printed JSON of all - * issues), so defer it until first read. The accessor functions and - * descriptors are shared across instances to keep error construction - * cheap; the computed message is cached on the internals object. The - * setter preserves plain assignment semantics for consumers that - * overwrite `message`. */ -function _getMessage() { - const internals = this._zod; - internals.message ?? (internals.message = JSON.stringify(internals.def, jsonStringifyReplacer, 2)); - return internals.message; -} -function _setMessage(value) { - this._zod.message = value; -} -const _messageDesc = { - get: _getMessage, - set: _setMessage, - enumerable: true, - configurable: true, -}; -const errors_zodDesc = { value: undefined, enumerable: false }; -const _issuesDesc = { value: undefined, enumerable: false }; -/* Prototypes that already carry the lazy `toString`. Seeded with the - * intrinsics so that `init` on a foreign object — it accepts any object — - * can never install an accessor onto a prototype we do not own. */ -const _installedToString = /* @__PURE__ */ new WeakSet([Object.prototype, Error.prototype]); -const errors_initializer = (inst, def) => { - inst.name = "$ZodError"; - errors_zodDesc.value = inst._zod; - Object.defineProperty(inst, "_zod", errors_zodDesc); - _issuesDesc.value = def; - Object.defineProperty(inst, "issues", _issuesDesc); - // Clear the shared slots; a retained `value` pins the last error's issues. - errors_zodDesc.value = undefined; - _issuesDesc.value = undefined; - Object.defineProperty(inst, "message", _messageDesc); - /* `toString` lives as a non-enumerable lazy getter on the shared - * prototype; on first access it caches a per-instance closure so - * detached usage still works. */ - const proto = Object.getPrototypeOf(inst); - if (!_installedToString.has(proto)) { - _installedToString.add(proto); - Object.defineProperty(proto, "toString", { - configurable: true, - enumerable: false, - get() { - const value = () => this.message; - Object.defineProperty(this, "toString", { value, configurable: true, writable: true }); - return value; - }, - set(value) { - Object.defineProperty(this, "toString", { value, configurable: true, writable: true }); - }, - }); - } -}; -const $ZodError = $constructor("$ZodError", errors_initializer); -const $ZodRealError = $constructor("$ZodError", errors_initializer, undefined, { - Parent: Error, -}); -/** Get-or-create `obj[key]` as an own data property. A path segment naming an inherited member - * ("toString", "constructor") would otherwise read through to the prototype, and assigning - * "__proto__" would hit the setter instead of creating a key. */ -function errors_node(obj, key, make) { - if (!Object.prototype.hasOwnProperty.call(obj, key)) { - if (key === "__proto__") { - Object.defineProperty(obj, key, { value: make(), writable: true, enumerable: true, configurable: true }); - } - else { - obj[key] = make(); - } - } - return obj[key]; -} -function flattenError(error, mapper = (issue) => issue.message) { - const fieldErrors = {}; - const formErrors = []; - for (const sub of error.issues) { - if (sub.path.length > 0) { - errors_node(fieldErrors, sub.path[0], () => []).push(mapper(sub)); - } - else { - formErrors.push(mapper(sub)); - } - } - return { formErrors, fieldErrors }; -} -function formatError(error, mapper = (issue) => issue.message) { - const fieldErrors = { _errors: [] }; - const processError = (error, path = []) => { - for (const issue of error.issues) { - if (issue.code === "invalid_union" && issue.errors.length) { - issue.errors.map((issues) => processError({ issues }, [...path, ...issue.path])); - } - else if (issue.code === "invalid_key") { - processError({ issues: issue.issues }, [...path, ...issue.path]); - } - else if (issue.code === "invalid_element") { - processError({ issues: issue.issues }, [...path, ...issue.path]); - } - else { - const fullpath = [...path, ...issue.path]; - if (fullpath.length === 0) { - fieldErrors._errors.push(mapper(issue)); - } - else { - let curr = fieldErrors; - let i = 0; - while (i < fullpath.length) { - const el = fullpath[i]; - const terminal = i === fullpath.length - 1; - // `_errors` is reserved by this legacy format, so merge a matching path segment into the current node instead of treating its array as a child. - if (el === "_errors") { - if (terminal) - curr._errors.push(mapper(issue)); - i++; - continue; - } - // A path element may collide with an inherited property name such as - // "__proto__" or "constructor". Truthiness checks read the prototype - // (so no node is created, then ._errors.push throws), and bracket - // assignment of "__proto__" hits the setter instead of creating an - // own key. Guard the read with hasOwnProperty and create the node - // with defineProperty so any path element becomes a real own key. - if (!Object.prototype.hasOwnProperty.call(curr, el)) { - Object.defineProperty(curr, el, { - value: { _errors: [] }, - enumerable: true, - writable: true, - configurable: true, - }); - } - const node = curr[el]; - if (terminal) { - node._errors.push(mapper(issue)); - } - curr = node; - i++; - } - } - } - } - }; - processError(error); - return fieldErrors; -} -function treeifyError(error, mapper = (issue) => issue.message) { - const result = { errors: [] }; - const processError = (error, path = []) => { - var _a; - for (const issue of error.issues) { - if (issue.code === "invalid_union" && issue.errors.length) { - // regular union error - issue.errors.map((issues) => processError({ issues }, [...path, ...issue.path])); - } - else if (issue.code === "invalid_key") { - processError({ issues: issue.issues }, [...path, ...issue.path]); - } - else if (issue.code === "invalid_element") { - processError({ issues: issue.issues }, [...path, ...issue.path]); - } - else { - const fullpath = [...path, ...issue.path]; - if (fullpath.length === 0) { - result.errors.push(mapper(issue)); - continue; - } - let curr = result; - let i = 0; - while (i < fullpath.length) { - const el = fullpath[i]; - const terminal = i === fullpath.length - 1; - if (typeof el === "string") { - curr.properties ?? (curr.properties = {}); - // el may collide with an inherited property name ("__proto__", - // "constructor", ...); ??= reads the prototype so the node is never - // created and curr.errors.push throws. Guard with hasOwnProperty and - // create the node with defineProperty so "__proto__" becomes a real - // own key rather than invoking the prototype setter. - if (!Object.prototype.hasOwnProperty.call(curr.properties, el)) { - Object.defineProperty(curr.properties, el, { - value: { errors: [] }, - enumerable: true, - writable: true, - configurable: true, - }); - } - curr = curr.properties[el]; - } - else { - curr.items ?? (curr.items = []); - (_a = curr.items)[el] ?? (_a[el] = { errors: [] }); - curr = curr.items[el]; - } - if (terminal) { - curr.errors.push(mapper(issue)); - } - i++; - } - } - } - }; - processError(error); - return result; -} -/** Format a ZodError as a human-readable string in the following form. - * - * From - * - * ```ts - * ZodError { - * issues: [ - * { - * expected: 'string', - * code: 'invalid_type', - * path: [ 'username' ], - * message: 'Invalid input: expected string' - * }, - * { - * expected: 'number', - * code: 'invalid_type', - * path: [ 'favoriteNumbers', 1 ], - * message: 'Invalid input: expected number' - * } - * ]; - * } - * ``` - * - * to - * - * ``` - * username - * ✖ Expected number, received string at "username - * favoriteNumbers[0] - * ✖ Invalid input: expected number - * ``` - */ -function toDotPath(_path) { - const segs = []; - const path = _path.map((seg) => (typeof seg === "object" ? seg.key : seg)); - for (const seg of path) { - if (typeof seg === "number") - segs.push(`[${seg}]`); - else if (typeof seg === "symbol") - segs.push(`[${JSON.stringify(String(seg))}]`); - else if (/[^\w$]/.test(seg)) - segs.push(`[${JSON.stringify(seg)}]`); - else { - if (segs.length) - segs.push("."); - segs.push(seg); - } - } - return segs.join(""); -} -function prettifyError(error) { - const lines = []; - // sort by path length - const issues = [...error.issues].sort((a, b) => (a.path ?? []).length - (b.path ?? []).length); - // Process each issue - for (const issue of issues) { - lines.push(`✖ ${issue.message}`); - if (issue.path?.length) - lines.push(` → at ${toDotPath(issue.path)}`); - } - // Convert Map to formatted string - return lines.join("\n"); -} - - - - -// Always both keys, so the `_params` read site in `_parse` sees one object shape rather than two. -function finalizeParams(callee, params) { - return { callee: params?.callee ?? callee, Err: params?.Err }; -} -const parse_parse = (_Err) => { - const fn = (schema, value, _ctx, _params) => { - const ctx = _ctx ? { ..._ctx, async: false } : { async: false }; - const result = schema._zod.run({ value, issues: [] }, ctx); - if (result instanceof Promise) { - throw new $ZodAsyncError(); - } - if (result.issues.length) { - const e = new (_params?.Err ?? _Err)(result.issues.map((iss) => finalizeIssue(iss, ctx, core_config()))); - captureStackTrace(e, _params?.callee ?? fn); - throw e; - } - return result.value; - }; - return fn; -}; -const core_parse_parse = /* @__PURE__*/ parse_parse($ZodRealError); -const parse_parseAsync = (_Err) => { - const fn = async (schema, value, _ctx, params) => { - const ctx = _ctx ? { ..._ctx, async: true } : { async: true }; - let result = schema._zod.run({ value, issues: [] }, ctx); - if (result instanceof Promise) - result = await result; - if (result.issues.length) { - const e = new (params?.Err ?? _Err)(result.issues.map((iss) => finalizeIssue(iss, ctx, core_config()))); - captureStackTrace(e, params?.callee ?? fn); - throw e; - } - return result.value; - }; - return fn; -}; -const core_parse_parseAsync = /* @__PURE__*/ parse_parseAsync($ZodRealError); -const _safeParse = (_Err) => (schema, value, _ctx) => { - const ctx = _ctx ? { ..._ctx, async: false } : { async: false }; - const result = schema._zod.run({ value, issues: [] }, ctx); - if (result instanceof Promise) { - throw new $ZodAsyncError(); - } - return result.issues.length - ? { - success: false, - error: new (_Err ?? $ZodError)(result.issues.map((iss) => finalizeIssue(iss, ctx, core_config()))), - } - : { success: true, data: result.value }; -}; -const safeParse = /* @__PURE__*/ _safeParse($ZodRealError); -const _safeParseAsync = (_Err) => async (schema, value, _ctx) => { - const ctx = _ctx ? { ..._ctx, async: true } : { async: true }; - let result = schema._zod.run({ value, issues: [] }, ctx); - if (result instanceof Promise) - result = await result; - return result.issues.length - ? { - success: false, - error: new _Err(result.issues.map((iss) => finalizeIssue(iss, ctx, core_config()))), - } - : { success: true, data: result.value }; -}; -const safeParseAsync = /* @__PURE__*/ _safeParseAsync($ZodRealError); -// registry mirrors of the compiler's sentinels, so this module never imports the compiler -const COMPILE_INVALID = /* @__PURE__ */ (/* unused pure expression or super */ null && (Symbol.for("zod.compile.invalid"))); -const COMPILE_FALLBACK = /* @__PURE__ */ (/* unused pure expression or super */ null && (Symbol.for("zod.compile.fallback"))); -// Deliberately tiny, because v8 will not inline a body carrying the fallback's object literals and throw. Everything that is not the compiled happy path lives in validateFallback, and that split is worth ~35% on a compiled schema. -const parse_validate = ((schema, value, _ctx) => { - const validator = schema._zod.bag.validator; - if (validator !== undefined && validator(value) !== COMPILE_INVALID) - return true; - return validateFallback(schema, value, _ctx); -}); -function validateFallback(schema, value, _ctx) { - const ctx = _ctx ? { ..._ctx, async: false } : { async: false }; - const fallbackRun = schema._zod.bag.fallbackRun; - let result; - if (fallbackRun) { - // skip nested fast paths on the fallback, so user callbacks keep the at-most-twice bound - ctx[COMPILE_FALLBACK] = true; - result = fallbackRun({ value, issues: [] }, ctx); - } - else { - result = schema._zod.run({ value, issues: [] }, ctx); - } - if (result instanceof Promise) { - throw new core.$ZodAsyncError(); - } - return result.issues.length === 0; -} -// no fast path: the compiler keeps async parses on the runtime, because a promise-returning callback that is not declared async compiles to a throw -const parse_validateAsync = async (schema, value, _ctx) => { - const ctx = _ctx ? { ..._ctx, async: true } : { async: true }; - let result = schema._zod.run({ value, issues: [] }, ctx); - if (result instanceof Promise) - result = await result; - return result.issues.length === 0; -}; -const parse_encode = (_Err) => { - const parse = parse_parse(_Err); - const fn = (schema, value, _ctx, _params) => { - const ctx = _ctx ? { ..._ctx, direction: "backward" } : { direction: "backward" }; - return parse(schema, value, ctx, finalizeParams(fn, _params)); - }; - return fn; -}; -const encode = /* @__PURE__*/ parse_encode($ZodRealError); -const parse_decode = (_Err) => { - const parse = parse_parse(_Err); - const fn = (schema, value, _ctx, _params) => { - return parse(schema, value, _ctx, finalizeParams(fn, _params)); - }; - return fn; -}; -const decode = /* @__PURE__*/ parse_decode($ZodRealError); -const parse_encodeAsync = (_Err) => { - const parseAsync = parse_parseAsync(_Err); - const fn = async (schema, value, _ctx, _params) => { - const ctx = _ctx ? { ..._ctx, direction: "backward" } : { direction: "backward" }; - return (await parseAsync(schema, value, ctx, finalizeParams(fn, _params))); - }; - return fn; -}; -const encodeAsync = /* @__PURE__*/ parse_encodeAsync($ZodRealError); -const parse_decodeAsync = (_Err) => { - const parseAsync = parse_parseAsync(_Err); - const fn = async (schema, value, _ctx, _params) => { - return await parseAsync(schema, value, _ctx, finalizeParams(fn, _params)); - }; - return fn; -}; -const decodeAsync = /* @__PURE__*/ parse_decodeAsync($ZodRealError); -const _safeEncode = (_Err) => (schema, value, _ctx) => { - const ctx = _ctx ? { ..._ctx, direction: "backward" } : { direction: "backward" }; - return _safeParse(_Err)(schema, value, ctx); -}; -const safeEncode = /* @__PURE__*/ _safeEncode($ZodRealError); -const _safeDecode = (_Err) => (schema, value, _ctx) => { - return _safeParse(_Err)(schema, value, _ctx); -}; -const safeDecode = /* @__PURE__*/ _safeDecode($ZodRealError); -const _safeEncodeAsync = (_Err) => async (schema, value, _ctx) => { - const ctx = _ctx ? { ..._ctx, direction: "backward" } : { direction: "backward" }; - return _safeParseAsync(_Err)(schema, value, ctx); -}; -const safeEncodeAsync = /* @__PURE__*/ _safeEncodeAsync($ZodRealError); -const _safeDecodeAsync = (_Err) => async (schema, value, _ctx) => { - return _safeParseAsync(_Err)(schema, value, _ctx); -}; -const safeDecodeAsync = /* @__PURE__*/ _safeDecodeAsync($ZodRealError); - -const versions_version = { - major: 4, - minor: 5, - patch: 4, -}; - - - - - - - - -const $ZodType = /*@__PURE__*/ $constructor("$ZodType", (inst, def) => { - var _a; - inst ?? (inst = {}); - inst._zod.def = def; // set _def property - inst._zod.bag = inst._zod.bag || {}; // initialize _bag object - inst._zod.version = versions_version; - const defChecks = inst._zod.def.checks; - // if inst is itself a checks.$ZodCheck, run it as a check - const checks = inst._zod.traits.has("$ZodCheck") - ? [inst, ...(defChecks ?? [])] - : defChecks?.length - ? [...defChecks] - : []; - for (const ch of checks) { - for (const fn of ch._zod.onattach) { - fn(inst); - } - } - if (checks.length === 0) { - // deferred initializer inst._zod.parse is not yet defined - (_a = inst._zod).deferred ?? (_a.deferred = []); - inst._zod.deferred?.push(() => { - inst._zod.run = inst._zod.parse; - }); - } - else { - const runChecks = (payload, checks, ctx) => { - if (payload.memo) - return payload; - let isAborted = aborted(payload); - let asyncResult; - for (const ch of checks) { - if (ch._zod.def.when) { - if (explicitlyAborted(payload)) - continue; - const shouldRun = ch._zod.def.when(payload); - if (!shouldRun) - continue; - } - else if (isAborted) { - continue; - } - const currLen = payload.issues.length; - const _ = ch._zod.check(payload); - if (_ instanceof Promise && ctx?.async === false) { - throw new $ZodAsyncError(); - } - if (asyncResult || _ instanceof Promise) { - asyncResult = (asyncResult ?? Promise.resolve()).then(async () => { - await _; - const nextLen = payload.issues.length; - if (nextLen === currLen) - return; - attachSchema(payload.issues, currLen, inst); - if (!isAborted) - isAborted = aborted(payload, currLen); - }); - } - else { - const nextLen = payload.issues.length; - if (nextLen === currLen) - continue; - attachSchema(payload.issues, currLen, inst); - if (!isAborted) - isAborted = aborted(payload, currLen); - } - } - if (asyncResult) { - return asyncResult.then(() => { - return payload; - }); - } - return payload; - }; - const handleCanaryResult = (canary, payload, ctx) => { - // abort if the canary is aborted - if (aborted(canary)) { - canary.aborted = true; - return canary; - } - // run checks first, then - const checkResult = runChecks(payload, checks, ctx); - if (checkResult instanceof Promise) { - if (ctx.async === false) - throw new $ZodAsyncError(); - return checkResult.then((checkResult) => inst._zod.parse(checkResult, ctx)); - } - return inst._zod.parse(checkResult, ctx); - }; - inst._zod.run = (payload, ctx) => { - if (ctx.skipChecks) { - return inst._zod.parse(payload, ctx); - } - if (ctx.direction === "backward") { - // run canary initial pass (no checks) - const canary = inst._zod.parse({ value: payload.value, issues: [] }, { ...ctx, skipChecks: true }); - if (canary instanceof Promise) { - return canary.then((canary) => { - return handleCanaryResult(canary, payload, ctx); - }); - } - return handleCanaryResult(canary, payload, ctx); - } - // forward - const result = inst._zod.parse(payload, ctx); - if (result instanceof Promise) { - if (ctx.async === false) - throw new $ZodAsyncError(); - return result.then((result) => runChecks(result, checks, ctx)); - } - return runChecks(result, checks, ctx); - }; - } -}, { - // Wrappers extend this by installing a richer factory over it; reading it eagerly would defeat the laziness. - get "~standard"() { - return hide(this, "~standard", standardProps(this)); - }, - set "~standard"(value) { - util_own(this, "~standard", value); - }, -}); -/** The Standard Schema surface for `inst`. Shared so wrappers can extend it without forcing it. */ -const toStandardResult = (r) => r.success ? { value: r.data } : { issues: r.error?.issues }; -function standardProps(inst) { - return { - validate: (value) => { - try { - return toStandardResult(safeParse(inst, value)); - } - catch (_) { - return safeParseAsync(inst, value).then(toStandardResult); - } - }, - vendor: "zod", - version: 1, - }; -} - -const $ZodString = /*@__PURE__*/ $constructor("$ZodString", (inst, def) => { - $ZodType.init(inst, def); - inst._zod.pattern = [...(inst?._zod.bag?.patterns ?? [])].pop() ?? regexes_string(inst._zod.bag); - inst._zod.parse = (payload, _) => { - if (def.coerce) - try { - payload.value = String(payload.value); - } - catch (_) { } - if (typeof payload.value === "string") - return payload; - payload.issues.push({ - expected: "string", - code: "invalid_type", - input: payload.value, - inst, - }); - return payload; - }; -}); -const $ZodStringFormat = /*@__PURE__*/ $constructor("$ZodStringFormat", (inst, def) => { - // check initialization must come first - $ZodCheckStringFormat.init(inst, def); - $ZodString.init(inst, def); -}); -const $ZodGUID = /*@__PURE__*/ $constructor("$ZodGUID", (inst, def) => { - def.pattern ?? (def.pattern = guid); - $ZodStringFormat.init(inst, def); -}); -const $ZodUUID = /*@__PURE__*/ $constructor("$ZodUUID", (inst, def) => { - if (def.version) { - const versionMap = { - v1: 1, - v2: 2, - v3: 3, - v4: 4, - v5: 5, - v6: 6, - v7: 7, - v8: 8, - }; - const v = versionMap[def.version]; - if (v === undefined) - throw new Error(`Invalid UUID version: "${def.version}"`); - def.pattern ?? (def.pattern = uuid(v)); - } - else - def.pattern ?? (def.pattern = uuid()); - $ZodStringFormat.init(inst, def); -}); -const $ZodEmail = /*@__PURE__*/ $constructor("$ZodEmail", (inst, def) => { - def.pattern ?? (def.pattern = email); - $ZodStringFormat.init(inst, def); -}); -/** The `://` guard rejected the input before the URL constructor saw it. */ -const URL_BAD_FORMAT = 1; -/** The URL constructor rejected the input. */ -const URL_UNPARSEABLE = 2; -/** Parses a URL for `$ZodURL`, applying the one guard the URL constructor cannot express. Returns the parsed URL, or a code naming the stage that rejected it — the runtime needs that distinction to pick an issue note, and compiled code only needs to know it is not a URL. */ -function parseURLObject(trimmed, def) { - // When normalize is off, require :// for http/https URLs. This prevents strings like "http:example.com" or "https:/path" from being silently accepted - if (!def.normalize && def.protocol?.source === httpProtocol.source && !/^https?:\/\//i.test(trimmed)) { - return URL_BAD_FORMAT; - } - try { - // @ts-ignore - return new URL(trimmed); - } - catch { - return URL_UNPARSEABLE; - } -} -const asciiTabOrNewline = /[\t\n\r]/g; -/** The URL parser deletes every ASCII tab, LF and CR from its input before it parses, so `new URL("https://exa\nmple.com")` reports on `example.com`. Applying the same deletion to the returned value closes the half of that divergence which can move the host; the parser's other rewrite, stripping C0 controls at the edges, cannot. */ -function stripTabAndNewline(value) { - return value.replace(asciiTabOrNewline, ""); -} -function urlHostnameOk(url, hostname) { - hostname.lastIndex = 0; - return hostname.test(url.hostname); -} -function urlProtocolOk(url, protocol) { - protocol.lastIndex = 0; - return protocol.test(url.protocol.endsWith(":") ? url.protocol.slice(0, -1) : url.protocol); -} -const $ZodURL = /*@__PURE__*/ $constructor("$ZodURL", (inst, def) => { - $ZodStringFormat.init(inst, def); - inst._zod.check = (payload) => { - try { - // Trim whitespace from input - const trimmed = payload.value.trim(); - const url = parseURLObject(trimmed, def); - if (url === URL_BAD_FORMAT) { - payload.issues.push({ - code: "invalid_format", - format: "url", - note: "Invalid URL format", - input: payload.value, - inst, - continue: !def.abort, - }); - return; - } - if (url === URL_UNPARSEABLE) { - payload.issues.push({ - code: "invalid_format", - format: "url", - input: payload.value, - inst, - continue: !def.abort, - }); - return; - } - if (def.hostname && !urlHostnameOk(url, def.hostname)) { - payload.issues.push({ - code: "invalid_format", - format: "url", - note: "Invalid hostname", - pattern: def.hostname.source, - input: payload.value, - inst, - continue: !def.abort, - }); - } - if (def.protocol && !urlProtocolOk(url, def.protocol)) { - payload.issues.push({ - code: "invalid_format", - format: "url", - note: "Invalid protocol", - pattern: def.protocol.source, - input: payload.value, - inst, - continue: !def.abort, - }); - } - // Set the output value based on normalize flag - payload.value = def.normalize ? url.href : stripTabAndNewline(trimmed); - return; - } - catch (_) { - payload.issues.push({ - code: "invalid_format", - format: "url", - input: payload.value, - inst, - continue: !def.abort, - }); - } - }; -}); -const $ZodEmoji = /*@__PURE__*/ $constructor("$ZodEmoji", (inst, def) => { - def.pattern ?? (def.pattern = emoji()); - $ZodStringFormat.init(inst, def); -}); -const $ZodNanoID = /*@__PURE__*/ $constructor("$ZodNanoID", (inst, def) => { - if (def.length !== undefined && (!Number.isInteger(def.length) || def.length < 1)) - throw new Error(`Invalid nanoid length: ${def.length}`); - def.pattern ?? (def.pattern = def.length === undefined ? nanoid : nanoidOfLength(def.length)); - $ZodStringFormat.init(inst, def); -}); -/** - * @deprecated CUID v1 is deprecated by its authors due to information leakage - * (timestamps embedded in the id). Use {@link $ZodCUID2} instead. - * See https://github.com/paralleldrive/cuid. - */ -const $ZodCUID = /*@__PURE__*/ $constructor("$ZodCUID", (inst, def) => { - def.pattern ?? (def.pattern = cuid); - $ZodStringFormat.init(inst, def); -}); -const $ZodCUID2 = /*@__PURE__*/ $constructor("$ZodCUID2", (inst, def) => { - def.pattern ?? (def.pattern = cuid2); - $ZodStringFormat.init(inst, def); -}); -const $ZodULID = /*@__PURE__*/ $constructor("$ZodULID", (inst, def) => { - def.pattern ?? (def.pattern = ulid); - $ZodStringFormat.init(inst, def); -}); -const $ZodXID = /*@__PURE__*/ $constructor("$ZodXID", (inst, def) => { - def.pattern ?? (def.pattern = xid); - $ZodStringFormat.init(inst, def); -}); -const $ZodKSUID = /*@__PURE__*/ $constructor("$ZodKSUID", (inst, def) => { - def.pattern ?? (def.pattern = ksuid); - $ZodStringFormat.init(inst, def); -}); -const $ZodISODateTime = /*@__PURE__*/ $constructor("$ZodISODateTime", (inst, def) => { - def.pattern ?? (def.pattern = datetime(def)); - $ZodStringFormat.init(inst, def); - // these two drop the offset or seconds `date-time` requires — on the bag not the def, since `z.string().check(...)` lands the format on a different schema - if (def.local || def.precision === -1) { - inst._zod.bag.laxFormat = true; - inst._zod.onattach.push((s) => { - s._zod.bag.laxFormat = true; - }); - } -}); -const $ZodISODate = /*@__PURE__*/ $constructor("$ZodISODate", (inst, def) => { - def.pattern ?? (def.pattern = regexes_date); - $ZodStringFormat.init(inst, def); -}); -const $ZodISOTime = /*@__PURE__*/ $constructor("$ZodISOTime", (inst, def) => { - def.pattern ?? (def.pattern = regexes_time(def)); - $ZodStringFormat.init(inst, def); -}); -const $ZodISODuration = /*@__PURE__*/ $constructor("$ZodISODuration", (inst, def) => { - def.pattern ?? (def.pattern = duration); - $ZodStringFormat.init(inst, def); -}); -const $ZodIPv4 = /*@__PURE__*/ $constructor("$ZodIPv4", (inst, def) => { - def.pattern ?? (def.pattern = ipv4); - $ZodStringFormat.init(inst, def); - inst._zod.bag.format = `ipv4`; -}); -/** An IPv6 address is written with hex digits, colons and dots, and nothing else. The guard is what makes the check below an IPv6 check: `new URL("http://[...]")` parses an authority, not an address, so `@` and `\` re-delimit it and `"::@1\\"` validates against the host `0.0.0.1`. The URL parser also deletes ASCII tab, LF and CR rather than failing, which is how `"::1\n"` validated as `::1`. */ -const ipv6Alphabet = /^[0-9a-fA-F:.]+$/; -function isValidIPv6(value) { - if (!ipv6Alphabet.test(value)) - return false; - try { - // @ts-ignore - new URL(`http://[${value}]`); - return true; - } - catch { - return false; - } -} -const $ZodIPv6 = /*@__PURE__*/ $constructor("$ZodIPv6", (inst, def) => { - def.pattern ?? (def.pattern = regexes_ipv6); - $ZodStringFormat.init(inst, def); - inst._zod.bag.format = `ipv6`; - inst._zod.check = (payload) => { - if (!isValidIPv6(payload.value)) { - payload.issues.push({ - code: "invalid_format", - format: "ipv6", - input: payload.value, - inst, - continue: !def.abort, - }); - } - }; -}); -const $ZodMAC = /*@__PURE__*/ (/* unused pure expression or super */ null && (core.$constructor("$ZodMAC", (inst, def) => { - def.pattern ?? (def.pattern = regexes.mac(def.delimiter)); - $ZodStringFormat.init(inst, def); - inst._zod.bag.format = `mac`; -}))); -const $ZodCIDRv4 = /*@__PURE__*/ $constructor("$ZodCIDRv4", (inst, def) => { - def.pattern ?? (def.pattern = cidrv4); - $ZodStringFormat.init(inst, def); -}); -function isValidCIDRv6(value) { - const parts = value.split("/"); - if (parts.length !== 2) - return false; - const [address, prefix] = parts; - if (!prefix) - return false; - const prefixNum = Number(prefix); - if (`${prefixNum}` !== prefix) - return false; - if (prefixNum < 0 || prefixNum > 128) - return false; - return isValidIPv6(address); -} -const $ZodCIDRv6 = /*@__PURE__*/ $constructor("$ZodCIDRv6", (inst, def) => { - def.pattern ?? (def.pattern = cidrv6); // not used for validation - $ZodStringFormat.init(inst, def); - inst._zod.check = (payload) => { - if (!isValidCIDRv6(payload.value)) { - payload.issues.push({ - code: "invalid_format", - format: "cidrv6", - input: payload.value, - inst, - continue: !def.abort, - }); - } - }; -}); -////////////////////////////// ZodBase64 ////////////////////////////// -function isValidBase64(data) { - if (data === "") - return true; - // atob ignores whitespace, so reject it up front. - if (/\s/.test(data)) - return false; - if (data.length % 4 !== 0) - return false; - try { - // @ts-ignore - atob(data); - return true; - } - catch { - return false; - } -} -const $ZodBase64 = /*@__PURE__*/ $constructor("$ZodBase64", (inst, def) => { - def.pattern ?? (def.pattern = regexes_base64); - $ZodStringFormat.init(inst, def); - inst._zod.bag.contentEncoding = "base64"; - inst._zod.check = (payload) => { - if (isValidBase64(payload.value)) - return; - payload.issues.push({ - code: "invalid_format", - format: "base64", - input: payload.value, - inst, - continue: !def.abort, - }); - }; -}); -////////////////////////////// ZodBase64 ////////////////////////////// -function isValidBase64URL(data) { - if (!regexes_base64url.test(data)) - return false; - const base64 = data.replace(/[-_]/g, (c) => (c === "-" ? "+" : "/")); - const padded = base64.padEnd(Math.ceil(base64.length / 4) * 4, "="); - return isValidBase64(padded); -} -const $ZodBase64URL = /*@__PURE__*/ $constructor("$ZodBase64URL", (inst, def) => { - def.pattern ?? (def.pattern = regexes_base64url); - $ZodStringFormat.init(inst, def); - inst._zod.bag.contentEncoding = "base64url"; - inst._zod.check = (payload) => { - if (isValidBase64URL(payload.value)) - return; - payload.issues.push({ - code: "invalid_format", - format: "base64url", - input: payload.value, - inst, - continue: !def.abort, - }); - }; -}); -const $ZodE164 = /*@__PURE__*/ $constructor("$ZodE164", (inst, def) => { - def.pattern ?? (def.pattern = e164); - $ZodStringFormat.init(inst, def); -}); -////////////////////////////// ZodCreditCard ////////////////////////////// -const CC_SANITIZE = /[- ]/g; -/** Luhn checksum on a digit-only string. Adapted from valibot (MIT). */ -function isLuhnAlgo(digits) { - let length = digits.length; - let bit = 1; - let sum = 0; - while (length) { - const value = +digits[--length]; - bit ^= 1; - sum += bit ? [0, 2, 4, 6, 8, 1, 3, 5, 7, 9][value] : value; - } - return sum % 10 === 0; -} -function isValidCreditCard(input) { - if (!regexes.creditCard.test(input)) - return false; - return isLuhnAlgo(input.replace(CC_SANITIZE, "")); -} -const $ZodCreditCard = /*@__PURE__*/ (/* unused pure expression or super */ null && (core.$constructor("$ZodCreditCard", (inst, def) => { - // Shape only — the Luhn check below is not expressible as a pattern, so consumers of `pattern` (JSON Schema, template literals) get the length and separator rules alone. - def.pattern ?? (def.pattern = regexes.creditCard); - $ZodStringFormat.init(inst, def); - inst._zod.check = (payload) => { - if (isValidCreditCard(payload.value)) - return; - payload.issues.push({ - code: "invalid_format", - format: "credit_card", - input: payload.value, - inst, - continue: !def.abort, - }); - }; -}))); -////////////////////////////// ZodJWT ////////////////////////////// -function isValidJWT(token, algorithm = null) { - try { - const tokensParts = token.split("."); - if (tokensParts.length !== 3) - return false; - const [header] = tokensParts; - if (!header) - return false; - // @ts-ignore - const parsedHeader = JSON.parse(atob(header)); - if ("typ" in parsedHeader && parsedHeader?.typ !== "JWT") - return false; - if (!parsedHeader.alg) - return false; - if (algorithm && (!("alg" in parsedHeader) || parsedHeader.alg !== algorithm)) - return false; - return true; - } - catch { - return false; - } -} -const $ZodJWT = /*@__PURE__*/ $constructor("$ZodJWT", (inst, def) => { - $ZodStringFormat.init(inst, def); - inst._zod.check = (payload) => { - if (isValidJWT(payload.value, def.alg)) - return; - payload.issues.push({ - code: "invalid_format", - format: "jwt", - input: payload.value, - inst, - continue: !def.abort, - }); - }; -}); -const $ZodCustomStringFormat = /*@__PURE__*/ (/* unused pure expression or super */ null && (core.$constructor("$ZodCustomStringFormat", (inst, def) => { - $ZodStringFormat.init(inst, def); - inst._zod.check = (payload) => { - if (def.fn(payload.value)) - return; - payload.issues.push({ - code: "invalid_format", - format: def.format, - input: payload.value, - inst, - continue: !def.abort, - }); - }; -}))); -const $ZodNumber = /*@__PURE__*/ $constructor("$ZodNumber", (inst, def) => { - $ZodType.init(inst, def); - inst._zod.pattern = inst._zod.bag.pattern ?? number; - inst._zod.parse = (payload, _ctx) => { - if (def.coerce) - try { - payload.value = Number(payload.value); - } - catch (_) { } - const input = payload.value; - if (typeof input === "number" && !Number.isNaN(input) && Number.isFinite(input)) { - return payload; - } - const received = typeof input === "number" - ? Number.isNaN(input) - ? "NaN" - : !Number.isFinite(input) - ? String(input) - : undefined - : undefined; - payload.issues.push({ - expected: "number", - code: "invalid_type", - input, - inst, - ...(received ? { received } : {}), - }); - return payload; - }; -}); -const $ZodNumberFormat = /*@__PURE__*/ $constructor("$ZodNumberFormat", (inst, def) => { - $ZodCheckNumberFormat.init(inst, def); - $ZodNumber.init(inst, def); // no format checks -}); -const $ZodBoolean = /*@__PURE__*/ $constructor("$ZodBoolean", (inst, def) => { - $ZodType.init(inst, def); - inst._zod.pattern = regexes_boolean; - inst._zod.parse = (payload, _ctx) => { - if (def.coerce) - try { - payload.value = Boolean(payload.value); - } - catch (_) { } - const input = payload.value; - if (typeof input === "boolean") - return payload; - payload.issues.push({ - expected: "boolean", - code: "invalid_type", - input, - inst, - }); - return payload; - }; -}); -const $ZodBigInt = /*@__PURE__*/ (/* unused pure expression or super */ null && (core.$constructor("$ZodBigInt", (inst, def) => { - $ZodType.init(inst, def); - inst._zod.pattern = regexes.bigint; - inst._zod.parse = (payload, _ctx) => { - if (def.coerce) - try { - payload.value = BigInt(payload.value); - } - catch (_) { } - if (typeof payload.value === "bigint") - return payload; - payload.issues.push({ - expected: "bigint", - code: "invalid_type", - input: payload.value, - inst, - }); - return payload; - }; -}))); -const $ZodBigIntFormat = /*@__PURE__*/ (/* unused pure expression or super */ null && (core.$constructor("$ZodBigIntFormat", (inst, def) => { - checks.$ZodCheckBigIntFormat.init(inst, def); - $ZodBigInt.init(inst, def); // no format checks -}))); -const $ZodSymbol = /*@__PURE__*/ (/* unused pure expression or super */ null && (core.$constructor("$ZodSymbol", (inst, def) => { - $ZodType.init(inst, def); - inst._zod.parse = (payload, _ctx) => { - const input = payload.value; - if (typeof input === "symbol") - return payload; - payload.issues.push({ - expected: "symbol", - code: "invalid_type", - input, - inst, - }); - return payload; - }; -}))); -const $ZodUndefined = /*@__PURE__*/ (/* unused pure expression or super */ null && (core.$constructor("$ZodUndefined", (inst, def) => { - $ZodType.init(inst, def); - inst._zod.pattern = regexes.undefined; - inst._zod.values = new Set([undefined]); - inst._zod.parse = (payload, _ctx) => { - const input = payload.value; - if (typeof input === "undefined") - return payload; - payload.issues.push({ - expected: "undefined", - code: "invalid_type", - input, - inst, - }); - return payload; - }; -}))); -const $ZodNull = /*@__PURE__*/ $constructor("$ZodNull", (inst, def) => { - $ZodType.init(inst, def); - inst._zod.pattern = _null; - inst._zod.values = new Set([null]); - inst._zod.parse = (payload, _ctx) => { - const input = payload.value; - if (input === null) - return payload; - payload.issues.push({ - expected: "null", - code: "invalid_type", - input, - inst, - }); - return payload; - }; -}); -const $ZodAny = /*@__PURE__*/ $constructor("$ZodAny", (inst, def) => { - $ZodType.init(inst, def); - inst._zod.parse = (payload) => payload; -}); -const $ZodUnknown = /*@__PURE__*/ $constructor("$ZodUnknown", (inst, def) => { - $ZodType.init(inst, def); - inst._zod.parse = (payload) => payload; -}); -const $ZodNever = /*@__PURE__*/ $constructor("$ZodNever", (inst, def) => { - $ZodType.init(inst, def); - inst._zod.parse = (payload, _ctx) => { - payload.issues.push({ - expected: "never", - code: "invalid_type", - input: payload.value, - inst, - }); - return payload; - }; -}); -const $ZodVoid = /*@__PURE__*/ (/* unused pure expression or super */ null && (core.$constructor("$ZodVoid", (inst, def) => { - $ZodType.init(inst, def); - inst._zod.parse = (payload, _ctx) => { - const input = payload.value; - if (typeof input === "undefined") - return payload; - payload.issues.push({ - expected: "void", - code: "invalid_type", - input, - inst, - }); - return payload; - }; -}))); -const $ZodDate = /*@__PURE__*/ (/* unused pure expression or super */ null && (core.$constructor("$ZodDate", (inst, def) => { - $ZodType.init(inst, def); - inst._zod.parse = (payload, _ctx) => { - if (def.coerce) { - try { - payload.value = new Date(payload.value); - } - catch (_err) { } - } - const input = payload.value; - const isDate = input instanceof Date; - const isValidDate = isDate && !Number.isNaN(input.getTime()); - if (isValidDate) - return payload; - payload.issues.push({ - expected: "date", - code: "invalid_type", - input, - ...(isDate ? { received: "Invalid Date" } : {}), - inst, - }); - return payload; - }; -}))); -function handleArrayResult(result, final, index) { - if (result.issues.length) { - final.issues.push(...prefixIssues(index, result.issues)); - } - final.value[index] = result.value; -} -const $ZodArray = /*@__PURE__*/ $constructor("$ZodArray", (inst, def) => { - $ZodType.init(inst, def); - const memo = globalConfig.memoizer; - memo?.attach(inst); - inst._zod.parse = (payload, ctx) => { - const input = payload.value; - if (!Array.isArray(input)) { - payload.issues.push({ - expected: "array", - code: "invalid_type", - input, - inst, - }); - return payload; - } - payload.value = memo ? memo.alloc(inst, payload, Array(input.length), ctx) : Array(input.length); - const proms = []; - for (let i = 0; i < input.length; i++) { - const item = input[i]; - const result = def.element._zod.run({ - value: item, - issues: [], - }, ctx); - if (result instanceof Promise) { - proms.push(result.then((result) => handleArrayResult(result, payload, i))); - } - else { - handleArrayResult(result, payload, i); - } - } - if (proms.length) { - return Promise.all(proms).then(() => payload); - } - return payload; //handleArrayResultsAsync(parseResults, final); - }; -}); -function handlePropertyResult(result, final, key, input, optin, optout) { - const isPresent = key in input; - const isOptionalOut = optout === "optional"; - // The middle rung means "absence permitted, nothing supplied in its place", so an absent key contributes nothing — whatever the schema made of `undefined` is invented, not substituted. Only `optional` reaches this with a value: `defaulted` substitutes, and a schema that isn't optional-out has to keep the key. - if (!isPresent && isOptionalOut && optin === "optional") { - return; - } - if (result.issues.length) { - // For optional-in/out schemas, ignore errors on absent keys. - if (optin !== undefined && isOptionalOut && !isPresent) { - return; - } - final.issues.push(...prefixIssues(key, result.issues)); - } - if (!isPresent && optin === undefined) { - if (!result.issues.length) { - final.issues.push({ - code: "invalid_type", - expected: "nonoptional", - input: undefined, - path: [key], - }); - } - return; - } - if (result.value === undefined) { - if (isPresent) { - final.value[key] = undefined; - } - } - else { - final.value[key] = result.value; - } -} -// one shared instance; a fresh [] per schema cost 56 bytes retained -const NO_SYMBOL_KEYS = []; -function normalizeDef(def) { - const keys = Object.keys(def.shape); - const ownSymbols = Object.getOwnPropertySymbols(def.shape); - const symbolKeys = ownSymbols.length ? ownSymbols : NO_SYMBOL_KEYS; - // aliases `keys` when there are no symbols, so a string-only shape keeps one array - const allKeys = symbolKeys.length ? [...keys, ...symbolKeys] : keys; - for (const k of allKeys) { - if (!def.shape?.[k]?._zod?.traits?.has("$ZodType")) { - throw new Error(`Invalid element at key "${String(k)}": expected a Zod schema`); - } - } - const okeys = optionalKeys(def.shape); - return { - ...def, - allKeys, - symbolKeys, - // string-only: handleCatchall matches it against `for...in`, which never yields a symbol - keySet: new Set(keys), - numKeys: keys.length, - optionalKeys: new Set(okeys), - }; -} -function handleCatchall(proms, input, payload, ctx, def, inst) { - const unrecognized = []; - const keySet = def.keySet; - const _catchall = def.catchall._zod; - const t = _catchall.def.type; - const optin = _catchall.optin; - const optout = _catchall.optout; - for (const key in input) { - // Must precede the __proto__ branch: a declared key is not unrecognized, even though the shape loop deliberately strips __proto__ from the parsed output. - if (keySet.has(key)) - continue; - // Don't copy an undeclared __proto__ into the result; assignment to a plain {} would replace the result prototype. But in strict mode it is still an unknown key, so report it before skipping. - if (key === "__proto__") { - if (t === "never") - unrecognized.push(key); - continue; - } - if (t === "never") { - unrecognized.push(key); - continue; - } - const r = _catchall.run({ value: input[key], issues: [] }, ctx); - if (r instanceof Promise) { - proms.push(r.then((r) => handlePropertyResult(r, payload, key, input, optin, optout))); - } - else { - handlePropertyResult(r, payload, key, input, optin, optout); - } - } - if (unrecognized.length) { - payload.issues.push({ - code: "unrecognized_keys", - keys: unrecognized, - input, - inst, - // Describes the shape of the input, not the validity of the parsed value, so it never aborts. The parse still fails; the schema's own checks just get to run first, and an enclosing intersection can reconcile the key against a sibling operand. - continue: true, - }); - } - if (!proms.length) - return payload; - return Promise.all(proms).then(() => { - return payload; - }); -} -// Whichever object a def's `shape` currently answers from: the one the caller passed until the first read, the frozen copy after it. Keyed by def, so a def rebuilt by a builder is simply absent rather than inheriting the source's. Read its keys with `Object.keys`, which does not invoke them — that is what lets a discriminated union check its discriminator without resolving an option whose getters reference the union being constructed. -const propShapes = new WeakMap(); -const $ZodObject = /*@__PURE__*/ $constructor("$ZodObject", (inst, def) => { - // requires cast because technically $ZodObject doesn't extend - $ZodType.init(inst, def); - // const sh = def.shape; - const desc = Object.getOwnPropertyDescriptor(def, "shape"); - if (!desc?.get) { - const sh = def.shape; - propShapes.set(def, sh); - Object.defineProperty(def, "shape", { - get: () => { - const newSh = { ...sh }; - Object.defineProperty(def, "shape", { - value: newSh, - }); - propShapes.set(def, newSh); - return newSh; - }, - }); - } - const _normalized = util_cached(() => normalizeDef(def)); - defineLazyInternal(inst, "propValues", (zod) => { - const shape = zod.def.shape; - const propValues = {}; - for (const key in shape) { - const field = shape[key]._zod; - if (field.values) { - if (!Object.prototype.hasOwnProperty.call(propValues, key)) { - assignProp(propValues, key, new Set()); - } - for (const v of field.values) - propValues[key].add(v); - // An omittable slot reads back as undefined at a discriminator lookup, so it has to claim undefined: two options that can both omit the key are not discriminable on it. - if (field.optin !== undefined) - propValues[key].add(undefined); - } - } - return propValues; - }); - const isObject = util_isObject; - const catchall = def.catchall; - let value; - const memo = globalConfig.memoizer; - memo?.attach(inst); - inst._zod.parse = (payload, ctx) => { - value ?? (value = _normalized.value); - const input = payload.value; - if (!isObject(input)) { - payload.issues.push({ - expected: "object", - code: "invalid_type", - input, - inst, - }); - return payload; - } - payload.value = memo ? memo.alloc(inst, payload, {}, ctx) : {}; - const proms = []; - const shape = value.shape; - for (const key of value.allKeys) { - if (key === "__proto__") - continue; - const el = shape[key]; - const optin = el._zod.optin; - const optout = el._zod.optout; - const r = el._zod.run({ value: input[key], issues: [] }, ctx); - if (r instanceof Promise) { - proms.push(r.then((r) => handlePropertyResult(r, payload, key, input, optin, optout))); - } - else { - handlePropertyResult(r, payload, key, input, optin, optout); - } - } - if (!catchall) { - return proms.length ? Promise.all(proms).then(() => payload) : payload; - } - return handleCatchall(proms, input, payload, ctx, _normalized.value, inst); - }; -}); -const $ZodObjectJIT = /*@__PURE__*/ $constructor("$ZodObjectJIT", (inst, def) => { - // requires cast because technically $ZodObject doesn't extend - $ZodObject.init(inst, def); - const superParse = inst._zod.parse; - const _normalized = util_cached(() => normalizeDef(def)); - const memo = globalConfig.memoizer; - const generateFastpass = (shape) => { - const normalized = _normalized.value; - const syms = normalized.symbolKeys; - // a symbol has no source literal, so it is read as `syms[i]` off the closed-over scope - const doc = new Doc(["payload", "ctx"], { shape, inst, memo, syms }); - const parseStr = (k) => `shape[${k}]._zod.run({ value: input[${k}], issues: [] }, ctx)`; - // Prefixes in place, like util.prefixIssues does for every interpreted path. - const prefixStr = (id, k) => ` - for (let i = 0; i < ${id}.issues.length; i++) { - const iss = ${id}.issues[i]; - iss.path = iss.path ? [${k}, ...iss.path] : [${k}]; - payload.issues.push(iss); - }`; - doc.write(`const input = payload.value;`); - const ids = Object.create(null); - let counter = 0; - for (const key of normalized.allKeys) { - ids[key] = `key_${counter++}`; - } - // A: preserve key order { - doc.write(memo ? `const newResult = memo.alloc(inst, payload, {}, ctx);` : `const newResult = {};`); - for (const key of normalized.allKeys) { - if (key === "__proto__") - continue; - const id = ids[key]; - const k = typeof key === "symbol" ? `syms[${syms.indexOf(key)}]` : util_esc(key); - const isPresent = `${k} in input`; - const schema = shape[key]; - const optin = schema?._zod?.optin; - const isOptionalIn = optin !== undefined; - const isOptionalOut = schema?._zod?.optout === "optional"; - doc.write(`const ${id} = ${parseStr(k)};`); - if (isOptionalIn && isOptionalOut) { - // For optional-in/out schemas, ignore errors on absent keys — and, like the interpreted path, drop the value produced alongside them. The middle rung goes further: it permits absence without supplying anything in its place, so an absent key contributes nothing at all. - const assign = optin === "optional" ? `${id}_present` : `${id}.value !== undefined || ${id}_present`; - doc.write(` - const ${id}_present = ${isPresent}; - if (!${id}.issues.length || ${id}_present) { - if (${id}.issues.length) {${prefixStr(id, k)} - } - - if (${assign}) { - newResult[${k}] = ${id}.value; - } - } - - `); - } - else if (!isOptionalIn) { - doc.write(` - const ${id}_present = ${isPresent}; - if (${id}.issues.length) {${prefixStr(id, k)} - } - if (!${id}_present && !${id}.issues.length) { - payload.issues.push({ - code: "invalid_type", - expected: "nonoptional", - input: undefined, - path: [${k}] - }); - } - - if (${id}_present) { - newResult[${k}] = ${id}.value; - } - - `); - } - else { - doc.write(` - if (${id}.issues.length) {${prefixStr(id, k)} - } - - if (${id}.value === undefined) { - if (${isPresent}) { - newResult[${k}] = undefined; - } - } else { - newResult[${k}] = ${id}.value; - } - - `); - } - } - doc.write(`payload.value = newResult;`); - doc.write(`return payload;`); - // closing `shape` in is what pays: turbofan specializes the parser against that one shape object, so every `shape[k]._zod.run` folds to a known callee. as a parameter it stays a generic load and measures 13% slower even with the forwarding frame gone - return doc.compile(); - }; - let fastpass; - const isObject = util_isObject; - const jit = !globalConfig.jitless; - const allowsEval = util_allowsEval; - const fastEnabled = jit && allowsEval.value; // && !def.catchall; - const catchall = def.catchall; - let value; - inst._zod.parse = (payload, ctx) => { - value ?? (value = _normalized.value); - const input = payload.value; - if (!isObject(input)) { - payload.issues.push({ - expected: "object", - code: "invalid_type", - input, - inst, - }); - return payload; - } - if (jit && fastEnabled && ctx?.async === false && ctx.jitless !== true) { - // always synchronous - if (!fastpass) - fastpass = generateFastpass(def.shape); - payload = fastpass(payload, ctx); - if (!catchall) - return payload; - return handleCatchall([], input, payload, ctx, value, inst); - } - return superParse(payload, ctx); - }; -}); -function handleUnionResults(results, final, inst, ctx) { - for (const result of results) { - if (result.issues.length === 0) { - final.value = result.value; - return final; - } - } - const nonaborted = results.filter((r) => !aborted(r)); - if (nonaborted.length === 1) { - final.value = nonaborted[0].value; - return nonaborted[0]; - } - final.issues.push({ - code: "invalid_union", - input: final.value, - inst, - errors: results.map((result) => result.issues.map((iss) => finalizeIssue(iss, ctx, core_config()))), - }); - return final; -} -const $ZodUnion = /*@__PURE__*/ $constructor("$ZodUnion", (inst, def) => { - $ZodType.init(inst, def); - defineLazyInternal(inst, "optin", (zod) => zod.def.options.some((o) => o._zod.optin === "defaulted") - ? "defaulted" - : zod.def.options.some((o) => o._zod.optin !== undefined) - ? "optional" - : undefined); - defineLazyInternal(inst, "optout", (zod) => zod.def.options.some((o) => o._zod.optout === "optional") ? "optional" : undefined); - defineLazyInternal(inst, "values", (zod) => { - if (zod.def.options.every((o) => o._zod.values)) { - return new Set(zod.def.options.flatMap((option) => Array.from(option._zod.values))); - } - return undefined; - }); - defineLazyInternal(inst, "pattern", (zod) => { - if (zod.def.options.every((o) => o._zod.pattern)) { - const patterns = zod.def.options.map((o) => o._zod.pattern); - return new RegExp(`^(${patterns.map((p) => cleanRegex(p.source)).join("|")})$`); - } - return undefined; - }); - const first = def.options.length === 1 ? def.options[0]._zod.run : null; - inst._zod.parse = (payload, ctx) => { - if (first) { - return first(payload, ctx); - } - let async = false; - const results = []; - for (const option of def.options) { - const result = option._zod.run({ - value: payload.value, - issues: [], - }, ctx); - if (result instanceof Promise) { - results.push(result); - async = true; - } - else { - if (result.issues.length === 0) - return result; - results.push(result); - } - } - if (!async) - return handleUnionResults(results, payload, inst, ctx); - return Promise.all(results).then((results) => { - return handleUnionResults(results, payload, inst, ctx); - }); - }; -}); -function handleExclusiveUnionResults(results, final, inst, ctx) { - const matches = []; - for (let i = 0; i < results.length; i++) { - if (results[i].issues.length === 0) - matches.push(i); - } - if (matches.length === 1) { - final.value = results[matches[0]].value; - return final; - } - if (matches.length === 0) { - // No matches - same as regular union - final.issues.push({ - code: "invalid_union", - input: final.value, - inst, - errors: results.map((result) => result.issues.map((iss) => util.finalizeIssue(iss, ctx, core.config()))), - }); - } - else { - // Multiple matches - exclusive union failure - final.issues.push({ - code: "invalid_union", - input: final.value, - inst, - errors: [], - inclusive: false, - matches, - }); - } - return final; -} -const $ZodXor = /*@__PURE__*/ (/* unused pure expression or super */ null && (core.$constructor("$ZodXor", (inst, def) => { - $ZodUnion.init(inst, def); - def.inclusive = false; - const first = def.options.length === 1 ? def.options[0]._zod.run : null; - inst._zod.parse = (payload, ctx) => { - if (first) { - return first(payload, ctx); - } - let async = false; - const results = []; - for (const option of def.options) { - const result = option._zod.run({ - value: payload.value, - issues: [], - }, ctx); - if (result instanceof Promise) { - results.push(result); - async = true; - } - else { - results.push(result); - } - } - if (!async) - return handleExclusiveUnionResults(results, payload, inst, ctx); - return Promise.all(results).then((results) => { - return handleExclusiveUnionResults(results, payload, inst, ctx); - }); - }; -}))); -/** Returns the option of `union` whose discriminator claims `value`. */ -function getDiscriminatedOption(union, value) { - const internals = union._zod; - let map = internals.bag.optionsMap; - if (!map) { - map = new Map(); - const { options, discriminator } = internals.def; - for (const option of options) { - // First declaration wins, matching the order the parse path resolves a duplicate in. - for (const v of option._zod.propValues?.[discriminator] ?? []) - if (!map.has(v)) - map.set(v, option); - } - internals.bag.optionsMap = map; - } - return map.get(value); -} -const $ZodDiscriminatedUnion = -/*@__PURE__*/ -$constructor("$ZodDiscriminatedUnion", (inst, def) => { - def.inclusive = false; - $ZodUnion.init(inst, def); - const _super = inst._zod.parse; - defineLazyInternal(inst, "propValues", (zod) => { - const propValues = {}; - for (const option of zod.def.options) { - const pv = option._zod.propValues; - if (!pv || Object.keys(pv).length === 0) - throw new Error(`Invalid discriminated union option at index "${zod.def.options.indexOf(option)}"`); - for (const [k, v] of Object.entries(pv)) { - if (!Object.prototype.hasOwnProperty.call(propValues, k)) { - assignProp(propValues, k, new Set()); - } - for (const val of v) { - propValues[k].add(val); - } - } - } - return propValues; - }); - // Checked now rather than in the lookup map below, so an option that lacks the discriminator fails at the `discriminatedUnion` call instead of on the first object parsed. Options whose shape cannot be enumerated without resolving it — pipes, lazies, and objects rebuilt by a builder such as `.extend()` — are left to the map. - def.options.forEach((option, i) => { - const propShape = propShapes.get(option._zod.def); - if (propShape && !Object.prototype.hasOwnProperty.call(propShape, def.discriminator)) { - throw new Error(`Invalid discriminated union option at index "${i}"`); - } - }); - const disc = util_cached(() => { - const opts = def.options; - const map = new Map(); - for (const o of opts) { - const values = o._zod.propValues?.[def.discriminator]; - if (!values || values.size === 0) - throw new Error(`Invalid discriminated union option at index "${def.options.indexOf(o)}"`); - for (const v of values) { - if (map.has(v)) { - throw new Error(`Duplicate discriminator value "${String(v)}"`); - } - map.set(v, o); - } - } - return map; - }); - inst._zod.parse = (payload, ctx) => { - const input = payload.value; - if (!util_isObject(input)) { - payload.issues.push({ - code: "invalid_type", - expected: "object", - input, - inst, - }); - return payload; - } - const opt = disc.value.get(input?.[def.discriminator]); - if (opt) { - return opt._zod.run(payload, ctx); - } - // Fall back to union matching when the fast discriminator path fails: - // - explicitly enabled via unionFallback, or - // - during backward direction (encode), since codec-based discriminators have different values in forward vs backward directions - if (def.unionFallback || ctx.direction === "backward") { - return _super(payload, ctx); - } - // no matching discriminator - payload.issues.push({ - code: "invalid_union", - errors: [], - note: "No matching discriminator", - discriminator: def.discriminator, - options: Array.from(disc.value.keys()), - input, - path: [def.discriminator], - inst, - }); - return payload; - }; -}); -const $ZodIntersection = /*@__PURE__*/ $constructor("$ZodIntersection", (inst, def) => { - $ZodType.init(inst, def); - inst._zod.parse = (payload, ctx) => { - const input = payload.value; - const left = def.left._zod.run({ value: input, issues: [] }, ctx); - const right = def.right._zod.run({ value: input, issues: [] }, ctx); - const async = left instanceof Promise || right instanceof Promise; - if (async) { - return Promise.all([left, right]).then(([left, right]) => { - return handleIntersectionResults(payload, left, right); - }); - } - return handleIntersectionResults(payload, left, right); - }; -}); -function schemas_mergeValues(a, b) { - // const aType = parse.t(a); - // const bType = parse.t(b); - if (a === b) { - return { valid: true, data: a }; - } - if (a instanceof Date && b instanceof Date && +a === +b) { - return { valid: true, data: a }; - } - if (isPlainObject(a) && isPlainObject(b)) { - const bKeys = Object.keys(b); - const sharedKeys = Object.keys(a).filter((key) => bKeys.indexOf(key) !== -1); - const newObj = { ...a, ...b }; - if (Object.prototype.hasOwnProperty.call(newObj, "__proto__")) - delete newObj.__proto__; - for (const key of sharedKeys) { - if (key === "__proto__") - continue; - const sharedValue = schemas_mergeValues(a[key], b[key]); - if (!sharedValue.valid) { - return { - valid: false, - mergeErrorPath: [key, ...sharedValue.mergeErrorPath], - }; - } - newObj[key] = sharedValue.data; - } - return { valid: true, data: newObj }; - } - if (Array.isArray(a) && Array.isArray(b)) { - if (a.length !== b.length) { - return { valid: false, mergeErrorPath: [] }; - } - const newArray = []; - for (let index = 0; index < a.length; index++) { - const itemA = a[index]; - const itemB = b[index]; - const sharedValue = schemas_mergeValues(itemA, itemB); - if (!sharedValue.valid) { - return { - valid: false, - mergeErrorPath: [index, ...sharedValue.mergeErrorPath], - }; - } - newArray.push(sharedValue.data); - } - return { valid: true, data: newArray }; - } - return { valid: false, mergeErrorPath: [] }; -} -function handleIntersectionResults(result, left, right) { - // Track which side(s) reject each key. A key rejection is reported only when BOTH sides reject it, so a key owned by one branch survives the other's key schema. strictObject reports these as unrecognized_keys; a record with an open key schema reports one invalid_key per key. - const unrecKeys = new Map(); - let unrecIssue; - const keyIssues = new Map(); - const collect = (iss, side) => { - let keys; - if (iss.code === "unrecognized_keys" && !iss.path?.length) { - unrecIssue ?? (unrecIssue = iss); - keys = iss.keys; - } - else if (iss.code === "invalid_key" && iss.origin === "record" && iss.path?.length === 1) { - const k = String(iss.path[0]); - if (!keyIssues.has(k)) - keyIssues.set(k, iss); - keys = [k]; - } - else { - return false; - } - for (const k of keys) { - if (!unrecKeys.has(k)) - unrecKeys.set(k, {}); - unrecKeys.get(k)[side] = true; - } - return true; - }; - for (const iss of left.issues) { - if (!collect(iss, "l")) - result.issues.push(iss); - } - for (const iss of right.issues) { - if (!collect(iss, "r")) - result.issues.push(iss); - } - // Report only keys rejected by BOTH sides - const bothKeys = [...unrecKeys].filter(([, f]) => f.l && f.r).map(([k]) => k); - if (bothKeys.length) { - const aggregated = unrecIssue ? bothKeys.filter((k) => unrecIssue.keys.includes(k)) : []; - if (aggregated.length) - result.issues.push({ ...unrecIssue, keys: aggregated }); - for (const k of bothKeys) { - if (!aggregated.includes(k) && keyIssues.has(k)) - result.issues.push(keyIssues.get(k)); - } - } - const merged = schemas_mergeValues(left.value, right.value); - if (!merged.valid) { - if (aborted(result)) - return result; - throw new Error(`Unmergable intersection. Error path: ` + `${JSON.stringify(merged.mergeErrorPath)}`); - } - result.value = merged.data; - return result; -} -const $ZodTuple = /*@__PURE__*/ (/* unused pure expression or super */ null && (core.$constructor("$ZodTuple", (inst, def) => { - $ZodType.init(inst, def); - const items = def.items; - const memo = core.globalConfig.memoizer; - memo?.attach(inst); - inst._zod.parse = (payload, ctx) => { - const input = payload.value; - if (!Array.isArray(input)) { - payload.issues.push({ - input, - inst, - expected: "tuple", - code: "invalid_type", - }); - return payload; - } - payload.value = memo ? memo.alloc(inst, payload, [], ctx) : []; - const proms = []; - const optinStart = getTupleOptStart(items, "optin"); - const optoutStart = getTupleOptStart(items, "optout"); - if (!def.rest) { - if (input.length < optinStart) { - payload.issues.push({ - code: "too_small", - minimum: optinStart, - inclusive: true, - input, - inst, - origin: "array", - }); - return payload; - } - if (input.length > items.length) { - payload.issues.push({ - code: "too_big", - maximum: items.length, - inclusive: true, - input, - inst, - origin: "array", - }); - } - } - // Run every item in parallel, collecting results into an indexed array. The post-processing in `handleTupleResults` walks them in order so it can decide whether an absent optional-output error can truncate the tail or must be reported to preserve required output. - const itemResults = new Array(items.length); - for (let i = 0; i < items.length; i++) { - const r = items[i]._zod.run({ value: input[i], issues: [] }, ctx); - if (r instanceof Promise) { - proms.push(r.then((rr) => { - itemResults[i] = rr; - })); - } - else { - itemResults[i] = r; - } - } - if (def.rest) { - let i = items.length - 1; - const rest = input.slice(items.length); - for (const el of rest) { - i++; - const result = def.rest._zod.run({ value: el, issues: [] }, ctx); - if (result instanceof Promise) { - proms.push(result.then((r) => handleTupleResult(r, payload, i))); - } - else { - handleTupleResult(result, payload, i); - } - } - } - if (proms.length) { - return Promise.all(proms).then(() => handleTupleResults(itemResults, payload, items, input, optoutStart)); - } - return handleTupleResults(itemResults, payload, items, input, optoutStart); - }; -}))); -function getTupleOptStart(items, key) { - for (let i = items.length - 1; i >= 0; i--) { - // optin is a three-rung ladder so any rung above `undefined` permits an absent slot; optout stays two-valued. - const omittable = key === "optin" ? items[i]._zod.optin !== undefined : items[i]._zod.optout === "optional"; - if (!omittable) - return i + 1; - } - return 0; -} -function handleTupleResult(result, final, index) { - if (result.issues.length) { - final.issues.push(...util.prefixIssues(index, result.issues)); - } - final.value[index] = result.value; -} -function handleTupleResults(itemResults, final, items, input, optoutStart) { - // Walk results in order. Mirror $ZodObject's swallow-on-absent-optional rule, but only after `optoutStart`: the first index where the output tuple tail can be absent. - for (let i = 0; i < items.length; i++) { - const r = itemResults[i]; - const isPresent = i < input.length; - // The array analog of `handlePropertyResult`'s absent-key early return: the middle rung permits absence without supplying anything in its place, so the tail truncates here instead of materializing whatever the item made of `undefined`. - if (!isPresent && i >= optoutStart && items[i]._zod.optin === "optional") { - final.value.length = i; - break; - } - if (r.issues.length) { - if (!isPresent && i >= optoutStart) { - final.value.length = i; - break; - } - final.issues.push(...util.prefixIssues(i, r.issues)); - } - final.value[i] = r.value; - } - // Drop trailing slots that produced `undefined` for absent input - // (the array analog of an absent optional key on an object). The - // `i >= input.length` floor is critical: an explicit `undefined` - // *inside* the input must be preserved even when the schema is - // optional-out (e.g. `z.string().or(z.undefined())` accepting an - // explicit undefined value). - for (let i = final.value.length - 1; i >= input.length; i--) { - if (items[i]._zod.optout === "optional" && final.value[i] === undefined) { - final.value.length = i; - } - else { - break; - } - } - return final; -} -const $ZodRecord = /*@__PURE__*/ $constructor("$ZodRecord", (inst, def) => { - $ZodType.init(inst, def); - const memo = globalConfig.memoizer; - memo?.attach(inst); - inst._zod.parse = (payload, ctx) => { - const input = payload.value; - if (!isPlainObject(input)) { - payload.issues.push({ - expected: "record", - code: "invalid_type", - input, - inst, - }); - return payload; - } - const proms = []; - const values = def.keyType._zod.values; - if (values && !def.partial) { - payload.value = memo ? memo.alloc(inst, payload, {}, ctx) : {}; - const recordKeys = new Set(); - for (const key of values) { - if (typeof key === "string" || typeof key === "number" || typeof key === "symbol") { - recordKeys.add(typeof key === "number" ? key.toString() : key); - // A declared __proto__ is stripped but is not an unrecognized key. - if (key === "__proto__") - continue; - const keyResult = def.keyType._zod.run({ value: key, issues: [] }, ctx); - if (keyResult instanceof Promise) { - throw new Error("Async schemas not supported in object keys currently"); - } - if (keyResult.issues.length) { - payload.issues.push({ - code: "invalid_key", - origin: "record", - issues: keyResult.issues.map((iss) => finalizeIssue(iss, ctx, core_config())), - input: key, - path: [key], - inst, - }); - continue; - } - const outKey = keyResult.value; - if (outKey === "__proto__") - continue; - const result = def.valueType._zod.run({ value: input[key], issues: [] }, ctx); - if (result instanceof Promise) { - proms.push(result.then((result) => { - if (result.issues.length) { - payload.issues.push(...prefixIssues(key, result.issues)); - } - payload.value[outKey] = result.value; - })); - } - else { - if (result.issues.length) { - payload.issues.push(...prefixIssues(key, result.issues)); - } - payload.value[outKey] = result.value; - } - } - } - let unrecognized; - for (const key in input) { - if (!recordKeys.has(key)) { - if (def.mode === "loose") { - // skip __proto__ so it can't replace the result prototype via the assignment setter on the plain {} we build into - if (key === "__proto__") - continue; - payload.value[key] = input[key]; - } - else { - unrecognized = unrecognized ?? []; - unrecognized.push(key); - } - } - } - if (unrecognized && unrecognized.length > 0) { - payload.issues.push({ - code: "unrecognized_keys", - input, - inst, - keys: unrecognized, - continue: true, - }); - } - } - else { - payload.value = memo ? memo.alloc(inst, payload, {}, ctx) : {}; - // An enumerable key schema declares which keys the record owns, so a key outside the set is unrecognized. A non-enumerable one (regex, refine) is a constraint every key must satisfy, so a failing key is invalid. Only the former is reconcilable against the other side of an intersection. - let unrecognized; - // Reflect.ownKeys for Symbol-key support; filter non-enumerable to match z.object() - for (const key of Reflect.ownKeys(input)) { - if (key === "__proto__") - continue; - if (!Object.prototype.propertyIsEnumerable.call(input, key)) - continue; - let keyResult = def.keyType._zod.run({ value: key, issues: [] }, ctx); - if (keyResult instanceof Promise) { - throw new Error("Async schemas not supported in object keys currently"); - } - // Numeric string fallback: if key is a numeric string and failed, retry with Number(key). This handles z.number(), z.literal([1, 2, 3]), and unions containing numeric literals - const checkNumericKey = typeof key === "string" && number.test(key) && keyResult.issues.length; - if (checkNumericKey) { - const retryResult = def.keyType._zod.run({ value: Number(key), issues: [] }, ctx); - if (retryResult instanceof Promise) { - throw new Error("Async schemas not supported in object keys currently"); - } - if (retryResult.issues.length === 0) { - keyResult = retryResult; - } - } - if (keyResult.issues.length) { - if (def.mode === "loose") { - // Pass through unchanged - payload.value[key] = input[key]; - } - else if (values) { - unrecognized = unrecognized ?? []; - unrecognized.push(key); - } - else { - // Default "strict" behavior: error on invalid key - payload.issues.push({ - code: "invalid_key", - origin: "record", - issues: keyResult.issues.map((iss) => finalizeIssue(iss, ctx, core_config())), - input: key, - path: [key], - inst, - }); - } - continue; - } - // the guard above tests the raw input key, but the key schema can normalize an ordinary key into __proto__; re-check the key we actually write under - const outKey = keyResult.value; - if (outKey === "__proto__") - continue; - const result = def.valueType._zod.run({ value: input[key], issues: [] }, ctx); - if (result instanceof Promise) { - proms.push(result.then((result) => { - if (result.issues.length) { - payload.issues.push(...prefixIssues(key, result.issues)); - } - payload.value[outKey] = result.value; - })); - } - else { - if (result.issues.length) { - payload.issues.push(...prefixIssues(key, result.issues)); - } - payload.value[outKey] = result.value; - } - } - if (unrecognized && unrecognized.length > 0) { - payload.issues.push({ - code: "unrecognized_keys", - input, - inst, - keys: unrecognized, - continue: true, - }); - } - } - if (proms.length) { - return Promise.all(proms).then(() => payload); - } - return payload; - }; -}); -const $ZodMap = /*@__PURE__*/ (/* unused pure expression or super */ null && (core.$constructor("$ZodMap", (inst, def) => { - $ZodType.init(inst, def); - const memo = core.globalConfig.memoizer; - memo?.attach(inst); - inst._zod.parse = (payload, ctx) => { - const input = payload.value; - if (!(input instanceof Map)) { - payload.issues.push({ - expected: "map", - code: "invalid_type", - input, - inst, - }); - return payload; - } - const proms = []; - payload.value = memo ? memo.alloc(inst, payload, new Map(), ctx) : new Map(); - for (const [key, value] of input) { - const keyResult = def.keyType._zod.run({ value: key, issues: [] }, ctx); - const valueResult = def.valueType._zod.run({ value: value, issues: [] }, ctx); - if (keyResult instanceof Promise || valueResult instanceof Promise) { - proms.push(Promise.all([keyResult, valueResult]).then(([keyResult, valueResult]) => { - handleMapResult(keyResult, valueResult, payload, key, input, inst, ctx); - })); - } - else { - handleMapResult(keyResult, valueResult, payload, key, input, inst, ctx); - } - } - if (proms.length) - return Promise.all(proms).then(() => payload); - return payload; - }; -}))); -function handleMapResult(keyResult, valueResult, final, key, input, inst, ctx) { - if (keyResult.issues.length) { - if (util.propertyKeyTypes.has(typeof key)) { - final.issues.push(...util.prefixIssues(key, keyResult.issues)); - } - else { - final.issues.push({ - code: "invalid_key", - origin: "map", - input, - inst, - issues: keyResult.issues.map((iss) => util.finalizeIssue(iss, ctx, core.config())), - }); - } - } - if (valueResult.issues.length) { - if (util.propertyKeyTypes.has(typeof key)) { - final.issues.push(...util.prefixIssues(key, valueResult.issues)); - } - else { - final.issues.push({ - origin: "map", - code: "invalid_element", - input, - inst, - key: key, - issues: valueResult.issues.map((iss) => util.finalizeIssue(iss, ctx, core.config())), - }); - } - } - final.value.set(keyResult.value, valueResult.value); -} -const $ZodSet = /*@__PURE__*/ (/* unused pure expression or super */ null && (core.$constructor("$ZodSet", (inst, def) => { - $ZodType.init(inst, def); - const memo = core.globalConfig.memoizer; - memo?.attach(inst); - inst._zod.parse = (payload, ctx) => { - const input = payload.value; - if (!(input instanceof Set)) { - payload.issues.push({ - input, - inst, - expected: "set", - code: "invalid_type", - }); - return payload; - } - const proms = []; - payload.value = memo ? memo.alloc(inst, payload, new Set(), ctx) : new Set(); - for (const item of input) { - const result = def.valueType._zod.run({ value: item, issues: [] }, ctx); - if (result instanceof Promise) { - proms.push(result.then((result) => handleSetResult(result, payload))); - } - else - handleSetResult(result, payload); - } - if (proms.length) - return Promise.all(proms).then(() => payload); - return payload; - }; -}))); -function handleSetResult(result, final) { - if (result.issues.length) { - final.issues.push(...result.issues); - } - final.value.add(result.value); -} -const $ZodEnum = /*@__PURE__*/ $constructor("$ZodEnum", (inst, def) => { - $ZodType.init(inst, def); - const values = getEnumValues(def.entries); - const valuesSet = new Set(values); - inst._zod.values = valuesSet; - const patternValues = values.filter((k) => propertyKeyTypes.has(typeof k)); - // unmatchable fallback, RE2-safe: an empty alternation would compile to /^()$/, which matches "" - inst._zod.pattern = new RegExp(patternValues.length ? `^(${patternValues.map((o) => escapeRegex(o.toString())).join("|")})$` : "^[^\\s\\S]$"); - inst._zod.parse = (payload, _ctx) => { - const input = payload.value; - if (valuesSet.has(input)) { - return payload; - } - payload.issues.push({ - code: "invalid_value", - values, - input, - inst, - }); - return payload; - }; -}); -const $ZodLiteral = /*@__PURE__*/ $constructor("$ZodLiteral", (inst, def) => { - $ZodType.init(inst, def); - const values = new Set(def.values); - inst._zod.values = values; - // unmatchable fallback, RE2-safe: an empty alternation would compile to /^()$/, which matches "" - inst._zod.pattern = new RegExp(def.values.length - ? `^(${def.values - .map((o) => (typeof o === "string" ? escapeRegex(o) : o ? escapeRegex(o.toString()) : String(o))) - .join("|")})$` - : "^[^\\s\\S]$"); - inst._zod.parse = (payload, _ctx) => { - const input = payload.value; - if (values.has(input)) { - return payload; - } - payload.issues.push({ - code: "invalid_value", - values: def.values, - input, - inst, - }); - return payload; - }; -}); -const $ZodFile = /*@__PURE__*/ (/* unused pure expression or super */ null && (core.$constructor("$ZodFile", (inst, def) => { - $ZodType.init(inst, def); - inst._zod.parse = (payload, _ctx) => { - const input = payload.value; - // @ts-ignore - if (input instanceof File) - return payload; - payload.issues.push({ - expected: "file", - code: "invalid_type", - input, - inst, - }); - return payload; - }; -}))); -const $ZodTransform = /*@__PURE__*/ $constructor("$ZodTransform", (inst, def) => { - $ZodType.init(inst, def); - inst._zod.optin = "optional"; - globalConfig.memoizer?.guard(inst); - inst._zod.parse = (payload, ctx) => { - if (ctx.direction === "backward") { - throw new $ZodEncodeError(inst.constructor.name); - } - const _out = def.transform(payload.value, payload); - if (ctx.async) { - const output = _out instanceof Promise ? _out : Promise.resolve(_out); - return output.then((output) => { - payload.value = output; - return payload; - }); - } - if (_out instanceof Promise) { - throw new $ZodAsyncError(); - } - payload.value = _out; - return payload; - }; -}); -function handleOptionalResult(payload, result) { - // A substituting schema that still failed has no usable answer; yield undefined. Its issues are simply dropped: it ran on a payload of its own, so there is no shared array to truncate and nothing of the caller's to lose with it. - payload.value = result.issues.length ? undefined : result.value; - return payload; -} -const $ZodOptional = /*@__PURE__*/ $constructor("$ZodOptional", (inst, def) => { - $ZodType.init(inst, def); - // .optional() propagates absence rather than substituting for it, so a defaulted inner keeps its rung. - defineLazyInternal(inst, "optin", (zod) => zod.def.innerType._zod.optin === "defaulted" ? "defaulted" : "optional"); - inst._zod.optout = "optional"; - defineLazyInternal(inst, "values", (zod) => { - const values = zod.def.innerType._zod.values; - return values ? new Set([...values, undefined]) : undefined; - }); - defineLazyInternal(inst, "pattern", (zod) => { - const pattern = zod.def.innerType._zod.pattern; - return pattern ? new RegExp(`^(${cleanRegex(pattern.source)})?$`) : undefined; - }); - inst._zod.parse = (payload, ctx) => { - if (payload.value === undefined) { - // Only the top rung substitutes a value for absence; everything else leaves it intact, which is what .optional() means. - if (def.innerType._zod.optin !== "defaulted") - return payload; - // Its own payload, for the same reason $ZodCatch gets one: a pipe forwards an unrecognized key through the caller's issues array, and this must not read that as the substituting schema failing and drop it. - const result = def.innerType._zod.run({ value: payload.value, issues: [] }, ctx); - if (result instanceof Promise) - return result.then((result) => handleOptionalResult(payload, result)); - return handleOptionalResult(payload, result); - } - return def.innerType._zod.run(payload, ctx); - }; -}); -const $ZodExactOptional = /*@__PURE__*/ $constructor("$ZodExactOptional", (inst, def) => { - // Call parent init - inherits optin/optout = "optional" - $ZodOptional.init(inst, def); - // Override values/pattern to NOT add undefined - defineLazyInternal(inst, "values", (zod) => zod.def.innerType._zod.values); - defineLazyInternal(inst, "pattern", (zod) => zod.def.innerType._zod.pattern); - // Override parse to just delegate (no undefined handling) - inst._zod.parse = (payload, ctx) => { - return def.innerType._zod.run(payload, ctx); - }; -}); -const $ZodNullable = /*@__PURE__*/ $constructor("$ZodNullable", (inst, def) => { - $ZodType.init(inst, def); - defineLazyInternal(inst, "optin", (zod) => zod.def.innerType._zod.optin); - defineLazyInternal(inst, "optout", (zod) => zod.def.innerType._zod.optout); - defineLazyInternal(inst, "pattern", (zod) => { - const pattern = zod.def.innerType._zod.pattern; - return pattern ? new RegExp(`^(${cleanRegex(pattern.source)}|null)$`) : undefined; - }); - defineLazyInternal(inst, "values", (zod) => { - return zod.def.innerType._zod.values ? new Set([...zod.def.innerType._zod.values, null]) : undefined; - }); - inst._zod.parse = (payload, ctx) => { - // Forward direction (decode): allow null to pass through - if (payload.value === null) - return payload; - return def.innerType._zod.run(payload, ctx); - }; -}); -const $ZodDefault = /*@__PURE__*/ $constructor("$ZodDefault", (inst, def) => { - $ZodType.init(inst, def); - // inst._zod.qin = "true"; - inst._zod.optin = "defaulted"; - defineLazyInternal(inst, "values", (zod) => zod.def.innerType._zod.values); - inst._zod.parse = (payload, ctx) => { - if (ctx.direction === "backward") { - return def.innerType._zod.run(payload, ctx); - } - // Forward direction (decode): apply defaults for undefined input - if (payload.value === undefined) { - payload.value = def.defaultValue; - /** - * $ZodDefault returns the default value immediately in forward direction. - * It doesn't pass the default value into the validator ("prefault"). There's no reason to pass the default value through validation. The validity of the default is enforced by TypeScript statically. Otherwise, it's the responsibility of the user to ensure the default is valid. In the case of pipes with divergent in/out types, you can specify the default on the `in` schema of your ZodPipe to set a "prefault" for the pipe. */ - return payload; - } - // Forward direction: continue with default handling - const result = def.innerType._zod.run(payload, ctx); - if (result instanceof Promise) { - return result.then((result) => handleDefaultResult(result, def)); - } - return handleDefaultResult(result, def); - }; -}); -function handleDefaultResult(payload, def) { - if (payload.value === undefined) { - payload.value = def.defaultValue; - } - return payload; -} -const $ZodPrefault = /*@__PURE__*/ $constructor("$ZodPrefault", (inst, def) => { - $ZodType.init(inst, def); - inst._zod.optin = "defaulted"; - defineLazyInternal(inst, "values", (zod) => zod.def.innerType._zod.values); - inst._zod.parse = (payload, ctx) => { - if (ctx.direction === "backward") { - return def.innerType._zod.run(payload, ctx); - } - // Forward direction (decode): apply prefault for undefined input - if (payload.value === undefined) { - payload.value = def.defaultValue; - } - return def.innerType._zod.run(payload, ctx); - }; -}); -const $ZodNonOptional = /*@__PURE__*/ $constructor("$ZodNonOptional", (inst, def) => { - $ZodType.init(inst, def); - defineLazyInternal(inst, "values", (zod) => { - const v = zod.def.innerType._zod.values; - return v ? new Set([...v].filter((x) => x !== undefined)) : undefined; - }); - inst._zod.parse = (payload, ctx) => { - const result = def.innerType._zod.run(payload, ctx); - if (result instanceof Promise) { - return result.then((result) => handleNonOptionalResult(result, inst)); - } - return handleNonOptionalResult(result, inst); - }; -}); -function handleNonOptionalResult(payload, inst) { - if (!payload.issues.length && payload.value === undefined) { - payload.issues.push({ - code: "invalid_type", - expected: "nonoptional", - input: payload.value, - inst, - }); - } - return payload; -} -const $ZodSuccess = /*@__PURE__*/ (/* unused pure expression or super */ null && (core.$constructor("$ZodSuccess", (inst, def) => { - $ZodType.init(inst, def); - inst._zod.parse = (payload, ctx) => { - if (ctx.direction === "backward") { - throw new core.$ZodEncodeError("ZodSuccess"); - } - const result = def.innerType._zod.run(payload, ctx); - if (result instanceof Promise) { - return result.then((result) => { - payload.value = result.issues.length === 0; - return payload; - }); - } - payload.value = result.issues.length === 0; - return payload; - }; -}))); -function handleCatchResult(payload, result, def, ctx) { - if (!result.issues.length) { - payload.value = result.value; - // The value carries up, so the flag describing it has to carry with it: a back-edge into a node still being parsed must not be frozen by an enclosing readonly, and its checks belong to the node itself. Guarded so the ordinary case adds no own property. - if (result.memo) - payload.memo = true; - return payload; - } - // Spread the inner's own payload, not ours: `value` has to stay the input the catch was handed, and the inner ran on a payload of its own so its issues are already private to this call. - payload.value = def.catchValue({ - ...result, - value: payload.value, - error: { - issues: result.issues.map((iss) => finalizeIssue(iss, ctx, core_config())), - }, - input: payload.value, - }); - return payload; -} -const $ZodCatch = /*@__PURE__*/ $constructor("$ZodCatch", (inst, def) => { - $ZodType.init(inst, def); - defineLazyInternal(inst, "optin", (zod) => zod.def.innerType._zod.optin === "defaulted" ? "defaulted" : "optional"); - defineLazyInternal(inst, "optout", (zod) => zod.def.innerType._zod.optout); - defineLazyInternal(inst, "values", (zod) => zod.def.innerType._zod.values); - inst._zod.parse = (payload, ctx) => { - if (ctx.direction === "backward") { - return def.innerType._zod.run(payload, ctx); - } - // Forward direction (decode): apply catch logic - const result = def.innerType._zod.run({ value: payload.value, issues: [] }, ctx); - if (result instanceof Promise) { - return result.then((result) => handleCatchResult(payload, result, def, ctx)); - } - return handleCatchResult(payload, result, def, ctx); - }; -}); -const $ZodNaN = /*@__PURE__*/ (/* unused pure expression or super */ null && (core.$constructor("$ZodNaN", (inst, def) => { - $ZodType.init(inst, def); - inst._zod.parse = (payload, _ctx) => { - if (typeof payload.value !== "number" || !Number.isNaN(payload.value)) { - payload.issues.push({ - input: payload.value, - inst, - expected: "nan", - code: "invalid_type", - }); - return payload; - } - return payload; - }; -}))); -const $ZodPipe = /*@__PURE__*/ $constructor("$ZodPipe", (inst, def) => { - $ZodType.init(inst, def); - defineLazyInternal(inst, "values", (zod) => zod.def.in._zod.values); - defineLazyInternal(inst, "optin", (zod) => zod.def.in._zod.optin); - defineLazyInternal(inst, "optout", (zod) => zod.def.out._zod.optout); - defineLazyInternal(inst, "propValues", (zod) => zod.def.in._zod.propValues); - inst._zod.parse = (payload, ctx) => { - if (ctx.direction === "backward") { - const right = def.out._zod.run(payload, ctx); - if (right instanceof Promise) { - return right.then((right) => handlePipeResult(right, def.in, ctx)); - } - return handlePipeResult(right, def.in, ctx); - } - const left = def.in._zod.run(payload, ctx); - if (left instanceof Promise) { - return left.then((left) => handlePipeResult(left, def.out, ctx)); - } - return handlePipeResult(left, def.out, ctx); - }; -}); -function handlePipeResult(left, next, ctx) { - // Any issue stops the pipe, so a failing refinement never feeds its transform. An unrecognized key is the exception: it describes the input's extra properties, not the value being piped, and an enclosing intersection may yet reconcile it. - if (left.issues.some((iss) => iss.code !== "unrecognized_keys")) { - // prevent further checks - left.aborted = true; - return left; - } - return next._zod.run({ value: left.value, issues: left.issues }, ctx); -} -const $ZodCodec = /*@__PURE__*/ (/* unused pure expression or super */ null && (core.$constructor("$ZodCodec", (inst, def) => { - $ZodType.init(inst, def); - util.defineLazyInternal(inst, "values", (zod) => zod.def.in._zod.values); - util.defineLazyInternal(inst, "optin", (zod) => zod.def.in._zod.optin); - util.defineLazyInternal(inst, "optout", (zod) => zod.def.out._zod.optout); - util.defineLazyInternal(inst, "propValues", (zod) => zod.def.in._zod.propValues); - inst._zod.parse = (payload, ctx) => { - const direction = ctx.direction || "forward"; - if (direction === "forward") { - const left = def.in._zod.run(payload, ctx); - if (left instanceof Promise) { - return left.then((left) => handleCodecAResult(left, def, ctx)); - } - return handleCodecAResult(left, def, ctx); - } - else { - const right = def.out._zod.run(payload, ctx); - if (right instanceof Promise) { - return right.then((right) => handleCodecAResult(right, def, ctx)); - } - return handleCodecAResult(right, def, ctx); - } - }; -}))); -function handleCodecAResult(result, def, ctx) { - if (result.issues.length) { - // prevent further checks - result.aborted = true; - return result; - } - const direction = ctx.direction || "forward"; - if (direction === "forward") { - const transformed = def.transform(result.value, result); - if (transformed instanceof Promise) { - return transformed.then((value) => handleCodecTxResult(result, value, def.out, ctx)); - } - return handleCodecTxResult(result, transformed, def.out, ctx); - } - else { - const transformed = def.reverseTransform(result.value, result); - if (transformed instanceof Promise) { - return transformed.then((value) => handleCodecTxResult(result, value, def.in, ctx)); - } - return handleCodecTxResult(result, transformed, def.in, ctx); - } -} -function handleCodecTxResult(left, value, nextSchema, ctx) { - // Check if transform added any issues - if (left.issues.length) { - left.aborted = true; - return left; - } - return nextSchema._zod.run({ value, issues: left.issues }, ctx); -} -const $ZodPreprocess = /*@__PURE__*/ $constructor("$ZodPreprocess", (inst, def) => { - $ZodPipe.init(inst, def); -}); -const $ZodReadonly = /*@__PURE__*/ $constructor("$ZodReadonly", (inst, def) => { - $ZodType.init(inst, def); - defineLazyInternal(inst, "propValues", (zod) => zod.def.innerType._zod.propValues); - defineLazyInternal(inst, "values", (zod) => zod.def.innerType._zod.values); - defineLazyInternal(inst, "optin", (zod) => zod.def.innerType?._zod?.optin); - defineLazyInternal(inst, "optout", (zod) => zod.def.innerType?._zod?.optout); - inst._zod.parse = (payload, ctx) => { - if (ctx.direction === "backward") { - return def.innerType._zod.run(payload, ctx); - } - const result = def.innerType._zod.run(payload, ctx); - if (result instanceof Promise) { - return result.then(handleReadonlyResult); - } - return handleReadonlyResult(result); - }; -}); -function handleReadonlyResult(payload) { - // A repeat visit hands back a node that is still being built; freezing it here would make the rest of its keys fail to assign. - if (!payload.memo) - payload.value = Object.freeze(payload.value); - return payload; -} -const $ZodTemplateLiteral = /*@__PURE__*/ (/* unused pure expression or super */ null && (core.$constructor("$ZodTemplateLiteral", (inst, def) => { - $ZodType.init(inst, def); - const regexParts = []; - for (const part of def.parts) { - if (typeof part === "object" && part !== null) { - // is Zod schema - if (!part._zod.pattern) { - // if (!source) - throw new Error(`Invalid template literal part, no pattern found: ${[...part._zod.traits].shift()}`); - } - const source = part._zod.pattern instanceof RegExp ? part._zod.pattern.source : part._zod.pattern; - if (!source) - throw new Error(`Invalid template literal part: ${part._zod.traits}`); - const start = source.startsWith("^") ? 1 : 0; - const end = source.endsWith("$") ? source.length - 1 : source.length; - regexParts.push(source.slice(start, end)); - } - else if (part === null || util.primitiveTypes.has(typeof part)) { - regexParts.push(util.escapeRegex(`${part}`)); - } - else { - throw new Error(`Invalid template literal part: ${part}`); - } - } - inst._zod.pattern = new RegExp(`^${regexParts.join("")}$`); - inst._zod.parse = (payload, _ctx) => { - if (typeof payload.value !== "string") { - payload.issues.push({ - input: payload.value, - inst, - expected: "string", - code: "invalid_type", - }); - return payload; - } - inst._zod.pattern.lastIndex = 0; - if (!inst._zod.pattern.test(payload.value)) { - payload.issues.push({ - input: payload.value, - inst, - code: "invalid_format", - format: def.format ?? "template_literal", - pattern: inst._zod.pattern.source, - }); - return payload; - } - return payload; - }; -}))); -const $ZodFunction = /*@__PURE__*/ (/* unused pure expression or super */ null && (core.$constructor("$ZodFunction", (inst, def) => { - $ZodType.init(inst, def); - // Defined, not assigned: the classic prototype exposes `_def` as a getter with no setter. - Object.defineProperty(inst, "_def", { value: def }); - inst._zod.def = def; - inst.implement = (func) => { - if (typeof func !== "function") { - throw new Error("implement() must be called with a function"); - } - // Defined inline so the closure stays anonymous: binding it to a `const` first names it, which costs 256 bytes per implemented function. - return Object.defineProperty(function (...args) { - const parsedArgs = inst._def.input ? parse(inst._def.input, args) : args; - const result = Reflect.apply(func, this, parsedArgs); - if (inst._def.output) { - return parse(inst._def.output, result); - } - return result; - }, "_zod", { value: inst._zod, enumerable: false }); - }; - inst.implementAsync = (func) => { - if (typeof func !== "function") { - throw new Error("implementAsync() must be called with a function"); - } - return Object.defineProperty(async function (...args) { - const parsedArgs = inst._def.input ? await parseAsync(inst._def.input, args) : args; - const result = await Reflect.apply(func, this, parsedArgs); - if (inst._def.output) { - return await parseAsync(inst._def.output, result); - } - return result; - }, "_zod", { value: inst._zod, enumerable: false }); - }; - inst._zod.parse = (payload, _ctx) => { - if (typeof payload.value !== "function") { - payload.issues.push({ - code: "invalid_type", - expected: "function", - input: payload.value, - inst, - }); - return payload; - } - // Check if output is a promise type to determine if we should use async implementation - const hasPromiseOutput = inst._def.output && inst._def.output._zod.def.type === "promise"; - if (hasPromiseOutput) { - payload.value = inst.implementAsync(payload.value); - } - else { - payload.value = inst.implement(payload.value); - } - return payload; - }; - inst.input = (...args) => { - const F = inst.constructor; - if (Array.isArray(args[0])) { - return new F({ - type: "function", - input: new $ZodTuple({ - type: "tuple", - items: args[0], - rest: args[1], - }), - output: inst._def.output, - }); - } - return new F({ - type: "function", - input: args[0], - output: inst._def.output, - }); - }; - inst.output = (output) => { - const F = inst.constructor; - return new F({ - type: "function", - input: inst._def.input, - output, - }); - }; - return inst; -}))); -const $ZodPromise = /*@__PURE__*/ (/* unused pure expression or super */ null && (core.$constructor("$ZodPromise", (inst, def) => { - $ZodType.init(inst, def); - inst._zod.parse = (payload, ctx) => { - return Promise.resolve(payload.value).then((inner) => def.innerType._zod.run({ value: inner, issues: [] }, ctx)); - }; -}))); -const $ZodLazy = /*@__PURE__*/ $constructor("$ZodLazy", (inst, def) => { - $ZodType.init(inst, def); - // Cache the resolved inner type on the shared `def` so all clones of this lazy (e.g. via `.describe()`/`.meta()`) share the same inner instance, preserving identity for cycle detection on recursive schemas. - defineLazy(inst._zod, "innerType", () => { - const d = def; - if (!d._cachedInner) - d._cachedInner = def.getter(); - return d._cachedInner; - }); - defineLazyInternal(inst, "pattern", (zod) => zod.innerType?._zod?.pattern); - defineLazyInternal(inst, "propValues", (zod) => zod.innerType?._zod?.propValues); - defineLazyInternal(inst, "optin", (zod) => zod.innerType?._zod?.optin ?? undefined); - defineLazyInternal(inst, "optout", (zod) => zod.innerType?._zod?.optout ?? undefined); - inst._zod.parse = (payload, ctx) => { - const inner = inst._zod.innerType; - return inner._zod.run(payload, ctx); - }; -}); -const $ZodCustom = /*@__PURE__*/ $constructor("$ZodCustom", (inst, def) => { - $ZodCheck.init(inst, def); - $ZodType.init(inst, def); - inst._zod.parse = (payload, _) => { - return payload; - }; - inst._zod.check = (payload) => { - const input = payload.value; - const r = def.fn(input); - if (r instanceof Promise) { - return r.then((r) => handleRefineResult(r, payload, input, inst)); - } - handleRefineResult(r, payload, input, inst); - return; - }; -}); -function handleRefineResult(result, payload, input, inst) { - if (!result) { - const _iss = { - code: "custom", - input, - inst, // incorporates params.error into issue reporting - path: [...(inst._zod.def.path ?? [])], // incorporates params.error into issue reporting - continue: !inst._zod.def.abort, - // params: inst._zod.def.params, - }; - if (inst._zod.def.params) - _iss.params = inst._zod.def.params; - payload.issues.push(util_issue(_iss)); - } -} - -var registries_a; -const $output = /*@__PURE__*/ (/* unused pure expression or super */ null && (Symbol("ZodOutput"))); -const $input = /*@__PURE__*/ (/* unused pure expression or super */ null && (Symbol("ZodInput"))); -class $ZodRegistry { - constructor() { - this._map = new WeakMap(); - this._idmap = new Map(); - } - add(schema, ..._meta) { - const meta = _meta[0]; - this._map.set(schema, meta); - if (meta && typeof meta === "object" && "id" in meta) { - this._idmap.set(meta.id, schema); - } - return this; - } - clear() { - this._map = new WeakMap(); - this._idmap = new Map(); - return this; - } - remove(schema) { - const meta = this._map.get(schema); - if (meta && typeof meta === "object" && "id" in meta) { - this._idmap.delete(meta.id); - } - this._map.delete(schema); - return this; - } - get(schema) { - // return this._map.get(schema) as any; - // inherit metadata - const p = schema._zod.parent; - if (p) { - const pm = { ...(this.get(p) ?? {}) }; - delete pm.id; // do not inherit id - const f = { ...pm, ...this._map.get(schema) }; - return Object.keys(f).length ? f : undefined; - } - return this._map.get(schema); - } - has(schema) { - return this._map.has(schema); - } -} -// registries -function registries_registry() { - return new $ZodRegistry(); -} -(registries_a = globalThis).__zod_globalRegistry ?? (registries_a.__zod_globalRegistry = registries_registry()); -const globalRegistry = globalThis.__zod_globalRegistry; - - - - - -// @__NO_SIDE_EFFECTS__ -function _string(Class, params) { - return new Class({ - type: "string", - ...normalizeParams(params), - }); -} -// @__NO_SIDE_EFFECTS__ -function _coercedString(Class, params) { - return new Class({ - type: "string", - coerce: true, - ...util.normalizeParams(params), - }); -} -// @__NO_SIDE_EFFECTS__ -function _email(Class, params) { - return new Class({ - type: "string", - format: "email", - check: "string_format", - abort: false, - ...normalizeParams(params), - }); -} -// @__NO_SIDE_EFFECTS__ -function _guid(Class, params) { - return new Class({ - type: "string", - format: "guid", - check: "string_format", - abort: false, - ...normalizeParams(params), - }); -} -// @__NO_SIDE_EFFECTS__ -function _uuid(Class, params) { - return new Class({ - type: "string", - format: "uuid", - check: "string_format", - abort: false, - ...normalizeParams(params), - }); -} -// @__NO_SIDE_EFFECTS__ -function _uuidv4(Class, params) { - return new Class({ - type: "string", - format: "uuid", - check: "string_format", - abort: false, - version: "v4", - ...normalizeParams(params), - }); -} -// @__NO_SIDE_EFFECTS__ -function _uuidv6(Class, params) { - return new Class({ - type: "string", - format: "uuid", - check: "string_format", - abort: false, - version: "v6", - ...normalizeParams(params), - }); -} -// @__NO_SIDE_EFFECTS__ -function _uuidv7(Class, params) { - return new Class({ - type: "string", - format: "uuid", - check: "string_format", - abort: false, - version: "v7", - ...normalizeParams(params), - }); -} -// @__NO_SIDE_EFFECTS__ -function _url(Class, params) { - return new Class({ - type: "string", - format: "url", - check: "string_format", - abort: false, - ...normalizeParams(params), - }); -} -// @__NO_SIDE_EFFECTS__ -function api_emoji(Class, params) { - return new Class({ - type: "string", - format: "emoji", - check: "string_format", - abort: false, - ...normalizeParams(params), - }); -} -// @__NO_SIDE_EFFECTS__ -function _nanoid(Class, params) { - return new Class({ - type: "string", - format: "nanoid", - check: "string_format", - abort: false, - ...normalizeParams(params), - }); -} -/** - * @deprecated CUID v1 is deprecated by its authors due to information leakage - * (timestamps embedded in the id). Use {@link _cuid2} instead. - * See https://github.com/paralleldrive/cuid. - */ -// @__NO_SIDE_EFFECTS__ -function _cuid(Class, params) { - return new Class({ - type: "string", - format: "cuid", - check: "string_format", - abort: false, - ...normalizeParams(params), - }); -} -// @__NO_SIDE_EFFECTS__ -function _cuid2(Class, params) { - return new Class({ - type: "string", - format: "cuid2", - check: "string_format", - abort: false, - ...normalizeParams(params), - }); -} -// @__NO_SIDE_EFFECTS__ -function _ulid(Class, params) { - return new Class({ - type: "string", - format: "ulid", - check: "string_format", - abort: false, - ...normalizeParams(params), - }); -} -// @__NO_SIDE_EFFECTS__ -function _xid(Class, params) { - return new Class({ - type: "string", - format: "xid", - check: "string_format", - abort: false, - ...normalizeParams(params), - }); -} -// @__NO_SIDE_EFFECTS__ -function _ksuid(Class, params) { - return new Class({ - type: "string", - format: "ksuid", - check: "string_format", - abort: false, - ...normalizeParams(params), - }); -} -// @__NO_SIDE_EFFECTS__ -function _ipv4(Class, params) { - return new Class({ - type: "string", - format: "ipv4", - check: "string_format", - abort: false, - ...normalizeParams(params), - }); -} -// @__NO_SIDE_EFFECTS__ -function _ipv6(Class, params) { - return new Class({ - type: "string", - format: "ipv6", - check: "string_format", - abort: false, - ...normalizeParams(params), - }); -} -// @__NO_SIDE_EFFECTS__ -function _mac(Class, params) { - return new Class({ - type: "string", - format: "mac", - check: "string_format", - abort: false, - ...util.normalizeParams(params), - }); -} -// @__NO_SIDE_EFFECTS__ -function _cidrv4(Class, params) { - return new Class({ - type: "string", - format: "cidrv4", - check: "string_format", - abort: false, - ...normalizeParams(params), - }); -} -// @__NO_SIDE_EFFECTS__ -function _cidrv6(Class, params) { - return new Class({ - type: "string", - format: "cidrv6", - check: "string_format", - abort: false, - ...normalizeParams(params), - }); -} -// @__NO_SIDE_EFFECTS__ -function _base64(Class, params) { - return new Class({ - type: "string", - format: "base64", - check: "string_format", - abort: false, - ...normalizeParams(params), - }); -} -// @__NO_SIDE_EFFECTS__ -function _base64url(Class, params) { - return new Class({ - type: "string", - format: "base64url", - check: "string_format", - abort: false, - ...normalizeParams(params), - }); -} -// @__NO_SIDE_EFFECTS__ -function _e164(Class, params) { - return new Class({ - type: "string", - format: "e164", - check: "string_format", - abort: false, - ...normalizeParams(params), - }); -} -// @__NO_SIDE_EFFECTS__ -function _creditCard(Class, params) { - return new Class({ - type: "string", - format: "credit_card", - check: "string_format", - abort: false, - ...util.normalizeParams(params), - }); -} -// @__NO_SIDE_EFFECTS__ -function _jwt(Class, params) { - return new Class({ - type: "string", - format: "jwt", - check: "string_format", - abort: false, - ...normalizeParams(params), - }); -} -const TimePrecision = (/* unused pure expression or super */ null && ({ - Any: null, - Minute: -1, - Second: 0, - Millisecond: 3, - Microsecond: 6, -})); -// @__NO_SIDE_EFFECTS__ -function _isoDateTime(Class, params) { - return new Class({ - type: "string", - format: "datetime", - check: "string_format", - offset: false, - local: false, - precision: null, - ...normalizeParams(params), - }); -} -// @__NO_SIDE_EFFECTS__ -function _isoDate(Class, params) { - return new Class({ - type: "string", - format: "date", - check: "string_format", - ...normalizeParams(params), - }); -} -// @__NO_SIDE_EFFECTS__ -function _isoTime(Class, params) { - return new Class({ - type: "string", - format: "time", - check: "string_format", - precision: null, - ...normalizeParams(params), - }); -} -// @__NO_SIDE_EFFECTS__ -function _isoDuration(Class, params) { - return new Class({ - type: "string", - format: "duration", - check: "string_format", - ...normalizeParams(params), - }); -} -// @__NO_SIDE_EFFECTS__ -function _number(Class, params) { - return new Class({ - type: "number", - checks: [], - ...normalizeParams(params), - }); -} -// @__NO_SIDE_EFFECTS__ -function _coercedNumber(Class, params) { - return new Class({ - type: "number", - coerce: true, - checks: [], - ...normalizeParams(params), - }); -} -// @__NO_SIDE_EFFECTS__ -function _int(Class, params) { - return new Class({ - type: "number", - check: "number_format", - abort: false, - format: "safeint", - ...normalizeParams(params), - }); -} -// @__NO_SIDE_EFFECTS__ -function _float32(Class, params) { - return new Class({ - type: "number", - check: "number_format", - abort: false, - format: "float32", - ...util.normalizeParams(params), - }); -} -// @__NO_SIDE_EFFECTS__ -function _float64(Class, params) { - return new Class({ - type: "number", - check: "number_format", - abort: false, - format: "float64", - ...util.normalizeParams(params), - }); -} -// @__NO_SIDE_EFFECTS__ -function _int32(Class, params) { - return new Class({ - type: "number", - check: "number_format", - abort: false, - format: "int32", - ...util.normalizeParams(params), - }); -} -// @__NO_SIDE_EFFECTS__ -function _uint32(Class, params) { - return new Class({ - type: "number", - check: "number_format", - abort: false, - format: "uint32", - ...util.normalizeParams(params), - }); -} -// @__NO_SIDE_EFFECTS__ -function _boolean(Class, params) { - return new Class({ - type: "boolean", - ...normalizeParams(params), - }); -} -// @__NO_SIDE_EFFECTS__ -function _coercedBoolean(Class, params) { - return new Class({ - type: "boolean", - coerce: true, - ...util.normalizeParams(params), - }); -} -// @__NO_SIDE_EFFECTS__ -function _bigint(Class, params) { - return new Class({ - type: "bigint", - ...util.normalizeParams(params), - }); -} -// @__NO_SIDE_EFFECTS__ -function _coercedBigint(Class, params) { - return new Class({ - type: "bigint", - coerce: true, - ...util.normalizeParams(params), - }); -} -// @__NO_SIDE_EFFECTS__ -function _int64(Class, params) { - return new Class({ - type: "bigint", - check: "bigint_format", - abort: false, - format: "int64", - ...util.normalizeParams(params), - }); -} -// @__NO_SIDE_EFFECTS__ -function _uint64(Class, params) { - return new Class({ - type: "bigint", - check: "bigint_format", - abort: false, - format: "uint64", - ...util.normalizeParams(params), - }); -} -// @__NO_SIDE_EFFECTS__ -function _symbol(Class, params) { - return new Class({ - type: "symbol", - ...util.normalizeParams(params), - }); -} -// @__NO_SIDE_EFFECTS__ -function api_undefined(Class, params) { - return new Class({ - type: "undefined", - ...util.normalizeParams(params), - }); -} -// @__NO_SIDE_EFFECTS__ -function api_null(Class, params) { - return new Class({ - type: "null", - ...normalizeParams(params), - }); -} -// @__NO_SIDE_EFFECTS__ -function _any(Class) { - return new Class({ - type: "any", - }); -} -// @__NO_SIDE_EFFECTS__ -function _unknown(Class) { - return new Class({ - type: "unknown", - }); -} -// @__NO_SIDE_EFFECTS__ -function _never(Class, params) { - return new Class({ - type: "never", - ...normalizeParams(params), - }); -} -// @__NO_SIDE_EFFECTS__ -function _void(Class, params) { - return new Class({ - type: "void", - ...util.normalizeParams(params), - }); -} -// @__NO_SIDE_EFFECTS__ -function _date(Class, params) { - return new Class({ - type: "date", - ...util.normalizeParams(params), - }); -} -// @__NO_SIDE_EFFECTS__ -function _coercedDate(Class, params) { - return new Class({ - type: "date", - coerce: true, - ...util.normalizeParams(params), - }); -} -// @__NO_SIDE_EFFECTS__ -function _nan(Class, params) { - return new Class({ - type: "nan", - ...util.normalizeParams(params), - }); -} -// @__NO_SIDE_EFFECTS__ -function _lt(value, params) { - return new $ZodCheckLessThan({ - check: "less_than", - ...normalizeParams(params), - value, - inclusive: false, - }); -} -// @__NO_SIDE_EFFECTS__ -function _lte(value, params) { - return new $ZodCheckLessThan({ - check: "less_than", - ...normalizeParams(params), - value, - inclusive: true, - }); -} - -// @__NO_SIDE_EFFECTS__ -function _gt(value, params) { - return new $ZodCheckGreaterThan({ - check: "greater_than", - ...normalizeParams(params), - value, - inclusive: false, - }); -} -// @__NO_SIDE_EFFECTS__ -function _gte(value, params) { - return new $ZodCheckGreaterThan({ - check: "greater_than", - ...normalizeParams(params), - value, - inclusive: true, - }); -} - -// @__NO_SIDE_EFFECTS__ -function _positive(params) { - return _gt(0, params); -} -// negative -// @__NO_SIDE_EFFECTS__ -function _negative(params) { - return _lt(0, params); -} -// nonpositive -// @__NO_SIDE_EFFECTS__ -function _nonpositive(params) { - return _lte(0, params); -} -// nonnegative -// @__NO_SIDE_EFFECTS__ -function _nonnegative(params) { - return _gte(0, params); -} -// @__NO_SIDE_EFFECTS__ -function _multipleOf(value, params) { - return new $ZodCheckMultipleOf({ - check: "multiple_of", - ...normalizeParams(params), - value, - }); -} -// @__NO_SIDE_EFFECTS__ -function _maxSize(maximum, params) { - return new checks.$ZodCheckMaxSize({ - check: "max_size", - ...util.normalizeParams(params), - maximum, - }); -} -// @__NO_SIDE_EFFECTS__ -function _minSize(minimum, params) { - return new checks.$ZodCheckMinSize({ - check: "min_size", - ...util.normalizeParams(params), - minimum, - }); -} -// @__NO_SIDE_EFFECTS__ -function _size(size, params) { - return new checks.$ZodCheckSizeEquals({ - check: "size_equals", - ...util.normalizeParams(params), - size, - }); -} -// @__NO_SIDE_EFFECTS__ -function _maxLength(maximum, params) { - const ch = new $ZodCheckMaxLength({ - check: "max_length", - ...normalizeParams(params), - maximum, - }); - return ch; -} -// @__NO_SIDE_EFFECTS__ -function _minLength(minimum, params) { - return new $ZodCheckMinLength({ - check: "min_length", - ...normalizeParams(params), - minimum, - }); -} -// @__NO_SIDE_EFFECTS__ -function _length(length, params) { - return new $ZodCheckLengthEquals({ - check: "length_equals", - ...normalizeParams(params), - length, - }); -} -// @__NO_SIDE_EFFECTS__ -function _regex(pattern, params) { - return new $ZodCheckRegex({ - check: "string_format", - format: "regex", - ...normalizeParams(params), - pattern, - }); -} -// @__NO_SIDE_EFFECTS__ -function _lowercase(params) { - return new $ZodCheckLowerCase({ - check: "string_format", - format: "lowercase", - ...normalizeParams(params), - }); -} -// @__NO_SIDE_EFFECTS__ -function _uppercase(params) { - return new $ZodCheckUpperCase({ - check: "string_format", - format: "uppercase", - ...normalizeParams(params), - }); -} -// @__NO_SIDE_EFFECTS__ -function _includes(includes, params) { - return new $ZodCheckIncludes({ - check: "string_format", - format: "includes", - ...normalizeParams(params), - includes, - }); -} -// @__NO_SIDE_EFFECTS__ -function _startsWith(prefix, params) { - return new $ZodCheckStartsWith({ - check: "string_format", - format: "starts_with", - ...normalizeParams(params), - prefix, - }); -} -// @__NO_SIDE_EFFECTS__ -function _endsWith(suffix, params) { - return new $ZodCheckEndsWith({ - check: "string_format", - format: "ends_with", - ...normalizeParams(params), - suffix, - }); -} -// @__NO_SIDE_EFFECTS__ -function _property(property, schema, params) { - return new checks.$ZodCheckProperty({ - check: "property", - property, - schema, - ...util.normalizeParams(params), - }); -} -// @__NO_SIDE_EFFECTS__ -function _properties(shape) { - return Object.entries(shape).map(([property, schema]) => new checks.$ZodCheckProperty({ check: "property", property, schema })); -} -// @__NO_SIDE_EFFECTS__ -function _mime(types, params) { - return new checks.$ZodCheckMimeType({ - check: "mime_type", - mime: types, - ...util.normalizeParams(params), - }); -} -// @__NO_SIDE_EFFECTS__ -function _overwrite(tx) { - return new $ZodCheckOverwrite({ - check: "overwrite", - tx, - }); -} -// normalize -// @__NO_SIDE_EFFECTS__ -function _normalize(form) { - return _overwrite((input) => input.normalize(form)); -} -// trim -// @__NO_SIDE_EFFECTS__ -function _trim() { - return _overwrite((input) => input.trim()); -} -// toLowerCase -// @__NO_SIDE_EFFECTS__ -function _toLowerCase() { - return _overwrite((input) => input.toLowerCase()); -} -// toUpperCase -// @__NO_SIDE_EFFECTS__ -function _toUpperCase() { - return _overwrite((input) => input.toUpperCase()); -} -// slugify -// @__NO_SIDE_EFFECTS__ -function _slugify() { - return _overwrite((input) => slugify(input)); -} -// @__NO_SIDE_EFFECTS__ -function _array(Class, element, params) { - return new Class({ - type: "array", - element, - // get element() { - // return element; - // }, - ...normalizeParams(params), - }); -} -// @__NO_SIDE_EFFECTS__ -function _union(Class, options, params) { - return new Class({ - type: "union", - options, - ...util.normalizeParams(params), - }); -} -function _xor(Class, options, params) { - return new Class({ - type: "union", - options, - inclusive: false, - ...util.normalizeParams(params), - }); -} -// @__NO_SIDE_EFFECTS__ -function _discriminatedUnion(Class, discriminator, options, params) { - return new Class({ - type: "union", - options: options, - discriminator, - ...util.normalizeParams(params), - }); -} -// @__NO_SIDE_EFFECTS__ -function _intersection(Class, left, right) { - return new Class({ - type: "intersection", - left, - right, - }); -} -// export function _tuple( -// Class: util.SchemaClass, -// items: [], -// params?: string | $ZodTupleParams -// ): schemas.$ZodTuple<[], null>; -// @__NO_SIDE_EFFECTS__ -function _tuple(Class, items, _paramsOrRest, _params) { - const hasRest = _paramsOrRest instanceof schemas.$ZodType; - const params = hasRest ? _params : _paramsOrRest; - const rest = hasRest ? _paramsOrRest : null; - return new Class({ - type: "tuple", - items, - rest, - ...util.normalizeParams(params), - }); -} -// @__NO_SIDE_EFFECTS__ -function _record(Class, keyType, valueType, params) { - return new Class({ - type: "record", - keyType, - valueType, - ...util.normalizeParams(params), - }); -} -// @__NO_SIDE_EFFECTS__ -function _map(Class, keyType, valueType, params) { - return new Class({ - type: "map", - keyType, - valueType, - ...util.normalizeParams(params), - }); -} -// @__NO_SIDE_EFFECTS__ -function _set(Class, valueType, params) { - return new Class({ - type: "set", - valueType, - ...util.normalizeParams(params), - }); -} -// @__NO_SIDE_EFFECTS__ -function _enum(Class, values, params) { - const entries = Array.isArray(values) ? Object.fromEntries(values.map((v) => [v, v])) : values; - // if (Array.isArray(values)) { - // for (const value of values) { - // entries[value] = value; - // } - // } else { - // Object.assign(entries, values); - // } - // const entries: util.EnumLike = {}; - // for (const val of values) { - // entries[val] = val; - // } - return new Class({ - type: "enum", - entries, - ...util.normalizeParams(params), - }); -} -// @__NO_SIDE_EFFECTS__ -/** @deprecated This API has been merged into `z.enum()`. Use `z.enum()` instead. - * - * ```ts - * enum Colors { red, green, blue } - * z.enum(Colors); - * ``` - */ -function _nativeEnum(Class, entries, params) { - return new Class({ - type: "enum", - entries, - ...util.normalizeParams(params), - }); -} -// @__NO_SIDE_EFFECTS__ -function _literal(Class, value, params) { - return new Class({ - type: "literal", - values: Array.isArray(value) ? value : [value], - ...util.normalizeParams(params), - }); -} -// @__NO_SIDE_EFFECTS__ -function _file(Class, params) { - return new Class({ - type: "file", - ...util.normalizeParams(params), - }); -} -// @__NO_SIDE_EFFECTS__ -function _transform(Class, fn) { - return new Class({ - type: "transform", - transform: fn, - }); -} -// @__NO_SIDE_EFFECTS__ -function _optional(Class, innerType) { - return new Class({ - type: "optional", - innerType, - }); -} -// @__NO_SIDE_EFFECTS__ -function _nullable(Class, innerType) { - return new Class({ - type: "nullable", - innerType, - }); -} -// @__NO_SIDE_EFFECTS__ -function _default(Class, innerType, defaultValue) { - return new Class({ - type: "default", - innerType, - get defaultValue() { - return typeof defaultValue === "function" ? defaultValue() : util.shallowClone(defaultValue); - }, - }); -} -// @__NO_SIDE_EFFECTS__ -function _nonoptional(Class, innerType, params) { - return new Class({ - type: "nonoptional", - innerType, - ...util.normalizeParams(params), - }); -} -// @__NO_SIDE_EFFECTS__ -function _success(Class, innerType) { - return new Class({ - type: "success", - innerType, - }); -} -// @__NO_SIDE_EFFECTS__ -function _catch(Class, innerType, catchValue) { - return new Class({ - type: "catch", - innerType, - catchValue: (typeof catchValue === "function" ? catchValue : util.constantCatch(catchValue)), - }); -} -// @__NO_SIDE_EFFECTS__ -function _pipe(Class, in_, out) { - return new Class({ - type: "pipe", - in: in_, - out, - }); -} -// @__NO_SIDE_EFFECTS__ -function _readonly(Class, innerType) { - return new Class({ - type: "readonly", - innerType, - }); -} -// @__NO_SIDE_EFFECTS__ -function _templateLiteral(Class, parts, params) { - return new Class({ - type: "template_literal", - parts, - ...util.normalizeParams(params), - }); -} -// @__NO_SIDE_EFFECTS__ -function _lazy(Class, getter) { - return new Class({ - type: "lazy", - getter, - }); -} -// @__NO_SIDE_EFFECTS__ -function _promise(Class, innerType) { - return new Class({ - type: "promise", - innerType, - }); -} -// @__NO_SIDE_EFFECTS__ -function _custom(Class, fn, _params) { - const norm = util.normalizeParams(_params); - norm.abort ?? (norm.abort = true); // default to abort:false - const schema = new Class({ - type: "custom", - check: "custom", - fn: fn, - ...norm, - }); - return schema; -} -// same as _custom but defaults to abort:false -// @__NO_SIDE_EFFECTS__ -function _refine(Class, fn, _params) { - const schema = new Class({ - type: "custom", - check: "custom", - fn: fn, - ...normalizeParams(_params), - }); - return schema; -} -// @__NO_SIDE_EFFECTS__ -function _superRefine(fn, params) { - const ch = _check((payload) => { - payload.addIssue = (issue) => { - if (typeof issue === "string") { - payload.issues.push(util_issue(issue, payload.value, ch._zod.def)); - } - else { - // for Zod 3 backwards compatibility - const _issue = issue; - if (_issue.fatal) - _issue.continue = false; - _issue.code ?? (_issue.code = "custom"); - if (!("input" in _issue)) - _issue.input = payload.value; - _issue.inst ?? (_issue.inst = ch); - _issue.continue ?? (_issue.continue = !ch._zod.def.abort); // abort is always undefined, so this is always true... - payload.issues.push(util_issue(_issue)); - } - }; - return fn(payload.value, payload); - }, params); - return ch; -} -// @__NO_SIDE_EFFECTS__ -function _check(fn, params) { - const ch = new $ZodCheck({ - check: "custom", - ...normalizeParams(params), - }); - ch._zod.check = fn; - return ch; -} -// @__NO_SIDE_EFFECTS__ -function describe(description) { - const ch = new $ZodCheck({ check: "describe" }); - ch._zod.onattach = [ - (inst) => { - const existing = globalRegistry.get(inst) ?? {}; - globalRegistry.add(inst, { ...existing, description }); - }, - ]; - ch._zod.check = () => { }; // no-op check - return ch; -} -// @__NO_SIDE_EFFECTS__ -function api_meta(metadata) { - const ch = new $ZodCheck({ check: "meta" }); - ch._zod.onattach = [ - (inst) => { - const existing = globalRegistry.get(inst) ?? {}; - globalRegistry.add(inst, { ...existing, ...metadata }); - }, - ]; - ch._zod.check = () => { }; // no-op check - return ch; -} -// @__NO_SIDE_EFFECTS__ -function _stringbool(Classes, _params) { - const params = util.normalizeParams(_params); - let truthyArray = params.truthy ?? ["true", "1", "yes", "on", "y", "enabled"]; - let falsyArray = params.falsy ?? ["false", "0", "no", "off", "n", "disabled"]; - if (params.case !== "sensitive") { - truthyArray = truthyArray.map((v) => (typeof v === "string" ? v.toLowerCase() : v)); - falsyArray = falsyArray.map((v) => (typeof v === "string" ? v.toLowerCase() : v)); - } - const truthySet = new Set(truthyArray); - const falsySet = new Set(falsyArray); - const _Codec = Classes.Codec ?? schemas.$ZodCodec; - const _Boolean = Classes.Boolean ?? schemas.$ZodBoolean; - const _String = Classes.String ?? schemas.$ZodString; - const stringSchema = new _String({ type: "string", error: params.error }); - const booleanSchema = new _Boolean({ type: "boolean", error: params.error }); - const codec = new _Codec({ - type: "pipe", - in: stringSchema, - out: booleanSchema, - transform: ((input, payload) => { - let data = input; - if (params.case !== "sensitive") - data = data.toLowerCase(); - if (truthySet.has(data)) { - return true; - } - else if (falsySet.has(data)) { - return false; - } - else { - payload.issues.push({ - code: "invalid_value", - expected: "stringbool", - values: [...truthySet, ...falsySet], - input: payload.value, - inst: codec, - continue: false, - }); - return {}; - } - }), - reverseTransform: ((input, _payload) => { - if (input === true) { - return truthyArray[0] || "true"; - } - else { - return falsyArray[0] || "false"; - } - }), - error: params.error, - }); - codec._zod.bag.truthy = truthyArray; - codec._zod.bag.falsy = falsyArray; - codec._zod.bag.case = params.case ?? "insensitive"; - return codec; -} -// @__NO_SIDE_EFFECTS__ -function _stringFormat(Class, format, fnOrRegex, _params = {}) { - const params = util.normalizeParams(_params); - const def = { - check: "string_format", - type: "string", - format, - fn: typeof fnOrRegex === "function" ? fnOrRegex : (val) => fnOrRegex.test(val), - ...params, - }; - if (fnOrRegex instanceof RegExp) { - def.pattern = fnOrRegex; - } - const inst = new Class(def); - return inst; -} - - - -function assignProps(target, ...sources) { - for (const source of sources) { - for (const key of Reflect.ownKeys(source)) { - if (Object.prototype.propertyIsEnumerable.call(source, key)) { - assignProp(target, key, source[key]); - } - } - } - return target; -} -// function initializeContext(inputs: JSONSchemaGeneratorParams): ToJSONSchemaContext { -// return { -// processor: inputs.processor, -// metadataRegistry: inputs.metadata ?? globalRegistry, -// target: inputs.target ?? "draft-2020-12", -// unrepresentable: inputs.unrepresentable ?? "throw", -// }; -// } -function initializeContext(params) { - // Normalize target: convert old non-hyphenated versions to hyphenated versions - let target = params?.target ?? "draft-2020-12"; - if (target === "draft-4") - target = "draft-04"; - if (target === "draft-7") - target = "draft-07"; - return { - processors: params.processors ?? {}, - metadataRegistry: params?.metadata ?? globalRegistry, - target, - unrepresentable: params?.unrepresentable ?? "throw", - override: params?.override ?? (() => { }), - io: params?.io ?? "output", - counter: 0, - seen: new Map(), - sharedDefsExtractedFor: undefined, - sharedEmitDoneFor: undefined, - cycles: params?.cycles ?? "ref", - reused: params?.reused ?? "inline", - intersections: [], - deferred: [], - external: params?.external ?? undefined, - }; -} -/** - * Applies the `unrepresentable` setting at a site that has no JSON Schema equivalent. Throws - * `message` unless the setting (or the handler's return value) says otherwise. Returns `true` if a - * custom JSON Schema was written into `json`, in which case the caller must not write its own. - */ -function handleUnrepresentable(schema, ctx, json, params, message) { - const result = typeof ctx.unrepresentable === "function" - ? ctx.unrepresentable({ zodSchema: schema, path: params.path, message }) - : ctx.unrepresentable; - if (result === "any") - return false; - if (result === undefined || result === "throw") - throw new Error(message); - Object.assign(json, result); - return true; -} -function to_json_schema_process(schema, ctx, _params = { path: [], schemaPath: [] }) { - var _a; - const def = schema._zod.def; - // check for schema in seens - const seen = ctx.seen.get(schema); - if (seen) { - seen.count++; - // check if cycle - const isCycle = _params.schemaPath.includes(schema); - if (isCycle) { - seen.cycle = _params.path; - } - return seen.schema; - } - // initialize - const result = { schema: {}, count: 1, cycle: undefined, path: _params.path }; - ctx.seen.set(schema, result); - ctx.sharedDefsExtractedFor = undefined; - ctx.sharedEmitDoneFor = undefined; - // custom method overrides default behavior - const overrideSchema = schema._zod.toJSONSchema?.(); - if (overrideSchema) { - result.schema = overrideSchema; - } - else { - const params = { - ..._params, - schemaPath: [..._params.schemaPath, schema], - path: _params.path, - }; - if (schema._zod.processJSONSchema) { - schema._zod.processJSONSchema(ctx, result.schema, params); - } - else { - const _json = result.schema; - const processor = ctx.processors[def.type]; - if (!processor) { - throw new Error(`[toJSONSchema]: Non-representable type encountered: ${def.type}`); - } - processor(schema, ctx, _json, params); - } - const parent = schema._zod.parent; - if (parent) { - // Also set ref if processor didn't (for inheritance) - if (!result.ref) - result.ref = parent; - to_json_schema_process(parent, ctx, params); - ctx.seen.get(parent).isParent = true; - } - } - // metadata - const meta = ctx.metadataRegistry.get(schema); - if (meta) - assignProps(result.schema, meta); - if (ctx.io === "input" && isTransforming(schema)) { - // examples/defaults only apply to output type of pipe - delete result.schema.examples; - delete result.schema.default; - } - // set prefault as default - if (ctx.io === "input" && "_prefault" in result.schema) - (_a = result.schema).default ?? (_a.default = result.schema._prefault); - delete result.schema._prefault; - // pulling fresh from ctx.seen in case it was overwritten - const _result = ctx.seen.get(schema); - return _result.schema; -} -// Escape a reference token for use in a JSON Pointer fragment (RFC 6901): `~` becomes `~0` and `/` becomes `~1`. The `~` replacement must run first. -function encodeJSONPointerSegment(segment) { - return segment.replace(/~/g, "~0").replace(/\//g, "~1"); -} -function extractDefs(ctx, schema -// params: EmitParams -) { - // iterate over seen map; - const root = ctx.seen.get(schema); - if (!root) - throw new Error("Unprocessed schema. This is a bug in Zod."); - // With `external` set, every registered schema resolves through the external branch of `makeURI`, so the root branch below produces the same ref the external branch would — this pass is identical whichever schema it is called with, and only needs to run once. - if (ctx.external && ctx.sharedDefsExtractedFor === ctx.external) - return; - // Track ids to detect duplicates across different schemas - const idToSchema = new Map(); - for (const entry of ctx.seen.entries()) { - const id = ctx.metadataRegistry.get(entry[0])?.id; - if (id) { - const existing = idToSchema.get(id); - if (existing && existing !== entry[0]) { - throw new Error(`Duplicate schema id "${id}" detected during JSON Schema conversion. Two different schemas cannot share the same id when converted together.`); - } - idToSchema.set(id, entry[0]); - } - } - // returns a ref to the schema defId will be empty if the ref points to an external schema (or #) - const makeURI = (entry) => { - // comparing the seen objects because sometimes multiple schemas map to the same seen object. e.g. lazy - // external is configured - const defsSegment = ctx.target === "draft-2020-12" ? "$defs" : "definitions"; - if (ctx.external) { - const externalId = ctx.external.registry.get(entry[0])?.id; // ?? "__shared";// `__schema${ctx.counter++}`; - // check if schema is in the external registry - const uriGenerator = ctx.external.uri ?? ((id) => id); - if (externalId) { - return { ref: uriGenerator(externalId) }; - } - // otherwise, add to __shared - const id = entry[1].defId ?? entry[1].schema.id ?? `schema${ctx.counter++}`; - entry[1].defId = id; // set defId so it will be reused if needed - return { defId: id, ref: `${uriGenerator("__shared")}#/${defsSegment}/${encodeJSONPointerSegment(id)}` }; - } - const uriPrefix = `#`; - const defUriPrefix = `${uriPrefix}/${defsSegment}/`; - // an id-less root has nowhere to be extracted to, so it stays inline and self-references as `#` - if (entry[1] === root && !entry[1].schema.id) { - return { ref: uriPrefix }; - } - // self-contained schema - const defId = entry[1].schema.id ?? `__schema${ctx.counter++}`; - return { defId, ref: defUriPrefix + encodeJSONPointerSegment(defId) }; - }; - // stored cached version in `def` property remove all properties, set $ref - const extractToDef = (entry) => { - // if the schema is already a reference, do not extract it - if (entry[1].schema.$ref) { - return; - } - const seen = entry[1]; - const { ref, defId } = makeURI(entry); - seen.def = { ...seen.schema }; - // defId won't be set if the schema is a reference to an external schema or if the schema is the root schema - if (defId) - seen.defId = defId; - // wipe away all properties except $ref - const schema = seen.schema; - for (const key in schema) { - delete schema[key]; - } - schema.$ref = ref; - }; - // throw on cycles - // break cycles - if (ctx.cycles === "throw") { - for (const entry of ctx.seen.entries()) { - const seen = entry[1]; - if (seen.cycle) { - throw new Error("Cycle detected: " + - `#/${seen.cycle?.join("/")}/` + - '\n\nSet the `cycles` parameter to `"ref"` to resolve cyclical schemas with defs.'); - } - } - } - // extract schemas into $defs - for (const entry of ctx.seen.entries()) { - const seen = entry[1]; - // convert root schema to # $ref - if (schema === entry[0]) { - extractToDef(entry); // this has special handling for the root schema - continue; - } - // extract schemas that are in the external registry - if (ctx.external) { - const ext = ctx.external.registry.get(entry[0])?.id; - if (schema !== entry[0] && ext) { - extractToDef(entry); - continue; - } - } - // extract schemas with `id` meta - const id = ctx.metadataRegistry.get(entry[0])?.id; - if (id) { - extractToDef(entry); - continue; - } - // break cycles - if (seen.cycle) { - // any - extractToDef(entry); - continue; - } - // extract reused schemas - if (seen.count > 1) { - if (ctx.reused === "ref") { - extractToDef(entry); - // biome-ignore lint: - continue; - } - } - } - if (ctx.external) - ctx.sharedDefsExtractedFor = ctx.external; -} -/** Rewrites `anyOf: [{type: "a"}, {type: "b"}]` to `type: ["a", "b"]`, which every JSON Schema draft treats as equivalent and most consumers render far better for the nullable case. Only branches that are a bare type assertion qualify — anything carrying a constraint, `$ref`, `const` or metadata is left alone. Runs after `flattenRef`, so a branch an override decorated or `$defs` extraction turned into a `$ref` is no longer bare and correctly stays in `anyOf`. `oneOf` is excluded: `integer` and `number` overlap, so "exactly one" and "at least one" are not the same there. OpenAPI 3.0 is excluded: its `type` must be a single string. */ -function compactTypeUnion(schema) { - const options = schema.anyOf; - if (!Array.isArray(options) || options.length === 0 || schema.type !== undefined) - return; - const types = []; - for (const option of options) { - if (!option || typeof option !== "object") - return; - // A branch that is itself a compactible union folds into this one — nested `anyOf` and a flat `type` array say the same thing. Compacting it first also makes the result independent of the order this pass walks the seen map in. - compactTypeUnion(option); - const keys = Object.keys(option); - if (keys.length !== 1 || keys[0] !== "type") - return; - const type = option.type; - for (const member of Array.isArray(type) ? type : [type]) { - if (typeof member !== "string") - return; - if (!types.includes(member)) - types.push(member); - } - } - delete schema.anyOf; - // A `type` array must be non-empty and unique (metaschema); a single member is spelled as a bare string. - schema.type = types.length === 1 ? types[0] : types; -} -/** Keywords `foldIntersection` knows how to combine. Anything else — `$ref`, `patternProperties`, - * an annotation like `description` — makes a member unfoldable, so a constraint this does not - * understand leaves the `allOf` alone instead of being silently dropped or misattributed. */ -const FOLDABLE_KEYS = new Set(["type", "properties", "required", "additionalProperties"]); -const UNION_KEYS = ["oneOf", "anyOf"]; -/** A member's constraint on a key it does not declare itself. A `catchall` states one; `false`, an absent `additionalProperties`, and the empty schema a loose object emits state nothing. */ -function undeclaredConstraint(member) { - const extra = member.additionalProperties; - if (extra === undefined || extra === false || typeof extra !== "object" || extra === null) - return null; - return Object.keys(extra).length ? extra : null; -} -/** Combines object members into the single object they describe together, or returns `null` if any of them carries a keyword outside {@link FOLDABLE_KEYS}. */ -function foldObjects(members) { - const objects = []; - for (const member of members) { - // A boolean subschema is legal JSON Schema and carries no keywords to fold. - if (typeof member !== "object" || member.type !== "object") - return null; - for (const key in member) { - if (!FOLDABLE_KEYS.has(key)) - return null; - } - objects.push(member); - } - const properties = {}; - const required = new Set(); - for (const object of objects) { - for (const key in object.properties) { - // `in` would report a `__proto__` key as already present via the prototype chain and skip it. - if (Object.prototype.hasOwnProperty.call(properties, key)) - continue; - // Every member constrains this key: the ones that declare it say how, and a `catchall` member constrains it too even though it does not name it. The key has to satisfy all of them, which is the same intersection one level down. - const parts = []; - for (const other of objects) { - const part = other.properties?.[key] ?? undeclaredConstraint(other); - if (part === null || part === undefined) - continue; - if (!parts.some((seen) => JSON.stringify(seen) === JSON.stringify(part))) - parts.push(part); - } - const merged = parts.length === 1 - ? parts[0] - : (foldObjects(parts) ?? { allOf: parts }); - assignProp(properties, key, merged); - } - for (const key of object.required ?? []) - required.add(key); - } - const folded = { type: "object", properties }; - if (required.size) - folded.required = [...required]; - // A key no member declares is rejected only when every member rejects it, so the fold is closed only when every member is. Otherwise it carries whatever the `catchall` members demand of such a key. - if (objects.every((object) => object.additionalProperties === false)) { - folded.additionalProperties = false; - } - else { - const constraints = []; - for (const object of objects) { - const constraint = undeclaredConstraint(object); - if (constraint && !constraints.some((seen) => JSON.stringify(seen) === JSON.stringify(constraint))) - constraints.push(constraint); - } - if (constraints.length === 1) - folded.additionalProperties = constraints[0]; - else if (constraints.length > 1) - folded.additionalProperties = { allOf: constraints }; - } - return folded; -} -/** `additionalProperties` in an `allOf` member sees only that member's own `properties`, so two - * closed object members reject each other's keys and the schema validates nothing. Zod's parser - * pools the key sets instead — `handleIntersectionResults` reports a key as unrecognized only when - * *every* side rejects it — so the emitted schema has to pool them too, and folding the members - * into one object is the encoding that says so on every target. - * - * This runs from `finalize`, after `extractDefs`, which is what keeps it clear of the `$ref` - * machinery: a member extracted into `$defs` is already a `$ref` by now and declines to fold, so it - * keeps its reference and its own closedness rather than being inlined as a stale copy. */ -function foldIntersection(json) { - const allOf = json.allOf; - if (!Array.isArray(allOf) || allOf.length < 2) - return; - // An `override` runs before this pass and may have written object keywords onto the intersection itself. Those are deliberate, so decline rather than overwrite them. - for (const key of FOLDABLE_KEYS) - if (key in json) - return; - // An intersection distributes over a union: `A & (X | Y)` is `(A & X) | (A & Y)`. Only the first union is distributed over; a second one stays among the members every branch folds against, where it fails the object check and declines the whole intersection rather than multiplying out. - const unions = allOf.filter((m) => UNION_KEYS.some((k) => Array.isArray(m[k]))); - let folded = null; - if (!unions.length) { - folded = foldObjects(allOf); - } - else { - const union = unions[0]; - const keyword = UNION_KEYS.find((k) => Array.isArray(union[k])); - if (Object.keys(union).length !== 1) - return; - const rest = allOf.filter((m) => m !== union); - const branches = union[keyword].map((branch) => foldObjects([...rest, branch])); - if (branches.some((b) => !b)) - return; - folded = { [keyword]: branches }; - } - if (!folded) - return; - delete json.allOf; - assignProps(json, folded); -} -function finalize(ctx, schema) { - const root = ctx.seen.get(schema); - if (!root) - throw new Error("Unprocessed schema. This is a bug in Zod."); - // flatten refs - inherit properties from parent schemas - const flattenRef = (zodSchema) => { - const seen = ctx.seen.get(zodSchema); - // already processed - if (seen.ref === null) - return; - const schema = seen.def ?? seen.schema; - const _cached = { ...schema }; - const ref = seen.ref; - seen.ref = null; // prevent infinite recursion - if (ref) { - flattenRef(ref); - const refSeen = ctx.seen.get(ref); - const refSchema = refSeen.schema; - // merge referenced schema into current - if (refSchema.$ref && (ctx.target === "draft-07" || ctx.target === "draft-04" || ctx.target === "openapi-3.0")) { - // older drafts can't combine $ref with other properties - schema.allOf = schema.allOf ?? []; - schema.allOf.push(refSchema); - } - else { - assignProps(schema, refSchema); - } - // restore child's own properties (child wins) - assignProps(schema, _cached); - const isParentRef = zodSchema._zod.parent === ref; - // For parent chain, child is a refinement - remove parent-only properties - if (isParentRef) { - for (const key in schema) { - if (key === "$ref" || key === "allOf") - continue; - if (!(key in _cached)) { - delete schema[key]; - } - } - } - // When ref was extracted to $defs, remove properties that match the definition - if (refSchema.$ref && refSeen.def) { - for (const key in schema) { - if (key === "$ref" || key === "allOf") - continue; - if (key in refSeen.def && JSON.stringify(schema[key]) === JSON.stringify(refSeen.def[key])) { - delete schema[key]; - } - } - } - } - // If parent was extracted (has $ref), propagate $ref to this schema. This handles cases like: readonly().meta({id}).describe() where processor sets ref to innerType but parent should be referenced - const parent = zodSchema._zod.parent; - if (parent && parent !== ref) { - // Ensure parent is processed first so its def has inherited properties - flattenRef(parent); - const parentSeen = ctx.seen.get(parent); - if (parentSeen?.schema.$ref) { - schema.$ref = parentSeen.schema.$ref; - // De-duplicate with parent's definition - if (parentSeen.def) { - for (const key in schema) { - if (key === "$ref" || key === "allOf") - continue; - if (key in parentSeen.def && JSON.stringify(schema[key]) === JSON.stringify(parentSeen.def[key])) { - delete schema[key]; - } - } - } - } - } - // execute overrides - ctx.override({ - zodSchema: zodSchema, - jsonSchema: schema, - path: seen.path ?? [], - }); - }; - // Flattening walks the whole map and clears each `ref` as it goes, so a second call over the same map is a no-op scan. Skip it outright once it has run for a registry conversion. - if (!ctx.external || ctx.sharedEmitDoneFor !== ctx.external) { - for (const entry of [...ctx.seen.entries()].reverse()) { - flattenRef(entry[0]); - } - if (ctx.target !== "openapi-3.0") { - for (const entry of ctx.seen.entries()) { - compactTypeUnion(entry[1].def ?? entry[1].schema); - } - } - for (const rewrite of ctx.deferred) - rewrite(); - // After flattening, every member that was extracted is a `$ref`, so the fold sees the final shape. A schema that inherits an intersection — through `z.lazy`, or any `ref` chain — holds the same `allOf` array, so fold by array identity to catch every copy. - if (ctx.intersections.length) { - const carriers = new Map(); - for (const seen of ctx.seen.values()) { - for (const json of [seen.schema, seen.def]) { - const allOf = json?.allOf; - if (!Array.isArray(allOf)) - continue; - const existing = carriers.get(allOf); - if (existing) - existing.push(json); - else - carriers.set(allOf, [json]); - } - } - for (const allOf of ctx.intersections) { - for (const json of carriers.get(allOf) ?? []) - foldIntersection(json); - } - } - } - const result = {}; - if (ctx.target === "draft-2020-12") { - result.$schema = "https://json-schema.org/draft/2020-12/schema"; - } - else if (ctx.target === "draft-07") { - result.$schema = "http://json-schema.org/draft-07/schema#"; - } - else if (ctx.target === "draft-04") { - result.$schema = "http://json-schema.org/draft-04/schema#"; - } - else if (ctx.target === "openapi-3.0") { - // OpenAPI 3.0 schema objects should not include a $schema property - } - else { - // Arbitrary string values are allowed but won't have a $schema property set - } - if (ctx.external?.uri) { - const id = ctx.external.registry.get(schema)?.id; - if (!id) - throw new Error("Schema is missing an `id` property"); - result.$id = ctx.external.uri(id); - } - // when the root was extracted into $defs, `root.schema` is the `$ref` wrapper and `root.def` is the body that now lives under $defs - assignProps(result, root.defId ? root.schema : (root.def ?? root.schema)); - // The `id` in `.meta()` is a Zod-specific registration tag used to extract schemas into $defs — it is not user-facing JSON Schema metadata. Strip it from the output body where it would otherwise leak. The id is preserved implicitly via the $defs key (and via $ref paths). - const rootMetaId = ctx.metadataRegistry.get(schema)?.id; - if (rootMetaId !== undefined && result.id === rootMetaId) - delete result.id; - // build defs object. With `external`, `defs` is the shared object every schema writes into, so the same entries are reassigned on every call. Without it, `defs` is fresh per call and must be rebuilt. - const defs = ctx.external?.defs ?? {}; - if (!ctx.external || ctx.sharedEmitDoneFor !== ctx.external) { - for (const entry of ctx.seen.entries()) { - const seen = entry[1]; - if (seen.def && seen.defId) { - if (seen.def.id === seen.defId) - delete seen.def.id; - assignProp(defs, seen.defId, seen.def); - } - } - } - if (ctx.external) - ctx.sharedEmitDoneFor = ctx.external; - // set definitions in result - if (ctx.external) { - } - else { - if (Object.keys(defs).length > 0) { - if (ctx.target === "draft-2020-12") { - result.$defs = defs; - } - else { - result.definitions = defs; - } - } - } - try { - // this "finalizes" this schema and ensures all cycles are removed each call to finalize() is functionally independent though the seen map is shared - const finalized = JSON.parse(JSON.stringify(result)); - Object.defineProperty(finalized, "~standard", { - value: { - ...schema["~standard"], - jsonSchema: { - input: createStandardJSONSchemaMethod(schema, "input", ctx.processors), - output: createStandardJSONSchemaMethod(schema, "output", ctx.processors), - }, - }, - enumerable: false, - writable: false, - }); - return finalized; - } - catch (_err) { - throw new Error("Error converting schema to JSON."); - } -} -function isTransforming(_schema, _ctx) { - const ctx = _ctx ?? { seen: new Set() }; - if (ctx.seen.has(_schema)) - return false; - ctx.seen.add(_schema); - const def = _schema._zod.def; - if (def.type === "transform") - return true; - if (def.type === "array") - return isTransforming(def.element, ctx); - if (def.type === "set") - return isTransforming(def.valueType, ctx); - if (def.type === "lazy") - return isTransforming(def.getter(), ctx); - if (def.type === "promise" || - def.type === "optional" || - def.type === "nonoptional" || - def.type === "nullable" || - def.type === "readonly" || - def.type === "default" || - def.type === "prefault" || - def.type === "catch") { - return isTransforming(def.innerType, ctx); - } - if (def.type === "intersection") { - return isTransforming(def.left, ctx) || isTransforming(def.right, ctx); - } - if (def.type === "record" || def.type === "map") { - return isTransforming(def.keyType, ctx) || isTransforming(def.valueType, ctx); - } - if (def.type === "pipe") { - if (_schema._zod.traits.has("$ZodCodec")) - return true; - return isTransforming(def.in, ctx) || isTransforming(def.out, ctx); - } - if (def.type === "object") { - for (const key in def.shape) { - if (isTransforming(def.shape[key], ctx)) - return true; - } - return false; - } - if (def.type === "union") { - for (const option of def.options) { - if (isTransforming(option, ctx)) - return true; - } - return false; - } - if (def.type === "tuple") { - for (const item of def.items) { - if (isTransforming(item, ctx)) - return true; - } - if (def.rest && isTransforming(def.rest, ctx)) - return true; - return false; - } - return false; -} -/** - * Creates a toJSONSchema method for a schema instance. - * This encapsulates the logic of initializing context, processing, extracting defs, and finalizing. - */ -const createToJSONSchemaMethod = (schema, processors = {}) => (params) => { - const ctx = initializeContext({ ...params, processors }); - to_json_schema_process(schema, ctx); - extractDefs(ctx, schema); - return finalize(ctx, schema); -}; -const createStandardJSONSchemaMethod = (schema, io, processors = {}) => (params) => { - const { libraryOptions, target } = params ?? {}; - const ctx = initializeContext({ ...(libraryOptions ?? {}), target, io, processors }); - to_json_schema_process(schema, ctx); - extractDefs(ctx, schema); - return finalize(ctx, schema); -}; - - - - -const formatMap = { - guid: "uuid", - url: "uri", - datetime: "date-time", - json_string: "json-string", - regex: "", // do not set -}; -// ==================== SIMPLE TYPE PROCESSORS ==================== -const stringProcessor = (schema, ctx, _json, _params) => { - const json = _json; - json.type = "string"; - const { minimum, maximum, format, patterns, contentEncoding, laxFormat } = schema._zod - .bag; - if (typeof minimum === "number") - json.minLength = minimum; - if (typeof maximum === "number") - json.maxLength = maximum; - // custom pattern overrides format - if (format) { - json.format = formatMap[format] ?? format; - if (json.format === "") - delete json.format; // empty format is not valid - // `z.iso.time()` is never full-time, and `laxFormat` carries the datetime shapes that also accept what their keyword forbids - if (format === "time" || laxFormat) { - delete json.format; - } - } - if (contentEncoding) - json.contentEncoding = contentEncoding; - if (patterns && patterns.size > 0) { - const patternList = [...patterns]; - if (patternList.length === 1) - json.pattern = patternList[0].source; - else if (patternList.length > 1) { - json.allOf = [ - ...patternList.map((regex) => ({ - ...(ctx.target === "draft-07" || ctx.target === "draft-04" || ctx.target === "openapi-3.0" - ? { type: "string" } - : {}), - pattern: regex.source, - })), - ]; - } - } -}; -const numberProcessor = (schema, ctx, _json, params) => { - const json = _json; - const { minimum, maximum, format, multipleOf, exclusiveMaximum, exclusiveMinimum } = schema._zod.bag; - if (typeof format === "string" && format.includes("int")) - json.type = "integer"; - else - json.type = "number"; - // when both minimum and exclusiveMinimum exist, pick the more restrictive one - const exMin = typeof exclusiveMinimum === "number" && exclusiveMinimum >= (minimum ?? Number.NEGATIVE_INFINITY); - const exMax = typeof exclusiveMaximum === "number" && exclusiveMaximum <= (maximum ?? Number.POSITIVE_INFINITY); - const legacy = ctx.target === "draft-04" || ctx.target === "openapi-3.0"; - if (exMin) { - if (legacy) { - json.minimum = exclusiveMinimum; - json.exclusiveMinimum = true; - } - else { - json.exclusiveMinimum = exclusiveMinimum; - } - } - else if (typeof minimum === "number") { - json.minimum = minimum; - } - if (exMax) { - if (legacy) { - json.maximum = exclusiveMaximum; - json.exclusiveMaximum = true; - } - else { - json.exclusiveMaximum = exclusiveMaximum; - } - } - else if (typeof maximum === "number") { - json.maximum = maximum; - } - if (typeof multipleOf === "number") { - // JSON Schema requires a divisor strictly greater than zero, and a non-finite one does not survive JSON at all. A negative divisor accepts exactly what its absolute value accepts, so it still maps; zero, NaN and Infinity have no keyword form. - if (Number.isFinite(multipleOf) && multipleOf !== 0) - json.multipleOf = Math.abs(multipleOf); - else - handleUnrepresentable(schema, ctx, json, params, `A multipleOf divisor of ${multipleOf} cannot be represented in JSON Schema`); - } -}; -const booleanProcessor = (_schema, _ctx, json, _params) => { - json.type = "boolean"; -}; -const bigintProcessor = (schema, ctx, json, params) => { - handleUnrepresentable(schema, ctx, json, params, "BigInt cannot be represented in JSON Schema"); -}; -const symbolProcessor = (schema, ctx, json, params) => { - handleUnrepresentable(schema, ctx, json, params, "Symbols cannot be represented in JSON Schema"); -}; -const nullProcessor = (_schema, ctx, json, _params) => { - if (ctx.target === "openapi-3.0") { - json.type = "string"; - json.nullable = true; - json.enum = [null]; - } - else { - json.type = "null"; - } -}; -const undefinedProcessor = (schema, ctx, json, params) => { - handleUnrepresentable(schema, ctx, json, params, "Undefined cannot be represented in JSON Schema"); -}; -const voidProcessor = (schema, ctx, json, params) => { - handleUnrepresentable(schema, ctx, json, params, "Void cannot be represented in JSON Schema"); -}; -const neverProcessor = (_schema, _ctx, json, _params) => { - json.not = {}; -}; -const anyProcessor = (_schema, _ctx, _json, _params) => { - // empty schema accepts anything -}; -const unknownProcessor = (_schema, _ctx, _json, _params) => { - // empty schema accepts anything -}; -const dateProcessor = (schema, ctx, json, params) => { - handleUnrepresentable(schema, ctx, json, params, "Date cannot be represented in JSON Schema"); -}; -const enumProcessor = (schema, _ctx, json, _params) => { - const def = schema._zod.def; - const values = getEnumValues(def.entries); - // an empty enum accepts nothing, same as z.never() - if (values.length === 0) { - json.not = {}; - return; - } - // Number enums can have both string and number values - if (values.every((v) => typeof v === "number")) - json.type = "number"; - if (values.every((v) => typeof v === "string")) - json.type = "string"; - json.enum = values; -}; -const literalProcessor = (schema, ctx, json, params) => { - const def = schema._zod.def; - // a literal with no values accepts nothing, same as z.never() - if (def.values.length === 0) { - json.not = {}; - return; - } - const vals = []; - for (const val of def.values) { - if (val === undefined) { - // a custom schema replaces the whole literal, so there is nothing left to accumulate - if (handleUnrepresentable(schema, ctx, json, params, "Literal `undefined` cannot be represented in JSON Schema")) - return; - // otherwise do not add to vals - } - else if (typeof val === "bigint") { - if (handleUnrepresentable(schema, ctx, json, params, "BigInt literals cannot be represented in JSON Schema")) - return; - vals.push(Number(val)); - } - else { - vals.push(val); - } - } - if (vals.length === 0) { - // do nothing (an undefined literal was stripped) - } - else if (vals.length === 1) { - const val = vals[0]; - json.type = val === null ? "null" : typeof val; - if (ctx.target === "draft-04" || ctx.target === "openapi-3.0") { - json.enum = [val]; - } - else { - json.const = val; - } - } - else { - if (vals.every((v) => typeof v === "number")) - json.type = "number"; - if (vals.every((v) => typeof v === "string")) - json.type = "string"; - if (vals.every((v) => typeof v === "boolean")) - json.type = "boolean"; - if (vals.every((v) => v === null)) - json.type = "null"; - json.enum = vals; - } -}; -const nanProcessor = (schema, ctx, json, params) => { - handleUnrepresentable(schema, ctx, json, params, "NaN cannot be represented in JSON Schema"); -}; -const templateLiteralProcessor = (schema, _ctx, json, _params) => { - const _json = json; - const pattern = schema._zod.pattern; - if (!pattern) - throw new Error("Pattern not found in template literal"); - _json.type = "string"; - _json.pattern = pattern.source; -}; -const fileProcessor = (schema, _ctx, json, _params) => { - const _json = json; - const file = { - type: "string", - format: "binary", - contentEncoding: "binary", - }; - const { minimum, maximum, mime } = schema._zod.bag; - if (minimum !== undefined) - file.minLength = minimum; - if (maximum !== undefined) - file.maxLength = maximum; - if (mime) { - if (mime.length === 1) { - file.contentMediaType = mime[0]; - Object.assign(_json, file); - } - else { - Object.assign(_json, file); // shared props at root - _json.anyOf = mime.map((m) => ({ contentMediaType: m })); // only contentMediaType differs - } - } - else { - Object.assign(_json, file); - } -}; -const successProcessor = (_schema, _ctx, json, _params) => { - json.type = "boolean"; -}; -const customProcessor = (schema, ctx, json, params) => { - handleUnrepresentable(schema, ctx, json, params, "Custom types cannot be represented in JSON Schema"); -}; -const functionProcessor = (schema, ctx, json, params) => { - handleUnrepresentable(schema, ctx, json, params, "Function types cannot be represented in JSON Schema"); -}; -const transformProcessor = (schema, ctx, json, params) => { - handleUnrepresentable(schema, ctx, json, params, "Transforms cannot be represented in JSON Schema"); -}; -const mapProcessor = (schema, ctx, json, params) => { - handleUnrepresentable(schema, ctx, json, params, "Map cannot be represented in JSON Schema"); -}; -const setProcessor = (schema, ctx, json, params) => { - handleUnrepresentable(schema, ctx, json, params, "Set cannot be represented in JSON Schema"); -}; -// ==================== COMPOSITE TYPE PROCESSORS ==================== -const arrayProcessor = (schema, ctx, _json, params) => { - const json = _json; - const def = schema._zod.def; - const { minimum, maximum } = schema._zod.bag; - if (typeof minimum === "number") - json.minItems = minimum; - if (typeof maximum === "number") - json.maxItems = maximum; - json.type = "array"; - json.items = to_json_schema_process(def.element, ctx, { - ...params, - path: [...params.path, "items"], - }); -}; -// Transform and catch set `optin = "optional"` at runtime so the parser lets them observe an -// absent key, but their declared input type stays required. An input JSON Schema describes the -// declared type, so resolve past them to the schema that actually carries the optionality. -// Used by both `objectProcessor` (for `required`) and `tupleProcessor` (for `minItems`); see -// wiki/optionality.md, "The JSON Schema emitter reads the *static* value". -function inputOptin(schema) { - const def = schema._zod.def; - if (def.type === "pipe" && def.in._zod.traits.has("$ZodTransform")) { - return inputOptin(def.out); - } - if (def.type === "catch") { - return inputOptin(def.innerType); - } - return schema._zod.optin; -} -const objectProcessor = (schema, ctx, _json, params) => { - const json = _json; - const def = schema._zod.def; - const shape = def.shape; - // dropping it while still emitting `additionalProperties: false` would emit a schema that rejects data this one requires - const symbolKeys = Object.getOwnPropertySymbols(shape); - if (symbolKeys.length && - handleUnrepresentable(schema, ctx, json, params, "Symbol keys cannot be represented in JSON Schema")) { - return; - } - json.type = "object"; - json.properties = {}; - for (const key in shape) { - // assignProp so a __proto__ key becomes an own property instead of hitting the inherited setter on the plain {} we build into - assignProp(json.properties, key, to_json_schema_process(shape[key], ctx, { - ...params, - path: [...params.path, "properties", key], - })); - } - // required keys - const allKeys = new Set(Object.keys(shape)); - const requiredKeys = new Set([...allKeys].filter((key) => { - const field = def.shape[key]; - if (ctx.io === "input") { - return inputOptin(field) === undefined; - } - else { - return field._zod.optout === undefined; - } - })); - if (requiredKeys.size > 0) { - json.required = Array.from(requiredKeys); - } - // catchall - if (def.catchall?._zod.def.type === "never") { - // strict - json.additionalProperties = false; - } - else if (!def.catchall) { - // regular - if (ctx.io === "output") - json.additionalProperties = false; - } - else if (def.catchall) { - json.additionalProperties = to_json_schema_process(def.catchall, ctx, { - ...params, - path: [...params.path, "additionalProperties"], - }); - } -}; -const unionProcessor = (schema, ctx, json, params) => { - const def = schema._zod.def; - // Exclusive unions (inclusive === false) use oneOf (exactly one match) instead of anyOf (one or more matches). This includes both z.xor() and discriminated unions - const isExclusive = def.inclusive === false; - const options = def.options.map((x, i) => to_json_schema_process(x, ctx, { - ...params, - path: [...params.path, isExclusive ? "oneOf" : "anyOf", i], - })); - if (isExclusive) { - json.oneOf = options; - } - else { - json.anyOf = options; - } -}; -const intersectionProcessor = (schema, ctx, json, params) => { - const def = schema._zod.def; - const a = to_json_schema_process(def.left, ctx, { - ...params, - path: [...params.path, "allOf", 0], - }); - const b = to_json_schema_process(def.right, ctx, { - ...params, - path: [...params.path, "allOf", 1], - }); - const isSimpleIntersection = (val) => "allOf" in val && Object.keys(val).length === 1; - const allOf = [ - ...(isSimpleIntersection(a) ? a.allOf : [a]), - ...(isSimpleIntersection(b) ? b.allOf : [b]), - ]; - json.allOf = allOf; - // Recorded innermost first, so a nested intersection has already folded by the time this one is considered. The array is the handle rather than the schema, because a wrapper that inherits this schema shares the same array; `finalize` folds every object holding it. See `foldIntersection`. - ctx.intersections.push(allOf); -}; -const tupleProcessor = (schema, ctx, _json, params) => { - const json = _json; - const def = schema._zod.def; - json.type = "array"; - const prefixPath = ctx.target === "draft-2020-12" ? "prefixItems" : "items"; - const restPath = ctx.target === "draft-2020-12" ? "items" : ctx.target === "openapi-3.0" ? "items" : "additionalItems"; - const prefixItems = def.items.map((x, i) => to_json_schema_process(x, ctx, { - ...params, - path: [...params.path, prefixPath, i], - })); - const rest = def.rest - ? to_json_schema_process(def.rest, ctx, { - ...params, - path: [...params.path, restPath, ...(ctx.target === "openapi-3.0" ? [def.items.length] : [])], - }) - : null; - let minItems = def.items.length; - while (minItems > 0) { - const item = def.items[minItems - 1]; - const optional = ctx.io === "input" ? inputOptin(item) !== undefined : item._zod.optout === "optional"; - if (!optional) - break; - minItems--; - } - const maxItems = def.items.length; - const isClosed = !def.rest; - if (ctx.target === "draft-2020-12") { - json.prefixItems = prefixItems; - if (isClosed) { - json.items = false; - } - else if (rest) { - json.items = rest; - } - if (minItems > 0) - json.minItems = minItems; - if (isClosed) - json.maxItems = maxItems; - } - else if (ctx.target === "openapi-3.0") { - json.items = { - anyOf: prefixItems, - }; - if (rest) { - json.items.anyOf.push(rest); - } - if (minItems > 0) - json.minItems = minItems; - if (isClosed) - json.maxItems = maxItems; - } - else { - json.items = prefixItems; - if (isClosed) { - json.additionalItems = false; - } - else if (rest) { - json.additionalItems = rest; - } - if (minItems > 0) - json.minItems = minItems; - if (isClosed) - json.maxItems = maxItems; - } - // explicit user-defined length checks take precedence - const { minimum, maximum } = schema._zod.bag; - if (typeof minimum === "number") - json.minItems = minimum; - if (typeof maximum === "number") - json.maxItems = maximum; -}; -/** JSON object keys are always strings, so a numeric record key schema is re-expressed over the - * numeric-string form the record parser matches. Deferred to `finalize`, after the flatten: a key - * behind a wrapper only carries its own `type` before then, and a union key only has its branches. - * - * A numeric bound cannot apply to a property name, so `minimum` and its siblings are dropped rather - * than carried over: keeping them beside `type: "string"` reproduces the match-nothing schema this - * exists to fix. A key that carries one therefore emits wider than the record parses — `z.record(z.number().min(5), V)` - * accepts `"3"` — which is the deliberate trade, since throwing on it would reject an ordinary schema - * outright. */ -function stringifyKeyNames(bySchema, json, visited) { - // an extracted key that rewrites cannot go on sharing its definition — the string form a key position needs is not the number form every other reference wants — so it inlines. One that does not rewrite keeps the `$ref`. - if (json.$ref) { - // a recursive key holds its own reference inside its definition, so a node already on the path is left alone rather than resolved again - if (visited.has(json)) - return json; - visited.add(json); - const def = bySchema.get(json)?.def; - if (!def) - return json; - const inlined = stringifyKeyNames(bySchema, def, visited); - return inlined === def ? json : inlined; - } - for (const keyword of ["anyOf", "oneOf"]) { - const branches = json[keyword]; - if (!Array.isArray(branches)) - continue; - const mapped = branches.map((branch) => stringifyKeyNames(bySchema, branch, visited)); - // rebuilding regardless would detach a key that had nothing to re-express, dropping its `$ref` and leaking the internal `id` - if (mapped.some((branch, i) => branch !== branches[i])) - json = { ...json, [keyword]: mapped }; - } - // a member that already admits a string leaves the key unconstrained, so the node's own type re-expresses only when every member is numeric - const types = Array.isArray(json.type) ? json.type : [json.type]; - const numericType = !types.includes("string") && types.some((t) => t === "number" || t === "integer"); - // a heterogeneous key carries no type at all, so its numeric members are caught here instead - const values = json.enum ?? (json.const !== undefined ? [json.const] : undefined); - if (!numericType && !values?.some((v) => typeof v === "number")) - return json; - const { minimum, maximum, exclusiveMinimum, exclusiveMaximum, multipleOf, format, id, ...rest } = json; - if (rest.enum) - rest.enum = rest.enum.map((v) => (typeof v === "number" ? String(v) : v)); - else if (typeof rest.const === "number") - rest.const = String(rest.const); - // a heterogeneous key keeps its absent type: the stringified members already say what a key may be - if (!numericType) - return rest; - rest.type = "string"; - if (!values) - rest.pattern = (types.includes("number") ? number : integer).source; - return rest; -} -/** Every record of one conversion, so the carriers are found in a single pass rather than once per record. */ -const pendingRecords = new WeakMap(); -function rewriteKeyNames(ctx) { - // an extracted key is resolved by the object `extractToDef` left in its place, so the map is built once rather than searched per reference. `_zod.toJSONSchema` can hand the same object to two schemas, so the first entry carrying a body wins, as a search would have found it. - const bySchema = new Map(); - for (const entry of ctx.seen.values()) { - if (entry.def && !bySchema.has(entry.schema)) - bySchema.set(entry.schema, entry); - } - const rewrites = new Map(); - for (const record of pendingRecords.get(ctx) ?? []) { - const seen = ctx.seen.get(record); - const names = (seen?.def ?? seen?.schema)?.propertyNames; - if (!names || names === true || rewrites.has(names)) - continue; - const rewritten = stringifyKeyNames(bySchema, names, new Set()); - if (rewritten !== names) - rewrites.set(names, rewritten); - } - if (!rewrites.size) - return; - // the flatten has already copied each record's own properties onto every wrapper by reference, and an extracted body is another such copy, so every carrier holding a rewritten key is updated together - for (const entry of ctx.seen.values()) { - for (const carrier of [entry.schema, entry.def]) { - const rewritten = carrier && rewrites.get(carrier.propertyNames); - if (rewritten) - carrier.propertyNames = rewritten; - } - } -} -const recordProcessor = (schema, ctx, _json, params) => { - const json = _json; - const def = schema._zod.def; - json.type = "object"; - // For looseRecord with regex patterns, use patternProperties. This correctly represents "only validate keys matching the pattern" semantics and composes well with allOf (intersections) - const keyType = def.keyType; - const keyBag = keyType._zod.bag; - const patterns = keyBag?.patterns; - if (def.mode === "loose" && patterns && patterns.size > 0) { - // Use patternProperties for looseRecord with regex patterns - const valueSchema = to_json_schema_process(def.valueType, ctx, { - ...params, - path: [...params.path, "patternProperties", "*"], - }); - json.patternProperties = {}; - for (const pattern of patterns) { - assignProp(json.patternProperties, pattern.source, valueSchema); - } - } - else { - // Default behavior: use propertyNames + additionalProperties - if (ctx.target === "draft-07" || ctx.target === "draft-2020-12") { - json.propertyNames = to_json_schema_process(def.keyType, ctx, { - ...params, - path: [...params.path, "propertyNames"], - }); - let pending = pendingRecords.get(ctx); - if (!pending) { - pending = []; - pendingRecords.set(ctx, pending); - ctx.deferred.push(() => rewriteKeyNames(ctx)); - } - pending.push(schema); - } - json.additionalProperties = to_json_schema_process(def.valueType, ctx, { - ...params, - path: [...params.path, "additionalProperties"], - }); - } - // Add required for keys with discrete values (enum, literal, etc.) - const keyValues = keyType._zod.values; - // Every key shares one value schema, so an optional-in value makes the whole key set omittable on input. Output keeps them: the exhaustive branch assigns every key, even one whose value came back undefined. - const omittableOnInput = ctx.io === "input" && inputOptin(def.valueType) !== undefined; - if (keyValues && !def.partial && !omittableOnInput) { - const validKeyValues = [...keyValues].filter((v) => typeof v === "string" || typeof v === "number"); - if (validKeyValues.length > 0) { - json.required = validKeyValues.map(String); - } - } -}; -const nullableProcessor = (schema, ctx, json, params) => { - const def = schema._zod.def; - const inner = to_json_schema_process(def.innerType, ctx, params); - const seen = ctx.seen.get(schema); - if (ctx.target === "openapi-3.0") { - seen.ref = def.innerType; - json.nullable = true; - } - else { - json.anyOf = [inner, { type: "null" }]; - } -}; -const nonoptionalProcessor = (schema, ctx, _json, params) => { - const def = schema._zod.def; - to_json_schema_process(def.innerType, ctx, params); - const seen = ctx.seen.get(schema); - seen.ref = def.innerType; -}; -/** Round-trips a default value through JSON so the emitted schema is guaranteed to be valid JSON. - * A BigInt has no reliable encoding, so it goes through `unrepresentable` like any other - * unrepresentable value. Returns a sentinel when the caller must not write a default of its own. */ -const UNREPRESENTABLE_DEFAULT = Symbol(); -function serializeDefaultValue(value, schema, ctx, json, params) { - let unrepresentable = false; - const serialized = JSON.stringify(value, (_, val) => { - if (typeof val !== "bigint") - return val; - unrepresentable = true; - return null; - }); - if (!unrepresentable) - return JSON.parse(serialized); - handleUnrepresentable(schema, ctx, json, params, "BigInt defaults cannot be represented in JSON Schema"); - return UNREPRESENTABLE_DEFAULT; -} -const defaultProcessor = (schema, ctx, json, params) => { - const def = schema._zod.def; - to_json_schema_process(def.innerType, ctx, params); - const seen = ctx.seen.get(schema); - seen.ref = def.innerType; - const value = serializeDefaultValue(def.defaultValue, schema, ctx, json, params); - if (value !== UNREPRESENTABLE_DEFAULT) - json.default = value; -}; -const prefaultProcessor = (schema, ctx, json, params) => { - const def = schema._zod.def; - to_json_schema_process(def.innerType, ctx, params); - const seen = ctx.seen.get(schema); - seen.ref = def.innerType; - if (ctx.io !== "input") - return; - const value = serializeDefaultValue(def.defaultValue, schema, ctx, json, params); - if (value !== UNREPRESENTABLE_DEFAULT) - json._prefault = value; -}; -const catchProcessor = (schema, ctx, json, params) => { - const def = schema._zod.def; - to_json_schema_process(def.innerType, ctx, params); - const seen = ctx.seen.get(schema); - seen.ref = def.innerType; - let catchValue; - try { - catchValue = def.catchValue(undefined); - } - catch { - handleUnrepresentable(schema, ctx, json, params, "Dynamic catch values are not supported in JSON Schema"); - return; - } - json.default = catchValue; -}; -const pipeProcessor = (schema, ctx, _json, params) => { - const def = schema._zod.def; - const inIsTransform = def.in._zod.traits.has("$ZodTransform"); - const innerType = ctx.io === "input" ? (inIsTransform ? def.out : def.in) : def.out; - to_json_schema_process(innerType, ctx, params); - const seen = ctx.seen.get(schema); - seen.ref = innerType; -}; -const readonlyProcessor = (schema, ctx, json, params) => { - const def = schema._zod.def; - to_json_schema_process(def.innerType, ctx, params); - const seen = ctx.seen.get(schema); - seen.ref = def.innerType; - json.readOnly = true; -}; -const promiseProcessor = (schema, ctx, _json, params) => { - const def = schema._zod.def; - to_json_schema_process(def.innerType, ctx, params); - const seen = ctx.seen.get(schema); - seen.ref = def.innerType; -}; -const optionalProcessor = (schema, ctx, _json, params) => { - const def = schema._zod.def; - to_json_schema_process(def.innerType, ctx, params); - const seen = ctx.seen.get(schema); - seen.ref = def.innerType; -}; -const lazyProcessor = (schema, ctx, _json, params) => { - const innerType = schema._zod.innerType; - to_json_schema_process(innerType, ctx, params); - const seen = ctx.seen.get(schema); - seen.ref = innerType; -}; -// ==================== ALL PROCESSORS ==================== -const allProcessors = { - string: stringProcessor, - number: numberProcessor, - boolean: booleanProcessor, - bigint: bigintProcessor, - symbol: symbolProcessor, - null: nullProcessor, - undefined: undefinedProcessor, - void: voidProcessor, - never: neverProcessor, - any: anyProcessor, - unknown: unknownProcessor, - date: dateProcessor, - enum: enumProcessor, - literal: literalProcessor, - nan: nanProcessor, - template_literal: templateLiteralProcessor, - file: fileProcessor, - success: successProcessor, - custom: customProcessor, - function: functionProcessor, - transform: transformProcessor, - map: mapProcessor, - set: setProcessor, - array: arrayProcessor, - object: objectProcessor, - union: unionProcessor, - intersection: intersectionProcessor, - tuple: tupleProcessor, - record: recordProcessor, - nullable: nullableProcessor, - nonoptional: nonoptionalProcessor, - default: defaultProcessor, - prefault: prefaultProcessor, - catch: catchProcessor, - pipe: pipeProcessor, - readonly: readonlyProcessor, - promise: promiseProcessor, - optional: optionalProcessor, - lazy: lazyProcessor, -}; -function toJSONSchema(input, params) { - if ("_idmap" in input) { - // Registry case - const registry = input; - const ctx = initializeContext({ ...params, processors: allProcessors }); - const defs = {}; - // First pass: process all schemas to build the seen map - for (const entry of registry._idmap.entries()) { - const [_, schema] = entry; - to_json_schema_process(schema, ctx); - } - const schemas = {}; - const external = { - registry, - uri: params?.uri, - defs, - }; - // Update the context with external configuration - ctx.external = external; - // Second pass: emit each schema - for (const entry of registry._idmap.entries()) { - const [key, schema] = entry; - extractDefs(ctx, schema); - assignProp(schemas, key, finalize(ctx, schema)); - } - if (Object.keys(defs).length > 0) { - const defsSegment = ctx.target === "draft-2020-12" ? "$defs" : "definitions"; - schemas.__shared = { - [defsSegment]: defs, - }; - } - return { schemas }; - } - // Single schema case - const ctx = initializeContext({ ...params, processors: allProcessors }); - to_json_schema_process(input, ctx); - extractDefs(ctx, input); - return finalize(ctx, input); -} - - -const en_error = () => { - const Sizable = { - string: { unit: "characters", verb: "to have" }, - file: { unit: "bytes", verb: "to have" }, - array: { unit: "items", verb: "to have" }, - set: { unit: "items", verb: "to have" }, - map: { unit: "entries", verb: "to have" }, - }; - function getSizing(origin) { - return Sizable[origin] ?? null; - } - const FormatDictionary = { - 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", - credit_card: "credit card number", - jwt: "JWT", - template_literal: "input", - }; - // type names: missing keys = do not translate (use raw value via ?? fallback) - const TypeDictionary = { - // Compatibility: "nan" -> "NaN" for display - nan: "NaN", - // All other type names omitted - they fall back to raw values via ?? operator - }; - function getTypeName(type, input) { - if (type === "number" && typeof input === "number" && !Number.isFinite(input)) { - return String(input); - } - return TypeDictionary[type] ?? type; - } - return (issue) => { - switch (issue.code) { - case "invalid_type": { - const expected = getTypeName(issue.expected); - const receivedType = parsedType(issue.input); - const received = getTypeName(receivedType, issue.input); - return `Invalid input: expected ${expected}, received ${received}`; - } - case "invalid_value": - if (issue.values.length === 1) - return `Invalid input: expected ${stringifyPrimitive(issue.values[0])}`; - return `Invalid option: expected one of ${joinValues(issue.values, "|")}`; - case "too_big": { - const adj = issue.exact ? "exactly " : issue.inclusive ? "<=" : "<"; - const sizing = getSizing(issue.origin); - if (sizing) - return `Too big: expected ${issue.origin ?? "value"} to have ${adj}${issue.maximum.toString()} ${sizing.unit ?? "elements"}`; - return `Too big: expected ${issue.origin ?? "value"} to be ${adj}${issue.maximum.toString()}`; - } - case "too_small": { - const adj = issue.exact ? "exactly " : issue.inclusive ? ">=" : ">"; - const sizing = getSizing(issue.origin); - if (sizing) { - return `Too small: expected ${issue.origin} to have ${adj}${issue.minimum.toString()} ${sizing.unit}`; - } - return `Too small: expected ${issue.origin} to be ${adj}${issue.minimum.toString()}`; - } - case "invalid_format": { - const _issue = issue; - if (_issue.format === "starts_with") { - return `Invalid string: must start with "${_issue.prefix}"`; - } - if (_issue.format === "ends_with") - return `Invalid string: must end with "${_issue.suffix}"`; - if (_issue.format === "includes") - return `Invalid string: must include "${_issue.includes}"`; - if (_issue.format === "regex") - return `Invalid string: must match pattern ${_issue.pattern}`; - return `Invalid ${FormatDictionary[_issue.format] ?? issue.format}`; - } - case "not_multiple_of": - return `Invalid number: must be a multiple of ${issue.divisor}`; - case "unrecognized_keys": - return `Unrecognized key${issue.keys.length > 1 ? "s" : ""}: ${joinValues(issue.keys, ", ")}`; - case "invalid_key": - return `Invalid key in ${issue.origin}`; - case "invalid_union": - if (issue.options && Array.isArray(issue.options) && issue.options.length > 0) { - const opts = issue.options.map((o) => `'${o}'`).join(" | "); - return `Invalid discriminator value. Expected ${opts}`; - } - if (issue.inclusive === false) { - return "Invalid input: more than one option matched"; - } - return "Invalid input"; - case "invalid_element": - return `Invalid value in ${issue.origin}`; - default: - return `Invalid input`; - } - }; -}; -/* export default */ function en() { - return { - localeError: en_error(), - }; -} - - - - -/* Prototypes that already carry the lazy helper methods. Seeded with the - * intrinsics so that `init` on a foreign object — it accepts any object — - * can never install an accessor onto a prototype we do not own. */ -const _installedErrorProtos = /* @__PURE__ */ new WeakSet([Object.prototype, Error.prototype]); -/* Helper methods live as non-enumerable lazy getters on the shared - * prototype instead of own properties on every instance. On first - * access the getter allocates the per-instance closure and caches it - * as a non-enumerable own property, so detached usage still works and - * the allocation only happens for methods actually touched. */ -function _lazyMethod(proto, key, make) { - Object.defineProperty(proto, key, { - configurable: true, - enumerable: false, - get() { - const value = make(this); - Object.defineProperty(this, key, { value, configurable: true, writable: true }); - return value; - }, - set(value) { - Object.defineProperty(this, key, { value, configurable: true, writable: true }); - }, - }); -} -const classic_errors_initializer = (inst, issues) => { - $ZodError.init(inst, issues); - inst.name = "ZodError"; - const proto = Object.getPrototypeOf(inst); - if (_installedErrorProtos.has(proto)) - return; - _installedErrorProtos.add(proto); - _lazyMethod(proto, "format", (self) => (mapper) => formatError(self, mapper)); - _lazyMethod(proto, "flatten", (self) => (mapper) => flattenError(self, mapper)); - _lazyMethod(proto, "addIssue", (self) => (issue) => { - self.issues.push(issue); - self.message = JSON.stringify(self.issues, jsonStringifyReplacer, 2); - }); - _lazyMethod(proto, "addIssues", (self) => (issues) => { - self.issues.push(...issues); - self.message = JSON.stringify(self.issues, jsonStringifyReplacer, 2); - }); - Object.defineProperty(proto, "isEmpty", { - configurable: true, - enumerable: false, - get() { - return this.issues.length === 0; - }, - }); -}; -const ZodError = /*@__PURE__*/ (/* unused pure expression or super */ null && (core.$constructor("ZodError", classic_errors_initializer))); -const ZodRealError = /*@__PURE__*/ $constructor("ZodError", classic_errors_initializer, undefined, { - Parent: Error, -}); -// /** @deprecated Use `z.core.$ZodErrorMapCtx` instead. */ -// export type ErrorMapCtx = core.$ZodErrorMapCtx; - - - -const classic_parse_parse = /* @__PURE__ */ parse_parse(ZodRealError); -const classic_parse_parseAsync = /* @__PURE__ */ parse_parseAsync(ZodRealError); -const parse_safeParse = /* @__PURE__ */ _safeParse(ZodRealError); -const parse_safeParseAsync = /* @__PURE__ */ _safeParseAsync(ZodRealError); - -// Codec functions -const classic_parse_encode = /* @__PURE__ */ parse_encode(ZodRealError); -const classic_parse_decode = /* @__PURE__ */ parse_decode(ZodRealError); -const classic_parse_encodeAsync = /* @__PURE__ */ parse_encodeAsync(ZodRealError); -const classic_parse_decodeAsync = /* @__PURE__ */ parse_decodeAsync(ZodRealError); -const parse_safeEncode = /* @__PURE__ */ _safeEncode(ZodRealError); -const parse_safeDecode = /* @__PURE__ */ _safeDecode(ZodRealError); -const parse_safeEncodeAsync = /* @__PURE__ */ _safeEncodeAsync(ZodRealError); -const parse_safeDecodeAsync = /* @__PURE__ */ _safeDecodeAsync(ZodRealError); - - - - - - - - -// Register English as the default locale on first ZodType construction. Hooked into the `ZodType` `$constructor` (rather than a top-level `config(en())` in `external.ts`) so bundlers honoring `sideEffects: false` can't tree-shake it out — see #5953, #5725. An explicit `z.config(z.locales.xx())` call wins regardless of order, since this only sets the default when none is present. -function _ensureDefaultLocale() { - if (!globalConfig.localeError) - core_config(en()); -} -// the default memoizer is read by the core container init, which runs before `ZodType.init`, so each container calls this first -function _ensureDefaultMemoizer() { - if (!globalConfig.memoizer) - core_config({ memoizer: memoizer() }); -} -const ZodType = /*@__PURE__*/ $constructor("ZodType", (inst, def) => { - _ensureDefaultLocale(); - $ZodType.init(inst, def); - inst.def = def; - inst.type = def.type; - return inst; -}, { - check(...chks) { - const def = this.def; - return this.clone(mergeDefs(def, { - checks: [ - ...(def.checks ?? []), - ...chks.map((ch) => typeof ch === "function" ? { _zod: { check: ch, def: { check: "custom" }, onattach: [] } } : ch), - ], - }), { parent: true }); - }, - with(...chks) { - return this.check(...chks); - }, - clone(def, params) { - return clone(this, def, params); - }, - brand() { - return this; - }, - register(reg, meta) { - reg.add(this, meta); - return this; - }, - refine(check, params) { - return this.check(refine(check, params)); - }, - superRefine(refinement, params) { - return this.check(superRefine(refinement, params)); - }, - overwrite(fn) { - return this.check(_overwrite(fn)); - }, - optional() { - return schemas_optional(this); - }, - exactOptional() { - return exactOptional(this); - }, - nullable() { - return nullable(this); - }, - nullish() { - return schemas_optional(nullable(this)); - }, - nonoptional(params) { - return nonoptional(this, params); - }, - array() { - return schemas_array(this); - }, - or(arg) { - return schemas_union([this, arg]); - }, - and(arg) { - return intersection(this, arg); - }, - transform(tx) { - return pipe(this, transform(tx)); - }, - default(d) { - return schemas_default(this, d); - }, - prefault(d) { - return prefault(this, d); - }, - catch(params) { - return schemas_catch(this, params); - }, - pipe(target) { - return pipe(this, target); - }, - readonly() { - return readonly(this); - }, - describe(description) { - const cl = this.clone(); - globalRegistry.add(cl, { description }); - return cl; - }, - meta(...args) { - // overloaded: meta() returns the registered metadata, meta(data) returns a clone with `data` registered. The mapped type picks up the second overload, so we accept variadic any-args and return `any` to satisfy both at runtime. - if (args.length === 0) - return globalRegistry.get(this); - const cl = this.clone(); - globalRegistry.add(cl, args[0]); - return cl; - }, - isOptional() { - return this.safeParse(undefined).success; - }, - isNullable() { - return this.safeParse(null).success; - }, - apply(fn, ...args) { - return args.length === 0 ? fn(this) : fn(this, ...args); - }, - // Overrides core's `~standard` to add `jsonSchema`. Must stay a prototype entry: redefining it per instance demotes instances to dictionary mode. - get "~standard"() { - return hide(this, "~standard", { - ...standardProps(this), - jsonSchema: { - input: createStandardJSONSchemaMethod(this, "input"), - output: createStandardJSONSchemaMethod(this, "output"), - }, - }); - }, - set "~standard"(value) { - util_own(this, "~standard", value); - }, - parse: function _parse(data, params) { - return classic_parse_parse(this, data, params, { callee: _parse }); - }, - parseAsync: async function _parseAsync(data, params) { - return await classic_parse_parseAsync(this, data, params, { callee: _parseAsync }); - }, - safeParse(data, params) { - return parse_safeParse(this, data, params); - }, - async safeParseAsync(data, params) { - return parse_safeParseAsync(this, data, params); - }, - // `spa` is an alias: same function object as `safeParseAsync`, as before. - get spa() { - return this?.safeParseAsync; - }, - set spa(value) { - util_own(this, "spa", value); - }, - encode: function _encode(data, params) { - return classic_parse_encode(this, data, params, { callee: _encode }); - }, - decode: function _decode(data, params) { - return classic_parse_decode(this, data, params, { callee: _decode }); - }, - encodeAsync: async function _encodeAsync(data, params) { - return await classic_parse_encodeAsync(this, data, params, { callee: _encodeAsync }); - }, - decodeAsync: async function _decodeAsync(data, params) { - return await classic_parse_decodeAsync(this, data, params, { callee: _decodeAsync }); - }, - safeEncode(data, params) { - return parse_safeEncode(this, data, params); - }, - safeDecode(data, params) { - return parse_safeDecode(this, data, params); - }, - async safeEncodeAsync(data, params) { - return parse_safeEncodeAsync(this, data, params); - }, - async safeDecodeAsync(data, params) { - return parse_safeDecodeAsync(this, data, params); - }, - toJSONSchema(params) { - return createToJSONSchemaMethod(this, {})(params); - }, - // Reads through to the registry on every access, so it must not cache. - get description() { - return globalRegistry.get(this)?.description; - }, - // No setter: `schema._def = x` throws, as it did when `_def` was a non-writable own property. - get _def() { - return this._zod.def; - }, -}); -/** @internal */ -const _ZodString = /*@__PURE__*/ $constructor("_ZodString", (inst, def) => { - $ZodString.init(inst, def); - ZodType.init(inst, def); - inst._zod.processJSONSchema = (ctx, json, params) => stringProcessor(inst, ctx, json, params); - const bag = inst._zod.bag; - inst.format = bag.format ?? null; - inst.minLength = bag.minimum ?? null; - inst.maxLength = bag.maximum ?? null; -}, { - regex(...args) { - return this.check(_regex(...args)); - }, - includes(...args) { - return this.check(_includes(...args)); - }, - startsWith(...args) { - return this.check(_startsWith(...args)); - }, - endsWith(...args) { - return this.check(_endsWith(...args)); - }, - min(...args) { - return this.check(_minLength(...args)); - }, - max(...args) { - return this.check(_maxLength(...args)); - }, - length(...args) { - return this.check(_length(...args)); - }, - nonempty(...args) { - return this.check(_minLength(1, ...args)); - }, - lowercase(params) { - return this.check(_lowercase(params)); - }, - uppercase(params) { - return this.check(_uppercase(params)); - }, - trim() { - return this.check(_trim()); - }, - normalize(...args) { - return this.check(_normalize(...args)); - }, - toLowerCase() { - return this.check(_toLowerCase()); - }, - toUpperCase() { - return this.check(_toUpperCase()); - }, - slugify() { - return this.check(_slugify()); - }, -}); -const ZodString = /*@__PURE__*/ $constructor("ZodString", (inst, def) => { - $ZodString.init(inst, def); - _ZodString.init(inst, def); -}, { - email(params) { - return this.check(_email(ZodEmail, params)); - }, - url(params) { - return this.check(_url(ZodURL, params)); - }, - jwt(params) { - return this.check(_jwt(ZodJWT, params)); - }, - emoji(params) { - return this.check(api_emoji(ZodEmoji, params)); - }, - guid(params) { - return this.check(_guid(ZodGUID, params)); - }, - uuid(params) { - return this.check(_uuid(ZodUUID, params)); - }, - uuidv4(params) { - return this.check(_uuidv4(ZodUUID, params)); - }, - uuidv6(params) { - return this.check(_uuidv6(ZodUUID, params)); - }, - uuidv7(params) { - return this.check(_uuidv7(ZodUUID, params)); - }, - nanoid(params) { - return this.check(_nanoid(ZodNanoID, params)); - }, - cuid(params) { - return this.check(_cuid(ZodCUID, params)); - }, - cuid2(params) { - return this.check(_cuid2(ZodCUID2, params)); - }, - ulid(params) { - return this.check(_ulid(ZodULID, params)); - }, - base64(params) { - return this.check(_base64(ZodBase64, params)); - }, - base64url(params) { - return this.check(_base64url(ZodBase64URL, params)); - }, - xid(params) { - return this.check(_xid(ZodXID, params)); - }, - ksuid(params) { - return this.check(_ksuid(ZodKSUID, params)); - }, - ipv4(params) { - return this.check(_ipv4(ZodIPv4, params)); - }, - ipv6(params) { - return this.check(_ipv6(ZodIPv6, params)); - }, - cidrv4(params) { - return this.check(_cidrv4(ZodCIDRv4, params)); - }, - cidrv6(params) { - return this.check(_cidrv6(ZodCIDRv6, params)); - }, - e164(params) { - return this.check(_e164(ZodE164, params)); - }, - datetime(params) { - return this.check(_isoDateTime(ZodISODateTime, params)); - }, - date(params) { - return this.check(_isoDate(ZodISODate, params)); - }, - time(params) { - return this.check(_isoTime(schemas_ZodISOTime, params)); - }, - duration(params) { - return this.check(_isoDuration(schemas_ZodISODuration, params)); - }, -}); -function schemas_string(params) { - return _string(ZodString, params); -} -const ZodStringFormat = /*@__PURE__*/ $constructor("ZodStringFormat", (inst, def) => { - $ZodStringFormat.init(inst, def); - _ZodString.init(inst, def); -}); -const ZodISODateTime = /*@__PURE__*/ $constructor("ZodISODateTime", (inst, def) => { - $ZodISODateTime.init(inst, def); - ZodStringFormat.init(inst, def); -}); -const ZodISODate = /*@__PURE__*/ $constructor("ZodISODate", (inst, def) => { - $ZodISODate.init(inst, def); - ZodStringFormat.init(inst, def); -}); -const schemas_ZodISOTime = /*@__PURE__*/ $constructor("ZodISOTime", (inst, def) => { - $ZodISOTime.init(inst, def); - ZodStringFormat.init(inst, def); -}); -const schemas_ZodISODuration = /*@__PURE__*/ $constructor("ZodISODuration", (inst, def) => { - $ZodISODuration.init(inst, def); - ZodStringFormat.init(inst, def); -}); -const ZodEmail = /*@__PURE__*/ $constructor("ZodEmail", (inst, def) => { - // ZodStringFormat.init(inst, def); - $ZodEmail.init(inst, def); - ZodStringFormat.init(inst, def); -}); -function schemas_email(params) { - return _email(ZodEmail, params); -} -const ZodGUID = /*@__PURE__*/ $constructor("ZodGUID", (inst, def) => { - // ZodStringFormat.init(inst, def); - $ZodGUID.init(inst, def); - ZodStringFormat.init(inst, def); -}); -function schemas_guid(params) { - return core._guid(ZodGUID, params); -} -const ZodUUID = /*@__PURE__*/ $constructor("ZodUUID", (inst, def) => { - // ZodStringFormat.init(inst, def); - $ZodUUID.init(inst, def); - ZodStringFormat.init(inst, def); -}); -function schemas_uuid(params) { - return core._uuid(ZodUUID, params); -} -function uuidv4(params) { - return core._uuidv4(ZodUUID, params); -} -// ZodUUIDv6 -function uuidv6(params) { - return core._uuidv6(ZodUUID, params); -} -// ZodUUIDv7 -function uuidv7(params) { - return core._uuidv7(ZodUUID, params); -} -const ZodURL = /*@__PURE__*/ $constructor("ZodURL", (inst, def) => { - // ZodStringFormat.init(inst, def); - $ZodURL.init(inst, def); - ZodStringFormat.init(inst, def); -}); -function schemas_url(params) { - return _url(ZodURL, params); -} -function httpUrl(params) { - return core._url(ZodURL, { - protocol: core.regexes.httpProtocol, - hostname: core.regexes.domain, - ...util.normalizeParams(params), - }); -} -const ZodEmoji = /*@__PURE__*/ $constructor("ZodEmoji", (inst, def) => { - // ZodStringFormat.init(inst, def); - $ZodEmoji.init(inst, def); - ZodStringFormat.init(inst, def); -}); -function schemas_emoji(params) { - return core._emoji(ZodEmoji, params); -} -const ZodNanoID = /*@__PURE__*/ $constructor("ZodNanoID", (inst, def) => { - // ZodStringFormat.init(inst, def); - $ZodNanoID.init(inst, def); - ZodStringFormat.init(inst, def); -}); -function schemas_nanoid(params) { - return core._nanoid(ZodNanoID, params); -} -/** - * @deprecated CUID v1 is deprecated by its authors due to information leakage - * (timestamps embedded in the id). Use {@link ZodCUID2} instead. - * See https://github.com/paralleldrive/cuid. - */ -const ZodCUID = /*@__PURE__*/ $constructor("ZodCUID", (inst, def) => { - // ZodStringFormat.init(inst, def); - $ZodCUID.init(inst, def); - ZodStringFormat.init(inst, def); -}); -/** - * Validates a CUID v1 string. - * - * @deprecated CUID v1 is deprecated by its authors due to information leakage - * (timestamps embedded in the id). Use {@link cuid2 | `z.cuid2()`} instead. - * See https://github.com/paralleldrive/cuid. - */ -function schemas_cuid(params) { - return core._cuid(ZodCUID, params); -} -const ZodCUID2 = /*@__PURE__*/ $constructor("ZodCUID2", (inst, def) => { - // ZodStringFormat.init(inst, def); - $ZodCUID2.init(inst, def); - ZodStringFormat.init(inst, def); -}); -function schemas_cuid2(params) { - return core._cuid2(ZodCUID2, params); -} -const ZodULID = /*@__PURE__*/ $constructor("ZodULID", (inst, def) => { - // ZodStringFormat.init(inst, def); - $ZodULID.init(inst, def); - ZodStringFormat.init(inst, def); -}); -function schemas_ulid(params) { - return core._ulid(ZodULID, params); -} -const ZodXID = /*@__PURE__*/ $constructor("ZodXID", (inst, def) => { - // ZodStringFormat.init(inst, def); - $ZodXID.init(inst, def); - ZodStringFormat.init(inst, def); -}); -function schemas_xid(params) { - return core._xid(ZodXID, params); -} -const ZodKSUID = /*@__PURE__*/ $constructor("ZodKSUID", (inst, def) => { - // ZodStringFormat.init(inst, def); - $ZodKSUID.init(inst, def); - ZodStringFormat.init(inst, def); -}); -function schemas_ksuid(params) { - return core._ksuid(ZodKSUID, params); -} -const ZodIPv4 = /*@__PURE__*/ $constructor("ZodIPv4", (inst, def) => { - // ZodStringFormat.init(inst, def); - $ZodIPv4.init(inst, def); - ZodStringFormat.init(inst, def); -}); -function schemas_ipv4(params) { - return core._ipv4(ZodIPv4, params); -} -const ZodMAC = /*@__PURE__*/ (/* unused pure expression or super */ null && (core.$constructor("ZodMAC", (inst, def) => { - // ZodStringFormat.init(inst, def); - core.$ZodMAC.init(inst, def); - ZodStringFormat.init(inst, def); -}))); -function schemas_mac(params) { - return core._mac(ZodMAC, params); -} -const ZodIPv6 = /*@__PURE__*/ $constructor("ZodIPv6", (inst, def) => { - // ZodStringFormat.init(inst, def); - $ZodIPv6.init(inst, def); - ZodStringFormat.init(inst, def); -}); -function schemas_ipv6(params) { - return core._ipv6(ZodIPv6, params); -} -const ZodCIDRv4 = /*@__PURE__*/ $constructor("ZodCIDRv4", (inst, def) => { - $ZodCIDRv4.init(inst, def); - ZodStringFormat.init(inst, def); -}); -function schemas_cidrv4(params) { - return core._cidrv4(ZodCIDRv4, params); -} -const ZodCIDRv6 = /*@__PURE__*/ $constructor("ZodCIDRv6", (inst, def) => { - $ZodCIDRv6.init(inst, def); - ZodStringFormat.init(inst, def); -}); -function schemas_cidrv6(params) { - return core._cidrv6(ZodCIDRv6, params); -} -const ZodBase64 = /*@__PURE__*/ $constructor("ZodBase64", (inst, def) => { - // ZodStringFormat.init(inst, def); - $ZodBase64.init(inst, def); - ZodStringFormat.init(inst, def); -}); -function schemas_base64(params) { - return core._base64(ZodBase64, params); -} -const ZodBase64URL = /*@__PURE__*/ $constructor("ZodBase64URL", (inst, def) => { - // ZodStringFormat.init(inst, def); - $ZodBase64URL.init(inst, def); - ZodStringFormat.init(inst, def); -}); -function schemas_base64url(params) { - return core._base64url(ZodBase64URL, params); -} -const ZodE164 = /*@__PURE__*/ $constructor("ZodE164", (inst, def) => { - // ZodStringFormat.init(inst, def); - $ZodE164.init(inst, def); - ZodStringFormat.init(inst, def); -}); -function schemas_e164(params) { - return core._e164(ZodE164, params); -} -const ZodCreditCard = /*@__PURE__*/ (/* unused pure expression or super */ null && (core.$constructor("ZodCreditCard", (inst, def) => { - core.$ZodCreditCard.init(inst, def); - ZodStringFormat.init(inst, def); -}))); -function schemas_creditCard(params) { - return core._creditCard(ZodCreditCard, params); -} -const ZodJWT = /*@__PURE__*/ $constructor("ZodJWT", (inst, def) => { - // ZodStringFormat.init(inst, def); - $ZodJWT.init(inst, def); - ZodStringFormat.init(inst, def); -}); -function jwt(params) { - return core._jwt(ZodJWT, params); -} -const ZodCustomStringFormat = /*@__PURE__*/ (/* unused pure expression or super */ null && (core.$constructor("ZodCustomStringFormat", (inst, def) => { - // ZodStringFormat.init(inst, def); - core.$ZodCustomStringFormat.init(inst, def); - ZodStringFormat.init(inst, def); -}))); -function stringFormat(format, fnOrRegex, _params = {}) { - return core._stringFormat(ZodCustomStringFormat, format, fnOrRegex, _params); -} -function schemas_hostname(_params) { - return core._stringFormat(ZodCustomStringFormat, "hostname", core.regexes.hostname, _params); -} -function schemas_hex(_params) { - return core._stringFormat(ZodCustomStringFormat, "hex", core.regexes.hex, _params); -} -function schemas_hash(alg, params) { - const enc = params?.enc ?? "hex"; - const format = `${alg}_${enc}`; - const regex = core.regexes[format]; - if (!regex) - throw new Error(`Unrecognized hash format: ${format}`); - return core._stringFormat(ZodCustomStringFormat, format, regex, params); -} -const ZodNumber = /*@__PURE__*/ $constructor("ZodNumber", (inst, def) => { - $ZodNumber.init(inst, def); - ZodType.init(inst, def); - inst._zod.processJSONSchema = (ctx, json, params) => numberProcessor(inst, ctx, json, params); - const bag = inst._zod.bag; - inst.minValue = - Math.max(bag.minimum ?? Number.NEGATIVE_INFINITY, bag.exclusiveMinimum ?? Number.NEGATIVE_INFINITY) ?? null; - inst.maxValue = - Math.min(bag.maximum ?? Number.POSITIVE_INFINITY, bag.exclusiveMaximum ?? Number.POSITIVE_INFINITY) ?? null; - inst.isInt = (bag.format ?? "").includes("int") || Number.isSafeInteger(bag.multipleOf ?? 0.5); - inst.isFinite = true; - inst.format = bag.format ?? null; -}, { - gt(value, params) { - return this.check(_gt(value, params)); - }, - gte(value, params) { - return this.check(_gte(value, params)); - }, - min(value, params) { - return this.check(_gte(value, params)); - }, - lt(value, params) { - return this.check(_lt(value, params)); - }, - lte(value, params) { - return this.check(_lte(value, params)); - }, - max(value, params) { - return this.check(_lte(value, params)); - }, - int(params) { - return this.check(schemas_int(params)); - }, - safe(params) { - return this.check(schemas_int(params)); - }, - positive(params) { - return this.check(_gt(0, params)); - }, - nonnegative(params) { - return this.check(_gte(0, params)); - }, - negative(params) { - return this.check(_lt(0, params)); - }, - nonpositive(params) { - return this.check(_lte(0, params)); - }, - multipleOf(value, params) { - return this.check(_multipleOf(value, params)); - }, - step(value, params) { - return this.check(_multipleOf(value, params)); - }, - finite() { - return this; - }, -}); -function schemas_number(params) { - return _number(ZodNumber, params); -} -const ZodNumberFormat = /*@__PURE__*/ $constructor("ZodNumberFormat", (inst, def) => { - $ZodNumberFormat.init(inst, def); - ZodNumber.init(inst, def); -}); -function schemas_int(params) { - return _int(ZodNumberFormat, params); -} -function float32(params) { - return core._float32(ZodNumberFormat, params); -} -function float64(params) { - return core._float64(ZodNumberFormat, params); -} -function int32(params) { - return core._int32(ZodNumberFormat, params); -} -function uint32(params) { - return core._uint32(ZodNumberFormat, params); -} -const ZodBoolean = /*@__PURE__*/ $constructor("ZodBoolean", (inst, def) => { - $ZodBoolean.init(inst, def); - ZodType.init(inst, def); - inst._zod.processJSONSchema = (ctx, json, params) => booleanProcessor(inst, ctx, json, params); -}); -function schemas_boolean(params) { - return _boolean(ZodBoolean, params); -} -const ZodBigInt = /*@__PURE__*/ (/* unused pure expression or super */ null && (core.$constructor("ZodBigInt", (inst, def) => { - core.$ZodBigInt.init(inst, def); - ZodType.init(inst, def); - inst._zod.processJSONSchema = (ctx, json, params) => processors.bigintProcessor(inst, ctx, json, params); - const bag = inst._zod.bag; - inst.minValue = bag.minimum ?? null; - inst.maxValue = bag.maximum ?? null; - inst.format = bag.format ?? null; -}, { - gte(value, params) { - return this.check(checks.gte(value, params)); - }, - min(value, params) { - return this.check(checks.gte(value, params)); - }, - gt(value, params) { - return this.check(checks.gt(value, params)); - }, - lt(value, params) { - return this.check(checks.lt(value, params)); - }, - lte(value, params) { - return this.check(checks.lte(value, params)); - }, - max(value, params) { - return this.check(checks.lte(value, params)); - }, - positive(params) { - return this.check(checks.gt(BigInt(0), params)); - }, - negative(params) { - return this.check(checks.lt(BigInt(0), params)); - }, - nonpositive(params) { - return this.check(checks.lte(BigInt(0), params)); - }, - nonnegative(params) { - return this.check(checks.gte(BigInt(0), params)); - }, - multipleOf(value, params) { - return this.check(checks.multipleOf(value, params)); - }, -}))); -function schemas_bigint(params) { - return core._bigint(ZodBigInt, params); -} -const ZodBigIntFormat = /*@__PURE__*/ (/* unused pure expression or super */ null && (core.$constructor("ZodBigIntFormat", (inst, def) => { - core.$ZodBigIntFormat.init(inst, def); - ZodBigInt.init(inst, def); -}))); -function int64(params) { - return core._int64(ZodBigIntFormat, params); -} -function uint64(params) { - return core._uint64(ZodBigIntFormat, params); -} -const ZodSymbol = /*@__PURE__*/ (/* unused pure expression or super */ null && (core.$constructor("ZodSymbol", (inst, def) => { - core.$ZodSymbol.init(inst, def); - ZodType.init(inst, def); - inst._zod.processJSONSchema = (ctx, json, params) => processors.symbolProcessor(inst, ctx, json, params); -}))); -function symbol(params) { - return core._symbol(ZodSymbol, params); -} -const ZodUndefined = /*@__PURE__*/ (/* unused pure expression or super */ null && (core.$constructor("ZodUndefined", (inst, def) => { - core.$ZodUndefined.init(inst, def); - ZodType.init(inst, def); - inst._zod.processJSONSchema = (ctx, json, params) => processors.undefinedProcessor(inst, ctx, json, params); -}))); -function schemas_undefined(params) { - return core._undefined(ZodUndefined, params); -} - -const ZodNull = /*@__PURE__*/ $constructor("ZodNull", (inst, def) => { - $ZodNull.init(inst, def); - ZodType.init(inst, def); - inst._zod.processJSONSchema = (ctx, json, params) => nullProcessor(inst, ctx, json, params); -}); -function schemas_null(params) { - return api_null(ZodNull, params); -} - -const ZodAny = /*@__PURE__*/ $constructor("ZodAny", (inst, def) => { - $ZodAny.init(inst, def); - ZodType.init(inst, def); - inst._zod.processJSONSchema = (ctx, json, params) => anyProcessor(inst, ctx, json, params); -}); -function any() { - return _any(ZodAny); -} -const ZodUnknown = /*@__PURE__*/ $constructor("ZodUnknown", (inst, def) => { - $ZodUnknown.init(inst, def); - ZodType.init(inst, def); - inst._zod.processJSONSchema = (ctx, json, params) => unknownProcessor(inst, ctx, json, params); -}); -function unknown() { - return _unknown(ZodUnknown); -} -const ZodNever = /*@__PURE__*/ $constructor("ZodNever", (inst, def) => { - $ZodNever.init(inst, def); - ZodType.init(inst, def); - inst._zod.processJSONSchema = (ctx, json, params) => neverProcessor(inst, ctx, json, params); -}); -function never(params) { - return _never(ZodNever, params); -} -const ZodVoid = /*@__PURE__*/ (/* unused pure expression or super */ null && (core.$constructor("ZodVoid", (inst, def) => { - core.$ZodVoid.init(inst, def); - ZodType.init(inst, def); - inst._zod.processJSONSchema = (ctx, json, params) => processors.voidProcessor(inst, ctx, json, params); -}))); -function schemas_void(params) { - return core._void(ZodVoid, params); -} - -const ZodDate = /*@__PURE__*/ (/* unused pure expression or super */ null && (core.$constructor("ZodDate", (inst, def) => { - core.$ZodDate.init(inst, def); - ZodType.init(inst, def); - inst._zod.processJSONSchema = (ctx, json, params) => processors.dateProcessor(inst, ctx, json, params); - inst.min = (value, params) => inst.check(checks.gte(value, params)); - inst.max = (value, params) => inst.check(checks.lte(value, params)); - const c = inst._zod.bag; - inst.minDate = c.minimum ? new Date(c.minimum) : null; - inst.maxDate = c.maximum ? new Date(c.maximum) : null; -}))); -function schemas_date(params) { - return core._date(ZodDate, params); -} -const ZodArray = /*@__PURE__*/ $constructor("ZodArray", (inst, def) => { - _ensureDefaultMemoizer(); - $ZodArray.init(inst, def); - ZodType.init(inst, def); - inst._zod.processJSONSchema = (ctx, json, params) => arrayProcessor(inst, ctx, json, params); - inst.element = def.element; -}, { - min(n, params) { - return this.check(_minLength(n, params)); - }, - nonempty(params) { - return this.check(_minLength(1, params)); - }, - max(n, params) { - return this.check(_maxLength(n, params)); - }, - length(n, params) { - return this.check(_length(n, params)); - }, - unwrap() { - return this.element; - }, -}); -function schemas_array(element, params) { - return _array(ZodArray, element, params); -} -// .keyof -function keyof(schema) { - const shape = schema._zod.def.shape; - return schemas_enum(Object.keys(shape)); -} -const ZodObject = /*@__PURE__*/ $constructor("ZodObject", (inst, def) => { - _ensureDefaultMemoizer(); - $ZodObjectJIT.init(inst, def); - ZodType.init(inst, def); - inst._zod.processJSONSchema = (ctx, json, params) => objectProcessor(inst, ctx, json, params); - installLazyProp(inst, "shape", (self) => self._zod.def.shape, false); -}, { - keyof() { - return schemas_enum(Object.keys(this._zod.def.shape)); - }, - catchall(catchall) { - return this.clone({ ...this._zod.def, catchall: catchall }); - }, - passthrough() { - return this.clone({ ...this._zod.def, catchall: unknown() }); - }, - loose() { - return this.clone({ ...this._zod.def, catchall: unknown() }); - }, - strict() { - return this.clone({ ...this._zod.def, catchall: never() }); - }, - strip() { - return this.clone({ ...this._zod.def, catchall: undefined }); - }, - extend(incoming) { - return extend(this, incoming); - }, - safeExtend(incoming) { - return safeExtend(this, incoming); - }, - merge(other) { - return merge(this, other); - }, - pick(mask) { - return pick(this, mask); - }, - omit(mask) { - return omit(this, mask); - }, - partial(...args) { - return partial(ZodOptional, this, args[0]); - }, - exactPartial(...args) { - return partial(ZodExactOptional, this, args[0], "exactPartial"); - }, - required(...args) { - return util_required(ZodNonOptional, this, args[0]); - }, -}); -function schemas_object(shape, params) { - const def = { - type: "object", - shape: shape ?? {}, - ...normalizeParams(params), - }; - return new ZodObject(def); -} -// strictObject -function strictObject(shape, params) { - return new ZodObject({ - type: "object", - shape, - catchall: never(), - ...util.normalizeParams(params), - }); -} -// looseObject -function looseObject(shape, params) { - return new ZodObject({ - type: "object", - shape, - catchall: unknown(), - ...normalizeParams(params), - }); -} -const ZodUnion = /*@__PURE__*/ $constructor("ZodUnion", (inst, def) => { - $ZodUnion.init(inst, def); - ZodType.init(inst, def); - inst._zod.processJSONSchema = (ctx, json, params) => unionProcessor(inst, ctx, json, params); - inst.options = def.options; -}); -function schemas_union(options, params) { - return new ZodUnion({ - type: "union", - options: options, - ...normalizeParams(params), - }); -} -const ZodXor = /*@__PURE__*/ (/* unused pure expression or super */ null && (core.$constructor("ZodXor", (inst, def) => { - ZodUnion.init(inst, def); - core.$ZodXor.init(inst, def); - inst._zod.processJSONSchema = (ctx, json, params) => processors.unionProcessor(inst, ctx, json, params); - inst.options = def.options; -}))); -/** Creates an exclusive union (XOR) where exactly one option must match. - * Unlike regular unions that succeed when any option matches, xor fails if - * zero or more than one option matches the input. */ -function xor(options, params) { - return new ZodXor({ - type: "union", - options: options, - inclusive: false, - ...util.normalizeParams(params), - }); -} -const ZodDiscriminatedUnion = /*@__PURE__*/ $constructor("ZodDiscriminatedUnion", (inst, def) => { - ZodUnion.init(inst, def); - $ZodDiscriminatedUnion.init(inst, def); -}); -function discriminatedUnion(discriminator, options, params) { - // const [options, params] = args; - return new ZodDiscriminatedUnion({ - type: "union", - options: options, - discriminator, - ...normalizeParams(params), - }); -} -const ZodIntersection = /*@__PURE__*/ $constructor("ZodIntersection", (inst, def) => { - $ZodIntersection.init(inst, def); - ZodType.init(inst, def); - inst._zod.processJSONSchema = (ctx, json, params) => intersectionProcessor(inst, ctx, json, params); -}); -function intersection(left, right) { - return new ZodIntersection({ - type: "intersection", - left: left, - right: right, - }); -} -const ZodTuple = /*@__PURE__*/ (/* unused pure expression or super */ null && (core.$constructor("ZodTuple", (inst, def) => { - _ensureDefaultMemoizer(); - core.$ZodTuple.init(inst, def); - ZodType.init(inst, def); - inst._zod.processJSONSchema = (ctx, json, params) => processors.tupleProcessor(inst, ctx, json, params); -}, { - rest(rest) { - return this.clone({ - ...this._zod.def, - rest: rest, - }); - }, - partial() { - const def = this._zod.def; - // a refinement was authored against the full arity; partialing would run it on a shorter array - if (def.checks?.length) - throw new Error(".partial() cannot be used on tuple schemas containing refinements"); - return this.clone({ - ...def, - items: def.items.map((item) => new ZodOptional({ type: "optional", innerType: item })), - }); - }, -}))); -function tuple(items, _paramsOrRest, _params) { - const hasRest = _paramsOrRest instanceof core.$ZodType; - const params = hasRest ? _params : _paramsOrRest; - const rest = hasRest ? _paramsOrRest : null; - return new ZodTuple({ - type: "tuple", - items: items, - rest, - ...util.normalizeParams(params), - }); -} -const ZodRecord = /*@__PURE__*/ $constructor("ZodRecord", (inst, def) => { - _ensureDefaultMemoizer(); - $ZodRecord.init(inst, def); - ZodType.init(inst, def); - inst._zod.processJSONSchema = (ctx, json, params) => recordProcessor(inst, ctx, json, params); - inst.keyType = def.keyType; - inst.valueType = def.valueType; -}); -function schemas_record(keyType, valueType, params) { - // v3-compat: z.record(valueType, params?) — defaults keyType to z.string() - if (!valueType || !valueType._zod) { - return new ZodRecord({ - type: "record", - keyType: schemas_string(), - valueType: keyType, - ...normalizeParams(valueType), - }); - } - return new ZodRecord({ - type: "record", - keyType, - valueType: valueType, - ...normalizeParams(params), - }); -} -// type alksjf = core.output; -function partialRecord(keyType, valueType, params) { - return new ZodRecord({ - type: "record", - keyType, - valueType: valueType, - ...util.normalizeParams(params), - partial: true, - }); -} -function looseRecord(keyType, valueType, params) { - return new ZodRecord({ - type: "record", - keyType, - valueType: valueType, - mode: "loose", - ...util.normalizeParams(params), - }); -} -const ZodMap = /*@__PURE__*/ (/* unused pure expression or super */ null && (core.$constructor("ZodMap", (inst, def) => { - _ensureDefaultMemoizer(); - core.$ZodMap.init(inst, def); - ZodType.init(inst, def); - inst._zod.processJSONSchema = (ctx, json, params) => processors.mapProcessor(inst, ctx, json, params); - inst.keyType = def.keyType; - inst.valueType = def.valueType; - inst.min = (...args) => inst.check(core._minSize(...args)); - inst.nonempty = (params) => inst.check(core._minSize(1, params)); - inst.max = (...args) => inst.check(core._maxSize(...args)); - inst.size = (...args) => inst.check(core._size(...args)); -}))); -function schemas_map(keyType, valueType, params) { - return new ZodMap({ - type: "map", - keyType: keyType, - valueType: valueType, - ...util.normalizeParams(params), - }); -} -const ZodSet = /*@__PURE__*/ (/* unused pure expression or super */ null && (core.$constructor("ZodSet", (inst, def) => { - _ensureDefaultMemoizer(); - core.$ZodSet.init(inst, def); - ZodType.init(inst, def); - inst._zod.processJSONSchema = (ctx, json, params) => processors.setProcessor(inst, ctx, json, params); - inst.min = (...args) => inst.check(core._minSize(...args)); - inst.nonempty = (params) => inst.check(core._minSize(1, params)); - inst.max = (...args) => inst.check(core._maxSize(...args)); - inst.size = (...args) => inst.check(core._size(...args)); -}))); -function schemas_set(valueType, params) { - return new ZodSet({ - type: "set", - valueType: valueType, - ...util.normalizeParams(params), - }); -} -const ZodEnum = /*@__PURE__*/ $constructor("ZodEnum", (inst, def) => { - $ZodEnum.init(inst, def); - ZodType.init(inst, def); - inst._zod.processJSONSchema = (ctx, json, params) => enumProcessor(inst, ctx, json, params); - inst.enum = def.entries; - inst.options = Object.values(def.entries); - const keys = new Set(Object.keys(def.entries)); - inst.extract = (values, params) => { - const newEntries = {}; - for (const value of values) { - if (keys.has(value)) { - newEntries[value] = def.entries[value]; - } - else - throw new Error(`Key ${value} not found in enum`); - } - return new ZodEnum({ - ...def, - checks: [], - ...normalizeParams(params), - entries: newEntries, - }); - }; - inst.exclude = (values, params) => { - const newEntries = { ...def.entries }; - for (const value of values) { - if (keys.has(value)) { - delete newEntries[value]; - } - else - throw new Error(`Key ${value} not found in enum`); - } - return new ZodEnum({ - ...def, - checks: [], - ...normalizeParams(params), - entries: newEntries, - }); - }; -}); -function schemas_enum(values, params) { - const entries = Array.isArray(values) ? Object.fromEntries(values.map((v) => [v, v])) : values; - return new ZodEnum({ - type: "enum", - entries, - ...normalizeParams(params), - }); -} - -/** @deprecated This API has been merged into `z.enum()`. Use `z.enum()` instead. - * - * ```ts - * enum Colors { red, green, blue } - * z.enum(Colors); - * ``` - */ -function nativeEnum(entries, params) { - return new ZodEnum({ - type: "enum", - entries, - ...util.normalizeParams(params), - }); -} -const ZodLiteral = /*@__PURE__*/ $constructor("ZodLiteral", (inst, def) => { - $ZodLiteral.init(inst, def); - ZodType.init(inst, def); - inst._zod.processJSONSchema = (ctx, json, params) => literalProcessor(inst, ctx, json, params); - inst.values = new Set(def.values); - Object.defineProperty(inst, "value", { - get() { - if (def.values.length > 1) { - throw new Error("This schema contains multiple valid literal values. Use `.values` instead."); - } - return def.values[0]; - }, - }); -}); -function literal(value, params) { - return new ZodLiteral({ - type: "literal", - values: Array.isArray(value) ? value : [value], - ...normalizeParams(params), - }); -} -const ZodFile = /*@__PURE__*/ (/* unused pure expression or super */ null && (core.$constructor("ZodFile", (inst, def) => { - core.$ZodFile.init(inst, def); - ZodType.init(inst, def); - inst._zod.processJSONSchema = (ctx, json, params) => processors.fileProcessor(inst, ctx, json, params); - inst.min = (size, params) => inst.check(core._minSize(size, params)); - inst.max = (size, params) => inst.check(core._maxSize(size, params)); - inst.mime = (types, params) => inst.check(core._mime(Array.isArray(types) ? types : [types], params)); -}))); -function schemas_file(params) { - return core._file(ZodFile, params); -} -const ZodTransform = /*@__PURE__*/ $constructor("ZodTransform", (inst, def) => { - _ensureDefaultMemoizer(); - $ZodTransform.init(inst, def); - ZodType.init(inst, def); - inst._zod.processJSONSchema = (ctx, json, params) => transformProcessor(inst, ctx, json, params); - inst._zod.parse = (payload, _ctx) => { - if (_ctx.direction === "backward") { - throw new $ZodEncodeError(inst.constructor.name); - } - payload.addIssue = (issue) => { - if (typeof issue === "string") { - payload.issues.push(util_issue(issue, payload.value, def)); - } - else { - // for Zod 3 backwards compatibility - const _issue = issue; - if (_issue.fatal) - _issue.continue = false; - _issue.code ?? (_issue.code = "custom"); - if (!("input" in _issue)) - _issue.input = payload.value; - _issue.inst ?? (_issue.inst = inst); - // _issue.continue ??= true; - payload.issues.push(util_issue(_issue)); - } - }; - const output = def.transform(payload.value, payload); - if (output instanceof Promise) { - return output.then((output) => { - payload.value = output; - return payload; - }); - } - payload.value = output; - return payload; - }; -}); -function transform(fn) { - return new ZodTransform({ - type: "transform", - transform: fn, - }); -} -const ZodOptional = /*@__PURE__*/ $constructor("ZodOptional", (inst, def) => { - $ZodOptional.init(inst, def); - ZodType.init(inst, def); - inst._zod.processJSONSchema = (ctx, json, params) => optionalProcessor(inst, ctx, json, params); - inst.unwrap = () => inst._zod.def.innerType; -}); -function schemas_optional(innerType) { - return new ZodOptional({ - type: "optional", - innerType: innerType, - }); -} -const ZodExactOptional = /*@__PURE__*/ $constructor("ZodExactOptional", (inst, def) => { - $ZodExactOptional.init(inst, def); - ZodType.init(inst, def); - inst._zod.processJSONSchema = (ctx, json, params) => optionalProcessor(inst, ctx, json, params); - inst.unwrap = () => inst._zod.def.innerType; -}); -function exactOptional(innerType) { - return new ZodExactOptional({ - type: "optional", - innerType: innerType, - }); -} -const ZodNullable = /*@__PURE__*/ $constructor("ZodNullable", (inst, def) => { - $ZodNullable.init(inst, def); - ZodType.init(inst, def); - inst._zod.processJSONSchema = (ctx, json, params) => nullableProcessor(inst, ctx, json, params); - inst.unwrap = () => inst._zod.def.innerType; -}); -function nullable(innerType) { - return new ZodNullable({ - type: "nullable", - innerType: innerType, - }); -} -// nullish -function schemas_nullish(innerType) { - return schemas_optional(nullable(innerType)); -} -const ZodDefault = /*@__PURE__*/ $constructor("ZodDefault", (inst, def) => { - $ZodDefault.init(inst, def); - ZodType.init(inst, def); - inst._zod.processJSONSchema = (ctx, json, params) => defaultProcessor(inst, ctx, json, params); - inst.unwrap = () => inst._zod.def.innerType; - inst.removeDefault = inst.unwrap; -}); -function schemas_default(innerType, defaultValue) { - return new ZodDefault({ - type: "default", - innerType: innerType, - get defaultValue() { - return typeof defaultValue === "function" ? defaultValue() : shallowClone(defaultValue); - }, - }); -} -const ZodPrefault = /*@__PURE__*/ $constructor("ZodPrefault", (inst, def) => { - $ZodPrefault.init(inst, def); - ZodType.init(inst, def); - inst._zod.processJSONSchema = (ctx, json, params) => prefaultProcessor(inst, ctx, json, params); - inst.unwrap = () => inst._zod.def.innerType; -}); -function prefault(innerType, defaultValue) { - return new ZodPrefault({ - type: "prefault", - innerType: innerType, - get defaultValue() { - return typeof defaultValue === "function" ? defaultValue() : shallowClone(defaultValue); - }, - }); -} -const ZodNonOptional = /*@__PURE__*/ $constructor("ZodNonOptional", (inst, def) => { - $ZodNonOptional.init(inst, def); - ZodType.init(inst, def); - inst._zod.processJSONSchema = (ctx, json, params) => nonoptionalProcessor(inst, ctx, json, params); - inst.unwrap = () => inst._zod.def.innerType; -}); -function nonoptional(innerType, params) { - return new ZodNonOptional({ - type: "nonoptional", - innerType: innerType, - ...normalizeParams(params), - }); -} -const ZodSuccess = /*@__PURE__*/ (/* unused pure expression or super */ null && (core.$constructor("ZodSuccess", (inst, def) => { - core.$ZodSuccess.init(inst, def); - ZodType.init(inst, def); - inst._zod.processJSONSchema = (ctx, json, params) => processors.successProcessor(inst, ctx, json, params); - inst.unwrap = () => inst._zod.def.innerType; -}))); -function success(innerType) { - return new ZodSuccess({ - type: "success", - innerType: innerType, - }); -} -const ZodCatch = /*@__PURE__*/ $constructor("ZodCatch", (inst, def) => { - $ZodCatch.init(inst, def); - ZodType.init(inst, def); - inst._zod.processJSONSchema = (ctx, json, params) => catchProcessor(inst, ctx, json, params); - inst.unwrap = () => inst._zod.def.innerType; - inst.removeCatch = inst.unwrap; -}); -function schemas_catch(innerType, catchValue) { - return new ZodCatch({ - type: "catch", - innerType: innerType, - catchValue: (typeof catchValue === "function" ? catchValue : constantCatch(catchValue)), - }); -} - -const ZodNaN = /*@__PURE__*/ (/* unused pure expression or super */ null && (core.$constructor("ZodNaN", (inst, def) => { - core.$ZodNaN.init(inst, def); - ZodType.init(inst, def); - inst._zod.processJSONSchema = (ctx, json, params) => processors.nanProcessor(inst, ctx, json, params); -}))); -function nan(params) { - return core._nan(ZodNaN, params); -} -const ZodPipe = /*@__PURE__*/ $constructor("ZodPipe", (inst, def) => { - $ZodPipe.init(inst, def); - ZodType.init(inst, def); - inst._zod.processJSONSchema = (ctx, json, params) => pipeProcessor(inst, ctx, json, params); - inst.in = def.in; - inst.out = def.out; -}); -function pipe(in_, out) { - return new ZodPipe({ - type: "pipe", - in: in_, - out: out, - // ...util.normalizeParams(params), - }); -} -const ZodCodec = /*@__PURE__*/ (/* unused pure expression or super */ null && (core.$constructor("ZodCodec", (inst, def) => { - ZodPipe.init(inst, def); - core.$ZodCodec.init(inst, def); -}))); -function schemas_codec(in_, out, params) { - return new ZodCodec({ - type: "pipe", - in: in_, - out: out, - transform: params.decode, - reverseTransform: params.encode, - }); -} -function invertCodec(codec) { - const def = codec._zod.def; - return new ZodCodec({ - type: "pipe", - in: def.out, - out: def.in, - transform: def.reverseTransform, - reverseTransform: def.transform, - }); -} -const ZodPreprocess = /*@__PURE__*/ $constructor("ZodPreprocess", (inst, def) => { - ZodPipe.init(inst, def); - $ZodPreprocess.init(inst, def); -}); -const ZodReadonly = /*@__PURE__*/ $constructor("ZodReadonly", (inst, def) => { - $ZodReadonly.init(inst, def); - ZodType.init(inst, def); - inst._zod.processJSONSchema = (ctx, json, params) => readonlyProcessor(inst, ctx, json, params); - inst.unwrap = () => inst._zod.def.innerType; -}); -function readonly(innerType) { - return new ZodReadonly({ - type: "readonly", - innerType: innerType, - }); -} -const ZodTemplateLiteral = /*@__PURE__*/ (/* unused pure expression or super */ null && (core.$constructor("ZodTemplateLiteral", (inst, def) => { - core.$ZodTemplateLiteral.init(inst, def); - ZodType.init(inst, def); - inst._zod.processJSONSchema = (ctx, json, params) => processors.templateLiteralProcessor(inst, ctx, json, params); -}))); -function templateLiteral(parts, params) { - return new ZodTemplateLiteral({ - type: "template_literal", - parts, - ...util.normalizeParams(params), - }); -} -const ZodLazy = /*@__PURE__*/ $constructor("ZodLazy", (inst, def) => { - $ZodLazy.init(inst, def); - ZodType.init(inst, def); - inst._zod.processJSONSchema = (ctx, json, params) => lazyProcessor(inst, ctx, json, params); - inst.unwrap = () => inst._zod.def.getter(); -}); -function lazy(getter) { - return new ZodLazy({ - type: "lazy", - getter: getter, - }); -} -const ZodPromise = /*@__PURE__*/ (/* unused pure expression or super */ null && (core.$constructor("ZodPromise", (inst, def) => { - core.$ZodPromise.init(inst, def); - ZodType.init(inst, def); - inst._zod.processJSONSchema = (ctx, json, params) => processors.promiseProcessor(inst, ctx, json, params); - inst.unwrap = () => inst._zod.def.innerType; -}))); -function schemas_promise(innerType) { - return new ZodPromise({ - type: "promise", - innerType: innerType, - }); -} -const ZodFunction = /*@__PURE__*/ (/* unused pure expression or super */ null && (core.$constructor("ZodFunction", (inst, def) => { - core.$ZodFunction.init(inst, def); - ZodType.init(inst, def); - inst._zod.processJSONSchema = (ctx, json, params) => processors.functionProcessor(inst, ctx, json, params); -}))); -function _function(params) { - return new ZodFunction({ - type: "function", - input: Array.isArray(params?.input) ? tuple(params?.input) : (params?.input ?? schemas_array(unknown())), - output: params?.output ?? unknown(), - }); -} - -const ZodCustom = /*@__PURE__*/ $constructor("ZodCustom", (inst, def) => { - $ZodCustom.init(inst, def); - ZodType.init(inst, def); - inst._zod.processJSONSchema = (ctx, json, params) => customProcessor(inst, ctx, json, params); -}); -// custom checks -function schemas_check(fn) { - const ch = new core.$ZodCheck({ - check: "custom", - // ...util.normalizeParams(params), - }); - ch._zod.check = fn; - return ch; -} -function custom(fn, _params) { - return core._custom(ZodCustom, fn ?? (() => true), _params); -} -function refine(fn, _params = {}) { - return _refine(ZodCustom, fn, _params); -} -// superRefine -function superRefine(fn, params) { - return _superRefine(fn, params); -} -// Re-export describe and meta from core -const schemas_describe = describe; -const schemas_meta = api_meta; -function _instanceof(cls, params = {}) { - const inst = new ZodCustom({ - type: "custom", - check: "custom", - fn: (data) => data instanceof cls, - abort: true, - ...util.normalizeParams(params), - }); - inst._zod.bag.Class = cls; - // Override check to emit invalid_type instead of custom - inst._zod.check = (payload) => { - if (!(payload.value instanceof cls)) { - payload.issues.push({ - code: "invalid_type", - expected: cls.name, - input: payload.value, - inst, - path: [...(inst._zod.def.path ?? [])], - }); - } - }; - return inst; -} - -// stringbool -const stringbool = (...args) => core._stringbool({ - Codec: ZodCodec, - Boolean: ZodBoolean, - String: ZodString, -}, ...args); -function schemas_json(params) { - const jsonSchema = lazy(() => { - return schemas_union([schemas_string(params), schemas_number(), schemas_boolean(), schemas_null(), schemas_array(jsonSchema), schemas_record(schemas_string(), jsonSchema)]); - }); - return jsonSchema; -} -// preprocess -function preprocess(fn, schema) { - return new ZodPreprocess({ - type: "pipe", - in: transform(fn), - out: schema, - }); -} - - - - -function iso_datetime(params) { - return _isoDateTime(ZodISODateTime, params); -} -function iso_date(params) { - return _isoDate(ZodISODate, params); -} -function iso_time(params) { - return core._isoTime(ZodISOTime, params); -} -function iso_duration(params) { - return core._isoDuration(ZodISODuration, params); -} - -// Zod 3 compat layer - -/** @deprecated Use the raw string literal codes instead, e.g. "invalid_type". */ -const ZodIssueCode = { - 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", -}; - -/** @deprecated Use `z.config(params)` instead. */ -function setErrorMap(map) { - core.config({ - customError: map, - }); -} -/** @deprecated Use `z.config()` instead. */ -function getErrorMap() { - return core.config().customError; -} -/** @deprecated Do not use. Stub definition, only included for zod-to-json-schema compatibility. */ -var compat_ZodFirstPartyTypeKind; -(function (ZodFirstPartyTypeKind) { -})(compat_ZodFirstPartyTypeKind || (compat_ZodFirstPartyTypeKind = {})); - - - -function coerce_string(params) { - return core._coercedString(schemas.ZodString, params); -} -function coerce_number(params) { - return _coercedNumber(ZodNumber, params); -} -function coerce_boolean(params) { - return core._coercedBoolean(schemas.ZodBoolean, params); -} -function coerce_bigint(params) { - return core._coercedBigint(schemas.ZodBigInt, params); -} -function coerce_date(params) { - return core._coercedDate(schemas.ZodDate, params); -} - - - -//#region src/constants.ts -const LATEST_PROTOCOL_VERSION = "2025-11-25"; -const auth_CUe6YdwF_DEFAULT_NEGOTIATED_PROTOCOL_VERSION = "2025-03-26"; -const auth_CUe6YdwF_SUPPORTED_PROTOCOL_VERSIONS = [ - LATEST_PROTOCOL_VERSION, - "2025-06-18", - "2025-03-26", - "2024-11-05", - "2024-10-07" -]; -/** -* `_meta` key associating a message with a 2025-11-25 task. -* -* @deprecated 2025-11-25 wire vocabulary with no SDK runtime; kept importable for interoperability only. -*/ -const RELATED_TASK_META_KEY = "io.modelcontextprotocol/related-task"; -/** -* `_meta` key carrying the MCP protocol version governing a request. -* -* For the HTTP transport, the value must match the `MCP-Protocol-Version` header. -*/ -const auth_CUe6YdwF_PROTOCOL_VERSION_META_KEY = "io.modelcontextprotocol/protocolVersion"; -/** -* `_meta` key identifying the client software making a request. -* -* Clients SHOULD include it on every request; the value is self-reported and -* intended for display, logging, and debugging — servers should not rely on -* it for behavior or security decisions. -*/ -const auth_CUe6YdwF_CLIENT_INFO_META_KEY = "io.modelcontextprotocol/clientInfo"; -/** -* `_meta` key identifying the server software producing a response. -* -* Servers SHOULD include it on every response; the value is self-reported and -* intended for display, logging, and debugging — clients should not rely on -* it for behavior or security decisions. -*/ -const auth_CUe6YdwF_SERVER_INFO_META_KEY = "io.modelcontextprotocol/serverInfo"; -/** -* `_meta` key carrying the client's capabilities for a request. -* -* Capabilities are declared per request rather than once at initialization; -* servers must not infer capabilities from prior requests. -*/ -const auth_CUe6YdwF_CLIENT_CAPABILITIES_META_KEY = "io.modelcontextprotocol/clientCapabilities"; -/** -* `_meta` key carrying the JSON-RPC ID of the `subscriptions/listen` request -* that opened the stream a notification was delivered on. -* -* Stamped by the server on every notification delivered via a -* `subscriptions/listen` stream (including the leading -* `notifications/subscriptions/acknowledged`); on stdio, where all messages -* share one channel, clients use it to correlate notifications with their -* originating subscription. The value is the listen request's JSON-RPC ID -* verbatim. -*/ -const auth_CUe6YdwF_SUBSCRIPTION_ID_META_KEY = "io.modelcontextprotocol/subscriptionId"; -/** -* `_meta` key carrying the desired log level for a request. -* -* When absent, the server must not send `notifications/message` notifications -* for the request. -* -* @deprecated Deprecated as of protocol version 2026-07-28 (SEP-2577); remains -* in the specification for at least twelve months. -*/ -const LOG_LEVEL_META_KEY = "io.modelcontextprotocol/logLevel"; -/** -* `_meta` key carrying W3C Trace Context for distributed tracing (SEP-414). -* -* When present, the value MUST follow the W3C `traceparent` header format, -* e.g. `00-4bf92f3577b34da6a3ce929d0e0e4736-00f067aa0ba902b7-01`. -* -* @see https://www.w3.org/TR/trace-context/#traceparent-header -*/ -const TRACEPARENT_META_KEY = "traceparent"; -/** -* `_meta` key carrying vendor-specific trace state for distributed tracing (SEP-414). -* -* When present, the value MUST follow the W3C `tracestate` header format, -* e.g. `vendor1=value1,vendor2=value2`. -* -* @see https://www.w3.org/TR/trace-context/#tracestate-header -*/ -const TRACESTATE_META_KEY = "tracestate"; -/** -* `_meta` key carrying cross-cutting propagation values for distributed tracing (SEP-414). -* -* When present, the value MUST follow the W3C Baggage header format, -* e.g. `userId=alice,serverRegion=us-east-1`. -* -* @see https://www.w3.org/TR/baggage/ -*/ -const BAGGAGE_META_KEY = "baggage"; -const JSONRPC_VERSION = "2.0"; -const PARSE_ERROR = (/* unused pure expression or super */ null && (-32700)); -const INVALID_REQUEST = (/* unused pure expression or super */ null && (-32600)); -const METHOD_NOT_FOUND = (/* unused pure expression or super */ null && (-32601)); -const INVALID_PARAMS = (/* unused pure expression or super */ null && (-32602)); -const INTERNAL_ERROR = (/* unused pure expression or super */ null && (-32603)); - -//#endregion -//#region src/schemas.ts -const JSONValueSchema = lazy(() => schemas_union([ - schemas_string(), - schemas_number(), - schemas_boolean(), - schemas_null(), - schemas_record(schemas_string(), JSONValueSchema), - schemas_array(JSONValueSchema) -])); -const JSONObjectSchema = schemas_record(schemas_string(), JSONValueSchema); -const JSONArraySchema = schemas_array(JSONValueSchema); -/** -* A progress token, used to associate progress notifications with the original request. -*/ -const ProgressTokenSchema = schemas_union([schemas_string(), schemas_number().int()]); -/** -* An opaque token used to represent a cursor for pagination. -*/ -const CursorSchema = schemas_string(); -/** @deprecated 2025-11-25 wire vocabulary with no SDK runtime; kept importable for interoperability only. */ -const TaskMetadataSchema = schemas_object({ ttl: schemas_number().optional() }); -/** -* Metadata for associating messages with a task. -* Include this in the `_meta` field under the key `io.modelcontextprotocol/related-task`. -* -* @deprecated 2025-11-25 wire vocabulary with no SDK runtime; kept importable for interoperability only. -*/ -const RelatedTaskMetadataSchema = schemas_object({ taskId: schemas_string() }); -const RequestMetaSchema = looseObject({ - progressToken: ProgressTokenSchema.optional(), - [RELATED_TASK_META_KEY]: RelatedTaskMetadataSchema.optional() -}); -/** -* Common params for any request. -*/ -const BaseRequestParamsSchema = schemas_object({ _meta: RequestMetaSchema.optional() }); -/** -* Common params for any task-augmented request. -* -* @deprecated 2025-11-25 wire vocabulary with no SDK runtime; kept importable for interoperability only. -*/ -const auth_CUe6YdwF_TaskAugmentedRequestParamsSchema = BaseRequestParamsSchema.extend({ task: TaskMetadataSchema.optional() }); -const RequestSchema = schemas_object({ - method: schemas_string(), - params: BaseRequestParamsSchema.loose().optional() -}); -const NotificationsParamsSchema = schemas_object({ _meta: RequestMetaSchema.optional() }); -const NotificationSchema = schemas_object({ - method: schemas_string(), - params: NotificationsParamsSchema.loose().optional() -}); -/** -* The contents of a result's `_meta` field (the 2026-07-28 `ResultMetaObject`). -* Loose — implementation-specific keys pass through. -* -* The serverInfo key identifies the server software producing the response -* (servers SHOULD include it on every response; the value is self-reported -* and intended for display, logging, and debugging). The getter defers the -* `ImplementationSchema` reference, which is declared later in this file. -*/ -const ResultMetaObjectSchema = looseObject({ get [auth_CUe6YdwF_SERVER_INFO_META_KEY]() { - return ImplementationSchema.optional().catch(void 0); -} }); -const ResultSchema = looseObject({ _meta: ResultMetaObjectSchema.optional() }); -/** -* A uniquely identifying ID for a request in JSON-RPC. -*/ -const RequestIdSchema = schemas_union([schemas_string(), schemas_number().int()]); -/** -* A request that expects a response. -*/ -const JSONRPCRequestSchema = schemas_object({ - jsonrpc: literal(JSONRPC_VERSION), - id: RequestIdSchema, - ...RequestSchema.shape -}).strict(); -/** -* A notification which does not expect a response. -*/ -const JSONRPCNotificationSchema = schemas_object({ - jsonrpc: literal(JSONRPC_VERSION), - ...NotificationSchema.shape -}).strict(); -/** -* A successful (non-error) response to a request. -*/ -const JSONRPCResultResponseSchema = schemas_object({ - jsonrpc: literal(JSONRPC_VERSION), - id: RequestIdSchema, - result: ResultSchema -}).strict(); -/** -* A response to a request that indicates an error occurred. -*/ -const JSONRPCErrorResponseSchema = schemas_object({ - jsonrpc: literal(JSONRPC_VERSION), - id: RequestIdSchema.optional(), - error: schemas_object({ - code: schemas_number().int(), - message: schemas_string(), - data: unknown().optional() - }) -}).strict(); -const auth_CUe6YdwF_JSONRPCMessageSchema = schemas_union([ - JSONRPCRequestSchema, - JSONRPCNotificationSchema, - JSONRPCResultResponseSchema, - JSONRPCErrorResponseSchema -]); -const auth_CUe6YdwF_JSONRPCResponseSchema = schemas_union([JSONRPCResultResponseSchema, JSONRPCErrorResponseSchema]); -/** -* A response that indicates success but carries no data. -*/ -const EmptyResultSchema = ResultSchema.strict(); -const CancelledNotificationParamsSchema = NotificationsParamsSchema.extend({ - requestId: RequestIdSchema.optional(), - reason: schemas_string().optional() -}); -/** -* This notification can be sent by either side to indicate that it is cancelling a previously-issued request. -* -* The request SHOULD still be in-flight, but due to communication latency, it is always possible that this notification MAY arrive after the request has already finished. -* -* This notification indicates that the result will be unused, so any associated processing SHOULD cease. -* -* A client MUST NOT attempt to cancel its {@linkcode InitializeRequest | initialize} request. -*/ -const CancelledNotificationSchema = NotificationSchema.extend({ - method: literal("notifications/cancelled"), - params: CancelledNotificationParamsSchema -}); -/** -* Icon schema for use in {@link Tool | tools}, {@link Prompt | prompts}, {@link Resource | resources}, and {@link Implementation | implementations}. -*/ -const IconSchema = schemas_object({ - src: schemas_string(), - mimeType: schemas_string().optional(), - sizes: schemas_array(schemas_string()).optional(), - theme: schemas_enum(["light", "dark"]).optional() -}); -/** -* Base schema to add `icons` property. -* -*/ -const IconsSchema = schemas_object({ icons: schemas_array(IconSchema).optional() }); -/** -* Base metadata interface for common properties across {@link Resource | resources}, {@link Tool | tools}, {@link Prompt | prompts}, and {@link Implementation | implementations}. -*/ -const BaseMetadataSchema = schemas_object({ - name: schemas_string(), - title: schemas_string().optional() -}); -/** -* Describes the name and version of an MCP implementation. -*/ -const ImplementationSchema = BaseMetadataSchema.extend({ - ...BaseMetadataSchema.shape, - ...IconsSchema.shape, - version: schemas_string(), - websiteUrl: schemas_string().optional(), - description: schemas_string().optional() -}); -const auth_CUe6YdwF_FormElicitationCapabilitySchema = intersection(schemas_object({ applyDefaults: schemas_boolean().optional() }), JSONObjectSchema); -const auth_CUe6YdwF_ElicitationCapabilitySchema = preprocess((value) => { - if (value && typeof value === "object" && !Array.isArray(value) && Object.keys(value).length === 0) return { form: {} }; - return value; -}, intersection(schemas_object({ - form: auth_CUe6YdwF_FormElicitationCapabilitySchema.optional(), - url: JSONObjectSchema.optional() -}), JSONObjectSchema.optional())); -/** -* Task capabilities for clients, indicating which request types support task creation. -* -* @deprecated 2025-11-25 wire vocabulary with no SDK runtime; kept importable for interoperability only. -*/ -const ClientTasksCapabilitySchema = looseObject({ - list: JSONObjectSchema.optional(), - cancel: JSONObjectSchema.optional(), - requests: looseObject({ - sampling: looseObject({ createMessage: JSONObjectSchema.optional() }).optional(), - elicitation: looseObject({ create: JSONObjectSchema.optional() }).optional() - }).optional() -}); -/** -* Task capabilities for servers, indicating which request types support task creation. -* -* @deprecated 2025-11-25 wire vocabulary with no SDK runtime; kept importable for interoperability only. -*/ -const ServerTasksCapabilitySchema = looseObject({ - list: JSONObjectSchema.optional(), - cancel: JSONObjectSchema.optional(), - requests: looseObject({ tools: looseObject({ call: JSONObjectSchema.optional() }).optional() }).optional() -}); -/** -* Capabilities a client may support. Known capabilities are defined here, in this schema, but this is not a closed set: any client can define its own, additional capabilities. -*/ -const ClientCapabilitiesSchema = schemas_object({ - experimental: schemas_record(schemas_string(), JSONObjectSchema).optional(), - sampling: schemas_object({ - context: JSONObjectSchema.optional(), - tools: JSONObjectSchema.optional() - }).optional(), - elicitation: auth_CUe6YdwF_ElicitationCapabilitySchema.optional(), - roots: schemas_object({ listChanged: schemas_boolean().optional() }).optional(), - tasks: ClientTasksCapabilitySchema.optional(), - extensions: schemas_record(schemas_string(), JSONObjectSchema).optional() -}); -const InitializeRequestParamsSchema = BaseRequestParamsSchema.extend({ - protocolVersion: schemas_string(), - capabilities: ClientCapabilitiesSchema, - clientInfo: ImplementationSchema -}); -/** -* This request is sent from the client to the server when it first connects, asking it to begin initialization. -*/ -const auth_CUe6YdwF_InitializeRequestSchema = RequestSchema.extend({ - method: literal("initialize"), - params: InitializeRequestParamsSchema -}); -/** -* Capabilities that a server may support. Known capabilities are defined here, in this schema, but this is not a closed set: any server can define its own, additional capabilities. -*/ -const ServerCapabilitiesSchema = schemas_object({ - experimental: schemas_record(schemas_string(), JSONObjectSchema).optional(), - logging: JSONObjectSchema.optional(), - completions: JSONObjectSchema.optional(), - prompts: schemas_object({ listChanged: schemas_boolean().optional() }).optional(), - resources: schemas_object({ - subscribe: schemas_boolean().optional(), - listChanged: schemas_boolean().optional() - }).optional(), - tools: schemas_object({ listChanged: schemas_boolean().optional() }).optional(), - tasks: ServerTasksCapabilitySchema.optional(), - extensions: schemas_record(schemas_string(), JSONObjectSchema).optional() -}); -/** -* After receiving an initialize request from the client, the server sends this response. -*/ -const InitializeResultSchema = ResultSchema.extend({ - protocolVersion: schemas_string(), - capabilities: ServerCapabilitiesSchema, - serverInfo: ImplementationSchema, - instructions: schemas_string().optional() -}); -/** -* This notification is sent from the client to the server after initialization has finished. -*/ -const auth_CUe6YdwF_InitializedNotificationSchema = NotificationSchema.extend({ - method: literal("notifications/initialized"), - params: NotificationsParamsSchema.optional() -}); -/** -* A request from the client asking the server to advertise its supported protocol -* versions, capabilities, and other metadata (protocol revision 2026-07-28). Servers -* MUST implement `server/discover`. Clients MAY call it but are not required to — -* version negotiation can also happen inline via the per-request `_meta` envelope. -*/ -const DiscoverRequestSchema = RequestSchema.extend({ - method: literal("server/discover"), - params: BaseRequestParamsSchema.optional() -}); -/** -* The result returned by the server for a `server/discover` request. -*/ -const DiscoverResultSchema = ResultSchema.extend({ - supportedVersions: schemas_array(schemas_string()), - capabilities: ServerCapabilitiesSchema, - instructions: schemas_string().optional() -}); -/** -* A ping, issued by either the server or the client, to check that the other party is still alive. The receiver must promptly respond, or else may be disconnected. -*/ -const PingRequestSchema = RequestSchema.extend({ - method: literal("ping"), - params: BaseRequestParamsSchema.optional() -}); -const ProgressSchema = schemas_object({ - progress: schemas_number(), - total: schemas_optional(schemas_number()), - message: schemas_optional(schemas_string()) -}); -const ProgressNotificationParamsSchema = schemas_object({ - ...NotificationsParamsSchema.shape, - ...ProgressSchema.shape, - progressToken: ProgressTokenSchema -}); -/** -* An out-of-band notification used to inform the receiver of a progress update for a long-running request. -* -* @category notifications/progress -*/ -const ProgressNotificationSchema = NotificationSchema.extend({ - method: literal("notifications/progress"), - params: ProgressNotificationParamsSchema -}); -const PaginatedRequestParamsSchema = BaseRequestParamsSchema.extend({ cursor: CursorSchema.optional() }); -const PaginatedRequestSchema = RequestSchema.extend({ params: PaginatedRequestParamsSchema.optional() }); -const PaginatedResultSchema = ResultSchema.extend({ nextCursor: CursorSchema.optional() }); -/** -* The contents of a specific resource or sub-resource. -*/ -const ResourceContentsSchema = schemas_object({ - uri: schemas_string(), - mimeType: schemas_optional(schemas_string()), - _meta: schemas_record(schemas_string(), unknown()).optional() -}); -const TextResourceContentsSchema = ResourceContentsSchema.extend({ text: schemas_string() }); -/** -* A Zod schema for validating Base64 strings that is more performant and -* robust for very large inputs than the default regex-based check. It avoids -* stack overflows by using the native `atob` function for validation. -*/ -const auth_CUe6YdwF_Base64Schema = schemas_string().refine((val) => { - try { - atob(val); - return true; - } catch { - return false; - } -}, { message: "Invalid Base64 string" }); -const BlobResourceContentsSchema = ResourceContentsSchema.extend({ blob: auth_CUe6YdwF_Base64Schema }); -/** -* The sender or recipient of messages and data in a conversation. -*/ -const RoleSchema = schemas_enum(["user", "assistant"]); -/** -* Optional annotations providing clients additional context about a resource. -*/ -const AnnotationsSchema = schemas_object({ - audience: schemas_array(RoleSchema).optional(), - priority: schemas_number().min(0).max(1).optional(), - lastModified: iso_datetime({ offset: true }).optional() -}); -/** -* A known resource that the server is capable of reading. -*/ -const ResourceSchema = schemas_object({ - ...BaseMetadataSchema.shape, - ...IconsSchema.shape, - uri: schemas_string(), - description: schemas_optional(schemas_string()), - mimeType: schemas_optional(schemas_string()), - size: schemas_optional(schemas_number()), - annotations: AnnotationsSchema.optional(), - _meta: schemas_optional(looseObject({})) -}); -/** -* A template description for resources available on the server. -*/ -const ResourceTemplateSchema = schemas_object({ - ...BaseMetadataSchema.shape, - ...IconsSchema.shape, - uriTemplate: schemas_string(), - description: schemas_optional(schemas_string()), - mimeType: schemas_optional(schemas_string()), - annotations: AnnotationsSchema.optional(), - _meta: schemas_optional(looseObject({})) -}); -/** -* Sent from the client to request a list of resources the server has. -*/ -const ListResourcesRequestSchema = PaginatedRequestSchema.extend({ method: literal("resources/list") }); -/** -* The server's response to a {@linkcode ListResourcesRequest | resources/list} request from the client. -*/ -const ListResourcesResultSchema = PaginatedResultSchema.extend({ resources: schemas_array(ResourceSchema) }); -/** -* Sent from the client to request a list of resource templates the server has. -*/ -const ListResourceTemplatesRequestSchema = PaginatedRequestSchema.extend({ method: literal("resources/templates/list") }); -/** -* The server's response to a {@linkcode ListResourceTemplatesRequest | resources/templates/list} request from the client. -*/ -const ListResourceTemplatesResultSchema = PaginatedResultSchema.extend({ resourceTemplates: schemas_array(ResourceTemplateSchema) }); -const ResourceRequestParamsSchema = BaseRequestParamsSchema.extend({ uri: schemas_string() }); -/** -* Parameters for a {@linkcode ReadResourceRequest | resources/read} request. -*/ -const ReadResourceRequestParamsSchema = ResourceRequestParamsSchema; -/** -* Sent from the client to the server, to read a specific resource URI. -*/ -const ReadResourceRequestSchema = RequestSchema.extend({ - method: literal("resources/read"), - params: ReadResourceRequestParamsSchema -}); -/** -* The server's response to a {@linkcode ReadResourceRequest | resources/read} request from the client. -*/ -const ReadResourceResultSchema = ResultSchema.extend({ contents: schemas_array(schemas_union([TextResourceContentsSchema, BlobResourceContentsSchema])) }); -/** -* An optional notification from the server to the client, informing it that the list of resources it can read from has changed. This may be issued by servers without any previous subscription from the client. -*/ -const ResourceListChangedNotificationSchema = NotificationSchema.extend({ - method: literal("notifications/resources/list_changed"), - params: NotificationsParamsSchema.optional() -}); -const SubscribeRequestParamsSchema = ResourceRequestParamsSchema; -/** -* Sent from the client to request `resources/updated` notifications from the server whenever a particular resource changes. -*/ -const SubscribeRequestSchema = RequestSchema.extend({ - method: literal("resources/subscribe"), - params: SubscribeRequestParamsSchema -}); -const UnsubscribeRequestParamsSchema = ResourceRequestParamsSchema; -/** -* Sent from the client to request cancellation of {@linkcode ResourceUpdatedNotification | resources/updated} notifications from the server. This should follow a previous {@linkcode SubscribeRequest | resources/subscribe} request. -*/ -const UnsubscribeRequestSchema = RequestSchema.extend({ - method: literal("resources/unsubscribe"), - params: UnsubscribeRequestParamsSchema -}); -/** -* The set of notification types a client opts in to on a `subscriptions/listen` -* request. Each type is opt-in; the server MUST NOT send a notification type -* the client has not explicitly requested here. -*/ -const SubscriptionFilterSchema = schemas_object({ - toolsListChanged: schemas_boolean().optional(), - promptsListChanged: schemas_boolean().optional(), - resourcesListChanged: schemas_boolean().optional(), - resourceSubscriptions: schemas_array(schemas_string()).optional() -}); -const SubscriptionsListenRequestParamsSchema = BaseRequestParamsSchema.extend({ notifications: SubscriptionFilterSchema }); -/** -* Sent from the client to open a long-lived channel for receiving notifications -* outside the context of a specific request (protocol revision 2026-07-28). -* Replaces the previous HTTP GET endpoint and `resources/subscribe`. -*/ -const SubscriptionsListenRequestSchema = RequestSchema.extend({ - method: literal("subscriptions/listen"), - params: SubscriptionsListenRequestParamsSchema -}); -const SubscriptionsAcknowledgedNotificationParamsSchema = NotificationsParamsSchema.extend({ notifications: SubscriptionFilterSchema }); -/** -* Sent by the server as the first message on a `subscriptions/listen` stream -* to acknowledge that the subscription has been established and report which -* notification types it agreed to honor (protocol revision 2026-07-28). -*/ -const SubscriptionsAcknowledgedNotificationSchema = NotificationSchema.extend({ - method: literal("notifications/subscriptions/acknowledged"), - params: SubscriptionsAcknowledgedNotificationParamsSchema -}); -/** -* `_meta` for a {@linkcode SubscriptionsListenResult}: the listen request's -* JSON-RPC ID under the canonical subscription-id key (mirroring the same key -* on every notification delivered on the stream). Extends -* {@linkcode ResultMetaObjectSchema}, so the optional serverInfo key is typed -* here too. -*/ -const SubscriptionsListenResultMetaSchema = ResultMetaObjectSchema.extend({ [auth_CUe6YdwF_SUBSCRIPTION_ID_META_KEY]: RequestIdSchema }); -/** -* The response to a `subscriptions/listen` request, signalling that the -* subscription has ended gracefully (for example, during server shutdown). -* Because the listen stream is long-lived, this result is sent only when the -* server tears the subscription down; an abrupt transport close carries no -* response. The result body is otherwise empty. -*/ -const SubscriptionsListenResultSchema = ResultSchema.extend({ _meta: SubscriptionsListenResultMetaSchema }); -/** -* Parameters for a {@linkcode ResourceUpdatedNotification | notifications/resources/updated} notification. -*/ -const ResourceUpdatedNotificationParamsSchema = NotificationsParamsSchema.extend({ uri: schemas_string() }); -/** -* A notification from the server to the client, informing it that a resource has changed and may need to be read again. This should only be sent if the client previously sent a {@linkcode SubscribeRequest | resources/subscribe} request. -*/ -const ResourceUpdatedNotificationSchema = NotificationSchema.extend({ - method: literal("notifications/resources/updated"), - params: ResourceUpdatedNotificationParamsSchema -}); -/** -* Describes an argument that a prompt can accept. -*/ -const PromptArgumentSchema = schemas_object({ - name: schemas_string(), - description: schemas_optional(schemas_string()), - required: schemas_optional(schemas_boolean()) -}); -/** -* A prompt or prompt template that the server offers. -*/ -const PromptSchema = schemas_object({ - ...BaseMetadataSchema.shape, - ...IconsSchema.shape, - description: schemas_optional(schemas_string()), - arguments: schemas_optional(schemas_array(PromptArgumentSchema)), - _meta: schemas_optional(looseObject({})) -}); -/** -* Sent from the client to request a list of prompts and prompt templates the server has. -*/ -const ListPromptsRequestSchema = PaginatedRequestSchema.extend({ method: literal("prompts/list") }); -/** -* The server's response to a {@linkcode ListPromptsRequest | prompts/list} request from the client. -*/ -const ListPromptsResultSchema = PaginatedResultSchema.extend({ prompts: schemas_array(PromptSchema) }); -/** -* Parameters for a {@linkcode GetPromptRequest | prompts/get} request. -*/ -const GetPromptRequestParamsSchema = BaseRequestParamsSchema.extend({ - name: schemas_string(), - arguments: schemas_record(schemas_string(), schemas_string()).optional() -}); -/** -* Used by the client to get a prompt provided by the server. -*/ -const GetPromptRequestSchema = RequestSchema.extend({ - method: literal("prompts/get"), - params: GetPromptRequestParamsSchema -}); -/** -* Text provided to or from an LLM. -*/ -const TextContentSchema = schemas_object({ - type: literal("text"), - text: schemas_string(), - annotations: AnnotationsSchema.optional(), - _meta: schemas_record(schemas_string(), unknown()).optional() -}); -/** -* An image provided to or from an LLM. -*/ -const ImageContentSchema = schemas_object({ - type: literal("image"), - data: auth_CUe6YdwF_Base64Schema, - mimeType: schemas_string(), - annotations: AnnotationsSchema.optional(), - _meta: schemas_record(schemas_string(), unknown()).optional() -}); -/** -* Audio content provided to or from an LLM. -*/ -const AudioContentSchema = schemas_object({ - type: literal("audio"), - data: auth_CUe6YdwF_Base64Schema, - mimeType: schemas_string(), - annotations: AnnotationsSchema.optional(), - _meta: schemas_record(schemas_string(), unknown()).optional() -}); -/** -* A tool call request from an assistant (LLM). -* Represents the assistant's request to use a tool. -* -* @deprecated Deprecated as of protocol version 2026-07-28 (SEP-2577); remains -* in the specification for at least twelve months. Migrate to calling LLM -* provider APIs directly. -*/ -const ToolUseContentSchema = schemas_object({ - type: literal("tool_use"), - name: schemas_string(), - id: schemas_string(), - input: schemas_record(schemas_string(), unknown()), - _meta: schemas_record(schemas_string(), unknown()).optional() -}); -/** -* The contents of a resource, embedded into a prompt or tool call result. -*/ -const EmbeddedResourceSchema = schemas_object({ - type: literal("resource"), - resource: schemas_union([TextResourceContentsSchema, BlobResourceContentsSchema]), - annotations: AnnotationsSchema.optional(), - _meta: schemas_record(schemas_string(), unknown()).optional() -}); -/** -* A resource that the server is capable of reading, included in a prompt or tool call result. -* -* Note: resource links returned by tools are not guaranteed to appear in the results of {@linkcode ListResourcesRequest | resources/list} requests. -*/ -const ResourceLinkSchema = ResourceSchema.extend({ type: literal("resource_link") }); -/** -* A content block that can be used in prompts and tool results. -*/ -const ContentBlockSchema = schemas_union([ - TextContentSchema, - ImageContentSchema, - AudioContentSchema, - ResourceLinkSchema, - EmbeddedResourceSchema -]); -/** -* Describes a message returned as part of a prompt. -*/ -const PromptMessageSchema = schemas_object({ - role: RoleSchema, - content: ContentBlockSchema -}); -/** -* The server's response to a {@linkcode GetPromptRequest | prompts/get} request from the client. -*/ -const GetPromptResultSchema = ResultSchema.extend({ - description: schemas_string().optional(), - messages: schemas_array(PromptMessageSchema) -}); -/** -* An optional notification from the server to the client, informing it that the list of prompts it offers has changed. This may be issued by servers without any previous subscription from the client. -*/ -const PromptListChangedNotificationSchema = NotificationSchema.extend({ - method: literal("notifications/prompts/list_changed"), - params: NotificationsParamsSchema.optional() -}); -/** -* Additional properties describing a `Tool` to clients. -* -* NOTE: all properties in {@linkcode ToolAnnotations} are **hints**. -* They are not guaranteed to provide a faithful description of -* tool behavior (including descriptive properties like `title`). -* -* Clients should never make tool use decisions based on `ToolAnnotations` -* received from untrusted servers. -*/ -const ToolAnnotationsSchema = schemas_object({ - title: schemas_string().optional(), - readOnlyHint: schemas_boolean().optional(), - destructiveHint: schemas_boolean().optional(), - idempotentHint: schemas_boolean().optional(), - openWorldHint: schemas_boolean().optional() -}); -/** -* Execution-related properties for a tool. -*/ -const ToolExecutionSchema = schemas_object({ taskSupport: schemas_enum([ - "required", - "optional", - "forbidden" -]).optional() }); -/** -* Definition for a tool the client can call. -*/ -const ToolSchema = schemas_object({ - ...BaseMetadataSchema.shape, - ...IconsSchema.shape, - description: schemas_string().optional(), - inputSchema: schemas_object({ - type: literal("object"), - properties: schemas_record(schemas_string(), JSONValueSchema).optional(), - required: schemas_array(schemas_string()).optional() - }).catchall(unknown()), - outputSchema: looseObject({ $schema: schemas_string().optional() }).optional(), - annotations: ToolAnnotationsSchema.optional(), - execution: ToolExecutionSchema.optional(), - _meta: schemas_record(schemas_string(), unknown()).optional() -}); -/** -* Sent from the client to request a list of tools the server has. -*/ -const ListToolsRequestSchema = PaginatedRequestSchema.extend({ method: literal("tools/list") }); -/** -* The server's response to a {@linkcode ListToolsRequest | tools/list} request from the client. -*/ -const ListToolsResultSchema = PaginatedResultSchema.extend({ tools: schemas_array(ToolSchema) }); -/** -* The server's response to a tool call. -*/ -const auth_CUe6YdwF_CallToolResultSchema = ResultSchema.extend({ - content: schemas_array(ContentBlockSchema).default([]), - structuredContent: unknown().optional(), - isError: schemas_boolean().optional() -}); -/** -* {@linkcode CallToolResultSchema} extended with backwards compatibility to protocol version 2024-10-07. -*/ -const CompatibilityCallToolResultSchema = auth_CUe6YdwF_CallToolResultSchema.or(ResultSchema.extend({ toolResult: unknown() })); -/** -* Parameters for a `tools/call` request. -*/ -const CallToolRequestParamsSchema = auth_CUe6YdwF_TaskAugmentedRequestParamsSchema.extend({ - name: schemas_string(), - arguments: schemas_record(schemas_string(), unknown()).optional() -}); -/** -* Used by the client to invoke a tool provided by the server. -*/ -const CallToolRequestSchema = RequestSchema.extend({ - method: literal("tools/call"), - params: CallToolRequestParamsSchema -}); -/** -* An optional notification from the server to the client, informing it that the list of tools it offers has changed. This may be issued by servers without any previous subscription from the client. -*/ -const ToolListChangedNotificationSchema = NotificationSchema.extend({ - method: literal("notifications/tools/list_changed"), - params: NotificationsParamsSchema.optional() -}); -/** -* Base schema for list changed subscription options (without callback). -* Used internally for Zod validation of `autoRefresh` and `debounceMs`. -*/ -const ListChangedOptionsBaseSchema = schemas_object({ - autoRefresh: schemas_boolean().default(true), - debounceMs: schemas_number().int().nonnegative().default(300) -}); -/** -* The severity of a log message. -* -* @deprecated Deprecated as of protocol version 2026-07-28 (SEP-2577); remains -* in the specification for at least twelve months. Migrate to stderr logging -* (STDIO servers) or OpenTelemetry. -*/ -const LoggingLevelSchema = schemas_enum([ - "debug", - "info", - "notice", - "warning", - "error", - "critical", - "alert", - "emergency" -]); -/** -* Parameters for a `logging/setLevel` request. -* -* @deprecated Deprecated as of protocol version 2026-07-28 (SEP-2577); remains -* in the specification for at least twelve months. Migrate to stderr logging -* (STDIO servers) or OpenTelemetry. -*/ -const SetLevelRequestParamsSchema = BaseRequestParamsSchema.extend({ level: LoggingLevelSchema }); -/** -* A request from the client to the server, to enable or adjust logging. -* -* @deprecated Deprecated as of protocol version 2026-07-28 (SEP-2577); remains -* in the specification for at least twelve months. Migrate to stderr logging -* (STDIO servers) or OpenTelemetry. -*/ -const SetLevelRequestSchema = RequestSchema.extend({ - method: literal("logging/setLevel"), - params: SetLevelRequestParamsSchema -}); -/** -* Parameters for a `notifications/message` notification. -* -* @deprecated Deprecated as of protocol version 2026-07-28 (SEP-2577); remains -* in the specification for at least twelve months. Migrate to stderr logging -* (STDIO servers) or OpenTelemetry. -*/ -const LoggingMessageNotificationParamsSchema = NotificationsParamsSchema.extend({ - level: LoggingLevelSchema, - logger: schemas_string().optional(), - data: unknown() -}); -/** -* Notification of a log message passed from server to client. If no `logging/setLevel` request has been sent from the client, the server MAY decide which messages to send automatically. -* -* @deprecated Deprecated as of protocol version 2026-07-28 (SEP-2577); remains -* in the specification for at least twelve months. Migrate to stderr logging -* (STDIO servers) or OpenTelemetry. -*/ -const LoggingMessageNotificationSchema = NotificationSchema.extend({ - method: literal("notifications/message"), - params: LoggingMessageNotificationParamsSchema -}); -/** -* Hints to use for model selection. -* -* @deprecated Deprecated as of protocol version 2026-07-28 (SEP-2577); remains -* in the specification for at least twelve months. Migrate to calling LLM -* provider APIs directly. -*/ -const ModelHintSchema = schemas_object({ name: schemas_string().optional() }); -/** -* The server's preferences for model selection, requested of the client during sampling. -* -* @deprecated Deprecated as of protocol version 2026-07-28 (SEP-2577); remains -* in the specification for at least twelve months. Migrate to calling LLM -* provider APIs directly. -*/ -const ModelPreferencesSchema = schemas_object({ - hints: schemas_array(ModelHintSchema).optional(), - costPriority: schemas_number().min(0).max(1).optional(), - speedPriority: schemas_number().min(0).max(1).optional(), - intelligencePriority: schemas_number().min(0).max(1).optional() -}); -/** -* Controls tool usage behavior in sampling requests. -* -* @deprecated Deprecated as of protocol version 2026-07-28 (SEP-2577); remains -* in the specification for at least twelve months. Migrate to calling LLM -* provider APIs directly. -*/ -const ToolChoiceSchema = schemas_object({ mode: schemas_enum([ - "auto", - "required", - "none" -]).optional() }); -/** -* The result of a tool execution, provided by the user (server). -* Represents the outcome of invoking a tool requested via `ToolUseContent`. -* -* @deprecated Deprecated as of protocol version 2026-07-28 (SEP-2577); remains -* in the specification for at least twelve months. Migrate to calling LLM -* provider APIs directly. -*/ -const ToolResultContentSchema = schemas_object({ - type: literal("tool_result"), - toolUseId: schemas_string().describe("The unique identifier for the corresponding tool call."), - content: schemas_array(ContentBlockSchema), - structuredContent: unknown().optional(), - isError: schemas_boolean().optional(), - _meta: schemas_record(schemas_string(), unknown()).optional() -}); -/** -* Basic content types for sampling responses (without tool use). -* Used for backwards-compatible {@linkcode CreateMessageResult} when tools are not used. -* -* @deprecated Deprecated as of protocol version 2026-07-28 (SEP-2577); remains -* in the specification for at least twelve months. Migrate to calling LLM -* provider APIs directly. -*/ -const SamplingContentSchema = discriminatedUnion("type", [ - TextContentSchema, - ImageContentSchema, - AudioContentSchema -]); -/** -* Content block types allowed in sampling messages. -* This includes text, image, audio, tool use requests, and tool results. -* -* @deprecated Deprecated as of protocol version 2026-07-28 (SEP-2577); remains -* in the specification for at least twelve months. Migrate to calling LLM -* provider APIs directly. -*/ -const SamplingMessageContentBlockSchema = discriminatedUnion("type", [ - TextContentSchema, - ImageContentSchema, - AudioContentSchema, - ToolUseContentSchema, - ToolResultContentSchema -]); -/** -* Describes a message issued to or received from an LLM API. -* -* @deprecated Deprecated as of protocol version 2026-07-28 (SEP-2577); remains -* in the specification for at least twelve months. Migrate to calling LLM -* provider APIs directly. -*/ -const SamplingMessageSchema = schemas_object({ - role: RoleSchema, - content: schemas_union([SamplingMessageContentBlockSchema, schemas_array(SamplingMessageContentBlockSchema)]), - _meta: schemas_record(schemas_string(), unknown()).optional() -}); -/** -* Parameters for a `sampling/createMessage` request. -* -* @deprecated Deprecated as of protocol version 2026-07-28 (SEP-2577); remains -* in the specification for at least twelve months. Migrate to calling LLM -* provider APIs directly. -*/ -const CreateMessageRequestParamsSchema = auth_CUe6YdwF_TaskAugmentedRequestParamsSchema.extend({ - messages: schemas_array(SamplingMessageSchema), - modelPreferences: ModelPreferencesSchema.optional(), - systemPrompt: schemas_string().optional(), - includeContext: schemas_enum([ - "none", - "thisServer", - "allServers" - ]).optional(), - temperature: schemas_number().optional(), - maxTokens: schemas_number().int(), - stopSequences: schemas_array(schemas_string()).optional(), - metadata: JSONObjectSchema.optional(), - tools: schemas_array(ToolSchema).optional(), - toolChoice: ToolChoiceSchema.optional() -}); -/** -* A request from the server to sample an LLM via the client. The client has full discretion over which model to select. The client should also inform the user before beginning sampling, to allow them to inspect the request (human in the loop) and decide whether to approve it. -* -* @deprecated Deprecated as of protocol version 2026-07-28 (SEP-2577); remains -* in the specification for at least twelve months. Migrate to calling LLM -* provider APIs directly. -*/ -const CreateMessageRequestSchema = RequestSchema.extend({ - method: literal("sampling/createMessage"), - params: CreateMessageRequestParamsSchema -}); -/** -* The client's response to a `sampling/create_message` request from the server. -* This is the backwards-compatible version that returns single content (no arrays). -* Used when the request does not include tools. -* -* @deprecated Deprecated as of protocol version 2026-07-28 (SEP-2577); remains -* in the specification for at least twelve months. Migrate to calling LLM -* provider APIs directly. -*/ -const CreateMessageResultSchema = ResultSchema.extend({ - model: schemas_string(), - stopReason: schemas_optional(schemas_enum([ - "endTurn", - "stopSequence", - "maxTokens" - ]).or(schemas_string())), - role: RoleSchema, - content: SamplingContentSchema -}); -/** -* The client's response to a `sampling/create_message` request when tools were provided. -* This version supports array content for tool use flows. -* -* @deprecated Deprecated as of protocol version 2026-07-28 (SEP-2577); remains -* in the specification for at least twelve months. Migrate to calling LLM -* provider APIs directly. -*/ -const CreateMessageResultWithToolsSchema = ResultSchema.extend({ - model: schemas_string(), - stopReason: schemas_optional(schemas_enum([ - "endTurn", - "stopSequence", - "maxTokens", - "toolUse" - ]).or(schemas_string())), - role: RoleSchema, - content: schemas_union([SamplingMessageContentBlockSchema, schemas_array(SamplingMessageContentBlockSchema)]) -}); -/** -* Primitive schema definition for boolean fields. -*/ -const BooleanSchemaSchema = schemas_object({ - type: literal("boolean"), - title: schemas_string().optional(), - description: schemas_string().optional(), - default: schemas_boolean().optional() -}); -/** -* Primitive schema definition for string fields. -*/ -const StringSchemaSchema = schemas_object({ - type: literal("string"), - title: schemas_string().optional(), - description: schemas_string().optional(), - minLength: schemas_number().optional(), - maxLength: schemas_number().optional(), - format: schemas_enum([ - "email", - "uri", - "date", - "date-time" - ]).optional(), - default: schemas_string().optional() -}); -/** -* Primitive schema definition for number fields. -*/ -const NumberSchemaSchema = schemas_object({ - type: schemas_enum(["number", "integer"]), - title: schemas_string().optional(), - description: schemas_string().optional(), - minimum: schemas_number().optional(), - maximum: schemas_number().optional(), - default: schemas_number().optional() -}); -/** -* Schema for single-selection enumeration without display titles for options. -*/ -const UntitledSingleSelectEnumSchemaSchema = schemas_object({ - type: literal("string"), - title: schemas_string().optional(), - description: schemas_string().optional(), - enum: schemas_array(schemas_string()), - default: schemas_string().optional() -}); -/** -* Schema for single-selection enumeration with display titles for each option. -*/ -const TitledSingleSelectEnumSchemaSchema = schemas_object({ - type: literal("string"), - title: schemas_string().optional(), - description: schemas_string().optional(), - oneOf: schemas_array(schemas_object({ - const: schemas_string(), - title: schemas_string() - })), - default: schemas_string().optional() -}); -/** -* Use {@linkcode TitledSingleSelectEnumSchema} instead. -* This interface will be removed in a future version. -*/ -const LegacyTitledEnumSchemaSchema = schemas_object({ - type: literal("string"), - title: schemas_string().optional(), - description: schemas_string().optional(), - enum: schemas_array(schemas_string()), - enumNames: schemas_array(schemas_string()).optional(), - default: schemas_string().optional() -}); -const SingleSelectEnumSchemaSchema = schemas_union([UntitledSingleSelectEnumSchemaSchema, TitledSingleSelectEnumSchemaSchema]); -/** -* Schema for multiple-selection enumeration without display titles for options. -*/ -const UntitledMultiSelectEnumSchemaSchema = schemas_object({ - type: literal("array"), - title: schemas_string().optional(), - description: schemas_string().optional(), - minItems: schemas_number().optional(), - maxItems: schemas_number().optional(), - items: schemas_object({ - type: literal("string"), - enum: schemas_array(schemas_string()) - }), - default: schemas_array(schemas_string()).optional() -}); -/** -* Schema for multiple-selection enumeration with display titles for each option. -*/ -const TitledMultiSelectEnumSchemaSchema = schemas_object({ - type: literal("array"), - title: schemas_string().optional(), - description: schemas_string().optional(), - minItems: schemas_number().optional(), - maxItems: schemas_number().optional(), - items: schemas_object({ anyOf: schemas_array(schemas_object({ - const: schemas_string(), - title: schemas_string() - })) }), - default: schemas_array(schemas_string()).optional() -}); -/** -* Combined schema for multiple-selection enumeration -*/ -const MultiSelectEnumSchemaSchema = schemas_union([UntitledMultiSelectEnumSchemaSchema, TitledMultiSelectEnumSchemaSchema]); -/** -* Primitive schema definition for enum fields. -*/ -const EnumSchemaSchema = schemas_union([ - LegacyTitledEnumSchemaSchema, - SingleSelectEnumSchemaSchema, - MultiSelectEnumSchemaSchema -]); -/** -* Union of all primitive schema definitions. -*/ -const PrimitiveSchemaDefinitionSchema = schemas_union([ - EnumSchemaSchema, - BooleanSchemaSchema, - StringSchemaSchema, - NumberSchemaSchema -]); -/** -* Parameters for an `elicitation/create` request for form-based elicitation. -*/ -const ElicitRequestFormParamsSchema = auth_CUe6YdwF_TaskAugmentedRequestParamsSchema.extend({ - mode: literal("form").optional(), - message: schemas_string(), - requestedSchema: schemas_object({ - type: literal("object"), - properties: schemas_record(schemas_string(), PrimitiveSchemaDefinitionSchema), - required: schemas_array(schemas_string()).optional() - }).catchall(unknown()) -}); -/** -* Parameters for an {@linkcode ElicitRequest | elicitation/create} request for URL-based elicitation. -*/ -const ElicitRequestURLParamsSchema = auth_CUe6YdwF_TaskAugmentedRequestParamsSchema.extend({ - mode: literal("url"), - message: schemas_string(), - elicitationId: schemas_string(), - url: schemas_string().url() -}); -/** -* The parameters for a request to elicit additional information from the user via the client. -*/ -const ElicitRequestParamsSchema = schemas_union([ElicitRequestFormParamsSchema, ElicitRequestURLParamsSchema]); -/** -* A request from the server to elicit user input via the client. -* The client should present the message and form fields to the user (form mode) -* or navigate to a URL (URL mode). -*/ -const ElicitRequestSchema = RequestSchema.extend({ - method: literal("elicitation/create"), - params: ElicitRequestParamsSchema -}); -/** -* Parameters for a {@linkcode ElicitationCompleteNotification | notifications/elicitation/complete} notification. -* -* @deprecated Removed from the spec by #2891 (2026-07-28). The client learns the outcome -* of an out-of-band interaction by retrying the original request; no server-initiated -* completion signal exists in the 2026-07-28 revision. Kept here for the 2025-era flow -* only. The 2026-07-28 wire codec excludes this notification. -* @category notifications/elicitation/complete -*/ -const ElicitationCompleteNotificationParamsSchema = NotificationsParamsSchema.extend({ elicitationId: schemas_string() }); -/** -* A notification from the server to the client, informing it of a completion of an out-of-band elicitation request. -* -* @deprecated Removed from the spec by #2891 (2026-07-28). The client learns the outcome -* of an out-of-band interaction by retrying the original request; no server-initiated -* completion signal exists in the 2026-07-28 revision. Kept here for the 2025-era flow -* only. The 2026-07-28 wire codec excludes this notification. -* @category notifications/elicitation/complete -*/ -const ElicitationCompleteNotificationSchema = NotificationSchema.extend({ - method: literal("notifications/elicitation/complete"), - params: ElicitationCompleteNotificationParamsSchema -}); -/** -* The client's response to an {@linkcode ElicitRequest | elicitation/create} request from the server. -*/ -const ElicitResultSchema = ResultSchema.extend({ - action: schemas_enum([ - "accept", - "decline", - "cancel" - ]), - content: preprocess((val) => val === null ? void 0 : val, schemas_record(schemas_string(), schemas_union([ - schemas_string(), - schemas_number(), - schemas_boolean(), - schemas_array(schemas_string()) - ])).optional()) -}); -/** -* A reference to a resource or resource template definition. -*/ -const ResourceTemplateReferenceSchema = schemas_object({ - type: literal("ref/resource"), - uri: schemas_string() -}); -/** -* Identifies a prompt. -*/ -const PromptReferenceSchema = schemas_object({ - type: literal("ref/prompt"), - name: schemas_string() -}); -/** -* Parameters for a {@linkcode CompleteRequest | completion/complete} request. -*/ -const CompleteRequestParamsSchema = BaseRequestParamsSchema.extend({ - ref: schemas_union([PromptReferenceSchema, ResourceTemplateReferenceSchema]), - argument: schemas_object({ - name: schemas_string(), - value: schemas_string() - }), - context: schemas_object({ arguments: schemas_record(schemas_string(), schemas_string()).optional() }).optional() -}); -/** -* A request from the client to the server, to ask for completion options. -*/ -const CompleteRequestSchema = RequestSchema.extend({ - method: literal("completion/complete"), - params: CompleteRequestParamsSchema -}); -/** -* The server's response to a {@linkcode CompleteRequest | completion/complete} request -*/ -const CompleteResultSchema = ResultSchema.extend({ completion: looseObject({ - values: schemas_array(schemas_string()).max(100), - total: schemas_optional(schemas_number().int()), - hasMore: schemas_optional(schemas_boolean()) -}) }); -/** -* Represents a root directory or file that the server can operate on. -* -* @deprecated Deprecated as of protocol version 2026-07-28 (SEP-2577); remains -* in the specification for at least twelve months. Migrate to passing paths via -* tool parameters, resource URIs, or configuration. -*/ -const RootSchema = schemas_object({ - uri: schemas_string().startsWith("file://"), - name: schemas_string().optional(), - _meta: schemas_record(schemas_string(), unknown()).optional() -}); -/** -* Sent from the server to request a list of root URIs from the client. -* -* @deprecated Deprecated as of protocol version 2026-07-28 (SEP-2577); remains -* in the specification for at least twelve months. Migrate to passing paths via -* tool parameters, resource URIs, or configuration. -*/ -const ListRootsRequestSchema = RequestSchema.extend({ - method: literal("roots/list"), - params: BaseRequestParamsSchema.optional() -}); -/** -* The client's response to a `roots/list` request from the server. -* -* @deprecated Deprecated as of protocol version 2026-07-28 (SEP-2577); remains -* in the specification for at least twelve months. Migrate to passing paths via -* tool parameters, resource URIs, or configuration. -*/ -const ListRootsResultSchema = ResultSchema.extend({ roots: schemas_array(RootSchema) }); -/** -* A notification from the client to the server, informing it that the list of roots has changed. -* -* @deprecated Deprecated as of protocol version 2026-07-28 (SEP-2577); remains -* in the specification for at least twelve months. Migrate to passing paths via -* tool parameters, resource URIs, or configuration. -*/ -const RootsListChangedNotificationSchema = NotificationSchema.extend({ - method: literal("notifications/roots/list_changed"), - params: NotificationsParamsSchema.optional() -}); -/** -* Task creation parameters, used to ask that the server create a task to represent a request. -* -* @deprecated 2025-11-25 wire vocabulary with no SDK runtime; kept importable for interoperability only. -*/ -const TaskCreationParamsSchema = looseObject({ - ttl: schemas_number().optional(), - pollInterval: schemas_number().optional() -}); -/** -* The status of a task. -* -* @deprecated 2025-11-25 wire vocabulary with no SDK runtime; kept importable for interoperability only. -*/ -const TaskStatusSchema = schemas_enum([ - "working", - "input_required", - "completed", - "failed", - "cancelled" -]); -/** -* A pollable state object associated with a request. -* -* @deprecated 2025-11-25 wire vocabulary with no SDK runtime; kept importable for interoperability only. -*/ -const TaskSchema = schemas_object({ - taskId: schemas_string(), - status: TaskStatusSchema, - ttl: schemas_union([schemas_number(), schemas_null()]), - createdAt: schemas_string(), - lastUpdatedAt: schemas_string(), - pollInterval: schemas_optional(schemas_number()), - statusMessage: schemas_optional(schemas_string()) -}); -/** -* Result returned when a task is created, containing the task data wrapped in a `task` field. -* -* @deprecated 2025-11-25 wire vocabulary with no SDK runtime; kept importable for interoperability only. -*/ -const CreateTaskResultSchema = ResultSchema.extend({ task: TaskSchema }); -/** -* Parameters for task status notification. -* -* @deprecated 2025-11-25 wire vocabulary with no SDK runtime; kept importable for interoperability only. -*/ -const TaskStatusNotificationParamsSchema = NotificationsParamsSchema.merge(TaskSchema); -/** -* A notification sent when a task's status changes. -* -* @deprecated 2025-11-25 wire vocabulary with no SDK runtime; kept importable for interoperability only. -*/ -const TaskStatusNotificationSchema = NotificationSchema.extend({ - method: literal("notifications/tasks/status"), - params: TaskStatusNotificationParamsSchema -}); -/** -* A request to get the state of a specific task. -* -* @deprecated 2025-11-25 wire vocabulary with no SDK runtime; kept importable for interoperability only. -*/ -const GetTaskRequestSchema = RequestSchema.extend({ - method: literal("tasks/get"), - params: BaseRequestParamsSchema.extend({ taskId: schemas_string() }) -}); -/** -* The response to a {@linkcode GetTaskRequest | tasks/get} request. -* -* @deprecated 2025-11-25 wire vocabulary with no SDK runtime; kept importable for interoperability only. -*/ -const GetTaskResultSchema = ResultSchema.merge(TaskSchema); -/** -* A request to get the result of a specific task. -* -* @deprecated 2025-11-25 wire vocabulary with no SDK runtime; kept importable for interoperability only. -*/ -const GetTaskPayloadRequestSchema = RequestSchema.extend({ - method: literal("tasks/result"), - params: BaseRequestParamsSchema.extend({ taskId: schemas_string() }) -}); -/** -* The response to a `tasks/result` request. -* The structure matches the result type of the original request. -* For example, a {@linkcode CallToolRequest | tools/call} task would return the `CallToolResult` structure. -* -* -* @deprecated 2025-11-25 wire vocabulary with no SDK runtime; kept importable for interoperability only. -*/ -const GetTaskPayloadResultSchema = ResultSchema.loose(); -/** -* A request to list tasks. -* -* @deprecated 2025-11-25 wire vocabulary with no SDK runtime; kept importable for interoperability only. -*/ -const ListTasksRequestSchema = PaginatedRequestSchema.extend({ method: literal("tasks/list") }); -/** -* The response to a {@linkcode ListTasksRequest | tasks/list} request. -* -* @deprecated 2025-11-25 wire vocabulary with no SDK runtime; kept importable for interoperability only. -*/ -const ListTasksResultSchema = PaginatedResultSchema.extend({ tasks: schemas_array(TaskSchema) }); -/** -* A request to cancel a specific task. -* -* @deprecated 2025-11-25 wire vocabulary with no SDK runtime; kept importable for interoperability only. -*/ -const CancelTaskRequestSchema = RequestSchema.extend({ - method: literal("tasks/cancel"), - params: BaseRequestParamsSchema.extend({ taskId: schemas_string() }) -}); -/** -* The response to a {@linkcode CancelTaskRequest | tasks/cancel} request. -* -* @deprecated 2025-11-25 wire vocabulary with no SDK runtime; kept importable for interoperability only. -*/ -const CancelTaskResultSchema = ResultSchema.merge(TaskSchema); -const ClientRequestSchema = schemas_union([ - PingRequestSchema, - auth_CUe6YdwF_InitializeRequestSchema, - DiscoverRequestSchema, - CompleteRequestSchema, - SetLevelRequestSchema, - GetPromptRequestSchema, - ListPromptsRequestSchema, - ListResourcesRequestSchema, - ListResourceTemplatesRequestSchema, - ReadResourceRequestSchema, - SubscribeRequestSchema, - UnsubscribeRequestSchema, - SubscriptionsListenRequestSchema, - CallToolRequestSchema, - ListToolsRequestSchema -]); -const ClientNotificationSchema = schemas_union([ - CancelledNotificationSchema, - ProgressNotificationSchema, - auth_CUe6YdwF_InitializedNotificationSchema, - RootsListChangedNotificationSchema -]); -const ClientResultSchema = schemas_union([ - EmptyResultSchema, - CreateMessageResultSchema, - CreateMessageResultWithToolsSchema, - ElicitResultSchema, - ListRootsResultSchema -]); -const ServerRequestSchema = schemas_union([ - PingRequestSchema, - CreateMessageRequestSchema, - ElicitRequestSchema, - ListRootsRequestSchema -]); -const ServerNotificationSchema = schemas_union([ - CancelledNotificationSchema, - ProgressNotificationSchema, - LoggingMessageNotificationSchema, - ResourceUpdatedNotificationSchema, - ResourceListChangedNotificationSchema, - ToolListChangedNotificationSchema, - PromptListChangedNotificationSchema, - SubscriptionsAcknowledgedNotificationSchema, - ElicitationCompleteNotificationSchema -]); -const ServerResultSchema = schemas_union([ - EmptyResultSchema, - InitializeResultSchema, - DiscoverResultSchema, - CompleteResultSchema, - GetPromptResultSchema, - ListPromptsResultSchema, - ListResourcesResultSchema, - ListResourceTemplatesResultSchema, - ReadResourceResultSchema, - auth_CUe6YdwF_CallToolResultSchema, - ListToolsResultSchema, - SubscriptionsListenResultSchema -]); - -//#endregion -//#region src/auth.ts -/** -* Reusable URL validation that disallows `javascript:` scheme -*/ -const SafeUrlSchema = schemas_url().superRefine((val, ctx) => { - if (!URL.canParse(val)) { - ctx.addIssue({ - code: ZodIssueCode.custom, - message: "URL must be parseable", - fatal: true - }); - return NEVER; - } -}).refine((url) => { - const u = new URL(url); - return u.protocol !== "javascript:" && u.protocol !== "data:" && u.protocol !== "vbscript:"; -}, { message: "URL cannot use javascript:, data:, or vbscript: scheme" }); -/** -* RFC 9728 OAuth Protected Resource Metadata -*/ -const OAuthProtectedResourceMetadataSchema = looseObject({ - resource: schemas_string().url(), - authorization_servers: schemas_array(SafeUrlSchema).optional(), - jwks_uri: schemas_string().url().optional(), - scopes_supported: schemas_array(schemas_string()).optional(), - bearer_methods_supported: schemas_array(schemas_string()).optional(), - resource_signing_alg_values_supported: schemas_array(schemas_string()).optional(), - resource_name: schemas_string().optional(), - resource_documentation: schemas_string().optional(), - resource_policy_uri: schemas_string().url().optional(), - resource_tos_uri: schemas_string().url().optional(), - tls_client_certificate_bound_access_tokens: schemas_boolean().optional(), - authorization_details_types_supported: schemas_array(schemas_string()).optional(), - dpop_signing_alg_values_supported: schemas_array(schemas_string()).optional(), - dpop_bound_access_tokens_required: schemas_boolean().optional() -}); -/** -* RFC 8414 OAuth 2.0 Authorization Server Metadata -*/ -const OAuthMetadataSchema = looseObject({ - issuer: schemas_string(), - authorization_endpoint: SafeUrlSchema, - token_endpoint: SafeUrlSchema, - registration_endpoint: SafeUrlSchema.optional(), - scopes_supported: schemas_array(schemas_string()).optional(), - response_types_supported: schemas_array(schemas_string()), - response_modes_supported: schemas_array(schemas_string()).optional(), - grant_types_supported: schemas_array(schemas_string()).optional(), - token_endpoint_auth_methods_supported: schemas_array(schemas_string()).optional(), - token_endpoint_auth_signing_alg_values_supported: schemas_array(schemas_string()).optional(), - service_documentation: SafeUrlSchema.optional(), - revocation_endpoint: SafeUrlSchema.optional(), - revocation_endpoint_auth_methods_supported: schemas_array(schemas_string()).optional(), - revocation_endpoint_auth_signing_alg_values_supported: schemas_array(schemas_string()).optional(), - introspection_endpoint: schemas_string().optional(), - introspection_endpoint_auth_methods_supported: schemas_array(schemas_string()).optional(), - introspection_endpoint_auth_signing_alg_values_supported: schemas_array(schemas_string()).optional(), - code_challenge_methods_supported: schemas_array(schemas_string()).optional(), - client_id_metadata_document_supported: schemas_boolean().optional(), - authorization_response_iss_parameter_supported: schemas_boolean().optional().catch(void 0) -}); -/** -* OpenID Connect Discovery 1.0 Provider Metadata -* -* @see https://openid.net/specs/openid-connect-discovery-1_0.html#ProviderMetadata -*/ -const OpenIdProviderMetadataSchema = looseObject({ - issuer: schemas_string(), - authorization_endpoint: SafeUrlSchema, - token_endpoint: SafeUrlSchema, - userinfo_endpoint: SafeUrlSchema.optional(), - jwks_uri: SafeUrlSchema, - registration_endpoint: SafeUrlSchema.optional(), - scopes_supported: schemas_array(schemas_string()).optional(), - response_types_supported: schemas_array(schemas_string()), - response_modes_supported: schemas_array(schemas_string()).optional(), - grant_types_supported: schemas_array(schemas_string()).optional(), - acr_values_supported: schemas_array(schemas_string()).optional(), - subject_types_supported: schemas_array(schemas_string()), - id_token_signing_alg_values_supported: schemas_array(schemas_string()), - id_token_encryption_alg_values_supported: schemas_array(schemas_string()).optional(), - id_token_encryption_enc_values_supported: schemas_array(schemas_string()).optional(), - userinfo_signing_alg_values_supported: schemas_array(schemas_string()).optional(), - userinfo_encryption_alg_values_supported: schemas_array(schemas_string()).optional(), - userinfo_encryption_enc_values_supported: schemas_array(schemas_string()).optional(), - request_object_signing_alg_values_supported: schemas_array(schemas_string()).optional(), - request_object_encryption_alg_values_supported: schemas_array(schemas_string()).optional(), - request_object_encryption_enc_values_supported: schemas_array(schemas_string()).optional(), - token_endpoint_auth_methods_supported: schemas_array(schemas_string()).optional(), - token_endpoint_auth_signing_alg_values_supported: schemas_array(schemas_string()).optional(), - display_values_supported: schemas_array(schemas_string()).optional(), - claim_types_supported: schemas_array(schemas_string()).optional(), - claims_supported: schemas_array(schemas_string()).optional(), - service_documentation: schemas_string().optional(), - claims_locales_supported: schemas_array(schemas_string()).optional(), - ui_locales_supported: schemas_array(schemas_string()).optional(), - claims_parameter_supported: schemas_boolean().optional(), - request_parameter_supported: schemas_boolean().optional(), - request_uri_parameter_supported: schemas_boolean().optional(), - require_request_uri_registration: schemas_boolean().optional(), - op_policy_uri: SafeUrlSchema.optional(), - op_tos_uri: SafeUrlSchema.optional(), - client_id_metadata_document_supported: schemas_boolean().optional(), - authorization_response_iss_parameter_supported: schemas_boolean().optional().catch(void 0) -}); -/** -* OpenID Connect Discovery metadata that may include OAuth 2.0 fields -* This schema represents the real-world scenario where OIDC providers -* return a mix of OpenID Connect and OAuth 2.0 metadata fields -*/ -const OpenIdProviderDiscoveryMetadataSchema = schemas_object({ - ...OpenIdProviderMetadataSchema.shape, - ...OAuthMetadataSchema.pick({ code_challenge_methods_supported: true }).shape -}); -/** -* OAuth 2.1 token response -*/ -const OAuthTokensSchema = schemas_object({ - access_token: schemas_string(), - id_token: schemas_string().optional(), - token_type: schemas_string(), - expires_in: coerce_number().optional(), - scope: schemas_string().optional(), - refresh_token: schemas_string().optional() -}).strip(); -/** -* RFC 8693 §2.2.1 Token Exchange response for ID-JAG tokens. -* -* `token_type` is intentionally optional: per RFC 8693 §2.2.1 it is informational when -* the issued token is not an access token, and per RFC 6749 §5.1 it is case-insensitive, -* so strict checking rejects conformant IdPs. -*/ -const IdJagTokenExchangeResponseSchema = schemas_object({ - issued_token_type: literal("urn:ietf:params:oauth:token-type:id-jag"), - access_token: schemas_string(), - token_type: schemas_string().optional(), - expires_in: schemas_number().optional(), - scope: schemas_string().optional() -}).strip(); -/** -* OAuth 2.1 error response -*/ -const OAuthErrorResponseSchema = schemas_object({ - error: schemas_string(), - error_description: schemas_string().optional(), - error_uri: schemas_string().optional() -}); -/** -* Optional version of {@linkcode SafeUrlSchema} that allows empty string for backward compatibility on `tos_uri` and `logo_uri` -*/ -const OptionalSafeUrlSchema = SafeUrlSchema.optional().or(literal("").transform(() => void 0)); -/** -* RFC 7591 OAuth 2.0 Dynamic Client Registration metadata -*/ -const OAuthClientMetadataSchema = schemas_object({ - redirect_uris: schemas_array(SafeUrlSchema), - token_endpoint_auth_method: schemas_string().optional(), - grant_types: schemas_array(schemas_string()).optional(), - response_types: schemas_array(schemas_string()).optional(), - application_type: schemas_string().optional(), - client_name: schemas_string().optional(), - client_uri: SafeUrlSchema.optional(), - logo_uri: OptionalSafeUrlSchema, - scope: schemas_string().optional(), - contacts: schemas_array(schemas_string()).optional(), - tos_uri: OptionalSafeUrlSchema, - policy_uri: schemas_string().optional(), - jwks_uri: SafeUrlSchema.optional(), - jwks: any().optional(), - software_id: schemas_string().optional(), - software_version: schemas_string().optional(), - software_statement: schemas_string().optional() -}).strip(); -/** -* RFC 7591 OAuth 2.0 Dynamic Client Registration client information -*/ -const OAuthClientInformationSchema = schemas_object({ - client_id: schemas_string(), - client_secret: schemas_string().optional(), - client_id_issued_at: schemas_number().optional(), - client_secret_expires_at: schemas_number().optional() -}).strip(); -/** -* RFC 7591 OAuth 2.0 Dynamic Client Registration full response (client information plus metadata) -*/ -const OAuthClientInformationFullSchema = OAuthClientMetadataSchema.merge(OAuthClientInformationSchema); -/** -* RFC 7591 OAuth 2.0 Dynamic Client Registration error response -*/ -const OAuthClientRegistrationErrorSchema = schemas_object({ - error: schemas_string(), - error_description: schemas_string().optional() -}).strip(); -/** -* RFC 7009 OAuth 2.0 Token Revocation request -*/ -const OAuthTokenRevocationRequestSchema = schemas_object({ - token: schemas_string(), - token_type_hint: schemas_string().optional() -}).strip(); - -//#endregion - -//# sourceMappingURL=auth-CUe6YdwF.mjs.map - - - - - - - - -//#region ../core-internal/src/errors/crossBundleBrand.ts -/** -* Cross-bundle `instanceof` support for the SDK error classes. -* -* `@modelcontextprotocol/client` and `@modelcontextprotocol/server` each bundle their -* own copy of `core-internal`, so an error constructed by one package fails a -* prototype-identity `instanceof` against the same class re-exported by the other — -* exactly the check a dual-role process (gateway, host, in-process test) writes. -* -* Instead of prototype identity, branded classes stamp every instance with the brand -* strings of its class chain under a registry symbol (`Symbol.for`, shared across -* bundles and realms), and resolve `instanceof` via `Symbol.hasInstance` against the -* brand set. Ordinary prototype-based `instanceof` is kept as a fallback so behavior -* is unchanged for anything unbranded. -* -* A class participates by defining an **own** `mcpBrand` static (via a `static {}` -* block, so nothing reaches the declaration files — a declared `protected static` -* field would make the constructor types nominally incompatible across the bundled -* copies) and (for hierarchy roots) installing {@linkcode brandedHasInstance} as -* `Symbol.hasInstance`. User-defined subclasses that do not declare their own brand -* keep plain prototype semantics — a foreign base-class instance never satisfies -* `instanceof UserSubclass`. -* -* Prior art — the same stamp-and-hook shape ships at scale elsewhere: Node core -* (stream.Writable since 2017, Console via a marker symbol, diagnostics_channel), -* undici's whole error hierarchy (vendored into Node as fetch), googleapis/gaxios -* (GaxiosError, Symbol.for marker), AWS SDK v3's ServiceException (which pairs a -* Symbol.hasInstance override with a static isInstance guard, as we do), and zod v4 -* (Symbol.hasInstance on every schema class for cross-version interop). -* -* Contract notes: -* - Participation criterion: **every error class exported from a public package that -* callers are documented to `instanceof` must be branded.** The per-package -* errorBrandConformance tests walk the export surfaces and fail naming any -* exported Error subclass that has not opted in. -* - Brands assert **identity, not shape**: brand strings are version-less, so an -* instance from one SDK version matches the class of another. Members added to a -* branded class in a later version may be absent on a matched instance — read -* fields defensively, and treat branded classes as additive-only. The escape -* hatch when a release must break a branded class's read contract: change that -* class's brand string in the same release, which cleanly severs cross-version -* matching for that class. The per-package brand pins make the rename -* deliberate: errorSurfacePins.test.ts owns the core-internal brands, and each -* package's errorBrandConformance test pins its package-local ones. -* - Cross-bundle matching requires **both** copies to be at or after the release -* that introduced branding; against an older copy, behavior degrades to plain -* prototype `instanceof` in both directions. -* - A consumer re-bundling the SDK with property mangling (`mangle.props`) would -* break the brand statics; default esbuild/webpack/terser settings do not. -*/ -/** Registry symbol — identical across bundled copies and realms. */ -const BRANDS = Symbol.for("mcp.sdk.errorBrands"); -/** -* Stamp `instance` with the brand of every class in `ctor`'s chain that declares an -* own `mcpBrand`. Call once from the hierarchy root's constructor with `new.target` — -* subclasses inherit the stamping without touching their constructors. -* -* Constructor-time only: never stamp arbitrary objects. A stamped non-instance would -* satisfy `instanceof` while lacking the prototype members (getters like `.status`) -* that callers reach for after the check. -*/ -function stampErrorBrands(instance, ctor) { - const brands = /* @__PURE__ */ new Set(); - let current = ctor; - while (typeof current === "function") { - const brand = current.mcpBrand; - if (Object.prototype.hasOwnProperty.call(current, "mcpBrand") && typeof brand === "string") brands.add(brand); - current = Object.getPrototypeOf(current); - } - if (brands.size === 0) return; - Object.defineProperty(instance, BRANDS, { - value: brands, - enumerable: false, - configurable: true - }); -} -/** -* `Symbol.hasInstance` implementation for branded hierarchy roots. Matches when the -* value carries the **own** brand of the class being tested against (cross-bundle -* path), falling back to ordinary prototype-based `instanceof` otherwise. -*/ -function brandedHasInstance(cls, value) { - try { - if (typeof value === "object" && value !== null && Object.prototype.hasOwnProperty.call(cls, "mcpBrand") && typeof cls.mcpBrand === "string" && Object.prototype.hasOwnProperty.call(value, BRANDS)) { - const carried = value[BRANDS]; - if (carried && typeof carried.has === "function" && carried.has(cls.mcpBrand)) return true; - } - } catch {} - return Function.prototype[Symbol.hasInstance].call(cls, value); -} - -//#endregion -//#region ../core-internal/src/auth/errors.ts -/** -* OAuth error codes as defined by {@link https://datatracker.ietf.org/doc/html/rfc6749#section-5.2 | RFC 6749} -* and extensions. -*/ -let src_CX2iR2pK_OAuthErrorCode = /* @__PURE__ */ (/* unused pure expression or super */ null && (function(OAuthErrorCode$1) { - /** - * The request is missing a required parameter, includes an invalid parameter value, - * includes a parameter more than once, or is otherwise malformed. - */ - OAuthErrorCode$1["InvalidRequest"] = "invalid_request"; - /** - * Client authentication failed (e.g., unknown client, no client authentication included, - * or unsupported authentication method). - */ - OAuthErrorCode$1["InvalidClient"] = "invalid_client"; - /** - * The provided authorization grant or refresh token is invalid, expired, revoked, - * does not match the redirection URI used in the authorization request, or was issued to another client. - */ - OAuthErrorCode$1["InvalidGrant"] = "invalid_grant"; - /** - * The authenticated client is not authorized to use this authorization grant type. - */ - OAuthErrorCode$1["UnauthorizedClient"] = "unauthorized_client"; - /** - * The authorization grant type is not supported by the authorization server. - */ - OAuthErrorCode$1["UnsupportedGrantType"] = "unsupported_grant_type"; - /** - * The requested scope is invalid, unknown, malformed, or exceeds the scope granted by the resource owner. - */ - OAuthErrorCode$1["InvalidScope"] = "invalid_scope"; - /** - * The resource owner or authorization server denied the request. - */ - OAuthErrorCode$1["AccessDenied"] = "access_denied"; - /** - * The authorization server encountered an unexpected condition that prevented it from fulfilling the request. - */ - OAuthErrorCode$1["ServerError"] = "server_error"; - /** - * The authorization server is currently unable to handle the request due to temporary overloading or maintenance. - */ - OAuthErrorCode$1["TemporarilyUnavailable"] = "temporarily_unavailable"; - /** - * The authorization server does not support obtaining an authorization code using this method. - */ - OAuthErrorCode$1["UnsupportedResponseType"] = "unsupported_response_type"; - /** - * The authorization server does not support the requested token type. - */ - OAuthErrorCode$1["UnsupportedTokenType"] = "unsupported_token_type"; - /** - * The access token provided is expired, revoked, malformed, or invalid for other reasons. - */ - OAuthErrorCode$1["InvalidToken"] = "invalid_token"; - /** - * The HTTP method used is not allowed for this endpoint. (Custom, non-standard error) - */ - OAuthErrorCode$1["MethodNotAllowed"] = "method_not_allowed"; - /** - * Rate limit exceeded. (Custom, non-standard error based on RFC 6585) - */ - OAuthErrorCode$1["TooManyRequests"] = "too_many_requests"; - /** - * The client metadata is invalid. (Custom error for dynamic client registration - RFC 7591) - */ - OAuthErrorCode$1["InvalidClientMetadata"] = "invalid_client_metadata"; - /** - * The value of one or more redirection URIs is invalid. (Dynamic client registration - RFC 7591 §3.2.2) - */ - OAuthErrorCode$1["InvalidRedirectUri"] = "invalid_redirect_uri"; - /** - * The request requires higher privileges than provided by the access token. - */ - OAuthErrorCode$1["InsufficientScope"] = "insufficient_scope"; - /** - * The requested resource is invalid, missing, unknown, or malformed. (Custom error for resource indicators - RFC 8707) - */ - OAuthErrorCode$1["InvalidTarget"] = "invalid_target"; - return OAuthErrorCode$1; -}({}))); -/** -* OAuth error class for all OAuth-related errors. -*/ -var src_CX2iR2pK_OAuthError = class OAuthError extends Error { - static { - Object.defineProperty(this, "mcpBrand", { value: "mcp.OAuthError" }); - } - static [Symbol.hasInstance](value) { - return brandedHasInstance(this, value); - } - /** - * Brand-based type guard: equivalent to `value instanceof this`, as an - * explicit static predicate (the axios/AWS-SDK `isInstance` style). Reads - * the caller's own brand via `this`, so every branded subclass gets a - * correctly-scoped guard by inheritance. Must be invoked on the class — - * in callback position write `v => SdkError.isInstance(v)`, not - * `.filter(SdkError.isInstance)` (detached calls throw rather than - * silently matching nothing). - */ - static isInstance(value) { - 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 brandedHasInstance(this, value); - } - constructor(code, message, errorUri) { - super(message); - this.code = code; - this.errorUri = errorUri; - this.name = "OAuthError"; - stampErrorBrands(this, new.target); - } - /** - * Converts the error to a standard OAuth error response object. - */ - toResponseObject() { - const response = { - error: this.code, - error_description: this.message - }; - if (this.errorUri) response.error_uri = this.errorUri; - return response; - } - /** - * Creates an {@linkcode OAuthError} from an OAuth error response. - */ - static fromResponse(response) { - return new OAuthError(response.error, response.error_description ?? response.error, response.error_uri); - } -}; - -//#endregion -//#region ../core-internal/src/errors/sdkErrors.ts -/** -* Error codes for SDK errors (local errors that never cross the wire). -* Unlike {@linkcode ProtocolErrorCode} which uses numeric JSON-RPC codes, `SdkErrorCode` uses -* descriptive string values for better developer experience. -* -* These errors are thrown locally by the SDK and are never serialized as -* JSON-RPC error responses. -*/ -let src_CX2iR2pK_SdkErrorCode = /* @__PURE__ */ function(SdkErrorCode$1) { - /** Transport is not connected */ - SdkErrorCode$1["NotConnected"] = "NOT_CONNECTED"; - /** Transport is already connected */ - SdkErrorCode$1["AlreadyConnected"] = "ALREADY_CONNECTED"; - /** Protocol is not initialized */ - SdkErrorCode$1["NotInitialized"] = "NOT_INITIALIZED"; - /** Required capability is not supported by the remote side */ - SdkErrorCode$1["CapabilityNotSupported"] = "CAPABILITY_NOT_SUPPORTED"; - /** Request timed out waiting for response */ - SdkErrorCode$1["RequestTimeout"] = "REQUEST_TIMEOUT"; - /** Connection was closed */ - SdkErrorCode$1["ConnectionClosed"] = "CONNECTION_CLOSED"; - /** Failed to send message */ - SdkErrorCode$1["SendFailed"] = "SEND_FAILED"; - /** Response result failed local schema validation */ - SdkErrorCode$1["InvalidResult"] = "INVALID_RESULT"; - /** - * The response carried a `resultType` discriminator (protocol revision - * 2026-07-28) naming a result kind this client cannot consume yet, e.g. - * `input_required`. The kind is carried in `data.resultType`. - */ - SdkErrorCode$1["UnsupportedResultType"] = "UNSUPPORTED_RESULT_TYPE"; - /** - * The multi-round-trip auto-fulfilment driver exhausted its round cap - * (`inputRequired.maxRounds`) without the server returning a complete - * result. `data.rounds` carries the cap that was hit and - * `data.lastResult` carries the last `input_required` payload received - * (`{ inputRequests, requestState? }`), so callers can inspect or resume - * the flow manually. - */ - SdkErrorCode$1["InputRequiredRoundsExceeded"] = "INPUT_REQUIRED_ROUNDS_EXCEEDED"; - /** - * The auto-aggregating no-`cursor` `listTools()` / `listPrompts()` / - * `listResources()` / `listResourceTemplates()` walk hit the - * `ClientOptions.listMaxPages` cap without the server's pagination - * converging. `data.method` carries the list verb and - * `data.listMaxPages` the cap that was hit; raise the cap or fall back to - * explicit per-page `{ cursor }` calls. - */ - SdkErrorCode$1["ListPaginationExceeded"] = "LIST_PAGINATION_EXCEEDED"; - /** - * The spec method being sent does not exist on the negotiated protocol - * version's wire era (e.g. `tasks/get` toward a 2026-07-28 peer, or - * `server/discover` toward a 2025-era peer). Raised locally, before - * anything reaches the transport. The method and era are carried in - * `data.method` / `data.era`. - */ - SdkErrorCode$1["MethodNotSupportedByProtocolVersion"] = "METHOD_NOT_SUPPORTED_BY_PROTOCOL_VERSION"; - /** - * Protocol-era negotiation at connect time failed without producing either a - * usable modern (2026-07-28+) era or a definitive legacy fallback signal — - * e.g. the negotiation mode forbids falling back (`pin`), the probe hit a - * network failure, or the server answered the probe with a 5xx (a typed - * connect error, never an era verdict). - * - * Negotiation-phase only: this code is never used once an era is - * established. Auth walls never carry it: a 401/403 rejecting the probe - * uses {@linkcode ClientHttpAuthentication} / {@linkcode ClientHttpForbidden} - * instead, so era-recovery flows keyed on this code (e.g. cached-verdict - * gateways) can never persist a verdict for an unauthorized exchange. - */ - SdkErrorCode$1["EraNegotiationFailed"] = "ERA_NEGOTIATION_FAILED"; - SdkErrorCode$1["ClientHttpNotImplemented"] = "CLIENT_HTTP_NOT_IMPLEMENTED"; - /** - * HTTP 401 authentication failure: the transport's re-auth retry still got - * 401 (`Server returned 401 after re-authentication`), or the version - * negotiation probe was rejected 401 with no `authProvider` configured - * (`Version negotiation failed: the server requires authorization (HTTP 401)`). - * Carried on an {@linkcode SdkHttpError} with `status: 401`. - */ - SdkErrorCode$1["ClientHttpAuthentication"] = "CLIENT_HTTP_AUTHENTICATION"; - /** - * HTTP 403 denial: the step-up re-authorization retry limit was reached, - * or the version negotiation probe was rejected 403 - * (`Version negotiation failed: the server denied access (HTTP 403)`). - * Carried on an {@linkcode SdkHttpError} with `status: 403`. - */ - SdkErrorCode$1["ClientHttpForbidden"] = "CLIENT_HTTP_FORBIDDEN"; - SdkErrorCode$1["ClientHttpUnexpectedContent"] = "CLIENT_HTTP_UNEXPECTED_CONTENT"; - SdkErrorCode$1["ClientHttpFailedToOpenStream"] = "CLIENT_HTTP_FAILED_TO_OPEN_STREAM"; - SdkErrorCode$1["ClientHttpFailedToTerminateSession"] = "CLIENT_HTTP_FAILED_TO_TERMINATE_SESSION"; - return SdkErrorCode$1; -}({}); -/** -* SDK errors are local errors that never cross the wire. -* They are distinct from {@linkcode ProtocolError} which represents JSON-RPC protocol errors -* that are serialized and sent as error responses. -* -* @example -* ```ts source="./sdkErrors.examples.ts#SdkError_basicUsage" -* try { -* // Throwing an SDK error -* throw new SdkError(SdkErrorCode.NotConnected, 'Transport is not connected'); -* } catch (error) { -* // Checking error type by code -* if (error instanceof SdkError && error.code === SdkErrorCode.RequestTimeout) { -* // Handle timeout -* } -* } -* ``` -*/ -var src_CX2iR2pK_SdkError = class extends Error { - static { - Object.defineProperty(this, "mcpBrand", { value: "mcp.SdkError" }); - } - static [Symbol.hasInstance](value) { - return brandedHasInstance(this, value); - } - /** - * Brand-based type guard: equivalent to `value instanceof this`, as an - * explicit static predicate (the axios/AWS-SDK `isInstance` style). Reads - * the caller's own brand via `this`, so every branded subclass gets a - * correctly-scoped guard by inheritance. Must be invoked on the class — - * in callback position write `v => SdkError.isInstance(v)`, not - * `.filter(SdkError.isInstance)` (detached calls throw rather than - * silently matching nothing). - */ - static isInstance(value) { - 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 brandedHasInstance(this, value); - } - constructor(code, message, data) { - super(message); - this.code = code; - this.data = data; - this.name = "SdkError"; - stampErrorBrands(this, new.target); - } -}; -/** -* An {@linkcode SdkError} subclass for HTTP transport failures. -* -* Thrown by the streamable HTTP transport when the server responds with a -* non-OK status code. Narrows {@linkcode SdkError.data | data} to -* {@linkcode SdkHttpErrorData} so consumers can inspect the HTTP status -* without unsafe casting. -* -* @example -* ```ts source="./sdkErrors.examples.ts#SdkHttpError_basicUsage" -* if (error instanceof SdkHttpError) { -* console.log(error.status); // number -* console.log(error.statusText); // string | undefined -* } -* ``` -*/ -var SdkHttpError = class extends src_CX2iR2pK_SdkError { - static { - Object.defineProperty(this, "mcpBrand", { value: "mcp.SdkHttpError" }); - } - constructor(code, message, data) { - super(code, message, data); - this.name = "SdkHttpError"; - } - get status() { - return this.data.status; - } - get statusText() { - return this.data.statusText; - } -}; - -//#endregion -//#region ../core-internal/src/shared/authUtils.ts -/** -* Utilities for handling OAuth resource URIs. -*/ -/** -* Converts a server URL to a resource URL by removing the fragment. -* {@link https://datatracker.ietf.org/doc/html/rfc8707#section-2 | RFC 8707 section 2} -* states that resource URIs "MUST NOT include a fragment component". -* Keeps everything else unchanged (scheme, domain, port, path, query). -*/ -function resourceUrlFromServerUrl(url) { - const resourceURL = typeof url === "string" ? new URL(url) : new URL(url.href); - resourceURL.hash = ""; - return resourceURL; -} -/** -* Checks if a requested resource URL matches a configured resource URL. -* A requested resource matches if it has the same scheme, domain, port, -* and its path starts with the configured resource's path. -* -* @param options - The options object -* @param options.requestedResource - The resource URL being requested -* @param options.configuredResource - The resource URL that has been configured -* @returns true if the requested resource matches the configured resource, false otherwise -*/ -function checkResourceAllowed({ requestedResource, configuredResource }) { - const requested = typeof requestedResource === "string" ? new URL(requestedResource) : new URL(requestedResource.href); - const configured = typeof configuredResource === "string" ? new URL(configuredResource) : new URL(configuredResource.href); - if (requested.origin !== configured.origin) return false; - if (requested.pathname.length < configured.pathname.length) return false; - const requestedPath = requested.pathname.endsWith("/") ? requested.pathname : requested.pathname + "/"; - const configuredPath = configured.pathname.endsWith("/") ? configured.pathname : configured.pathname + "/"; - return requestedPath.startsWith(configuredPath); -} - -//#endregion -//#region ../core-internal/src/shared/clientCapabilityRequirements.ts -/** -* Inbound request methods whose processing structurally requires a client -* capability, keyed by method, valued by the capabilities required. -* -* Currently empty: none of the request methods served on the 2026-07-28 -* registry unconditionally requires a client capability. Entries appear here -* when such methods exist — for example requests whose handling embeds -* elicitation or sampling input requests (the input-request engine), or -* opt-in subscription delivery. Handler-conditional requirements (a specific -* tool that needs sampling) are not expressible as a static method table and -* are enforced at the point the requirement arises instead. -*/ -const REQUIRED_CLIENT_CAPABILITIES_BY_METHOD = (/* unused pure expression or super */ null && ({})); -/** -* The client capabilities a request method structurally requires, or -* `undefined` when the method has no static requirement. -*/ -function src_CX2iR2pK_requiredClientCapabilitiesForRequest(method) { - return Object.hasOwn(REQUIRED_CLIENT_CAPABILITIES_BY_METHOD, method) ? REQUIRED_CLIENT_CAPABILITIES_BY_METHOD[method] : void 0; -} -function isPlainObject$7(value) { - return value !== null && typeof value === "object" && !Array.isArray(value); -} -/** -* Whether a required nested member counts as declared even though it is not -* spelled out: a bare `elicitation: {}` declaration (no mode sub-capability at -* all) is read as form support — the pre-mode (2025) meaning of a bare -* declaration — so an `elicitation.form` requirement treats it as satisfied. -* Declaring any mode explicitly (for example `elicitation: { url: {} }`) -* removes the implication. -*/ -function isImpliedCapabilityMember(capability, member, declaredValue) { - return capability === "elicitation" && member === "form" && declaredValue["form"] === void 0 && declaredValue["url"] === void 0; -} -/** -* The client capabilities an embedded multi-round-trip input request requires -* (call site 2 — the outbound input-request leg): a server MUST NOT send an -* `inputRequests` kind the request's declared client capabilities do not -* cover. Returns `undefined` for entries whose method is not one of the -* embedded input-request kinds (those are a server bug handled separately, -* not a capability question). -* -* The requirement is mode-aware where the capability is: URL-mode elicitation -* requires `elicitation.url`; form-mode (or mode-omitted) elicitation requires -* `elicitation.form` (modes are sub-capabilities, and a server MUST NOT send a -* mode the client did not declare); sampling with `tools`/`toolChoice` -* requires `sampling.tools`. A bare `elicitation: {}` declaration satisfies -* the form requirement — see {@linkcode missingClientCapabilities}. -*/ -function requiredClientCapabilitiesForInputRequest(entry) { - switch (entry.method) { - case "elicitation/create": - if (entry.params?.["mode"] === "url") return { elicitation: { url: {} } }; - return { elicitation: { form: {} } }; - case "sampling/createMessage": { - const params = entry.params; - if (params !== void 0 && (params["tools"] !== void 0 || params["toolChoice"] !== void 0)) return { sampling: { tools: {} } }; - return { sampling: {} }; - } - case "roots/list": return { roots: {} }; - default: return; - } -} -/** -* Computes the subset of `required` client capabilities the client did not -* declare. Returns `undefined` when every required capability is declared; -* otherwise returns an object in the `ClientCapabilities` shape containing -* exactly the missing capabilities (suitable for -* `data.requiredCapabilities` on the `-32021` error). -* -* A capability counts as declared when its top-level key is present on the -* declared capabilities; when the requirement names nested members (for -* example `elicitation: { url: {} }`), each named member must also be present -* under the declared capability. One lenient reading applies: a bare -* `elicitation: {}` declaration (no mode sub-capability at all) counts as -* declaring `elicitation.form` — the pre-mode (2025) meaning of a bare -* declaration. An absent or empty `declared` value means -* nothing is declared — every required capability is missing (the structural -* clean-refusal posture for sessions with no per-request capability view). -*/ -function src_CX2iR2pK_missingClientCapabilities(required, declared) { - const missing = {}; - for (const [capability, requirement] of Object.entries(required)) { - if (requirement === void 0) continue; - const declaredValue = declared === void 0 ? void 0 : declared[capability]; - if (declaredValue === void 0) { - missing[capability] = requirement; - continue; - } - if (isPlainObject$7(requirement) && isPlainObject$7(declaredValue)) { - const missingMembers = {}; - for (const [member, memberRequirement] of Object.entries(requirement)) if (memberRequirement !== void 0 && declaredValue[member] === void 0 && !isImpliedCapabilityMember(capability, member, declaredValue)) missingMembers[member] = memberRequirement; - if (Object.keys(missingMembers).length > 0) missing[capability] = missingMembers; - } - } - return Object.keys(missing).length > 0 ? missing : void 0; -} - -//#endregion -//#region ../core-internal/src/shared/protocolEras.ts -/** -* The first protocol revision of the modern (2026-07-28) era. Revision identifiers -* are ISO dates, so lexicographic comparison orders them chronologically. -*/ -const FIRST_MODERN_PROTOCOL_VERSION = "2026-07-28"; -/** -* Modern-era protocol revisions this SDK can negotiate via `server/discover`. -* Deliberately separate from {@linkcode SUPPORTED_PROTOCOL_VERSIONS} (the legacy -* `initialize` list), so adding a revision here can never leak a modern version -* string into a 2025-era handshake. Internal — not part of the public API surface. -*/ -const src_CX2iR2pK_SUPPORTED_MODERN_PROTOCOL_VERSIONS = (/* unused pure expression or super */ null && ([FIRST_MODERN_PROTOCOL_VERSION])); -/** Whether the given protocol revision belongs to the modern (2026-07-28+) era. */ -function isModernProtocolVersion(version) { - return version >= FIRST_MODERN_PROTOCOL_VERSION; -} -/** The legacy-era (pre-2026-07-28) subset of a supported-versions list, in the list's own preference order. */ -function legacyProtocolVersions(versions) { - return versions.filter((version) => !isModernProtocolVersion(version)); -} -/** The modern-era (2026-07-28+) subset of a supported-versions list, in the list's own preference order. */ -function modernProtocolVersions(versions) { - return versions.filter((version) => isModernProtocolVersion(version)); -} - -//#endregion -//#region ../core-internal/src/wire/textFallback.ts -/** -* SEP-2106 §4.3 TextContent auto-append, era-agnostic, called from BOTH -* codecs' {@link WireCodec.projectCallToolResult}: when `structuredContent` -* is a non-object value (array/primitive/`null`) and the handler authored no -* `type:'text'` block, append `{type:'text', text: JSON.stringify(value)}`. -* Object-shaped (or absent) `structuredContent` returns the same reference. -* -* Leaf module: imported by both era codec modules, so it must NOT import from -* `./codec.js` (which value-imports the rev codecs at top level — that would -* make a runtime cycle and a TDZ hazard for entries that evaluate a rev codec -* module first). -*/ -function appendTextFallbackForNonObject(result) { - const sc = result.structuredContent; - if (sc === void 0) return result; - if (!(typeof sc !== "object" || sc === null || Array.isArray(sc))) return result; - if (result.content?.some((c) => c.type === "text") ?? false) return result; - return { - ...result, - content: [...result.content ?? [], { - type: "text", - text: JSON.stringify(sc) - }] - }; -} - -//#endregion -//#region ../core-internal/src/wire/resultFamilies.ts -/** -* Result-family keys that must never default into a `{content: []}` tools/call -* success. Shared by the 2025 wire-seam schema and server normalization. -* Leaf module (like `textFallback.ts`): imported by registry/server paths, so -* it must NOT import from `./codec.js` — that would close a runtime cycle. -*/ -const TOOL_RESULT_FOREIGN_FAMILY_KEYS = [ - "task", - "inputRequests", - "requestState" -]; -/** -* Single owner of the v1-parity ruling: a plain-object tool result without `content` (and -* without foreign-family keys) gains `content: []`. Shared by the 2025 wire seam and server-side handler normalization. -*/ -function normalizeContentlessToolResult(value) { - if (value === null || typeof value !== "object" || Array.isArray(value) || value.content !== void 0 || TOOL_RESULT_FOREIGN_FAMILY_KEYS.some((key) => key in value)) return value; - return { - ...value, - content: [] - }; -} - -//#endregion -//#region ../core-internal/src/wire/rev2025-11-25/buildSchemas.ts -/** -* Complete frozen 2025-11-25 wire schemas. Self-contained — no imports from -* the public/neutral types/schemas.ts. The neutral layer is the public-API -* superset and is free to evolve (e.g., SEP-2106 widening); this file is the -* 2025 wire-parse contract (Q10-L2 byte-identity) and is BEHAVIOR-FROZEN. -* -* This is the era's complete frozen wire-parse contract — both the 2025-only -* delta (the deprecated task family, the era role unions) AND frozen copies of -* every era-shared shape (Tool, CallToolResult, Initialize*, ContentBlock, -* prompts/resources/completion/elicitation, …). The 2026-era codec -* (`wire/rev2026-07-28/`) is symmetrically self-contained in the same way. -* -* The 2025-only delta (the task message surface, restored types-only by #2248 -* for interop with task-capable 2025 peers) is parsed ONLY through this era's -* registry; the deprecated Task* schemas also live (marked `@deprecated`) in -* the neutral schema layer so the public types stay nameable without a -* cross-layer import — nameability is constant, runtime availability is -* version-keyed — but appear in no API signature. Q1 increment 2 — deletions -* are physical: the -* 2026-era REGISTRY has no Task* methods (its frozen building-block copies do -* carry the deprecated Task* sub-schemas by composition — soft contamination, -* tracked for anchor-exactness adjudication). -* -* The only cross-layer dependency is `import type { JSONObject, JSONValue }` -* from the neutral types barrel — pure structural type aliases with no parse -* behavior. No runtime schema is shared with the neutral layer. -*/ -function build$1() { - const JSONValueSchema$1 = lazy(() => schemas_union([ - schemas_string(), - schemas_number(), - schemas_boolean(), - schemas_null(), - schemas_record(schemas_string(), JSONValueSchema$1), - schemas_array(JSONValueSchema$1) - ])); - const JSONObjectSchema$1 = schemas_record(schemas_string(), JSONValueSchema$1); - /** - * A progress token, used to associate progress notifications with the original request. - */ - const ProgressTokenSchema$1 = schemas_union([schemas_string(), schemas_number().int()]); - /** - * An opaque token used to represent a cursor for pagination. - */ - const CursorSchema$1 = schemas_string(); - /** @deprecated 2025-11-25 wire vocabulary with no SDK runtime; kept importable for interoperability only. */ - const TaskMetadataSchema$1 = schemas_object({ ttl: schemas_number().optional() }); - /** - * Metadata for associating messages with a task. - * Include this in the `_meta` field under the key `io.modelcontextprotocol/related-task`. - * - * @deprecated 2025-11-25 wire vocabulary with no SDK runtime; kept importable for interoperability only. - */ - const RelatedTaskMetadataSchema$1 = schemas_object({ taskId: schemas_string() }); - const RequestMetaSchema$1 = looseObject({ - progressToken: ProgressTokenSchema$1.optional(), - "io.modelcontextprotocol/related-task": RelatedTaskMetadataSchema$1.optional() - }); - /** - * Common params for any request. - */ - const BaseRequestParamsSchema$1 = schemas_object({ _meta: RequestMetaSchema$1.optional() }); - /** - * Common params for any task-augmented request. - * - * @deprecated 2025-11-25 wire vocabulary with no SDK runtime; kept importable for interoperability only. - */ - const TaskAugmentedRequestParamsSchema$1 = BaseRequestParamsSchema$1.extend({ task: TaskMetadataSchema$1.optional() }); - const RequestSchema$1 = schemas_object({ - method: schemas_string(), - params: BaseRequestParamsSchema$1.loose().optional() - }); - const NotificationsParamsSchema$1 = schemas_object({ _meta: RequestMetaSchema$1.optional() }); - const NotificationSchema$1 = schemas_object({ - method: schemas_string(), - params: NotificationsParamsSchema$1.loose().optional() - }); - const ResultSchema$1 = looseObject({ _meta: RequestMetaSchema$1.optional() }); - /** - * A uniquely identifying ID for a request in JSON-RPC. - */ - const RequestIdSchema$1 = schemas_union([schemas_string(), schemas_number().int()]); - /** - * A response that indicates success but carries no data. - */ - const EmptyResultSchema$1 = ResultSchema$1.strict(); - const CancelledNotificationParamsSchema$1 = NotificationsParamsSchema$1.extend({ - requestId: RequestIdSchema$1.optional(), - reason: schemas_string().optional() - }); - /** - * This notification can be sent by either side to indicate that it is cancelling a previously-issued request. - * - * The request SHOULD still be in-flight, but due to communication latency, it is always possible that this notification MAY arrive after the request has already finished. - * - * This notification indicates that the result will be unused, so any associated processing SHOULD cease. - * - * A client MUST NOT attempt to cancel its {@linkcode InitializeRequest | initialize} request. - */ - const CancelledNotificationSchema$1 = NotificationSchema$1.extend({ - method: literal("notifications/cancelled"), - params: CancelledNotificationParamsSchema$1 - }); - /** - * Icon schema for use in {@link Tool | tools}, {@link Prompt | prompts}, {@link Resource | resources}, and {@link Implementation | implementations}. - */ - const IconSchema$1 = schemas_object({ - src: schemas_string(), - mimeType: schemas_string().optional(), - sizes: schemas_array(schemas_string()).optional(), - theme: schemas_enum(["light", "dark"]).optional() - }); - /** - * Base schema to add `icons` property. - * - */ - const IconsSchema$1 = schemas_object({ icons: schemas_array(IconSchema$1).optional() }); - /** - * Base metadata interface for common properties across {@link Resource | resources}, {@link Tool | tools}, {@link Prompt | prompts}, and {@link Implementation | implementations}. - */ - const BaseMetadataSchema$1 = schemas_object({ - name: schemas_string(), - title: schemas_string().optional() - }); - /** - * Describes the name and version of an MCP implementation. - */ - const ImplementationSchema$1 = BaseMetadataSchema$1.extend({ - ...BaseMetadataSchema$1.shape, - ...IconsSchema$1.shape, - version: schemas_string(), - websiteUrl: schemas_string().optional(), - description: schemas_string().optional() - }); - const FormElicitationCapabilitySchema = intersection(schemas_object({ applyDefaults: schemas_boolean().optional() }), JSONObjectSchema$1); - const ElicitationCapabilitySchema = preprocess((value) => { - if (value && typeof value === "object" && !Array.isArray(value) && Object.keys(value).length === 0) return { form: {} }; - return value; - }, intersection(schemas_object({ - form: FormElicitationCapabilitySchema.optional(), - url: JSONObjectSchema$1.optional() - }), JSONObjectSchema$1.optional())); - /** - * Task capabilities for clients, indicating which request types support task creation. - * - * @deprecated 2025-11-25 wire vocabulary with no SDK runtime; kept importable for interoperability only. - */ - const ClientTasksCapabilitySchema$1 = looseObject({ - list: JSONObjectSchema$1.optional(), - cancel: JSONObjectSchema$1.optional(), - requests: looseObject({ - sampling: looseObject({ createMessage: JSONObjectSchema$1.optional() }).optional(), - elicitation: looseObject({ create: JSONObjectSchema$1.optional() }).optional() - }).optional() - }); - /** - * Task capabilities for servers, indicating which request types support task creation. - * - * @deprecated 2025-11-25 wire vocabulary with no SDK runtime; kept importable for interoperability only. - */ - const ServerTasksCapabilitySchema$1 = looseObject({ - list: JSONObjectSchema$1.optional(), - cancel: JSONObjectSchema$1.optional(), - requests: looseObject({ tools: looseObject({ call: JSONObjectSchema$1.optional() }).optional() }).optional() - }); - /** - * Capabilities a client may support. Known capabilities are defined here, in this schema, but this is not a closed set: any client can define its own, additional capabilities. - */ - const ClientCapabilitiesSchema$1 = schemas_object({ - experimental: schemas_record(schemas_string(), JSONObjectSchema$1).optional(), - sampling: schemas_object({ - context: JSONObjectSchema$1.optional(), - tools: JSONObjectSchema$1.optional() - }).optional(), - elicitation: ElicitationCapabilitySchema.optional(), - roots: schemas_object({ listChanged: schemas_boolean().optional() }).optional(), - tasks: ClientTasksCapabilitySchema$1.optional(), - extensions: schemas_record(schemas_string(), JSONObjectSchema$1).optional() - }); - const InitializeRequestParamsSchema$1 = BaseRequestParamsSchema$1.extend({ - protocolVersion: schemas_string(), - capabilities: ClientCapabilitiesSchema$1, - clientInfo: ImplementationSchema$1 - }); - /** - * This request is sent from the client to the server when it first connects, asking it to begin initialization. - */ - const InitializeRequestSchema$1 = RequestSchema$1.extend({ - method: literal("initialize"), - params: InitializeRequestParamsSchema$1 - }); - /** - * Capabilities that a server may support. Known capabilities are defined here, in this schema, but this is not a closed set: any server can define its own, additional capabilities. - */ - const ServerCapabilitiesSchema$1 = schemas_object({ - experimental: schemas_record(schemas_string(), JSONObjectSchema$1).optional(), - logging: JSONObjectSchema$1.optional(), - completions: JSONObjectSchema$1.optional(), - prompts: schemas_object({ listChanged: schemas_boolean().optional() }).optional(), - resources: schemas_object({ - subscribe: schemas_boolean().optional(), - listChanged: schemas_boolean().optional() - }).optional(), - tools: schemas_object({ listChanged: schemas_boolean().optional() }).optional(), - tasks: ServerTasksCapabilitySchema$1.optional(), - extensions: schemas_record(schemas_string(), JSONObjectSchema$1).optional() - }); - /** - * After receiving an initialize request from the client, the server sends this response. - */ - const InitializeResultSchema$1 = ResultSchema$1.extend({ - protocolVersion: schemas_string(), - capabilities: ServerCapabilitiesSchema$1, - serverInfo: ImplementationSchema$1, - instructions: schemas_string().optional() - }); - /** - * This notification is sent from the client to the server after initialization has finished. - */ - const InitializedNotificationSchema$1 = NotificationSchema$1.extend({ - method: literal("notifications/initialized"), - params: NotificationsParamsSchema$1.optional() - }); - /** - * A ping, issued by either the server or the client, to check that the other party is still alive. The receiver must promptly respond, or else may be disconnected. - */ - const PingRequestSchema$1 = RequestSchema$1.extend({ - method: literal("ping"), - params: BaseRequestParamsSchema$1.optional() - }); - const ProgressSchema$1 = schemas_object({ - progress: schemas_number(), - total: schemas_optional(schemas_number()), - message: schemas_optional(schemas_string()) - }); - const ProgressNotificationParamsSchema$1 = schemas_object({ - ...NotificationsParamsSchema$1.shape, - ...ProgressSchema$1.shape, - progressToken: ProgressTokenSchema$1 - }); - /** - * An out-of-band notification used to inform the receiver of a progress update for a long-running request. - * - * @category notifications/progress - */ - const ProgressNotificationSchema$1 = NotificationSchema$1.extend({ - method: literal("notifications/progress"), - params: ProgressNotificationParamsSchema$1 - }); - const PaginatedRequestParamsSchema$1 = BaseRequestParamsSchema$1.extend({ cursor: CursorSchema$1.optional() }); - const PaginatedRequestSchema$1 = RequestSchema$1.extend({ params: PaginatedRequestParamsSchema$1.optional() }); - const PaginatedResultSchema$1 = ResultSchema$1.extend({ nextCursor: CursorSchema$1.optional() }); - /** - * The contents of a specific resource or sub-resource. - */ - const ResourceContentsSchema$1 = schemas_object({ - uri: schemas_string(), - mimeType: schemas_optional(schemas_string()), - _meta: schemas_record(schemas_string(), unknown()).optional() - }); - const TextResourceContentsSchema$1 = ResourceContentsSchema$1.extend({ text: schemas_string() }); - /** - * A Zod schema for validating Base64 strings that is more performant and - * robust for very large inputs than the default regex-based check. It avoids - * stack overflows by using the native `atob` function for validation. - */ - const Base64Schema = schemas_string().refine((val) => { - try { - atob(val); - return true; - } catch { - return false; - } - }, { message: "Invalid Base64 string" }); - const BlobResourceContentsSchema$1 = ResourceContentsSchema$1.extend({ blob: Base64Schema }); - /** - * The sender or recipient of messages and data in a conversation. - */ - const RoleSchema$1 = schemas_enum(["user", "assistant"]); - /** - * Optional annotations providing clients additional context about a resource. - */ - const AnnotationsSchema$1 = schemas_object({ - audience: schemas_array(RoleSchema$1).optional(), - priority: schemas_number().min(0).max(1).optional(), - lastModified: iso_datetime({ offset: true }).optional() - }); - /** - * A known resource that the server is capable of reading. - */ - const ResourceSchema$1 = schemas_object({ - ...BaseMetadataSchema$1.shape, - ...IconsSchema$1.shape, - uri: schemas_string(), - description: schemas_optional(schemas_string()), - mimeType: schemas_optional(schemas_string()), - size: schemas_optional(schemas_number()), - annotations: AnnotationsSchema$1.optional(), - _meta: schemas_optional(looseObject({})) - }); - /** - * A template description for resources available on the server. - */ - const ResourceTemplateSchema$1 = schemas_object({ - ...BaseMetadataSchema$1.shape, - ...IconsSchema$1.shape, - uriTemplate: schemas_string(), - description: schemas_optional(schemas_string()), - mimeType: schemas_optional(schemas_string()), - annotations: AnnotationsSchema$1.optional(), - _meta: schemas_optional(looseObject({})) - }); - /** - * Sent from the client to request a list of resources the server has. - */ - const ListResourcesRequestSchema$1 = PaginatedRequestSchema$1.extend({ method: literal("resources/list") }); - /** - * The server's response to a {@linkcode ListResourcesRequest | resources/list} request from the client. - */ - const ListResourcesResultSchema$1 = PaginatedResultSchema$1.extend({ resources: schemas_array(ResourceSchema$1) }); - /** - * Sent from the client to request a list of resource templates the server has. - */ - const ListResourceTemplatesRequestSchema$1 = PaginatedRequestSchema$1.extend({ method: literal("resources/templates/list") }); - /** - * The server's response to a {@linkcode ListResourceTemplatesRequest | resources/templates/list} request from the client. - */ - const ListResourceTemplatesResultSchema$1 = PaginatedResultSchema$1.extend({ resourceTemplates: schemas_array(ResourceTemplateSchema$1) }); - const ResourceRequestParamsSchema$1 = BaseRequestParamsSchema$1.extend({ uri: schemas_string() }); - /** - * Parameters for a {@linkcode ReadResourceRequest | resources/read} request. - */ - const ReadResourceRequestParamsSchema$1 = ResourceRequestParamsSchema$1; - /** - * Sent from the client to the server, to read a specific resource URI. - */ - const ReadResourceRequestSchema$1 = RequestSchema$1.extend({ - method: literal("resources/read"), - params: ReadResourceRequestParamsSchema$1 - }); - /** - * The server's response to a {@linkcode ReadResourceRequest | resources/read} request from the client. - */ - const ReadResourceResultSchema$1 = ResultSchema$1.extend({ contents: schemas_array(schemas_union([TextResourceContentsSchema$1, BlobResourceContentsSchema$1])) }); - /** - * An optional notification from the server to the client, informing it that the list of resources it can read from has changed. This may be issued by servers without any previous subscription from the client. - */ - const ResourceListChangedNotificationSchema$1 = NotificationSchema$1.extend({ - method: literal("notifications/resources/list_changed"), - params: NotificationsParamsSchema$1.optional() - }); - const SubscribeRequestParamsSchema$1 = ResourceRequestParamsSchema$1; - /** - * Sent from the client to request `resources/updated` notifications from the server whenever a particular resource changes. - */ - const SubscribeRequestSchema$1 = RequestSchema$1.extend({ - method: literal("resources/subscribe"), - params: SubscribeRequestParamsSchema$1 - }); - const UnsubscribeRequestParamsSchema$1 = ResourceRequestParamsSchema$1; - /** - * Sent from the client to request cancellation of {@linkcode ResourceUpdatedNotification | resources/updated} notifications from the server. This should follow a previous {@linkcode SubscribeRequest | resources/subscribe} request. - */ - const UnsubscribeRequestSchema$1 = RequestSchema$1.extend({ - method: literal("resources/unsubscribe"), - params: UnsubscribeRequestParamsSchema$1 - }); - /** - * Parameters for a {@linkcode ResourceUpdatedNotification | notifications/resources/updated} notification. - */ - const ResourceUpdatedNotificationParamsSchema$1 = NotificationsParamsSchema$1.extend({ uri: schemas_string() }); - /** - * A notification from the server to the client, informing it that a resource has changed and may need to be read again. This should only be sent if the client previously sent a {@linkcode SubscribeRequest | resources/subscribe} request. - */ - const ResourceUpdatedNotificationSchema$1 = NotificationSchema$1.extend({ - method: literal("notifications/resources/updated"), - params: ResourceUpdatedNotificationParamsSchema$1 - }); - /** - * Describes an argument that a prompt can accept. - */ - const PromptArgumentSchema$1 = schemas_object({ - name: schemas_string(), - description: schemas_optional(schemas_string()), - required: schemas_optional(schemas_boolean()) - }); - /** - * A prompt or prompt template that the server offers. - */ - const PromptSchema$1 = schemas_object({ - ...BaseMetadataSchema$1.shape, - ...IconsSchema$1.shape, - description: schemas_optional(schemas_string()), - arguments: schemas_optional(schemas_array(PromptArgumentSchema$1)), - _meta: schemas_optional(looseObject({})) - }); - /** - * Sent from the client to request a list of prompts and prompt templates the server has. - */ - const ListPromptsRequestSchema$1 = PaginatedRequestSchema$1.extend({ method: literal("prompts/list") }); - /** - * The server's response to a {@linkcode ListPromptsRequest | prompts/list} request from the client. - */ - const ListPromptsResultSchema$1 = PaginatedResultSchema$1.extend({ prompts: schemas_array(PromptSchema$1) }); - /** - * Parameters for a {@linkcode GetPromptRequest | prompts/get} request. - */ - const GetPromptRequestParamsSchema$1 = BaseRequestParamsSchema$1.extend({ - name: schemas_string(), - arguments: schemas_record(schemas_string(), schemas_string()).optional() - }); - /** - * Used by the client to get a prompt provided by the server. - */ - const GetPromptRequestSchema$1 = RequestSchema$1.extend({ - method: literal("prompts/get"), - params: GetPromptRequestParamsSchema$1 - }); - /** - * Text provided to or from an LLM. - */ - const TextContentSchema$1 = schemas_object({ - type: literal("text"), - text: schemas_string(), - annotations: AnnotationsSchema$1.optional(), - _meta: schemas_record(schemas_string(), unknown()).optional() - }); - /** - * An image provided to or from an LLM. - */ - const ImageContentSchema$1 = schemas_object({ - type: literal("image"), - data: Base64Schema, - mimeType: schemas_string(), - annotations: AnnotationsSchema$1.optional(), - _meta: schemas_record(schemas_string(), unknown()).optional() - }); - /** - * Audio content provided to or from an LLM. - */ - const AudioContentSchema$1 = schemas_object({ - type: literal("audio"), - data: Base64Schema, - mimeType: schemas_string(), - annotations: AnnotationsSchema$1.optional(), - _meta: schemas_record(schemas_string(), unknown()).optional() - }); - /** - * A tool call request from an assistant (LLM). - * Represents the assistant's request to use a tool. - * - * @deprecated Deprecated as of protocol version 2026-07-28 (SEP-2577); remains - * in the specification for at least twelve months. Migrate to calling LLM - * provider APIs directly. - */ - const ToolUseContentSchema$1 = schemas_object({ - type: literal("tool_use"), - name: schemas_string(), - id: schemas_string(), - input: schemas_record(schemas_string(), unknown()), - _meta: schemas_record(schemas_string(), unknown()).optional() - }); - /** - * The contents of a resource, embedded into a prompt or tool call result. - */ - const EmbeddedResourceSchema$1 = schemas_object({ - type: literal("resource"), - resource: schemas_union([TextResourceContentsSchema$1, BlobResourceContentsSchema$1]), - annotations: AnnotationsSchema$1.optional(), - _meta: schemas_record(schemas_string(), unknown()).optional() - }); - /** - * A resource that the server is capable of reading, included in a prompt or tool call result. - * - * Note: resource links returned by tools are not guaranteed to appear in the results of {@linkcode ListResourcesRequest | resources/list} requests. - */ - const ResourceLinkSchema$1 = ResourceSchema$1.extend({ type: literal("resource_link") }); - /** - * A content block that can be used in prompts and tool results. - */ - const ContentBlockSchema$1 = schemas_union([ - TextContentSchema$1, - ImageContentSchema$1, - AudioContentSchema$1, - ResourceLinkSchema$1, - EmbeddedResourceSchema$1 - ]); - /** - * Describes a message returned as part of a prompt. - */ - const PromptMessageSchema$1 = schemas_object({ - role: RoleSchema$1, - content: ContentBlockSchema$1 - }); - /** - * The server's response to a {@linkcode GetPromptRequest | prompts/get} request from the client. - */ - const GetPromptResultSchema$1 = ResultSchema$1.extend({ - description: schemas_string().optional(), - messages: schemas_array(PromptMessageSchema$1) - }); - /** - * An optional notification from the server to the client, informing it that the list of prompts it offers has changed. This may be issued by servers without any previous subscription from the client. - */ - const PromptListChangedNotificationSchema$1 = NotificationSchema$1.extend({ - method: literal("notifications/prompts/list_changed"), - params: NotificationsParamsSchema$1.optional() - }); - /** - * Additional properties describing a `Tool` to clients. - * - * NOTE: all properties in {@linkcode ToolAnnotations} are **hints**. - * They are not guaranteed to provide a faithful description of - * tool behavior (including descriptive properties like `title`). - * - * Clients should never make tool use decisions based on `ToolAnnotations` - * received from untrusted servers. - */ - const ToolAnnotationsSchema$1 = schemas_object({ - title: schemas_string().optional(), - readOnlyHint: schemas_boolean().optional(), - destructiveHint: schemas_boolean().optional(), - idempotentHint: schemas_boolean().optional(), - openWorldHint: schemas_boolean().optional() - }); - /** - * Execution-related properties for a tool. - */ - const ToolExecutionSchema$1 = schemas_object({ taskSupport: schemas_enum([ - "required", - "optional", - "forbidden" - ]).optional() }); - /** - * Definition for a tool the client can call. - */ - const ToolSchema$1 = schemas_object({ - ...BaseMetadataSchema$1.shape, - ...IconsSchema$1.shape, - description: schemas_string().optional(), - inputSchema: schemas_object({ - type: literal("object"), - properties: schemas_record(schemas_string(), JSONValueSchema$1).optional(), - required: schemas_array(schemas_string()).optional() - }).catchall(unknown()), - outputSchema: schemas_object({ - type: literal("object"), - properties: schemas_record(schemas_string(), JSONValueSchema$1).optional(), - required: schemas_array(schemas_string()).optional() - }).catchall(unknown()).optional(), - annotations: ToolAnnotationsSchema$1.optional(), - execution: ToolExecutionSchema$1.optional(), - _meta: schemas_record(schemas_string(), unknown()).optional() - }); - /** - * Sent from the client to request a list of tools the server has. - */ - const ListToolsRequestSchema$1 = PaginatedRequestSchema$1.extend({ method: literal("tools/list") }); - /** - * The server's response to a {@linkcode ListToolsRequest | tools/list} request from the client. - */ - const ListToolsResultSchema$1 = PaginatedResultSchema$1.extend({ tools: schemas_array(ToolSchema$1) }); - /** - * The server's response to a tool call. - */ - const CallToolResultSchema$1 = ResultSchema$1.extend({ - content: schemas_array(ContentBlockSchema$1), - structuredContent: schemas_record(schemas_string(), unknown()).optional(), - isError: schemas_boolean().optional() - }); - /** - * Parameters for a `tools/call` request. - */ - const CallToolRequestParamsSchema$1 = TaskAugmentedRequestParamsSchema$1.extend({ - name: schemas_string(), - arguments: schemas_record(schemas_string(), unknown()).optional() - }); - /** - * Used by the client to invoke a tool provided by the server. - */ - const CallToolRequestSchema$1 = RequestSchema$1.extend({ - method: literal("tools/call"), - params: CallToolRequestParamsSchema$1 - }); - /** - * An optional notification from the server to the client, informing it that the list of tools it offers has changed. This may be issued by servers without any previous subscription from the client. - */ - const ToolListChangedNotificationSchema$1 = NotificationSchema$1.extend({ - method: literal("notifications/tools/list_changed"), - params: NotificationsParamsSchema$1.optional() - }); - /** - * The severity of a log message. - * - * @deprecated Deprecated as of protocol version 2026-07-28 (SEP-2577); remains - * in the specification for at least twelve months. Migrate to stderr logging - * (STDIO servers) or OpenTelemetry. - */ - const LoggingLevelSchema$1 = schemas_enum([ - "debug", - "info", - "notice", - "warning", - "error", - "critical", - "alert", - "emergency" - ]); - /** - * Parameters for a `logging/setLevel` request. - * - * @deprecated Deprecated as of protocol version 2026-07-28 (SEP-2577); remains - * in the specification for at least twelve months. Migrate to stderr logging - * (STDIO servers) or OpenTelemetry. - */ - const SetLevelRequestParamsSchema$1 = BaseRequestParamsSchema$1.extend({ level: LoggingLevelSchema$1 }); - /** - * A request from the client to the server, to enable or adjust logging. - * - * @deprecated Deprecated as of protocol version 2026-07-28 (SEP-2577); remains - * in the specification for at least twelve months. Migrate to stderr logging - * (STDIO servers) or OpenTelemetry. - */ - const SetLevelRequestSchema$1 = RequestSchema$1.extend({ - method: literal("logging/setLevel"), - params: SetLevelRequestParamsSchema$1 - }); - /** - * Parameters for a `notifications/message` notification. - * - * @deprecated Deprecated as of protocol version 2026-07-28 (SEP-2577); remains - * in the specification for at least twelve months. Migrate to stderr logging - * (STDIO servers) or OpenTelemetry. - */ - const LoggingMessageNotificationParamsSchema$1 = NotificationsParamsSchema$1.extend({ - level: LoggingLevelSchema$1, - logger: schemas_string().optional(), - data: unknown() - }); - /** - * Notification of a log message passed from server to client. If no `logging/setLevel` request has been sent from the client, the server MAY decide which messages to send automatically. - * - * @deprecated Deprecated as of protocol version 2026-07-28 (SEP-2577); remains - * in the specification for at least twelve months. Migrate to stderr logging - * (STDIO servers) or OpenTelemetry. - */ - const LoggingMessageNotificationSchema$1 = NotificationSchema$1.extend({ - method: literal("notifications/message"), - params: LoggingMessageNotificationParamsSchema$1 - }); - /** - * Hints to use for model selection. - * - * @deprecated Deprecated as of protocol version 2026-07-28 (SEP-2577); remains - * in the specification for at least twelve months. Migrate to calling LLM - * provider APIs directly. - */ - const ModelHintSchema$1 = schemas_object({ name: schemas_string().optional() }); - /** - * The server's preferences for model selection, requested of the client during sampling. - * - * @deprecated Deprecated as of protocol version 2026-07-28 (SEP-2577); remains - * in the specification for at least twelve months. Migrate to calling LLM - * provider APIs directly. - */ - const ModelPreferencesSchema$1 = schemas_object({ - hints: schemas_array(ModelHintSchema$1).optional(), - costPriority: schemas_number().min(0).max(1).optional(), - speedPriority: schemas_number().min(0).max(1).optional(), - intelligencePriority: schemas_number().min(0).max(1).optional() - }); - /** - * Controls tool usage behavior in sampling requests. - * - * @deprecated Deprecated as of protocol version 2026-07-28 (SEP-2577); remains - * in the specification for at least twelve months. Migrate to calling LLM - * provider APIs directly. - */ - const ToolChoiceSchema$1 = schemas_object({ mode: schemas_enum([ - "auto", - "required", - "none" - ]).optional() }); - /** - * The result of a tool execution, provided by the user (server). - * Represents the outcome of invoking a tool requested via `ToolUseContent`. - * - * @deprecated Deprecated as of protocol version 2026-07-28 (SEP-2577); remains - * in the specification for at least twelve months. Migrate to calling LLM - * provider APIs directly. - */ - const ToolResultContentSchema$1 = schemas_object({ - type: literal("tool_result"), - toolUseId: schemas_string().describe("The unique identifier for the corresponding tool call."), - content: schemas_array(ContentBlockSchema$1), - structuredContent: schemas_object({}).loose().optional(), - isError: schemas_boolean().optional(), - _meta: schemas_record(schemas_string(), unknown()).optional() - }); - /** - * Basic content types for sampling responses (without tool use). - * Used for backwards-compatible {@linkcode CreateMessageResult} when tools are not used. - * - * @deprecated Deprecated as of protocol version 2026-07-28 (SEP-2577); remains - * in the specification for at least twelve months. Migrate to calling LLM - * provider APIs directly. - */ - const SamplingContentSchema$1 = discriminatedUnion("type", [ - TextContentSchema$1, - ImageContentSchema$1, - AudioContentSchema$1 - ]); - /** - * Content block types allowed in sampling messages. - * This includes text, image, audio, tool use requests, and tool results. - * - * @deprecated Deprecated as of protocol version 2026-07-28 (SEP-2577); remains - * in the specification for at least twelve months. Migrate to calling LLM - * provider APIs directly. - */ - const SamplingMessageContentBlockSchema$1 = discriminatedUnion("type", [ - TextContentSchema$1, - ImageContentSchema$1, - AudioContentSchema$1, - ToolUseContentSchema$1, - ToolResultContentSchema$1 - ]); - /** - * Describes a message issued to or received from an LLM API. - * - * @deprecated Deprecated as of protocol version 2026-07-28 (SEP-2577); remains - * in the specification for at least twelve months. Migrate to calling LLM - * provider APIs directly. - */ - const SamplingMessageSchema$1 = schemas_object({ - role: RoleSchema$1, - content: schemas_union([SamplingMessageContentBlockSchema$1, schemas_array(SamplingMessageContentBlockSchema$1)]), - _meta: schemas_record(schemas_string(), unknown()).optional() - }); - /** - * Parameters for a `sampling/createMessage` request. - * - * @deprecated Deprecated as of protocol version 2026-07-28 (SEP-2577); remains - * in the specification for at least twelve months. Migrate to calling LLM - * provider APIs directly. - */ - const CreateMessageRequestParamsSchema$1 = TaskAugmentedRequestParamsSchema$1.extend({ - messages: schemas_array(SamplingMessageSchema$1), - modelPreferences: ModelPreferencesSchema$1.optional(), - systemPrompt: schemas_string().optional(), - includeContext: schemas_enum([ - "none", - "thisServer", - "allServers" - ]).optional(), - temperature: schemas_number().optional(), - maxTokens: schemas_number().int(), - stopSequences: schemas_array(schemas_string()).optional(), - metadata: JSONObjectSchema$1.optional(), - tools: schemas_array(ToolSchema$1).optional(), - toolChoice: ToolChoiceSchema$1.optional() - }); - /** - * A request from the server to sample an LLM via the client. The client has full discretion over which model to select. The client should also inform the user before beginning sampling, to allow them to inspect the request (human in the loop) and decide whether to approve it. - * - * @deprecated Deprecated as of protocol version 2026-07-28 (SEP-2577); remains - * in the specification for at least twelve months. Migrate to calling LLM - * provider APIs directly. - */ - const CreateMessageRequestSchema$1 = RequestSchema$1.extend({ - method: literal("sampling/createMessage"), - params: CreateMessageRequestParamsSchema$1 - }); - /** - * The client's response to a `sampling/create_message` request from the server. - * This is the backwards-compatible version that returns single content (no arrays). - * Used when the request does not include tools. - * - * @deprecated Deprecated as of protocol version 2026-07-28 (SEP-2577); remains - * in the specification for at least twelve months. Migrate to calling LLM - * provider APIs directly. - */ - const CreateMessageResultSchema$1 = ResultSchema$1.extend({ - model: schemas_string(), - stopReason: schemas_optional(schemas_enum([ - "endTurn", - "stopSequence", - "maxTokens" - ]).or(schemas_string())), - role: RoleSchema$1, - content: SamplingContentSchema$1 - }); - /** - * The client's response to a `sampling/create_message` request when tools were provided. - * This version supports array content for tool use flows. - * - * @deprecated Deprecated as of protocol version 2026-07-28 (SEP-2577); remains - * in the specification for at least twelve months. Migrate to calling LLM - * provider APIs directly. - */ - const CreateMessageResultWithToolsSchema$1 = ResultSchema$1.extend({ - model: schemas_string(), - stopReason: schemas_optional(schemas_enum([ - "endTurn", - "stopSequence", - "maxTokens", - "toolUse" - ]).or(schemas_string())), - role: RoleSchema$1, - content: schemas_union([SamplingMessageContentBlockSchema$1, schemas_array(SamplingMessageContentBlockSchema$1)]) - }); - /** - * Primitive schema definition for boolean fields. - */ - const BooleanSchemaSchema$1 = schemas_object({ - type: literal("boolean"), - title: schemas_string().optional(), - description: schemas_string().optional(), - default: schemas_boolean().optional() - }); - /** - * Primitive schema definition for string fields. - */ - const StringSchemaSchema$1 = schemas_object({ - type: literal("string"), - title: schemas_string().optional(), - description: schemas_string().optional(), - minLength: schemas_number().optional(), - maxLength: schemas_number().optional(), - format: schemas_enum([ - "email", - "uri", - "date", - "date-time" - ]).optional(), - default: schemas_string().optional() - }); - /** - * Primitive schema definition for number fields. - */ - const NumberSchemaSchema$1 = schemas_object({ - type: schemas_enum(["number", "integer"]), - title: schemas_string().optional(), - description: schemas_string().optional(), - minimum: schemas_number().optional(), - maximum: schemas_number().optional(), - default: schemas_number().optional() - }); - /** - * Schema for single-selection enumeration without display titles for options. - */ - const UntitledSingleSelectEnumSchemaSchema$1 = schemas_object({ - type: literal("string"), - title: schemas_string().optional(), - description: schemas_string().optional(), - enum: schemas_array(schemas_string()), - default: schemas_string().optional() - }); - /** - * Schema for single-selection enumeration with display titles for each option. - */ - const TitledSingleSelectEnumSchemaSchema$1 = schemas_object({ - type: literal("string"), - title: schemas_string().optional(), - description: schemas_string().optional(), - oneOf: schemas_array(schemas_object({ - const: schemas_string(), - title: schemas_string() - })), - default: schemas_string().optional() - }); - /** - * Use {@linkcode TitledSingleSelectEnumSchema} instead. - * This interface will be removed in a future version. - */ - const LegacyTitledEnumSchemaSchema$1 = schemas_object({ - type: literal("string"), - title: schemas_string().optional(), - description: schemas_string().optional(), - enum: schemas_array(schemas_string()), - enumNames: schemas_array(schemas_string()).optional(), - default: schemas_string().optional() - }); - const SingleSelectEnumSchemaSchema$1 = schemas_union([UntitledSingleSelectEnumSchemaSchema$1, TitledSingleSelectEnumSchemaSchema$1]); - /** - * Schema for multiple-selection enumeration without display titles for options. - */ - const UntitledMultiSelectEnumSchemaSchema$1 = schemas_object({ - type: literal("array"), - title: schemas_string().optional(), - description: schemas_string().optional(), - minItems: schemas_number().optional(), - maxItems: schemas_number().optional(), - items: schemas_object({ - type: literal("string"), - enum: schemas_array(schemas_string()) - }), - default: schemas_array(schemas_string()).optional() - }); - /** - * Schema for multiple-selection enumeration with display titles for each option. - */ - const TitledMultiSelectEnumSchemaSchema$1 = schemas_object({ - type: literal("array"), - title: schemas_string().optional(), - description: schemas_string().optional(), - minItems: schemas_number().optional(), - maxItems: schemas_number().optional(), - items: schemas_object({ anyOf: schemas_array(schemas_object({ - const: schemas_string(), - title: schemas_string() - })) }), - default: schemas_array(schemas_string()).optional() - }); - /** - * Combined schema for multiple-selection enumeration - */ - const MultiSelectEnumSchemaSchema$1 = schemas_union([UntitledMultiSelectEnumSchemaSchema$1, TitledMultiSelectEnumSchemaSchema$1]); - /** - * Primitive schema definition for enum fields. - */ - const EnumSchemaSchema$1 = schemas_union([ - LegacyTitledEnumSchemaSchema$1, - SingleSelectEnumSchemaSchema$1, - MultiSelectEnumSchemaSchema$1 - ]); - /** - * Union of all primitive schema definitions. - */ - const PrimitiveSchemaDefinitionSchema$1 = schemas_union([ - EnumSchemaSchema$1, - BooleanSchemaSchema$1, - StringSchemaSchema$1, - NumberSchemaSchema$1 - ]); - /** - * Parameters for an `elicitation/create` request for form-based elicitation. - */ - const ElicitRequestFormParamsSchema$1 = TaskAugmentedRequestParamsSchema$1.extend({ - mode: literal("form").optional(), - message: schemas_string(), - requestedSchema: schemas_object({ - type: literal("object"), - properties: schemas_record(schemas_string(), PrimitiveSchemaDefinitionSchema$1), - required: schemas_array(schemas_string()).optional() - }).catchall(unknown()) - }); - /** - * Parameters for an {@linkcode ElicitRequest | elicitation/create} request for URL-based elicitation. - */ - const ElicitRequestURLParamsSchema$1 = TaskAugmentedRequestParamsSchema$1.extend({ - mode: literal("url"), - message: schemas_string(), - elicitationId: schemas_string(), - url: schemas_string().url() - }); - /** - * The parameters for a request to elicit additional information from the user via the client. - */ - const ElicitRequestParamsSchema$1 = schemas_union([ElicitRequestFormParamsSchema$1, ElicitRequestURLParamsSchema$1]); - /** - * A request from the server to elicit user input via the client. - * The client should present the message and form fields to the user (form mode) - * or navigate to a URL (URL mode). - */ - const ElicitRequestSchema$1 = RequestSchema$1.extend({ - method: literal("elicitation/create"), - params: ElicitRequestParamsSchema$1 - }); - /** - * Parameters for a {@linkcode ElicitationCompleteNotification | notifications/elicitation/complete} notification. - * - * @category notifications/elicitation/complete - */ - const ElicitationCompleteNotificationParamsSchema$1 = NotificationsParamsSchema$1.extend({ elicitationId: schemas_string() }); - /** - * A notification from the server to the client, informing it of a completion of an out-of-band elicitation request. - * - * @category notifications/elicitation/complete - */ - const ElicitationCompleteNotificationSchema$1 = NotificationSchema$1.extend({ - method: literal("notifications/elicitation/complete"), - params: ElicitationCompleteNotificationParamsSchema$1 - }); - /** - * The client's response to an {@linkcode ElicitRequest | elicitation/create} request from the server. - */ - const ElicitResultSchema$1 = ResultSchema$1.extend({ - action: schemas_enum([ - "accept", - "decline", - "cancel" - ]), - content: preprocess((val) => val === null ? void 0 : val, schemas_record(schemas_string(), schemas_union([ - schemas_string(), - schemas_number(), - schemas_boolean(), - schemas_array(schemas_string()) - ])).optional()) - }); - /** - * A reference to a resource or resource template definition. - */ - const ResourceTemplateReferenceSchema$1 = schemas_object({ - type: literal("ref/resource"), - uri: schemas_string() - }); - /** - * Identifies a prompt. - */ - const PromptReferenceSchema$1 = schemas_object({ - type: literal("ref/prompt"), - name: schemas_string() - }); - /** - * Parameters for a {@linkcode CompleteRequest | completion/complete} request. - */ - const CompleteRequestParamsSchema$1 = BaseRequestParamsSchema$1.extend({ - ref: schemas_union([PromptReferenceSchema$1, ResourceTemplateReferenceSchema$1]), - argument: schemas_object({ - name: schemas_string(), - value: schemas_string() - }), - context: schemas_object({ arguments: schemas_record(schemas_string(), schemas_string()).optional() }).optional() - }); - /** - * A request from the client to the server, to ask for completion options. - */ - const CompleteRequestSchema$1 = RequestSchema$1.extend({ - method: literal("completion/complete"), - params: CompleteRequestParamsSchema$1 - }); - /** - * The server's response to a {@linkcode CompleteRequest | completion/complete} request - */ - const CompleteResultSchema$1 = ResultSchema$1.extend({ completion: looseObject({ - values: schemas_array(schemas_string()).max(100), - total: schemas_optional(schemas_number().int()), - hasMore: schemas_optional(schemas_boolean()) - }) }); - /** - * Represents a root directory or file that the server can operate on. - * - * @deprecated Deprecated as of protocol version 2026-07-28 (SEP-2577); remains - * in the specification for at least twelve months. Migrate to passing paths via - * tool parameters, resource URIs, or configuration. - */ - const RootSchema$1 = schemas_object({ - uri: schemas_string().startsWith("file://"), - name: schemas_string().optional(), - _meta: schemas_record(schemas_string(), unknown()).optional() - }); - /** - * Sent from the server to request a list of root URIs from the client. - * - * @deprecated Deprecated as of protocol version 2026-07-28 (SEP-2577); remains - * in the specification for at least twelve months. Migrate to passing paths via - * tool parameters, resource URIs, or configuration. - */ - const ListRootsRequestSchema$1 = RequestSchema$1.extend({ - method: literal("roots/list"), - params: BaseRequestParamsSchema$1.optional() - }); - /** - * The client's response to a `roots/list` request from the server. - * - * @deprecated Deprecated as of protocol version 2026-07-28 (SEP-2577); remains - * in the specification for at least twelve months. Migrate to passing paths via - * tool parameters, resource URIs, or configuration. - */ - const ListRootsResultSchema$1 = ResultSchema$1.extend({ roots: schemas_array(RootSchema$1) }); - /** - * A notification from the client to the server, informing it that the list of roots has changed. - * - * @deprecated Deprecated as of protocol version 2026-07-28 (SEP-2577); remains - * in the specification for at least twelve months. Migrate to passing paths via - * tool parameters, resource URIs, or configuration. - */ - const RootsListChangedNotificationSchema$1 = NotificationSchema$1.extend({ - method: literal("notifications/roots/list_changed"), - params: NotificationsParamsSchema$1.optional() - }); - /** - * Task creation parameters, used to ask that the server create a task to represent a request. - * - * @deprecated 2025-11-25 wire vocabulary with no SDK runtime; kept importable for interoperability only. - */ - const TaskCreationParamsSchema$1 = looseObject({ - ttl: schemas_number().optional(), - pollInterval: schemas_number().optional() - }); - /** - * The status of a task. - * - * @deprecated 2025-11-25 wire vocabulary with no SDK runtime; kept importable for interoperability only. - */ - const TaskStatusSchema$1 = schemas_enum([ - "working", - "input_required", - "completed", - "failed", - "cancelled" - ]); - /** - * A pollable state object associated with a request. - * - * @deprecated 2025-11-25 wire vocabulary with no SDK runtime; kept importable for interoperability only. - */ - const TaskSchema$1 = schemas_object({ - taskId: schemas_string(), - status: TaskStatusSchema$1, - ttl: schemas_union([schemas_number(), schemas_null()]), - createdAt: schemas_string(), - lastUpdatedAt: schemas_string(), - pollInterval: schemas_optional(schemas_number()), - statusMessage: schemas_optional(schemas_string()) - }); - /** - * Result returned when a task is created, containing the task data wrapped in a `task` field. - * - * @deprecated 2025-11-25 wire vocabulary with no SDK runtime; kept importable for interoperability only. - */ - const CreateTaskResultSchema$1 = ResultSchema$1.extend({ task: TaskSchema$1 }); - /** - * Parameters for task status notification. - * - * @deprecated 2025-11-25 wire vocabulary with no SDK runtime; kept importable for interoperability only. - */ - const TaskStatusNotificationParamsSchema$1 = NotificationsParamsSchema$1.merge(TaskSchema$1); - /** - * A notification sent when a task's status changes. - * - * @deprecated 2025-11-25 wire vocabulary with no SDK runtime; kept importable for interoperability only. - */ - const TaskStatusNotificationSchema$1 = NotificationSchema$1.extend({ - method: literal("notifications/tasks/status"), - params: TaskStatusNotificationParamsSchema$1 - }); - /** - * A request to get the state of a specific task. - * - * @deprecated 2025-11-25 wire vocabulary with no SDK runtime; kept importable for interoperability only. - */ - const GetTaskRequestSchema$1 = RequestSchema$1.extend({ - method: literal("tasks/get"), - params: BaseRequestParamsSchema$1.extend({ taskId: schemas_string() }) - }); - /** - * The response to a {@linkcode GetTaskRequest | tasks/get} request. - * - * @deprecated 2025-11-25 wire vocabulary with no SDK runtime; kept importable for interoperability only. - */ - const GetTaskResultSchema$1 = ResultSchema$1.merge(TaskSchema$1); - /** - * A request to get the result of a specific task. - * - * @deprecated 2025-11-25 wire vocabulary with no SDK runtime; kept importable for interoperability only. - */ - const GetTaskPayloadRequestSchema$1 = RequestSchema$1.extend({ - method: literal("tasks/result"), - params: BaseRequestParamsSchema$1.extend({ taskId: schemas_string() }) - }); - /** - * The response to a `tasks/result` request. - * The structure matches the result type of the original request. - * For example, a {@linkcode CallToolRequest | tools/call} task would return the `CallToolResult` structure. - * - * - * @deprecated 2025-11-25 wire vocabulary with no SDK runtime; kept importable for interoperability only. - */ - const GetTaskPayloadResultSchema$1 = ResultSchema$1.loose(); - /** - * A request to list tasks. - * - * @deprecated 2025-11-25 wire vocabulary with no SDK runtime; kept importable for interoperability only. - */ - const ListTasksRequestSchema$1 = PaginatedRequestSchema$1.extend({ method: literal("tasks/list") }); - /** - * The response to a {@linkcode ListTasksRequest | tasks/list} request. - * - * @deprecated 2025-11-25 wire vocabulary with no SDK runtime; kept importable for interoperability only. - */ - const ListTasksResultSchema$1 = PaginatedResultSchema$1.extend({ tasks: schemas_array(TaskSchema$1) }); - /** - * A request to cancel a specific task. - * - * @deprecated 2025-11-25 wire vocabulary with no SDK runtime; kept importable for interoperability only. - */ - const CancelTaskRequestSchema$1 = RequestSchema$1.extend({ - method: literal("tasks/cancel"), - params: BaseRequestParamsSchema$1.extend({ taskId: schemas_string() }) - }); - return { - JSONValueSchema: JSONValueSchema$1, - JSONObjectSchema: JSONObjectSchema$1, - ProgressTokenSchema: ProgressTokenSchema$1, - CursorSchema: CursorSchema$1, - TaskMetadataSchema: TaskMetadataSchema$1, - RelatedTaskMetadataSchema: RelatedTaskMetadataSchema$1, - RequestMetaSchema: RequestMetaSchema$1, - BaseRequestParamsSchema: BaseRequestParamsSchema$1, - TaskAugmentedRequestParamsSchema: TaskAugmentedRequestParamsSchema$1, - RequestSchema: RequestSchema$1, - NotificationsParamsSchema: NotificationsParamsSchema$1, - NotificationSchema: NotificationSchema$1, - ResultSchema: ResultSchema$1, - RequestIdSchema: RequestIdSchema$1, - EmptyResultSchema: EmptyResultSchema$1, - CancelledNotificationParamsSchema: CancelledNotificationParamsSchema$1, - CancelledNotificationSchema: CancelledNotificationSchema$1, - IconSchema: IconSchema$1, - IconsSchema: IconsSchema$1, - BaseMetadataSchema: BaseMetadataSchema$1, - ImplementationSchema: ImplementationSchema$1, - ClientTasksCapabilitySchema: ClientTasksCapabilitySchema$1, - ServerTasksCapabilitySchema: ServerTasksCapabilitySchema$1, - ClientCapabilitiesSchema: ClientCapabilitiesSchema$1, - InitializeRequestParamsSchema: InitializeRequestParamsSchema$1, - InitializeRequestSchema: InitializeRequestSchema$1, - ServerCapabilitiesSchema: ServerCapabilitiesSchema$1, - InitializeResultSchema: InitializeResultSchema$1, - InitializedNotificationSchema: InitializedNotificationSchema$1, - PingRequestSchema: PingRequestSchema$1, - ProgressSchema: ProgressSchema$1, - ProgressNotificationParamsSchema: ProgressNotificationParamsSchema$1, - ProgressNotificationSchema: ProgressNotificationSchema$1, - PaginatedRequestParamsSchema: PaginatedRequestParamsSchema$1, - PaginatedRequestSchema: PaginatedRequestSchema$1, - PaginatedResultSchema: PaginatedResultSchema$1, - ResourceContentsSchema: ResourceContentsSchema$1, - TextResourceContentsSchema: TextResourceContentsSchema$1, - BlobResourceContentsSchema: BlobResourceContentsSchema$1, - RoleSchema: RoleSchema$1, - AnnotationsSchema: AnnotationsSchema$1, - ResourceSchema: ResourceSchema$1, - ResourceTemplateSchema: ResourceTemplateSchema$1, - ListResourcesRequestSchema: ListResourcesRequestSchema$1, - ListResourcesResultSchema: ListResourcesResultSchema$1, - ListResourceTemplatesRequestSchema: ListResourceTemplatesRequestSchema$1, - ListResourceTemplatesResultSchema: ListResourceTemplatesResultSchema$1, - ResourceRequestParamsSchema: ResourceRequestParamsSchema$1, - ReadResourceRequestParamsSchema: ReadResourceRequestParamsSchema$1, - ReadResourceRequestSchema: ReadResourceRequestSchema$1, - ReadResourceResultSchema: ReadResourceResultSchema$1, - ResourceListChangedNotificationSchema: ResourceListChangedNotificationSchema$1, - SubscribeRequestParamsSchema: SubscribeRequestParamsSchema$1, - SubscribeRequestSchema: SubscribeRequestSchema$1, - UnsubscribeRequestParamsSchema: UnsubscribeRequestParamsSchema$1, - UnsubscribeRequestSchema: UnsubscribeRequestSchema$1, - ResourceUpdatedNotificationParamsSchema: ResourceUpdatedNotificationParamsSchema$1, - ResourceUpdatedNotificationSchema: ResourceUpdatedNotificationSchema$1, - PromptArgumentSchema: PromptArgumentSchema$1, - PromptSchema: PromptSchema$1, - ListPromptsRequestSchema: ListPromptsRequestSchema$1, - ListPromptsResultSchema: ListPromptsResultSchema$1, - GetPromptRequestParamsSchema: GetPromptRequestParamsSchema$1, - GetPromptRequestSchema: GetPromptRequestSchema$1, - TextContentSchema: TextContentSchema$1, - ImageContentSchema: ImageContentSchema$1, - AudioContentSchema: AudioContentSchema$1, - ToolUseContentSchema: ToolUseContentSchema$1, - EmbeddedResourceSchema: EmbeddedResourceSchema$1, - ResourceLinkSchema: ResourceLinkSchema$1, - ContentBlockSchema: ContentBlockSchema$1, - PromptMessageSchema: PromptMessageSchema$1, - GetPromptResultSchema: GetPromptResultSchema$1, - PromptListChangedNotificationSchema: PromptListChangedNotificationSchema$1, - ToolAnnotationsSchema: ToolAnnotationsSchema$1, - ToolExecutionSchema: ToolExecutionSchema$1, - ToolSchema: ToolSchema$1, - ListToolsRequestSchema: ListToolsRequestSchema$1, - ListToolsResultSchema: ListToolsResultSchema$1, - CallToolResultSchema: CallToolResultSchema$1, - CallToolRequestParamsSchema: CallToolRequestParamsSchema$1, - CallToolRequestSchema: CallToolRequestSchema$1, - ToolListChangedNotificationSchema: ToolListChangedNotificationSchema$1, - LoggingLevelSchema: LoggingLevelSchema$1, - SetLevelRequestParamsSchema: SetLevelRequestParamsSchema$1, - SetLevelRequestSchema: SetLevelRequestSchema$1, - LoggingMessageNotificationParamsSchema: LoggingMessageNotificationParamsSchema$1, - LoggingMessageNotificationSchema: LoggingMessageNotificationSchema$1, - ModelHintSchema: ModelHintSchema$1, - ModelPreferencesSchema: ModelPreferencesSchema$1, - ToolChoiceSchema: ToolChoiceSchema$1, - ToolResultContentSchema: ToolResultContentSchema$1, - SamplingContentSchema: SamplingContentSchema$1, - SamplingMessageContentBlockSchema: SamplingMessageContentBlockSchema$1, - SamplingMessageSchema: SamplingMessageSchema$1, - CreateMessageRequestParamsSchema: CreateMessageRequestParamsSchema$1, - CreateMessageRequestSchema: CreateMessageRequestSchema$1, - CreateMessageResultSchema: CreateMessageResultSchema$1, - CreateMessageResultWithToolsSchema: CreateMessageResultWithToolsSchema$1, - BooleanSchemaSchema: BooleanSchemaSchema$1, - StringSchemaSchema: StringSchemaSchema$1, - NumberSchemaSchema: NumberSchemaSchema$1, - UntitledSingleSelectEnumSchemaSchema: UntitledSingleSelectEnumSchemaSchema$1, - TitledSingleSelectEnumSchemaSchema: TitledSingleSelectEnumSchemaSchema$1, - LegacyTitledEnumSchemaSchema: LegacyTitledEnumSchemaSchema$1, - SingleSelectEnumSchemaSchema: SingleSelectEnumSchemaSchema$1, - UntitledMultiSelectEnumSchemaSchema: UntitledMultiSelectEnumSchemaSchema$1, - TitledMultiSelectEnumSchemaSchema: TitledMultiSelectEnumSchemaSchema$1, - MultiSelectEnumSchemaSchema: MultiSelectEnumSchemaSchema$1, - EnumSchemaSchema: EnumSchemaSchema$1, - PrimitiveSchemaDefinitionSchema: PrimitiveSchemaDefinitionSchema$1, - ElicitRequestFormParamsSchema: ElicitRequestFormParamsSchema$1, - ElicitRequestURLParamsSchema: ElicitRequestURLParamsSchema$1, - ElicitRequestParamsSchema: ElicitRequestParamsSchema$1, - ElicitRequestSchema: ElicitRequestSchema$1, - ElicitationCompleteNotificationParamsSchema: ElicitationCompleteNotificationParamsSchema$1, - ElicitationCompleteNotificationSchema: ElicitationCompleteNotificationSchema$1, - ElicitResultSchema: ElicitResultSchema$1, - ResourceTemplateReferenceSchema: ResourceTemplateReferenceSchema$1, - PromptReferenceSchema: PromptReferenceSchema$1, - CompleteRequestParamsSchema: CompleteRequestParamsSchema$1, - CompleteRequestSchema: CompleteRequestSchema$1, - CompleteResultSchema: CompleteResultSchema$1, - RootSchema: RootSchema$1, - ListRootsRequestSchema: ListRootsRequestSchema$1, - ListRootsResultSchema: ListRootsResultSchema$1, - RootsListChangedNotificationSchema: RootsListChangedNotificationSchema$1, - TaskCreationParamsSchema: TaskCreationParamsSchema$1, - TaskStatusSchema: TaskStatusSchema$1, - TaskSchema: TaskSchema$1, - CreateTaskResultSchema: CreateTaskResultSchema$1, - TaskStatusNotificationParamsSchema: TaskStatusNotificationParamsSchema$1, - TaskStatusNotificationSchema: TaskStatusNotificationSchema$1, - GetTaskRequestSchema: GetTaskRequestSchema$1, - GetTaskResultSchema: GetTaskResultSchema$1, - GetTaskPayloadRequestSchema: GetTaskPayloadRequestSchema$1, - GetTaskPayloadResultSchema: GetTaskPayloadResultSchema$1, - ListTasksRequestSchema: ListTasksRequestSchema$1, - ListTasksResultSchema: ListTasksResultSchema$1, - CancelTaskRequestSchema: CancelTaskRequestSchema$1, - CancelTaskResultSchema: ResultSchema$1.merge(TaskSchema$1), - ClientRequestSchema: schemas_union([ - PingRequestSchema$1, - InitializeRequestSchema$1, - CompleteRequestSchema$1, - SetLevelRequestSchema$1, - GetPromptRequestSchema$1, - ListPromptsRequestSchema$1, - ListResourcesRequestSchema$1, - ListResourceTemplatesRequestSchema$1, - ReadResourceRequestSchema$1, - SubscribeRequestSchema$1, - UnsubscribeRequestSchema$1, - CallToolRequestSchema$1, - ListToolsRequestSchema$1, - GetTaskRequestSchema$1, - GetTaskPayloadRequestSchema$1, - ListTasksRequestSchema$1, - CancelTaskRequestSchema$1 - ]), - ClientNotificationSchema: schemas_union([ - CancelledNotificationSchema$1, - ProgressNotificationSchema$1, - InitializedNotificationSchema$1, - RootsListChangedNotificationSchema$1, - TaskStatusNotificationSchema$1 - ]), - ClientResultSchema: schemas_union([ - EmptyResultSchema$1, - CreateMessageResultSchema$1, - CreateMessageResultWithToolsSchema$1, - ElicitResultSchema$1, - ListRootsResultSchema$1, - GetTaskResultSchema$1, - ListTasksResultSchema$1, - CreateTaskResultSchema$1 - ]), - ServerRequestSchema: schemas_union([ - PingRequestSchema$1, - CreateMessageRequestSchema$1, - ElicitRequestSchema$1, - ListRootsRequestSchema$1, - GetTaskRequestSchema$1, - GetTaskPayloadRequestSchema$1, - ListTasksRequestSchema$1, - CancelTaskRequestSchema$1 - ]), - ServerNotificationSchema: schemas_union([ - CancelledNotificationSchema$1, - ProgressNotificationSchema$1, - LoggingMessageNotificationSchema$1, - ResourceUpdatedNotificationSchema$1, - ResourceListChangedNotificationSchema$1, - ToolListChangedNotificationSchema$1, - PromptListChangedNotificationSchema$1, - TaskStatusNotificationSchema$1, - ElicitationCompleteNotificationSchema$1 - ]), - ServerResultSchema: schemas_union([ - EmptyResultSchema$1, - InitializeResultSchema$1, - CompleteResultSchema$1, - GetPromptResultSchema$1, - ListPromptsResultSchema$1, - ListResourcesResultSchema$1, - ListResourceTemplatesResultSchema$1, - ReadResourceResultSchema$1, - CallToolResultSchema$1, - ListToolsResultSchema$1, - GetTaskResultSchema$1, - ListTasksResultSchema$1, - CreateTaskResultSchema$1 - ]), - CallToolResultWireSchema: unknown().superRefine((value, ctx) => { - if (typeof value !== "object" || value === null || Array.isArray(value) || value.content !== void 0) return; - for (const key of TOOL_RESULT_FOREIGN_FAMILY_KEYS) if (key in value) { - ctx.addIssue({ - code: "custom", - message: `content is required when the body carries '${key}' — another result family cannot default into an empty tools/call success` - }); - return; - } - }).transform(normalizeContentlessToolResult).pipe(CallToolResultSchema$1) - }; -} -let memo$1; -/** -* Builds the era wire-schema set on first call and returns the same object -* thereafter. Module evaluation stays construction-free so importing the -* era codec/registry costs nothing until the first validation actually -* needs a schema; the registry, the codec, and the eager `schemas.ts` -* shim all pull through this memo, so reference identity holds across -* every consumer. -*/ -function buildSchemas2025() { - return memo$1 ??= build$1(); -} - -//#endregion -//#region ../core-internal/src/wire/rev2025-11-25/legacyWrap.ts -/** -* SEP-2106 legacy `outputSchema` wrap helpers (2025-era projection only). -* -* The neutral / 2026-07-28 model lets a tool's `outputSchema` carry any JSON -* Schema root. The 2025-11-25 wire shape requires `type:'object'` at the root, -* so when an era-blind handler advertises a non-object root, the 2025 codec's -* `encodeResult('tools/list', …)` projects it down to -* `{type:'object', properties:{result:}, required:['result']}`, and -* `projectCallToolResult` wraps the matching `structuredContent` as -* `{result:}`. The 2026 codec's projections are the identity. -* -* These helpers are wire-layer property — they exist so the projection can -* live behind {@link WireCodec.encodeResult} / {@link WireCodec.projectCallToolResult} -* and never be re-derived in shared/ or server-side code. -*/ -/** -* Whether a JSON Schema's root is non-object: either an explicit non-object -* `type`, or a typeless root such as `{anyOf:[…]}`. Object-shaped typeless -* roots that the schema-conversion layer can prove are objects are stamped -* `type:'object'` upstream, so they reach this predicate as object roots. -*/ -function isNonObjectJsonSchemaRoot(json) { - return json["type"] !== "object"; -} -/** -* Keyword-position keys whose values are instance data (not subschemas). A -* `{$ref:…}` appearing inside one is a literal value, not a JSON Pointer to -* rewrite. Only consulted when the current object is in keyword position — -* a PROPERTY named `default`/`const` (under `properties`/`$defs`/…) is a name -* position whose value IS a subschema and is recursed into. -*/ -const REF_REWRITE_DATA_POSITION_KEYS = new Set([ - "const", - "enum", - "default", - "examples" -]); -/** -* Keyword-position keys whose value is a name→subschema map. Entries inside -* such a map are in NAME position: their keys are author-chosen property -* names (which may collide with JSON Schema keywords), their values are -* subschemas to recurse into. -*/ -const REF_REWRITE_NAME_MAP_KEYS = new Set([ - "properties", - "patternProperties", - "$defs", - "definitions", - "dependentSchemas", - "dependencies" -]); -/** -* Whether a subtree's `$id` establishes a new resolution base. A fragment-only -* `$id` (`"#item"`, the draft-07/06 spelling of 2020-12's `$anchor`) does not -* change the RFC 3986 base URI — same-document pointers inside still resolve -* against the document root and must be rewritten. -*/ -function establishesNewBase(id) { - return id !== void 0 && !(typeof id === "string" && id.startsWith("#")); -} -/** -* Wrap a non-object output schema in the 2025-era envelope: -* `{type:'object', properties:{result:}, required:['result']}`. -* -* Same-document `$ref` / `$dynamicRef` JSON Pointers inside the natural schema -* (e.g. `#/properties/foo` produced by zod for de-duplicated/recursive types) -* are rewritten to account for the new `#/properties/result` root: bare `#` → -* `#/properties/result`, `#/…` → `#/properties/result/…`. Cross-document refs -* (anything not starting with `#`) are left untouched. -* -* The rewrite is position-aware: data-valued keywords -* (`const`/`enum`/`default`/`examples`) in keyword position are NOT descended -* into; the same names appearing as property names under -* `properties`/`patternProperties`/`$defs`/`definitions`/`dependentSchemas`/ -* `dependencies` ARE descended into (they're subschemas). The rewrite is also -* `$id`-scoped: if the natural root carries a base-establishing `$id` no -* pointer is rewritten (same-document refs inside resolve against the embedded -* `$id` base, not the wrapper root), and any subtree that establishes its own -* `$id` is left untouched for the same reason. Fragment-only `$id` (`"#item"`, -* draft-07's anchor spelling) does not establish a base and IS descended into. -*/ -function wrapOutputSchemaForLegacy(natural) { - const $schema = typeof natural["$schema"] === "string" ? natural["$schema"] : void 0; - if (establishesNewBase(natural["$id"])) return { - ...$schema !== void 0 && { $schema }, - type: "object", - properties: { result: natural }, - required: ["result"] - }; - const convertRecursiveRefs = declares2019Dialect(natural["$schema"]) && natural["$recursiveAnchor"] !== true; - const rewriteRefs = (node, parentIsNameMap) => { - if (Array.isArray(node)) return node.map((item) => rewriteRefs(item, false)); - if (node === null || typeof node !== "object") return node; - if (!parentIsNameMap && establishesNewBase(node["$id"])) return node; - const out = {}; - let convertedRecursion = false; - for (const [k, v] of Object.entries(node)) if (parentIsNameMap) out[k] = rewriteRefs(v, false); - else if ((k === "$ref" || k === "$dynamicRef") && typeof v === "string") out[k] = v === "#" ? "#/properties/result" : v.startsWith("#/") ? `#/properties/result${v.slice(1)}` : v; - else if (k === "$recursiveRef" && v === "#" && convertRecursiveRefs) convertedRecursion = true; - else if (REF_REWRITE_DATA_POSITION_KEYS.has(k)) out[k] = v; - else if (REF_REWRITE_NAME_MAP_KEYS.has(k)) out[k] = rewriteRefs(v, true); - else out[k] = rewriteRefs(v, false); - if (convertedRecursion) if ("$ref" in out) out["allOf"] = [...Array.isArray(out["allOf"]) ? out["allOf"] : [], { $ref: "#/properties/result" }]; - else out["$ref"] = "#/properties/result"; - return out; - }; - return { - ...$schema !== void 0 && { $schema }, - type: "object", - properties: { result: rewriteRefs(natural, false) }, - required: ["result"] - }; -} - -//#endregion -//#region ../core-internal/src/wire/rev2025-11-25/registry.ts -const requestMethodKeys$1 = { - 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 -}; -const notificationMethodKeys$1 = { - "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 -}; -const resultMethodKeys = { - 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 -}; -let maps$1; -function registryMaps() { - if (maps$1) return maps$1; - const s = buildSchemas2025(); - maps$1 = { - requestSchemas: { - ping: s.PingRequestSchema, - initialize: s.InitializeRequestSchema, - "completion/complete": s.CompleteRequestSchema, - "logging/setLevel": s.SetLevelRequestSchema, - "prompts/get": s.GetPromptRequestSchema, - "prompts/list": s.ListPromptsRequestSchema, - "resources/list": s.ListResourcesRequestSchema, - "resources/templates/list": s.ListResourceTemplatesRequestSchema, - "resources/read": s.ReadResourceRequestSchema, - "resources/subscribe": s.SubscribeRequestSchema, - "resources/unsubscribe": s.UnsubscribeRequestSchema, - "tools/call": s.CallToolRequestSchema, - "tools/list": s.ListToolsRequestSchema, - "tasks/get": s.GetTaskRequestSchema, - "tasks/result": s.GetTaskPayloadRequestSchema, - "tasks/list": s.ListTasksRequestSchema, - "tasks/cancel": s.CancelTaskRequestSchema, - "sampling/createMessage": s.CreateMessageRequestSchema, - "elicitation/create": s.ElicitRequestSchema, - "roots/list": s.ListRootsRequestSchema - }, - notificationSchemas: { - "notifications/cancelled": s.CancelledNotificationSchema, - "notifications/progress": s.ProgressNotificationSchema, - "notifications/initialized": s.InitializedNotificationSchema, - "notifications/roots/list_changed": s.RootsListChangedNotificationSchema, - "notifications/tasks/status": s.TaskStatusNotificationSchema, - "notifications/message": s.LoggingMessageNotificationSchema, - "notifications/resources/updated": s.ResourceUpdatedNotificationSchema, - "notifications/resources/list_changed": s.ResourceListChangedNotificationSchema, - "notifications/tools/list_changed": s.ToolListChangedNotificationSchema, - "notifications/prompts/list_changed": s.PromptListChangedNotificationSchema, - "notifications/elicitation/complete": s.ElicitationCompleteNotificationSchema - }, - resultSchemas: { - ping: s.EmptyResultSchema, - initialize: s.InitializeResultSchema, - "completion/complete": s.CompleteResultSchema, - "logging/setLevel": s.EmptyResultSchema, - "prompts/get": s.GetPromptResultSchema, - "prompts/list": s.ListPromptsResultSchema, - "resources/list": s.ListResourcesResultSchema, - "resources/templates/list": s.ListResourceTemplatesResultSchema, - "resources/read": s.ReadResourceResultSchema, - "resources/subscribe": s.EmptyResultSchema, - "resources/unsubscribe": s.EmptyResultSchema, - "tools/call": s.CallToolResultWireSchema, - "tools/list": s.ListToolsResultSchema, - "sampling/createMessage": s.CreateMessageResultWithToolsSchema, - "elicitation/create": s.ElicitResultSchema, - "roots/list": s.ListRootsResultSchema - } - }; - return maps$1; -} -/** -* Forces the lazy registry maps (and, through them, the era's schema memo). -* Warm-up hook for `preloadSchemas()` — no-op once the maps exist. -*/ -function warmRegistryMaps2025() { - registryMaps(); -} -/** The 2025-era request-method set (registry membership = the deletion story). */ -function hasRequestMethod2025(method) { - return Object.prototype.hasOwnProperty.call(requestMethodKeys$1, method); -} -/** The 2025-era notification-method set. */ -function hasNotificationMethod2025(method) { - return Object.prototype.hasOwnProperty.call(notificationMethodKeys$1, method); -} -/** Result-map membership: exactly the era's typed-method subset (no task entries, no 2026-only methods). */ -function hasResultMethod(method) { - return Object.prototype.hasOwnProperty.call(resultMethodKeys, method); -} -function getResultSchema(method) { - return hasResultMethod(method) ? registryMaps().resultSchemas[method] : void 0; -} -function getRequestSchema(method) { - return hasRequestMethod2025(method) ? registryMaps().requestSchemas[method] : void 0; -} -function getNotificationSchema(method) { - return hasNotificationMethod2025(method) ? registryMaps().notificationSchemas[method] : void 0; -} -/** Registry method lists (for the spec-method universe and the CI registry-diff oracle). */ -const rev2025RequestMethods = Object.keys(requestMethodKeys$1); -const rev2025NotificationMethods = Object.keys(notificationMethodKeys$1); - -//#endregion -//#region ../core-internal/src/wire/rev2025-11-25/codec.ts -function isPlainObject$6(value) { - return value !== null && typeof value === "object" && !Array.isArray(value); -} -/** Tri-state wrap of an optional Zod schema lookup (the function-only contract). */ -function triState$1(schema, raw) { - if (schema === void 0) return { - ok: false, - reason: "not-in-era" - }; - const parsed = schema.safeParse(raw); - return parsed.success ? { - ok: true, - value: parsed.data - } : { - ok: false, - reason: "invalid", - message: String(parsed.error) - }; -} -const NOT_IN_ERA$1 = { - ok: false, - reason: "not-in-era" -}; -/** Whether a `tools/list` entry advertises a non-object `outputSchema` root that needs the SEP-2106 legacy wrap. */ -function toolNeedsLegacyWrap(t) { - return isPlainObject$6(t) && isPlainObject$6(t["outputSchema"]) && isNonObjectJsonSchemaRoot(t["outputSchema"]); -} -/** The wire→neutral trust boundary: a decoded 2025-era wire result is adopted as the neutral `Result` here (the module's single deliberate assertion). */ -function toNeutralResult(value) { - return value; -} -const rev2025Codec = { - era: "2025-11-25", - hasRequestMethod: hasRequestMethod2025, - hasNotificationMethod: hasNotificationMethod2025, - validateRequest: (method, raw) => triState$1(getRequestSchema(method), raw), - validateResult: (method, raw) => triState$1(getResultSchema(method), raw), - validateNotification: (method, raw) => triState$1(getNotificationSchema(method), raw), - hasInputRequestMethod: () => false, - validateInputRequest: () => NOT_IN_ERA$1, - validateInputResponse: () => NOT_IN_ERA$1, - samplingResultVariant: ((hasTools, raw) => { - const s = buildSchemas2025(); - return triState$1(hasTools ? s.CreateMessageResultWithToolsSchema : s.CreateMessageResultSchema, raw); - }), - outboundEnvelope: (_material) => void 0, - validateEnvelopeMeta: (_meta) => [], - projectCallToolResult(result, advertisedOutputSchema) { - const withText = appendTextFallbackForNonObject(result); - const sc = withText.structuredContent; - if (sc === void 0) return withText; - const valueIsNonObject = typeof sc !== "object" || sc === null || Array.isArray(sc); - const schemaWrapped = advertisedOutputSchema !== void 0 && isNonObjectJsonSchemaRoot(advertisedOutputSchema); - if (!valueIsNonObject && !schemaWrapped) return withText; - return { - ...withText, - structuredContent: { result: sc } - }; - }, - decodeResult(_method, raw) { - if (isPlainObject$6(raw) && "resultType" in raw) { - const stripped = { ...raw }; - delete stripped["resultType"]; - return { - kind: "complete", - result: toNeutralResult(stripped) - }; - } - return { - kind: "complete", - result: toNeutralResult(raw) - }; - }, - encodeResult(method, result) { - if (method !== "tools/list") return result; - const tools = result.tools; - if (!Array.isArray(tools) || !tools.some((t) => toolNeedsLegacyWrap(t))) return result; - return { - ...result, - tools: tools.map((t) => toolNeedsLegacyWrap(t) ? { - ...t, - outputSchema: wrapOutputSchemaForLegacy(t.outputSchema) - } : t) - }; - }, - encodeErrorCode: (code) => code === -32002 ? -32602 : code, - checkInboundEnvelope: (_material) => void 0 -}; - -//#endregion -//#region ../core-internal/src/wire/rev2026-07-28/buildSchemas.ts -/** -* 2026-era wire schemas (protocol revision 2026-07-28). -* -* Fully self-contained — no runtime imports from types/schemas.ts. The -* neutral types/schemas.ts layer is the public-API superset and is free to -* evolve; this file is the 2026 wire-parse contract and is BEHAVIOR-FROZEN -* against the 2026-07-28 anchor. Every era-shared building block (content -* blocks, resources, prompts, capabilities, notifications, …) that the wire -* shapes compose is a frozen LOCAL copy — verbatim from the neutral layer at -* the point this revision was sealed, dependencies first. The only cross-layer -* dependency is `import type { JSONObject, JSONValue }` from the neutral types -* barrel — pure structural type aliases with no parse behavior. -* -* This module is the only place the per-request `_meta` envelope is modeled. -* The envelope is wire-only vocabulary: the protocol layer lifts it off -* inbound requests before any handler runs and surfaces it at -* `ctx.mcpReq.envelope`; the 2026-era codec enforces its requiredness at -* dispatch time (`checkInboundEnvelope`) - the former neutral-schema JSDoc -* deferral ("enforced per request at dispatch time, not here") is now -* discharged by that codec step. -* -* No 2025-era traffic ever touches this module, so requiredness here is -* bare and spec-exact (the shared-schema `.catch` hazards do not apply). -* -* SPEC-CURRENCY RE-SEAL (2026-07-17): the 2026-07-28 revision was re-sealed -* upstream by spec PR #3002 (commit 71e30695, merged 2026-07-15 — after the -* previous anchor pin f68d864a): the envelope's `clientInfo` demoted from -* required to SHOULD, and `DiscoverResult.serverInfo` moved from the result -* body to the new `ResultMetaObject` key -* `_meta['io.modelcontextprotocol/serverInfo']` (optional on every result). -* The shapes below are the re-sealed anchor, exactly — no pre-#3002 shape is -* modeled anywhere (per ruling: the final revision is the only 2026-07-28). -*/ -function build() { - const JSONValueSchema$1 = lazy(() => schemas_union([ - schemas_string(), - schemas_number(), - schemas_boolean(), - schemas_null(), - schemas_record(schemas_string(), JSONValueSchema$1), - schemas_array(JSONValueSchema$1) - ])); - const JSONObjectSchema$1 = schemas_record(schemas_string(), JSONValueSchema$1); - /** - * A progress token, used to associate progress notifications with the original request. - */ - const ProgressTokenSchema$1 = schemas_union([schemas_string(), schemas_number().int()]); - /** - * An opaque token used to represent a cursor for pagination. - */ - const CursorSchema$1 = schemas_string(); - /** - * A uniquely identifying ID for a request in JSON-RPC. - */ - const RequestIdSchema$1 = schemas_union([schemas_string(), schemas_number().int()]); - /** - * The sender or recipient of messages and data in a conversation. - */ - const RoleSchema$1 = schemas_enum(["user", "assistant"]); - /** - * The severity of a log message. - */ - const LoggingLevelSchema$1 = schemas_enum([ - "debug", - "info", - "notice", - "warning", - "error", - "critical", - "alert", - "emergency" - ]); - /** - * A Zod schema for validating Base64 strings that is more performant and - * robust for very large inputs than the default regex-based check. It avoids - * stack overflows by using the native `atob` function for validation. - */ - const Base64Schema = schemas_string().refine((val) => { - try { - atob(val); - return true; - } catch { - return false; - } - }, { message: "Invalid Base64 string" }); - /** @deprecated 2025-11-25 wire vocabulary with no SDK runtime; kept importable for interoperability only. */ - const TaskMetadataSchema$1 = schemas_object({ ttl: schemas_number().optional() }); - /** @deprecated 2025-11-25 wire vocabulary with no SDK runtime; kept importable for interoperability only. */ - const RelatedTaskMetadataSchema$1 = schemas_object({ taskId: schemas_string() }); - const RequestMetaSchema$1 = looseObject({ - progressToken: ProgressTokenSchema$1.optional(), - "io.modelcontextprotocol/related-task": RelatedTaskMetadataSchema$1.optional() - }); - const BaseRequestParamsSchema$1 = schemas_object({ _meta: RequestMetaSchema$1.optional() }); - /** @deprecated 2025-11-25 wire vocabulary with no SDK runtime; kept importable for interoperability only. */ - const TaskAugmentedRequestParamsSchema$1 = BaseRequestParamsSchema$1.extend({ task: TaskMetadataSchema$1.optional() }); - const NotificationsParamsSchema$1 = schemas_object({ _meta: RequestMetaSchema$1.optional() }); - const NotificationSchema$1 = schemas_object({ - method: schemas_string(), - params: NotificationsParamsSchema$1.loose().optional() - }); - const IconSchema$1 = schemas_object({ - src: schemas_string(), - mimeType: schemas_string().optional(), - sizes: schemas_array(schemas_string()).optional(), - theme: schemas_enum(["light", "dark"]).optional() - }); - const IconsSchema$1 = schemas_object({ icons: schemas_array(IconSchema$1).optional() }); - const BaseMetadataSchema$1 = schemas_object({ - name: schemas_string(), - title: schemas_string().optional() - }); - const ImplementationSchema$1 = BaseMetadataSchema$1.extend({ - ...BaseMetadataSchema$1.shape, - ...IconsSchema$1.shape, - version: schemas_string(), - websiteUrl: schemas_string().optional(), - description: schemas_string().optional() - }); - const FormElicitationCapabilitySchema = intersection(schemas_object({ applyDefaults: schemas_boolean().optional() }), JSONObjectSchema$1); - const ElicitationCapabilitySchema = preprocess((value) => { - if (value && typeof value === "object" && !Array.isArray(value) && Object.keys(value).length === 0) return { form: {} }; - return value; - }, intersection(schemas_object({ - form: FormElicitationCapabilitySchema.optional(), - url: JSONObjectSchema$1.optional() - }), JSONObjectSchema$1.optional())); - /** @deprecated 2025-11-25 wire vocabulary with no SDK runtime; kept importable for interoperability only. */ - const ClientTasksCapabilitySchema$1 = looseObject({ - list: JSONObjectSchema$1.optional(), - cancel: JSONObjectSchema$1.optional(), - requests: looseObject({ - sampling: looseObject({ createMessage: JSONObjectSchema$1.optional() }).optional(), - elicitation: looseObject({ create: JSONObjectSchema$1.optional() }).optional() - }).optional() - }); - /** @deprecated 2025-11-25 wire vocabulary with no SDK runtime; kept importable for interoperability only. */ - const ServerTasksCapabilitySchema$1 = looseObject({ - list: JSONObjectSchema$1.optional(), - cancel: JSONObjectSchema$1.optional(), - requests: looseObject({ tools: looseObject({ call: JSONObjectSchema$1.optional() }).optional() }).optional() - }); - const ClientCapabilitiesSchema$1 = schemas_object({ - experimental: schemas_record(schemas_string(), JSONObjectSchema$1).optional(), - sampling: schemas_object({ - context: JSONObjectSchema$1.optional(), - tools: JSONObjectSchema$1.optional() - }).optional(), - elicitation: ElicitationCapabilitySchema.optional(), - roots: schemas_object({ listChanged: schemas_boolean().optional() }).optional(), - tasks: ClientTasksCapabilitySchema$1.optional(), - extensions: schemas_record(schemas_string(), JSONObjectSchema$1).optional() - }); - const ServerCapabilitiesSchema$1 = schemas_object({ - experimental: schemas_record(schemas_string(), JSONObjectSchema$1).optional(), - logging: JSONObjectSchema$1.optional(), - completions: JSONObjectSchema$1.optional(), - prompts: schemas_object({ listChanged: schemas_boolean().optional() }).optional(), - resources: schemas_object({ - subscribe: schemas_boolean().optional(), - listChanged: schemas_boolean().optional() - }).optional(), - tools: schemas_object({ listChanged: schemas_boolean().optional() }).optional(), - tasks: ServerTasksCapabilitySchema$1.optional(), - extensions: schemas_record(schemas_string(), JSONObjectSchema$1).optional() - }); - const ProgressSchema$1 = schemas_object({ - progress: schemas_number(), - total: schemas_optional(schemas_number()), - message: schemas_optional(schemas_string()) - }); - const ProgressNotificationParamsSchema$1 = schemas_object({ - ...NotificationsParamsSchema$1.shape, - ...ProgressSchema$1.shape, - progressToken: ProgressTokenSchema$1 - }); - const ProgressNotificationSchema$1 = NotificationSchema$1.extend({ - method: literal("notifications/progress"), - params: ProgressNotificationParamsSchema$1 - }); - const LoggingMessageNotificationParamsSchema$1 = NotificationsParamsSchema$1.extend({ - level: LoggingLevelSchema$1, - logger: schemas_string().optional(), - data: unknown() - }); - const LoggingMessageNotificationSchema$1 = NotificationSchema$1.extend({ - method: literal("notifications/message"), - params: LoggingMessageNotificationParamsSchema$1 - }); - const ResourceContentsSchema$1 = schemas_object({ - uri: schemas_string(), - mimeType: schemas_optional(schemas_string()), - _meta: schemas_record(schemas_string(), unknown()).optional() - }); - const TextResourceContentsSchema$1 = ResourceContentsSchema$1.extend({ text: schemas_string() }); - const BlobResourceContentsSchema$1 = ResourceContentsSchema$1.extend({ blob: Base64Schema }); - const AnnotationsSchema$1 = schemas_object({ - audience: schemas_array(RoleSchema$1).optional(), - priority: schemas_number().min(0).max(1).optional(), - lastModified: iso_datetime({ offset: true }).optional() - }); - const ResourceSchema$1 = schemas_object({ - ...BaseMetadataSchema$1.shape, - ...IconsSchema$1.shape, - uri: schemas_string(), - description: schemas_optional(schemas_string()), - mimeType: schemas_optional(schemas_string()), - size: schemas_optional(schemas_number()), - annotations: AnnotationsSchema$1.optional(), - _meta: schemas_optional(looseObject({})) - }); - const ResourceTemplateSchema$1 = schemas_object({ - ...BaseMetadataSchema$1.shape, - ...IconsSchema$1.shape, - uriTemplate: schemas_string(), - description: schemas_optional(schemas_string()), - mimeType: schemas_optional(schemas_string()), - annotations: AnnotationsSchema$1.optional(), - _meta: schemas_optional(looseObject({})) - }); - const ResourceListChangedNotificationSchema$1 = NotificationSchema$1.extend({ - method: literal("notifications/resources/list_changed"), - params: NotificationsParamsSchema$1.optional() - }); - const ResourceUpdatedNotificationParamsSchema$1 = NotificationsParamsSchema$1.extend({ uri: schemas_string() }); - const ResourceUpdatedNotificationSchema$1 = NotificationSchema$1.extend({ - method: literal("notifications/resources/updated"), - params: ResourceUpdatedNotificationParamsSchema$1 - }); - const PromptArgumentSchema$1 = schemas_object({ - name: schemas_string(), - description: schemas_optional(schemas_string()), - required: schemas_optional(schemas_boolean()) - }); - const PromptSchema$1 = schemas_object({ - ...BaseMetadataSchema$1.shape, - ...IconsSchema$1.shape, - description: schemas_optional(schemas_string()), - arguments: schemas_optional(schemas_array(PromptArgumentSchema$1)), - _meta: schemas_optional(looseObject({})) - }); - const PromptListChangedNotificationSchema$1 = NotificationSchema$1.extend({ - method: literal("notifications/prompts/list_changed"), - params: NotificationsParamsSchema$1.optional() - }); - const TextContentSchema$1 = schemas_object({ - type: literal("text"), - text: schemas_string(), - annotations: AnnotationsSchema$1.optional(), - _meta: schemas_record(schemas_string(), unknown()).optional() - }); - const ImageContentSchema$1 = schemas_object({ - type: literal("image"), - data: Base64Schema, - mimeType: schemas_string(), - annotations: AnnotationsSchema$1.optional(), - _meta: schemas_record(schemas_string(), unknown()).optional() - }); - const AudioContentSchema$1 = schemas_object({ - type: literal("audio"), - data: Base64Schema, - mimeType: schemas_string(), - annotations: AnnotationsSchema$1.optional(), - _meta: schemas_record(schemas_string(), unknown()).optional() - }); - const ToolUseContentSchema$1 = schemas_object({ - type: literal("tool_use"), - name: schemas_string(), - id: schemas_string(), - input: schemas_record(schemas_string(), unknown()), - _meta: schemas_record(schemas_string(), unknown()).optional() - }); - const EmbeddedResourceSchema$1 = schemas_object({ - type: literal("resource"), - resource: schemas_union([TextResourceContentsSchema$1, BlobResourceContentsSchema$1]), - annotations: AnnotationsSchema$1.optional(), - _meta: schemas_record(schemas_string(), unknown()).optional() - }); - const ResourceLinkSchema$1 = ResourceSchema$1.extend({ type: literal("resource_link") }); - const ContentBlockSchema$1 = schemas_union([ - TextContentSchema$1, - ImageContentSchema$1, - AudioContentSchema$1, - ResourceLinkSchema$1, - EmbeddedResourceSchema$1 - ]); - const PromptMessageSchema$1 = schemas_object({ - role: RoleSchema$1, - content: ContentBlockSchema$1 - }); - const ToolAnnotationsSchema$1 = schemas_object({ - title: schemas_string().optional(), - readOnlyHint: schemas_boolean().optional(), - destructiveHint: schemas_boolean().optional(), - idempotentHint: schemas_boolean().optional(), - openWorldHint: schemas_boolean().optional() - }); - const ToolListChangedNotificationSchema$1 = NotificationSchema$1.extend({ - method: literal("notifications/tools/list_changed"), - params: NotificationsParamsSchema$1.optional() - }); - const ModelHintSchema$1 = schemas_object({ name: schemas_string().optional() }); - const ModelPreferencesSchema$1 = schemas_object({ - hints: schemas_array(ModelHintSchema$1).optional(), - costPriority: schemas_number().min(0).max(1).optional(), - speedPriority: schemas_number().min(0).max(1).optional(), - intelligencePriority: schemas_number().min(0).max(1).optional() - }); - const ToolChoiceSchema$1 = schemas_object({ mode: schemas_enum([ - "auto", - "required", - "none" - ]).optional() }); - const BooleanSchemaSchema$1 = schemas_object({ - type: literal("boolean"), - title: schemas_string().optional(), - description: schemas_string().optional(), - default: schemas_boolean().optional() - }); - const StringSchemaSchema$1 = schemas_object({ - type: literal("string"), - title: schemas_string().optional(), - description: schemas_string().optional(), - minLength: schemas_number().optional(), - maxLength: schemas_number().optional(), - format: schemas_enum([ - "email", - "uri", - "date", - "date-time" - ]).optional(), - default: schemas_string().optional() - }); - const NumberSchemaSchema$1 = schemas_object({ - type: schemas_enum(["number", "integer"]), - title: schemas_string().optional(), - description: schemas_string().optional(), - minimum: schemas_number().optional(), - maximum: schemas_number().optional(), - default: schemas_number().optional() - }); - const UntitledSingleSelectEnumSchemaSchema$1 = schemas_object({ - type: literal("string"), - title: schemas_string().optional(), - description: schemas_string().optional(), - enum: schemas_array(schemas_string()), - default: schemas_string().optional() - }); - const TitledSingleSelectEnumSchemaSchema$1 = schemas_object({ - type: literal("string"), - title: schemas_string().optional(), - description: schemas_string().optional(), - oneOf: schemas_array(schemas_object({ - const: schemas_string(), - title: schemas_string() - })), - default: schemas_string().optional() - }); - const LegacyTitledEnumSchemaSchema$1 = schemas_object({ - type: literal("string"), - title: schemas_string().optional(), - description: schemas_string().optional(), - enum: schemas_array(schemas_string()), - enumNames: schemas_array(schemas_string()).optional(), - default: schemas_string().optional() - }); - const SingleSelectEnumSchemaSchema$1 = schemas_union([UntitledSingleSelectEnumSchemaSchema$1, TitledSingleSelectEnumSchemaSchema$1]); - const UntitledMultiSelectEnumSchemaSchema$1 = schemas_object({ - type: literal("array"), - title: schemas_string().optional(), - description: schemas_string().optional(), - minItems: schemas_number().optional(), - maxItems: schemas_number().optional(), - items: schemas_object({ - type: literal("string"), - enum: schemas_array(schemas_string()) - }), - default: schemas_array(schemas_string()).optional() - }); - const TitledMultiSelectEnumSchemaSchema$1 = schemas_object({ - type: literal("array"), - title: schemas_string().optional(), - description: schemas_string().optional(), - minItems: schemas_number().optional(), - maxItems: schemas_number().optional(), - items: schemas_object({ anyOf: schemas_array(schemas_object({ - const: schemas_string(), - title: schemas_string() - })) }), - default: schemas_array(schemas_string()).optional() - }); - const MultiSelectEnumSchemaSchema$1 = schemas_union([UntitledMultiSelectEnumSchemaSchema$1, TitledMultiSelectEnumSchemaSchema$1]); - const EnumSchemaSchema$1 = schemas_union([ - LegacyTitledEnumSchemaSchema$1, - SingleSelectEnumSchemaSchema$1, - MultiSelectEnumSchemaSchema$1 - ]); - const PrimitiveSchemaDefinitionSchema$1 = schemas_union([ - EnumSchemaSchema$1, - BooleanSchemaSchema$1, - StringSchemaSchema$1, - NumberSchemaSchema$1 - ]); - const ElicitRequestFormParamsSchema$1 = TaskAugmentedRequestParamsSchema$1.extend({ - mode: literal("form").optional(), - message: schemas_string(), - requestedSchema: schemas_object({ - type: literal("object"), - properties: schemas_record(schemas_string(), PrimitiveSchemaDefinitionSchema$1), - required: schemas_array(schemas_string()).optional() - }).catchall(unknown()) - }); - const ResourceTemplateReferenceSchema$1 = schemas_object({ - type: literal("ref/resource"), - uri: schemas_string() - }); - const PromptReferenceSchema$1 = schemas_object({ - type: literal("ref/prompt"), - name: schemas_string() - }); - const RootSchema$1 = schemas_object({ - uri: schemas_string().startsWith("file://"), - name: schemas_string().optional(), - _meta: schemas_record(schemas_string(), unknown()).optional() - }); - const sharedClientCapabilityShape = ClientCapabilitiesSchema$1.shape; - const ClientCapabilities2026Schema = schemas_object({ - experimental: sharedClientCapabilityShape.experimental, - sampling: sharedClientCapabilityShape.sampling, - elicitation: sharedClientCapabilityShape.elicitation, - roots: sharedClientCapabilityShape.roots, - extensions: sharedClientCapabilityShape.extensions - }); - const sharedServerCapabilityShape = ServerCapabilitiesSchema$1.shape; - const ServerCapabilities2026Schema = schemas_object({ - experimental: sharedServerCapabilityShape.experimental, - logging: sharedServerCapabilityShape.logging, - completions: sharedServerCapabilityShape.completions, - prompts: sharedServerCapabilityShape.prompts, - resources: sharedServerCapabilityShape.resources, - tools: sharedServerCapabilityShape.tools, - extensions: sharedServerCapabilityShape.extensions - }); - /** - * The per-request `_meta` envelope carried by every request under protocol revision - * 2026-07-28: the protocol version governing the request, the client implementation - * info, and the client's capabilities — declared per request rather than once at - * initialization — plus the optional log-level opt-in. - * - * This schema models the complete envelope on its own (loose: foreign keys - * pass through - the lift extracts exactly the reserved keys, so enforcement - * never sees extension material). Requiredness is enforced per request at - * dispatch time by the 2026-era codec's `checkInboundEnvelope` step. - */ - const RequestMetaEnvelopeSchema = looseObject({ - progressToken: ProgressTokenSchema$1.optional(), - [auth_CUe6YdwF_PROTOCOL_VERSION_META_KEY]: schemas_string(), - [auth_CUe6YdwF_CLIENT_INFO_META_KEY]: ImplementationSchema$1.optional(), - [auth_CUe6YdwF_CLIENT_CAPABILITIES_META_KEY]: ClientCapabilities2026Schema, - [LOG_LEVEL_META_KEY]: LoggingLevelSchema$1.optional() - }); - /** 2026-era Tool: anchor-exact — no `execution` (deleted vocabulary). */ - const ToolSchema$1 = schemas_object({ - ...BaseMetadataSchema$1.shape, - ...IconsSchema$1.shape, - description: schemas_string().optional(), - inputSchema: looseObject({ - $schema: schemas_string().optional(), - type: literal("object") - }), - outputSchema: looseObject({ $schema: schemas_string().optional() }).optional(), - annotations: ToolAnnotationsSchema$1.optional(), - _meta: schemas_record(schemas_string(), unknown()).optional() - }); - /** 2026-era ToolResultContent (anchor-exact: `structuredContent?: unknown`). */ - const ToolResultContentSchema$1 = schemas_object({ - type: literal("tool_result"), - toolUseId: schemas_string(), - content: schemas_array(ContentBlockSchema$1), - structuredContent: unknown().optional(), - isError: schemas_boolean().optional(), - _meta: schemas_record(schemas_string(), unknown()).optional() - }); - /** 2026-era sampling content union (composes the forked tool-result shape). */ - const SamplingMessageContentBlockSchema$1 = schemas_union([ - TextContentSchema$1, - ImageContentSchema$1, - AudioContentSchema$1, - ToolUseContentSchema$1, - ToolResultContentSchema$1 - ]); - /** 2026-era SamplingMessage (anchor-exact: single block or array). */ - const SamplingMessageSchema$1 = schemas_object({ - role: RoleSchema$1, - content: schemas_union([SamplingMessageContentBlockSchema$1, schemas_array(SamplingMessageContentBlockSchema$1)]), - _meta: schemas_record(schemas_string(), unknown()).optional() - }); - /** Open union per the anchor: 'complete' | 'input_required' | string. */ - const ResultTypeSchema = schemas_string(); - /** - * Result `_meta` (anchor `ResultMetaObject`, added by spec PR #3002): - * loose, with the serverInfo key typed when present; the outbound stamp - * is the encode contract's `stampServerInfoMeta` step. - */ - const ResultMetaSchema = looseObject({ [auth_CUe6YdwF_SERVER_INFO_META_KEY]: ImplementationSchema$1.optional().catch(void 0) }); - const wireMeta = ResultMetaSchema.optional(); - function wireResult(shape) { - return looseObject({ - _meta: wireMeta, - resultType: ResultTypeSchema.default("complete"), - ...shape - }); - } - const ResultSchema$1 = wireResult({}); - const PaginatedResultSchema$1 = wireResult({ nextCursor: CursorSchema$1.optional() }); - const CallToolResultSchema$1 = wireResult({ - content: schemas_array(ContentBlockSchema$1), - structuredContent: unknown().optional(), - isError: schemas_boolean().optional() - }); - const ListToolsResultSchema$1 = wireResult({ - ttlMs: schemas_number().int().min(0), - cacheScope: schemas_enum(["public", "private"]), - tools: schemas_array(ToolSchema$1), - nextCursor: CursorSchema$1.optional() - }); - const ListPromptsResultSchema$1 = wireResult({ - ttlMs: schemas_number().int().min(0), - cacheScope: schemas_enum(["public", "private"]), - prompts: schemas_array(PromptSchema$1), - nextCursor: CursorSchema$1.optional() - }); - const GetPromptResultSchema$1 = wireResult({ - description: schemas_string().optional(), - messages: schemas_array(PromptMessageSchema$1) - }); - const ListResourcesResultSchema$1 = wireResult({ - ttlMs: schemas_number().int().min(0), - cacheScope: schemas_enum(["public", "private"]), - resources: schemas_array(ResourceSchema$1), - nextCursor: CursorSchema$1.optional() - }); - const ListResourceTemplatesResultSchema$1 = wireResult({ - ttlMs: schemas_number().int().min(0), - cacheScope: schemas_enum(["public", "private"]), - resourceTemplates: schemas_array(ResourceTemplateSchema$1), - nextCursor: CursorSchema$1.optional() - }); - const ReadResourceResultSchema$1 = wireResult({ - ttlMs: schemas_number().int().min(0), - cacheScope: schemas_enum(["public", "private"]), - contents: schemas_array(schemas_union([TextResourceContentsSchema$1, BlobResourceContentsSchema$1])) - }); - const CompleteResultSchema$1 = wireResult({ completion: schemas_object({ - values: schemas_array(schemas_string()).max(100), - total: schemas_number().int().optional(), - hasMore: schemas_boolean().optional() - }).loose() }); - /** CacheableResult (SEP-2549): ttlMs and cacheScope REQUIRED per the anchor. */ - const CacheableResultSchema = wireResult({ - ttlMs: schemas_number().int().min(0), - cacheScope: schemas_enum(["public", "private"]) - }); - const DiscoverResultSchema$1 = wireResult({ - ttlMs: schemas_number().int().min(0).catch(0), - cacheScope: schemas_enum(["public", "private"]).catch("private"), - supportedVersions: schemas_array(schemas_string()), - capabilities: ServerCapabilities2026Schema, - instructions: schemas_string().optional() - }); - /** 2026-era CreateMessageRequestParams (anchor-exact: forked SamplingMessage/Tool, no task augmentation). */ - const CreateMessageRequestParamsSchema$1 = schemas_object({ - messages: schemas_array(SamplingMessageSchema$1), - modelPreferences: ModelPreferencesSchema$1.optional(), - systemPrompt: schemas_string().optional(), - includeContext: schemas_enum([ - "none", - "thisServer", - "allServers" - ]).optional(), - temperature: schemas_number().optional(), - maxTokens: schemas_number().int(), - stopSequences: schemas_array(schemas_string()).optional(), - metadata: JSONObjectSchema$1.optional(), - tools: schemas_array(ToolSchema$1).optional(), - toolChoice: ToolChoiceSchema$1.optional() - }); - /** 2026-era embedded sampling request (de-JSON-RPC'd). */ - const CreateMessageRequestSchema$1 = schemas_object({ - method: literal("sampling/createMessage"), - params: CreateMessageRequestParamsSchema$1 - }); - /** - * 2026-era embedded roots listing request (de-JSON-RPC'd). Embedded input - * requests do NOT carry the per-request `_meta` envelope on this revision — - * the anchor declares a bare optional `_meta` on `params`. - */ - const ListRootsRequestSchema$1 = schemas_object({ - method: literal("roots/list"), - params: schemas_object({ _meta: schemas_record(schemas_string(), unknown()).optional() }).optional() - }); - /** 2026-era embedded sampling response (anchor-exact: extends the forked SamplingMessage). */ - const CreateMessageResultSchema$1 = schemas_object({ - ...SamplingMessageSchema$1.shape, - model: schemas_string(), - stopReason: schemas_string().optional() - }); - /** 2026-era embedded roots listing response (anchor-exact: bare `roots` array). */ - const ListRootsResultSchema$1 = schemas_object({ roots: schemas_array(RootSchema$1) }); - /** 2026-era embedded elicitation response (anchor-exact: bare result, restricted content value types). */ - const ElicitResultSchema$1 = schemas_object({ - action: schemas_enum([ - "accept", - "decline", - "cancel" - ]), - content: schemas_record(schemas_string(), schemas_union([ - schemas_string(), - schemas_number(), - schemas_boolean(), - schemas_array(schemas_string()) - ])).optional() - }); - /** - * 2026-era URL-mode elicitation params (anchor-exact fork): the draft removed - * `elicitationId` (and the `notifications/elicitation/complete` channel it - * keyed) — the shared schema keeps the field because it is required on the - * frozen 2025-11-25 revision. - */ - const ElicitRequestURLParamsSchema$1 = schemas_object({ - mode: literal("url"), - message: schemas_string(), - url: schemas_string().url() - }); - /** 2026-era elicitation params (form mode is revision-identical; URL mode is the fork above). */ - const ElicitRequestParamsSchema$1 = schemas_union([ElicitRequestFormParamsSchema$1, ElicitRequestURLParamsSchema$1]); - /** 2026-era embedded elicitation request (de-JSON-RPC'd; see the URL-mode fork above). */ - const ElicitRequestSchema$1 = schemas_object({ - method: literal("elicitation/create"), - params: ElicitRequestParamsSchema$1 - }); - /** A single embedded input request (one of the three demoted server→client requests). */ - const InputRequestSchema = schemas_union([ - CreateMessageRequestSchema$1, - ListRootsRequestSchema$1, - ElicitRequestSchema$1 - ]); - /** A single embedded input response — the BARE result union (never a `{method, result}` wrapper). */ - const InputResponseSchema = schemas_union([ - CreateMessageResultSchema$1, - ListRootsResultSchema$1, - ElicitResultSchema$1 - ]); - /** Map of embedded input requests, keyed by server-assigned identifiers. */ - const InputRequestsSchema = schemas_record(schemas_string(), InputRequestSchema); - /** Map of embedded input responses, keyed by the corresponding request identifiers. */ - const InputResponsesSchema = schemas_record(schemas_string(), InputResponseSchema); - /** - * The wire InputRequiredResult: `resultType: 'input_required'` plus at least - * one of `inputRequests` / `requestState` (the at-least-one rule is enforced - * at the server seam, not by this parse shape). - */ - const InputRequiredResultSchema = wireResult({ - inputRequests: InputRequestsSchema.optional(), - requestState: schemas_string().optional() - }); - /** The retry-channel members carried by client-initiated requests on this revision. */ - const retryParamsShape = { - inputResponses: InputResponsesSchema.optional(), - requestState: schemas_string().optional() - }; - /** Anchor InputResponseRequestParams: the retry channel on top of the required request `_meta` envelope. */ - const InputResponseRequestParamsSchema = schemas_object({ - _meta: RequestMetaEnvelopeSchema, - ...retryParamsShape - }); - /** Post-lift request `_meta` (progressToken + extension keys; loose). */ - const DispatchRequestMetaSchema = looseObject({ progressToken: ProgressTokenSchema$1.optional() }); - function wireRequest(method, paramsShape) { - return schemas_object({ - method: literal(method), - params: schemas_object({ - _meta: RequestMetaEnvelopeSchema, - ...paramsShape - }) - }); - } - function dispatchRequest(method, paramsShape) { - return schemas_object({ - method: literal(method), - params: schemas_object({ - _meta: DispatchRequestMetaSchema.optional(), - ...paramsShape - }).optional() - }); - } - const callToolParamsShape = { - name: schemas_string(), - arguments: schemas_record(schemas_string(), unknown()).optional(), - ...retryParamsShape - }; - const paginatedParamsShape = { cursor: CursorSchema$1.optional() }; - const CallToolRequestSchema$1 = wireRequest("tools/call", callToolParamsShape); - const ListToolsRequestSchema$1 = wireRequest("tools/list", paginatedParamsShape); - const ListPromptsRequestSchema$1 = wireRequest("prompts/list", paginatedParamsShape); - const GetPromptRequestSchema$1 = wireRequest("prompts/get", { - name: schemas_string(), - arguments: schemas_record(schemas_string(), schemas_string()).optional(), - ...retryParamsShape - }); - const ListResourcesRequestSchema$1 = wireRequest("resources/list", paginatedParamsShape); - const ListResourceTemplatesRequestSchema$1 = wireRequest("resources/templates/list", paginatedParamsShape); - const ReadResourceRequestSchema$1 = wireRequest("resources/read", { - uri: schemas_string(), - ...retryParamsShape - }); - const completeParamsShape = { - ref: schemas_union([PromptReferenceSchema$1, ResourceTemplateReferenceSchema$1]), - argument: schemas_object({ - name: schemas_string(), - value: schemas_string() - }), - context: schemas_object({ arguments: schemas_record(schemas_string(), schemas_string()).optional() }).optional() - }; - const CompleteRequestSchema$1 = wireRequest("completion/complete", completeParamsShape); - const DiscoverRequestSchema$1 = wireRequest("server/discover", {}); - /** Anchor SubscriptionFilter (2026-only). */ - const SubscriptionFilterSchema$1 = schemas_object({ - toolsListChanged: schemas_boolean().optional(), - promptsListChanged: schemas_boolean().optional(), - resourcesListChanged: schemas_boolean().optional(), - resourceSubscriptions: schemas_array(schemas_string()).optional() - }); - const subscriptionsListenParamsShape = { notifications: SubscriptionFilterSchema$1 }; - const SubscriptionsListenRequestSchema$1 = wireRequest("subscriptions/listen", subscriptionsListenParamsShape); - /** - * Anchor SubscriptionsListenResultMeta — required subscriptionId stamp on - * the graceful-close result. Extends `ResultMetaObject` since spec PR - * #3002 (composed, so the serverInfo key and its leniency stay single-sourced). - */ - const SubscriptionsListenResultMetaSchema$1 = ResultMetaSchema.extend({ "io.modelcontextprotocol/subscriptionId": RequestIdSchema$1 }); - /** - * Anchor SubscriptionsListenResult (2026-only). The empty `subscriptions/listen` - * response signalling that the subscription has ended gracefully (server - * shutdown). An abrupt transport close carries no response — the client treats - * stream-close-without-result as a disconnect. - */ - const SubscriptionsListenResultSchema$1 = looseObject({ - _meta: SubscriptionsListenResultMetaSchema$1, - resultType: ResultTypeSchema.default("complete") - }); - /** Dispatch (post-lift) request schemas, keyed by method — registry-internal. */ - const dispatchRequestSchemas = { - "tools/call": dispatchRequest("tools/call", callToolParamsShape), - "tools/list": dispatchRequest("tools/list", paginatedParamsShape), - "prompts/get": dispatchRequest("prompts/get", { - name: schemas_string(), - arguments: schemas_record(schemas_string(), schemas_string()).optional() - }), - "prompts/list": dispatchRequest("prompts/list", paginatedParamsShape), - "resources/list": dispatchRequest("resources/list", paginatedParamsShape), - "resources/templates/list": dispatchRequest("resources/templates/list", paginatedParamsShape), - "resources/read": dispatchRequest("resources/read", { uri: schemas_string() }), - "completion/complete": dispatchRequest("completion/complete", completeParamsShape), - "server/discover": dispatchRequest("server/discover", {}), - "subscriptions/listen": dispatchRequest("subscriptions/listen", subscriptionsListenParamsShape) - }; - /** Dispatch (post-lift) result schemas, keyed by method — what the funnel - * validates AFTER `decodeResult` consumed `resultType`. */ - function liftedResult(shape) { - return looseObject({ - _meta: wireMeta, - ...shape - }); - } - const dispatchResultSchemas = { - "tools/call": liftedResult({ - content: schemas_array(ContentBlockSchema$1), - structuredContent: unknown().optional(), - isError: schemas_boolean().optional() - }), - "tools/list": liftedResult({ - ttlMs: schemas_number().int().min(0), - cacheScope: schemas_enum(["public", "private"]), - tools: schemas_array(ToolSchema$1), - nextCursor: CursorSchema$1.optional() - }), - "prompts/get": liftedResult({ - description: schemas_string().optional(), - messages: schemas_array(PromptMessageSchema$1) - }), - "prompts/list": liftedResult({ - ttlMs: schemas_number().int().min(0), - cacheScope: schemas_enum(["public", "private"]), - prompts: schemas_array(PromptSchema$1), - nextCursor: CursorSchema$1.optional() - }), - "resources/list": liftedResult({ - ttlMs: schemas_number().int().min(0), - cacheScope: schemas_enum(["public", "private"]), - resources: schemas_array(ResourceSchema$1), - nextCursor: CursorSchema$1.optional() - }), - "resources/templates/list": liftedResult({ - ttlMs: schemas_number().int().min(0), - cacheScope: schemas_enum(["public", "private"]), - resourceTemplates: schemas_array(ResourceTemplateSchema$1), - nextCursor: CursorSchema$1.optional() - }), - "resources/read": liftedResult({ - ttlMs: schemas_number().int().min(0), - cacheScope: schemas_enum(["public", "private"]), - contents: schemas_array(schemas_union([TextResourceContentsSchema$1, BlobResourceContentsSchema$1])) - }), - "completion/complete": liftedResult({ completion: schemas_object({ - values: schemas_array(schemas_string()).max(100), - total: schemas_number().int().optional(), - hasMore: schemas_boolean().optional() - }).loose() }), - "server/discover": liftedResult({ - ttlMs: schemas_number().int().min(0).catch(0), - cacheScope: schemas_enum(["public", "private"]).catch("private"), - supportedVersions: schemas_array(schemas_string()), - capabilities: ServerCapabilities2026Schema, - instructions: schemas_string().optional() - }), - "subscriptions/listen": liftedResult({}) - }; - /** - * Notification `_meta` (anchor `NotificationMetaObject`): loose, with the - * subscriptions/listen demux key typed when present. Only the anchor-exact - * SHAPE is modeled here — listen delivery itself (filter gating, demux, - * teardown) is #14 scope and not implemented by this module. - */ - const NotificationMetaSchema = looseObject({ "io.modelcontextprotocol/subscriptionId": RequestIdSchema$1.optional() }); - /** Anchor SubscriptionsAcknowledgedNotification (2026-only). */ - const SubscriptionsAcknowledgedNotificationSchema$1 = schemas_object({ - method: literal("notifications/subscriptions/acknowledged"), - params: schemas_object({ - _meta: NotificationMetaSchema.optional(), - notifications: SubscriptionFilterSchema$1 - }) - }); - /** - * 2026-era `notifications/cancelled` params (anchor-exact fork): `requestId` - * is REQUIRED on this revision — the shared schema keeps it optional because - * the frozen 2025-11-25 shape declares it optional (task cancellation goes - * through `tasks/cancel` there). Requiredness is bare because no 2025-era - * traffic touches this module. - */ - const CancelledNotificationParamsSchema$1 = schemas_object({ - _meta: NotificationMetaSchema.optional(), - requestId: RequestIdSchema$1, - reason: schemas_string().optional() - }); - /** 2026-era `notifications/cancelled` (see the params fork above). */ - const CancelledNotificationSchema$1 = schemas_object({ - method: literal("notifications/cancelled"), - params: CancelledNotificationParamsSchema$1 - }); - const notificationSchemas2026 = { - "notifications/cancelled": CancelledNotificationSchema$1, - "notifications/progress": ProgressNotificationSchema$1, - "notifications/message": LoggingMessageNotificationSchema$1, - "notifications/resources/updated": ResourceUpdatedNotificationSchema$1, - "notifications/resources/list_changed": ResourceListChangedNotificationSchema$1, - "notifications/tools/list_changed": ToolListChangedNotificationSchema$1, - "notifications/prompts/list_changed": PromptListChangedNotificationSchema$1, - "notifications/subscriptions/acknowledged": SubscriptionsAcknowledgedNotificationSchema$1 - }; - const wireResultResponse = (result) => schemas_object({ - jsonrpc: literal("2.0"), - id: schemas_union([schemas_string(), schemas_number().int()]), - result - }).strict(); - return { - JSONValueSchema: JSONValueSchema$1, - JSONObjectSchema: JSONObjectSchema$1, - ProgressTokenSchema: ProgressTokenSchema$1, - CursorSchema: CursorSchema$1, - RequestIdSchema: RequestIdSchema$1, - RoleSchema: RoleSchema$1, - LoggingLevelSchema: LoggingLevelSchema$1, - TaskMetadataSchema: TaskMetadataSchema$1, - RelatedTaskMetadataSchema: RelatedTaskMetadataSchema$1, - RequestMetaSchema: RequestMetaSchema$1, - BaseRequestParamsSchema: BaseRequestParamsSchema$1, - TaskAugmentedRequestParamsSchema: TaskAugmentedRequestParamsSchema$1, - NotificationsParamsSchema: NotificationsParamsSchema$1, - NotificationSchema: NotificationSchema$1, - IconSchema: IconSchema$1, - IconsSchema: IconsSchema$1, - BaseMetadataSchema: BaseMetadataSchema$1, - ImplementationSchema: ImplementationSchema$1, - ClientTasksCapabilitySchema: ClientTasksCapabilitySchema$1, - ServerTasksCapabilitySchema: ServerTasksCapabilitySchema$1, - ClientCapabilitiesSchema: ClientCapabilitiesSchema$1, - ServerCapabilitiesSchema: ServerCapabilitiesSchema$1, - ProgressSchema: ProgressSchema$1, - ProgressNotificationParamsSchema: ProgressNotificationParamsSchema$1, - ProgressNotificationSchema: ProgressNotificationSchema$1, - LoggingMessageNotificationParamsSchema: LoggingMessageNotificationParamsSchema$1, - LoggingMessageNotificationSchema: LoggingMessageNotificationSchema$1, - ResourceContentsSchema: ResourceContentsSchema$1, - TextResourceContentsSchema: TextResourceContentsSchema$1, - BlobResourceContentsSchema: BlobResourceContentsSchema$1, - AnnotationsSchema: AnnotationsSchema$1, - ResourceSchema: ResourceSchema$1, - ResourceTemplateSchema: ResourceTemplateSchema$1, - ResourceListChangedNotificationSchema: ResourceListChangedNotificationSchema$1, - ResourceUpdatedNotificationParamsSchema: ResourceUpdatedNotificationParamsSchema$1, - ResourceUpdatedNotificationSchema: ResourceUpdatedNotificationSchema$1, - PromptArgumentSchema: PromptArgumentSchema$1, - PromptSchema: PromptSchema$1, - PromptListChangedNotificationSchema: PromptListChangedNotificationSchema$1, - TextContentSchema: TextContentSchema$1, - ImageContentSchema: ImageContentSchema$1, - AudioContentSchema: AudioContentSchema$1, - ToolUseContentSchema: ToolUseContentSchema$1, - EmbeddedResourceSchema: EmbeddedResourceSchema$1, - ResourceLinkSchema: ResourceLinkSchema$1, - ContentBlockSchema: ContentBlockSchema$1, - PromptMessageSchema: PromptMessageSchema$1, - ToolAnnotationsSchema: ToolAnnotationsSchema$1, - ToolListChangedNotificationSchema: ToolListChangedNotificationSchema$1, - ModelHintSchema: ModelHintSchema$1, - ModelPreferencesSchema: ModelPreferencesSchema$1, - ToolChoiceSchema: ToolChoiceSchema$1, - BooleanSchemaSchema: BooleanSchemaSchema$1, - StringSchemaSchema: StringSchemaSchema$1, - NumberSchemaSchema: NumberSchemaSchema$1, - UntitledSingleSelectEnumSchemaSchema: UntitledSingleSelectEnumSchemaSchema$1, - TitledSingleSelectEnumSchemaSchema: TitledSingleSelectEnumSchemaSchema$1, - LegacyTitledEnumSchemaSchema: LegacyTitledEnumSchemaSchema$1, - SingleSelectEnumSchemaSchema: SingleSelectEnumSchemaSchema$1, - UntitledMultiSelectEnumSchemaSchema: UntitledMultiSelectEnumSchemaSchema$1, - TitledMultiSelectEnumSchemaSchema: TitledMultiSelectEnumSchemaSchema$1, - MultiSelectEnumSchemaSchema: MultiSelectEnumSchemaSchema$1, - EnumSchemaSchema: EnumSchemaSchema$1, - PrimitiveSchemaDefinitionSchema: PrimitiveSchemaDefinitionSchema$1, - ElicitRequestFormParamsSchema: ElicitRequestFormParamsSchema$1, - ResourceTemplateReferenceSchema: ResourceTemplateReferenceSchema$1, - PromptReferenceSchema: PromptReferenceSchema$1, - RootSchema: RootSchema$1, - ClientCapabilities2026Schema, - ServerCapabilities2026Schema, - RequestMetaEnvelopeSchema, - ToolSchema: ToolSchema$1, - ToolResultContentSchema: ToolResultContentSchema$1, - SamplingMessageContentBlockSchema: SamplingMessageContentBlockSchema$1, - SamplingMessageSchema: SamplingMessageSchema$1, - ResultTypeSchema, - ResultMetaSchema, - ResultSchema: ResultSchema$1, - PaginatedResultSchema: PaginatedResultSchema$1, - CallToolResultSchema: CallToolResultSchema$1, - ListToolsResultSchema: ListToolsResultSchema$1, - ListPromptsResultSchema: ListPromptsResultSchema$1, - GetPromptResultSchema: GetPromptResultSchema$1, - ListResourcesResultSchema: ListResourcesResultSchema$1, - ListResourceTemplatesResultSchema: ListResourceTemplatesResultSchema$1, - ReadResourceResultSchema: ReadResourceResultSchema$1, - CompleteResultSchema: CompleteResultSchema$1, - CacheableResultSchema, - DiscoverResultSchema: DiscoverResultSchema$1, - CreateMessageRequestParamsSchema: CreateMessageRequestParamsSchema$1, - CreateMessageRequestSchema: CreateMessageRequestSchema$1, - ListRootsRequestSchema: ListRootsRequestSchema$1, - CreateMessageResultSchema: CreateMessageResultSchema$1, - ListRootsResultSchema: ListRootsResultSchema$1, - ElicitResultSchema: ElicitResultSchema$1, - ElicitRequestURLParamsSchema: ElicitRequestURLParamsSchema$1, - ElicitRequestParamsSchema: ElicitRequestParamsSchema$1, - ElicitRequestSchema: ElicitRequestSchema$1, - InputRequestSchema, - InputResponseSchema, - InputRequestsSchema, - InputResponsesSchema, - InputRequiredResultSchema, - InputResponseRequestParamsSchema, - CallToolRequestSchema: CallToolRequestSchema$1, - ListToolsRequestSchema: ListToolsRequestSchema$1, - ListPromptsRequestSchema: ListPromptsRequestSchema$1, - GetPromptRequestSchema: GetPromptRequestSchema$1, - ListResourcesRequestSchema: ListResourcesRequestSchema$1, - ListResourceTemplatesRequestSchema: ListResourceTemplatesRequestSchema$1, - ReadResourceRequestSchema: ReadResourceRequestSchema$1, - CompleteRequestSchema: CompleteRequestSchema$1, - DiscoverRequestSchema: DiscoverRequestSchema$1, - SubscriptionFilterSchema: SubscriptionFilterSchema$1, - SubscriptionsListenRequestSchema: SubscriptionsListenRequestSchema$1, - SubscriptionsListenResultMetaSchema: SubscriptionsListenResultMetaSchema$1, - SubscriptionsListenResultSchema: SubscriptionsListenResultSchema$1, - dispatchRequestSchemas, - dispatchResultSchemas, - NotificationMetaSchema, - SubscriptionsAcknowledgedNotificationSchema: SubscriptionsAcknowledgedNotificationSchema$1, - CancelledNotificationParamsSchema: CancelledNotificationParamsSchema$1, - CancelledNotificationSchema: CancelledNotificationSchema$1, - notificationSchemas2026, - JSONRPCResultResponseSchema: wireResultResponse(ResultSchema$1), - CallToolResultResponseSchema: wireResultResponse(schemas_union([CallToolResultSchema$1, InputRequiredResultSchema])), - ListToolsResultResponseSchema: wireResultResponse(ListToolsResultSchema$1), - ListPromptsResultResponseSchema: wireResultResponse(ListPromptsResultSchema$1), - GetPromptResultResponseSchema: wireResultResponse(schemas_union([GetPromptResultSchema$1, InputRequiredResultSchema])), - ListResourcesResultResponseSchema: wireResultResponse(ListResourcesResultSchema$1), - ListResourceTemplatesResultResponseSchema: wireResultResponse(ListResourceTemplatesResultSchema$1), - ReadResourceResultResponseSchema: wireResultResponse(schemas_union([ReadResourceResultSchema$1, InputRequiredResultSchema])), - CompleteResultResponseSchema: wireResultResponse(CompleteResultSchema$1), - DiscoverResultResponseSchema: wireResultResponse(DiscoverResultSchema$1) - }; -} -let src_CX2iR2pK_memo; -/** -* Builds the era wire-schema set on first call and returns the same object -* thereafter. Module evaluation stays construction-free so importing the -* era codec/registry costs nothing until the first validation actually -* needs a schema; the registry, the codec, and the eager `schemas.ts` -* shim all pull through this memo, so reference identity holds across -* every consumer. -*/ -function buildSchemas2026() { - return src_CX2iR2pK_memo ??= build(); -} - -//#endregion -//#region ../core-internal/src/shared/resultCacheHints.ts -/** -* The operations whose results are cacheable on the 2026-07-28 revision (the -* `CacheableResult` extenders). This list is closed: no other operation's -* result ever receives cache fields from the SDK. -*/ -const CACHEABLE_RESULT_METHODS = [ - "tools/list", - "prompts/list", - "resources/list", - "resources/templates/list", - "resources/read", - "server/discover" -]; -/** Whether the given method's result is cacheable on the 2026-07-28 revision. */ -function isCacheableResultMethod(method) { - return CACHEABLE_RESULT_METHODS.includes(method); -} -/** -* The symbol-keyed carrier for a configured cache hint on a result object. -* Symbol properties are invisible to JSON serialization, so the carrier can be -* attached era-blind: only the 2026-era encode seam consumes it. -*/ -const RESULT_CACHE_HINT_FALLBACK = Symbol("modelcontextprotocol.resultCacheHintFallback"); -/** -* Attaches a configured cache hint to a result as the encode-time fallback. -* Returns the result unchanged when there is nothing to attach. When a more -* specific hint is already attached, the two hints are combined per field -* (most-specific-author-wins for each of `ttlMs` and `cacheScope`): the -* per-registration hint attached by the feature layer keeps every field it -* sets, and the server-level per-operation hint only fills the fields the -* more specific hint leaves unset. -*/ -function attachCacheHintFallback(result, hint) { - if (hint === void 0) return result; - const attached = result[RESULT_CACHE_HINT_FALLBACK]; - if (attached === void 0) return { - ...result, - [RESULT_CACHE_HINT_FALLBACK]: hint - }; - const merged = {}; - const ttlMs = attached.ttlMs ?? hint.ttlMs; - if (ttlMs !== void 0) merged.ttlMs = ttlMs; - const cacheScope = attached.cacheScope ?? hint.cacheScope; - if (cacheScope !== void 0) merged.cacheScope = cacheScope; - return { - ...result, - [RESULT_CACHE_HINT_FALLBACK]: merged - }; -} -/** Reads the configured cache-hint fallback attached to a result, if any. */ -function cacheHintFallbackOf(result) { - return result[RESULT_CACHE_HINT_FALLBACK]; -} -/** -* Whether a value is a valid `ttlMs`: a non-negative safe integer. Safe -* integers are required because the wire schemas validate `ttlMs` as an -* integer within `Number.MIN_SAFE_INTEGER`/`Number.MAX_SAFE_INTEGER`; a value -* outside that range is treated as invalid here so it falls through to the -* next author instead of being emitted and rejected downstream. -*/ -function isValidCacheTtlMs(value) { - return typeof value === "number" && Number.isSafeInteger(value) && value >= 0; -} -/** Whether a value is a valid `cacheScope`. */ -function isValidCacheScope(value) { - return value === "public" || value === "private"; -} -/** -* Validates a configured cache hint at configuration time. Throws a -* `RangeError` naming the offending field, so misconfiguration fails at -* startup/registration rather than silently degrading at encode time. -*/ -function assertValidCacheHint(hint, context) { - if (hint.ttlMs !== void 0 && !isValidCacheTtlMs(hint.ttlMs)) throw new RangeError(`Invalid cache hint for ${context}: ttlMs must be a non-negative safe integer (got ${String(hint.ttlMs)})`); - if (hint.cacheScope !== void 0 && !isValidCacheScope(hint.cacheScope)) throw new RangeError(`Invalid cache hint for ${context}: cacheScope must be 'public' or 'private' (got ${String(hint.cacheScope)})`); -} - -//#endregion -//#region ../core-internal/src/types/enums.ts -/** -* Error codes for protocol errors that cross the wire as JSON-RPC error responses. -* These follow the JSON-RPC specification and MCP-specific extensions. -*/ -let src_CX2iR2pK_ProtocolErrorCode = /* @__PURE__ */ function(ProtocolErrorCode$1) { - ProtocolErrorCode$1[ProtocolErrorCode$1["ParseError"] = -32700] = "ParseError"; - ProtocolErrorCode$1[ProtocolErrorCode$1["InvalidRequest"] = -32600] = "InvalidRequest"; - ProtocolErrorCode$1[ProtocolErrorCode$1["MethodNotFound"] = -32601] = "MethodNotFound"; - ProtocolErrorCode$1[ProtocolErrorCode$1["InvalidParams"] = -32602] = "InvalidParams"; - ProtocolErrorCode$1[ProtocolErrorCode$1["InternalError"] = -32603] = "InternalError"; - /** - * Resource not found. - * - * Receive-tolerated only: the SDK never EMITS `-32002` — `resources/read` - * misses answer `-32602` (Invalid Params) on every protocol revision per - * the 2026-07-28 spec MUST, and a handler-thrown `-32002` is mapped to - * `-32602` at the era encode seam. The member stays importable so clients - * can recognise `-32002` from peers built on earlier SDK releases (the - * spec's "clients SHOULD also accept `-32002`" backwards-compatibility - * clause). Throw `ResourceNotFoundError` instead. - */ - ProtocolErrorCode$1[ProtocolErrorCode$1["ResourceNotFound"] = -32002] = "ResourceNotFound"; - /** - * Processing the request requires a capability the client did not declare - * in the request's `clientCapabilities` (protocol revision 2026-07-28). - */ - ProtocolErrorCode$1[ProtocolErrorCode$1["MissingRequiredClientCapability"] = -32021] = "MissingRequiredClientCapability"; - /** - * The request's protocol version is unknown to the server or unsupported - * by it (protocol revision 2026-07-28). - */ - ProtocolErrorCode$1[ProtocolErrorCode$1["UnsupportedProtocolVersion"] = -32022] = "UnsupportedProtocolVersion"; - ProtocolErrorCode$1[ProtocolErrorCode$1["UrlElicitationRequired"] = -32042] = "UrlElicitationRequired"; - return ProtocolErrorCode$1; -}({}); - -//#endregion -//#region ../core-internal/src/types/errors.ts -/** -* Protocol errors are JSON-RPC errors that cross the wire as error responses. -* They use numeric error codes from the {@linkcode ProtocolErrorCode} enum. -* -* `instanceof` on this class (and its subclasses) is brand-matched, so it works -* across separately bundled copies of the SDK — e.g. an error constructed by -* `@modelcontextprotocol/client` matches the class re-exported by -* `@modelcontextprotocol/server` in the same process. -*/ -var src_CX2iR2pK_ProtocolError = class ProtocolError extends Error { - static { - Object.defineProperty(this, "mcpBrand", { value: "mcp.ProtocolError" }); - } - static [Symbol.hasInstance](value) { - return brandedHasInstance(this, value); - } - /** - * Brand-based type guard: equivalent to `value instanceof this`, as an - * explicit static predicate (the axios/AWS-SDK `isInstance` style). Reads - * the caller's own brand via `this`, so every branded subclass gets a - * correctly-scoped guard by inheritance. Must be invoked on the class — - * in callback position write `v => SdkError.isInstance(v)`, not - * `.filter(SdkError.isInstance)` (detached calls throw rather than - * silently matching nothing). - */ - static isInstance(value) { - 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 brandedHasInstance(this, value); - } - constructor(code, message, data) { - super(message); - this.code = code; - this.data = data; - this.name = "ProtocolError"; - stampErrorBrands(this, new.target); - } - /** - * Factory method to create the appropriate error type based on the error code and data - */ - static fromError(code, message, data) { - if (code === src_CX2iR2pK_ProtocolErrorCode.UrlElicitationRequired && data) { - const errorData = data; - if (errorData.elicitations) return new UrlElicitationRequiredError(errorData.elicitations, message); - } - if (code === src_CX2iR2pK_ProtocolErrorCode.UnsupportedProtocolVersion && data) { - const errorData = data; - if (Array.isArray(errorData.supported) && typeof errorData.requested === "string") return new src_CX2iR2pK_UnsupportedProtocolVersionError({ - supported: errorData.supported, - requested: errorData.requested - }, message); - } - if (code === src_CX2iR2pK_ProtocolErrorCode.InvalidParams || code === src_CX2iR2pK_ProtocolErrorCode.ResourceNotFound) { - const errorData = data; - if (typeof errorData?.uri === "string" && (code === src_CX2iR2pK_ProtocolErrorCode.ResourceNotFound || Object.keys(errorData).length === 1)) return new ResourceNotFoundError(errorData.uri, message); - } - if (code === src_CX2iR2pK_ProtocolErrorCode.MissingRequiredClientCapability && data) { - const errorData = data; - if (errorData.requiredCapabilities !== null && typeof errorData.requiredCapabilities === "object" && !Array.isArray(errorData.requiredCapabilities)) return new src_CX2iR2pK_MissingRequiredClientCapabilityError({ requiredCapabilities: errorData.requiredCapabilities }, message); - } - return new ProtocolError(code, message, data); - } -}; -/** -* Error type for a `resources/read` miss: the requested resource does not -* exist. The wire code is `-32602` (Invalid Params) on every protocol -* revision — the spec MUST for revision 2026-07-28, and the value the v1.x -* SDK has always emitted on earlier revisions. The error data echoes the -* requested URI. -* -* Recognise this error by checking `error.data` is exactly `{ uri: string }` -* (a `-32602` whose data carries `uri` and nothing else is resource-not-found; -* any other `-32602` is an ordinary Invalid Params). For backwards compatibility, clients should also -* accept `-32002` as resource not found — earlier SDK builds emitted that -* code, and {@linkcode ProtocolError.fromError} reconstructs this class for -* either code **when `error.data` carries `uri`** (a bare `-32002` without -* `data.uri` stays a generic {@linkcode ProtocolError}). `instanceof` checks -* are brand-matched and work across separately bundled copies of the SDK. -*/ -var ResourceNotFoundError = class extends src_CX2iR2pK_ProtocolError { - static { - Object.defineProperty(this, "mcpBrand", { value: "mcp.ResourceNotFoundError" }); - } - constructor(uri, message = `Resource not found: ${uri}`) { - super(src_CX2iR2pK_ProtocolErrorCode.InvalidParams, message, { uri }); - } - /** The URI that was requested and not found. */ - get uri() { - return this.data.uri; - } -}; -/** -* Specialized error type when a tool requires a URL mode elicitation. -* This makes it nicer for the client to handle since there is specific data to work with instead of just a code to check against. -*/ -var UrlElicitationRequiredError = class extends src_CX2iR2pK_ProtocolError { - static { - Object.defineProperty(this, "mcpBrand", { value: "mcp.UrlElicitationRequiredError" }); - } - constructor(elicitations, message = `URL elicitation${elicitations.length > 1 ? "s" : ""} required`) { - super(src_CX2iR2pK_ProtocolErrorCode.UrlElicitationRequired, message, { elicitations }); - } - get elicitations() { - return this.data?.elicitations ?? []; - } -}; -/** -* Error type for the `-32022` UnsupportedProtocolVersion protocol error (protocol -* revision 2026-07-28): the request's protocol version is unknown to the server or -* unsupported by it. -* -* The error data lists the protocol versions the receiver supports (`supported`), -* so the sender can choose a mutually supported version and retry, and echoes the -* version that was requested (`requested`). -*/ -var src_CX2iR2pK_UnsupportedProtocolVersionError = class extends src_CX2iR2pK_ProtocolError { - static { - Object.defineProperty(this, "mcpBrand", { value: "mcp.UnsupportedProtocolVersionError" }); - } - constructor(data, message = `Unsupported protocol version: ${data.requested}`) { - super(src_CX2iR2pK_ProtocolErrorCode.UnsupportedProtocolVersion, message, data); - } - /** - * Protocol versions the receiver supports. - */ - get supported() { - return this.data.supported; - } - /** - * The protocol version that was requested. - */ - get requested() { - return this.data.requested; - } -}; -/** -* Error type for the `-32021` MissingRequiredClientCapability protocol error -* (protocol revision 2026-07-28): processing the request requires a capability -* the client did not declare in the request's `clientCapabilities`. -* -* The error data lists the missing capabilities (`requiredCapabilities`) in -* the `ClientCapabilities` shape, so the client can see exactly what it would -* have to declare for the request to be served. On HTTP, the response status -* is `400 Bad Request`. -* -* Recognize this error by its code and `data.requiredCapabilities`, or by -* `instanceof` — checks are brand-matched and work across separately bundled -* copies of the SDK. -*/ -var src_CX2iR2pK_MissingRequiredClientCapabilityError = class extends src_CX2iR2pK_ProtocolError { - static { - Object.defineProperty(this, "mcpBrand", { value: "mcp.MissingRequiredClientCapabilityError" }); - } - constructor(data, message = `Missing required client capabilities: ${Object.keys(data.requiredCapabilities).join(", ")}`) { - super(src_CX2iR2pK_ProtocolErrorCode.MissingRequiredClientCapability, message, data); - } - /** - * The capabilities the server requires from the client to process the - * request (only the missing capabilities are listed). - */ - get requiredCapabilities() { - return this.data.requiredCapabilities; - } -}; - -//#endregion -//#region ../core-internal/src/wire/rev2026-07-28/encodeContract.ts -/** The default cache policy when neither the handler nor configuration provides one. */ -const DEFAULT_CACHE_TTL_MS = 0; -const DEFAULT_CACHE_SCOPE = "private"; -/** -* Request methods whose spec result vocabulary goes beyond `'complete'` on the -* 2026-07-28 revision: their results may be `input_required` (multi -* round-trip requests), so a handler-provided `resultType` passes through the -* stamp untouched. `subscriptions/listen` is NOT in this set: it never emits -* a JSON-RPC result — termination is stream close (HTTP) or -* `notifications/cancelled` (stdio) per the spec. -*/ -const EXTENDED_RESULT_TYPE_METHODS = [ - "tools/call", - "prompts/get", - "resources/read" -]; -/** -* Step 1 of the encode contract: ensure the outbound result carries the -* required `resultType` discriminator. -* -* - No handler-provided value → stamp `'complete'`. -* - Handler-provided `'complete'` → kept as-is. -* - Handler-provided non-`'complete'` value on a method whose vocabulary -* allows it ({@linkcode EXTENDED_RESULT_TYPE_METHODS}) → passes through. -* The value is forwarded verbatim — the wire vocabulary is an open union and -* the SDK does not validate the string, so emitting a `resultType` the -* negotiated revision does not define is the handler author's -* responsibility. -* - Handler-provided non-`'complete'` value on any other method → internal -* error (loud): the value would be mis-typed on the wire, and silently -* rewriting it would hide a server bug. -*/ -function stampResultType(method, result) { - const provided = result["resultType"]; - if (provided === void 0) return { - ...result, - resultType: "complete" - }; - if (provided === "complete") return result; - if (EXTENDED_RESULT_TYPE_METHODS.includes(method)) return result; - throw new src_CX2iR2pK_ProtocolError(src_CX2iR2pK_ProtocolErrorCode.InternalError, `Handler for ${method} returned resultType '${String(provided)}', but results of ${method} only support 'complete' on protocol revision 2026-07-28`); -} -/** -* Step 2 of the encode contract: fill the required `ttlMs`/`cacheScope` fields -* on cacheable results. -* -* Applies only when the (post-stamp) `resultType` is `'complete'` and the -* method is one of the cacheable operations; everything else is returned -* untouched apart from removing the configured-hint carrier. Field resolution -* is per field, most specific author first: a valid handler-returned value, -* then the configured cache hint attached by the server layer, then the -* defaults. Handler-returned values are validated at encode time (`ttlMs` -* must be a non-negative integer, `cacheScope` must be `'public'` or -* `'private'`); invalid values are ignored rather than emitted. -*/ -function fillCacheFields(method, result) { - const fallback = cacheHintFallbackOf(result); - if (result["resultType"] !== "complete" || !isCacheableResultMethod(method)) return fallback === void 0 ? result : stripCacheHintFallback(result); - const provided = result; - const ttlMs = isValidCacheTtlMs(provided["ttlMs"]) ? provided["ttlMs"] : resolveTtlMs(fallback); - const cacheScope = isValidCacheScope(provided["cacheScope"]) ? provided["cacheScope"] : resolveCacheScope(fallback); - const filled = { - ...provided, - ttlMs, - cacheScope - }; - delete filled[RESULT_CACHE_HINT_FALLBACK]; - return filled; -} -function isPlainObject$5(value) { - return value !== null && typeof value === "object" && !Array.isArray(value); -} -/** -* Step 3 of the encode contract: stamp the server's identity into the -* result's `_meta` under `io.modelcontextprotocol/serverInfo` (spec PR #3002: -* servers SHOULD include it on every response). -* -* - No `serverInfo` supplied (a client instance, or a hand-constructed -* protocol object) → identity function. -* - The result's `_meta` already carries the key → kept as-is (the handler -* is the more specific author; mirrors the cache-fill resolution order). -* - A present-but-non-object `_meta` (a dynamic-caller bug) → kept as-is: -* the stamp never rewrites handler material, and the malformed value fails -* loudly at the peer instead of being silently replaced here. -* - Otherwise → the key is added, preserving any other `_meta` entries. -* -* Runs for every result regardless of `resultType`: the anchor types -* `Result._meta` as `ResultMetaObject` on all results, `input_required` -* included. -*/ -function stampServerInfoMeta(result, serverInfo) { - if (serverInfo === void 0) return result; - const meta = result["_meta"]; - if (meta === void 0) return { - ...result, - _meta: { [auth_CUe6YdwF_SERVER_INFO_META_KEY]: serverInfo } - }; - if (!isPlainObject$5(meta)) return result; - if (meta[auth_CUe6YdwF_SERVER_INFO_META_KEY] !== void 0) return result; - return { - ...result, - _meta: { - ...meta, - [auth_CUe6YdwF_SERVER_INFO_META_KEY]: serverInfo - } - }; -} -function resolveTtlMs(fallback) { - return fallback !== void 0 && isValidCacheTtlMs(fallback.ttlMs) ? fallback.ttlMs : DEFAULT_CACHE_TTL_MS; -} -function resolveCacheScope(fallback) { - return fallback !== void 0 && isValidCacheScope(fallback.cacheScope) ? fallback.cacheScope : DEFAULT_CACHE_SCOPE; -} -function stripCacheHintFallback(result) { - const copy = { ...result }; - delete copy[RESULT_CACHE_HINT_FALLBACK]; - return copy; -} - -//#endregion -//#region ../core-internal/src/wire/rev2026-07-28/inputRequired.ts -/** -* In-band input-request vocabulary of the 2026-07-28 revision (SEP-2322 -* multi round-trip requests), dispatch view. -* -* The three former server→client wire requests (`elicitation/create`, -* `sampling/createMessage`, `roots/list`) are NOT wire request methods on -* this revision — they are demoted to de-JSON-RPC'd payloads embedded in an -* `input_required` result. The multi-round-trip driver dispatches those -* embedded payloads to the client's registered handlers through the normal -* handler machinery, and these are the schemas that dispatch parses them -* with: lenient where the anchor's wire-true artifacts are strict (an -* embedded request never carries the per-request `_meta` envelope), exact -* where the vocabulary forks (the sampling shapes compose the forked -* SamplingMessage/Tool payloads). -* -* Registry membership is intentionally NOT granted here — these methods stay -* absent from the 2026-era request registry (a peer sending one as a wire -* request still gets −32601 by absence). Only the codec's -* `inputRequestSchema`/`inputResponseSchema` accessors expose them. -*/ -/** The embedded input-request methods of the 2026-07-28 revision. */ -const INPUT_REQUEST_METHODS_2026 = [ - "elicitation/create", - "sampling/createMessage", - "roots/list" -]; -let maps; -function inputSchemaMaps() { - if (maps) return maps; - const s = buildSchemas2026(); - maps = { - request: { - "elicitation/create": schemas_object({ - method: literal("elicitation/create"), - params: s.ElicitRequestParamsSchema - }), - "sampling/createMessage": schemas_object({ - method: literal("sampling/createMessage"), - params: s.CreateMessageRequestParamsSchema - }), - "roots/list": schemas_object({ - method: literal("roots/list"), - params: looseObject({}).optional() - }) - }, - response: { - "elicitation/create": s.ElicitResultSchema, - "sampling/createMessage": s.CreateMessageResultSchema, - "roots/list": s.ListRootsResultSchema - } - }; - return maps; -} -/** -* Forces the lazy embedded-request maps (and, through them, the era's schema -* memo). Warm-up hook for `preloadSchemas()` — no-op once the maps exist. -*/ -function warmInputSchemaMaps2026() { - inputSchemaMaps(); -} -function isInputRequestMethod2026(method) { - return INPUT_REQUEST_METHODS_2026.includes(method); -} -function getInputRequestSchema2026(method) { - return isInputRequestMethod2026(method) ? inputSchemaMaps().request[method] : void 0; -} -function getInputResponseSchema2026(method) { - return isInputRequestMethod2026(method) ? inputSchemaMaps().response[method] : void 0; -} - -//#endregion -//#region ../core-internal/src/wire/rev2026-07-28/registry.ts -const requestMethodKeys = { - "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 -}; -const notificationMethodKeys = { - "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 -}; -/** The 2026-era request-method set (registry membership = the deletion story). */ -function hasRequestMethod2026(method) { - return Object.prototype.hasOwnProperty.call(requestMethodKeys, method); -} -/** The 2026-era notification-method set. */ -function hasNotificationMethod2026(method) { - return Object.prototype.hasOwnProperty.call(notificationMethodKeys, method); -} -/** Result-map membership (same key set as the request map on this era). */ -function hasResultMethod2026(method) { - return Object.prototype.hasOwnProperty.call(requestMethodKeys, method); -} -function getRequestSchema2026(method) { - return hasRequestMethod2026(method) ? buildSchemas2026().dispatchRequestSchemas[method] : void 0; -} -function getResultSchema2026(method) { - return hasResultMethod2026(method) ? buildSchemas2026().dispatchResultSchemas[method] : void 0; -} -function getNotificationSchema2026(method) { - return hasNotificationMethod2026(method) ? buildSchemas2026().notificationSchemas2026[method] : void 0; -} -/** Registry method lists (for the spec-method universe and the CI registry-diff oracle). */ -const rev2026RequestMethods = Object.keys(requestMethodKeys); -const rev2026NotificationMethods = Object.keys(notificationMethodKeys); - -//#endregion -//#region ../core-internal/src/wire/rev2026-07-28/codec.ts -function isPlainObject$4(value) { - return value !== null && typeof value === "object" && !Array.isArray(value); -} -/** Tri-state wrap of an optional Zod schema lookup (the function-only contract). */ -function triState(schema, raw) { - if (schema === void 0) return { - ok: false, - reason: "not-in-era" - }; - const parsed = schema.safeParse(raw); - return parsed.success ? { - ok: true, - value: parsed.data - } : { - ok: false, - reason: "invalid", - message: String(parsed.error) - }; -} -const NOT_IN_ERA = { - ok: false, - reason: "not-in-era" -}; -/** -* The reserved `_meta` keys an envelope must carry on this era (in reporting -* order). `clientInfo` is NOT here: spec PR #3002 demoted it to SHOULD, so a -* request without it is accepted (a present-but-malformed value still fails -* the envelope schema parse below). -*/ -const REQUIRED_ENVELOPE_KEYS = [auth_CUe6YdwF_PROTOCOL_VERSION_META_KEY, auth_CUe6YdwF_CLIENT_CAPABILITIES_META_KEY]; -/** Strip the known deleted-field set from an outbound result (Q1-SD3 iii). */ -function enforceDeletedFields(method, result) { - let next = result; - let copied = false; - const copy = () => { - if (!copied) { - next = { ...next }; - copied = true; - } - return next; - }; - const tools = result.tools; - if (method === "tools/list" && Array.isArray(tools) && tools.some((tool) => isPlainObject$4(tool) && "execution" in tool)) copy().tools = tools.map((tool) => { - if (!isPlainObject$4(tool) || !("execution" in tool)) return tool; - const rest = { ...tool }; - delete rest["execution"]; - return rest; - }); - const capabilities = result.capabilities; - if (isPlainObject$4(capabilities) && "tasks" in capabilities) { - const rest = { ...capabilities }; - delete rest["tasks"]; - copy().capabilities = rest; - } - return next; -} -const rev2026Codec = { - era: "2026-07-28", - hasRequestMethod: hasRequestMethod2026, - hasNotificationMethod: hasNotificationMethod2026, - hasInputRequestMethod: (method) => getInputRequestSchema2026(method) !== void 0, - validateRequest: (method, raw) => triState(getRequestSchema2026(method), raw), - validateResult: (method, raw) => triState(getResultSchema2026(method), raw), - validateNotification: (method, raw) => triState(getNotificationSchema2026(method), raw), - validateInputRequest: (method, raw) => triState(getInputRequestSchema2026(method), raw), - validateInputResponse: (method, raw) => triState(getInputResponseSchema2026(method), raw), - samplingResultVariant: () => NOT_IN_ERA, - outboundEnvelope(material) { - return { - [auth_CUe6YdwF_PROTOCOL_VERSION_META_KEY]: material.protocolVersion, - [auth_CUe6YdwF_CLIENT_INFO_META_KEY]: material.clientInfo, - [auth_CUe6YdwF_CLIENT_CAPABILITIES_META_KEY]: material.clientCapabilities, - ...material.logLevel !== void 0 && { [LOG_LEVEL_META_KEY]: material.logLevel } - }; - }, - validateEnvelopeMeta(meta) { - const issues = []; - for (const key of REQUIRED_ENVELOPE_KEYS) if (!(key in meta)) issues.push({ - key, - problem: "missing" - }); - const parsed = buildSchemas2026().RequestMetaEnvelopeSchema.safeParse(meta); - if (!parsed.success) for (const issue of parsed.error.issues) { - const path = issue.path.map(String); - const key = path.length > 0 ? path.join(".") : "_meta"; - if (path.length === 1 && issues.some((existing) => existing.key === key && existing.problem === "missing")) continue; - issues.push({ - key, - problem: issue.message - }); - } - return issues; - }, - projectCallToolResult: (result) => appendTextFallbackForNonObject(result), - inputRequestSchema: getInputRequestSchema2026, - decodeResult(method, raw) { - if (!isPlainObject$4(raw)) return { - kind: "invalid", - error: new src_CX2iR2pK_SdkError(src_CX2iR2pK_SdkErrorCode.InvalidResult, `Invalid result for ${method}: not an object`, { method }) - }; - const rawResultType = raw["resultType"]; - if (rawResultType === void 0) return { - kind: "invalid", - error: new src_CX2iR2pK_SdkError(src_CX2iR2pK_SdkErrorCode.InvalidResult, `Invalid result for ${method}: missing required resultType — servers implementing protocol revision 2026-07-28 MUST include it (the absent-means-complete bridge applies only to earlier-revision servers)`, { - method, - violation: "missing-resultType" - }) - }; - if (typeof rawResultType !== "string") return { - kind: "invalid", - error: new src_CX2iR2pK_SdkError(src_CX2iR2pK_SdkErrorCode.InvalidResult, `Invalid result for ${method}: non-string resultType`, { - method, - resultType: rawResultType - }) - }; - if (rawResultType === "input_required") { - const rawInputRequests = raw["inputRequests"]; - const inputRequests = isPlainObject$4(rawInputRequests) ? rawInputRequests : {}; - const requestState = raw["requestState"]; - if (Object.keys(inputRequests).length === 0 && typeof requestState !== "string") return { - kind: "invalid", - error: new src_CX2iR2pK_SdkError(src_CX2iR2pK_SdkErrorCode.InvalidResult, `Invalid result for ${method}: input_required carries neither inputRequests nor requestState (every input_required result must include at least one of the two)`, { - method, - violation: "input-required-missing-both" - }) - }; - return { - kind: "input_required", - inputRequests, - ...typeof requestState === "string" && { requestState } - }; - } - if (rawResultType !== "complete") return { - kind: "invalid", - error: new src_CX2iR2pK_SdkError(src_CX2iR2pK_SdkErrorCode.UnsupportedResultType, `Unsupported result type '${rawResultType}' for ${method}`, { - resultType: rawResultType, - method - }) - }; - const wireResultSchemas = getWireResultSchemas(); - const wireSchema = Object.hasOwn(wireResultSchemas, method) ? wireResultSchemas[method] : void 0; - if (wireSchema !== void 0) { - const parsed = wireSchema.safeParse(raw); - if (!parsed.success) return { - kind: "invalid", - error: new src_CX2iR2pK_SdkError(src_CX2iR2pK_SdkErrorCode.InvalidResult, `Invalid result for ${method}: ${parsed.error}`, { method }) - }; - } - const lifted = { ...raw }; - delete lifted["resultType"]; - return { - kind: "complete", - result: lifted - }; - }, - encodeResult(method, result, serverInfo) { - return stampServerInfoMeta(fillCacheFields(method, stampResultType(method, enforceDeletedFields(method, result))), serverInfo); - }, - encodeErrorCode: (code) => code === -32002 ? -32602 : code, - checkInboundEnvelope(material) { - if (material.envelope === void 0) return "Request is missing the required _meta envelope for protocol revision 2026-07-28 (io.modelcontextprotocol/protocolVersion, io.modelcontextprotocol/clientCapabilities)"; - const parsed = buildSchemas2026().RequestMetaEnvelopeSchema.safeParse(material.envelope); - if (!parsed.success) return `Invalid _meta envelope for protocol revision 2026-07-28: ${parsed.error.issues.map((issue) => issue.message).join("; ")}`; - } -}; -/** Wire-true result wrappers consulted by decode step 2, keyed by method — -* built once through the era's schema memo on the first decode. */ -let wireResultSchemasMemo; -function getWireResultSchemas() { - if (wireResultSchemasMemo) return wireResultSchemasMemo; - const s = buildSchemas2026(); - wireResultSchemasMemo = { - "tools/call": s.CallToolResultSchema, - "tools/list": s.ListToolsResultSchema, - "prompts/get": s.GetPromptResultSchema, - "prompts/list": s.ListPromptsResultSchema, - "resources/list": s.ListResourcesResultSchema, - "resources/templates/list": s.ListResourceTemplatesResultSchema, - "resources/read": s.ReadResourceResultSchema, - "completion/complete": s.CompleteResultSchema, - "server/discover": s.DiscoverResultSchema - }; - return wireResultSchemasMemo; -} -/** -* Forces the lazy wire-result wrapper map (and, through it, the era's schema -* memo). Warm-up hook for `preloadSchemas()` — no-op once the map exists. -*/ -function warmWireResultSchemas2026() { - getWireResultSchemas(); -} - -//#endregion -//#region ../core-internal/src/wire/codec.ts -/** -* The modern wire revision literal. Internal only — deliberately NOT a public -* constant (G-D2-4: no public modern-version constant ships before era-aware -* list semantics exist). -*/ -const src_CX2iR2pK_MODERN_WIRE_REVISION = "2026-07-28"; -/** -* Era resolution, many-to-one (Q1-SD1): every modern-era revision -* (`>= 2026-07-28`) → the 2026-era codec; every legacy revision (the five -* `SUPPORTED_PROTOCOL_VERSIONS`) and `undefined`/unknown → the 2025-era -* codec (the DV-13 default posture — hand-constructed instances and -* unclassified traffic are legacy-era). This is the same era predicate the -* rest of the SDK uses ({@link isModernProtocolVersion}); a pinned modern -* revision other than the literal '2026-07-28' must still resolve modern. -*/ -function src_CX2iR2pK_codecForVersion(version) { - return version !== void 0 && isModernProtocolVersion(version) ? rev2026Codec : rev2025Codec; -} -/** -* The wire era an edge classification names (Q2 — produced at the -* transport/entry edge; this layer only CONSUMES it). The dispatch funnel no -* longer resolves a codec FROM the classification: era is instance state, and -* a classified inbound message is VALIDATED against the instance era — a -* mismatch is an entry/routing error, never a per-message era switch. The -* exact `revision` wins over the coarse era flag when both are present. -*/ -function classifiedWireEra(classification) { - if (classification.revision !== void 0) return src_CX2iR2pK_codecForVersion(classification.revision).era; - return classification.era === "modern" ? rev2026Codec.era : rev2025Codec.era; -} -/** -* The derived spec-method universe: the union of every codec registry. A -* method in this set is era-gated at dispatch and send time; a method outside -* it is a consumer-owned extension method (era-blind, schema-explicit). -* Derived from the registries — never hand-curated (the LEGACY_ONLY_METHODS -* table class is exactly what registry membership replaces). -*/ -function isSpecRequestMethod(method) { - return ALL_CODECS.some((codec) => codec.hasRequestMethod(method)); -} -function isSpecNotificationMethod(method) { - return ALL_CODECS.some((codec) => codec.hasNotificationMethod(method)); -} -const ALL_CODECS = [rev2025Codec, rev2026Codec]; - -//#endregion -//#region ../core-internal/src/shared/envelope.ts -/** -* Per-request `_meta` envelope claim helpers (protocol revision 2026-07-28). -* -* Pure, value-returning helpers used by the inbound HTTP classifier -* (`classifyInboundRequest`): claim detection and envelope validation with -* self-identifying issues. The envelope schema itself stays the wire layer's -* single source of truth (`RequestMetaEnvelopeSchema`); this module only maps -* its outcomes into the shapes the validation ladder emits. -* -* Claim detection is deliberately narrow: a message claims the 2026-07-28 -* envelope mechanism if and only if the reserved protocol-version `_meta` key -* is present in `params._meta`. Other reserved keys (client info, client -* capabilities, log level), a bare `progressToken`, or unrelated keys under -* the `io.modelcontextprotocol/` prefix do NOT constitute a claim on their -* own — but once the claim key is present, a malformed envelope is a -* validation error, never a silent fall back to legacy handling. -* -* The wire-exact envelope schema, the required-key set, and the per-key issue -* mapping live in the wire layer (the 2026-era codec's `validateEnvelopeMeta`). -* This module never reaches into a per-revision wire module directly. -*/ -function isPlainObject$3(value) { - return value !== null && typeof value === "object" && !Array.isArray(value); -} -/** The `_meta` object of a message's params, when present. */ -function src_CX2iR2pK_requestMetaOf(params) { - if (!isPlainObject$3(params)) return void 0; - const meta = params["_meta"]; - return isPlainObject$3(meta) ? meta : void 0; -} -/** -* Whether a message's params carry the per-request envelope claim: the -* reserved protocol-version `_meta` key is present (regardless of whether the -* rest of the envelope is valid — validation is a separate, later step). -*/ -function src_CX2iR2pK_hasEnvelopeClaim(params) { - const meta = src_CX2iR2pK_requestMetaOf(params); - return meta !== void 0 && PROTOCOL_VERSION_META_KEY in meta; -} -/** -* The protocol version named by a message's envelope claim, when the claim is -* present and carries a string value. A present claim with a non-string value -* still counts as a claim ({@linkcode hasEnvelopeClaim}); it surfaces as a -* validation issue instead of a version. -*/ -function src_CX2iR2pK_envelopeClaimVersion(params) { - const value = src_CX2iR2pK_requestMetaOf(params)?.[PROTOCOL_VERSION_META_KEY]; - return typeof value === "string" ? value : void 0; -} -/** -* Validates a request's `_meta` object as a 2026-07-28 per-request envelope -* and reports problems as self-identifying issues (which key, what problem). -* -* Returns an empty array when the envelope is valid. Missing required keys are -* reported first (as `problem: 'missing'`), then schema violations inside -* present keys, in a stable order. -*/ -function src_CX2iR2pK_validateEnvelopeMeta(meta) { - return src_CX2iR2pK_codecForVersion(src_CX2iR2pK_MODERN_WIRE_REVISION).validateEnvelopeMeta(meta); -} - -//#endregion -//#region ../core-internal/src/types/schemas.ts -var schemas_exports = /* @__PURE__ */ __exportAll({ - AnnotationsSchema: () => AnnotationsSchema, - AudioContentSchema: () => AudioContentSchema, - BaseMetadataSchema: () => BaseMetadataSchema, - BaseRequestParamsSchema: () => BaseRequestParamsSchema, - BlobResourceContentsSchema: () => BlobResourceContentsSchema, - BooleanSchemaSchema: () => BooleanSchemaSchema, - CallToolRequestParamsSchema: () => CallToolRequestParamsSchema, - CallToolRequestSchema: () => CallToolRequestSchema, - CallToolResultSchema: () => auth_CUe6YdwF_CallToolResultSchema, - CancelTaskRequestSchema: () => CancelTaskRequestSchema, - CancelTaskResultSchema: () => CancelTaskResultSchema, - CancelledNotificationParamsSchema: () => CancelledNotificationParamsSchema, - CancelledNotificationSchema: () => CancelledNotificationSchema, - ClientCapabilitiesSchema: () => ClientCapabilitiesSchema, - ClientNotificationSchema: () => ClientNotificationSchema, - ClientRequestSchema: () => ClientRequestSchema, - ClientResultSchema: () => ClientResultSchema, - ClientTasksCapabilitySchema: () => ClientTasksCapabilitySchema, - CompatibilityCallToolResultSchema: () => CompatibilityCallToolResultSchema, - CompleteRequestParamsSchema: () => CompleteRequestParamsSchema, - CompleteRequestSchema: () => CompleteRequestSchema, - CompleteResultSchema: () => CompleteResultSchema, - ContentBlockSchema: () => ContentBlockSchema, - CreateMessageRequestParamsSchema: () => CreateMessageRequestParamsSchema, - CreateMessageRequestSchema: () => CreateMessageRequestSchema, - CreateMessageResultSchema: () => CreateMessageResultSchema, - CreateMessageResultWithToolsSchema: () => CreateMessageResultWithToolsSchema, - CreateTaskResultSchema: () => CreateTaskResultSchema, - CursorSchema: () => CursorSchema, - DiscoverRequestSchema: () => DiscoverRequestSchema, - DiscoverResultSchema: () => DiscoverResultSchema, - ElicitRequestFormParamsSchema: () => ElicitRequestFormParamsSchema, - ElicitRequestParamsSchema: () => ElicitRequestParamsSchema, - ElicitRequestSchema: () => ElicitRequestSchema, - ElicitRequestURLParamsSchema: () => ElicitRequestURLParamsSchema, - ElicitResultSchema: () => ElicitResultSchema, - ElicitationCompleteNotificationParamsSchema: () => ElicitationCompleteNotificationParamsSchema, - ElicitationCompleteNotificationSchema: () => ElicitationCompleteNotificationSchema, - EmbeddedResourceSchema: () => EmbeddedResourceSchema, - EmptyResultSchema: () => EmptyResultSchema, - EnumSchemaSchema: () => EnumSchemaSchema, - GetPromptRequestParamsSchema: () => GetPromptRequestParamsSchema, - GetPromptRequestSchema: () => GetPromptRequestSchema, - GetPromptResultSchema: () => GetPromptResultSchema, - GetTaskPayloadRequestSchema: () => GetTaskPayloadRequestSchema, - GetTaskPayloadResultSchema: () => GetTaskPayloadResultSchema, - GetTaskRequestSchema: () => GetTaskRequestSchema, - GetTaskResultSchema: () => GetTaskResultSchema, - IconSchema: () => IconSchema, - IconsSchema: () => IconsSchema, - ImageContentSchema: () => ImageContentSchema, - ImplementationSchema: () => ImplementationSchema, - InitializeRequestParamsSchema: () => InitializeRequestParamsSchema, - InitializeRequestSchema: () => auth_CUe6YdwF_InitializeRequestSchema, - InitializeResultSchema: () => InitializeResultSchema, - InitializedNotificationSchema: () => auth_CUe6YdwF_InitializedNotificationSchema, - JSONArraySchema: () => JSONArraySchema, - JSONObjectSchema: () => JSONObjectSchema, - JSONRPCErrorResponseSchema: () => JSONRPCErrorResponseSchema, - JSONRPCMessageSchema: () => auth_CUe6YdwF_JSONRPCMessageSchema, - JSONRPCNotificationSchema: () => JSONRPCNotificationSchema, - JSONRPCRequestSchema: () => JSONRPCRequestSchema, - JSONRPCResponseSchema: () => auth_CUe6YdwF_JSONRPCResponseSchema, - JSONRPCResultResponseSchema: () => JSONRPCResultResponseSchema, - JSONValueSchema: () => JSONValueSchema, - LegacyTitledEnumSchemaSchema: () => LegacyTitledEnumSchemaSchema, - ListChangedOptionsBaseSchema: () => ListChangedOptionsBaseSchema, - ListPromptsRequestSchema: () => ListPromptsRequestSchema, - ListPromptsResultSchema: () => ListPromptsResultSchema, - ListResourceTemplatesRequestSchema: () => ListResourceTemplatesRequestSchema, - ListResourceTemplatesResultSchema: () => ListResourceTemplatesResultSchema, - ListResourcesRequestSchema: () => ListResourcesRequestSchema, - ListResourcesResultSchema: () => ListResourcesResultSchema, - ListRootsRequestSchema: () => ListRootsRequestSchema, - ListRootsResultSchema: () => ListRootsResultSchema, - ListTasksRequestSchema: () => ListTasksRequestSchema, - ListTasksResultSchema: () => ListTasksResultSchema, - ListToolsRequestSchema: () => ListToolsRequestSchema, - ListToolsResultSchema: () => ListToolsResultSchema, - LoggingLevelSchema: () => LoggingLevelSchema, - LoggingMessageNotificationParamsSchema: () => LoggingMessageNotificationParamsSchema, - LoggingMessageNotificationSchema: () => LoggingMessageNotificationSchema, - ModelHintSchema: () => ModelHintSchema, - ModelPreferencesSchema: () => ModelPreferencesSchema, - MultiSelectEnumSchemaSchema: () => MultiSelectEnumSchemaSchema, - NotificationSchema: () => NotificationSchema, - NotificationsParamsSchema: () => NotificationsParamsSchema, - NumberSchemaSchema: () => NumberSchemaSchema, - PaginatedRequestParamsSchema: () => PaginatedRequestParamsSchema, - PaginatedRequestSchema: () => PaginatedRequestSchema, - PaginatedResultSchema: () => PaginatedResultSchema, - PingRequestSchema: () => PingRequestSchema, - PrimitiveSchemaDefinitionSchema: () => PrimitiveSchemaDefinitionSchema, - ProgressNotificationParamsSchema: () => ProgressNotificationParamsSchema, - ProgressNotificationSchema: () => ProgressNotificationSchema, - ProgressSchema: () => ProgressSchema, - ProgressTokenSchema: () => ProgressTokenSchema, - PromptArgumentSchema: () => PromptArgumentSchema, - PromptListChangedNotificationSchema: () => PromptListChangedNotificationSchema, - PromptMessageSchema: () => PromptMessageSchema, - PromptReferenceSchema: () => PromptReferenceSchema, - PromptSchema: () => PromptSchema, - ReadResourceRequestParamsSchema: () => ReadResourceRequestParamsSchema, - ReadResourceRequestSchema: () => ReadResourceRequestSchema, - ReadResourceResultSchema: () => ReadResourceResultSchema, - RelatedTaskMetadataSchema: () => RelatedTaskMetadataSchema, - RequestIdSchema: () => RequestIdSchema, - RequestMetaSchema: () => RequestMetaSchema, - RequestSchema: () => RequestSchema, - ResourceContentsSchema: () => ResourceContentsSchema, - ResourceLinkSchema: () => ResourceLinkSchema, - ResourceListChangedNotificationSchema: () => ResourceListChangedNotificationSchema, - ResourceRequestParamsSchema: () => ResourceRequestParamsSchema, - ResourceSchema: () => ResourceSchema, - ResourceTemplateReferenceSchema: () => ResourceTemplateReferenceSchema, - ResourceTemplateSchema: () => ResourceTemplateSchema, - ResourceUpdatedNotificationParamsSchema: () => ResourceUpdatedNotificationParamsSchema, - ResourceUpdatedNotificationSchema: () => ResourceUpdatedNotificationSchema, - ResultMetaObjectSchema: () => ResultMetaObjectSchema, - ResultSchema: () => ResultSchema, - RoleSchema: () => RoleSchema, - RootSchema: () => RootSchema, - RootsListChangedNotificationSchema: () => RootsListChangedNotificationSchema, - SamplingContentSchema: () => SamplingContentSchema, - SamplingMessageContentBlockSchema: () => SamplingMessageContentBlockSchema, - SamplingMessageSchema: () => SamplingMessageSchema, - ServerCapabilitiesSchema: () => ServerCapabilitiesSchema, - ServerNotificationSchema: () => ServerNotificationSchema, - ServerRequestSchema: () => ServerRequestSchema, - ServerResultSchema: () => ServerResultSchema, - ServerTasksCapabilitySchema: () => ServerTasksCapabilitySchema, - SetLevelRequestParamsSchema: () => SetLevelRequestParamsSchema, - SetLevelRequestSchema: () => SetLevelRequestSchema, - SingleSelectEnumSchemaSchema: () => SingleSelectEnumSchemaSchema, - StringSchemaSchema: () => StringSchemaSchema, - SubscribeRequestParamsSchema: () => SubscribeRequestParamsSchema, - SubscribeRequestSchema: () => SubscribeRequestSchema, - SubscriptionFilterSchema: () => SubscriptionFilterSchema, - SubscriptionsAcknowledgedNotificationParamsSchema: () => SubscriptionsAcknowledgedNotificationParamsSchema, - SubscriptionsAcknowledgedNotificationSchema: () => SubscriptionsAcknowledgedNotificationSchema, - SubscriptionsListenRequestParamsSchema: () => SubscriptionsListenRequestParamsSchema, - SubscriptionsListenRequestSchema: () => SubscriptionsListenRequestSchema, - SubscriptionsListenResultMetaSchema: () => SubscriptionsListenResultMetaSchema, - SubscriptionsListenResultSchema: () => SubscriptionsListenResultSchema, - TaskAugmentedRequestParamsSchema: () => auth_CUe6YdwF_TaskAugmentedRequestParamsSchema, - TaskCreationParamsSchema: () => TaskCreationParamsSchema, - TaskMetadataSchema: () => TaskMetadataSchema, - TaskSchema: () => TaskSchema, - TaskStatusNotificationParamsSchema: () => TaskStatusNotificationParamsSchema, - TaskStatusNotificationSchema: () => TaskStatusNotificationSchema, - TaskStatusSchema: () => TaskStatusSchema, - TextContentSchema: () => TextContentSchema, - TextResourceContentsSchema: () => TextResourceContentsSchema, - TitledMultiSelectEnumSchemaSchema: () => TitledMultiSelectEnumSchemaSchema, - TitledSingleSelectEnumSchemaSchema: () => TitledSingleSelectEnumSchemaSchema, - ToolAnnotationsSchema: () => ToolAnnotationsSchema, - ToolChoiceSchema: () => ToolChoiceSchema, - ToolExecutionSchema: () => ToolExecutionSchema, - ToolListChangedNotificationSchema: () => ToolListChangedNotificationSchema, - ToolResultContentSchema: () => ToolResultContentSchema, - ToolSchema: () => ToolSchema, - ToolUseContentSchema: () => ToolUseContentSchema, - UnsubscribeRequestParamsSchema: () => UnsubscribeRequestParamsSchema, - UnsubscribeRequestSchema: () => UnsubscribeRequestSchema, - UntitledMultiSelectEnumSchemaSchema: () => UntitledMultiSelectEnumSchemaSchema, - UntitledSingleSelectEnumSchemaSchema: () => UntitledSingleSelectEnumSchemaSchema -}); - -//#endregion -//#region ../core-internal/src/types/guards.ts -/** -* Validates and parses an unknown value as a JSON-RPC message. -* -* Use this to validate incoming messages in custom transport implementations. -* Throws if the value does not conform to the JSON-RPC message schema. -* -* @param value - The value to validate (typically a parsed JSON object). -* @returns The validated {@linkcode JSONRPCMessage}. -* @throws If validation fails. -*/ -function parseJSONRPCMessage(value) { - return JSONRPCMessageSchema.parse(value); -} -const src_CX2iR2pK_isJSONRPCRequest = (value) => JSONRPCRequestSchema.safeParse(value).success; -const src_CX2iR2pK_isJSONRPCNotification = (value) => JSONRPCNotificationSchema.safeParse(value).success; -/** -* Checks if a value is a valid {@linkcode JSONRPCResultResponse}. -* @param value - The value to check. -* -* @returns True if the value is a valid {@linkcode JSONRPCResultResponse}, false otherwise. -*/ -const src_CX2iR2pK_isJSONRPCResultResponse = (value) => JSONRPCResultResponseSchema.safeParse(value).success; -/** -* Checks if a value is a valid {@linkcode JSONRPCErrorResponse}. -* @param value - The value to check. -* -* @returns True if the value is a valid {@linkcode JSONRPCErrorResponse}, false otherwise. -*/ -const src_CX2iR2pK_isJSONRPCErrorResponse = (value) => JSONRPCErrorResponseSchema.safeParse(value).success; -/** -* Checks if a value is a valid {@linkcode JSONRPCResponse} (either a result or error response). -* @param value - The value to check. -* -* @returns True if the value is a valid {@linkcode JSONRPCResponse}, false otherwise. -*/ -const isJSONRPCResponse = (value) => JSONRPCResponseSchema.safeParse(value).success; -/** -* Checks if a value is a valid {@linkcode CallToolResult}. -* -* This is a consumer-side VALUE check against the neutral model, not a wire -* validator: a raw wire object that additionally carries wire-only members -* (e.g. `resultType`) still passes through the loose index signature. Use a -* transport-level parse to validate raw wire traffic. -* -* @param value - The value to check. -* -* @returns True if the value is a valid {@linkcode CallToolResult}, false otherwise. -*/ -const isCallToolResult = (value) => { - if (typeof value !== "object" || value === null || value.content === void 0) return false; - return CallToolResultSchema.safeParse(value).success; -}; -/** -* Checks whether a value is an input-required result (protocol revision -* 2026-07-28): the multi-round-trip return shape discriminated by -* `resultType: 'input_required'`. -* -* This is a discriminator check, not a full validator — the at-least-one rule -* (`inputRequests` or `requestState`) is enforced by the `inputRequired()` -* builder and re-checked by the server seam for hand-built values. -* -* @param value - The value to check. -* @returns True if the value carries the `input_required` discriminator. -*/ -const isInputRequiredResult = (value) => typeof value === "object" && value !== null && !Array.isArray(value) && value.resultType === "input_required"; -/** -* Checks if a value is a valid {@linkcode TaskAugmentedRequestParams}. -* @param value - The value to check. -* -* @returns True if the value is a valid {@linkcode TaskAugmentedRequestParams}, false otherwise. -* -* @deprecated Recognizes 2025-11-25 task wire vocabulary, which has no SDK -* runtime; kept importable for interoperability only. -*/ -const isTaskAugmentedRequestParams = (value) => TaskAugmentedRequestParamsSchema.safeParse(value).success; -const src_CX2iR2pK_isInitializeRequest = (value) => InitializeRequestSchema.safeParse(value).success; -const isInitializedNotification = (value) => InitializedNotificationSchema.safeParse(value).success; -function assertCompleteRequestPrompt(request) { - if (request.params.ref.type !== "ref/prompt") throw new TypeError(`Expected CompleteRequestPrompt, but got ${request.params.ref.type}`); -} -function assertCompleteRequestResourceTemplate(request) { - if (request.params.ref.type !== "ref/resource") throw new TypeError(`Expected CompleteRequestResourceTemplate, but got ${request.params.ref.type}`); -} - -//#endregion -//#region ../core-internal/src/shared/mcpParamHeaders.ts -/** The fixed prefix every custom-parameter header carries. */ -const MCP_PARAM_HEADER_PREFIX = "Mcp-Param-"; -/** The schema-extension property name a tool's `inputSchema` carries. */ -const X_MCP_HEADER_KEY = "x-mcp-header"; -/** -* RFC 9110 §5.1 `token` syntax (`1*tchar`). Rejects empty, space, control -* characters (including CR/LF), and the listed delimiters. -*/ -const RFC9110_TOKEN = /^[!#$%&'*+\-.^_`|~0-9A-Za-z]+$/; -/** -* JSON Schema `type` values the spec admits on an `x-mcp-header` property. -* -* The spec text names `integer`, `string`, `boolean` and explicitly excludes -* `number`. The published conformance referee at the pinned release ships its -* `http-custom-headers` scenario with two `type: "number"` `x-mcp-header` -* parameters and expects the client to mirror them, so `number` is accepted -* here so that the conformance gate passes; the discrepancy is tracked -* upstream. Everything else (`object`, `array`, `null`, absent) is rejected. -*/ -const PERMITTED_X_MCP_HEADER_TYPES = new Set([ - "string", - "integer", - "boolean", - "number" -]); -/** -* Scan a tool's JSON-serialized `inputSchema` for `x-mcp-header` declarations -* and validate every constraint the spec places on them. Returns either the -* collected declarations (possibly empty) or the first violated constraint. -* -* The walk descends through `properties` at any depth (the spec's "any nesting -* depth" clause). The static-reachability MUST is enforced as a structural -* sweep: every position the chain MUST NOT pass through (`items`/ -* `additionalProperties`, `oneOf`/`anyOf`/`allOf`/`not`, `if`/`then`/`else`, -* `$defs`, `$ref` targets within `$defs`) is visited too, and an -* `x-mcp-header` found anywhere on that path invalidates the schema — "an -* annotation anywhere else makes the tool definition invalid". -*/ -function src_CX2iR2pK_scanXMcpHeaderDeclarations(inputSchema) { - const declarations = []; - const seenLower = /* @__PURE__ */ new Map(); - const visit = (node, path, reachable) => { - if (node === null || typeof node !== "object") return void 0; - const schema = node; - if (X_MCP_HEADER_KEY in schema) { - if (!reachable || path.length === 0) return `${pathName(path)}: x-mcp-header is only permitted on properties statically reachable via a chain of 'properties' keys (not under items, additionalProperties, oneOf/anyOf/allOf/not, if/then/else, or $ref)`; - const raw = schema[X_MCP_HEADER_KEY]; - if (typeof raw !== "string" || raw.length === 0) return `${pathName(path)}: x-mcp-header MUST be a non-empty string`; - if (!RFC9110_TOKEN.test(raw)) return `${pathName(path)}: x-mcp-header '${raw}' is not a valid RFC 9110 token (no spaces, control characters or HTTP delimiters)`; - const type = typeof schema.type === "string" ? schema.type : void 0; - if (type === void 0 || !PERMITTED_X_MCP_HEADER_TYPES.has(type)) return `${pathName(path)}: x-mcp-header is only permitted on primitive-typed properties (string, integer, boolean); got ${type ?? ""}`; - const lower = raw.toLowerCase(); - const prior = seenLower.get(lower); - if (prior !== void 0) return `x-mcp-header '${raw}' is not case-insensitively unique (also declared as '${prior}')`; - seenLower.set(lower, raw); - declarations.push({ - path, - headerName: raw, - type - }); - } - const properties = schema.properties; - if (properties !== null && typeof properties === "object") for (const [key, child] of Object.entries(properties)) { - const fault$1 = visit(child, [...path, key], reachable); - if (fault$1 !== void 0) return fault$1; - } - for (const k of NON_REACHABLE_SUBSCHEMA_KEYWORDS) { - const sub = schema[k]; - if (sub === void 0) continue; - const branches = Array.isArray(sub) ? sub : sub !== null && typeof sub === "object" && OBJECT_VALUED_SUBSCHEMA_KEYWORDS.has(k) ? Object.values(sub) : [sub]; - for (const branch of branches) { - const fault$1 = visit(branch, [...path, `<${k}>`], false); - if (fault$1 !== void 0) return fault$1; - } - } - }; - const fault = visit(inputSchema, [], true); - return fault === void 0 ? { - valid: true, - declarations - } : { - valid: false, - reason: fault - }; -} -/** -* JSON Schema keywords whose subschemas the SEP-2243 static-reachability -* constraint excludes from the `properties`-only chain. An `x-mcp-header` -* found under any of these invalidates the tool definition. -*/ -const NON_REACHABLE_SUBSCHEMA_KEYWORDS = [ - "items", - "prefixItems", - "contains", - "additionalProperties", - "unevaluatedProperties", - "unevaluatedItems", - "propertyNames", - "patternProperties", - "dependentSchemas", - "oneOf", - "anyOf", - "allOf", - "not", - "if", - "then", - "else", - "$defs", - "definitions" -]; -/** -* Subschema-carrying keywords whose value is a `name → subschema` object -* (not a single subschema or array of subschemas). The visit branches over -* `Object.values()` for these. -*/ -const OBJECT_VALUED_SUBSCHEMA_KEYWORDS = new Set([ - "patternProperties", - "dependentSchemas", - "$defs", - "definitions" -]); -function pathName(path) { - return path.length === 0 ? "" : path.join("."); -} -const BASE64_SENTINEL_PREFIX = "=?base64?"; -const BASE64_SENTINEL_SUFFIX = "?="; -const BASE64_CANONICAL = /^(?:[A-Za-z0-9+/]{4})*(?:[A-Za-z0-9+/]{2}==|[A-Za-z0-9+/]{3}=)?$/; -const CANONICAL_DECIMAL = /^-?\d+(\.\d+)?$/; -/** -* Convert a primitive argument value to its string representation per the -* spec's type-conversion rules: strings pass through, integers and numbers -* become their decimal string, booleans become lowercase `'true'` / `'false'`. -* Non-finite numbers and integers outside the safe range are refused (the -* caller treats `undefined` as "do not emit a header for this value"). -*/ -function mcpParamPrimitiveToString(value) { - if (typeof value === "string") return value; - if (typeof value === "boolean") return value ? "true" : "false"; - if (typeof value === "number") { - if (!Number.isFinite(value)) return void 0; - if (Number.isInteger(value) && !Number.isSafeInteger(value)) return void 0; - return String(value); - } -} -function base64ToUtf8(b64) { - const bin = atob(b64); - const bytes = new Uint8Array(bin.length); - for (let i = 0; i < bin.length; i++) bytes[i] = bin.codePointAt(i); - return new TextDecoder("utf-8", { fatal: true }).decode(bytes); -} -/** -* Decode an `Mcp-Param-*` header value: when it carries the Base64 sentinel, -* the payload is decoded as UTF-8; otherwise the value is returned as-is. -* Returns `undefined` when the sentinel is present but the payload is not -* canonical Base64 (or not valid UTF-8) — the spec requires servers to reject -* such values. -*/ -function decodeMcpParamValue(value) { - if (!(value.startsWith(BASE64_SENTINEL_PREFIX) && value.endsWith(BASE64_SENTINEL_SUFFIX))) return value; - const b64 = value.slice(9, value.length - 2); - if (!BASE64_CANONICAL.test(b64)) return void 0; - try { - return base64ToUtf8(b64); - } catch { - return; - } -} -function valueAtPath(root, path) { - let node = root; - for (const key of path) { - if (node === null || typeof node !== "object") return void 0; - node = node[key]; - } - return node; -} -/** -* The header/body comparison the server performs at tool-resolution time. -* -* For each `x-mcp-header` declaration on the named tool: when the body -* `arguments` carries a value, the matching `Mcp-Param-{Name}` header MUST be -* present and decode to an equal value; when the body value is `null` or -* absent the server MUST NOT expect the header (a present header is ignored). -* A sentinel-carrying header whose payload is not canonical Base64 / valid -* UTF-8 is rejected as invalid characters. -* -* Integer-typed declarations are compared numerically (the spec's SHOULD — -* `42.0` and `42` are equal); everything else is compared as decoded strings. -* -* Returns `undefined` when every check passes, or an -* {@linkcode InboundLadderRejection} carrying the same `-32020` -* (`HeaderMismatch`) shape the inbound classifier emits for the -* standard-header cross-checks — `400 Bad Request` with the disagreeing pair -* in `data.mismatch`. -*/ -function src_CX2iR2pK_validateMcpParamHeaders(declarations, args, headers) { - for (const decl of declarations) { - const headerKey = `${MCP_PARAM_HEADER_PREFIX}${decl.headerName}`; - const headerValue = headers.get(headerKey); - const bodyRaw = valueAtPath(args, decl.path); - if (bodyRaw === void 0 || bodyRaw === null) continue; - const bodyString = mcpParamPrimitiveToString(bodyRaw); - if (bodyString === void 0) continue; - if (headerValue === null) return paramHeaderMismatchRejection("param-header-missing", headerKey, `the body carries ${pathName(decl.path)}=${JSON.stringify(bodyRaw)} but the ${headerKey} header is absent`); - const decoded = decodeMcpParamValue(headerValue); - if (decoded === void 0) return paramHeaderMismatchRejection("param-header-invalid-encoding", headerKey, `the ${headerKey} header carries an invalid Base64 sentinel value`); - if (!((decl.type === "integer" || decl.type === "number") && CANONICAL_DECIMAL.test(decoded) && typeof bodyRaw === "number" ? Number(decoded) === bodyRaw : decoded === bodyString)) return paramHeaderMismatchRejection("param-header-mismatch", headerKey, `the ${headerKey} header decodes to ${JSON.stringify(decoded)} but the body carries ${pathName(decl.path)}=${JSON.stringify(bodyRaw)}`); - } -} -/** -* Build the `-32020` (`HeaderMismatch`) rejection for an `Mcp-Param-*` -* disagreement. Same shape as the inbound classifier's standard-header -* cross-check mismatch (HTTP `400`, `data.mismatch` naming the disagreeing -* pair, `settled: true`); only the rung differs because this check runs at the -* pre-dispatch step against a known tool's schema rather than at the edge. -*/ -function paramHeaderMismatchRejection(cell, header, body) { - return { - kind: "reject", - rung: "param-header-validation", - cell, - httpStatus: 400, - code: HEADER_MISMATCH_ERROR_CODE, - message: `Bad Request: the request headers and body disagree: ${body}`, - data: { mismatch: { - header, - body - } }, - settled: true - }; -} - -//#endregion -//#region ../core-internal/src/shared/inboundClassification.ts -/** -* Inbound HTTP request classification and the inbound validation ladder -* (protocol revision 2026-07-28). -* -* `classifyInboundRequest` is the body-primary era predicate for an HTTP -* entry that serves both protocol eras on one endpoint. It is evaluated -* exactly once, at the entry boundary, on the already-parsed request body: -* -* - `initialize` is a legacy-era request by definition (the modern era has no -* `initialize` handshake) — unless it carries a valid envelope claim naming -* a modern revision, in which case the claim wins and the request is -* classified like any other enveloped request (the modern era then answers -* it with method-not-found, exactly like every other method it does not -* define). -* - A request whose `params._meta` carries the reserved protocol-version key -* claims the per-request envelope mechanism and classifies into the era the -* named revision belongs to (a malformed envelope behind a present claim is -* a validation error, never a silent fall back to legacy handling). -* - A request without a claim is legacy-era traffic. -* - The `MCP-Protocol-Version` header is a cross-check only: it never -* upgrades or downgrades a body-derived classification, and a disagreement -* between header and body is an explicit ladder outcome. -* - Notifications carry no envelope claim of their own under the current -* spec, so for notification POSTs without a body claim the modern header is -* determinative; the `Mcp-Method` header is validated against the body when -* the message classifies modern and is never enforced on legacy traffic. -* A notification that does carry a claim is treated body-primary like a -* request, and a malformed claim is rejected the same way a request's -* malformed claim is — never silently resolved against the header. -* The notification-POST header cross-checks here are an SDK-defensive -* posture, not a spec requirement: the spec leaves header rules for posted -* notifications undefined (core client notifications do not occur over -* Streamable HTTP); applying the request rules symmetrically is what an -* ecosystem custom-notification POST expects, and the −32020 cells stay -* passing for them. -* - `GET`/`DELETE` (and any other non-`POST` method) are body-less 2025-era -* session operations: the modern era is `POST`-only, so they are routed to -* legacy serving when it is configured and rejected otherwise. -* - Array (batch) bodies are classified element-wise: an array containing a -* modern-claiming or invalid element is rejected, an all-legacy array is -* legacy traffic unchanged, and a single-element array is still an array. -* -* The classifier returns plain values (it never throws and never touches a -* transport): a routing outcome (`legacy`/`modern`) or a ladder rejection -* carrying the JSON-RPC error to emit and the HTTP status to emit it with. -* Legacy routing outcomes deliberately carry NO `MessageClassification` — -* legacy and hand-wired traffic is never classified, which keeps its -* dispatch behavior byte-identical to today's. -* -* Error codes for the modern-path rejection cells follow the published -* conformance suite (and the spec text it asserts): -* -* - A header/body cross-check mismatch (the `MCP-Protocol-Version` header -* disagreeing with the body, or the `Mcp-Method` header disagreeing with the -* body method) is rejected with `-32020` (`HeaderMismatch`) on HTTP 400. -* - A request whose protocol-version header names a modern revision but whose -* body carries no `_meta` envelope claim — including an envelope present but -* missing the required protocol-version key — is rejected with `-32602` -* (invalid params) naming the missing key(s), on HTTP 400. -* -* Should a future spec revision or conformance release change these -* assignments, the affected cells are re-derived against that release; the -* `settled` flag on {@linkcode InboundLadderRejection} stays available to mark -* a cell provisional again while such a change is in flight. -*/ -/** -* The error code emitted for header/body cross-check mismatches: the -* `MCP-Protocol-Version` header disagreeing with the body's envelope claim (or -* with the body's classification), and the `Mcp-Method` header disagreeing -* with the body method. -* -* `-32020` is the draft schema's `HEADER_MISMATCH` constant (the SEP-2243 -* `HeaderMismatch` code; the spec requires HTTP 400 for it), as also asserted -* by the published conformance suite for header-validation failures. It has no -* {@linkcode ProtocolErrorCode} member because it is not part of the 2025-era -* wire vocabulary; the validation ladder is its only emitter. -*/ -const HEADER_MISMATCH_ERROR_CODE = -32020; -/** -* The inbound validation ladder, expressed as data rather than control flow. -* -* The edge rungs are evaluated by {@linkcode classifyInboundRequest}; the -* dispatch rungs are evaluated by the protocol layer once the classified -* message is injected into a per-request server instance (the era registry -* gate, the envelope requiredness check, and per-method params validation). -* The client-capability rung is evaluated by the HTTP entry itself, -* pre-dispatch, on the validated envelope the classifier produced — see that -* rung's rationale for the ordering caveat. The order is the precedence: a -* request that fails several rungs is answered by the earliest one. -*/ -const INBOUND_VALIDATION_LADDER = [ - { - 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: [src_CX2iR2pK_ProtocolErrorCode.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: [HEADER_MISMATCH_ERROR_CODE, src_CX2iR2pK_ProtocolErrorCode.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: [src_CX2iR2pK_ProtocolErrorCode.InvalidParams], - conformance: ["server-stateless"], - rationale: "A present envelope claim with a malformed envelope — and a missing envelope on a request whose protocol-version header names a modern revision — 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: [src_CX2iR2pK_ProtocolErrorCode.MethodNotFound], - conformance: ["server-stateless"], - rationale: "Method existence outranks parameter validity: a method absent from the negotiated revision’s 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: [src_CX2iR2pK_ProtocolErrorCode.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: [HEADER_MISMATCH_ERROR_CODE], - conformance: ["http-header-validation"], - rationale: "SEP-2243 standard `Mcp-Method` / `Mcp-Name` headers — presence, sentinel decoding, and `Mcp-Name` ↔ body cross-check — are validated by the HTTP entry on a modern-classified request after the supported-revision gate and before dispatch. The classifier’s 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–6) are consulted." - }, - { - rung: "client-capabilities", - order: 8, - evaluatedAt: "pre-dispatch", - codes: [src_CX2iR2pK_ProtocolErrorCode.MissingRequiredClientCapability], - conformance: ["server-stateless"], - rationale: "The capability requirement is checked by the HTTP entry, pre-dispatch, against the validated envelope the classifier produced — 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: [HEADER_MISMATCH_ERROR_CODE], - conformance: ["http-custom-header-server-validation"], - rationale: "SEP-2243 `Mcp-Param-*` headers are validated against the named tool’s `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." - } -]; -/** -* HTTP status for ladder-originated JSON-RPC error codes. -* -* Keyed on origin, not on the bare code: this table only applies to errors -* the ladder (or a pre-handler protocol gate) produced. Errors produced by -* request handlers — whatever their code — stay in-band on HTTP 200, and are -* never mapped to an HTTP status by this table; in particular `-32603` and -* domain-specific codes never become a blanket 500. The single exception is -* `MissingRequiredClientCapability` (-32021) — see -* {@linkcode httpStatusForErrorCode}. -* -* `-32602` (invalid params) deliberately has NO entry: the only invalid-params -* rejection that maps to HTTP 400 is the classifier's own envelope rung -* short-circuit, which carries its HTTP status directly. A dispatch- or -* handler-produced invalid-params error is always in-band. -*/ -const src_CX2iR2pK_LADDER_ERROR_HTTP_STATUS = { - [src_CX2iR2pK_ProtocolErrorCode.ParseError]: 400, - [src_CX2iR2pK_ProtocolErrorCode.InvalidRequest]: 400, - [src_CX2iR2pK_ProtocolErrorCode.MethodNotFound]: 404, - [src_CX2iR2pK_ProtocolErrorCode.UnsupportedProtocolVersion]: 400, - [src_CX2iR2pK_ProtocolErrorCode.MissingRequiredClientCapability]: 400, - [HEADER_MISMATCH_ERROR_CODE]: 400 -}; -/** -* The HTTP status to answer a JSON-RPC error with, keyed on the error's -* origin. `in-band` errors (anything produced by a request handler) are -* HTTP 200 — the JSON-RPC error response is the payload, not an HTTP -* failure — with ONE exception: `MissingRequiredClientCapability` (-32021), -* whose 400 the spec mandates on the error itself with no origin condition, -* and which the SDK genuinely produces after dispatch (the `input_required` -* capability gate). A handler relaying some downstream peer's `-32020`/`-32022` -* is NOT that peer's spec error and stays in-band like every other handler -* code. `ladder` errors map through {@linkcode LADDER_ERROR_HTTP_STATUS}. -* -* The per-request transport intentionally does NOT delegate to this function: -* its `?? 400` ladder fallback is only correct for entry-gate codes known to -* the table, and would wrongly map dispatch-window errors outside it (a -* window `-32602` must stay in-band on 200). The transport indexes the table -* directly; keep the two in agreement when editing either. -*/ -function src_CX2iR2pK_httpStatusForErrorCode(code, origin) { - if (origin === "in-band") return code === src_CX2iR2pK_ProtocolErrorCode.MissingRequiredClientCapability ? 400 : 200; - return src_CX2iR2pK_LADDER_ERROR_HTTP_STATUS[code] ?? 400; -} -function src_CX2iR2pK_rejection(rung, cell, httpStatus, error, settled) { - return { - kind: "reject", - rung, - cell, - httpStatus, - code: error.code, - message: error.message, - ...error.data !== void 0 && { data: error.data }, - settled - }; -} -function crossCheckMismatch(cell, header, body, rung = "era-classification") { - return src_CX2iR2pK_rejection(rung, cell, 400, new src_CX2iR2pK_ProtocolError(HEADER_MISMATCH_ERROR_CODE, `Bad Request: the request headers and body disagree: ${body}`, { mismatch: { - header, - body - } }), true); -} -/** -* The methods whose body carries a `params.name` / `params.uri` value the -* `Mcp-Name` header must mirror, and which body field supplies it (SEP-2243 -* § Standard Request Headers, `Required For` column). -*/ -const MCP_NAME_HEADER_SOURCE = (/* unused pure expression or super */ null && ({ - "tools/call": "name", - "prompts/get": "name", - "resources/read": "uri" -})); -/** Strip RFC 9110 optional whitespace (SP / HTAB) around a field value in linear time. */ -function stripHttpOws(value) { - let start = 0; - while (start < value.length) { - const code = value.codePointAt(start); - if (code !== 9 && code !== 32) break; - start += 1; - } - let end = value.length; - while (end > start) { - const code = value.codePointAt(end - 1); - if (code !== 9 && code !== 32) break; - end -= 1; - } - return start === 0 && end === value.length ? value : value.slice(start, end); -} -/** -* SEP-2243 standard-header server-side validation, evaluated by the HTTP -* entry on a modern-classified request immediately after -* {@linkcode classifyInboundRequest} returns a modern route. -* -* Returns the `-32020` (`HeaderMismatch`) ladder rejection (HTTP `400`, -* `standard-header-validation` rung — the same shape -* {@linkcode classifyInboundRequest} already emits on the edge -* `era-classification` rung for the `MCP-Protocol-Version` and -* `Mcp-Method` *mismatch* cells) when: -* -* - the required `Mcp-Method` header is absent; -* - the required `Mcp-Name` header is absent on a `tools/call`, -* `prompts/get`, or `resources/read` request whose body carries the -* `params.name` / `params.uri` value the header mirrors; -* - the `Mcp-Name` header carries an invalid `=?base64?…?=` sentinel; or -* - the (decoded) `Mcp-Name` value disagrees with the body's -* `params.name` / `params.uri`. -* -* Returns `undefined` (pass) for notifications (the spec table reads -* "All requests"), for methods that have no `Mcp-Name` source, and when the -* headers agree with the body. Never enforced on legacy traffic — the entry -* only calls this on a modern route. -* -* Kept separate from {@linkcode classifyInboundRequest} so that a body-only -* call to the classifier (no headers passed) keeps routing a modern request -* unchanged: the classifier remains a pure body-primary router, and this -* function is the presence/`Mcp-Name` half of the standard-header rung the -* entry layers on top. -*/ -function src_CX2iR2pK_validateStandardRequestHeaders(request, route) { - if (route.messageKind !== "request") return; - const method = route.message.method; - if (request.mcpMethodHeader === void 0) return crossCheckMismatch("method-header-missing", "(missing)", `the body names method ${method} but the required Mcp-Method header is absent`, "standard-header-validation"); - const sourceField = Object.hasOwn(MCP_NAME_HEADER_SOURCE, method) ? MCP_NAME_HEADER_SOURCE[method] : void 0; - if (sourceField === void 0) return; - const sourceValue = route.message.params?.[sourceField]; - const bodyValue = typeof sourceValue === "string" ? sourceValue : void 0; - if (request.mcpNameHeader === void 0) { - if (bodyValue === void 0) return; - return crossCheckMismatch("name-header-missing", "(missing)", `the body carries params.${sourceField}="${bodyValue}" but the required Mcp-Name header is absent`, "standard-header-validation"); - } - const normalizedNameHeader = stripHttpOws(request.mcpNameHeader); - const decoded = decodeMcpParamValue(normalizedNameHeader); - if (decoded === void 0) return crossCheckMismatch("name-header-invalid-encoding", normalizedNameHeader, "the Mcp-Name header carries an invalid Base64 sentinel value", "standard-header-validation"); - if (bodyValue !== void 0 && decoded !== bodyValue) return crossCheckMismatch("name-header-mismatch", normalizedNameHeader, `the body carries params.${sourceField}="${bodyValue}" but the Mcp-Name header names "${decoded}"`, "standard-header-validation"); -} -function isPlainObject$2(value) { - return value !== null && typeof value === "object" && !Array.isArray(value); -} -function classificationForClaim(claimedVersion) { - if (claimedVersion === void 0) return { era: "modern" }; - return { - era: isModernProtocolVersion(claimedVersion) ? "modern" : "legacy", - revision: claimedVersion - }; -} -/** -* Whether a request's params carry a per-request envelope claim that is both -* well-formed and names a modern protocol revision. -* -* Used by the `initialize` precedence rule: only such a claim overrides the -* `initialize` ⇒ legacy-handshake classification — a request carrying a valid -* modern envelope is a modern request regardless of its method name, and the -* modern era then answers `initialize` exactly like any other method it does -* not define (method-not-found). A malformed claim, or one naming a pre-2026 -* revision, keeps the legacy-handshake routing unchanged. -* -* Exported on the core internal barrel for the stdio serving entry, which -* applies the same precedence rule to a connection's opening message; not -* public API. -*/ -function src_CX2iR2pK_carriesValidModernEnvelopeClaim(params) { - if (!src_CX2iR2pK_hasEnvelopeClaim(params)) return false; - const claimedVersion = src_CX2iR2pK_envelopeClaimVersion(params); - if (claimedVersion === void 0 || !isModernProtocolVersion(claimedVersion)) return false; - const meta = src_CX2iR2pK_requestMetaOf(params); - return meta !== void 0 && src_CX2iR2pK_validateEnvelopeMeta(meta).length === 0; -} -function classifyBatch(body) { - if (body.length === 0) return src_CX2iR2pK_rejection("jsonrpc-shape", "empty-batch", 400, new src_CX2iR2pK_ProtocolError(src_CX2iR2pK_ProtocolErrorCode.InvalidRequest, "Bad Request: empty JSON-RPC batch"), true); - for (const element of body) { - if (src_CX2iR2pK_hasEnvelopeClaim(isPlainObject$2(element) ? element["params"] : void 0)) return src_CX2iR2pK_rejection("jsonrpc-shape", "batch-with-modern-element", 400, new src_CX2iR2pK_ProtocolError(src_CX2iR2pK_ProtocolErrorCode.InvalidRequest, "Bad Request: JSON-RPC batches may not contain requests for protocol revision 2026-07-28 or later"), true); - if (!(src_CX2iR2pK_isJSONRPCRequest(element) || src_CX2iR2pK_isJSONRPCNotification(element) || src_CX2iR2pK_isJSONRPCResultResponse(element) || src_CX2iR2pK_isJSONRPCErrorResponse(element))) return src_CX2iR2pK_rejection("jsonrpc-shape", "batch-with-invalid-element", 400, new src_CX2iR2pK_ProtocolError(src_CX2iR2pK_ProtocolErrorCode.InvalidRequest, "Bad Request: JSON-RPC batch contains an invalid message"), true); - } - return { - kind: "legacy", - reason: "batch" - }; -} -function classifyRequestBody(request, body) { - const params = body.params; - const method = body.method; - const headerVersion = request.protocolVersionHeader; - const headerNamesModern = headerVersion !== void 0 && isModernProtocolVersion(headerVersion); - if (method === "initialize" && !src_CX2iR2pK_carriesValidModernEnvelopeClaim(params)) { - if (headerNamesModern) return crossCheckMismatch("initialize-with-modern-header", headerVersion, "an initialize request (legacy handshake) was sent with a modern MCP-Protocol-Version header"); - const requestedVersion = isPlainObject$2(params) && typeof params["protocolVersion"] === "string" ? params["protocolVersion"] : void 0; - return { - kind: "legacy", - reason: "initialize", - ...requestedVersion !== void 0 && { requestedVersion } - }; - } - if (src_CX2iR2pK_hasEnvelopeClaim(params)) { - const meta = src_CX2iR2pK_requestMetaOf(params); - const firstIssue = (meta === void 0 ? [] : src_CX2iR2pK_validateEnvelopeMeta(meta))[0]; - if (firstIssue !== void 0) return src_CX2iR2pK_rejection("envelope", "envelope-invalid", 400, new src_CX2iR2pK_ProtocolError(src_CX2iR2pK_ProtocolErrorCode.InvalidParams, `Invalid _meta envelope for protocol revision 2026-07-28: ${firstIssue.key}: ${firstIssue.problem}`, { envelope: firstIssue }), true); - const claimedVersion = src_CX2iR2pK_envelopeClaimVersion(params); - if (headerVersion !== void 0 && claimedVersion !== void 0 && headerVersion !== claimedVersion) return crossCheckMismatch("header-body-version-mismatch", headerVersion, `the body envelope names protocol version ${claimedVersion} but the MCP-Protocol-Version header names ${headerVersion}`); - if (request.mcpMethodHeader !== void 0 && request.mcpMethodHeader !== method) return crossCheckMismatch("method-header-mismatch", request.mcpMethodHeader, `the body names method ${method} but the Mcp-Method header names ${request.mcpMethodHeader}`); - return { - kind: "modern", - messageKind: "request", - message: body, - classification: classificationForClaim(claimedVersion) - }; - } - if (headerNamesModern) { - const meta = src_CX2iR2pK_requestMetaOf(params); - const missingFromEnvelope = src_CX2iR2pK_validateEnvelopeMeta(meta ?? {}).filter((issue) => issue.problem === "missing").map((issue) => issue.key); - const missing = meta === void 0 ? ["_meta"] : missingFromEnvelope.length > 0 ? missingFromEnvelope : [PROTOCOL_VERSION_META_KEY]; - return src_CX2iR2pK_rejection("envelope", "modern-header-without-claim", 400, new src_CX2iR2pK_ProtocolError(src_CX2iR2pK_ProtocolErrorCode.InvalidParams, `Invalid params: the MCP-Protocol-Version header names protocol revision ${headerVersion}, but the request is missing the required per-request envelope key(s): ${missing.join(", ")}`, { envelope: { missing } }), true); - } - return { - kind: "legacy", - reason: "no-claim", - ...headerVersion !== void 0 && { requestedVersion: headerVersion } - }; -} -function classifyNotificationBody(request, body) { - const params = body.params; - const method = body.method; - const headerVersion = request.protocolVersionHeader; - const headerNamesModern = headerVersion !== void 0 && isModernProtocolVersion(headerVersion); - if (src_CX2iR2pK_hasEnvelopeClaim(params)) { - const claimedVersion = src_CX2iR2pK_envelopeClaimVersion(params); - if (claimedVersion === void 0) { - const meta = src_CX2iR2pK_requestMetaOf(params); - const claimIssue = (meta === void 0 ? [] : src_CX2iR2pK_validateEnvelopeMeta(meta)).find((issue) => issue.key === PROTOCOL_VERSION_META_KEY) ?? { - key: PROTOCOL_VERSION_META_KEY, - problem: "expected a protocol version string" - }; - return src_CX2iR2pK_rejection("envelope", "notification-envelope-invalid", 400, new src_CX2iR2pK_ProtocolError(src_CX2iR2pK_ProtocolErrorCode.InvalidParams, `Invalid _meta envelope for protocol revision 2026-07-28: ${claimIssue.key}: ${claimIssue.problem}`, { envelope: claimIssue }), true); - } - if (headerVersion !== void 0 && headerVersion !== claimedVersion) return crossCheckMismatch("notification-header-body-version-mismatch", headerVersion, `the notification envelope names protocol version ${claimedVersion} but the MCP-Protocol-Version header names ${headerVersion}`); - const classification = classificationForClaim(claimedVersion); - if (classification.era === "modern" && request.mcpMethodHeader !== void 0 && request.mcpMethodHeader !== method) return crossCheckMismatch("notification-method-header-mismatch", request.mcpMethodHeader, `the notification body names method ${method} but the Mcp-Method header names ${request.mcpMethodHeader}`); - return { - kind: "modern", - messageKind: "notification", - message: body, - classification - }; - } - if (headerNamesModern) { - if (request.mcpMethodHeader !== void 0 && request.mcpMethodHeader !== method) return crossCheckMismatch("notification-method-header-mismatch", request.mcpMethodHeader, `the notification body names method ${method} but the Mcp-Method header names ${request.mcpMethodHeader}`); - return { - kind: "modern", - messageKind: "notification", - message: body, - classification: { - era: "modern", - revision: headerVersion - } - }; - } - return { - kind: "legacy", - reason: "notification", - ...headerVersion !== void 0 && { requestedVersion: headerVersion } - }; -} -/** -* Classifies one inbound HTTP request for dual-era serving. -* -* The body-primary predicate, evaluated once at the entry boundary: see the -* module documentation for the rules. Returns a routing outcome (`legacy` or -* `modern`) or a ladder rejection; it never throws. -*/ -function src_CX2iR2pK_classifyInboundRequest(request) { - request = { - ...request, - ...request.protocolVersionHeader !== void 0 && { protocolVersionHeader: stripHttpOws(request.protocolVersionHeader) }, - ...request.mcpMethodHeader !== void 0 && { mcpMethodHeader: stripHttpOws(request.mcpMethodHeader) }, - ...request.mcpNameHeader !== void 0 && { mcpNameHeader: stripHttpOws(request.mcpNameHeader) } - }; - if (request.httpMethod.toUpperCase() !== "POST") return { - kind: "legacy", - reason: "http-method" - }; - const body = request.body; - if (Array.isArray(body)) return classifyBatch(body); - if (src_CX2iR2pK_isJSONRPCResultResponse(body) || src_CX2iR2pK_isJSONRPCErrorResponse(body)) return { - kind: "legacy", - reason: "response" - }; - if (isPlainObject$2(body) && src_CX2iR2pK_isJSONRPCRequest(body)) return classifyRequestBody(request, body); - if (isPlainObject$2(body) && src_CX2iR2pK_isJSONRPCNotification(body)) return classifyNotificationBody(request, body); - return src_CX2iR2pK_rejection("jsonrpc-shape", "invalid-json-rpc-body", 400, new src_CX2iR2pK_ProtocolError(src_CX2iR2pK_ProtocolErrorCode.InvalidRequest, "Bad Request: the request body is not a valid JSON-RPC message"), true); -} -/** -* The rejection a modern-only endpoint (no legacy serving configured) -* answers a legacy-classified request with. -* -* - Envelope-less requests (including `initialize`) are answered with the -* unsupported-protocol-version error carrying the endpoint's supported -* versions and echoing the version the request named (when it named one — -* `requested` is omitted rather than fabricated when the request named no -* version at all), so a legacy client can discover what the endpoint serves -* from the error alone. -* - Posted responses and batch arrays are invalid requests on the modern era. -* - Non-`POST` methods are not allowed. -* - Legacy-classified notifications return `undefined`: the caller answers -* 202 with no body and does not dispatch the notification (accept-and-drop). -*/ -function src_CX2iR2pK_modernOnlyStrictRejection(route, supportedVersions) { - switch (route.reason) { - case "http-method": return src_CX2iR2pK_rejection("http-method", "modern-only-method-not-allowed", 405, new src_CX2iR2pK_ProtocolError(-32e3, "Method not allowed."), true); - case "batch": return src_CX2iR2pK_rejection("jsonrpc-shape", "modern-only-batch-not-supported", 400, new src_CX2iR2pK_ProtocolError(src_CX2iR2pK_ProtocolErrorCode.InvalidRequest, "Bad Request: JSON-RPC batches are not supported by this endpoint"), true); - case "response": return src_CX2iR2pK_rejection("jsonrpc-shape", "modern-only-response-post", 400, new src_CX2iR2pK_ProtocolError(src_CX2iR2pK_ProtocolErrorCode.InvalidRequest, "Bad Request: JSON-RPC responses cannot be posted to this endpoint"), true); - case "notification": return; - case "initialize": - case "no-claim": { - const requested = route.requestedVersion; - return src_CX2iR2pK_rejection("era-classification", "modern-only-missing-envelope", 400, requested === void 0 ? new src_CX2iR2pK_ProtocolError(src_CX2iR2pK_ProtocolErrorCode.UnsupportedProtocolVersion, "Unsupported protocol version: the request did not name a protocol version", { supported: [...supportedVersions] }) : new src_CX2iR2pK_UnsupportedProtocolVersionError({ - supported: [...supportedVersions], - requested - }), true); - } - } -} - -//#endregion -//#region ../core-internal/src/util/schema.ts -/** -* Internal Zod schema utilities for protocol handling. -* These are used internally by the SDK for protocol message validation. -*/ -/** -* Parses data against a Zod schema (synchronous). -* Returns a discriminated union with success/error. -*/ -function parseSchema(schema, data) { - return parse_safeParse(schema, data); -} -/** -* Union of the declared shape keys across several Zod object schemas. -*/ -function shapeKeys(schemas) { - return new Set(schemas.flatMap((schema) => Object.keys(schema.shape))); -} - -//#endregion -//#region ../core-internal/src/util/standardSchema.ts -/** -* Standard Schema utilities for user-provided schemas. -* Supports Zod v4, Valibot, ArkType, and other Standard Schema implementations. -* @see https://standardschema.dev -*/ -function isStandardSchema(schema) { - if (schema == null) return false; - const schemaType = typeof schema; - if (schemaType !== "object" && schemaType !== "function") return false; - if (!("~standard" in schema)) return false; - return typeof schema["~standard"]?.validate === "function"; -} -let warnedZodFallback = false; -/** JSON Schema draft targeted by every conversion; shared so pattern references above stay in lockstep. */ -const JSON_SCHEMA_CONVERSION_TARGET = "draft-2020-12"; -/** -* Converts a StandardSchema to JSON Schema for use as an MCP tool/prompt schema. -* -* MCP requires `type: "object"` at the root of tool `inputSchema` and prompt -* argument schemas; `outputSchema` may have any JSON Schema root (SEP-2106). -* Zod's discriminated unions emit `{oneOf: [...]}` without a top-level `type`, -* so for `io: 'input'` this function defaults `type` to `"object"` when absent -* and throws on an explicit non-object `type` (e.g. `z.string()`). For -* `io: 'output'` a non-object root is returned as-is; the `"object"` default is -* applied only when the root is provably object-shaped. -*/ -function standardSchemaToJsonSchema(schema, io = "input") { - const std = schema["~standard"]; - let result; - if (std.jsonSchema) result = std.jsonSchema[io]({ target: JSON_SCHEMA_CONVERSION_TARGET }); - else if (std.vendor === "zod") { - if (!("_zod" in schema)) 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()."); - if (!warnedZodFallback) { - warnedZodFallback = true; - 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."); - } - result = toJSONSchema(schema, { - target: JSON_SCHEMA_CONVERSION_TARGET, - io - }); - } else throw new Error(`Schema library "${std.vendor}" does not implement StandardJSONSchemaV1 (\`~standard.jsonSchema\`). Upgrade to a version that does, or wrap your JSON Schema with fromJsonSchema().`); - if (io === "output") { - if (result.type !== void 0) return result; - return isProvablyObjectShapedRoot(result) ? { - type: "object", - ...result - } : result; - } - if (result.type !== void 0 && result.type !== "object") throw new Error(`MCP tool and prompt schemas must describe objects (got type: ${JSON.stringify(result.type)}). Wrap your schema in z.object({...}) or equivalent.`); - return { - type: "object", - ...result - }; -} -/** -* A typeless JSON Schema root is "provably object-shaped" when either it carries object keywords -* directly (`properties`/`patternProperties`/`additionalProperties`/`required`), or it is a -* composition (`oneOf`/`anyOf`/`allOf`) whose every member is itself `type:'object'` or recursively -* provably object-shaped (e.g. a nested `discriminatedUnion`). `$ref` is not followed. Used to -* decide whether stamping `type:'object'` is safe (redundant-but-valid) versus self-contradictory. -*/ -function isProvablyObjectShapedRoot(schema) { - if ("properties" in schema || "patternProperties" in schema || "additionalProperties" in schema || "required" in schema) return true; - for (const key of [ - "oneOf", - "anyOf", - "allOf" - ]) { - const members = schema[key]; - if (Array.isArray(members) && members.length > 0) return members.every((m) => m !== null && typeof m === "object" && (m.type === "object" || isProvablyObjectShapedRoot(m))); - } - return false; -} -function formatIssue(issue) { - if (!issue.path?.length) return issue.message; - return `${issue.path.map((p) => String(typeof p === "object" ? p.key : p)).join(".")}: ${issue.message}`; -} -async function validateStandardSchema(schema, data) { - const result = await schema["~standard"].validate(data); - if (result.issues && result.issues.length > 0) return { - success: false, - error: result.issues.map((i) => formatIssue(i)).join(", ") - }; - return { - success: true, - data: result.value - }; -} -function zodEmittedPattern(schema) { - const jsonSchema = toJSONSchema(schema, { - target: JSON_SCHEMA_CONVERSION_TARGET, - io: "input" - }); - return typeof jsonSchema.pattern === "string" ? jsonSchema.pattern : void 0; -} -const DATETIME_FRACTION_DIGITS = /\\\.\\d\{(\d+)\}/; -function datetimeReferenceSchemas(pattern) { - const fractionDigits = DATETIME_FRACTION_DIGITS.exec(pattern); - const precisions = [ - void 0, - -1, - 0 - ]; - if (fractionDigits) precisions.push(Number(fractionDigits[1])); - return [false, true].flatMap((local) => [false, true].flatMap((offset) => precisions.map((precision) => iso_datetime({ - local, - offset, - precision - })))); -} -function referencePatternsForFormat(format, pattern) { - let referenceSchemas; - switch (format) { - case "email": - referenceSchemas = [schemas_email()]; - break; - case "uri": - referenceSchemas = [schemas_url()]; - break; - case "date": - referenceSchemas = [iso_date()]; - break; - case "date-time": - referenceSchemas = datetimeReferenceSchemas(pattern); - break; - } - return new Set(referenceSchemas.map((schema) => zodEmittedPattern(schema)).filter((emitted) => emitted !== void 0)); -} -/** Whether `pattern` is the library's own realization of `format` (droppable) rather than a user customization. */ -function isLibraryFormatPattern(format, pattern, vendor) { - if (vendor !== "zod") return true; - return referencePatternsForFormat(format, pattern).has(pattern); -} -function promptArgumentsFromStandardSchema(schema) { - const jsonSchema = standardSchemaToJsonSchema(schema, "input"); - const properties = jsonSchema.properties || {}; - const required = jsonSchema.required || []; - return Object.entries(properties).map(([name, prop]) => ({ - name, - description: prop?.description, - required: required.includes(name) - })); -} - -//#endregion -//#region ../core-internal/src/shared/elicitation.ts -function isJsonObject(value) { - return typeof value === "object" && value !== null && !Array.isArray(value); -} -function convertStandardElicitationSchema(schema) { - try { - return standardSchemaToJsonSchema(schema, "input"); - } catch (error) { - const detail = error instanceof Error ? error.message : String(error); - throw new src_CX2iR2pK_ProtocolError(src_CX2iR2pK_ProtocolErrorCode.InvalidParams, `Elicitation requestedSchema must describe an object with flat primitive properties: ${detail}`); - } -} -const ANNOTATION_ONLY_JSON_SCHEMA_KEYWORDS = new Set([ - "$comment", - "deprecated", - "description", - "examples", - "readOnly", - "title", - "writeOnly" -]); -function isAnnotationOnlyJsonSchemaKeyword(key) { - return ANNOTATION_ONLY_JSON_SCHEMA_KEYWORDS.has(key) || key.startsWith("x-"); -} -const ROOT_KEYS = new Set(["$schema", ...Object.keys(ElicitRequestFormParamsSchema.shape.requestedSchema.shape)]); -const PROPERTY_KEYS_BY_TYPE = { - string: shapeKeys([ - StringSchemaSchema, - UntitledSingleSelectEnumSchemaSchema, - TitledSingleSelectEnumSchemaSchema, - LegacyTitledEnumSchemaSchema - ]), - number: shapeKeys([NumberSchemaSchema]), - integer: shapeKeys([NumberSchemaSchema]), - boolean: shapeKeys([BooleanSchemaSchema]), - array: shapeKeys([UntitledMultiSelectEnumSchemaSchema, TitledMultiSelectEnumSchemaSchema]) -}; -const SUPPORTED_STRING_FORMATS = new Set(StringSchemaSchema.shape.format.unwrap().options); -/** Walks one property node: keeps grammar keys, drops the library format pattern, rejects unknown constraints. */ -function walkProperty(node, path, vendor, unsupported) { - if (!isJsonObject(node)) return node; - const allowedKeys = typeof node.type === "string" && Object.hasOwn(PROPERTY_KEYS_BY_TYPE, node.type) ? PROPERTY_KEYS_BY_TYPE[node.type] : void 0; - if (allowedKeys === void 0) return node; - const pruned = {}; - for (const [key, value] of Object.entries(node)) if (allowedKeys.has(key) || isAnnotationOnlyJsonSchemaKeyword(key)) pruned[key] = value; - else if (key === "pattern" && node.type === "string" && typeof node.format === "string") { - if (!SUPPORTED_STRING_FORMATS.has(node.format)) pruned[key] = value; - else if (typeof value !== "string" || !isLibraryFormatPattern(node.format, value, vendor)) unsupported.push(`${path}.${key}`); - } else unsupported.push(`${path}.${key}`); - return pruned; -} -/** Walks the schema root: keeps the spec root keys, drops annotations, rejects the rest. */ -function walkRequestedSchema(converted, vendor) { - const pruned = {}; - const unsupported = []; - for (const [key, value] of Object.entries(converted)) if (key === "properties" && isJsonObject(value)) pruned[key] = Object.fromEntries(Object.entries(value).map(([name, node]) => [name, walkProperty(node, `properties.${name}`, vendor, unsupported)])); - else if (ROOT_KEYS.has(key)) pruned[key] = value; - else if (!isAnnotationOnlyJsonSchemaKeyword(key)) unsupported.push(key); - if (unsupported.length > 0) throw new src_CX2iR2pK_ProtocolError(src_CX2iR2pK_ProtocolErrorCode.InvalidParams, `Elicitation requestedSchema contains unsupported JSON Schema constraint(s) after Standard Schema conversion: ${unsupported.join(", ")}`); - return pruned; -} -/** Names the properties that fail value validation, instead of surfacing a raw union dump. */ -function describeUnsupportedProperties(pruned, fallback) { - if (!isJsonObject(pruned.properties)) return fallback; - const offenders = Object.entries(pruned.properties).filter(([, node]) => !parseSchema(PrimitiveSchemaDefinitionSchema, node).success).map(([name]) => `properties.${name}`); - return offenders.length > 0 ? offenders.join(", ") : fallback; -} -function findDroppedConstraintPaths(original, parsed, path = "") { - if (Array.isArray(original) && Array.isArray(parsed)) return original.flatMap((item, index) => findDroppedConstraintPaths(item, parsed[index], `${path}[${index}]`)); - if (!isJsonObject(original) || !isJsonObject(parsed)) return []; - return Object.entries(original).flatMap(([key, value]) => { - const childPath = path ? `${path}.${key}` : key; - if (!Object.prototype.hasOwnProperty.call(parsed, key)) return isAnnotationOnlyJsonSchemaKeyword(key) ? [] : [childPath]; - return findDroppedConstraintPaths(value, parsed[key], childPath); - }); -} -/** Converts an authoring-friendly elicitation input into its wire-ready form. */ -function normalizeElicitInputParams(input) { - if (!isStandardSchema(input.requestedSchema)) return { - ...input, - mode: "form", - requestedSchema: input.requestedSchema - }; - const vendor = input.requestedSchema["~standard"].vendor; - const pruned = walkRequestedSchema(convertStandardElicitationSchema(input.requestedSchema), vendor); - const parsed = parseSchema(ElicitRequestFormParamsSchema.shape.requestedSchema, pruned); - if (!parsed.success) throw new src_CX2iR2pK_ProtocolError(src_CX2iR2pK_ProtocolErrorCode.InvalidParams, `Elicitation requestedSchema only supports flat primitive properties (string, number, integer, boolean, and string enums): ${describeUnsupportedProperties(pruned, parsed.error.message)}`); - const droppedConstraints = findDroppedConstraintPaths(pruned, parsed.data); - if (droppedConstraints.length > 0) throw new src_CX2iR2pK_ProtocolError(src_CX2iR2pK_ProtocolErrorCode.InvalidParams, `Elicitation requestedSchema contains unsupported JSON Schema constraint(s) after Standard Schema conversion: ${droppedConstraints.join(", ")}`); - const danglingRequired = (parsed.data.required ?? []).filter((key) => !Object.prototype.hasOwnProperty.call(parsed.data.properties, key)); - if (danglingRequired.length > 0) throw new src_CX2iR2pK_ProtocolError(src_CX2iR2pK_ProtocolErrorCode.InvalidParams, `Elicitation requestedSchema lists required properties that are not defined in properties: ${danglingRequired.join(", ")}`); - return { - ...input, - mode: "form", - requestedSchema: parsed.data - }; -} - -//#endregion -//#region ../core-internal/src/shared/inputRequired.ts -/** -* Authoring helpers for multi-round-trip requests (protocol revision -* 2026-07-28). -* -* A handler for one of the multi-round-trip methods (`tools/call`, -* `prompts/get`, `resources/read`) requests additional client input by -* returning an {@linkcode InputRequiredResult} instead of a final result. The -* helpers here build that return value and its embedded requests as NEUTRAL -* values; only the 2026-07-28 wire codec maps them to/from the wire. The -* 2025-era codec has no input-required vocabulary — on a 2025-era request the -* server's legacy shim (on by default) fulfils the embedded requests as real -* server→client requests and re-enters the handler, so the same return shape -* serves both eras; `ServerOptions.inputRequired.legacyShim: false` restores -* the pre-shim loud failure. -* -* There is no nominal brand: `resultType: 'input_required'` is the -* discriminator, and hand-built result literals are equally legal — the -* server seam re-checks the at-least-one rule for them. -*/ -function buildInputRequired(spec) { - const hasInputRequests = spec.inputRequests !== void 0 && Object.keys(spec.inputRequests).length > 0; - const hasRequestState = typeof spec.requestState === "string"; - if (!hasInputRequests && !hasRequestState) 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", - ...spec.inputRequests !== void 0 && { inputRequests: spec.inputRequests }, - ...spec.requestState !== void 0 && { requestState: spec.requestState } - }; -} -/** -* Builder for the input-required return value of multi-round-trip handlers, -* with per-kind constructors for the embedded requests -* (`inputRequired.elicit`, `inputRequired.elicitUrl`, -* `inputRequired.createMessage`, `inputRequired.listRoots`). -* -* @example Write-once tool requesting confirmation -* ```ts -* server.registerTool('deploy', { inputSchema: z.object({ env: z.string() }) }, async ({ env }, ctx) => { -* const confirmed = acceptedContent<{ confirm: boolean }>(ctx.mcpReq.inputResponses, 'confirm'); -* if (!confirmed) { -* return inputRequired({ -* inputRequests: { -* confirm: inputRequired.elicit({ -* message: `Deploy to ${env}?`, -* requestedSchema: { type: 'object', properties: { confirm: { type: 'boolean' } }, required: ['confirm'] } -* }) -* } -* }); -* } -* return { content: [{ type: 'text', text: `deployed to ${env}` }] }; -* }); -* ``` -*/ -const inputRequired = Object.assign(buildInputRequired, { - elicit(params) { - try { - return { - method: "elicitation/create", - params: normalizeElicitInputParams(params) - }; - } catch (error) { - throw error instanceof src_CX2iR2pK_ProtocolError ? new TypeError(error.message, { cause: error }) : error; - } - }, - elicitUrl(params) { - return { - method: "elicitation/create", - params: { - ...params, - mode: "url" - } - }; - }, - createMessage(params) { - return { - method: "sampling/createMessage", - params - }; - }, - listRoots() { - return { method: "roots/list" }; - } -}); -function acceptedContent(responses, key, schema) { - const view = inputResponse(responses, key); - if (view.kind !== "elicit" || view.action !== "accept" || view.content === void 0) return void 0; - if (schema === void 0) return view.content; - const outcome = schema["~standard"].validate(view.content); - if (outcome instanceof Promise) throw new TypeError("acceptedContent(responses, key, schema) requires a synchronously-validating schema"); - return outcome.issues === void 0 ? outcome.value : void 0; -} -/** -* Reads one entry of a retried request's `inputResponses` -* (`ctx.mcpReq.inputResponses`) as a discriminated view, covering -* decline/cancel detection and the non-elicitation response kinds that -* {@linkcode acceptedContent} does not surface. -* -* The values arrive from the client and are not re-validated here — treat -* them as untrusted input (validate elicitation content with the -* schema-aware {@linkcode acceptedContent} overload where it matters). -*/ -function inputResponse(responses, key) { - if (responses === void 0 || typeof responses !== "object" || responses === null) return { kind: "missing" }; - const entry = responses[key]; - if (entry === null || typeof entry !== "object" || Array.isArray(entry)) return { kind: "missing" }; - const candidate = entry; - if (candidate["action"] === "accept" || candidate["action"] === "decline" || candidate["action"] === "cancel") { - const content = candidate["content"]; - return { - kind: "elicit", - action: candidate["action"], - ...content !== null && typeof content === "object" && !Array.isArray(content) && { content } - }; - } - if (Array.isArray(candidate["roots"])) return { - kind: "roots", - roots: candidate["roots"] - }; - if (typeof candidate["role"] === "string" && candidate["content"] !== void 0) return { - kind: "sampling", - result: candidate - }; - return { kind: "missing" }; -} - -//#endregion -//#region ../core-internal/src/shared/inputRequiredDriver.ts -/** -* The multi-round-trip auto-fulfilment driver (protocol revision 2026-07-28). -* -* When a request to one of the multi-round-trip methods comes back as -* `input_required`, the driver fulfils the embedded input requests by -* dispatching them to the client's already-registered handlers (elicitation, -* sampling, roots — one generic engine, no per-feature API), then retries the -* original request with the collected `inputResponses` and a byte-exact echo -* of `requestState`, on a fresh request id, until the server returns a -* complete result or the round cap is exhausted. -* -* The driver is a LAYER OVER THE MANUAL PATH: each retry is issued with the -* same primitive a manual caller uses (`allowInputRequired` semantics — the -* retry hands back the next `input_required` payload instead of recursing), -* so the loop, the cap, and the pacing live in one place and disabling -* auto-fulfilment (`inputRequired.autoFulfill: false`) simply skips this -* module. Timeouts ride the EXISTING knobs: the per-leg `timeout` applies to -* every wire leg unchanged, and `maxTotalTimeout` bounds the whole flow by -* shrinking the budget passed to each leg — no new timer system. -*/ -/** -* Fixed pacing applied before retrying a requestState-only (load-shedding) -* leg — a leg that carries no embedded input requests, so nothing slows the -* loop down naturally. Counted in the same round cap. -*/ -const REQUEST_STATE_ONLY_LEG_PACING_MS = 250; -/** -* The message both multi-round-trip loops emit when the round cap is -* exhausted — the client driver as a typed error, the server-side legacy -* shim as its per-family failure. One formatter so the texts cannot drift -* (hosts and models read the tool-result copy verbatim). -*/ -function inputRequiredRoundsExceededMessage(method, maxRounds) { - return `Multi-round-trip request '${method}' still required input after ${maxRounds} rounds (inputRequired.maxRounds)`; -} -/** -* Abortable delay: resolves after `ms`, or rejects with the signal's reason -* (wrapped in an `SdkError` when it isn't already one) if the signal aborts -* first. Aborting after resolution is a no-op. Shared with the server-side -* legacy shim (the pacing semantics must match per era). -*/ -function sleep(ms, signal) { - return new Promise((resolve, reject) => { - if (signal?.aborted) { - reject(signal.reason instanceof src_CX2iR2pK_SdkError ? signal.reason : new src_CX2iR2pK_SdkError(src_CX2iR2pK_SdkErrorCode.RequestTimeout, String(signal.reason))); - return; - } - const timer = setTimeout(() => { - signal?.removeEventListener("abort", onAbort); - resolve(); - }, ms); - const onAbort = () => { - clearTimeout(timer); - reject(signal?.reason instanceof src_CX2iR2pK_SdkError ? signal.reason : new src_CX2iR2pK_SdkError(src_CX2iR2pK_SdkErrorCode.RequestTimeout, String(signal?.reason))); - }; - signal?.addEventListener("abort", onAbort, { once: true }); - }); -} -/** -* A per-round abort linked to the caller's signal: the embedded sibling -* dispatches share it, so the first failure (or a caller abort) cancels the -* others instead of leaving them running. Shared with the server-side legacy -* shim (the abort-linkage semantics must match per era). -*/ -function linkedRoundAbort(outer) { - const controller = new AbortController(); - const onOuterAbort = () => controller.abort(outer?.reason); - outer?.addEventListener("abort", onOuterAbort, { once: true }); - if (outer?.aborted) controller.abort(outer.reason); - return { - signal: controller.signal, - abort: (reason) => controller.abort(reason), - dispose: () => outer?.removeEventListener("abort", onOuterAbort) - }; -} - -//#endregion -//#region ../core-internal/src/types/specTypeSchema.ts -/** -* Explicit allowlist of protocol Zod schemas that correspond to a public spec type in `types.ts`. -* -* This intentionally excludes internal helper schemas exported from `schemas.ts` that have no -* matching public type (e.g. `ListChangedOptionsBaseSchema`, `BaseRequestParamsSchema`, -* `NotificationsParamsSchema`, `ClientTasksCapabilitySchema`, `ServerTasksCapabilitySchema`). -* Keeping the list explicit means new public spec types must be added here deliberately, and -* internals never leak into `SpecTypeName`. -* -* `ResourceTemplateSchema` is included; its public type is exported as `ResourceTemplateType` -* (the bare name collides with the server package's `ResourceTemplate` class), so -* `SpecTypes['ResourceTemplate']` is structurally equal to `ResourceTemplateType` rather than to -* a type literally named `ResourceTemplate`. -*/ -const SPEC_SCHEMA_KEYS = [ - "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" -]; -const authSchemas = { - IdJagTokenExchangeResponseSchema: IdJagTokenExchangeResponseSchema, - OAuthClientInformationFullSchema: OAuthClientInformationFullSchema, - OAuthClientInformationSchema: OAuthClientInformationSchema, - OAuthClientMetadataSchema: OAuthClientMetadataSchema, - OAuthClientRegistrationErrorSchema: OAuthClientRegistrationErrorSchema, - OAuthErrorResponseSchema: OAuthErrorResponseSchema, - OAuthMetadataSchema: OAuthMetadataSchema, - OAuthProtectedResourceMetadataSchema: OAuthProtectedResourceMetadataSchema, - OAuthTokenRevocationRequestSchema: OAuthTokenRevocationRequestSchema, - OAuthTokensSchema: OAuthTokensSchema, - OpenIdProviderDiscoveryMetadataSchema: OpenIdProviderDiscoveryMetadataSchema, - OpenIdProviderMetadataSchema: OpenIdProviderMetadataSchema -}; -const _specTypeSchemas = {}; -const _isSpecType = {}; -function register(key, schema) { - const name = key.slice(0, -6); - _specTypeSchemas[name] = schema; - _isSpecType[name] = (v) => schema.safeParse(v).success; -} -for (const key of SPEC_SCHEMA_KEYS) register(key, schemas_exports[key]); -for (const [key, schema] of Object.entries(authSchemas)) register(key, schema); -/** -* Runtime validators for every MCP spec type, keyed by type name. -* -* Use this when you need to validate a spec-defined shape at a boundary the SDK does not own, for -* example an extension's custom-method payload that embeds a `CallToolResult`, or a value read from -* storage that should be a `Tool`. -* -* Each entry implements the Standard Schema interface, so it composes with any -* Standard-Schema-aware library. For a simple boolean check, use {@linkcode isSpecType} instead. -* -* @example -* ```ts source="./specTypeSchema.examples.ts#specTypeSchemas_basicUsage" -* const result = specTypeSchemas.CallToolResult['~standard'].validate(untrusted); -* if (result.issues === undefined) { -* // result.value is CallToolResult -* } -* ``` -*/ -const specTypeSchemas = Object.freeze(_specTypeSchemas); -/** -* Type predicates for every MCP spec type, keyed by type name. -* -* Returns `true` if the value satisfies the schema's input type (`z.input<>`, before defaults and -* transforms are applied), and narrows to that input type. For schemas with `.default()` or -* `.preprocess()`, this may accept values that do not structurally match the named output type; -* for example `isSpecType.CallToolResult({})` is `true` because `content` has a default. Use -* `specTypeSchemas.X['~standard'].validate(value)` when you need the validated output value. -* -* Each guard is a standalone function, so it can be passed directly as a callback. -* -* @example -* ```ts source="./specTypeSchema.examples.ts#isSpecType_basicUsage" -* if (isSpecType.ContentBlock(value)) { -* // value is ContentBlock -* } -* -* const blocks = mixed.filter(isSpecType.ContentBlock); -* ``` -*/ -const isSpecType = Object.freeze(_isSpecType); - -//#endregion -//#region ../core-internal/src/wire/bootstrap.ts -function bootstrapOutboundCodec(method) { - switch (method) { - case "initialize": - case "notifications/initialized": return src_CX2iR2pK_codecForVersion(void 0); - case "server/discover": return src_CX2iR2pK_codecForVersion(src_CX2iR2pK_MODERN_WIRE_REVISION); - default: return; - } -} - -//#endregion -//#region ../core-internal/src/shared/protocol.ts -/** -* The default request timeout, in milliseconds. -*/ -const DEFAULT_REQUEST_TIMEOUT_MSEC = 6e4; -/** -* The reserved per-request `_meta` envelope keys (protocol revision -* 2026-07-28). The protocol layer lifts these out of inbound `_meta` before -* handlers run and surfaces them at `ctx.mcpReq.envelope` — they are -* wire-level bookkeeping, not handler material. -*/ -const RESERVED_ENVELOPE_META_KEYS = [ - auth_CUe6YdwF_PROTOCOL_VERSION_META_KEY, - auth_CUe6YdwF_CLIENT_INFO_META_KEY, - auth_CUe6YdwF_CLIENT_CAPABILITIES_META_KEY, - LOG_LEVEL_META_KEY -]; -/** -* Top-level params members carrying multi-round-trip driver material -* (protocol revision 2026-07-28). The spec reserves these names on -* client-initiated REQUESTS only — notification params keep them untouched -* (a vendor notification may legitimately use the same names). -*/ -const RETRY_PARAMS_KEYS = ["inputResponses", "requestState"]; -/** -* Lift wire-only material out of an inbound message so handlers see exactly -* the 2025-era shape, and surface it for the protocol layer (requests: via -* `ctx.mcpReq`). What counts as wire-only depends on the message kind: the -* reserved envelope `_meta` keys are reserved on every message, while the -* multi-round-trip retry fields (`inputResponses`/`requestState`) are -* reserved on client-initiated requests only — so notifications get only the -* envelope lift, and their top-level params stay untouched. Messages without -* wire-only material are returned unchanged (same reference). -*/ -function liftWireOnlyMaterial(message, kind) { - const params = message.params; - if (!isPlainObject$1(params)) return { - message, - lifted: {} - }; - const meta = params._meta; - const envelopeKeys = isPlainObject$1(meta) ? RESERVED_ENVELOPE_META_KEYS.filter((key) => key in meta) : []; - const retryKeys = kind === "request" ? RETRY_PARAMS_KEYS.filter((key) => key in params) : []; - if (envelopeKeys.length === 0 && retryKeys.length === 0) return { - message, - lifted: {} - }; - const lifted = {}; - const nextParams = { ...params }; - if (envelopeKeys.length > 0 && isPlainObject$1(meta)) { - const envelope = {}; - const nextMeta = { ...meta }; - for (const key of envelopeKeys) { - envelope[key] = meta[key]; - delete nextMeta[key]; - } - lifted.envelope = envelope; - if (Object.keys(nextMeta).length > 0) nextParams._meta = nextMeta; - else delete nextParams._meta; - } - for (const key of retryKeys) { - if (key === "inputResponses") lifted.inputResponses = nextParams[key]; - if (key === "requestState") lifted.requestState = nextParams[key]; - delete nextParams[key]; - } - return { - message: { - ...message, - params: nextParams - }, - lifted - }; -} -/** -* Standard Schema adapter over the era codec's `validateResult` function (the -* function-only WireCodec contract exposes no schema objects). Used by the -* spec-method `request()` overload so the request funnel keeps a single -* `StandardSchemaV1`-shaped validation seam for both spec and explicit-schema -* paths. -* -* Returns `undefined` when the method has no result entry on this era's -* registry — the caller maps that to the synchronous "pass a result schema" -* TypeError, exactly matching the pre-function-only behavior the -* typedMapAlignment suite pins (the result map deliberately excludes the -* `tasks/*` methods, so the spec-method overload refuses them up front). -*/ -function codecResultValidator(codec, method) { - const probe = codec.validateResult(method, void 0); - if (!probe.ok && probe.reason === "not-in-era") return void 0; - return { "~standard": { - version: 1, - vendor: "mcp-wire-codec", - validate(value) { - const outcome = codec.validateResult(method, value); - if (outcome.ok) return { value: outcome.value }; - return { issues: [{ message: outcome.reason === "invalid" ? outcome.message : `not-in-era: ${method}` }] }; - } - } }; -} -/** -* Builds the `ctx.mcpReq.requestState` accessor for a resolved value. The -* `as T` below is the one place {@linkcode RequestStateAccessor}'s -* caller-asserted typing is implemented — no implementation can produce an -* arbitrary `T` from a runtime value honestly. -*/ -function requestStateAccessor(value) { - return () => value; -} -/** Shared no-state accessor: the common case allocates nothing per request. */ -const NO_REQUEST_STATE = requestStateAccessor(void 0); -/** -* Returns a context whose `requestState` accessor reads the given value — -* how the server seam hands a verify hook's decoded payload (or the legacy -* shim's per-round echo) to the handler without mutating the original -* context. -*/ -function withRequestStateValue(ctx, value) { - return { - ...ctx, - mcpReq: { - ...ctx.mcpReq, - requestState: requestStateAccessor(value) - } - }; -} -let writeNegotiatedProtocolVersion; -/** -* Package-internal write channel for a {@linkcode Protocol} instance's -* negotiated protocol version, for callers outside the class hierarchy: -* tests and the (future) modern-era server entry that marks a factory -* instance modern at binding time. Exported on the core internal barrel -* only — never public API. -*/ -function src_CX2iR2pK_setNegotiatedProtocolVersion(instance, version) { - writeNegotiatedProtocolVersion(instance, version); -} -/** -* Implements MCP protocol framing on top of a pluggable transport, including -* features like request/response linking, notifications, and progress. -* -* `Protocol` is abstract; `Client` and `Server` are the concrete role-specific -* implementations most code should use. -*/ -var Protocol = class { - _transport; - _requestMessageId = 0; - _requestHandlers = /* @__PURE__ */ new Map(); - _requestHandlerAbortControllers = /* @__PURE__ */ new Map(); - _notificationHandlers = /* @__PURE__ */ new Map(); - _responseHandlers = /* @__PURE__ */ new Map(); - _progressHandlers = /* @__PURE__ */ new Map(); - _timeoutInfo = /* @__PURE__ */ new Map(); - _pendingDebouncedNotifications = /* @__PURE__ */ new Set(); - /** - * The protocol version negotiated for the current connection (`undefined` - * before negotiation completes), which determines the wire era this - * instance speaks. Set by the SDK's negotiation and initialize paths - * (`Client.connect`, `Server._oninitialize`). - */ - _negotiatedProtocolVersion; - static { - writeNegotiatedProtocolVersion = (instance, version) => { - instance._negotiatedProtocolVersion = version; - }; - } - _supportedProtocolVersions; - /** - * Callback for when the connection is closed for any reason. - * - * This is invoked when {@linkcode Protocol.close | close()} is called as well. - */ - onclose; - /** - * Callback for when an error occurs. - * - * Note that errors are not necessarily fatal; they are used for reporting any kind of exceptional condition out of band. - */ - onerror; - /** - * A handler to invoke for any request types that do not have their own handler installed. - */ - fallbackRequestHandler; - /** - * A handler to invoke for any notification types that do not have their own handler installed. - */ - fallbackNotificationHandler; - constructor(_options) { - this._options = _options; - this._supportedProtocolVersions = _options?.supportedProtocolVersions ?? auth_CUe6YdwF_SUPPORTED_PROTOCOL_VERSIONS; - this.setNotificationHandler("notifications/cancelled", (notification) => { - this._oncancel(notification); - }); - this.setNotificationHandler("notifications/progress", (notification) => { - this._onprogress(notification); - }); - this.setRequestHandler("ping", (_request) => ({})); - } - /** - * Drop consult for inbound messages whose transport did not classify them - * at the edge — long-lived channels such as stdio, where a role class may - * need to decline traffic the negotiated era has no answer for (the - * client-side inbound-request drop on modern-era connections: the - * 2026-07-28 era has no server→client request channel, and on stdio the - * client must never write JSON-RPC responses). - * - * Consulted ONLY when the transport supplied no - * {@linkcode MessageExtraInfo.classification}: edge-classified traffic - * never reaches the hook. Returning `'drop'` discards the message without - * writing any response (requests are surfaced via `onerror`). The base - * implementation returns `undefined`: unclassified traffic keeps today's - * dispatch path unchanged. Era selection never happens here — era is - * instance state, owned by the serving entry that constructed and - * connected the instance. - */ - _shouldDropInbound(_message) {} - /** - * The per-request `_meta` envelope this instance attaches to every outgoing - * request and notification, when one applies. The base implementation - * returns `undefined` (no envelope — the 2025-era posture, so legacy-era - * outbound traffic is byte-identical to a build without this seam). - * `Client` overrides it on a connection that negotiated a modern (2026-07-28+) - * era to return the reserved protocol-version / client-info / - * client-capabilities keys. User-supplied `_meta` keys take precedence over - * the auto-attached ones. - */ - _outboundMetaEnvelope() {} - /** - * Attach this instance's outbound `_meta` envelope (when one is configured) - * to a request or notification. A no-op when the seam returns `undefined` - * — the message returns by reference, so the legacy-era wire stays - * byte-identical. User-supplied `_meta` keys are spread last so they win - * over the auto-attached envelope keys. - */ - _envelopeOutbound(message) { - const envelope = this._outboundMetaEnvelope(); - if (envelope === void 0) return message; - const params = message.params ?? {}; - return { - ...message, - params: { - ...params, - _meta: { - ...envelope, - ...params._meta - } - } - }; - } - /** - * Extension point for non-`complete` decoded results in the response - * funnel: a result the wire codec discriminated into a kind other than - * `'complete'` or `'invalid'` is handed here for the role class to - * resolve. The base default surfaces it as a typed - * {@linkcode SdkErrorCode.UnsupportedResultType} error (no retry). - * - * Intended consumers (named so the seam stays accountable): - * - the `Client`'s multi-round-trip auto-fulfilment engine, which fulfils - * `'input_required'` results through the registered - * elicitation/sampling/roots handlers and retries via `flow.retry`; - * - a future client-side terminal-result handler for - * `subscriptions/listen`, when the spec defines one. - * - * `Server` instances never receive `input_required` responses on their - * outbound legs and leave the base behavior in place. - */ - _resolveNonCompleteResult(decoded, flow) { - return Promise.reject(new src_CX2iR2pK_SdkError(src_CX2iR2pK_SdkErrorCode.UnsupportedResultType, `Unsupported result type '${decoded.kind}' for ${flow.request.method}`, { - resultType: decoded.kind, - method: flow.request.method - })); - } - /** - * Protected accessor for a registered request handler. Used by role - * classes that dispatch synthesized requests through the same stored - * handler chain (e.g. the `Client` fulfilling an embedded multi-round-trip - * input request). - */ - _getRequestHandler(method) { - return this._requestHandlers.get(method); - } - async _oncancel(notification) { - if (!notification.params.requestId) return; - this._requestHandlerAbortControllers.get(notification.params.requestId)?.abort(notification.params.reason); - } - _setupTimeout(messageId, timeout, maxTotalTimeout, onTimeout, resetTimeoutOnProgress = false) { - this._timeoutInfo.set(messageId, { - timeoutId: setTimeout(onTimeout, timeout), - startTime: Date.now(), - timeout, - maxTotalTimeout, - resetTimeoutOnProgress, - onTimeout - }); - } - _resetTimeout(messageId) { - const info = this._timeoutInfo.get(messageId); - if (!info) return false; - const totalElapsed = Date.now() - info.startTime; - if (info.maxTotalTimeout && totalElapsed >= info.maxTotalTimeout) { - this._timeoutInfo.delete(messageId); - throw new src_CX2iR2pK_SdkError(src_CX2iR2pK_SdkErrorCode.RequestTimeout, "Maximum total timeout exceeded", { - maxTotalTimeout: info.maxTotalTimeout, - totalElapsed - }); - } - clearTimeout(info.timeoutId); - info.timeoutId = setTimeout(info.onTimeout, info.timeout); - return true; - } - _cleanupTimeout(messageId) { - const info = this._timeoutInfo.get(messageId); - if (info) { - clearTimeout(info.timeoutId); - this._timeoutInfo.delete(messageId); - } - } - /** - * Attaches to the given transport, starts it, and starts listening for messages. - * - * The caller assumes ownership of the {@linkcode Transport}, replacing any callbacks that have already been set, and expects that it is the only user of the {@linkcode Transport} instance going forward. - */ - async connect(transport) { - this._transport = transport; - const _onclose = this.transport?.onclose; - this._transport.onclose = () => { - try { - _onclose?.(); - } finally { - this._onclose(); - } - }; - const _onerror = this.transport?.onerror; - this._transport.onerror = (error) => { - _onerror?.(error); - this._onerror(error); - }; - const _onmessage = this._transport?.onmessage; - this._transport.onmessage = (message, extra) => { - _onmessage?.(message, extra); - if (src_CX2iR2pK_isJSONRPCResultResponse(message) || src_CX2iR2pK_isJSONRPCErrorResponse(message)) this._onresponse(message); - else if (src_CX2iR2pK_isJSONRPCRequest(message)) this._onrequest(message, extra); - else if (src_CX2iR2pK_isJSONRPCNotification(message)) this._onnotification(message, extra); - else this._onerror(/* @__PURE__ */ new Error(`Unknown message type: ${JSON.stringify(message)}`)); - }; - transport.setSupportedProtocolVersions?.(this._supportedProtocolVersions); - await this._transport.start(); - } - /** - * Transport-close hook. Subclass overrides MUST call `super._onclose()` - * after their own cleanup — base teardown (response-handler settlement, - * timeout clearing, in-flight request abort) does not run otherwise. - */ - _onclose() { - const responseHandlers = this._responseHandlers; - this._responseHandlers = /* @__PURE__ */ new Map(); - this._progressHandlers.clear(); - this._pendingDebouncedNotifications.clear(); - for (const info of this._timeoutInfo.values()) clearTimeout(info.timeoutId); - this._timeoutInfo.clear(); - const requestHandlerAbortControllers = this._requestHandlerAbortControllers; - this._requestHandlerAbortControllers = /* @__PURE__ */ new Map(); - const error = new src_CX2iR2pK_SdkError(src_CX2iR2pK_SdkErrorCode.ConnectionClosed, "Connection closed"); - this._transport = void 0; - try { - this.onclose?.(); - } finally { - for (const handler of responseHandlers.values()) handler(error); - for (const controller of requestHandlerAbortControllers.values()) controller.abort(error); - } - } - _onerror(error) { - this.onerror?.(error); - } - /** - * Inbound-notification dispatch. Subclass overrides MUST delegate - * unmatched traffic to `super._onnotification(rawNotification, extra)` — - * an override that consumes only what it owns and falls through to base - * dispatch for everything else. - */ - _onnotification(rawNotification, extra) { - const { message: notification } = liftWireOnlyMaterial(rawNotification, "notification"); - const codec = this._negotiatedWireCodec(); - if (extra?.classification === void 0 && this._shouldDropInbound(rawNotification) === "drop") return; - if (extra?.classification !== void 0) { - const classified = classifiedWireEra(extra.classification); - if (classified !== codec.era) { - this._onerror(/* @__PURE__ */ new Error(`Era mismatch on inbound notification '${notification.method}': classified as ${classified} but this instance serves ${codec.era}`)); - return; - } - } - if (isSpecNotificationMethod(notification.method) && !codec.hasNotificationMethod(notification.method)) return; - const handler = this._notificationHandlers.get(notification.method); - const fallback = this.fallbackNotificationHandler; - if (handler === void 0 && fallback === void 0) return; - Promise.resolve().then(() => handler === void 0 ? fallback(notification) : handler(notification, codec)).catch((error) => this._onerror(/* @__PURE__ */ new Error(`Uncaught error in notification handler: ${error}`))); - } - _onrequest(rawRequest, extra) { - const { message: request, lifted } = liftWireOnlyMaterial(rawRequest, "request"); - const codec = this._negotiatedWireCodec(); - if (extra?.classification === void 0 && this._shouldDropInbound(rawRequest) === "drop") { - this._onerror(/* @__PURE__ */ new Error(`Dropped inbound request '${rawRequest.method}': not servable on this connection's protocol era`)); - return; - } - const capturedTransport = this._transport; - const sendErrorResponse = (code, message, data) => { - const errorResponse = { - jsonrpc: "2.0", - id: request.id, - error: { - code, - message, - ...data !== void 0 && { data } - } - }; - capturedTransport?.send(errorResponse).catch((error) => this._onerror(/* @__PURE__ */ new Error(`Failed to send an error response: ${error}`))); - }; - if (extra?.classification !== void 0) { - const classified = classifiedWireEra(extra.classification); - if (classified !== codec.era) { - this._onerror(/* @__PURE__ */ new Error(`Era mismatch on inbound request '${request.method}': classified as ${classified} but this instance serves ${codec.era}`)); - const requested = extra.classification.revision ?? classified; - sendErrorResponse(src_CX2iR2pK_ProtocolErrorCode.UnsupportedProtocolVersion, `Unsupported protocol version: ${requested}`, { - supported: this._supportedProtocolVersions, - requested - }); - return; - } - } - if (isSpecRequestMethod(request.method) && !codec.hasRequestMethod(request.method)) { - sendErrorResponse(src_CX2iR2pK_ProtocolErrorCode.MethodNotFound, "Method not found"); - return; - } - const handler = this._requestHandlers.get(request.method) ?? this.fallbackRequestHandler; - if (handler === void 0) { - sendErrorResponse(src_CX2iR2pK_ProtocolErrorCode.MethodNotFound, "Method not found"); - return; - } - const envelopeError = codec.checkInboundEnvelope(lifted); - if (envelopeError !== void 0) { - sendErrorResponse(src_CX2iR2pK_ProtocolErrorCode.InvalidParams, envelopeError); - return; - } - const sendNotification = (notification, options) => this._notificationViaCodec(this._resolveOutboundCodec(notification.method), notification, { - ...options, - relatedRequestId: request.id - }); - const sendRequest = (r, resultSchema, options) => this._requestWithSchemaViaCodec(this._resolveOutboundCodec(r.method), r, resultSchema, { - ...options, - relatedRequestId: request.id - }); - const abortController = new AbortController(); - this._requestHandlerAbortControllers.set(request.id, abortController); - const partitionedInputResponses = lifted.inputResponses === void 0 ? void 0 : partitionInputResponses(lifted.inputResponses); - const baseCtx = { - sessionId: capturedTransport?.sessionId, - mcpReq: { - id: request.id, - method: request.method, - _meta: request.params?._meta, - ...lifted.envelope !== void 0 && { envelope: lifted.envelope }, - ...partitionedInputResponses !== void 0 && { inputResponses: partitionedInputResponses.accepted }, - ...partitionedInputResponses !== void 0 && partitionedInputResponses.droppedKeys.length > 0 && { droppedInputResponseKeys: partitionedInputResponses.droppedKeys }, - requestState: lifted.requestState === void 0 ? NO_REQUEST_STATE : requestStateAccessor(lifted.requestState), - signal: abortController.signal, - send: ((r, schemaOrOptions, maybeOptions) => { - const sendCodec = this._resolveOutboundCodec(r.method); - this._assertOutboundRequestInEra(sendCodec, r.method); - if (isStandardSchema(schemaOrOptions)) return sendRequest(r, schemaOrOptions, maybeOptions); - const validate = codecResultValidator(sendCodec, r.method); - if (validate === void 0) throw new TypeError(`'${r.method}' is not a spec method; pass a result schema as the second argument to ctx.mcpReq.send().`); - return sendRequest(r, validate, schemaOrOptions); - }), - notify: sendNotification - }, - http: extra?.authInfo ? { authInfo: extra.authInfo } : void 0 - }; - const ctx = this.buildContext(baseCtx, extra); - Promise.resolve().then(() => handler(request, ctx)).then(async (result) => { - if (abortController.signal.aborted) return; - let encoded; - try { - encoded = codec.encodeResult(request.method, result, this._outboundServerInfo()); - } catch (error) { - this._onerror(/* @__PURE__ */ new Error(`Failed to encode result for ${request.method}: ${error}`)); - sendErrorResponse(src_CX2iR2pK_ProtocolErrorCode.InternalError, "Internal error"); - return; - } - const response = { - result: encoded, - jsonrpc: "2.0", - id: request.id - }; - await capturedTransport?.send(response); - }, async (error) => { - if (abortController.signal.aborted) return; - const thrownCode = Number.isSafeInteger(error["code"]) ? error["code"] : src_CX2iR2pK_ProtocolErrorCode.InternalError; - const errorResponse = { - jsonrpc: "2.0", - id: request.id, - error: { - code: codec.encodeErrorCode(thrownCode), - message: error.message ?? "Internal error", - ...error["data"] !== void 0 && { data: error["data"] } - } - }; - await capturedTransport?.send(errorResponse); - }).catch((error) => this._onerror(/* @__PURE__ */ new Error(`Failed to send response: ${error}`))).finally(() => { - if (this._requestHandlerAbortControllers.get(request.id) === abortController) this._requestHandlerAbortControllers.delete(request.id); - }); - } - _onprogress(notification) { - const { progressToken, ...params } = notification.params; - const messageId = Number(progressToken); - const handler = this._progressHandlers.get(messageId); - if (!handler) { - this._onerror(/* @__PURE__ */ new Error(`Received a progress notification for an unknown token: ${JSON.stringify(notification)}`)); - return; - } - const responseHandler = this._responseHandlers.get(messageId); - const timeoutInfo = this._timeoutInfo.get(messageId); - if (timeoutInfo && responseHandler && timeoutInfo.resetTimeoutOnProgress) try { - this._resetTimeout(messageId); - } catch (error) { - this._responseHandlers.delete(messageId); - this._progressHandlers.delete(messageId); - this._cleanupTimeout(messageId); - responseHandler(error); - return; - } - handler(params); - } - /** - * Inbound-response dispatch. Subclass overrides MUST delegate unmatched - * traffic to `super._onresponse(response)` — an override that consumes - * only what it owns and falls through to base dispatch for everything - * else. - */ - _onresponse(response) { - const messageId = Number(response.id); - const handler = this._responseHandlers.get(messageId); - if (handler === void 0) { - this._onerror(/* @__PURE__ */ new Error(`Received a response for an unknown message ID: ${JSON.stringify(response)}`)); - return; - } - this._responseHandlers.delete(messageId); - this._cleanupTimeout(messageId); - this._progressHandlers.delete(messageId); - if (src_CX2iR2pK_isJSONRPCResultResponse(response)) handler(response); - else handler(src_CX2iR2pK_ProtocolError.fromError(response.error.code, response.error.message, response.error.data)); - } - get transport() { - return this._transport; - } - /** - * Closes the connection. - */ - async close() { - await this._transport?.close(); - } - request(request, schemaOrOptions, maybeOptions) { - const codec = this._resolveOutboundCodec(request.method); - this._assertOutboundRequestInEra(codec, request.method); - if (isStandardSchema(schemaOrOptions)) return this._requestWithSchemaViaCodec(codec, request, schemaOrOptions, maybeOptions); - const validate = codecResultValidator(codec, request.method); - if (validate === void 0) throw new TypeError(`'${request.method}' is not a spec method; pass a result schema as the second argument to request().`); - return this._requestWithSchemaViaCodec(codec, request, validate, schemaOrOptions); - } - /** - * The wire codec for this instance's negotiated era — the phase-2 truth: - * everything an established connection sends and receives resolves - * through it. Legacy until a version has been negotiated. - */ - _negotiatedWireCodec() { - return src_CX2iR2pK_codecForVersion(this._negotiatedProtocolVersion); - } - /** - * Protected accessor for the instance's negotiated wire codec, for role - * classes (Client/Server/McpServer) routing era-dependent behavior - * through the codec's function-only surface — `samplingResultVariant`, - * `outboundEnvelope`, `projectCallToolResult` — instead of branching on - * the protocol version themselves. - */ - _wireCodec() { - return this._negotiatedWireCodec(); - } - /** - * Outbound codec resolution: while the negotiated version is still unset - * (the negotiation window), lifecycle messages are bootstrap-pinned BY - * METHOD — they self-identify their era (`initialize` IS the legacy - * handshake, `server/discover` IS the modern probe). Once a version has - * been negotiated, the instance era is authoritative for everything — a - * negotiated session never re-routes a method onto the other era. - */ - _resolveOutboundCodec(method) { - if (this._negotiatedProtocolVersion === void 0) { - const pinned = bootstrapOutboundCodec(method); - if (pinned) return pinned; - } - return this._negotiatedWireCodec(); - } - /** - * Era gate for outbound requests — deletions are physical in BOTH - * directions: sending a spec method that the resolved era does not define - * dies locally with a typed error before anything reaches the transport. - * Methods outside the spec universe are consumer-owned extension methods - * and stay era-blind. - */ - _assertOutboundRequestInEra(codec, method) { - if (isSpecRequestMethod(method) && !codec.hasRequestMethod(method)) throw new src_CX2iR2pK_SdkError(src_CX2iR2pK_SdkErrorCode.MethodNotSupportedByProtocolVersion, `Method '${method}' is not supported by the negotiated protocol version (wire era ${codec.era})`, { - method, - era: codec.era - }); - } - /** - * Sends a request and waits for a response, using the provided schema for - * validation instead of the era registry's method-keyed entry. - * - * This is the internal implementation used by SDK methods whose result - * schema cannot be expressed as a method-keyed registry entry — the one - * surviving case is `server.createMessage`, whose result schema depends - * on the REQUEST params (tools vs no tools) — and by callers passing - * explicit compatibility schemas. Spec methods are still era-gated here: - * an explicit schema never smuggles a deleted method onto the wire. - */ - _requestWithSchema(request, resultSchema, options) { - const codec = this._resolveOutboundCodec(request.method); - this._assertOutboundRequestInEra(codec, request.method); - return this._requestWithSchemaViaCodec(codec, request, resultSchema, options); - } - /** - * The request funnel proper, keyed by the resolved era codec: the codec - * owns result decoding (raw-first `resultType` discrimination — V-1 — - * and the era's lift posture) before the schema validation step. - */ - _requestWithSchemaViaCodec(codec, request, resultSchema, options) { - const { relatedRequestId, resumptionToken, onresumptiontoken, headers } = options ?? {}; - const flowStartedAt = Date.now(); - let onAbort; - let cleanupMessageId; - return new Promise((resolve, reject) => { - const earlyReject = (error) => { - reject(error); - }; - if (!this._transport) { - earlyReject(/* @__PURE__ */ new Error("Not connected")); - return; - } - if (this._options?.enforceStrictCapabilities === true) try { - this.assertCapabilityForMethod(request.method); - } catch (error) { - earlyReject(error); - return; - } - if (options?.signal?.aborted) { - const reason = options.signal.reason; - throw reason instanceof src_CX2iR2pK_SdkError ? reason : new src_CX2iR2pK_SdkError(src_CX2iR2pK_SdkErrorCode.RequestTimeout, String(reason)); - } - const requestAbort = codec.era === src_CX2iR2pK_MODERN_WIRE_REVISION && this._transport.hasPerRequestStream === true ? new AbortController() : void 0; - const messageId = this._requestMessageId++; - cleanupMessageId = messageId; - const jsonrpcRequest = { - ...request, - jsonrpc: "2.0", - id: messageId - }; - if (options?.onprogress) { - this._progressHandlers.set(messageId, options.onprogress); - jsonrpcRequest.params = { - ...request.params, - _meta: { - ...request.params?._meta, - progressToken: messageId - } - }; - } - const outbound = this._envelopeOutbound(jsonrpcRequest); - let responseReceived = false; - const cancel = (reason) => { - if (responseReceived) return; - this._progressHandlers.delete(messageId); - if (requestAbort === void 0) this._transport?.send(this._envelopeOutbound({ - jsonrpc: "2.0", - method: "notifications/cancelled", - params: { - requestId: messageId, - reason: String(reason) - } - }), { - relatedRequestId, - resumptionToken, - onresumptiontoken - }).catch((error) => this._onerror(/* @__PURE__ */ new Error(`Failed to send cancellation: ${error}`))); - else requestAbort.abort(); - reject(reason instanceof src_CX2iR2pK_SdkError ? reason : new src_CX2iR2pK_SdkError(src_CX2iR2pK_SdkErrorCode.RequestTimeout, String(reason))); - }; - this._responseHandlers.set(messageId, (response) => { - if (options?.signal?.aborted) return; - responseReceived = true; - if (response instanceof Error) return reject(response); - let decoded; - try { - decoded = codec.decodeResult(request.method, response.result); - } catch (error) { - return reject(error instanceof Error ? error : new Error(String(error))); - } - if (decoded.kind === "invalid") return reject(decoded.error); - if (decoded.kind === "input_required") { - if (options?.allowInputRequired === true) return resolve(manualInputRequiredValue(decoded)); - const flow = { - codec, - request, - resultSchema, - options, - flowStartedAt, - retry: (params, legOptions) => this._requestWithSchemaViaCodec(codec, params === void 0 ? { method: request.method } : { - method: request.method, - params - }, resultSchema, legOptions) - }; - return resolve(this._resolveNonCompleteResult(decoded, flow)); - } - const result = decoded.result; - validateStandardSchema(resultSchema, result).then((parseResult) => { - if (parseResult.success) resolve(parseResult.data); - else reject(new src_CX2iR2pK_SdkError(src_CX2iR2pK_SdkErrorCode.InvalidResult, `Invalid result for ${request.method}: ${parseResult.error}`)); - }, reject); - }); - onAbort = () => cancel(options?.signal?.reason); - options?.signal?.addEventListener("abort", onAbort, { once: true }); - const timeout = options?.timeout ?? DEFAULT_REQUEST_TIMEOUT_MSEC; - const timeoutHandler = () => cancel(new src_CX2iR2pK_SdkError(src_CX2iR2pK_SdkErrorCode.RequestTimeout, "Request timed out", { timeout })); - this._setupTimeout(messageId, timeout, options?.maxTotalTimeout, timeoutHandler, options?.resetTimeoutOnProgress ?? false); - this._transport.send(outbound, { - relatedRequestId, - resumptionToken, - onresumptiontoken, - headers, - requestSignal: requestAbort?.signal - }).catch((error) => { - this._progressHandlers.delete(messageId); - reject(error); - }); - }).finally(() => { - if (onAbort) options?.signal?.removeEventListener("abort", onAbort); - if (cleanupMessageId !== void 0) { - this._responseHandlers.delete(cleanupMessageId); - this._cleanupTimeout(cleanupMessageId); - } - }); - } - /** - * Emits a notification, which is a one-way message that does not expect a response. - */ - async notification(notification, options) { - return this._notificationViaCodec(this._resolveOutboundCodec(notification.method), notification, options); - } - /** - * The notification funnel proper, keyed by the resolved era codec — - * direct sends and related notifications (`ctx.mcpReq.notify`) alike - * resolve through the instance's negotiated era at send time. - */ - async _notificationViaCodec(codec, notification, options) { - if (!this._transport) throw new src_CX2iR2pK_SdkError(src_CX2iR2pK_SdkErrorCode.NotConnected, "Not connected"); - if (isSpecNotificationMethod(notification.method) && !codec.hasNotificationMethod(notification.method)) throw new src_CX2iR2pK_SdkError(src_CX2iR2pK_SdkErrorCode.MethodNotSupportedByProtocolVersion, `Notification '${notification.method}' is not supported by the negotiated protocol version (wire era ${codec.era})`, { - method: notification.method, - era: codec.era - }); - this.assertNotificationCapability(notification.method); - const jsonrpcNotification = this._envelopeOutbound({ - jsonrpc: "2.0", - ...notification - }); - if ((this._options?.debouncedNotificationMethods ?? []).includes(notification.method) && !notification.params && !options?.relatedRequestId) { - if (this._pendingDebouncedNotifications.has(notification.method)) return; - this._pendingDebouncedNotifications.add(notification.method); - Promise.resolve().then(() => { - this._pendingDebouncedNotifications.delete(notification.method); - if (!this._transport) return; - this._transport?.send(jsonrpcNotification, options).catch((error) => this._onerror(error)); - }); - return; - } - await this._transport.send(jsonrpcNotification, options); - } - setRequestHandler(method, schemasOrHandler, maybeHandler) { - this.assertRequestHandlerCapability(method); - let stored; - if (typeof schemasOrHandler === "function") { - if (!isSpecRequestMethod(method)) throw new TypeError(`'${method}' is not a spec request method; pass schemas as the second argument to setRequestHandler().`); - stored = (request, ctx) => { - const dispatchCodec = this._negotiatedWireCodec(); - let outcome = dispatchCodec.validateRequest(method, request); - if (!outcome.ok && outcome.reason === "not-in-era") outcome = dispatchCodec.validateInputRequest(method, request); - if (!outcome.ok) { - if (outcome.reason === "not-in-era") throw new src_CX2iR2pK_ProtocolError(src_CX2iR2pK_ProtocolErrorCode.InternalError, `No wire schema for ${method} in the resolved era`); - throw new Error(outcome.message); - } - return Promise.resolve(schemasOrHandler(outcome.value, ctx)); - }; - } else if (maybeHandler) stored = async (request, ctx) => { - const parsed = await validateStandardSchema(schemasOrHandler.params, { ...request.params }); - if (!parsed.success) throw new src_CX2iR2pK_ProtocolError(src_CX2iR2pK_ProtocolErrorCode.InvalidParams, `Invalid params for ${method}: ${parsed.error}`); - return maybeHandler(parsed.data, ctx); - }; - else throw new TypeError("setRequestHandler: handler is required"); - this._requestHandlers.set(method, this._wrapHandler(method, stored)); - } - /** - * Hook for subclasses to wrap a registered request handler with role-specific - * validation or behavior (e.g. `Server` validates `tools/call` results, `Client` - * validates `elicitation/create` mode and result). Runs for both the 2-arg and - * 3-arg registration paths. The default implementation is identity. - * - * Subclasses overriding this hook avoid redeclaring `setRequestHandler`'s overload set. - */ - _wrapHandler(_method, handler) { - return handler; - } - /** - * Hook for subclasses to supply the implementation identity the 2026-era - * encode seam stamps into outbound result `_meta` under - * `io.modelcontextprotocol/serverInfo` (spec PR #3002: servers SHOULD - * identify themselves on every response). The default is `undefined` — no - * stamp. Only `Server` overrides this: the key identifies the software - * producing a response, and the 2025-era codec never stamps anything - * regardless (the never-stamp guarantee). - */ - _outboundServerInfo() {} - /** - * Removes the request handler for the given method. - */ - removeRequestHandler(method) { - this._requestHandlers.delete(method); - } - /** - * Asserts that a request handler has not already been set for the given method, in preparation for a new one being automatically installed. - */ - assertCanSetRequestHandler(method) { - if (this._requestHandlers.has(method)) throw new Error(`A request handler for ${method} already exists, which would be overridden`); - } - setNotificationHandler(method, schemasOrHandler, maybeHandler) { - if (typeof schemasOrHandler === "function") { - if (!isSpecNotificationMethod(method)) throw new TypeError(`'${method}' is not a spec notification method; pass schemas as the second argument to setNotificationHandler().`); - this._notificationHandlers.set(method, (notification, codec) => { - const outcome = codec.validateNotification(method, notification); - if (!outcome.ok) { - if (outcome.reason === "not-in-era") throw new src_CX2iR2pK_ProtocolError(src_CX2iR2pK_ProtocolErrorCode.InternalError, `No wire schema for ${method} in the resolved era`); - throw new Error(outcome.message); - } - return Promise.resolve(schemasOrHandler(outcome.value)); - }); - return; - } - if (!maybeHandler) throw new TypeError("setNotificationHandler: handler is required"); - this._notificationHandlers.set(method, async (notification) => { - const parsed = await validateStandardSchema(schemasOrHandler.params, { ...notification.params }); - if (!parsed.success) throw new src_CX2iR2pK_ProtocolError(src_CX2iR2pK_ProtocolErrorCode.InvalidParams, `Invalid params for notification ${method}: ${parsed.error}`); - await maybeHandler(parsed.data, notification); - }); - } - /** - * Removes the notification handler for the given method. - */ - removeNotificationHandler(method) { - this._notificationHandlers.delete(method); - } -}; -function isPlainObject$1(value) { - return value !== null && typeof value === "object" && !Array.isArray(value); -} -function mergeCapabilities(base, additional) { - const result = { ...base }; - for (const key in additional) { - const k = key; - const addValue = additional[k]; - if (addValue === void 0) continue; - const baseValue = result[k]; - result[k] = isPlainObject$1(baseValue) && isPlainObject$1(addValue) ? { - ...baseValue, - ...addValue - } : addValue; - } - return result; -} - -//#endregion -//#region ../core-internal/src/shared/inputRequiredEngine.ts -function src_CX2iR2pK_isPlainObject(value) { - return typeof value === "object" && value !== null && !Array.isArray(value); -} -/** -* Splits a retried request's `inputResponses` map into the BARE response -* entries the spec defines and everything else. The spec's embedded responses -* are the bare result objects (an `ElicitResult`, `CreateMessageResult`, or -* `ListRootsResult`); a wrapped `{method, result}` envelope (a shape some -* peers emit) is never accepted as a response — its key is recorded so the -* handler can re-issue the corresponding input request. -*/ -function partitionInputResponses(inputResponses) { - const accepted = {}; - const droppedKeys = []; - if (!src_CX2iR2pK_isPlainObject(inputResponses)) return { - accepted, - droppedKeys - }; - for (const [key, entry] of Object.entries(inputResponses)) { - if (!src_CX2iR2pK_isPlainObject(entry) || "method" in entry || "result" in entry) { - droppedKeys.push(key); - continue; - } - accepted[key] = entry; - } - return { - accepted, - droppedKeys - }; -} -/** -* Builds the manual-mode {@linkcode InputRequiredResult} value from the -* codec's decoded payload — what an `allowInputRequired: true` caller -* receives instead of the auto-fulfilled complete result. -*/ -function manualInputRequiredValue(decoded) { - return { - resultType: "input_required", - inputRequests: decoded.inputRequests, - ...decoded.requestState !== void 0 && { requestState: decoded.requestState } - }; -} - -//#endregion -//#region ../../node_modules/.pnpm/content-type@1.0.5/node_modules/content-type/index.js -/*! -* content-type -* Copyright(c) 2015 Douglas Christopher Wilson -* MIT Licensed -*/ -var require_content_type = /* @__PURE__ */ __commonJSMin(((exports) => { - /** - * RegExp to match *( ";" parameter ) in RFC 7231 sec 3.1.1.1 - * - * parameter = token "=" ( token / quoted-string ) - * token = 1*tchar - * tchar = "!" / "#" / "$" / "%" / "&" / "'" / "*" - * / "+" / "-" / "." / "^" / "_" / "`" / "|" / "~" - * / DIGIT / ALPHA - * ; any VCHAR, except delimiters - * quoted-string = DQUOTE *( qdtext / quoted-pair ) DQUOTE - * qdtext = HTAB / SP / %x21 / %x23-5B / %x5D-7E / obs-text - * obs-text = %x80-FF - * quoted-pair = "\" ( HTAB / SP / VCHAR / obs-text ) - */ - var PARAM_REGEXP = /; *([!#$%&'*+.^_`|~0-9A-Za-z-]+) *= *("(?:[\u000b\u0020\u0021\u0023-\u005b\u005d-\u007e\u0080-\u00ff]|\\[\u000b\u0020-\u00ff])*"|[!#$%&'*+.^_`|~0-9A-Za-z-]+) */g; - /** - * RegExp to match quoted-pair in RFC 7230 sec 3.2.6 - * - * quoted-pair = "\" ( HTAB / SP / VCHAR / obs-text ) - * obs-text = %x80-FF - */ - var QESC_REGEXP = /\\([\u000b\u0020-\u00ff])/g; - /** - * RegExp to match type in RFC 7231 sec 3.1.1.1 - * - * media-type = type "/" subtype - * type = token - * subtype = token - */ - var TYPE_REGEXP = /^[!#$%&'*+.^_`|~0-9A-Za-z-]+\/[!#$%&'*+.^_`|~0-9A-Za-z-]+$/; - exports.parse = parse; - /** - * Parse media type to object. - * - * @param {string|object} string - * @return {Object} - * @public - */ - function parse(string) { - if (!string) throw new TypeError("argument string is required"); - var header = typeof string === "object" ? getcontenttype(string) : string; - if (typeof header !== "string") throw new TypeError("argument string is required to be a string"); - var index = header.indexOf(";"); - var type = index !== -1 ? header.slice(0, index).trim() : header.trim(); - if (!TYPE_REGEXP.test(type)) throw new TypeError("invalid media type"); - var obj = new ContentType(type.toLowerCase()); - if (index !== -1) { - var key; - var match; - var value; - PARAM_REGEXP.lastIndex = index; - while (match = PARAM_REGEXP.exec(header)) { - if (match.index !== index) throw new TypeError("invalid parameter format"); - index += match[0].length; - key = match[1].toLowerCase(); - value = match[2]; - if (value.charCodeAt(0) === 34) { - value = value.slice(1, -1); - if (value.indexOf("\\") !== -1) value = value.replace(QESC_REGEXP, "$1"); - } - obj.parameters[key] = value; - } - if (index !== header.length) throw new TypeError("invalid parameter format"); - } - return obj; - } - /** - * Get content-type from req/res objects. - * - * @param {object} - * @return {Object} - * @private - */ - function getcontenttype(obj) { - var header; - if (typeof obj.getHeader === "function") header = obj.getHeader("content-type"); - else if (typeof obj.headers === "object") header = obj.headers && obj.headers["content-type"]; - if (typeof header !== "string") throw new TypeError("content-type header is missing from object"); - return header; - } - /** - * Class to represent a content type. - * @private - */ - function ContentType(type) { - this.parameters = Object.create(null); - this.type = type; - } -})); - -//#endregion -//#region ../core-internal/src/shared/mediaType.ts -var import_content_type = /* @__PURE__ */ __toESM(require_content_type(), 1); -/** -* Extracts the media type (the lowercased `type/subtype` pair, without -* parameters) from a raw `Content-Type` header value, or `undefined` when the -* header is missing or empty. -* -* Content-Type comparisons must use the parsed media type, never a substring -* search of the raw header: a value like `text/plain; a=application/json` -* contains the substring `application/json` but its media type is -* `text/plain`, and case variants or parameters make naive string comparison -* wrong in both directions. -* -* "Essence" is the WHATWG MIME Sniffing standard's term for the bare -* `type/subtype` pair (https://mimesniff.spec.whatwg.org/#mime-type-essence); -* the Fetch standard's request classification is defined against it -* (https://fetch.spec.whatwg.org/#cors-safelisted-request-header). -* -* Parsing is RFC 9110 (`content-type` package) first. When the parameter -* section is malformed (`application/json;`, `application/json; charset=`), -* browsers and most HTTP stacks still derive the media type from the segment -* before the first `;` — the fallback matches that widely-implemented -* behavior, so a header whose media type is unambiguous is not rejected for -* a sloppy parameter section. -*/ -function src_CX2iR2pK_mediaTypeEssence(header) { - if (!header) return; - try { - return import_content_type.parse(header).type; - } catch { - const essence = (header.split(";", 1)[0] ?? "").trim().toLowerCase(); - if (essence === "" || header.slice(essence.length).includes(",")) return; - return essence; - } -} -/** -* Whether a raw `Content-Type` header value denotes `application/json`. -* Parameters (for example `charset=utf-8`) are allowed and ignored; malformed -* parameter sections do not reject a header whose media type is unambiguously -* `application/json` (see `mediaTypeEssence` for the exact grammar). -*/ -function src_CX2iR2pK_isJsonContentType(header) { - if (header === "application/json") return true; - return src_CX2iR2pK_mediaTypeEssence(header) === "application/json"; -} - -//#endregion -//#region ../core-internal/src/shared/metadataUtils.ts -/** -* Utilities for working with {@linkcode BaseMetadata} objects. -*/ -/** -* Gets the display name for an object with {@linkcode BaseMetadata}. -* For tools, the precedence is: `title` → {@linkcode index.ToolAnnotations | annotations}.`title` → `name` -* For other objects: `title` → `name` -* This implements the spec requirement: "if no title is provided, name should be used for display purposes" -*/ -function getDisplayName(metadata) { - if (metadata.title !== void 0 && metadata.title !== "") return metadata.title; - if ("annotations" in metadata && metadata.annotations?.title) return metadata.annotations.title; - return metadata.name; -} - -//#endregion -//#region ../core-internal/src/shared/stdio.ts -const STDIO_DEFAULT_MAX_BUFFER_SIZE = 10 * 1024 * 1024; -/** -* Buffers a continuous stdio stream into discrete JSON-RPC messages. -*/ -var ReadBuffer = class { - _buffer; - _maxBufferSize; - constructor(options) { - this._maxBufferSize = options?.maxBufferSize ?? STDIO_DEFAULT_MAX_BUFFER_SIZE; - } - append(chunk) { - if ((this._buffer?.length ?? 0) + chunk.length > this._maxBufferSize) { - this.clear(); - throw new Error(`ReadBuffer exceeded maximum size of ${this._maxBufferSize} bytes`); - } - this._buffer = this._buffer ? Buffer.concat([this._buffer, chunk]) : chunk; - } - readMessage() { - while (this._buffer) { - const index = this._buffer.indexOf("\n"); - if (index === -1) return null; - const line = this._buffer.toString("utf8", 0, index).replace(/\r$/, ""); - this._buffer = this._buffer.subarray(index + 1); - try { - return deserializeMessage(line); - } catch (error) { - if (error instanceof SyntaxError) continue; - throw error; - } - } - return null; - } - clear() { - this._buffer = void 0; - } -}; -function deserializeMessage(line) { - return auth_CUe6YdwF_JSONRPCMessageSchema.parse(JSON.parse(line)); -} -function serializeMessage(message) { - return JSON.stringify(message) + "\n"; -} - -//#endregion -//#region ../core-internal/src/shared/toolNameValidation.ts -/** -* Tool name validation utilities according to SEP: Specify Format for Tool Names -* -* Tool names SHOULD be between 1 and 128 characters in length (inclusive). -* Tool names are case-sensitive. -* Allowed characters: uppercase and lowercase ASCII letters (`A-Z`, `a-z`), digits -* (`0-9`), underscore (`_`), dash (`-`), and dot (`.`). -* Tool names SHOULD NOT contain spaces, commas, or other special characters. -* -* @see {@link https://github.com/modelcontextprotocol/modelcontextprotocol/issues/986 | SEP-986: Specify Format for Tool Names} -*/ -/** -* Regular expression for valid tool names according to SEP-986 specification -*/ -const TOOL_NAME_REGEX = /^[A-Za-z0-9._-]{1,128}$/; -/** -* Validates a tool name according to the SEP specification -* @param name - The tool name to validate -* @returns An object containing validation result and any warnings -*/ -function validateToolName(name) { - const warnings = []; - if (name.length === 0) return { - isValid: false, - warnings: ["Tool name cannot be empty"] - }; - if (name.length > 128) return { - isValid: false, - warnings: [`Tool name exceeds maximum length of 128 characters (current: ${name.length})`] - }; - if (name.includes(" ")) warnings.push("Tool name contains spaces, which may cause parsing issues"); - if (name.includes(",")) warnings.push("Tool name contains commas, which may cause parsing issues"); - if (name.startsWith("-") || name.endsWith("-")) warnings.push("Tool name starts or ends with a dash, which may cause parsing issues in some contexts"); - if (name.startsWith(".") || name.endsWith(".")) warnings.push("Tool name starts or ends with a dot, which may cause parsing issues in some contexts"); - if (!TOOL_NAME_REGEX.test(name)) { - const invalidChars = [...name].filter((char) => !/[A-Za-z0-9._-]/.test(char)).filter((char, index, arr) => arr.indexOf(char) === index); - warnings.push(`Tool name contains invalid characters: ${invalidChars.map((c) => `"${c}"`).join(", ")}`, "Allowed characters are: A-Z, a-z, 0-9, underscore (_), dash (-), and dot (.)"); - return { - isValid: false, - warnings - }; - } - return { - isValid: true, - warnings - }; -} -/** -* Issues warnings for non-conforming tool names -* @param name - The tool name that triggered the warnings -* @param warnings - Array of warning messages -*/ -function issueToolNameWarning(name, warnings) { - if (warnings.length > 0) { - console.warn(`Tool name validation warning for "${name}":`); - for (const warning of warnings) console.warn(` - ${warning}`); - console.warn("Tool registration will proceed, but this may cause compatibility issues."); - console.warn("Consider updating the tool name to conform to the MCP tool naming standard."); - console.warn("See SEP: Specify Format for Tool Names (https://github.com/modelcontextprotocol/modelcontextprotocol/issues/986) for more details."); - } -} -/** -* Validates a tool name and issues warnings for non-conforming names -* @param name - The tool name to validate -* @returns `true` if the name is valid, `false` otherwise -*/ -function validateAndWarnToolName(name) { - const result = validateToolName(name); - issueToolNameWarning(name, result.warnings); - return result.isValid; -} - -//#endregion -//#region ../core-internal/src/shared/transport.ts -/** -* Normalizes `HeadersInit` to a plain `Record` for manipulation. -* Handles `Headers` objects, arrays of tuples, and plain objects. -*/ -function normalizeHeaders(headers) { - if (!headers) return {}; - if (headers instanceof Headers) return Object.fromEntries(headers.entries()); - if (Array.isArray(headers)) return Object.fromEntries(headers); - return { ...headers }; -} -/** -* Creates a fetch function that includes base `RequestInit` options. -* This ensures requests inherit settings like credentials, mode, headers, etc. from the base init. -* -* @param baseFetch - The base fetch function to wrap (defaults to global `fetch`) -* @param baseInit - The base `RequestInit` to merge with each request -* @returns A wrapped fetch function that merges base options with call-specific options -*/ -function createFetchWithInit(baseFetch = fetch, baseInit) { - if (!baseInit) return baseFetch; - return async (url, init) => { - return baseFetch(url, { - ...baseInit, - ...init, - headers: init?.headers ? { - ...normalizeHeaders(baseInit.headers), - ...normalizeHeaders(init.headers) - } : baseInit.headers - }); - }; -} - -//#endregion -//#region ../core-internal/src/shared/uriTemplate.ts -const MAX_TEMPLATE_LENGTH = 1e6; -const MAX_VARIABLE_LENGTH = 1e6; -const MAX_TEMPLATE_EXPRESSIONS = 1e4; -const MAX_REGEX_LENGTH = 1e6; -var src_CX2iR2pK_UriTemplate = class UriTemplate { - /** - * Returns true if the given string contains any URI template expressions. - * A template expression is a sequence of characters enclosed in curly braces, - * like `{foo}` or `{?bar}`. - */ - static isTemplate(str) { - return /\{[^}\s]+\}/.test(str); - } - static validateLength(str, max, context) { - if (str.length > max) throw new Error(`${context} exceeds maximum length of ${max} characters (got ${str.length})`); - } - template; - parts; - get variableNames() { - return this.parts.flatMap((part) => typeof part === "string" ? [] : part.names); - } - constructor(template) { - UriTemplate.validateLength(template, MAX_TEMPLATE_LENGTH, "Template"); - this.template = template; - this.parts = this.parse(template); - } - toString() { - return this.template; - } - parse(template) { - const parts = []; - let currentText = ""; - let i = 0; - let expressionCount = 0; - while (i < template.length) if (template[i] === "{") { - if (currentText) { - parts.push(currentText); - currentText = ""; - } - const end = template.indexOf("}", i); - if (end === -1) throw new Error("Unclosed template expression"); - expressionCount++; - if (expressionCount > MAX_TEMPLATE_EXPRESSIONS) throw new Error(`Template contains too many expressions (max ${MAX_TEMPLATE_EXPRESSIONS})`); - const expr = template.slice(i + 1, end); - const operator = this.getOperator(expr); - const exploded = expr.includes("*"); - const names = this.getNames(expr); - const name = names[0]; - for (const name$1 of names) UriTemplate.validateLength(name$1, MAX_VARIABLE_LENGTH, "Variable name"); - parts.push({ - name, - operator, - names, - exploded - }); - i = end + 1; - } else { - currentText += template[i]; - i++; - } - if (currentText) parts.push(currentText); - return parts; - } - getOperator(expr) { - return [ - "+", - "#", - ".", - "/", - "?", - "&" - ].find((op) => expr.startsWith(op)) || ""; - } - getNames(expr) { - const operator = this.getOperator(expr); - return expr.slice(operator.length).split(",").map((name) => name.replace("*", "").trim()).filter((name) => name.length > 0); - } - encodeValue(value, operator) { - UriTemplate.validateLength(value, MAX_VARIABLE_LENGTH, "Variable value"); - if (operator === "+" || operator === "#") return encodeURI(value); - return encodeURIComponent(value); - } - expandPart(part, variables) { - if (part.operator === "?" || part.operator === "&") { - const pairs = part.names.map((name) => { - const value$1 = variables[name]; - if (value$1 === void 0) return ""; - return `${name}=${Array.isArray(value$1) ? value$1.map((v) => this.encodeValue(v, part.operator)).join(",") : this.encodeValue(value$1.toString(), part.operator)}`; - }).filter((pair) => pair.length > 0); - if (pairs.length === 0) return ""; - return (part.operator === "?" ? "?" : "&") + pairs.join("&"); - } - if (part.names.length > 1) { - const values = part.names.map((name) => variables[name]).filter((v) => v !== void 0); - if (values.length === 0) return ""; - return values.map((v) => Array.isArray(v) ? v[0] : v).join(","); - } - const value = variables[part.name]; - if (value === void 0) return ""; - const encoded = (Array.isArray(value) ? value : [value]).map((v) => this.encodeValue(v, part.operator)); - switch (part.operator) { - case "": return encoded.join(","); - case "+": return encoded.join(","); - case "#": return "#" + encoded.join(","); - case ".": return "." + encoded.join("."); - case "/": return "/" + encoded.join("/"); - default: return encoded.join(","); - } - } - expand(variables) { - let result = ""; - let hasQueryParam = false; - for (const part of this.parts) { - if (typeof part === "string") { - result += part; - continue; - } - const expanded = this.expandPart(part, variables); - if (!expanded) continue; - result += (part.operator === "?" || part.operator === "&") && hasQueryParam ? expanded.replace("?", "&") : expanded; - if (part.operator === "?" || part.operator === "&") hasQueryParam = true; - } - return result; - } - escapeRegExp(str) { - return str.replaceAll(/[.*+?^${}()|[\]\\]/g, String.raw`\$&`); - } - partToRegExp(part) { - const patterns = []; - for (const name$1 of part.names) UriTemplate.validateLength(name$1, MAX_VARIABLE_LENGTH, "Variable name"); - if (part.operator === "?" || part.operator === "&") { - for (let i = 0; i < part.names.length; i++) { - const name$1 = part.names[i]; - const prefix = i === 0 ? "\\" + part.operator : "&"; - patterns.push({ - pattern: prefix + this.escapeRegExp(name$1) + "=([^&]+)", - name: name$1 - }); - } - return patterns; - } - let pattern; - const name = part.name; - switch (part.operator) { - case "": - pattern = part.exploded ? "([^/,]+(?:,[^/,]+)*)" : "([^/,]+)"; - break; - case "+": - case "#": - pattern = "(.+)"; - break; - case ".": - pattern = String.raw`\.([^/,]+)`; - break; - case "/": - pattern = "/" + (part.exploded ? "([^/,]+(?:,[^/,]+)*)" : "([^/,]+)"); - break; - default: pattern = "([^/]+)"; - } - patterns.push({ - pattern, - name - }); - return patterns; - } - match(uri) { - UriTemplate.validateLength(uri, MAX_TEMPLATE_LENGTH, "URI"); - let pattern = "^"; - const names = []; - for (const part of this.parts) if (typeof part === "string") pattern += this.escapeRegExp(part); - else { - const patterns = this.partToRegExp(part); - for (const { pattern: partPattern, name } of patterns) { - pattern += partPattern; - names.push({ - name, - exploded: part.exploded - }); - } - } - pattern += "$"; - UriTemplate.validateLength(pattern, MAX_REGEX_LENGTH, "Generated regex pattern"); - const regex = new RegExp(pattern); - const match = uri.match(regex); - if (!match) return null; - const result = {}; - for (const [i, name_] of names.entries()) { - const { name, exploded } = name_; - const value = match[i + 1]; - const cleanName = name.replace("*", ""); - result[cleanName] = exploded && value.includes(",") ? value.split(",") : value; - } - return result; - } -}; - -//#endregion -//#region ../core-internal/src/util/inMemory.ts -/** -* In-memory transport for creating clients and servers that talk to each other within the same process. -* -* Intended for testing and development. For production in-process connections, use -* `StreamableHTTPClientTransport` against a local server URL. -*/ -var src_CX2iR2pK_InMemoryTransport = class InMemoryTransport { - _otherTransport; - _messageQueue = []; - _closed = false; - onclose; - onerror; - onmessage; - sessionId; - /** - * Creates a pair of linked in-memory transports that can communicate with each other. One should be passed to a {@linkcode @modelcontextprotocol/client!client/client.Client | Client} and one to a {@linkcode @modelcontextprotocol/server!server/server.Server | Server}. - */ - static createLinkedPair() { - const clientTransport = new InMemoryTransport(); - const serverTransport = new InMemoryTransport(); - clientTransport._otherTransport = serverTransport; - serverTransport._otherTransport = clientTransport; - return [clientTransport, serverTransport]; - } - async start() { - while (this._messageQueue.length > 0) { - const queuedMessage = this._messageQueue.shift(); - this.onmessage?.(queuedMessage.message, queuedMessage.extra); - } - } - async close() { - if (this._closed) return; - this._closed = true; - const other = this._otherTransport; - this._otherTransport = void 0; - try { - await other?.close(); - } finally { - this.onclose?.(); - } - } - /** - * Sends a message with optional auth info. - * This is useful for testing authentication scenarios. - */ - async send(message, options) { - if (!this._otherTransport) throw new src_CX2iR2pK_SdkError(src_CX2iR2pK_SdkErrorCode.NotConnected, "Not connected"); - if (this._otherTransport.onmessage) this._otherTransport.onmessage(message, { authInfo: options?.authInfo }); - else this._otherTransport._messageQueue.push({ - message, - extra: { authInfo: options?.authInfo } - }); - } -}; - -//#endregion -//#region ../core-internal/src/util/zodCompat.ts -/** -* Zod-specific helpers for the v1-compat raw-shape shorthand on -* `registerTool`/`registerPrompt`. Kept separate from `standardSchema.ts` so -* that file stays library-agnostic per the Standard Schema spec. -*/ -function isZodV4Schema(v) { - return typeof v === "object" && v !== null && "_zod" in v; -} -function looksLikeZodV3(v) { - return typeof v === "object" && v !== null && !("_zod" in v) && "_def" in v && typeof v._def?.typeName === "string"; -} -/** -* Detects a "raw shape" — a plain object whose values are Zod field schemas, -* e.g. `{ name: z.string() }`. Powers the auto-wrap in -* {@linkcode normalizeRawShapeSchema}, which wraps with `z.object()`, so only -* Zod values are supported. -* -* @internal -*/ -function isZodRawShape(obj) { - if (typeof obj !== "object" || obj === null) return false; - if (isStandardSchema(obj)) return false; - const proto = Object.getPrototypeOf(obj); - if (proto !== Object.prototype && proto !== null) return false; - return Object.values(obj).every((v) => isZodV4Schema(v)); -} -/** -* Accepts either a {@linkcode StandardSchemaWithJSON} or a raw Zod shape -* `{ field: z.string() }` and returns a {@linkcode StandardSchemaWithJSON}. -* Raw shapes are wrapped with `z.object()` so the rest of the pipeline sees a -* uniform schema type; already-wrapped schemas pass through unchanged. -* -* @internal -*/ -function normalizeRawShapeSchema(schema) { - if (schema === void 0) return void 0; - if (isZodRawShape(schema)) return schemas_object(schema); - if (typeof schema === "object" && schema !== null && !isStandardSchema(schema) && Object.values(schema).some((v) => looksLikeZodV3(v))) throw new TypeError("Raw-shape inputSchema/outputSchema/argsSchema fields must be Zod v4 schemas. Got a Zod v3 field schema. Import from `zod/v4` (or upgrade your zod import), or wrap with `z.object({...})` yourself."); - if (!isStandardSchema(schema)) throw new TypeError("inputSchema/outputSchema/argsSchema must be a Standard Schema (e.g. z.object({...})) or a raw Zod shape ({ field: z.string() })."); - return schema; -} - -//#endregion -//#region ../core-internal/src/wire/preload.ts -/** -* Explicit warm-up entry for the lazy wire-schema layers. -* -* The per-revision wire schemas are built lazily: each era's schema set sits -* behind a memoized factory (`buildSchemas2025`/`buildSchemas2026`), and the -* registry/codec lookup maps above those factories are memoized the same way. -* That laziness is the right default on process-per-invocation runtimes (CLI -* tools, dev servers), where module evaluation IS startup latency and most -* short-lived processes never validate a message on both eras. -* -* On platforms that bill request CPU but not module evaluation — isolate-based -* edge/serverless runtimes such as Cloudflare Workers — the trade inverts: -* module-scope work runs during isolate warm-up outside any request, while -* lazy construction lands inside the first request's billed (and latency -* budgeted) CPU. `preloadSchemas()` lets deployments on such platforms move -* the one-time construction cost back to module scope by calling it at module -* scope themselves. The packages' own workerd shims already do this, so -* Workers deployments get eager construction automatically. -*/ -/** -* Eagerly builds every lazily-constructed wire-schema layer, so that no later -* validation pays schema-construction cost. -* -* Synchronous and idempotent: every layer is a memo, so the first call does -* all the work and subsequent calls return immediately. Reference identity is -* unaffected — this forces the same memos every lazy consumer pulls through. -* -* Call it at module scope on platforms that bill per-request CPU but not -* module evaluation (isolate-based edge/serverless runtimes), where deferring -* construction would move it into the first request of every fresh isolate: -* -* ```ts -* // from '@modelcontextprotocol/server' or '@modelcontextprotocol/client' — -* // each package bundles its own schema copy, so warm the one(s) you import. -* preloadSchemas(); // module scope — runs during isolate warm-up -* ``` -* -* On Node CLIs and other process-per-invocation runtimes, prefer the lazy -* default — there, module-scope construction is pure added boot latency. -*/ -function preloadSchemas() { - buildSchemas2025(); - buildSchemas2026(); - warmRegistryMaps2025(); - warmInputSchemaMaps2026(); - warmWireResultSchemas2026(); -} - -//#endregion -//#region ../core-internal/src/validators/fromJsonSchema.ts -/** -* Wrap a raw JSON Schema object as a {@linkcode StandardSchemaWithJSON} so it can be -* passed to `registerTool` / `registerPrompt`. Use this when you already have JSON -* Schema (e.g. from TypeBox, or hand-written) and want to register it without going -* through a Standard Schema library. -* -* The callback arguments will be typed `unknown` (raw JSON Schema has no TypeScript -* types attached). Cast at the call site, or use the generic `fromJsonSchema(...)`. -* -* @param schema - A JSON Schema object describing the expected shape -* @param validator - A validator provider. When importing `fromJsonSchema` from -* `@modelcontextprotocol/server` or `@modelcontextprotocol/client`, a runtime-appropriate -* default is provided automatically (AJV on Node.js, CfWorker on edge runtimes). -* -* @example -* ```ts source="./fromJsonSchema.examples.ts#fromJsonSchema_basicUsage" -* const inputSchema = fromJsonSchema<{ name: string }>( -* { type: 'object', properties: { name: { type: 'string' } }, required: ['name'] }, -* validator -* ); -* // Use with server.registerTool('greet', { inputSchema }, handler) -* ``` -*/ -function fromJsonSchema(schema, validator) { - const check = validator.getValidator(schema); - return { "~standard": { - version: 1, - vendor: "mcp", - jsonSchema: { - input: () => schema, - output: () => schema - }, - validate: (data) => { - const result = check(data); - return result.valid ? { value: result.data } : { issues: [{ message: result.errorMessage }] }; - } - } }; -} - -//#endregion - -//# sourceMappingURL=src-CX2iR2pK.mjs.map - - - -//#region ../../node_modules/.pnpm/ajv@8.18.0/node_modules/ajv/dist/compile/codegen/code.js -var require_code$1 = /* @__PURE__ */ __commonJSMin(((exports) => { - Object.defineProperty(exports, "__esModule", { value: true }); - exports.regexpCode = exports.getEsmExportName = exports.getProperty = exports.safeStringify = exports.stringify = exports.strConcat = exports.addCodeArg = exports.str = exports._ = exports.nil = exports._Code = exports.Name = exports.IDENTIFIER = exports._CodeOrName = void 0; - var _CodeOrName = class {}; - exports._CodeOrName = _CodeOrName; - exports.IDENTIFIER = /^[a-z$_][a-z$_0-9]*$/i; - var Name = class extends _CodeOrName { - constructor(s) { - super(); - if (!exports.IDENTIFIER.test(s)) throw new Error("CodeGen: name must be a valid identifier"); - this.str = s; - } - toString() { - return this.str; - } - emptyStr() { - return false; - } - get names() { - return { [this.str]: 1 }; - } - }; - exports.Name = Name; - var _Code = class extends _CodeOrName { - constructor(code) { - super(); - this._items = typeof code === "string" ? [code] : code; - } - toString() { - return this.str; - } - emptyStr() { - if (this._items.length > 1) return false; - const item = this._items[0]; - return item === "" || item === "\"\""; - } - get str() { - var _a; - return (_a = this._str) !== null && _a !== void 0 ? _a : this._str = this._items.reduce((s, c) => `${s}${c}`, ""); - } - get names() { - var _a; - return (_a = this._names) !== null && _a !== void 0 ? _a : this._names = this._items.reduce((names, c) => { - if (c instanceof Name) names[c.str] = (names[c.str] || 0) + 1; - return names; - }, {}); - } - }; - exports._Code = _Code; - exports.nil = new _Code(""); - function _(strs, ...args) { - const code = [strs[0]]; - let i = 0; - while (i < args.length) { - addCodeArg(code, args[i]); - code.push(strs[++i]); - } - return new _Code(code); - } - exports._ = _; - const plus = new _Code("+"); - function str(strs, ...args) { - const expr = [safeStringify(strs[0])]; - let i = 0; - while (i < args.length) { - expr.push(plus); - addCodeArg(expr, args[i]); - expr.push(plus, safeStringify(strs[++i])); - } - optimize(expr); - return new _Code(expr); - } - exports.str = str; - function addCodeArg(code, arg) { - if (arg instanceof _Code) code.push(...arg._items); - else if (arg instanceof Name) code.push(arg); - else code.push(interpolate(arg)); - } - exports.addCodeArg = addCodeArg; - function optimize(expr) { - let i = 1; - while (i < expr.length - 1) { - if (expr[i] === plus) { - const res = mergeExprItems(expr[i - 1], expr[i + 1]); - if (res !== void 0) { - expr.splice(i - 1, 3, res); - continue; - } - expr[i++] = "+"; - } - i++; - } - } - function mergeExprItems(a, b) { - if (b === "\"\"") return a; - if (a === "\"\"") return b; - if (typeof a == "string") { - if (b instanceof Name || a[a.length - 1] !== "\"") return; - if (typeof b != "string") return `${a.slice(0, -1)}${b}"`; - if (b[0] === "\"") return a.slice(0, -1) + b.slice(1); - return; - } - if (typeof b == "string" && b[0] === "\"" && !(a instanceof Name)) return `"${a}${b.slice(1)}`; - } - function strConcat(c1, c2) { - return c2.emptyStr() ? c1 : c1.emptyStr() ? c2 : str`${c1}${c2}`; - } - exports.strConcat = strConcat; - function interpolate(x) { - return typeof x == "number" || typeof x == "boolean" || x === null ? x : safeStringify(Array.isArray(x) ? x.join(",") : x); - } - function stringify(x) { - return new _Code(safeStringify(x)); - } - exports.stringify = stringify; - function safeStringify(x) { - return JSON.stringify(x).replace(/\u2028/g, "\\u2028").replace(/\u2029/g, "\\u2029"); - } - exports.safeStringify = safeStringify; - function getProperty(key) { - return typeof key == "string" && exports.IDENTIFIER.test(key) ? new _Code(`.${key}`) : _`[${key}]`; - } - exports.getProperty = getProperty; - function getEsmExportName(key) { - if (typeof key == "string" && exports.IDENTIFIER.test(key)) return new _Code(`${key}`); - throw new Error(`CodeGen: invalid export name: ${key}, use explicit $id name mapping`); - } - exports.getEsmExportName = getEsmExportName; - function regexpCode(rx) { - return new _Code(rx.toString()); - } - exports.regexpCode = regexpCode; -})); - -//#endregion -//#region ../../node_modules/.pnpm/ajv@8.18.0/node_modules/ajv/dist/compile/codegen/scope.js -var require_scope = /* @__PURE__ */ __commonJSMin(((exports) => { - Object.defineProperty(exports, "__esModule", { value: true }); - exports.ValueScope = exports.ValueScopeName = exports.Scope = exports.varKinds = exports.UsedValueState = void 0; - const code_1 = require_code$1(); - var ValueError = class extends Error { - constructor(name) { - super(`CodeGen: "code" for ${name} not defined`); - this.value = name.value; - } - }; - var UsedValueState; - (function(UsedValueState) { - UsedValueState[UsedValueState["Started"] = 0] = "Started"; - UsedValueState[UsedValueState["Completed"] = 1] = "Completed"; - })(UsedValueState || (exports.UsedValueState = UsedValueState = {})); - exports.varKinds = { - const: new code_1.Name("const"), - let: new code_1.Name("let"), - var: new code_1.Name("var") - }; - var Scope = class { - constructor({ prefixes, parent } = {}) { - this._names = {}; - this._prefixes = prefixes; - this._parent = parent; - } - toName(nameOrPrefix) { - return nameOrPrefix instanceof code_1.Name ? nameOrPrefix : this.name(nameOrPrefix); - } - name(prefix) { - return new code_1.Name(this._newName(prefix)); - } - _newName(prefix) { - const ng = this._names[prefix] || this._nameGroup(prefix); - return `${prefix}${ng.index++}`; - } - _nameGroup(prefix) { - var _a, _b; - if (((_b = (_a = this._parent) === null || _a === void 0 ? void 0 : _a._prefixes) === null || _b === void 0 ? void 0 : _b.has(prefix)) || this._prefixes && !this._prefixes.has(prefix)) throw new Error(`CodeGen: prefix "${prefix}" is not allowed in this scope`); - return this._names[prefix] = { - prefix, - index: 0 - }; - } - }; - exports.Scope = Scope; - var ValueScopeName = class extends code_1.Name { - constructor(prefix, nameStr) { - super(nameStr); - this.prefix = prefix; - } - setValue(value, { property, itemIndex }) { - this.value = value; - this.scopePath = (0, code_1._)`.${new code_1.Name(property)}[${itemIndex}]`; - } - }; - exports.ValueScopeName = ValueScopeName; - const line = (0, code_1._)`\n`; - var ValueScope = class extends Scope { - constructor(opts) { - super(opts); - this._values = {}; - this._scope = opts.scope; - this.opts = { - ...opts, - _n: opts.lines ? line : code_1.nil - }; - } - get() { - return this._scope; - } - name(prefix) { - return new ValueScopeName(prefix, this._newName(prefix)); - } - value(nameOrPrefix, value) { - var _a; - if (value.ref === void 0) throw new Error("CodeGen: ref must be passed in value"); - const name = this.toName(nameOrPrefix); - const { prefix } = name; - const valueKey = (_a = value.key) !== null && _a !== void 0 ? _a : value.ref; - let vs = this._values[prefix]; - if (vs) { - const _name = vs.get(valueKey); - if (_name) return _name; - } else vs = this._values[prefix] = /* @__PURE__ */ new Map(); - vs.set(valueKey, name); - const s = this._scope[prefix] || (this._scope[prefix] = []); - const itemIndex = s.length; - s[itemIndex] = value.ref; - name.setValue(value, { - property: prefix, - itemIndex - }); - return name; - } - getValue(prefix, keyOrRef) { - const vs = this._values[prefix]; - if (!vs) return; - return vs.get(keyOrRef); - } - scopeRefs(scopeName, values = this._values) { - return this._reduceValues(values, (name) => { - if (name.scopePath === void 0) throw new Error(`CodeGen: name "${name}" has no value`); - return (0, code_1._)`${scopeName}${name.scopePath}`; - }); - } - scopeCode(values = this._values, usedValues, getCode) { - return this._reduceValues(values, (name) => { - if (name.value === void 0) throw new Error(`CodeGen: name "${name}" has no value`); - return name.value.code; - }, usedValues, getCode); - } - _reduceValues(values, valueCode, usedValues = {}, getCode) { - let code = code_1.nil; - for (const prefix in values) { - const vs = values[prefix]; - if (!vs) continue; - const nameSet = usedValues[prefix] = usedValues[prefix] || /* @__PURE__ */ new Map(); - vs.forEach((name) => { - if (nameSet.has(name)) return; - nameSet.set(name, UsedValueState.Started); - let c = valueCode(name); - if (c) { - const def = this.opts.es5 ? exports.varKinds.var : exports.varKinds.const; - code = (0, code_1._)`${code}${def} ${name} = ${c};${this.opts._n}`; - } else if (c = getCode === null || getCode === void 0 ? void 0 : getCode(name)) code = (0, code_1._)`${code}${c}${this.opts._n}`; - else throw new ValueError(name); - nameSet.set(name, UsedValueState.Completed); - }); - } - return code; - } - }; - exports.ValueScope = ValueScope; -})); - -//#endregion -//#region ../../node_modules/.pnpm/ajv@8.18.0/node_modules/ajv/dist/compile/codegen/index.js -var require_codegen = /* @__PURE__ */ __commonJSMin(((exports) => { - Object.defineProperty(exports, "__esModule", { value: true }); - exports.or = exports.and = exports.not = exports.CodeGen = exports.operators = exports.varKinds = exports.ValueScopeName = exports.ValueScope = exports.Scope = exports.Name = exports.regexpCode = exports.stringify = exports.getProperty = exports.nil = exports.strConcat = exports.str = exports._ = void 0; - const code_1 = require_code$1(); - const scope_1 = require_scope(); - var code_2 = require_code$1(); - Object.defineProperty(exports, "_", { - enumerable: true, - get: function() { - return code_2._; - } - }); - Object.defineProperty(exports, "str", { - enumerable: true, - get: function() { - return code_2.str; - } - }); - Object.defineProperty(exports, "strConcat", { - enumerable: true, - get: function() { - return code_2.strConcat; - } - }); - Object.defineProperty(exports, "nil", { - enumerable: true, - get: function() { - return code_2.nil; - } - }); - Object.defineProperty(exports, "getProperty", { - enumerable: true, - get: function() { - return code_2.getProperty; - } - }); - Object.defineProperty(exports, "stringify", { - enumerable: true, - get: function() { - return code_2.stringify; - } - }); - Object.defineProperty(exports, "regexpCode", { - enumerable: true, - get: function() { - return code_2.regexpCode; - } - }); - Object.defineProperty(exports, "Name", { - enumerable: true, - get: function() { - return code_2.Name; - } - }); - var scope_2 = require_scope(); - Object.defineProperty(exports, "Scope", { - enumerable: true, - get: function() { - return scope_2.Scope; - } - }); - Object.defineProperty(exports, "ValueScope", { - enumerable: true, - get: function() { - return scope_2.ValueScope; - } - }); - Object.defineProperty(exports, "ValueScopeName", { - enumerable: true, - get: function() { - return scope_2.ValueScopeName; - } - }); - Object.defineProperty(exports, "varKinds", { - enumerable: true, - get: function() { - return scope_2.varKinds; - } - }); - exports.operators = { - GT: new code_1._Code(">"), - GTE: new code_1._Code(">="), - LT: new code_1._Code("<"), - LTE: new code_1._Code("<="), - EQ: new code_1._Code("==="), - NEQ: new code_1._Code("!=="), - NOT: new code_1._Code("!"), - OR: new code_1._Code("||"), - AND: new code_1._Code("&&"), - ADD: new code_1._Code("+") - }; - var Node = class { - optimizeNodes() { - return this; - } - optimizeNames(_names, _constants) { - return this; - } - }; - var Def = class extends Node { - constructor(varKind, name, rhs) { - super(); - this.varKind = varKind; - this.name = name; - this.rhs = rhs; - } - render({ es5, _n }) { - const varKind = es5 ? scope_1.varKinds.var : this.varKind; - const rhs = this.rhs === void 0 ? "" : ` = ${this.rhs}`; - return `${varKind} ${this.name}${rhs};` + _n; - } - optimizeNames(names, constants) { - if (!names[this.name.str]) return; - if (this.rhs) this.rhs = optimizeExpr(this.rhs, names, constants); - return this; - } - get names() { - return this.rhs instanceof code_1._CodeOrName ? this.rhs.names : {}; - } - }; - var Assign = class extends Node { - constructor(lhs, rhs, sideEffects) { - super(); - this.lhs = lhs; - this.rhs = rhs; - this.sideEffects = sideEffects; - } - render({ _n }) { - return `${this.lhs} = ${this.rhs};` + _n; - } - optimizeNames(names, constants) { - if (this.lhs instanceof code_1.Name && !names[this.lhs.str] && !this.sideEffects) return; - this.rhs = optimizeExpr(this.rhs, names, constants); - return this; - } - get names() { - return addExprNames(this.lhs instanceof code_1.Name ? {} : { ...this.lhs.names }, this.rhs); - } - }; - var AssignOp = class extends Assign { - constructor(lhs, op, rhs, sideEffects) { - super(lhs, rhs, sideEffects); - this.op = op; - } - render({ _n }) { - return `${this.lhs} ${this.op}= ${this.rhs};` + _n; - } - }; - var Label = class extends Node { - constructor(label) { - super(); - this.label = label; - this.names = {}; - } - render({ _n }) { - return `${this.label}:` + _n; - } - }; - var Break = class extends Node { - constructor(label) { - super(); - this.label = label; - this.names = {}; - } - render({ _n }) { - return `break${this.label ? ` ${this.label}` : ""};` + _n; - } - }; - var Throw = class extends Node { - constructor(error) { - super(); - this.error = error; - } - render({ _n }) { - return `throw ${this.error};` + _n; - } - get names() { - return this.error.names; - } - }; - var AnyCode = class extends Node { - constructor(code) { - super(); - this.code = code; - } - render({ _n }) { - return `${this.code};` + _n; - } - optimizeNodes() { - return `${this.code}` ? this : void 0; - } - optimizeNames(names, constants) { - this.code = optimizeExpr(this.code, names, constants); - return this; - } - get names() { - return this.code instanceof code_1._CodeOrName ? this.code.names : {}; - } - }; - var ParentNode = class extends Node { - constructor(nodes = []) { - super(); - this.nodes = nodes; - } - render(opts) { - return this.nodes.reduce((code, n) => code + n.render(opts), ""); - } - optimizeNodes() { - const { nodes } = this; - let i = nodes.length; - while (i--) { - const n = nodes[i].optimizeNodes(); - if (Array.isArray(n)) nodes.splice(i, 1, ...n); - else if (n) nodes[i] = n; - else nodes.splice(i, 1); - } - return nodes.length > 0 ? this : void 0; - } - optimizeNames(names, constants) { - const { nodes } = this; - let i = nodes.length; - while (i--) { - const n = nodes[i]; - if (n.optimizeNames(names, constants)) continue; - subtractNames(names, n.names); - nodes.splice(i, 1); - } - return nodes.length > 0 ? this : void 0; - } - get names() { - return this.nodes.reduce((names, n) => addNames(names, n.names), {}); - } - }; - var BlockNode = class extends ParentNode { - render(opts) { - return "{" + opts._n + super.render(opts) + "}" + opts._n; - } - }; - var Root = class extends ParentNode {}; - var Else = class extends BlockNode {}; - Else.kind = "else"; - var If = class If extends BlockNode { - constructor(condition, nodes) { - super(nodes); - this.condition = condition; - } - render(opts) { - let code = `if(${this.condition})` + super.render(opts); - if (this.else) code += "else " + this.else.render(opts); - return code; - } - optimizeNodes() { - super.optimizeNodes(); - const cond = this.condition; - if (cond === true) return this.nodes; - let e = this.else; - if (e) { - const ns = e.optimizeNodes(); - e = this.else = Array.isArray(ns) ? new Else(ns) : ns; - } - if (e) { - if (cond === false) return e instanceof If ? e : e.nodes; - if (this.nodes.length) return this; - return new If(not(cond), e instanceof If ? [e] : e.nodes); - } - if (cond === false || !this.nodes.length) return void 0; - return this; - } - optimizeNames(names, constants) { - var _a; - this.else = (_a = this.else) === null || _a === void 0 ? void 0 : _a.optimizeNames(names, constants); - if (!(super.optimizeNames(names, constants) || this.else)) return; - this.condition = optimizeExpr(this.condition, names, constants); - return this; - } - get names() { - const names = super.names; - addExprNames(names, this.condition); - if (this.else) addNames(names, this.else.names); - return names; - } - }; - If.kind = "if"; - var For = class extends BlockNode {}; - For.kind = "for"; - var ForLoop = class extends For { - constructor(iteration) { - super(); - this.iteration = iteration; - } - render(opts) { - return `for(${this.iteration})` + super.render(opts); - } - optimizeNames(names, constants) { - if (!super.optimizeNames(names, constants)) return; - this.iteration = optimizeExpr(this.iteration, names, constants); - return this; - } - get names() { - return addNames(super.names, this.iteration.names); - } - }; - var ForRange = class extends For { - constructor(varKind, name, from, to) { - super(); - this.varKind = varKind; - this.name = name; - this.from = from; - this.to = to; - } - render(opts) { - const varKind = opts.es5 ? scope_1.varKinds.var : this.varKind; - const { name, from, to } = this; - return `for(${varKind} ${name}=${from}; ${name}<${to}; ${name}++)` + super.render(opts); - } - get names() { - return addExprNames(addExprNames(super.names, this.from), this.to); - } - }; - var ForIter = class extends For { - constructor(loop, varKind, name, iterable) { - super(); - this.loop = loop; - this.varKind = varKind; - this.name = name; - this.iterable = iterable; - } - render(opts) { - return `for(${this.varKind} ${this.name} ${this.loop} ${this.iterable})` + super.render(opts); - } - optimizeNames(names, constants) { - if (!super.optimizeNames(names, constants)) return; - this.iterable = optimizeExpr(this.iterable, names, constants); - return this; - } - get names() { - return addNames(super.names, this.iterable.names); - } - }; - var Func = class extends BlockNode { - constructor(name, args, async) { - super(); - this.name = name; - this.args = args; - this.async = async; - } - render(opts) { - return `${this.async ? "async " : ""}function ${this.name}(${this.args})` + super.render(opts); - } - }; - Func.kind = "func"; - var Return = class extends ParentNode { - render(opts) { - return "return " + super.render(opts); - } - }; - Return.kind = "return"; - var Try = class extends BlockNode { - render(opts) { - let code = "try" + super.render(opts); - if (this.catch) code += this.catch.render(opts); - if (this.finally) code += this.finally.render(opts); - return code; - } - optimizeNodes() { - var _a, _b; - super.optimizeNodes(); - (_a = this.catch) === null || _a === void 0 || _a.optimizeNodes(); - (_b = this.finally) === null || _b === void 0 || _b.optimizeNodes(); - return this; - } - optimizeNames(names, constants) { - var _a, _b; - super.optimizeNames(names, constants); - (_a = this.catch) === null || _a === void 0 || _a.optimizeNames(names, constants); - (_b = this.finally) === null || _b === void 0 || _b.optimizeNames(names, constants); - return this; - } - get names() { - const names = super.names; - if (this.catch) addNames(names, this.catch.names); - if (this.finally) addNames(names, this.finally.names); - return names; - } - }; - var Catch = class extends BlockNode { - constructor(error) { - super(); - this.error = error; - } - render(opts) { - return `catch(${this.error})` + super.render(opts); - } - }; - Catch.kind = "catch"; - var Finally = class extends BlockNode { - render(opts) { - return "finally" + super.render(opts); - } - }; - Finally.kind = "finally"; - var CodeGen = class { - constructor(extScope, opts = {}) { - this._values = {}; - this._blockStarts = []; - this._constants = {}; - this.opts = { - ...opts, - _n: opts.lines ? "\n" : "" - }; - this._extScope = extScope; - this._scope = new scope_1.Scope({ parent: extScope }); - this._nodes = [new Root()]; - } - toString() { - return this._root.render(this.opts); - } - name(prefix) { - return this._scope.name(prefix); - } - scopeName(prefix) { - return this._extScope.name(prefix); - } - scopeValue(prefixOrName, value) { - const name = this._extScope.value(prefixOrName, value); - (this._values[name.prefix] || (this._values[name.prefix] = /* @__PURE__ */ new Set())).add(name); - return name; - } - getScopeValue(prefix, keyOrRef) { - return this._extScope.getValue(prefix, keyOrRef); - } - scopeRefs(scopeName) { - return this._extScope.scopeRefs(scopeName, this._values); - } - scopeCode() { - return this._extScope.scopeCode(this._values); - } - _def(varKind, nameOrPrefix, rhs, constant) { - const name = this._scope.toName(nameOrPrefix); - if (rhs !== void 0 && constant) this._constants[name.str] = rhs; - this._leafNode(new Def(varKind, name, rhs)); - return name; - } - const(nameOrPrefix, rhs, _constant) { - return this._def(scope_1.varKinds.const, nameOrPrefix, rhs, _constant); - } - let(nameOrPrefix, rhs, _constant) { - return this._def(scope_1.varKinds.let, nameOrPrefix, rhs, _constant); - } - var(nameOrPrefix, rhs, _constant) { - return this._def(scope_1.varKinds.var, nameOrPrefix, rhs, _constant); - } - assign(lhs, rhs, sideEffects) { - return this._leafNode(new Assign(lhs, rhs, sideEffects)); - } - add(lhs, rhs) { - return this._leafNode(new AssignOp(lhs, exports.operators.ADD, rhs)); - } - code(c) { - if (typeof c == "function") c(); - else if (c !== code_1.nil) this._leafNode(new AnyCode(c)); - return this; - } - object(...keyValues) { - const code = ["{"]; - for (const [key, value] of keyValues) { - if (code.length > 1) code.push(","); - code.push(key); - if (key !== value || this.opts.es5) { - code.push(":"); - (0, code_1.addCodeArg)(code, value); - } - } - code.push("}"); - return new code_1._Code(code); - } - if(condition, thenBody, elseBody) { - this._blockNode(new If(condition)); - if (thenBody && elseBody) this.code(thenBody).else().code(elseBody).endIf(); - else if (thenBody) this.code(thenBody).endIf(); - else if (elseBody) throw new Error("CodeGen: \"else\" body without \"then\" body"); - return this; - } - elseIf(condition) { - return this._elseNode(new If(condition)); - } - else() { - return this._elseNode(new Else()); - } - endIf() { - return this._endBlockNode(If, Else); - } - _for(node, forBody) { - this._blockNode(node); - if (forBody) this.code(forBody).endFor(); - return this; - } - for(iteration, forBody) { - return this._for(new ForLoop(iteration), forBody); - } - forRange(nameOrPrefix, from, to, forBody, varKind = this.opts.es5 ? scope_1.varKinds.var : scope_1.varKinds.let) { - const name = this._scope.toName(nameOrPrefix); - return this._for(new ForRange(varKind, name, from, to), () => forBody(name)); - } - forOf(nameOrPrefix, iterable, forBody, varKind = scope_1.varKinds.const) { - const name = this._scope.toName(nameOrPrefix); - if (this.opts.es5) { - const arr = iterable instanceof code_1.Name ? iterable : this.var("_arr", iterable); - return this.forRange("_i", 0, (0, code_1._)`${arr}.length`, (i) => { - this.var(name, (0, code_1._)`${arr}[${i}]`); - forBody(name); - }); - } - return this._for(new ForIter("of", varKind, name, iterable), () => forBody(name)); - } - forIn(nameOrPrefix, obj, forBody, varKind = this.opts.es5 ? scope_1.varKinds.var : scope_1.varKinds.const) { - if (this.opts.ownProperties) return this.forOf(nameOrPrefix, (0, code_1._)`Object.keys(${obj})`, forBody); - const name = this._scope.toName(nameOrPrefix); - return this._for(new ForIter("in", varKind, name, obj), () => forBody(name)); - } - endFor() { - return this._endBlockNode(For); - } - label(label) { - return this._leafNode(new Label(label)); - } - break(label) { - return this._leafNode(new Break(label)); - } - return(value) { - const node = new Return(); - this._blockNode(node); - this.code(value); - if (node.nodes.length !== 1) throw new Error("CodeGen: \"return\" should have one node"); - return this._endBlockNode(Return); - } - try(tryBody, catchCode, finallyCode) { - if (!catchCode && !finallyCode) throw new Error("CodeGen: \"try\" without \"catch\" and \"finally\""); - const node = new Try(); - this._blockNode(node); - this.code(tryBody); - if (catchCode) { - const error = this.name("e"); - this._currNode = node.catch = new Catch(error); - catchCode(error); - } - if (finallyCode) { - this._currNode = node.finally = new Finally(); - this.code(finallyCode); - } - return this._endBlockNode(Catch, Finally); - } - throw(error) { - return this._leafNode(new Throw(error)); - } - block(body, nodeCount) { - this._blockStarts.push(this._nodes.length); - if (body) this.code(body).endBlock(nodeCount); - return this; - } - endBlock(nodeCount) { - const len = this._blockStarts.pop(); - if (len === void 0) throw new Error("CodeGen: not in self-balancing block"); - const toClose = this._nodes.length - len; - if (toClose < 0 || nodeCount !== void 0 && toClose !== nodeCount) throw new Error(`CodeGen: wrong number of nodes: ${toClose} vs ${nodeCount} expected`); - this._nodes.length = len; - return this; - } - func(name, args = code_1.nil, async, funcBody) { - this._blockNode(new Func(name, args, async)); - if (funcBody) this.code(funcBody).endFunc(); - return this; - } - endFunc() { - return this._endBlockNode(Func); - } - optimize(n = 1) { - while (n-- > 0) { - this._root.optimizeNodes(); - this._root.optimizeNames(this._root.names, this._constants); - } - } - _leafNode(node) { - this._currNode.nodes.push(node); - return this; - } - _blockNode(node) { - this._currNode.nodes.push(node); - this._nodes.push(node); - } - _endBlockNode(N1, N2) { - const n = this._currNode; - if (n instanceof N1 || N2 && n instanceof N2) { - this._nodes.pop(); - return this; - } - throw new Error(`CodeGen: not in block "${N2 ? `${N1.kind}/${N2.kind}` : N1.kind}"`); - } - _elseNode(node) { - const n = this._currNode; - if (!(n instanceof If)) throw new Error("CodeGen: \"else\" without \"if\""); - this._currNode = n.else = node; - return this; - } - get _root() { - return this._nodes[0]; - } - get _currNode() { - const ns = this._nodes; - return ns[ns.length - 1]; - } - set _currNode(node) { - const ns = this._nodes; - ns[ns.length - 1] = node; - } - }; - exports.CodeGen = CodeGen; - function addNames(names, from) { - for (const n in from) names[n] = (names[n] || 0) + (from[n] || 0); - return names; - } - function addExprNames(names, from) { - return from instanceof code_1._CodeOrName ? addNames(names, from.names) : names; - } - function optimizeExpr(expr, names, constants) { - if (expr instanceof code_1.Name) return replaceName(expr); - if (!canOptimize(expr)) return expr; - return new code_1._Code(expr._items.reduce((items, c) => { - if (c instanceof code_1.Name) c = replaceName(c); - if (c instanceof code_1._Code) items.push(...c._items); - else items.push(c); - return items; - }, [])); - function replaceName(n) { - const c = constants[n.str]; - if (c === void 0 || names[n.str] !== 1) return n; - delete names[n.str]; - return c; - } - function canOptimize(e) { - return e instanceof code_1._Code && e._items.some((c) => c instanceof code_1.Name && names[c.str] === 1 && constants[c.str] !== void 0); - } - } - function subtractNames(names, from) { - for (const n in from) names[n] = (names[n] || 0) - (from[n] || 0); - } - function not(x) { - return typeof x == "boolean" || typeof x == "number" || x === null ? !x : (0, code_1._)`!${par(x)}`; - } - exports.not = not; - const andCode = mappend(exports.operators.AND); - function and(...args) { - return args.reduce(andCode); - } - exports.and = and; - const orCode = mappend(exports.operators.OR); - function or(...args) { - return args.reduce(orCode); - } - exports.or = or; - function mappend(op) { - return (x, y) => x === code_1.nil ? y : y === code_1.nil ? x : (0, code_1._)`${par(x)} ${op} ${par(y)}`; - } - function par(x) { - return x instanceof code_1.Name ? x : (0, code_1._)`(${x})`; - } -})); - -//#endregion -//#region ../../node_modules/.pnpm/ajv@8.18.0/node_modules/ajv/dist/compile/util.js -var require_util = /* @__PURE__ */ __commonJSMin(((exports) => { - Object.defineProperty(exports, "__esModule", { value: true }); - exports.checkStrictMode = exports.getErrorPath = exports.Type = exports.useFunc = exports.setEvaluated = exports.evaluatedPropsToName = exports.mergeEvaluated = exports.eachItem = exports.unescapeJsonPointer = exports.escapeJsonPointer = exports.escapeFragment = exports.unescapeFragment = exports.schemaRefOrVal = exports.schemaHasRulesButRef = exports.schemaHasRules = exports.checkUnknownRules = exports.alwaysValidSchema = exports.toHash = void 0; - const codegen_1 = require_codegen(); - const code_1 = require_code$1(); - function toHash(arr) { - const hash = {}; - for (const item of arr) hash[item] = true; - return hash; - } - exports.toHash = toHash; - function alwaysValidSchema(it, schema) { - if (typeof schema == "boolean") return schema; - if (Object.keys(schema).length === 0) return true; - checkUnknownRules(it, schema); - return !schemaHasRules(schema, it.self.RULES.all); - } - exports.alwaysValidSchema = alwaysValidSchema; - function checkUnknownRules(it, schema = it.schema) { - const { opts, self } = it; - if (!opts.strictSchema) return; - if (typeof schema === "boolean") return; - const rules = self.RULES.keywords; - for (const key in schema) if (!rules[key]) checkStrictMode(it, `unknown keyword: "${key}"`); - } - exports.checkUnknownRules = checkUnknownRules; - function schemaHasRules(schema, rules) { - if (typeof schema == "boolean") return !schema; - for (const key in schema) if (rules[key]) return true; - return false; - } - exports.schemaHasRules = schemaHasRules; - function schemaHasRulesButRef(schema, RULES) { - if (typeof schema == "boolean") return !schema; - for (const key in schema) if (key !== "$ref" && RULES.all[key]) return true; - return false; - } - exports.schemaHasRulesButRef = schemaHasRulesButRef; - function schemaRefOrVal({ topSchemaRef, schemaPath }, schema, keyword, $data) { - if (!$data) { - if (typeof schema == "number" || typeof schema == "boolean") return schema; - if (typeof schema == "string") return (0, codegen_1._)`${schema}`; - } - return (0, codegen_1._)`${topSchemaRef}${schemaPath}${(0, codegen_1.getProperty)(keyword)}`; - } - exports.schemaRefOrVal = schemaRefOrVal; - function unescapeFragment(str) { - return unescapeJsonPointer(decodeURIComponent(str)); - } - exports.unescapeFragment = unescapeFragment; - function escapeFragment(str) { - return encodeURIComponent(escapeJsonPointer(str)); - } - exports.escapeFragment = escapeFragment; - function escapeJsonPointer(str) { - if (typeof str == "number") return `${str}`; - return str.replace(/~/g, "~0").replace(/\//g, "~1"); - } - exports.escapeJsonPointer = escapeJsonPointer; - function unescapeJsonPointer(str) { - return str.replace(/~1/g, "/").replace(/~0/g, "~"); - } - exports.unescapeJsonPointer = unescapeJsonPointer; - function eachItem(xs, f) { - if (Array.isArray(xs)) for (const x of xs) f(x); - else f(xs); - } - exports.eachItem = eachItem; - function makeMergeEvaluated({ mergeNames, mergeToName, mergeValues, resultToName }) { - return (gen, from, to, toName) => { - const res = to === void 0 ? from : to instanceof codegen_1.Name ? (from instanceof codegen_1.Name ? mergeNames(gen, from, to) : mergeToName(gen, from, to), to) : from instanceof codegen_1.Name ? (mergeToName(gen, to, from), from) : mergeValues(from, to); - return toName === codegen_1.Name && !(res instanceof codegen_1.Name) ? resultToName(gen, res) : res; - }; - } - exports.mergeEvaluated = { - props: makeMergeEvaluated({ - mergeNames: (gen, from, to) => gen.if((0, codegen_1._)`${to} !== true && ${from} !== undefined`, () => { - gen.if((0, codegen_1._)`${from} === true`, () => gen.assign(to, true), () => gen.assign(to, (0, codegen_1._)`${to} || {}`).code((0, codegen_1._)`Object.assign(${to}, ${from})`)); - }), - mergeToName: (gen, from, to) => gen.if((0, codegen_1._)`${to} !== true`, () => { - if (from === true) gen.assign(to, true); - else { - gen.assign(to, (0, codegen_1._)`${to} || {}`); - setEvaluated(gen, to, from); - } - }), - mergeValues: (from, to) => from === true ? true : { - ...from, - ...to - }, - resultToName: evaluatedPropsToName - }), - items: makeMergeEvaluated({ - mergeNames: (gen, from, to) => gen.if((0, codegen_1._)`${to} !== true && ${from} !== undefined`, () => gen.assign(to, (0, codegen_1._)`${from} === true ? true : ${to} > ${from} ? ${to} : ${from}`)), - mergeToName: (gen, from, to) => gen.if((0, codegen_1._)`${to} !== true`, () => gen.assign(to, from === true ? true : (0, codegen_1._)`${to} > ${from} ? ${to} : ${from}`)), - mergeValues: (from, to) => from === true ? true : Math.max(from, to), - resultToName: (gen, items) => gen.var("items", items) - }) - }; - function evaluatedPropsToName(gen, ps) { - if (ps === true) return gen.var("props", true); - const props = gen.var("props", (0, codegen_1._)`{}`); - if (ps !== void 0) setEvaluated(gen, props, ps); - return props; - } - exports.evaluatedPropsToName = evaluatedPropsToName; - function setEvaluated(gen, props, ps) { - Object.keys(ps).forEach((p) => gen.assign((0, codegen_1._)`${props}${(0, codegen_1.getProperty)(p)}`, true)); - } - exports.setEvaluated = setEvaluated; - const snippets = {}; - function useFunc(gen, f) { - return gen.scopeValue("func", { - ref: f, - code: snippets[f.code] || (snippets[f.code] = new code_1._Code(f.code)) - }); - } - exports.useFunc = useFunc; - var Type; - (function(Type) { - Type[Type["Num"] = 0] = "Num"; - Type[Type["Str"] = 1] = "Str"; - })(Type || (exports.Type = Type = {})); - function getErrorPath(dataProp, dataPropType, jsPropertySyntax) { - if (dataProp instanceof codegen_1.Name) { - const isNumber = dataPropType === Type.Num; - return jsPropertySyntax ? isNumber ? (0, codegen_1._)`"[" + ${dataProp} + "]"` : (0, codegen_1._)`"['" + ${dataProp} + "']"` : isNumber ? (0, codegen_1._)`"/" + ${dataProp}` : (0, codegen_1._)`"/" + ${dataProp}.replace(/~/g, "~0").replace(/\\//g, "~1")`; - } - return jsPropertySyntax ? (0, codegen_1.getProperty)(dataProp).toString() : "/" + escapeJsonPointer(dataProp); - } - exports.getErrorPath = getErrorPath; - function checkStrictMode(it, msg, mode = it.opts.strictSchema) { - if (!mode) return; - msg = `strict mode: ${msg}`; - if (mode === true) throw new Error(msg); - it.self.logger.warn(msg); - } - exports.checkStrictMode = checkStrictMode; -})); - -//#endregion -//#region ../../node_modules/.pnpm/ajv@8.18.0/node_modules/ajv/dist/compile/names.js -var require_names = /* @__PURE__ */ __commonJSMin(((exports) => { - Object.defineProperty(exports, "__esModule", { value: true }); - const codegen_1 = require_codegen(); - const names = { - data: new codegen_1.Name("data"), - valCxt: new codegen_1.Name("valCxt"), - instancePath: new codegen_1.Name("instancePath"), - parentData: new codegen_1.Name("parentData"), - parentDataProperty: new codegen_1.Name("parentDataProperty"), - rootData: new codegen_1.Name("rootData"), - dynamicAnchors: new codegen_1.Name("dynamicAnchors"), - vErrors: new codegen_1.Name("vErrors"), - errors: new codegen_1.Name("errors"), - this: new codegen_1.Name("this"), - self: new codegen_1.Name("self"), - scope: new codegen_1.Name("scope"), - json: new codegen_1.Name("json"), - jsonPos: new codegen_1.Name("jsonPos"), - jsonLen: new codegen_1.Name("jsonLen"), - jsonPart: new codegen_1.Name("jsonPart") - }; - exports.default = names; -})); - -//#endregion -//#region ../../node_modules/.pnpm/ajv@8.18.0/node_modules/ajv/dist/compile/errors.js -var require_errors = /* @__PURE__ */ __commonJSMin(((exports) => { - Object.defineProperty(exports, "__esModule", { value: true }); - exports.extendErrors = exports.resetErrorsCount = exports.reportExtraError = exports.reportError = exports.keyword$DataError = exports.keywordError = void 0; - const codegen_1 = require_codegen(); - const util_1 = require_util(); - const names_1 = require_names(); - exports.keywordError = { message: ({ keyword }) => (0, codegen_1.str)`must pass "${keyword}" keyword validation` }; - exports.keyword$DataError = { message: ({ keyword, schemaType }) => schemaType ? (0, codegen_1.str)`"${keyword}" keyword must be ${schemaType} ($data)` : (0, codegen_1.str)`"${keyword}" keyword is invalid ($data)` }; - function reportError(cxt, error = exports.keywordError, errorPaths, overrideAllErrors) { - const { it } = cxt; - const { gen, compositeRule, allErrors } = it; - const errObj = errorObjectCode(cxt, error, errorPaths); - if (overrideAllErrors !== null && overrideAllErrors !== void 0 ? overrideAllErrors : compositeRule || allErrors) addError(gen, errObj); - else returnErrors(it, (0, codegen_1._)`[${errObj}]`); - } - exports.reportError = reportError; - function reportExtraError(cxt, error = exports.keywordError, errorPaths) { - const { it } = cxt; - const { gen, compositeRule, allErrors } = it; - addError(gen, errorObjectCode(cxt, error, errorPaths)); - if (!(compositeRule || allErrors)) returnErrors(it, names_1.default.vErrors); - } - exports.reportExtraError = reportExtraError; - function resetErrorsCount(gen, errsCount) { - gen.assign(names_1.default.errors, errsCount); - gen.if((0, codegen_1._)`${names_1.default.vErrors} !== null`, () => gen.if(errsCount, () => gen.assign((0, codegen_1._)`${names_1.default.vErrors}.length`, errsCount), () => gen.assign(names_1.default.vErrors, null))); - } - exports.resetErrorsCount = resetErrorsCount; - function extendErrors({ gen, keyword, schemaValue, data, errsCount, it }) { - /* istanbul ignore if */ - if (errsCount === void 0) throw new Error("ajv implementation error"); - const err = gen.name("err"); - gen.forRange("i", errsCount, names_1.default.errors, (i) => { - gen.const(err, (0, codegen_1._)`${names_1.default.vErrors}[${i}]`); - gen.if((0, codegen_1._)`${err}.instancePath === undefined`, () => gen.assign((0, codegen_1._)`${err}.instancePath`, (0, codegen_1.strConcat)(names_1.default.instancePath, it.errorPath))); - gen.assign((0, codegen_1._)`${err}.schemaPath`, (0, codegen_1.str)`${it.errSchemaPath}/${keyword}`); - if (it.opts.verbose) { - gen.assign((0, codegen_1._)`${err}.schema`, schemaValue); - gen.assign((0, codegen_1._)`${err}.data`, data); - } - }); - } - exports.extendErrors = extendErrors; - function addError(gen, errObj) { - const err = gen.const("err", errObj); - gen.if((0, codegen_1._)`${names_1.default.vErrors} === null`, () => gen.assign(names_1.default.vErrors, (0, codegen_1._)`[${err}]`), (0, codegen_1._)`${names_1.default.vErrors}.push(${err})`); - gen.code((0, codegen_1._)`${names_1.default.errors}++`); - } - function returnErrors(it, errs) { - const { gen, validateName, schemaEnv } = it; - if (schemaEnv.$async) gen.throw((0, codegen_1._)`new ${it.ValidationError}(${errs})`); - else { - gen.assign((0, codegen_1._)`${validateName}.errors`, errs); - gen.return(false); - } - } - const E = { - keyword: new codegen_1.Name("keyword"), - schemaPath: new codegen_1.Name("schemaPath"), - params: new codegen_1.Name("params"), - propertyName: new codegen_1.Name("propertyName"), - message: new codegen_1.Name("message"), - schema: new codegen_1.Name("schema"), - parentSchema: new codegen_1.Name("parentSchema") - }; - function errorObjectCode(cxt, error, errorPaths) { - const { createErrors } = cxt.it; - if (createErrors === false) return (0, codegen_1._)`{}`; - return errorObject(cxt, error, errorPaths); - } - function errorObject(cxt, error, errorPaths = {}) { - const { gen, it } = cxt; - const keyValues = [errorInstancePath(it, errorPaths), errorSchemaPath(cxt, errorPaths)]; - extraErrorProps(cxt, error, keyValues); - return gen.object(...keyValues); - } - function errorInstancePath({ errorPath }, { instancePath }) { - const instPath = instancePath ? (0, codegen_1.str)`${errorPath}${(0, util_1.getErrorPath)(instancePath, util_1.Type.Str)}` : errorPath; - return [names_1.default.instancePath, (0, codegen_1.strConcat)(names_1.default.instancePath, instPath)]; - } - function errorSchemaPath({ keyword, it: { errSchemaPath } }, { schemaPath, parentSchema }) { - let schPath = parentSchema ? errSchemaPath : (0, codegen_1.str)`${errSchemaPath}/${keyword}`; - if (schemaPath) schPath = (0, codegen_1.str)`${schPath}${(0, util_1.getErrorPath)(schemaPath, util_1.Type.Str)}`; - return [E.schemaPath, schPath]; - } - function extraErrorProps(cxt, { params, message }, keyValues) { - const { keyword, data, schemaValue, it } = cxt; - const { opts, propertyName, topSchemaRef, schemaPath } = it; - keyValues.push([E.keyword, keyword], [E.params, typeof params == "function" ? params(cxt) : params || (0, codegen_1._)`{}`]); - if (opts.messages) keyValues.push([E.message, typeof message == "function" ? message(cxt) : message]); - if (opts.verbose) keyValues.push([E.schema, schemaValue], [E.parentSchema, (0, codegen_1._)`${topSchemaRef}${schemaPath}`], [names_1.default.data, data]); - if (propertyName) keyValues.push([E.propertyName, propertyName]); - } -})); - -//#endregion -//#region ../../node_modules/.pnpm/ajv@8.18.0/node_modules/ajv/dist/compile/validate/boolSchema.js -var require_boolSchema = /* @__PURE__ */ __commonJSMin(((exports) => { - Object.defineProperty(exports, "__esModule", { value: true }); - exports.boolOrEmptySchema = exports.topBoolOrEmptySchema = void 0; - const errors_1 = require_errors(); - const codegen_1 = require_codegen(); - const names_1 = require_names(); - const boolError = { message: "boolean schema is false" }; - function topBoolOrEmptySchema(it) { - const { gen, schema, validateName } = it; - if (schema === false) falseSchemaError(it, false); - else if (typeof schema == "object" && schema.$async === true) gen.return(names_1.default.data); - else { - gen.assign((0, codegen_1._)`${validateName}.errors`, null); - gen.return(true); - } - } - exports.topBoolOrEmptySchema = topBoolOrEmptySchema; - function boolOrEmptySchema(it, valid) { - const { gen, schema } = it; - if (schema === false) { - gen.var(valid, false); - falseSchemaError(it); - } else gen.var(valid, true); - } - exports.boolOrEmptySchema = boolOrEmptySchema; - function falseSchemaError(it, overrideAllErrors) { - const { gen, data } = it; - const cxt = { - gen, - keyword: "false schema", - data, - schema: false, - schemaCode: false, - schemaValue: false, - params: {}, - it - }; - (0, errors_1.reportError)(cxt, boolError, void 0, overrideAllErrors); - } -})); - -//#endregion -//#region ../../node_modules/.pnpm/ajv@8.18.0/node_modules/ajv/dist/compile/rules.js -var require_rules = /* @__PURE__ */ __commonJSMin(((exports) => { - Object.defineProperty(exports, "__esModule", { value: true }); - exports.getRules = exports.isJSONType = void 0; - const jsonTypes = new Set([ - "string", - "number", - "integer", - "boolean", - "null", - "object", - "array" - ]); - function isJSONType(x) { - return typeof x == "string" && jsonTypes.has(x); - } - exports.isJSONType = isJSONType; - function getRules() { - const groups = { - number: { - type: "number", - rules: [] - }, - string: { - type: "string", - rules: [] - }, - array: { - type: "array", - rules: [] - }, - object: { - type: "object", - rules: [] - } - }; - return { - types: { - ...groups, - integer: true, - boolean: true, - null: true - }, - rules: [ - { rules: [] }, - groups.number, - groups.string, - groups.array, - groups.object - ], - post: { rules: [] }, - all: {}, - keywords: {} - }; - } - exports.getRules = getRules; -})); - -//#endregion -//#region ../../node_modules/.pnpm/ajv@8.18.0/node_modules/ajv/dist/compile/validate/applicability.js -var require_applicability = /* @__PURE__ */ __commonJSMin(((exports) => { - Object.defineProperty(exports, "__esModule", { value: true }); - exports.shouldUseRule = exports.shouldUseGroup = exports.schemaHasRulesForType = void 0; - function schemaHasRulesForType({ schema, self }, type) { - const group = self.RULES.types[type]; - return group && group !== true && shouldUseGroup(schema, group); - } - exports.schemaHasRulesForType = schemaHasRulesForType; - function shouldUseGroup(schema, group) { - return group.rules.some((rule) => shouldUseRule(schema, rule)); - } - exports.shouldUseGroup = shouldUseGroup; - function shouldUseRule(schema, rule) { - var _a; - return schema[rule.keyword] !== void 0 || ((_a = rule.definition.implements) === null || _a === void 0 ? void 0 : _a.some((kwd) => schema[kwd] !== void 0)); - } - exports.shouldUseRule = shouldUseRule; -})); - -//#endregion -//#region ../../node_modules/.pnpm/ajv@8.18.0/node_modules/ajv/dist/compile/validate/dataType.js -var require_dataType = /* @__PURE__ */ __commonJSMin(((exports) => { - Object.defineProperty(exports, "__esModule", { value: true }); - exports.reportTypeError = exports.checkDataTypes = exports.checkDataType = exports.coerceAndCheckDataType = exports.getJSONTypes = exports.getSchemaTypes = exports.DataType = void 0; - const rules_1 = require_rules(); - const applicability_1 = require_applicability(); - const errors_1 = require_errors(); - const codegen_1 = require_codegen(); - const util_1 = require_util(); - var DataType; - (function(DataType) { - DataType[DataType["Correct"] = 0] = "Correct"; - DataType[DataType["Wrong"] = 1] = "Wrong"; - })(DataType || (exports.DataType = DataType = {})); - function getSchemaTypes(schema) { - const types = getJSONTypes(schema.type); - if (types.includes("null")) { - if (schema.nullable === false) throw new Error("type: null contradicts nullable: false"); - } else { - if (!types.length && schema.nullable !== void 0) throw new Error("\"nullable\" cannot be used without \"type\""); - if (schema.nullable === true) types.push("null"); - } - return types; - } - exports.getSchemaTypes = getSchemaTypes; - function getJSONTypes(ts) { - const types = Array.isArray(ts) ? ts : ts ? [ts] : []; - if (types.every(rules_1.isJSONType)) return types; - throw new Error("type must be JSONType or JSONType[]: " + types.join(",")); - } - exports.getJSONTypes = getJSONTypes; - function coerceAndCheckDataType(it, types) { - const { gen, data, opts } = it; - const coerceTo = coerceToTypes(types, opts.coerceTypes); - const checkTypes = types.length > 0 && !(coerceTo.length === 0 && types.length === 1 && (0, applicability_1.schemaHasRulesForType)(it, types[0])); - if (checkTypes) { - const wrongType = checkDataTypes(types, data, opts.strictNumbers, DataType.Wrong); - gen.if(wrongType, () => { - if (coerceTo.length) coerceData(it, types, coerceTo); - else reportTypeError(it); - }); - } - return checkTypes; - } - exports.coerceAndCheckDataType = coerceAndCheckDataType; - const COERCIBLE = new Set([ - "string", - "number", - "integer", - "boolean", - "null" - ]); - function coerceToTypes(types, coerceTypes) { - return coerceTypes ? types.filter((t) => COERCIBLE.has(t) || coerceTypes === "array" && t === "array") : []; - } - function coerceData(it, types, coerceTo) { - const { gen, data, opts } = it; - const dataType = gen.let("dataType", (0, codegen_1._)`typeof ${data}`); - const coerced = gen.let("coerced", (0, codegen_1._)`undefined`); - if (opts.coerceTypes === "array") gen.if((0, codegen_1._)`${dataType} == 'object' && Array.isArray(${data}) && ${data}.length == 1`, () => gen.assign(data, (0, codegen_1._)`${data}[0]`).assign(dataType, (0, codegen_1._)`typeof ${data}`).if(checkDataTypes(types, data, opts.strictNumbers), () => gen.assign(coerced, data))); - gen.if((0, codegen_1._)`${coerced} !== undefined`); - for (const t of coerceTo) if (COERCIBLE.has(t) || t === "array" && opts.coerceTypes === "array") coerceSpecificType(t); - gen.else(); - reportTypeError(it); - gen.endIf(); - gen.if((0, codegen_1._)`${coerced} !== undefined`, () => { - gen.assign(data, coerced); - assignParentData(it, coerced); - }); - function coerceSpecificType(t) { - switch (t) { - case "string": - gen.elseIf((0, codegen_1._)`${dataType} == "number" || ${dataType} == "boolean"`).assign(coerced, (0, codegen_1._)`"" + ${data}`).elseIf((0, codegen_1._)`${data} === null`).assign(coerced, (0, codegen_1._)`""`); - return; - case "number": - gen.elseIf((0, codegen_1._)`${dataType} == "boolean" || ${data} === null - || (${dataType} == "string" && ${data} && ${data} == +${data})`).assign(coerced, (0, codegen_1._)`+${data}`); - return; - case "integer": - gen.elseIf((0, codegen_1._)`${dataType} === "boolean" || ${data} === null - || (${dataType} === "string" && ${data} && ${data} == +${data} && !(${data} % 1))`).assign(coerced, (0, codegen_1._)`+${data}`); - return; - case "boolean": - gen.elseIf((0, codegen_1._)`${data} === "false" || ${data} === 0 || ${data} === null`).assign(coerced, false).elseIf((0, codegen_1._)`${data} === "true" || ${data} === 1`).assign(coerced, true); - return; - case "null": - gen.elseIf((0, codegen_1._)`${data} === "" || ${data} === 0 || ${data} === false`); - gen.assign(coerced, null); - return; - case "array": gen.elseIf((0, codegen_1._)`${dataType} === "string" || ${dataType} === "number" - || ${dataType} === "boolean" || ${data} === null`).assign(coerced, (0, codegen_1._)`[${data}]`); - } - } - } - function assignParentData({ gen, parentData, parentDataProperty }, expr) { - gen.if((0, codegen_1._)`${parentData} !== undefined`, () => gen.assign((0, codegen_1._)`${parentData}[${parentDataProperty}]`, expr)); - } - function checkDataType(dataType, data, strictNums, correct = DataType.Correct) { - const EQ = correct === DataType.Correct ? codegen_1.operators.EQ : codegen_1.operators.NEQ; - let cond; - switch (dataType) { - case "null": return (0, codegen_1._)`${data} ${EQ} null`; - case "array": - cond = (0, codegen_1._)`Array.isArray(${data})`; - break; - case "object": - cond = (0, codegen_1._)`${data} && typeof ${data} == "object" && !Array.isArray(${data})`; - break; - case "integer": - cond = numCond((0, codegen_1._)`!(${data} % 1) && !isNaN(${data})`); - break; - case "number": - cond = numCond(); - break; - default: return (0, codegen_1._)`typeof ${data} ${EQ} ${dataType}`; - } - return correct === DataType.Correct ? cond : (0, codegen_1.not)(cond); - function numCond(_cond = codegen_1.nil) { - return (0, codegen_1.and)((0, codegen_1._)`typeof ${data} == "number"`, _cond, strictNums ? (0, codegen_1._)`isFinite(${data})` : codegen_1.nil); - } - } - exports.checkDataType = checkDataType; - function checkDataTypes(dataTypes, data, strictNums, correct) { - if (dataTypes.length === 1) return checkDataType(dataTypes[0], data, strictNums, correct); - let cond; - const types = (0, util_1.toHash)(dataTypes); - if (types.array && types.object) { - const notObj = (0, codegen_1._)`typeof ${data} != "object"`; - cond = types.null ? notObj : (0, codegen_1._)`!${data} || ${notObj}`; - delete types.null; - delete types.array; - delete types.object; - } else cond = codegen_1.nil; - if (types.number) delete types.integer; - for (const t in types) cond = (0, codegen_1.and)(cond, checkDataType(t, data, strictNums, correct)); - return cond; - } - exports.checkDataTypes = checkDataTypes; - const typeError = { - message: ({ schema }) => `must be ${schema}`, - params: ({ schema, schemaValue }) => typeof schema == "string" ? (0, codegen_1._)`{type: ${schema}}` : (0, codegen_1._)`{type: ${schemaValue}}` - }; - function reportTypeError(it) { - const cxt = getTypeErrorContext(it); - (0, errors_1.reportError)(cxt, typeError); - } - exports.reportTypeError = reportTypeError; - function getTypeErrorContext(it) { - const { gen, data, schema } = it; - const schemaCode = (0, util_1.schemaRefOrVal)(it, schema, "type"); - return { - gen, - keyword: "type", - data, - schema: schema.type, - schemaCode, - schemaValue: schemaCode, - parentSchema: schema, - params: {}, - it - }; - } -})); - -//#endregion -//#region ../../node_modules/.pnpm/ajv@8.18.0/node_modules/ajv/dist/compile/validate/defaults.js -var require_defaults = /* @__PURE__ */ __commonJSMin(((exports) => { - Object.defineProperty(exports, "__esModule", { value: true }); - exports.assignDefaults = void 0; - const codegen_1 = require_codegen(); - const util_1 = require_util(); - function assignDefaults(it, ty) { - const { properties, items } = it.schema; - if (ty === "object" && properties) for (const key in properties) assignDefault(it, key, properties[key].default); - else if (ty === "array" && Array.isArray(items)) items.forEach((sch, i) => assignDefault(it, i, sch.default)); - } - exports.assignDefaults = assignDefaults; - function assignDefault(it, prop, defaultValue) { - const { gen, compositeRule, data, opts } = it; - if (defaultValue === void 0) return; - const childData = (0, codegen_1._)`${data}${(0, codegen_1.getProperty)(prop)}`; - if (compositeRule) { - (0, util_1.checkStrictMode)(it, `default is ignored for: ${childData}`); - return; - } - let condition = (0, codegen_1._)`${childData} === undefined`; - if (opts.useDefaults === "empty") condition = (0, codegen_1._)`${condition} || ${childData} === null || ${childData} === ""`; - gen.if(condition, (0, codegen_1._)`${childData} = ${(0, codegen_1.stringify)(defaultValue)}`); - } -})); - -//#endregion -//#region ../../node_modules/.pnpm/ajv@8.18.0/node_modules/ajv/dist/vocabularies/code.js -var require_code = /* @__PURE__ */ __commonJSMin(((exports) => { - Object.defineProperty(exports, "__esModule", { value: true }); - exports.validateUnion = exports.validateArray = exports.usePattern = exports.callValidateCode = exports.schemaProperties = exports.allSchemaProperties = exports.noPropertyInData = exports.propertyInData = exports.isOwnProperty = exports.hasPropFunc = exports.reportMissingProp = exports.checkMissingProp = exports.checkReportMissingProp = void 0; - const codegen_1 = require_codegen(); - const util_1 = require_util(); - const names_1 = require_names(); - const util_2 = require_util(); - function checkReportMissingProp(cxt, prop) { - const { gen, data, it } = cxt; - gen.if(noPropertyInData(gen, data, prop, it.opts.ownProperties), () => { - cxt.setParams({ missingProperty: (0, codegen_1._)`${prop}` }, true); - cxt.error(); - }); - } - exports.checkReportMissingProp = checkReportMissingProp; - function checkMissingProp({ gen, data, it: { opts } }, properties, missing) { - return (0, codegen_1.or)(...properties.map((prop) => (0, codegen_1.and)(noPropertyInData(gen, data, prop, opts.ownProperties), (0, codegen_1._)`${missing} = ${prop}`))); - } - exports.checkMissingProp = checkMissingProp; - function reportMissingProp(cxt, missing) { - cxt.setParams({ missingProperty: missing }, true); - cxt.error(); - } - exports.reportMissingProp = reportMissingProp; - function hasPropFunc(gen) { - return gen.scopeValue("func", { - ref: Object.prototype.hasOwnProperty, - code: (0, codegen_1._)`Object.prototype.hasOwnProperty` - }); - } - exports.hasPropFunc = hasPropFunc; - function isOwnProperty(gen, data, property) { - return (0, codegen_1._)`${hasPropFunc(gen)}.call(${data}, ${property})`; - } - exports.isOwnProperty = isOwnProperty; - function propertyInData(gen, data, property, ownProperties) { - const cond = (0, codegen_1._)`${data}${(0, codegen_1.getProperty)(property)} !== undefined`; - return ownProperties ? (0, codegen_1._)`${cond} && ${isOwnProperty(gen, data, property)}` : cond; - } - exports.propertyInData = propertyInData; - function noPropertyInData(gen, data, property, ownProperties) { - const cond = (0, codegen_1._)`${data}${(0, codegen_1.getProperty)(property)} === undefined`; - return ownProperties ? (0, codegen_1.or)(cond, (0, codegen_1.not)(isOwnProperty(gen, data, property))) : cond; - } - exports.noPropertyInData = noPropertyInData; - function allSchemaProperties(schemaMap) { - return schemaMap ? Object.keys(schemaMap).filter((p) => p !== "__proto__") : []; - } - exports.allSchemaProperties = allSchemaProperties; - function schemaProperties(it, schemaMap) { - return allSchemaProperties(schemaMap).filter((p) => !(0, util_1.alwaysValidSchema)(it, schemaMap[p])); - } - exports.schemaProperties = schemaProperties; - function callValidateCode({ schemaCode, data, it: { gen, topSchemaRef, schemaPath, errorPath }, it }, func, context, passSchema) { - const dataAndSchema = passSchema ? (0, codegen_1._)`${schemaCode}, ${data}, ${topSchemaRef}${schemaPath}` : data; - const valCxt = [ - [names_1.default.instancePath, (0, codegen_1.strConcat)(names_1.default.instancePath, errorPath)], - [names_1.default.parentData, it.parentData], - [names_1.default.parentDataProperty, it.parentDataProperty], - [names_1.default.rootData, names_1.default.rootData] - ]; - if (it.opts.dynamicRef) valCxt.push([names_1.default.dynamicAnchors, names_1.default.dynamicAnchors]); - const args = (0, codegen_1._)`${dataAndSchema}, ${gen.object(...valCxt)}`; - return context !== codegen_1.nil ? (0, codegen_1._)`${func}.call(${context}, ${args})` : (0, codegen_1._)`${func}(${args})`; - } - exports.callValidateCode = callValidateCode; - const newRegExp = (0, codegen_1._)`new RegExp`; - function usePattern({ gen, it: { opts } }, pattern) { - const u = opts.unicodeRegExp ? "u" : ""; - const { regExp } = opts.code; - const rx = regExp(pattern, u); - return gen.scopeValue("pattern", { - key: rx.toString(), - ref: rx, - code: (0, codegen_1._)`${regExp.code === "new RegExp" ? newRegExp : (0, util_2.useFunc)(gen, regExp)}(${pattern}, ${u})` - }); - } - exports.usePattern = usePattern; - function validateArray(cxt) { - const { gen, data, keyword, it } = cxt; - const valid = gen.name("valid"); - if (it.allErrors) { - const validArr = gen.let("valid", true); - validateItems(() => gen.assign(validArr, false)); - return validArr; - } - gen.var(valid, true); - validateItems(() => gen.break()); - return valid; - function validateItems(notValid) { - const len = gen.const("len", (0, codegen_1._)`${data}.length`); - gen.forRange("i", 0, len, (i) => { - cxt.subschema({ - keyword, - dataProp: i, - dataPropType: util_1.Type.Num - }, valid); - gen.if((0, codegen_1.not)(valid), notValid); - }); - } - } - exports.validateArray = validateArray; - function validateUnion(cxt) { - const { gen, schema, keyword, it } = cxt; - /* istanbul ignore if */ - if (!Array.isArray(schema)) throw new Error("ajv implementation error"); - if (schema.some((sch) => (0, util_1.alwaysValidSchema)(it, sch)) && !it.opts.unevaluated) return; - const valid = gen.let("valid", false); - const schValid = gen.name("_valid"); - gen.block(() => schema.forEach((_sch, i) => { - const schCxt = cxt.subschema({ - keyword, - schemaProp: i, - compositeRule: true - }, schValid); - gen.assign(valid, (0, codegen_1._)`${valid} || ${schValid}`); - if (!cxt.mergeValidEvaluated(schCxt, schValid)) gen.if((0, codegen_1.not)(valid)); - })); - cxt.result(valid, () => cxt.reset(), () => cxt.error(true)); - } - exports.validateUnion = validateUnion; -})); - -//#endregion -//#region ../../node_modules/.pnpm/ajv@8.18.0/node_modules/ajv/dist/compile/validate/keyword.js -var require_keyword = /* @__PURE__ */ __commonJSMin(((exports) => { - Object.defineProperty(exports, "__esModule", { value: true }); - exports.validateKeywordUsage = exports.validSchemaType = exports.funcKeywordCode = exports.macroKeywordCode = void 0; - const codegen_1 = require_codegen(); - const names_1 = require_names(); - const code_1 = require_code(); - const errors_1 = require_errors(); - function macroKeywordCode(cxt, def) { - const { gen, keyword, schema, parentSchema, it } = cxt; - const macroSchema = def.macro.call(it.self, schema, parentSchema, it); - const schemaRef = useKeyword(gen, keyword, macroSchema); - if (it.opts.validateSchema !== false) it.self.validateSchema(macroSchema, true); - const valid = gen.name("valid"); - cxt.subschema({ - schema: macroSchema, - schemaPath: codegen_1.nil, - errSchemaPath: `${it.errSchemaPath}/${keyword}`, - topSchemaRef: schemaRef, - compositeRule: true - }, valid); - cxt.pass(valid, () => cxt.error(true)); - } - exports.macroKeywordCode = macroKeywordCode; - function funcKeywordCode(cxt, def) { - var _a; - const { gen, keyword, schema, parentSchema, $data, it } = cxt; - checkAsyncKeyword(it, def); - const validateRef = useKeyword(gen, keyword, !$data && def.compile ? def.compile.call(it.self, schema, parentSchema, it) : def.validate); - const valid = gen.let("valid"); - cxt.block$data(valid, validateKeyword); - cxt.ok((_a = def.valid) !== null && _a !== void 0 ? _a : valid); - function validateKeyword() { - if (def.errors === false) { - assignValid(); - if (def.modifying) modifyData(cxt); - reportErrs(() => cxt.error()); - } else { - const ruleErrs = def.async ? validateAsync() : validateSync(); - if (def.modifying) modifyData(cxt); - reportErrs(() => addErrs(cxt, ruleErrs)); - } - } - function validateAsync() { - const ruleErrs = gen.let("ruleErrs", null); - gen.try(() => assignValid((0, codegen_1._)`await `), (e) => gen.assign(valid, false).if((0, codegen_1._)`${e} instanceof ${it.ValidationError}`, () => gen.assign(ruleErrs, (0, codegen_1._)`${e}.errors`), () => gen.throw(e))); - return ruleErrs; - } - function validateSync() { - const validateErrs = (0, codegen_1._)`${validateRef}.errors`; - gen.assign(validateErrs, null); - assignValid(codegen_1.nil); - return validateErrs; - } - function assignValid(_await = def.async ? (0, codegen_1._)`await ` : codegen_1.nil) { - const passCxt = it.opts.passContext ? names_1.default.this : names_1.default.self; - const passSchema = !("compile" in def && !$data || def.schema === false); - gen.assign(valid, (0, codegen_1._)`${_await}${(0, code_1.callValidateCode)(cxt, validateRef, passCxt, passSchema)}`, def.modifying); - } - function reportErrs(errors) { - var _a$1; - gen.if((0, codegen_1.not)((_a$1 = def.valid) !== null && _a$1 !== void 0 ? _a$1 : valid), errors); - } - } - exports.funcKeywordCode = funcKeywordCode; - function modifyData(cxt) { - const { gen, data, it } = cxt; - gen.if(it.parentData, () => gen.assign(data, (0, codegen_1._)`${it.parentData}[${it.parentDataProperty}]`)); - } - function addErrs(cxt, errs) { - const { gen } = cxt; - gen.if((0, codegen_1._)`Array.isArray(${errs})`, () => { - gen.assign(names_1.default.vErrors, (0, codegen_1._)`${names_1.default.vErrors} === null ? ${errs} : ${names_1.default.vErrors}.concat(${errs})`).assign(names_1.default.errors, (0, codegen_1._)`${names_1.default.vErrors}.length`); - (0, errors_1.extendErrors)(cxt); - }, () => cxt.error()); - } - function checkAsyncKeyword({ schemaEnv }, def) { - if (def.async && !schemaEnv.$async) throw new Error("async keyword in sync schema"); - } - function useKeyword(gen, keyword, result) { - if (result === void 0) throw new Error(`keyword "${keyword}" failed to compile`); - return gen.scopeValue("keyword", typeof result == "function" ? { ref: result } : { - ref: result, - code: (0, codegen_1.stringify)(result) - }); - } - function validSchemaType(schema, schemaType, allowUndefined = false) { - return !schemaType.length || schemaType.some((st) => st === "array" ? Array.isArray(schema) : st === "object" ? schema && typeof schema == "object" && !Array.isArray(schema) : typeof schema == st || allowUndefined && typeof schema == "undefined"); - } - exports.validSchemaType = validSchemaType; - function validateKeywordUsage({ schema, opts, self, errSchemaPath }, def, keyword) { - /* istanbul ignore if */ - if (Array.isArray(def.keyword) ? !def.keyword.includes(keyword) : def.keyword !== keyword) throw new Error("ajv implementation error"); - const deps = def.dependencies; - if (deps === null || deps === void 0 ? void 0 : deps.some((kwd) => !Object.prototype.hasOwnProperty.call(schema, kwd))) throw new Error(`parent schema must have dependencies of ${keyword}: ${deps.join(",")}`); - if (def.validateSchema) { - if (!def.validateSchema(schema[keyword])) { - const msg = `keyword "${keyword}" value is invalid at path "${errSchemaPath}": ` + self.errorsText(def.validateSchema.errors); - if (opts.validateSchema === "log") self.logger.error(msg); - else throw new Error(msg); - } - } - } - exports.validateKeywordUsage = validateKeywordUsage; -})); - -//#endregion -//#region ../../node_modules/.pnpm/ajv@8.18.0/node_modules/ajv/dist/compile/validate/subschema.js -var require_subschema = /* @__PURE__ */ __commonJSMin(((exports) => { - Object.defineProperty(exports, "__esModule", { value: true }); - exports.extendSubschemaMode = exports.extendSubschemaData = exports.getSubschema = void 0; - const codegen_1 = require_codegen(); - const util_1 = require_util(); - function getSubschema(it, { keyword, schemaProp, schema, schemaPath, errSchemaPath, topSchemaRef }) { - if (keyword !== void 0 && schema !== void 0) throw new Error("both \"keyword\" and \"schema\" passed, only one allowed"); - if (keyword !== void 0) { - const sch = it.schema[keyword]; - return schemaProp === void 0 ? { - schema: sch, - schemaPath: (0, codegen_1._)`${it.schemaPath}${(0, codegen_1.getProperty)(keyword)}`, - errSchemaPath: `${it.errSchemaPath}/${keyword}` - } : { - schema: sch[schemaProp], - schemaPath: (0, codegen_1._)`${it.schemaPath}${(0, codegen_1.getProperty)(keyword)}${(0, codegen_1.getProperty)(schemaProp)}`, - errSchemaPath: `${it.errSchemaPath}/${keyword}/${(0, util_1.escapeFragment)(schemaProp)}` - }; - } - if (schema !== void 0) { - if (schemaPath === void 0 || errSchemaPath === void 0 || topSchemaRef === void 0) throw new Error("\"schemaPath\", \"errSchemaPath\" and \"topSchemaRef\" are required with \"schema\""); - return { - schema, - schemaPath, - topSchemaRef, - errSchemaPath - }; - } - throw new Error("either \"keyword\" or \"schema\" must be passed"); - } - exports.getSubschema = getSubschema; - function extendSubschemaData(subschema, it, { dataProp, dataPropType: dpType, data, dataTypes, propertyName }) { - if (data !== void 0 && dataProp !== void 0) throw new Error("both \"data\" and \"dataProp\" passed, only one allowed"); - const { gen } = it; - if (dataProp !== void 0) { - const { errorPath, dataPathArr, opts } = it; - dataContextProps(gen.let("data", (0, codegen_1._)`${it.data}${(0, codegen_1.getProperty)(dataProp)}`, true)); - subschema.errorPath = (0, codegen_1.str)`${errorPath}${(0, util_1.getErrorPath)(dataProp, dpType, opts.jsPropertySyntax)}`; - subschema.parentDataProperty = (0, codegen_1._)`${dataProp}`; - subschema.dataPathArr = [...dataPathArr, subschema.parentDataProperty]; - } - if (data !== void 0) { - dataContextProps(data instanceof codegen_1.Name ? data : gen.let("data", data, true)); - if (propertyName !== void 0) subschema.propertyName = propertyName; - } - if (dataTypes) subschema.dataTypes = dataTypes; - function dataContextProps(_nextData) { - subschema.data = _nextData; - subschema.dataLevel = it.dataLevel + 1; - subschema.dataTypes = []; - it.definedProperties = /* @__PURE__ */ new Set(); - subschema.parentData = it.data; - subschema.dataNames = [...it.dataNames, _nextData]; - } - } - exports.extendSubschemaData = extendSubschemaData; - function extendSubschemaMode(subschema, { jtdDiscriminator, jtdMetadata, compositeRule, createErrors, allErrors }) { - if (compositeRule !== void 0) subschema.compositeRule = compositeRule; - if (createErrors !== void 0) subschema.createErrors = createErrors; - if (allErrors !== void 0) subschema.allErrors = allErrors; - subschema.jtdDiscriminator = jtdDiscriminator; - subschema.jtdMetadata = jtdMetadata; - } - exports.extendSubschemaMode = extendSubschemaMode; -})); - -//#endregion -//#region ../../node_modules/.pnpm/fast-deep-equal@3.1.3/node_modules/fast-deep-equal/index.js -var require_fast_deep_equal = /* @__PURE__ */ __commonJSMin(((exports, module) => { - module.exports = function equal(a, b) { - if (a === b) return true; - if (a && b && typeof a == "object" && typeof b == "object") { - if (a.constructor !== b.constructor) return false; - var length, i, keys; - if (Array.isArray(a)) { - length = a.length; - if (length != b.length) return false; - for (i = length; i-- !== 0;) if (!equal(a[i], b[i])) return false; - return true; - } - if (a.constructor === RegExp) return a.source === b.source && a.flags === b.flags; - if (a.valueOf !== Object.prototype.valueOf) return a.valueOf() === b.valueOf(); - if (a.toString !== Object.prototype.toString) return a.toString() === b.toString(); - keys = Object.keys(a); - length = keys.length; - if (length !== Object.keys(b).length) return false; - for (i = length; i-- !== 0;) if (!Object.prototype.hasOwnProperty.call(b, keys[i])) return false; - for (i = length; i-- !== 0;) { - var key = keys[i]; - if (!equal(a[key], b[key])) return false; - } - return true; - } - return a !== a && b !== b; - }; -})); - -//#endregion -//#region ../../node_modules/.pnpm/json-schema-traverse@1.0.0/node_modules/json-schema-traverse/index.js -var require_json_schema_traverse = /* @__PURE__ */ __commonJSMin(((exports, module) => { - var traverse = module.exports = function(schema, opts, cb) { - if (typeof opts == "function") { - cb = opts; - opts = {}; - } - cb = opts.cb || cb; - var pre = typeof cb == "function" ? cb : cb.pre || function() {}; - var post = cb.post || function() {}; - _traverse(opts, pre, post, schema, "", schema); - }; - traverse.keywords = { - additionalItems: true, - items: true, - contains: true, - additionalProperties: true, - propertyNames: true, - not: true, - if: true, - then: true, - else: true - }; - traverse.arrayKeywords = { - items: true, - allOf: true, - anyOf: true, - oneOf: true - }; - traverse.propsKeywords = { - $defs: true, - definitions: true, - properties: true, - patternProperties: true, - dependencies: true - }; - traverse.skipKeywords = { - default: true, - enum: true, - const: true, - required: true, - maximum: true, - minimum: true, - exclusiveMaximum: true, - exclusiveMinimum: true, - multipleOf: true, - maxLength: true, - minLength: true, - pattern: true, - format: true, - maxItems: true, - minItems: true, - uniqueItems: true, - maxProperties: true, - minProperties: true - }; - function _traverse(opts, pre, post, schema, jsonPtr, rootSchema, parentJsonPtr, parentKeyword, parentSchema, keyIndex) { - if (schema && typeof schema == "object" && !Array.isArray(schema)) { - pre(schema, jsonPtr, rootSchema, parentJsonPtr, parentKeyword, parentSchema, keyIndex); - for (var key in schema) { - var sch = schema[key]; - if (Array.isArray(sch)) { - if (key in traverse.arrayKeywords) for (var i = 0; i < sch.length; i++) _traverse(opts, pre, post, sch[i], jsonPtr + "/" + key + "/" + i, rootSchema, jsonPtr, key, schema, i); - } else if (key in traverse.propsKeywords) { - if (sch && typeof sch == "object") for (var prop in sch) _traverse(opts, pre, post, sch[prop], jsonPtr + "/" + key + "/" + escapeJsonPtr(prop), rootSchema, jsonPtr, key, schema, prop); - } else if (key in traverse.keywords || opts.allKeys && !(key in traverse.skipKeywords)) _traverse(opts, pre, post, sch, jsonPtr + "/" + key, rootSchema, jsonPtr, key, schema); - } - post(schema, jsonPtr, rootSchema, parentJsonPtr, parentKeyword, parentSchema, keyIndex); - } - } - function escapeJsonPtr(str) { - return str.replace(/~/g, "~0").replace(/\//g, "~1"); - } -})); - -//#endregion -//#region ../../node_modules/.pnpm/ajv@8.18.0/node_modules/ajv/dist/compile/resolve.js -var require_resolve = /* @__PURE__ */ __commonJSMin(((exports) => { - Object.defineProperty(exports, "__esModule", { value: true }); - exports.getSchemaRefs = exports.resolveUrl = exports.normalizeId = exports._getFullPath = exports.getFullPath = exports.inlineRef = void 0; - const util_1 = require_util(); - const equal = require_fast_deep_equal(); - const traverse = require_json_schema_traverse(); - const SIMPLE_INLINED = new Set([ - "type", - "format", - "pattern", - "maxLength", - "minLength", - "maxProperties", - "minProperties", - "maxItems", - "minItems", - "maximum", - "minimum", - "uniqueItems", - "multipleOf", - "required", - "enum", - "const" - ]); - function inlineRef(schema, limit = true) { - if (typeof schema == "boolean") return true; - if (limit === true) return !hasRef(schema); - if (!limit) return false; - return countKeys(schema) <= limit; - } - exports.inlineRef = inlineRef; - const REF_KEYWORDS = new Set([ - "$ref", - "$recursiveRef", - "$recursiveAnchor", - "$dynamicRef", - "$dynamicAnchor" - ]); - function hasRef(schema) { - for (const key in schema) { - if (REF_KEYWORDS.has(key)) return true; - const sch = schema[key]; - if (Array.isArray(sch) && sch.some(hasRef)) return true; - if (typeof sch == "object" && hasRef(sch)) return true; - } - return false; - } - function countKeys(schema) { - let count = 0; - for (const key in schema) { - if (key === "$ref") return Infinity; - count++; - if (SIMPLE_INLINED.has(key)) continue; - if (typeof schema[key] == "object") (0, util_1.eachItem)(schema[key], (sch) => count += countKeys(sch)); - if (count === Infinity) return Infinity; - } - return count; - } - function getFullPath(resolver, id = "", normalize) { - if (normalize !== false) id = normalizeId(id); - return _getFullPath(resolver, resolver.parse(id)); - } - exports.getFullPath = getFullPath; - function _getFullPath(resolver, p) { - return resolver.serialize(p).split("#")[0] + "#"; - } - exports._getFullPath = _getFullPath; - const TRAILING_SLASH_HASH = /#\/?$/; - function normalizeId(id) { - return id ? id.replace(TRAILING_SLASH_HASH, "") : ""; - } - exports.normalizeId = normalizeId; - function resolveUrl(resolver, baseId, id) { - id = normalizeId(id); - return resolver.resolve(baseId, id); - } - exports.resolveUrl = resolveUrl; - const ANCHOR = /^[a-z_][-a-z0-9._]*$/i; - function getSchemaRefs(schema, baseId) { - if (typeof schema == "boolean") return {}; - const { schemaId, uriResolver } = this.opts; - const schId = normalizeId(schema[schemaId] || baseId); - const baseIds = { "": schId }; - const pathPrefix = getFullPath(uriResolver, schId, false); - const localRefs = {}; - const schemaRefs = /* @__PURE__ */ new Set(); - traverse(schema, { allKeys: true }, (sch, jsonPtr, _, parentJsonPtr) => { - if (parentJsonPtr === void 0) return; - const fullPath = pathPrefix + jsonPtr; - let innerBaseId = baseIds[parentJsonPtr]; - if (typeof sch[schemaId] == "string") innerBaseId = addRef.call(this, sch[schemaId]); - addAnchor.call(this, sch.$anchor); - addAnchor.call(this, sch.$dynamicAnchor); - baseIds[jsonPtr] = innerBaseId; - function addRef(ref) { - const _resolve = this.opts.uriResolver.resolve; - ref = normalizeId(innerBaseId ? _resolve(innerBaseId, ref) : ref); - if (schemaRefs.has(ref)) throw ambiguos(ref); - schemaRefs.add(ref); - let schOrRef = this.refs[ref]; - if (typeof schOrRef == "string") schOrRef = this.refs[schOrRef]; - if (typeof schOrRef == "object") checkAmbiguosRef(sch, schOrRef.schema, ref); - else if (ref !== normalizeId(fullPath)) if (ref[0] === "#") { - checkAmbiguosRef(sch, localRefs[ref], ref); - localRefs[ref] = sch; - } else this.refs[ref] = fullPath; - return ref; - } - function addAnchor(anchor) { - if (typeof anchor == "string") { - if (!ANCHOR.test(anchor)) throw new Error(`invalid anchor "${anchor}"`); - addRef.call(this, `#${anchor}`); - } - } - }); - return localRefs; - function checkAmbiguosRef(sch1, sch2, ref) { - if (sch2 !== void 0 && !equal(sch1, sch2)) throw ambiguos(ref); - } - function ambiguos(ref) { - return /* @__PURE__ */ new Error(`reference "${ref}" resolves to more than one schema`); - } - } - exports.getSchemaRefs = getSchemaRefs; -})); - -//#endregion -//#region ../../node_modules/.pnpm/ajv@8.18.0/node_modules/ajv/dist/compile/validate/index.js -var require_validate = /* @__PURE__ */ __commonJSMin(((exports) => { - Object.defineProperty(exports, "__esModule", { value: true }); - exports.getData = exports.KeywordCxt = exports.validateFunctionCode = void 0; - const boolSchema_1 = require_boolSchema(); - const dataType_1 = require_dataType(); - const applicability_1 = require_applicability(); - const dataType_2 = require_dataType(); - const defaults_1 = require_defaults(); - const keyword_1 = require_keyword(); - const subschema_1 = require_subschema(); - const codegen_1 = require_codegen(); - const names_1 = require_names(); - const resolve_1 = require_resolve(); - const util_1 = require_util(); - const errors_1 = require_errors(); - function validateFunctionCode(it) { - if (isSchemaObj(it)) { - checkKeywords(it); - if (schemaCxtHasRules(it)) { - topSchemaObjCode(it); - return; - } - } - validateFunction(it, () => (0, boolSchema_1.topBoolOrEmptySchema)(it)); - } - exports.validateFunctionCode = validateFunctionCode; - function validateFunction({ gen, validateName, schema, schemaEnv, opts }, body) { - if (opts.code.es5) gen.func(validateName, (0, codegen_1._)`${names_1.default.data}, ${names_1.default.valCxt}`, schemaEnv.$async, () => { - gen.code((0, codegen_1._)`"use strict"; ${funcSourceUrl(schema, opts)}`); - destructureValCxtES5(gen, opts); - gen.code(body); - }); - else gen.func(validateName, (0, codegen_1._)`${names_1.default.data}, ${destructureValCxt(opts)}`, schemaEnv.$async, () => gen.code(funcSourceUrl(schema, opts)).code(body)); - } - function destructureValCxt(opts) { - return (0, codegen_1._)`{${names_1.default.instancePath}="", ${names_1.default.parentData}, ${names_1.default.parentDataProperty}, ${names_1.default.rootData}=${names_1.default.data}${opts.dynamicRef ? (0, codegen_1._)`, ${names_1.default.dynamicAnchors}={}` : codegen_1.nil}}={}`; - } - function destructureValCxtES5(gen, opts) { - gen.if(names_1.default.valCxt, () => { - gen.var(names_1.default.instancePath, (0, codegen_1._)`${names_1.default.valCxt}.${names_1.default.instancePath}`); - gen.var(names_1.default.parentData, (0, codegen_1._)`${names_1.default.valCxt}.${names_1.default.parentData}`); - gen.var(names_1.default.parentDataProperty, (0, codegen_1._)`${names_1.default.valCxt}.${names_1.default.parentDataProperty}`); - gen.var(names_1.default.rootData, (0, codegen_1._)`${names_1.default.valCxt}.${names_1.default.rootData}`); - if (opts.dynamicRef) gen.var(names_1.default.dynamicAnchors, (0, codegen_1._)`${names_1.default.valCxt}.${names_1.default.dynamicAnchors}`); - }, () => { - gen.var(names_1.default.instancePath, (0, codegen_1._)`""`); - gen.var(names_1.default.parentData, (0, codegen_1._)`undefined`); - gen.var(names_1.default.parentDataProperty, (0, codegen_1._)`undefined`); - gen.var(names_1.default.rootData, names_1.default.data); - if (opts.dynamicRef) gen.var(names_1.default.dynamicAnchors, (0, codegen_1._)`{}`); - }); - } - function topSchemaObjCode(it) { - const { schema, opts, gen } = it; - validateFunction(it, () => { - if (opts.$comment && schema.$comment) commentKeyword(it); - checkNoDefault(it); - gen.let(names_1.default.vErrors, null); - gen.let(names_1.default.errors, 0); - if (opts.unevaluated) resetEvaluated(it); - typeAndKeywords(it); - returnResults(it); - }); - } - function resetEvaluated(it) { - const { gen, validateName } = it; - it.evaluated = gen.const("evaluated", (0, codegen_1._)`${validateName}.evaluated`); - gen.if((0, codegen_1._)`${it.evaluated}.dynamicProps`, () => gen.assign((0, codegen_1._)`${it.evaluated}.props`, (0, codegen_1._)`undefined`)); - gen.if((0, codegen_1._)`${it.evaluated}.dynamicItems`, () => gen.assign((0, codegen_1._)`${it.evaluated}.items`, (0, codegen_1._)`undefined`)); - } - function funcSourceUrl(schema, opts) { - const schId = typeof schema == "object" && schema[opts.schemaId]; - return schId && (opts.code.source || opts.code.process) ? (0, codegen_1._)`/*# sourceURL=${schId} */` : codegen_1.nil; - } - function subschemaCode(it, valid) { - if (isSchemaObj(it)) { - checkKeywords(it); - if (schemaCxtHasRules(it)) { - subSchemaObjCode(it, valid); - return; - } - } - (0, boolSchema_1.boolOrEmptySchema)(it, valid); - } - function schemaCxtHasRules({ schema, self }) { - if (typeof schema == "boolean") return !schema; - for (const key in schema) if (self.RULES.all[key]) return true; - return false; - } - function isSchemaObj(it) { - return typeof it.schema != "boolean"; - } - function subSchemaObjCode(it, valid) { - const { schema, gen, opts } = it; - if (opts.$comment && schema.$comment) commentKeyword(it); - updateContext(it); - checkAsyncSchema(it); - const errsCount = gen.const("_errs", names_1.default.errors); - typeAndKeywords(it, errsCount); - gen.var(valid, (0, codegen_1._)`${errsCount} === ${names_1.default.errors}`); - } - function checkKeywords(it) { - (0, util_1.checkUnknownRules)(it); - checkRefsAndKeywords(it); - } - function typeAndKeywords(it, errsCount) { - if (it.opts.jtd) return schemaKeywords(it, [], false, errsCount); - const types = (0, dataType_1.getSchemaTypes)(it.schema); - schemaKeywords(it, types, !(0, dataType_1.coerceAndCheckDataType)(it, types), errsCount); - } - function checkRefsAndKeywords(it) { - const { schema, errSchemaPath, opts, self } = it; - if (schema.$ref && opts.ignoreKeywordsWithRef && (0, util_1.schemaHasRulesButRef)(schema, self.RULES)) self.logger.warn(`$ref: keywords ignored in schema at path "${errSchemaPath}"`); - } - function checkNoDefault(it) { - const { schema, opts } = it; - if (schema.default !== void 0 && opts.useDefaults && opts.strictSchema) (0, util_1.checkStrictMode)(it, "default is ignored in the schema root"); - } - function updateContext(it) { - const schId = it.schema[it.opts.schemaId]; - if (schId) it.baseId = (0, resolve_1.resolveUrl)(it.opts.uriResolver, it.baseId, schId); - } - function checkAsyncSchema(it) { - if (it.schema.$async && !it.schemaEnv.$async) throw new Error("async schema in sync schema"); - } - function commentKeyword({ gen, schemaEnv, schema, errSchemaPath, opts }) { - const msg = schema.$comment; - if (opts.$comment === true) gen.code((0, codegen_1._)`${names_1.default.self}.logger.log(${msg})`); - else if (typeof opts.$comment == "function") { - const schemaPath = (0, codegen_1.str)`${errSchemaPath}/$comment`; - const rootName = gen.scopeValue("root", { ref: schemaEnv.root }); - gen.code((0, codegen_1._)`${names_1.default.self}.opts.$comment(${msg}, ${schemaPath}, ${rootName}.schema)`); - } - } - function returnResults(it) { - const { gen, schemaEnv, validateName, ValidationError, opts } = it; - if (schemaEnv.$async) gen.if((0, codegen_1._)`${names_1.default.errors} === 0`, () => gen.return(names_1.default.data), () => gen.throw((0, codegen_1._)`new ${ValidationError}(${names_1.default.vErrors})`)); - else { - gen.assign((0, codegen_1._)`${validateName}.errors`, names_1.default.vErrors); - if (opts.unevaluated) assignEvaluated(it); - gen.return((0, codegen_1._)`${names_1.default.errors} === 0`); - } - } - function assignEvaluated({ gen, evaluated, props, items }) { - if (props instanceof codegen_1.Name) gen.assign((0, codegen_1._)`${evaluated}.props`, props); - if (items instanceof codegen_1.Name) gen.assign((0, codegen_1._)`${evaluated}.items`, items); - } - function schemaKeywords(it, types, typeErrors, errsCount) { - const { gen, schema, data, allErrors, opts, self } = it; - const { RULES } = self; - if (schema.$ref && (opts.ignoreKeywordsWithRef || !(0, util_1.schemaHasRulesButRef)(schema, RULES))) { - gen.block(() => keywordCode(it, "$ref", RULES.all.$ref.definition)); - return; - } - if (!opts.jtd) checkStrictTypes(it, types); - gen.block(() => { - for (const group of RULES.rules) groupKeywords(group); - groupKeywords(RULES.post); - }); - function groupKeywords(group) { - if (!(0, applicability_1.shouldUseGroup)(schema, group)) return; - if (group.type) { - gen.if((0, dataType_2.checkDataType)(group.type, data, opts.strictNumbers)); - iterateKeywords(it, group); - if (types.length === 1 && types[0] === group.type && typeErrors) { - gen.else(); - (0, dataType_2.reportTypeError)(it); - } - gen.endIf(); - } else iterateKeywords(it, group); - if (!allErrors) gen.if((0, codegen_1._)`${names_1.default.errors} === ${errsCount || 0}`); - } - } - function iterateKeywords(it, group) { - const { gen, schema, opts: { useDefaults } } = it; - if (useDefaults) (0, defaults_1.assignDefaults)(it, group.type); - gen.block(() => { - for (const rule of group.rules) if ((0, applicability_1.shouldUseRule)(schema, rule)) keywordCode(it, rule.keyword, rule.definition, group.type); - }); - } - function checkStrictTypes(it, types) { - if (it.schemaEnv.meta || !it.opts.strictTypes) return; - checkContextTypes(it, types); - if (!it.opts.allowUnionTypes) checkMultipleTypes(it, types); - checkKeywordTypes(it, it.dataTypes); - } - function checkContextTypes(it, types) { - if (!types.length) return; - if (!it.dataTypes.length) { - it.dataTypes = types; - return; - } - types.forEach((t) => { - if (!includesType(it.dataTypes, t)) strictTypesError(it, `type "${t}" not allowed by context "${it.dataTypes.join(",")}"`); - }); - narrowSchemaTypes(it, types); - } - function checkMultipleTypes(it, ts) { - if (ts.length > 1 && !(ts.length === 2 && ts.includes("null"))) strictTypesError(it, "use allowUnionTypes to allow union type keyword"); - } - function checkKeywordTypes(it, ts) { - const rules = it.self.RULES.all; - for (const keyword in rules) { - const rule = rules[keyword]; - if (typeof rule == "object" && (0, applicability_1.shouldUseRule)(it.schema, rule)) { - const { type } = rule.definition; - if (type.length && !type.some((t) => hasApplicableType(ts, t))) strictTypesError(it, `missing type "${type.join(",")}" for keyword "${keyword}"`); - } - } - } - function hasApplicableType(schTs, kwdT) { - return schTs.includes(kwdT) || kwdT === "number" && schTs.includes("integer"); - } - function includesType(ts, t) { - return ts.includes(t) || t === "integer" && ts.includes("number"); - } - function narrowSchemaTypes(it, withTypes) { - const ts = []; - for (const t of it.dataTypes) if (includesType(withTypes, t)) ts.push(t); - else if (withTypes.includes("integer") && t === "number") ts.push("integer"); - it.dataTypes = ts; - } - function strictTypesError(it, msg) { - const schemaPath = it.schemaEnv.baseId + it.errSchemaPath; - msg += ` at "${schemaPath}" (strictTypes)`; - (0, util_1.checkStrictMode)(it, msg, it.opts.strictTypes); - } - var KeywordCxt = class { - constructor(it, def, keyword) { - (0, keyword_1.validateKeywordUsage)(it, def, keyword); - this.gen = it.gen; - this.allErrors = it.allErrors; - this.keyword = keyword; - this.data = it.data; - this.schema = it.schema[keyword]; - this.$data = def.$data && it.opts.$data && this.schema && this.schema.$data; - this.schemaValue = (0, util_1.schemaRefOrVal)(it, this.schema, keyword, this.$data); - this.schemaType = def.schemaType; - this.parentSchema = it.schema; - this.params = {}; - this.it = it; - this.def = def; - if (this.$data) this.schemaCode = it.gen.const("vSchema", getData(this.$data, it)); - else { - this.schemaCode = this.schemaValue; - if (!(0, keyword_1.validSchemaType)(this.schema, def.schemaType, def.allowUndefined)) throw new Error(`${keyword} value must be ${JSON.stringify(def.schemaType)}`); - } - if ("code" in def ? def.trackErrors : def.errors !== false) this.errsCount = it.gen.const("_errs", names_1.default.errors); - } - result(condition, successAction, failAction) { - this.failResult((0, codegen_1.not)(condition), successAction, failAction); - } - failResult(condition, successAction, failAction) { - this.gen.if(condition); - if (failAction) failAction(); - else this.error(); - if (successAction) { - this.gen.else(); - successAction(); - if (this.allErrors) this.gen.endIf(); - } else if (this.allErrors) this.gen.endIf(); - else this.gen.else(); - } - pass(condition, failAction) { - this.failResult((0, codegen_1.not)(condition), void 0, failAction); - } - fail(condition) { - if (condition === void 0) { - this.error(); - if (!this.allErrors) this.gen.if(false); - return; - } - this.gen.if(condition); - this.error(); - if (this.allErrors) this.gen.endIf(); - else this.gen.else(); - } - fail$data(condition) { - if (!this.$data) return this.fail(condition); - const { schemaCode } = this; - this.fail((0, codegen_1._)`${schemaCode} !== undefined && (${(0, codegen_1.or)(this.invalid$data(), condition)})`); - } - error(append, errorParams, errorPaths) { - if (errorParams) { - this.setParams(errorParams); - this._error(append, errorPaths); - this.setParams({}); - return; - } - this._error(append, errorPaths); - } - _error(append, errorPaths) { - (append ? errors_1.reportExtraError : errors_1.reportError)(this, this.def.error, errorPaths); - } - $dataError() { - (0, errors_1.reportError)(this, this.def.$dataError || errors_1.keyword$DataError); - } - reset() { - if (this.errsCount === void 0) throw new Error("add \"trackErrors\" to keyword definition"); - (0, errors_1.resetErrorsCount)(this.gen, this.errsCount); - } - ok(cond) { - if (!this.allErrors) this.gen.if(cond); - } - setParams(obj, assign) { - if (assign) Object.assign(this.params, obj); - else this.params = obj; - } - block$data(valid, codeBlock, $dataValid = codegen_1.nil) { - this.gen.block(() => { - this.check$data(valid, $dataValid); - codeBlock(); - }); - } - check$data(valid = codegen_1.nil, $dataValid = codegen_1.nil) { - if (!this.$data) return; - const { gen, schemaCode, schemaType, def } = this; - gen.if((0, codegen_1.or)((0, codegen_1._)`${schemaCode} === undefined`, $dataValid)); - if (valid !== codegen_1.nil) gen.assign(valid, true); - if (schemaType.length || def.validateSchema) { - gen.elseIf(this.invalid$data()); - this.$dataError(); - if (valid !== codegen_1.nil) gen.assign(valid, false); - } - gen.else(); - } - invalid$data() { - const { gen, schemaCode, schemaType, def, it } = this; - return (0, codegen_1.or)(wrong$DataType(), invalid$DataSchema()); - function wrong$DataType() { - if (schemaType.length) { - /* istanbul ignore if */ - if (!(schemaCode instanceof codegen_1.Name)) throw new Error("ajv implementation error"); - const st = Array.isArray(schemaType) ? schemaType : [schemaType]; - return (0, codegen_1._)`${(0, dataType_2.checkDataTypes)(st, schemaCode, it.opts.strictNumbers, dataType_2.DataType.Wrong)}`; - } - return codegen_1.nil; - } - function invalid$DataSchema() { - if (def.validateSchema) { - const validateSchemaRef = gen.scopeValue("validate$data", { ref: def.validateSchema }); - return (0, codegen_1._)`!${validateSchemaRef}(${schemaCode})`; - } - return codegen_1.nil; - } - } - subschema(appl, valid) { - const subschema = (0, subschema_1.getSubschema)(this.it, appl); - (0, subschema_1.extendSubschemaData)(subschema, this.it, appl); - (0, subschema_1.extendSubschemaMode)(subschema, appl); - const nextContext = { - ...this.it, - ...subschema, - items: void 0, - props: void 0 - }; - subschemaCode(nextContext, valid); - return nextContext; - } - mergeEvaluated(schemaCxt, toName) { - const { it, gen } = this; - if (!it.opts.unevaluated) return; - if (it.props !== true && schemaCxt.props !== void 0) it.props = util_1.mergeEvaluated.props(gen, schemaCxt.props, it.props, toName); - if (it.items !== true && schemaCxt.items !== void 0) it.items = util_1.mergeEvaluated.items(gen, schemaCxt.items, it.items, toName); - } - mergeValidEvaluated(schemaCxt, valid) { - const { it, gen } = this; - if (it.opts.unevaluated && (it.props !== true || it.items !== true)) { - gen.if(valid, () => this.mergeEvaluated(schemaCxt, codegen_1.Name)); - return true; - } - } - }; - exports.KeywordCxt = KeywordCxt; - function keywordCode(it, keyword, def, ruleType) { - const cxt = new KeywordCxt(it, def, keyword); - if ("code" in def) def.code(cxt, ruleType); - else if (cxt.$data && def.validate) (0, keyword_1.funcKeywordCode)(cxt, def); - else if ("macro" in def) (0, keyword_1.macroKeywordCode)(cxt, def); - else if (def.compile || def.validate) (0, keyword_1.funcKeywordCode)(cxt, def); - } - const JSON_POINTER = /^\/(?:[^~]|~0|~1)*$/; - const RELATIVE_JSON_POINTER = /^([0-9]+)(#|\/(?:[^~]|~0|~1)*)?$/; - function getData($data, { dataLevel, dataNames, dataPathArr }) { - let jsonPointer; - let data; - if ($data === "") return names_1.default.rootData; - if ($data[0] === "/") { - if (!JSON_POINTER.test($data)) throw new Error(`Invalid JSON-pointer: ${$data}`); - jsonPointer = $data; - data = names_1.default.rootData; - } else { - const matches = RELATIVE_JSON_POINTER.exec($data); - if (!matches) throw new Error(`Invalid JSON-pointer: ${$data}`); - const up = +matches[1]; - jsonPointer = matches[2]; - if (jsonPointer === "#") { - if (up >= dataLevel) throw new Error(errorMsg("property/index", up)); - return dataPathArr[dataLevel - up]; - } - if (up > dataLevel) throw new Error(errorMsg("data", up)); - data = dataNames[dataLevel - up]; - if (!jsonPointer) return data; - } - let expr = data; - const segments = jsonPointer.split("/"); - for (const segment of segments) if (segment) { - data = (0, codegen_1._)`${data}${(0, codegen_1.getProperty)((0, util_1.unescapeJsonPointer)(segment))}`; - expr = (0, codegen_1._)`${expr} && ${data}`; - } - return expr; - function errorMsg(pointerType, up) { - return `Cannot access ${pointerType} ${up} levels up, current level is ${dataLevel}`; - } - } - exports.getData = getData; -})); - -//#endregion -//#region ../../node_modules/.pnpm/ajv@8.18.0/node_modules/ajv/dist/runtime/validation_error.js -var require_validation_error = /* @__PURE__ */ __commonJSMin(((exports) => { - Object.defineProperty(exports, "__esModule", { value: true }); - var ValidationError = class extends Error { - constructor(errors) { - super("validation failed"); - this.errors = errors; - this.ajv = this.validation = true; - } - }; - exports.default = ValidationError; -})); - -//#endregion -//#region ../../node_modules/.pnpm/ajv@8.18.0/node_modules/ajv/dist/compile/ref_error.js -var require_ref_error = /* @__PURE__ */ __commonJSMin(((exports) => { - Object.defineProperty(exports, "__esModule", { value: true }); - const resolve_1 = require_resolve(); - var MissingRefError = class extends Error { - constructor(resolver, baseId, ref, msg) { - super(msg || `can't resolve reference ${ref} from id ${baseId}`); - this.missingRef = (0, resolve_1.resolveUrl)(resolver, baseId, ref); - this.missingSchema = (0, resolve_1.normalizeId)((0, resolve_1.getFullPath)(resolver, this.missingRef)); - } - }; - exports.default = MissingRefError; -})); - -//#endregion -//#region ../../node_modules/.pnpm/ajv@8.18.0/node_modules/ajv/dist/compile/index.js -var require_compile = /* @__PURE__ */ __commonJSMin(((exports) => { - Object.defineProperty(exports, "__esModule", { value: true }); - exports.resolveSchema = exports.getCompilingSchema = exports.resolveRef = exports.compileSchema = exports.SchemaEnv = void 0; - const codegen_1 = require_codegen(); - const validation_error_1 = require_validation_error(); - const names_1 = require_names(); - const resolve_1 = require_resolve(); - const util_1 = require_util(); - const validate_1 = require_validate(); - var SchemaEnv = class { - constructor(env) { - var _a; - this.refs = {}; - this.dynamicAnchors = {}; - let schema; - if (typeof env.schema == "object") schema = env.schema; - this.schema = env.schema; - this.schemaId = env.schemaId; - this.root = env.root || this; - this.baseId = (_a = env.baseId) !== null && _a !== void 0 ? _a : (0, resolve_1.normalizeId)(schema === null || schema === void 0 ? void 0 : schema[env.schemaId || "$id"]); - this.schemaPath = env.schemaPath; - this.localRefs = env.localRefs; - this.meta = env.meta; - this.$async = schema === null || schema === void 0 ? void 0 : schema.$async; - this.refs = {}; - } - }; - exports.SchemaEnv = SchemaEnv; - function compileSchema(sch) { - const _sch = getCompilingSchema.call(this, sch); - if (_sch) return _sch; - const rootId = (0, resolve_1.getFullPath)(this.opts.uriResolver, sch.root.baseId); - const { es5, lines } = this.opts.code; - const { ownProperties } = this.opts; - const gen = new codegen_1.CodeGen(this.scope, { - es5, - lines, - ownProperties - }); - let _ValidationError; - if (sch.$async) _ValidationError = gen.scopeValue("Error", { - ref: validation_error_1.default, - code: (0, codegen_1._)`require("ajv/dist/runtime/validation_error").default` - }); - const validateName = gen.scopeName("validate"); - sch.validateName = validateName; - const schemaCxt = { - gen, - allErrors: this.opts.allErrors, - data: names_1.default.data, - parentData: names_1.default.parentData, - parentDataProperty: names_1.default.parentDataProperty, - dataNames: [names_1.default.data], - dataPathArr: [codegen_1.nil], - dataLevel: 0, - dataTypes: [], - definedProperties: /* @__PURE__ */ new Set(), - topSchemaRef: gen.scopeValue("schema", this.opts.code.source === true ? { - ref: sch.schema, - code: (0, codegen_1.stringify)(sch.schema) - } : { ref: sch.schema }), - validateName, - ValidationError: _ValidationError, - schema: sch.schema, - schemaEnv: sch, - rootId, - baseId: sch.baseId || rootId, - schemaPath: codegen_1.nil, - errSchemaPath: sch.schemaPath || (this.opts.jtd ? "" : "#"), - errorPath: (0, codegen_1._)`""`, - opts: this.opts, - self: this - }; - let sourceCode; - try { - this._compilations.add(sch); - (0, validate_1.validateFunctionCode)(schemaCxt); - gen.optimize(this.opts.code.optimize); - const validateCode = gen.toString(); - sourceCode = `${gen.scopeRefs(names_1.default.scope)}return ${validateCode}`; - if (this.opts.code.process) sourceCode = this.opts.code.process(sourceCode, sch); - const validate = new Function(`${names_1.default.self}`, `${names_1.default.scope}`, sourceCode)(this, this.scope.get()); - this.scope.value(validateName, { ref: validate }); - validate.errors = null; - validate.schema = sch.schema; - validate.schemaEnv = sch; - if (sch.$async) validate.$async = true; - if (this.opts.code.source === true) validate.source = { - validateName, - validateCode, - scopeValues: gen._values - }; - if (this.opts.unevaluated) { - const { props, items } = schemaCxt; - validate.evaluated = { - props: props instanceof codegen_1.Name ? void 0 : props, - items: items instanceof codegen_1.Name ? void 0 : items, - dynamicProps: props instanceof codegen_1.Name, - dynamicItems: items instanceof codegen_1.Name - }; - if (validate.source) validate.source.evaluated = (0, codegen_1.stringify)(validate.evaluated); - } - sch.validate = validate; - return sch; - } catch (e) { - delete sch.validate; - delete sch.validateName; - if (sourceCode) this.logger.error("Error compiling schema, function code:", sourceCode); - throw e; - } finally { - this._compilations.delete(sch); - } - } - exports.compileSchema = compileSchema; - function resolveRef(root, baseId, ref) { - var _a; - ref = (0, resolve_1.resolveUrl)(this.opts.uriResolver, baseId, ref); - const schOrFunc = root.refs[ref]; - if (schOrFunc) return schOrFunc; - let _sch = resolve.call(this, root, ref); - if (_sch === void 0) { - const schema = (_a = root.localRefs) === null || _a === void 0 ? void 0 : _a[ref]; - const { schemaId } = this.opts; - if (schema) _sch = new SchemaEnv({ - schema, - schemaId, - root, - baseId - }); - } - if (_sch === void 0) return; - return root.refs[ref] = inlineOrCompile.call(this, _sch); - } - exports.resolveRef = resolveRef; - function inlineOrCompile(sch) { - if ((0, resolve_1.inlineRef)(sch.schema, this.opts.inlineRefs)) return sch.schema; - return sch.validate ? sch : compileSchema.call(this, sch); - } - function getCompilingSchema(schEnv) { - for (const sch of this._compilations) if (sameSchemaEnv(sch, schEnv)) return sch; - } - exports.getCompilingSchema = getCompilingSchema; - function sameSchemaEnv(s1, s2) { - return s1.schema === s2.schema && s1.root === s2.root && s1.baseId === s2.baseId; - } - function resolve(root, ref) { - let sch; - while (typeof (sch = this.refs[ref]) == "string") ref = sch; - return sch || this.schemas[ref] || resolveSchema.call(this, root, ref); - } - function resolveSchema(root, ref) { - const p = this.opts.uriResolver.parse(ref); - const refPath = (0, resolve_1._getFullPath)(this.opts.uriResolver, p); - let baseId = (0, resolve_1.getFullPath)(this.opts.uriResolver, root.baseId, void 0); - if (Object.keys(root.schema).length > 0 && refPath === baseId) return getJsonPointer.call(this, p, root); - const id = (0, resolve_1.normalizeId)(refPath); - const schOrRef = this.refs[id] || this.schemas[id]; - if (typeof schOrRef == "string") { - const sch = resolveSchema.call(this, root, schOrRef); - if (typeof (sch === null || sch === void 0 ? void 0 : sch.schema) !== "object") return; - return getJsonPointer.call(this, p, sch); - } - if (typeof (schOrRef === null || schOrRef === void 0 ? void 0 : schOrRef.schema) !== "object") return; - if (!schOrRef.validate) compileSchema.call(this, schOrRef); - if (id === (0, resolve_1.normalizeId)(ref)) { - const { schema } = schOrRef; - const { schemaId } = this.opts; - const schId = schema[schemaId]; - if (schId) baseId = (0, resolve_1.resolveUrl)(this.opts.uriResolver, baseId, schId); - return new SchemaEnv({ - schema, - schemaId, - root, - baseId - }); - } - return getJsonPointer.call(this, p, schOrRef); - } - exports.resolveSchema = resolveSchema; - const PREVENT_SCOPE_CHANGE = new Set([ - "properties", - "patternProperties", - "enum", - "dependencies", - "definitions" - ]); - function getJsonPointer(parsedRef, { baseId, schema, root }) { - var _a; - if (((_a = parsedRef.fragment) === null || _a === void 0 ? void 0 : _a[0]) !== "/") return; - for (const part of parsedRef.fragment.slice(1).split("/")) { - if (typeof schema === "boolean") return; - const partSchema = schema[(0, util_1.unescapeFragment)(part)]; - if (partSchema === void 0) return; - schema = partSchema; - const schId = typeof schema === "object" && schema[this.opts.schemaId]; - if (!PREVENT_SCOPE_CHANGE.has(part) && schId) baseId = (0, resolve_1.resolveUrl)(this.opts.uriResolver, baseId, schId); - } - let env; - if (typeof schema != "boolean" && schema.$ref && !(0, util_1.schemaHasRulesButRef)(schema, this.RULES)) { - const $ref = (0, resolve_1.resolveUrl)(this.opts.uriResolver, baseId, schema.$ref); - env = resolveSchema.call(this, root, $ref); - } - const { schemaId } = this.opts; - env = env || new SchemaEnv({ - schema, - schemaId, - root, - baseId - }); - if (env.schema !== env.root.schema) return env; - } -})); - -//#endregion -//#region ../../node_modules/.pnpm/ajv@8.18.0/node_modules/ajv/dist/refs/data.json -var require_data = /* @__PURE__ */ __commonJSMin(((exports, module) => { - module.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": false - }; -})); - -//#endregion -//#region ../../node_modules/.pnpm/fast-uri@3.1.0/node_modules/fast-uri/lib/utils.js -var require_utils = /* @__PURE__ */ __commonJSMin(((exports, module) => { - /** @type {(value: string) => boolean} */ - const isUUID = RegExp.prototype.test.bind(/^[\da-f]{8}-[\da-f]{4}-[\da-f]{4}-[\da-f]{4}-[\da-f]{12}$/iu); - /** @type {(value: string) => boolean} */ - const isIPv4 = 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); - /** - * @param {Array} input - * @returns {string} - */ - function stringArrayToHexStripped(input) { - let acc = ""; - let code = 0; - let i = 0; - for (i = 0; i < input.length; i++) { - code = input[i].charCodeAt(0); - if (code === 48) continue; - if (!(code >= 48 && code <= 57 || code >= 65 && code <= 70 || code >= 97 && code <= 102)) return ""; - acc += input[i]; - break; - } - for (i += 1; i < input.length; i++) { - code = input[i].charCodeAt(0); - if (!(code >= 48 && code <= 57 || code >= 65 && code <= 70 || code >= 97 && code <= 102)) return ""; - acc += input[i]; - } - return acc; - } - /** - * @typedef {Object} GetIPV6Result - * @property {boolean} error - Indicates if there was an error parsing the IPv6 address. - * @property {string} address - The parsed IPv6 address. - * @property {string} [zone] - The zone identifier, if present. - */ - /** - * @param {string} value - * @returns {boolean} - */ - const nonSimpleDomain = RegExp.prototype.test.bind(/[^!"$&'()*+,\-.;=_`a-z{}~]/u); - /** - * @param {Array} buffer - * @returns {boolean} - */ - function consumeIsZone(buffer) { - buffer.length = 0; - return true; - } - /** - * @param {Array} buffer - * @param {Array} address - * @param {GetIPV6Result} output - * @returns {boolean} - */ - function consumeHextets(buffer, address, output) { - if (buffer.length) { - const hex = stringArrayToHexStripped(buffer); - if (hex !== "") address.push(hex); - else { - output.error = true; - return false; - } - buffer.length = 0; - } - return true; - } - /** - * @param {string} input - * @returns {GetIPV6Result} - */ - function getIPV6(input) { - let tokenCount = 0; - const output = { - error: false, - address: "", - zone: "" - }; - /** @type {Array} */ - const address = []; - /** @type {Array} */ - const buffer = []; - let endipv6Encountered = false; - let endIpv6 = false; - let consume = consumeHextets; - for (let i = 0; i < input.length; i++) { - const cursor = input[i]; - if (cursor === "[" || cursor === "]") continue; - if (cursor === ":") { - if (endipv6Encountered === true) endIpv6 = true; - if (!consume(buffer, address, output)) break; - if (++tokenCount > 7) { - output.error = true; - break; - } - if (i > 0 && input[i - 1] === ":") endipv6Encountered = true; - address.push(":"); - continue; - } else if (cursor === "%") { - if (!consume(buffer, address, output)) break; - consume = consumeIsZone; - } else { - buffer.push(cursor); - continue; - } - } - if (buffer.length) if (consume === consumeIsZone) output.zone = buffer.join(""); - else if (endIpv6) address.push(buffer.join("")); - else address.push(stringArrayToHexStripped(buffer)); - output.address = address.join(""); - return output; - } - /** - * @typedef {Object} NormalizeIPv6Result - * @property {string} host - The normalized host. - * @property {string} [escapedHost] - The escaped host. - * @property {boolean} isIPV6 - Indicates if the host is an IPv6 address. - */ - /** - * @param {string} host - * @returns {NormalizeIPv6Result} - */ - function normalizeIPv6(host) { - if (findToken(host, ":") < 2) return { - host, - isIPV6: false - }; - const ipv6 = getIPV6(host); - if (!ipv6.error) { - let newHost = ipv6.address; - let escapedHost = ipv6.address; - if (ipv6.zone) { - newHost += "%" + ipv6.zone; - escapedHost += "%25" + ipv6.zone; - } - return { - host: newHost, - isIPV6: true, - escapedHost - }; - } else return { - host, - isIPV6: false - }; - } - /** - * @param {string} str - * @param {string} token - * @returns {number} - */ - function findToken(str, token) { - let ind = 0; - for (let i = 0; i < str.length; i++) if (str[i] === token) ind++; - return ind; - } - /** - * @param {string} path - * @returns {string} - * - * @see https://datatracker.ietf.org/doc/html/rfc3986#section-5.2.4 - */ - function removeDotSegments(path) { - let input = path; - const output = []; - let nextSlash = -1; - let len = 0; - while (len = input.length) { - if (len === 1) if (input === ".") break; - else if (input === "/") { - output.push("/"); - break; - } else { - output.push(input); - break; - } - else if (len === 2) { - if (input[0] === ".") { - if (input[1] === ".") break; - else if (input[1] === "/") { - input = input.slice(2); - continue; - } - } else if (input[0] === "/") { - if (input[1] === "." || input[1] === "/") { - output.push("/"); - break; - } - } - } else if (len === 3) { - if (input === "/..") { - if (output.length !== 0) output.pop(); - output.push("/"); - break; - } - } - if (input[0] === ".") { - if (input[1] === ".") { - if (input[2] === "/") { - input = input.slice(3); - continue; - } - } else if (input[1] === "/") { - input = input.slice(2); - continue; - } - } else if (input[0] === "/") { - if (input[1] === ".") { - if (input[2] === "/") { - input = input.slice(2); - continue; - } else if (input[2] === ".") { - if (input[3] === "/") { - input = input.slice(3); - if (output.length !== 0) output.pop(); - continue; - } - } - } - } - if ((nextSlash = input.indexOf("/", 1)) === -1) { - output.push(input); - break; - } else { - output.push(input.slice(0, nextSlash)); - input = input.slice(nextSlash); - } - } - return output.join(""); - } - /** - * @param {import('../types/index').URIComponent} component - * @param {boolean} esc - * @returns {import('../types/index').URIComponent} - */ - function normalizeComponentEncoding(component, esc) { - const func = esc !== true ? escape : unescape; - if (component.scheme !== void 0) component.scheme = func(component.scheme); - if (component.userinfo !== void 0) component.userinfo = func(component.userinfo); - if (component.host !== void 0) component.host = func(component.host); - if (component.path !== void 0) component.path = func(component.path); - if (component.query !== void 0) component.query = func(component.query); - if (component.fragment !== void 0) component.fragment = func(component.fragment); - return component; - } - /** - * @param {import('../types/index').URIComponent} component - * @returns {string|undefined} - */ - function recomposeAuthority(component) { - const uriTokens = []; - if (component.userinfo !== void 0) { - uriTokens.push(component.userinfo); - uriTokens.push("@"); - } - if (component.host !== void 0) { - let host = unescape(component.host); - if (!isIPv4(host)) { - const ipV6res = normalizeIPv6(host); - if (ipV6res.isIPV6 === true) host = `[${ipV6res.escapedHost}]`; - else host = component.host; - } - uriTokens.push(host); - } - if (typeof component.port === "number" || typeof component.port === "string") { - uriTokens.push(":"); - uriTokens.push(String(component.port)); - } - return uriTokens.length ? uriTokens.join("") : void 0; - } - module.exports = { - nonSimpleDomain, - recomposeAuthority, - normalizeComponentEncoding, - removeDotSegments, - isIPv4, - isUUID, - normalizeIPv6, - stringArrayToHexStripped - }; -})); - -//#endregion -//#region ../../node_modules/.pnpm/fast-uri@3.1.0/node_modules/fast-uri/lib/schemes.js -var require_schemes = /* @__PURE__ */ __commonJSMin(((exports, module) => { - const { isUUID } = require_utils(); - const URN_REG = /([\da-z][\d\-a-z]{0,31}):((?:[\w!$'()*+,\-.:;=@]|%[\da-f]{2})+)/iu; - const supportedSchemeNames = [ - "http", - "https", - "ws", - "wss", - "urn", - "urn:uuid" - ]; - /** @typedef {supportedSchemeNames[number]} SchemeName */ - /** - * @param {string} name - * @returns {name is SchemeName} - */ - function isValidSchemeName(name) { - return supportedSchemeNames.indexOf(name) !== -1; - } - /** - * @callback SchemeFn - * @param {import('../types/index').URIComponent} component - * @param {import('../types/index').Options} options - * @returns {import('../types/index').URIComponent} - */ - /** - * @typedef {Object} SchemeHandler - * @property {SchemeName} scheme - The scheme name. - * @property {boolean} [domainHost] - Indicates if the scheme supports domain hosts. - * @property {SchemeFn} parse - Function to parse the URI component for this scheme. - * @property {SchemeFn} serialize - Function to serialize the URI component for this scheme. - * @property {boolean} [skipNormalize] - Indicates if normalization should be skipped for this scheme. - * @property {boolean} [absolutePath] - Indicates if the scheme uses absolute paths. - * @property {boolean} [unicodeSupport] - Indicates if the scheme supports Unicode. - */ - /** - * @param {import('../types/index').URIComponent} wsComponent - * @returns {boolean} - */ - function wsIsSecure(wsComponent) { - if (wsComponent.secure === true) return true; - else if (wsComponent.secure === false) return false; - else if (wsComponent.scheme) return wsComponent.scheme.length === 3 && (wsComponent.scheme[0] === "w" || wsComponent.scheme[0] === "W") && (wsComponent.scheme[1] === "s" || wsComponent.scheme[1] === "S") && (wsComponent.scheme[2] === "s" || wsComponent.scheme[2] === "S"); - else return false; - } - /** @type {SchemeFn} */ - function httpParse(component) { - if (!component.host) component.error = component.error || "HTTP URIs must have a host."; - return component; - } - /** @type {SchemeFn} */ - function httpSerialize(component) { - const secure = String(component.scheme).toLowerCase() === "https"; - if (component.port === (secure ? 443 : 80) || component.port === "") component.port = void 0; - if (!component.path) component.path = "/"; - return component; - } - /** @type {SchemeFn} */ - function wsParse(wsComponent) { - wsComponent.secure = wsIsSecure(wsComponent); - wsComponent.resourceName = (wsComponent.path || "/") + (wsComponent.query ? "?" + wsComponent.query : ""); - wsComponent.path = void 0; - wsComponent.query = void 0; - return wsComponent; - } - /** @type {SchemeFn} */ - function wsSerialize(wsComponent) { - if (wsComponent.port === (wsIsSecure(wsComponent) ? 443 : 80) || wsComponent.port === "") wsComponent.port = void 0; - if (typeof wsComponent.secure === "boolean") { - wsComponent.scheme = wsComponent.secure ? "wss" : "ws"; - wsComponent.secure = void 0; - } - if (wsComponent.resourceName) { - const [path, query] = wsComponent.resourceName.split("?"); - wsComponent.path = path && path !== "/" ? path : void 0; - wsComponent.query = query; - wsComponent.resourceName = void 0; - } - wsComponent.fragment = void 0; - return wsComponent; - } - /** @type {SchemeFn} */ - function urnParse(urnComponent, options) { - if (!urnComponent.path) { - urnComponent.error = "URN can not be parsed"; - return urnComponent; - } - const matches = urnComponent.path.match(URN_REG); - if (matches) { - const scheme = options.scheme || urnComponent.scheme || "urn"; - urnComponent.nid = matches[1].toLowerCase(); - urnComponent.nss = matches[2]; - const schemeHandler = getSchemeHandler(`${scheme}:${options.nid || urnComponent.nid}`); - urnComponent.path = void 0; - if (schemeHandler) urnComponent = schemeHandler.parse(urnComponent, options); - } else urnComponent.error = urnComponent.error || "URN can not be parsed."; - return urnComponent; - } - /** @type {SchemeFn} */ - function urnSerialize(urnComponent, options) { - if (urnComponent.nid === void 0) throw new Error("URN without nid cannot be serialized"); - const scheme = options.scheme || urnComponent.scheme || "urn"; - const nid = urnComponent.nid.toLowerCase(); - const schemeHandler = getSchemeHandler(`${scheme}:${options.nid || nid}`); - if (schemeHandler) urnComponent = schemeHandler.serialize(urnComponent, options); - const uriComponent = urnComponent; - const nss = urnComponent.nss; - uriComponent.path = `${nid || options.nid}:${nss}`; - options.skipEscape = true; - return uriComponent; - } - /** @type {SchemeFn} */ - function urnuuidParse(urnComponent, options) { - const uuidComponent = urnComponent; - uuidComponent.uuid = uuidComponent.nss; - uuidComponent.nss = void 0; - if (!options.tolerant && (!uuidComponent.uuid || !isUUID(uuidComponent.uuid))) uuidComponent.error = uuidComponent.error || "UUID is not valid."; - return uuidComponent; - } - /** @type {SchemeFn} */ - function urnuuidSerialize(uuidComponent) { - const urnComponent = uuidComponent; - urnComponent.nss = (uuidComponent.uuid || "").toLowerCase(); - return urnComponent; - } - const http = { - scheme: "http", - domainHost: true, - parse: httpParse, - serialize: httpSerialize - }; - const https = { - scheme: "https", - domainHost: http.domainHost, - parse: httpParse, - serialize: httpSerialize - }; - const ws = { - scheme: "ws", - domainHost: true, - parse: wsParse, - serialize: wsSerialize - }; - const wss = { - scheme: "wss", - domainHost: ws.domainHost, - parse: ws.parse, - serialize: ws.serialize - }; - const urn = { - scheme: "urn", - parse: urnParse, - serialize: urnSerialize, - skipNormalize: true - }; - const urnuuid = { - scheme: "urn:uuid", - parse: urnuuidParse, - serialize: urnuuidSerialize, - skipNormalize: true - }; - const SCHEMES = { - http, - https, - ws, - wss, - urn, - "urn:uuid": urnuuid - }; - Object.setPrototypeOf(SCHEMES, null); - /** - * @param {string|undefined} scheme - * @returns {SchemeHandler|undefined} - */ - function getSchemeHandler(scheme) { - return scheme && (SCHEMES[scheme] || SCHEMES[scheme.toLowerCase()]) || void 0; - } - module.exports = { - wsIsSecure, - SCHEMES, - isValidSchemeName, - getSchemeHandler - }; -})); - -//#endregion -//#region ../../node_modules/.pnpm/fast-uri@3.1.0/node_modules/fast-uri/index.js -var require_fast_uri = /* @__PURE__ */ __commonJSMin(((exports, module) => { - const { normalizeIPv6, removeDotSegments, recomposeAuthority, normalizeComponentEncoding, isIPv4, nonSimpleDomain } = require_utils(); - const { SCHEMES, getSchemeHandler } = require_schemes(); - /** - * @template {import('./types/index').URIComponent|string} T - * @param {T} uri - * @param {import('./types/index').Options} [options] - * @returns {T} - */ - function normalize(uri, options) { - if (typeof uri === "string") uri = serialize(parse(uri, options), options); - else if (typeof uri === "object") uri = parse(serialize(uri, options), options); - return uri; - } - /** - * @param {string} baseURI - * @param {string} relativeURI - * @param {import('./types/index').Options} [options] - * @returns {string} - */ - function resolve(baseURI, relativeURI, options) { - const schemelessOptions = options ? Object.assign({ scheme: "null" }, options) : { scheme: "null" }; - const resolved = resolveComponent(parse(baseURI, schemelessOptions), parse(relativeURI, schemelessOptions), schemelessOptions, true); - schemelessOptions.skipEscape = true; - return serialize(resolved, schemelessOptions); - } - /** - * @param {import ('./types/index').URIComponent} base - * @param {import ('./types/index').URIComponent} relative - * @param {import('./types/index').Options} [options] - * @param {boolean} [skipNormalization=false] - * @returns {import ('./types/index').URIComponent} - */ - function resolveComponent(base, relative, options, skipNormalization) { - /** @type {import('./types/index').URIComponent} */ - const target = {}; - if (!skipNormalization) { - base = parse(serialize(base, options), options); - relative = parse(serialize(relative, options), options); - } - options = options || {}; - if (!options.tolerant && relative.scheme) { - target.scheme = relative.scheme; - target.userinfo = relative.userinfo; - target.host = relative.host; - target.port = relative.port; - target.path = removeDotSegments(relative.path || ""); - target.query = relative.query; - } else { - if (relative.userinfo !== void 0 || relative.host !== void 0 || relative.port !== void 0) { - target.userinfo = relative.userinfo; - target.host = relative.host; - target.port = relative.port; - target.path = removeDotSegments(relative.path || ""); - target.query = relative.query; - } else { - if (!relative.path) { - target.path = base.path; - if (relative.query !== void 0) target.query = relative.query; - else target.query = base.query; - } else { - if (relative.path[0] === "/") target.path = removeDotSegments(relative.path); - else { - if ((base.userinfo !== void 0 || base.host !== void 0 || base.port !== void 0) && !base.path) target.path = "/" + relative.path; - else if (!base.path) target.path = relative.path; - else target.path = base.path.slice(0, base.path.lastIndexOf("/") + 1) + relative.path; - target.path = removeDotSegments(target.path); - } - target.query = relative.query; - } - target.userinfo = base.userinfo; - target.host = base.host; - target.port = base.port; - } - target.scheme = base.scheme; - } - target.fragment = relative.fragment; - return target; - } - /** - * @param {import ('./types/index').URIComponent|string} uriA - * @param {import ('./types/index').URIComponent|string} uriB - * @param {import ('./types/index').Options} options - * @returns {boolean} - */ - function equal(uriA, uriB, options) { - if (typeof uriA === "string") { - uriA = unescape(uriA); - uriA = serialize(normalizeComponentEncoding(parse(uriA, options), true), { - ...options, - skipEscape: true - }); - } else if (typeof uriA === "object") uriA = serialize(normalizeComponentEncoding(uriA, true), { - ...options, - skipEscape: true - }); - if (typeof uriB === "string") { - uriB = unescape(uriB); - uriB = serialize(normalizeComponentEncoding(parse(uriB, options), true), { - ...options, - skipEscape: true - }); - } else if (typeof uriB === "object") uriB = serialize(normalizeComponentEncoding(uriB, true), { - ...options, - skipEscape: true - }); - return uriA.toLowerCase() === uriB.toLowerCase(); - } - /** - * @param {Readonly} cmpts - * @param {import('./types/index').Options} [opts] - * @returns {string} - */ - function serialize(cmpts, opts) { - const component = { - host: cmpts.host, - scheme: cmpts.scheme, - userinfo: cmpts.userinfo, - port: cmpts.port, - path: cmpts.path, - query: cmpts.query, - nid: cmpts.nid, - nss: cmpts.nss, - uuid: cmpts.uuid, - fragment: cmpts.fragment, - reference: cmpts.reference, - resourceName: cmpts.resourceName, - secure: cmpts.secure, - error: "" - }; - const options = Object.assign({}, opts); - const uriTokens = []; - const schemeHandler = getSchemeHandler(options.scheme || component.scheme); - if (schemeHandler && schemeHandler.serialize) schemeHandler.serialize(component, options); - if (component.path !== void 0) if (!options.skipEscape) { - component.path = escape(component.path); - if (component.scheme !== void 0) component.path = component.path.split("%3A").join(":"); - } else component.path = unescape(component.path); - if (options.reference !== "suffix" && component.scheme) uriTokens.push(component.scheme, ":"); - const authority = recomposeAuthority(component); - if (authority !== void 0) { - if (options.reference !== "suffix") uriTokens.push("//"); - uriTokens.push(authority); - if (component.path && component.path[0] !== "/") uriTokens.push("/"); - } - if (component.path !== void 0) { - let s = component.path; - if (!options.absolutePath && (!schemeHandler || !schemeHandler.absolutePath)) s = removeDotSegments(s); - if (authority === void 0 && s[0] === "/" && s[1] === "/") s = "/%2F" + s.slice(2); - uriTokens.push(s); - } - if (component.query !== void 0) uriTokens.push("?", component.query); - if (component.fragment !== void 0) uriTokens.push("#", component.fragment); - return uriTokens.join(""); - } - const URI_PARSE = /^(?:([^#/:?]+):)?(?:\/\/((?:([^#/?@]*)@)?(\[[^#/?\]]+\]|[^#/:?]*)(?::(\d*))?))?([^#?]*)(?:\?([^#]*))?(?:#((?:.|[\n\r])*))?/u; - /** - * @param {string} uri - * @param {import('./types/index').Options} [opts] - * @returns - */ - function parse(uri, opts) { - const options = Object.assign({}, opts); - /** @type {import('./types/index').URIComponent} */ - const parsed = { - scheme: void 0, - userinfo: void 0, - host: "", - port: void 0, - path: "", - query: void 0, - fragment: void 0 - }; - let isIP = false; - if (options.reference === "suffix") if (options.scheme) uri = options.scheme + ":" + uri; - else uri = "//" + uri; - const matches = uri.match(URI_PARSE); - if (matches) { - parsed.scheme = matches[1]; - parsed.userinfo = matches[3]; - parsed.host = matches[4]; - parsed.port = parseInt(matches[5], 10); - parsed.path = matches[6] || ""; - parsed.query = matches[7]; - parsed.fragment = matches[8]; - if (isNaN(parsed.port)) parsed.port = matches[5]; - if (parsed.host) if (isIPv4(parsed.host) === false) { - const ipv6result = normalizeIPv6(parsed.host); - parsed.host = ipv6result.host.toLowerCase(); - isIP = ipv6result.isIPV6; - } else isIP = true; - if (parsed.scheme === void 0 && parsed.userinfo === void 0 && parsed.host === void 0 && parsed.port === void 0 && parsed.query === void 0 && !parsed.path) parsed.reference = "same-document"; - else if (parsed.scheme === void 0) parsed.reference = "relative"; - else if (parsed.fragment === void 0) parsed.reference = "absolute"; - else parsed.reference = "uri"; - if (options.reference && options.reference !== "suffix" && options.reference !== parsed.reference) parsed.error = parsed.error || "URI is not a " + options.reference + " reference."; - const schemeHandler = getSchemeHandler(options.scheme || parsed.scheme); - if (!options.unicodeSupport && (!schemeHandler || !schemeHandler.unicodeSupport)) { - if (parsed.host && (options.domainHost || schemeHandler && schemeHandler.domainHost) && isIP === false && nonSimpleDomain(parsed.host)) try { - parsed.host = URL.domainToASCII(parsed.host.toLowerCase()); - } catch (e) { - parsed.error = parsed.error || "Host's domain name can not be converted to ASCII: " + e; - } - } - if (!schemeHandler || schemeHandler && !schemeHandler.skipNormalize) { - if (uri.indexOf("%") !== -1) { - if (parsed.scheme !== void 0) parsed.scheme = unescape(parsed.scheme); - if (parsed.host !== void 0) parsed.host = unescape(parsed.host); - } - if (parsed.path) parsed.path = escape(unescape(parsed.path)); - if (parsed.fragment) parsed.fragment = encodeURI(decodeURIComponent(parsed.fragment)); - } - if (schemeHandler && schemeHandler.parse) schemeHandler.parse(parsed, options); - } else parsed.error = parsed.error || "URI can not be parsed."; - return parsed; - } - const fastUri = { - SCHEMES, - normalize, - resolve, - resolveComponent, - equal, - serialize, - parse - }; - module.exports = fastUri; - module.exports.default = fastUri; - module.exports.fastUri = fastUri; -})); - -//#endregion -//#region ../../node_modules/.pnpm/ajv@8.18.0/node_modules/ajv/dist/runtime/uri.js -var require_uri = /* @__PURE__ */ __commonJSMin(((exports) => { - Object.defineProperty(exports, "__esModule", { value: true }); - const uri = require_fast_uri(); - uri.code = "require(\"ajv/dist/runtime/uri\").default"; - exports.default = uri; -})); - -//#endregion -//#region ../../node_modules/.pnpm/ajv@8.18.0/node_modules/ajv/dist/core.js -var require_core$3 = /* @__PURE__ */ __commonJSMin(((exports) => { - Object.defineProperty(exports, "__esModule", { value: true }); - exports.CodeGen = exports.Name = exports.nil = exports.stringify = exports.str = exports._ = exports.KeywordCxt = void 0; - var validate_1 = require_validate(); - Object.defineProperty(exports, "KeywordCxt", { - enumerable: true, - get: function() { - return validate_1.KeywordCxt; - } - }); - var codegen_1 = require_codegen(); - Object.defineProperty(exports, "_", { - enumerable: true, - get: function() { - return codegen_1._; - } - }); - Object.defineProperty(exports, "str", { - enumerable: true, - get: function() { - return codegen_1.str; - } - }); - Object.defineProperty(exports, "stringify", { - enumerable: true, - get: function() { - return codegen_1.stringify; - } - }); - Object.defineProperty(exports, "nil", { - enumerable: true, - get: function() { - return codegen_1.nil; - } - }); - Object.defineProperty(exports, "Name", { - enumerable: true, - get: function() { - return codegen_1.Name; - } - }); - Object.defineProperty(exports, "CodeGen", { - enumerable: true, - get: function() { - return codegen_1.CodeGen; - } - }); - const validation_error_1 = require_validation_error(); - const ref_error_1 = require_ref_error(); - const rules_1 = require_rules(); - const compile_1 = require_compile(); - const codegen_2 = require_codegen(); - const resolve_1 = require_resolve(); - const dataType_1 = require_dataType(); - const util_1 = require_util(); - const $dataRefSchema = require_data(); - const uri_1 = require_uri(); - const defaultRegExp = (str, flags) => new RegExp(str, flags); - defaultRegExp.code = "new RegExp"; - const META_IGNORE_OPTIONS = [ - "removeAdditional", - "useDefaults", - "coerceTypes" - ]; - const EXT_SCOPE_NAMES = new Set([ - "validate", - "serialize", - "parse", - "wrapper", - "root", - "schema", - "keyword", - "pattern", - "formats", - "validate$data", - "func", - "obj", - "Error" - ]); - const removedOptions = { - 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." - }; - const deprecatedOptions = { - ignoreKeywordsWithRef: "", - jsPropertySyntax: "", - unicode: "\"minLength\"/\"maxLength\" account for unicode characters by default." - }; - const MAX_EXPRESSION = 200; - function requiredOptions(o) { - var _a, _b, _c, _d, _e, _f, _g, _h, _j, _k, _l, _m, _o, _p, _q, _r, _s, _t, _u, _v, _w, _x, _y, _z, _0; - const s = o.strict; - const _optz = (_a = o.code) === null || _a === void 0 ? void 0 : _a.optimize; - const optimize = _optz === true || _optz === void 0 ? 1 : _optz || 0; - const regExp = (_c = (_b = o.code) === null || _b === void 0 ? void 0 : _b.regExp) !== null && _c !== void 0 ? _c : defaultRegExp; - const uriResolver = (_d = o.uriResolver) !== null && _d !== void 0 ? _d : uri_1.default; - return { - strictSchema: (_f = (_e = o.strictSchema) !== null && _e !== void 0 ? _e : s) !== null && _f !== void 0 ? _f : true, - strictNumbers: (_h = (_g = o.strictNumbers) !== null && _g !== void 0 ? _g : s) !== null && _h !== void 0 ? _h : true, - strictTypes: (_k = (_j = o.strictTypes) !== null && _j !== void 0 ? _j : s) !== null && _k !== void 0 ? _k : "log", - strictTuples: (_m = (_l = o.strictTuples) !== null && _l !== void 0 ? _l : s) !== null && _m !== void 0 ? _m : "log", - strictRequired: (_p = (_o = o.strictRequired) !== null && _o !== void 0 ? _o : s) !== null && _p !== void 0 ? _p : false, - code: o.code ? { - ...o.code, - optimize, - regExp - } : { - optimize, - regExp - }, - loopRequired: (_q = o.loopRequired) !== null && _q !== void 0 ? _q : MAX_EXPRESSION, - loopEnum: (_r = o.loopEnum) !== null && _r !== void 0 ? _r : MAX_EXPRESSION, - meta: (_s = o.meta) !== null && _s !== void 0 ? _s : true, - messages: (_t = o.messages) !== null && _t !== void 0 ? _t : true, - inlineRefs: (_u = o.inlineRefs) !== null && _u !== void 0 ? _u : true, - schemaId: (_v = o.schemaId) !== null && _v !== void 0 ? _v : "$id", - addUsedSchema: (_w = o.addUsedSchema) !== null && _w !== void 0 ? _w : true, - validateSchema: (_x = o.validateSchema) !== null && _x !== void 0 ? _x : true, - validateFormats: (_y = o.validateFormats) !== null && _y !== void 0 ? _y : true, - unicodeRegExp: (_z = o.unicodeRegExp) !== null && _z !== void 0 ? _z : true, - int32range: (_0 = o.int32range) !== null && _0 !== void 0 ? _0 : true, - uriResolver - }; - } - var Ajv = class { - constructor(opts = {}) { - this.schemas = {}; - this.refs = {}; - this.formats = {}; - this._compilations = /* @__PURE__ */ new Set(); - this._loading = {}; - this._cache = /* @__PURE__ */ new Map(); - opts = this.opts = { - ...opts, - ...requiredOptions(opts) - }; - const { es5, lines } = this.opts.code; - this.scope = new codegen_2.ValueScope({ - scope: {}, - prefixes: EXT_SCOPE_NAMES, - es5, - lines - }); - this.logger = getLogger(opts.logger); - const formatOpt = opts.validateFormats; - opts.validateFormats = false; - this.RULES = (0, rules_1.getRules)(); - checkOptions.call(this, removedOptions, opts, "NOT SUPPORTED"); - checkOptions.call(this, deprecatedOptions, opts, "DEPRECATED", "warn"); - this._metaOpts = getMetaSchemaOptions.call(this); - if (opts.formats) addInitialFormats.call(this); - this._addVocabularies(); - this._addDefaultMetaSchema(); - if (opts.keywords) addInitialKeywords.call(this, opts.keywords); - if (typeof opts.meta == "object") this.addMetaSchema(opts.meta); - addInitialSchemas.call(this); - opts.validateFormats = formatOpt; - } - _addVocabularies() { - this.addKeyword("$async"); - } - _addDefaultMetaSchema() { - const { $data, meta, schemaId } = this.opts; - let _dataRefSchema = $dataRefSchema; - if (schemaId === "id") { - _dataRefSchema = { ...$dataRefSchema }; - _dataRefSchema.id = _dataRefSchema.$id; - delete _dataRefSchema.$id; - } - if (meta && $data) this.addMetaSchema(_dataRefSchema, _dataRefSchema[schemaId], false); - } - defaultMeta() { - const { meta, schemaId } = this.opts; - return this.opts.defaultMeta = typeof meta == "object" ? meta[schemaId] || meta : void 0; - } - validate(schemaKeyRef, data) { - let v; - if (typeof schemaKeyRef == "string") { - v = this.getSchema(schemaKeyRef); - if (!v) throw new Error(`no schema with key or ref "${schemaKeyRef}"`); - } else v = this.compile(schemaKeyRef); - const valid = v(data); - if (!("$async" in v)) this.errors = v.errors; - return valid; - } - compile(schema, _meta) { - const sch = this._addSchema(schema, _meta); - return sch.validate || this._compileSchemaEnv(sch); - } - compileAsync(schema, meta) { - if (typeof this.opts.loadSchema != "function") throw new Error("options.loadSchema should be a function"); - const { loadSchema } = this.opts; - return runCompileAsync.call(this, schema, meta); - async function runCompileAsync(_schema, _meta) { - await loadMetaSchema.call(this, _schema.$schema); - const sch = this._addSchema(_schema, _meta); - return sch.validate || _compileAsync.call(this, sch); - } - async function loadMetaSchema($ref) { - if ($ref && !this.getSchema($ref)) await runCompileAsync.call(this, { $ref }, true); - } - async function _compileAsync(sch) { - try { - return this._compileSchemaEnv(sch); - } catch (e) { - if (!(e instanceof ref_error_1.default)) throw e; - checkLoaded.call(this, e); - await loadMissingSchema.call(this, e.missingSchema); - return _compileAsync.call(this, sch); - } - } - function checkLoaded({ missingSchema: ref, missingRef }) { - if (this.refs[ref]) throw new Error(`AnySchema ${ref} is loaded but ${missingRef} cannot be resolved`); - } - async function loadMissingSchema(ref) { - const _schema = await _loadSchema.call(this, ref); - if (!this.refs[ref]) await loadMetaSchema.call(this, _schema.$schema); - if (!this.refs[ref]) this.addSchema(_schema, ref, meta); - } - async function _loadSchema(ref) { - const p = this._loading[ref]; - if (p) return p; - try { - return await (this._loading[ref] = loadSchema(ref)); - } finally { - delete this._loading[ref]; - } - } - } - addSchema(schema, key, _meta, _validateSchema = this.opts.validateSchema) { - if (Array.isArray(schema)) { - for (const sch of schema) this.addSchema(sch, void 0, _meta, _validateSchema); - return this; - } - let id; - if (typeof schema === "object") { - const { schemaId } = this.opts; - id = schema[schemaId]; - if (id !== void 0 && typeof id != "string") throw new Error(`schema ${schemaId} must be string`); - } - key = (0, resolve_1.normalizeId)(key || id); - this._checkUnique(key); - this.schemas[key] = this._addSchema(schema, _meta, key, _validateSchema, true); - return this; - } - addMetaSchema(schema, key, _validateSchema = this.opts.validateSchema) { - this.addSchema(schema, key, true, _validateSchema); - return this; - } - validateSchema(schema, throwOrLogError) { - if (typeof schema == "boolean") return true; - let $schema; - $schema = schema.$schema; - if ($schema !== void 0 && typeof $schema != "string") throw new Error("$schema must be a string"); - $schema = $schema || this.opts.defaultMeta || this.defaultMeta(); - if (!$schema) { - this.logger.warn("meta-schema not available"); - this.errors = null; - return true; - } - const valid = this.validate($schema, schema); - if (!valid && throwOrLogError) { - const message = "schema is invalid: " + this.errorsText(); - if (this.opts.validateSchema === "log") this.logger.error(message); - else throw new Error(message); - } - return valid; - } - getSchema(keyRef) { - let sch; - while (typeof (sch = getSchEnv.call(this, keyRef)) == "string") keyRef = sch; - if (sch === void 0) { - const { schemaId } = this.opts; - const root = new compile_1.SchemaEnv({ - schema: {}, - schemaId - }); - sch = compile_1.resolveSchema.call(this, root, keyRef); - if (!sch) return; - this.refs[keyRef] = sch; - } - return sch.validate || this._compileSchemaEnv(sch); - } - removeSchema(schemaKeyRef) { - if (schemaKeyRef instanceof RegExp) { - this._removeAllSchemas(this.schemas, schemaKeyRef); - this._removeAllSchemas(this.refs, schemaKeyRef); - return this; - } - switch (typeof schemaKeyRef) { - case "undefined": - this._removeAllSchemas(this.schemas); - this._removeAllSchemas(this.refs); - this._cache.clear(); - return this; - case "string": { - const sch = getSchEnv.call(this, schemaKeyRef); - if (typeof sch == "object") this._cache.delete(sch.schema); - delete this.schemas[schemaKeyRef]; - delete this.refs[schemaKeyRef]; - return this; - } - case "object": { - const cacheKey = schemaKeyRef; - this._cache.delete(cacheKey); - let id = schemaKeyRef[this.opts.schemaId]; - if (id) { - id = (0, resolve_1.normalizeId)(id); - delete this.schemas[id]; - delete this.refs[id]; - } - return this; - } - default: throw new Error("ajv.removeSchema: invalid parameter"); - } - } - addVocabulary(definitions) { - for (const def of definitions) this.addKeyword(def); - return this; - } - addKeyword(kwdOrDef, def) { - let keyword; - if (typeof kwdOrDef == "string") { - keyword = kwdOrDef; - if (typeof def == "object") { - this.logger.warn("these parameters are deprecated, see docs for addKeyword"); - def.keyword = keyword; - } - } else if (typeof kwdOrDef == "object" && def === void 0) { - def = kwdOrDef; - keyword = def.keyword; - if (Array.isArray(keyword) && !keyword.length) throw new Error("addKeywords: keyword must be string or non-empty array"); - } else throw new Error("invalid addKeywords parameters"); - checkKeyword.call(this, keyword, def); - if (!def) { - (0, util_1.eachItem)(keyword, (kwd) => addRule.call(this, kwd)); - return this; - } - keywordMetaschema.call(this, def); - const definition = { - ...def, - type: (0, dataType_1.getJSONTypes)(def.type), - schemaType: (0, dataType_1.getJSONTypes)(def.schemaType) - }; - (0, util_1.eachItem)(keyword, definition.type.length === 0 ? (k) => addRule.call(this, k, definition) : (k) => definition.type.forEach((t) => addRule.call(this, k, definition, t))); - return this; - } - getKeyword(keyword) { - const rule = this.RULES.all[keyword]; - return typeof rule == "object" ? rule.definition : !!rule; - } - removeKeyword(keyword) { - const { RULES } = this; - delete RULES.keywords[keyword]; - delete RULES.all[keyword]; - for (const group of RULES.rules) { - const i = group.rules.findIndex((rule) => rule.keyword === keyword); - if (i >= 0) group.rules.splice(i, 1); - } - return this; - } - addFormat(name, format) { - if (typeof format == "string") format = new RegExp(format); - this.formats[name] = format; - return this; - } - errorsText(errors = this.errors, { separator = ", ", dataVar = "data" } = {}) { - if (!errors || errors.length === 0) return "No errors"; - return errors.map((e) => `${dataVar}${e.instancePath} ${e.message}`).reduce((text, msg) => text + separator + msg); - } - $dataMetaSchema(metaSchema, keywordsJsonPointers) { - const rules = this.RULES.all; - metaSchema = JSON.parse(JSON.stringify(metaSchema)); - for (const jsonPointer of keywordsJsonPointers) { - const segments = jsonPointer.split("/").slice(1); - let keywords = metaSchema; - for (const seg of segments) keywords = keywords[seg]; - for (const key in rules) { - const rule = rules[key]; - if (typeof rule != "object") continue; - const { $data } = rule.definition; - const schema = keywords[key]; - if ($data && schema) keywords[key] = schemaOrData(schema); - } - } - return metaSchema; - } - _removeAllSchemas(schemas, regex) { - for (const keyRef in schemas) { - const sch = schemas[keyRef]; - if (!regex || regex.test(keyRef)) { - if (typeof sch == "string") delete schemas[keyRef]; - else if (sch && !sch.meta) { - this._cache.delete(sch.schema); - delete schemas[keyRef]; - } - } - } - } - _addSchema(schema, meta, baseId, validateSchema = this.opts.validateSchema, addSchema = this.opts.addUsedSchema) { - let id; - const { schemaId } = this.opts; - if (typeof schema == "object") id = schema[schemaId]; - else if (this.opts.jtd) throw new Error("schema must be object"); - else if (typeof schema != "boolean") throw new Error("schema must be object or boolean"); - let sch = this._cache.get(schema); - if (sch !== void 0) return sch; - baseId = (0, resolve_1.normalizeId)(id || baseId); - const localRefs = resolve_1.getSchemaRefs.call(this, schema, baseId); - sch = new compile_1.SchemaEnv({ - schema, - schemaId, - meta, - baseId, - localRefs - }); - this._cache.set(sch.schema, sch); - if (addSchema && !baseId.startsWith("#")) { - if (baseId) this._checkUnique(baseId); - this.refs[baseId] = sch; - } - if (validateSchema) this.validateSchema(schema, true); - return sch; - } - _checkUnique(id) { - if (this.schemas[id] || this.refs[id]) throw new Error(`schema with key or id "${id}" already exists`); - } - _compileSchemaEnv(sch) { - if (sch.meta) this._compileMetaSchema(sch); - else compile_1.compileSchema.call(this, sch); - /* istanbul ignore if */ - if (!sch.validate) throw new Error("ajv implementation error"); - return sch.validate; - } - _compileMetaSchema(sch) { - const currentOpts = this.opts; - this.opts = this._metaOpts; - try { - compile_1.compileSchema.call(this, sch); - } finally { - this.opts = currentOpts; - } - } - }; - Ajv.ValidationError = validation_error_1.default; - Ajv.MissingRefError = ref_error_1.default; - exports.default = Ajv; - function checkOptions(checkOpts, options, msg, log = "error") { - for (const key in checkOpts) { - const opt = key; - if (opt in options) this.logger[log](`${msg}: option ${key}. ${checkOpts[opt]}`); - } - } - function getSchEnv(keyRef) { - keyRef = (0, resolve_1.normalizeId)(keyRef); - return this.schemas[keyRef] || this.refs[keyRef]; - } - function addInitialSchemas() { - const optsSchemas = this.opts.schemas; - if (!optsSchemas) return; - if (Array.isArray(optsSchemas)) this.addSchema(optsSchemas); - else for (const key in optsSchemas) this.addSchema(optsSchemas[key], key); - } - function addInitialFormats() { - for (const name in this.opts.formats) { - const format = this.opts.formats[name]; - if (format) this.addFormat(name, format); - } - } - function addInitialKeywords(defs) { - if (Array.isArray(defs)) { - this.addVocabulary(defs); - return; - } - this.logger.warn("keywords option as map is deprecated, pass array"); - for (const keyword in defs) { - const def = defs[keyword]; - if (!def.keyword) def.keyword = keyword; - this.addKeyword(def); - } - } - function getMetaSchemaOptions() { - const metaOpts = { ...this.opts }; - for (const opt of META_IGNORE_OPTIONS) delete metaOpts[opt]; - return metaOpts; - } - const noLogs = { - log() {}, - warn() {}, - error() {} - }; - function getLogger(logger) { - if (logger === false) return noLogs; - if (logger === void 0) return console; - if (logger.log && logger.warn && logger.error) return logger; - throw new Error("logger must implement log, warn and error methods"); - } - const KEYWORD_NAME = /^[a-z_$][a-z0-9_$:-]*$/i; - function checkKeyword(keyword, def) { - const { RULES } = this; - (0, util_1.eachItem)(keyword, (kwd) => { - if (RULES.keywords[kwd]) throw new Error(`Keyword ${kwd} is already defined`); - if (!KEYWORD_NAME.test(kwd)) throw new Error(`Keyword ${kwd} has invalid name`); - }); - if (!def) return; - if (def.$data && !("code" in def || "validate" in def)) throw new Error("$data keyword must have \"code\" or \"validate\" function"); - } - function addRule(keyword, definition, dataType) { - var _a; - const post = definition === null || definition === void 0 ? void 0 : definition.post; - if (dataType && post) throw new Error("keyword with \"post\" flag cannot have \"type\""); - const { RULES } = this; - let ruleGroup = post ? RULES.post : RULES.rules.find(({ type: t }) => t === dataType); - if (!ruleGroup) { - ruleGroup = { - type: dataType, - rules: [] - }; - RULES.rules.push(ruleGroup); - } - RULES.keywords[keyword] = true; - if (!definition) return; - const rule = { - keyword, - definition: { - ...definition, - type: (0, dataType_1.getJSONTypes)(definition.type), - schemaType: (0, dataType_1.getJSONTypes)(definition.schemaType) - } - }; - if (definition.before) addBeforeRule.call(this, ruleGroup, rule, definition.before); - else ruleGroup.rules.push(rule); - RULES.all[keyword] = rule; - (_a = definition.implements) === null || _a === void 0 || _a.forEach((kwd) => this.addKeyword(kwd)); - } - function addBeforeRule(ruleGroup, rule, before) { - const i = ruleGroup.rules.findIndex((_rule) => _rule.keyword === before); - if (i >= 0) ruleGroup.rules.splice(i, 0, rule); - else { - ruleGroup.rules.push(rule); - this.logger.warn(`rule ${before} is not defined`); - } - } - function keywordMetaschema(def) { - let { metaSchema } = def; - if (metaSchema === void 0) return; - if (def.$data && this.opts.$data) metaSchema = schemaOrData(metaSchema); - def.validateSchema = this.compile(metaSchema, true); - } - const $dataRef = { $ref: "https://raw.githubusercontent.com/ajv-validator/ajv/master/lib/refs/data.json#" }; - function schemaOrData(schema) { - return { anyOf: [schema, $dataRef] }; - } -})); - -//#endregion -//#region ../../node_modules/.pnpm/ajv@8.18.0/node_modules/ajv/dist/vocabularies/core/id.js -var require_id = /* @__PURE__ */ __commonJSMin(((exports) => { - Object.defineProperty(exports, "__esModule", { value: true }); - const def = { - keyword: "id", - code() { - throw new Error("NOT SUPPORTED: keyword \"id\", use \"$id\" for schema ID"); - } - }; - exports.default = def; -})); - -//#endregion -//#region ../../node_modules/.pnpm/ajv@8.18.0/node_modules/ajv/dist/vocabularies/core/ref.js -var require_ref = /* @__PURE__ */ __commonJSMin(((exports) => { - Object.defineProperty(exports, "__esModule", { value: true }); - exports.callRef = exports.getValidate = void 0; - const ref_error_1 = require_ref_error(); - const code_1 = require_code(); - const codegen_1 = require_codegen(); - const names_1 = require_names(); - const compile_1 = require_compile(); - const util_1 = require_util(); - const def = { - keyword: "$ref", - schemaType: "string", - code(cxt) { - const { gen, schema: $ref, it } = cxt; - const { baseId, schemaEnv: env, validateName, opts, self } = it; - const { root } = env; - if (($ref === "#" || $ref === "#/") && baseId === root.baseId) return callRootRef(); - const schOrEnv = compile_1.resolveRef.call(self, root, baseId, $ref); - if (schOrEnv === void 0) throw new ref_error_1.default(it.opts.uriResolver, baseId, $ref); - if (schOrEnv instanceof compile_1.SchemaEnv) return callValidate(schOrEnv); - return inlineRefSchema(schOrEnv); - function callRootRef() { - if (env === root) return callRef(cxt, validateName, env, env.$async); - const rootName = gen.scopeValue("root", { ref: root }); - return callRef(cxt, (0, codegen_1._)`${rootName}.validate`, root, root.$async); - } - function callValidate(sch) { - callRef(cxt, getValidate(cxt, sch), sch, sch.$async); - } - function inlineRefSchema(sch) { - const schName = gen.scopeValue("schema", opts.code.source === true ? { - ref: sch, - code: (0, codegen_1.stringify)(sch) - } : { ref: sch }); - const valid = gen.name("valid"); - const schCxt = cxt.subschema({ - schema: sch, - dataTypes: [], - schemaPath: codegen_1.nil, - topSchemaRef: schName, - errSchemaPath: $ref - }, valid); - cxt.mergeEvaluated(schCxt); - cxt.ok(valid); - } - } - }; - function getValidate(cxt, sch) { - const { gen } = cxt; - return sch.validate ? gen.scopeValue("validate", { ref: sch.validate }) : (0, codegen_1._)`${gen.scopeValue("wrapper", { ref: sch })}.validate`; - } - exports.getValidate = getValidate; - function callRef(cxt, v, sch, $async) { - const { gen, it } = cxt; - const { allErrors, schemaEnv: env, opts } = it; - const passCxt = opts.passContext ? names_1.default.this : codegen_1.nil; - if ($async) callAsyncRef(); - else callSyncRef(); - function callAsyncRef() { - if (!env.$async) throw new Error("async schema referenced by sync schema"); - const valid = gen.let("valid"); - gen.try(() => { - gen.code((0, codegen_1._)`await ${(0, code_1.callValidateCode)(cxt, v, passCxt)}`); - addEvaluatedFrom(v); - if (!allErrors) gen.assign(valid, true); - }, (e) => { - gen.if((0, codegen_1._)`!(${e} instanceof ${it.ValidationError})`, () => gen.throw(e)); - addErrorsFrom(e); - if (!allErrors) gen.assign(valid, false); - }); - cxt.ok(valid); - } - function callSyncRef() { - cxt.result((0, code_1.callValidateCode)(cxt, v, passCxt), () => addEvaluatedFrom(v), () => addErrorsFrom(v)); - } - function addErrorsFrom(source) { - const errs = (0, codegen_1._)`${source}.errors`; - gen.assign(names_1.default.vErrors, (0, codegen_1._)`${names_1.default.vErrors} === null ? ${errs} : ${names_1.default.vErrors}.concat(${errs})`); - gen.assign(names_1.default.errors, (0, codegen_1._)`${names_1.default.vErrors}.length`); - } - function addEvaluatedFrom(source) { - var _a; - if (!it.opts.unevaluated) return; - const schEvaluated = (_a = sch === null || sch === void 0 ? void 0 : sch.validate) === null || _a === void 0 ? void 0 : _a.evaluated; - if (it.props !== true) if (schEvaluated && !schEvaluated.dynamicProps) { - if (schEvaluated.props !== void 0) it.props = util_1.mergeEvaluated.props(gen, schEvaluated.props, it.props); - } else { - const props = gen.var("props", (0, codegen_1._)`${source}.evaluated.props`); - it.props = util_1.mergeEvaluated.props(gen, props, it.props, codegen_1.Name); - } - if (it.items !== true) if (schEvaluated && !schEvaluated.dynamicItems) { - if (schEvaluated.items !== void 0) it.items = util_1.mergeEvaluated.items(gen, schEvaluated.items, it.items); - } else { - const items = gen.var("items", (0, codegen_1._)`${source}.evaluated.items`); - it.items = util_1.mergeEvaluated.items(gen, items, it.items, codegen_1.Name); - } - } - } - exports.callRef = callRef; - exports.default = def; -})); - -//#endregion -//#region ../../node_modules/.pnpm/ajv@8.18.0/node_modules/ajv/dist/vocabularies/core/index.js -var require_core$2 = /* @__PURE__ */ __commonJSMin(((exports) => { - Object.defineProperty(exports, "__esModule", { value: true }); - const id_1 = require_id(); - const ref_1 = require_ref(); - const core = [ - "$schema", - "$id", - "$defs", - "$vocabulary", - { keyword: "$comment" }, - "definitions", - id_1.default, - ref_1.default - ]; - exports.default = core; -})); - -//#endregion -//#region ../../node_modules/.pnpm/ajv@8.18.0/node_modules/ajv/dist/vocabularies/validation/limitNumber.js -var require_limitNumber = /* @__PURE__ */ __commonJSMin(((exports) => { - Object.defineProperty(exports, "__esModule", { value: true }); - const codegen_1 = require_codegen(); - const ops = codegen_1.operators; - const KWDs = { - maximum: { - okStr: "<=", - ok: ops.LTE, - fail: ops.GT - }, - minimum: { - okStr: ">=", - ok: ops.GTE, - fail: ops.LT - }, - exclusiveMaximum: { - okStr: "<", - ok: ops.LT, - fail: ops.GTE - }, - exclusiveMinimum: { - okStr: ">", - ok: ops.GT, - fail: ops.LTE - } - }; - const def = { - keyword: Object.keys(KWDs), - type: "number", - schemaType: "number", - $data: true, - error: { - message: ({ keyword, schemaCode }) => (0, codegen_1.str)`must be ${KWDs[keyword].okStr} ${schemaCode}`, - params: ({ keyword, schemaCode }) => (0, codegen_1._)`{comparison: ${KWDs[keyword].okStr}, limit: ${schemaCode}}` - }, - code(cxt) { - const { keyword, data, schemaCode } = cxt; - cxt.fail$data((0, codegen_1._)`${data} ${KWDs[keyword].fail} ${schemaCode} || isNaN(${data})`); - } - }; - exports.default = def; -})); - -//#endregion -//#region ../../node_modules/.pnpm/ajv@8.18.0/node_modules/ajv/dist/vocabularies/validation/multipleOf.js -var require_multipleOf = /* @__PURE__ */ __commonJSMin(((exports) => { - Object.defineProperty(exports, "__esModule", { value: true }); - const codegen_1 = require_codegen(); - const def = { - keyword: "multipleOf", - type: "number", - schemaType: "number", - $data: true, - error: { - message: ({ schemaCode }) => (0, codegen_1.str)`must be multiple of ${schemaCode}`, - params: ({ schemaCode }) => (0, codegen_1._)`{multipleOf: ${schemaCode}}` - }, - code(cxt) { - const { gen, data, schemaCode, it } = cxt; - const prec = it.opts.multipleOfPrecision; - const res = gen.let("res"); - const invalid = prec ? (0, codegen_1._)`Math.abs(Math.round(${res}) - ${res}) > 1e-${prec}` : (0, codegen_1._)`${res} !== parseInt(${res})`; - cxt.fail$data((0, codegen_1._)`(${schemaCode} === 0 || (${res} = ${data}/${schemaCode}, ${invalid}))`); - } - }; - exports.default = def; -})); - -//#endregion -//#region ../../node_modules/.pnpm/ajv@8.18.0/node_modules/ajv/dist/runtime/ucs2length.js -var require_ucs2length = /* @__PURE__ */ __commonJSMin(((exports) => { - Object.defineProperty(exports, "__esModule", { value: true }); - function ucs2length(str) { - const len = str.length; - let length = 0; - let pos = 0; - let value; - while (pos < len) { - length++; - value = str.charCodeAt(pos++); - if (value >= 55296 && value <= 56319 && pos < len) { - value = str.charCodeAt(pos); - if ((value & 64512) === 56320) pos++; - } - } - return length; - } - exports.default = ucs2length; - ucs2length.code = "require(\"ajv/dist/runtime/ucs2length\").default"; -})); - -//#endregion -//#region ../../node_modules/.pnpm/ajv@8.18.0/node_modules/ajv/dist/vocabularies/validation/limitLength.js -var require_limitLength = /* @__PURE__ */ __commonJSMin(((exports) => { - Object.defineProperty(exports, "__esModule", { value: true }); - const codegen_1 = require_codegen(); - const util_1 = require_util(); - const ucs2length_1 = require_ucs2length(); - const def = { - keyword: ["maxLength", "minLength"], - type: "string", - schemaType: "number", - $data: true, - error: { - message({ keyword, schemaCode }) { - const comp = keyword === "maxLength" ? "more" : "fewer"; - return (0, codegen_1.str)`must NOT have ${comp} than ${schemaCode} characters`; - }, - params: ({ schemaCode }) => (0, codegen_1._)`{limit: ${schemaCode}}` - }, - code(cxt) { - const { keyword, data, schemaCode, it } = cxt; - const op = keyword === "maxLength" ? codegen_1.operators.GT : codegen_1.operators.LT; - const len = it.opts.unicode === false ? (0, codegen_1._)`${data}.length` : (0, codegen_1._)`${(0, util_1.useFunc)(cxt.gen, ucs2length_1.default)}(${data})`; - cxt.fail$data((0, codegen_1._)`${len} ${op} ${schemaCode}`); - } - }; - exports.default = def; -})); - -//#endregion -//#region ../../node_modules/.pnpm/ajv@8.18.0/node_modules/ajv/dist/vocabularies/validation/pattern.js -var require_pattern = /* @__PURE__ */ __commonJSMin(((exports) => { - Object.defineProperty(exports, "__esModule", { value: true }); - const code_1 = require_code(); - const util_1 = require_util(); - const codegen_1 = require_codegen(); - const def = { - keyword: "pattern", - type: "string", - schemaType: "string", - $data: true, - error: { - message: ({ schemaCode }) => (0, codegen_1.str)`must match pattern "${schemaCode}"`, - params: ({ schemaCode }) => (0, codegen_1._)`{pattern: ${schemaCode}}` - }, - code(cxt) { - const { gen, data, $data, schema, schemaCode, it } = cxt; - const u = it.opts.unicodeRegExp ? "u" : ""; - if ($data) { - const { regExp } = it.opts.code; - const regExpCode = regExp.code === "new RegExp" ? (0, codegen_1._)`new RegExp` : (0, util_1.useFunc)(gen, regExp); - const valid = gen.let("valid"); - gen.try(() => gen.assign(valid, (0, codegen_1._)`${regExpCode}(${schemaCode}, ${u}).test(${data})`), () => gen.assign(valid, false)); - cxt.fail$data((0, codegen_1._)`!${valid}`); - } else { - const regExp = (0, code_1.usePattern)(cxt, schema); - cxt.fail$data((0, codegen_1._)`!${regExp}.test(${data})`); - } - } - }; - exports.default = def; -})); - -//#endregion -//#region ../../node_modules/.pnpm/ajv@8.18.0/node_modules/ajv/dist/vocabularies/validation/limitProperties.js -var require_limitProperties = /* @__PURE__ */ __commonJSMin(((exports) => { - Object.defineProperty(exports, "__esModule", { value: true }); - const codegen_1 = require_codegen(); - const def = { - keyword: ["maxProperties", "minProperties"], - type: "object", - schemaType: "number", - $data: true, - error: { - message({ keyword, schemaCode }) { - const comp = keyword === "maxProperties" ? "more" : "fewer"; - return (0, codegen_1.str)`must NOT have ${comp} than ${schemaCode} properties`; - }, - params: ({ schemaCode }) => (0, codegen_1._)`{limit: ${schemaCode}}` - }, - code(cxt) { - const { keyword, data, schemaCode } = cxt; - const op = keyword === "maxProperties" ? codegen_1.operators.GT : codegen_1.operators.LT; - cxt.fail$data((0, codegen_1._)`Object.keys(${data}).length ${op} ${schemaCode}`); - } - }; - exports.default = def; -})); - -//#endregion -//#region ../../node_modules/.pnpm/ajv@8.18.0/node_modules/ajv/dist/vocabularies/validation/required.js -var require_required = /* @__PURE__ */ __commonJSMin(((exports) => { - Object.defineProperty(exports, "__esModule", { value: true }); - const code_1 = require_code(); - const codegen_1 = require_codegen(); - const util_1 = require_util(); - const def = { - keyword: "required", - type: "object", - schemaType: "array", - $data: true, - error: { - message: ({ params: { missingProperty } }) => (0, codegen_1.str)`must have required property '${missingProperty}'`, - params: ({ params: { missingProperty } }) => (0, codegen_1._)`{missingProperty: ${missingProperty}}` - }, - code(cxt) { - const { gen, schema, schemaCode, data, $data, it } = cxt; - const { opts } = it; - if (!$data && schema.length === 0) return; - const useLoop = schema.length >= opts.loopRequired; - if (it.allErrors) allErrorsMode(); - else exitOnErrorMode(); - if (opts.strictRequired) { - const props = cxt.parentSchema.properties; - const { definedProperties } = cxt.it; - for (const requiredKey of schema) if ((props === null || props === void 0 ? void 0 : props[requiredKey]) === void 0 && !definedProperties.has(requiredKey)) { - const msg = `required property "${requiredKey}" is not defined at "${it.schemaEnv.baseId + it.errSchemaPath}" (strictRequired)`; - (0, util_1.checkStrictMode)(it, msg, it.opts.strictRequired); - } - } - function allErrorsMode() { - if (useLoop || $data) cxt.block$data(codegen_1.nil, loopAllRequired); - else for (const prop of schema) (0, code_1.checkReportMissingProp)(cxt, prop); - } - function exitOnErrorMode() { - const missing = gen.let("missing"); - if (useLoop || $data) { - const valid = gen.let("valid", true); - cxt.block$data(valid, () => loopUntilMissing(missing, valid)); - cxt.ok(valid); - } else { - gen.if((0, code_1.checkMissingProp)(cxt, schema, missing)); - (0, code_1.reportMissingProp)(cxt, missing); - gen.else(); - } - } - function loopAllRequired() { - gen.forOf("prop", schemaCode, (prop) => { - cxt.setParams({ missingProperty: prop }); - gen.if((0, code_1.noPropertyInData)(gen, data, prop, opts.ownProperties), () => cxt.error()); - }); - } - function loopUntilMissing(missing, valid) { - cxt.setParams({ missingProperty: missing }); - gen.forOf(missing, schemaCode, () => { - gen.assign(valid, (0, code_1.propertyInData)(gen, data, missing, opts.ownProperties)); - gen.if((0, codegen_1.not)(valid), () => { - cxt.error(); - gen.break(); - }); - }, codegen_1.nil); - } - } - }; - exports.default = def; -})); - -//#endregion -//#region ../../node_modules/.pnpm/ajv@8.18.0/node_modules/ajv/dist/vocabularies/validation/limitItems.js -var require_limitItems = /* @__PURE__ */ __commonJSMin(((exports) => { - Object.defineProperty(exports, "__esModule", { value: true }); - const codegen_1 = require_codegen(); - const def = { - keyword: ["maxItems", "minItems"], - type: "array", - schemaType: "number", - $data: true, - error: { - message({ keyword, schemaCode }) { - const comp = keyword === "maxItems" ? "more" : "fewer"; - return (0, codegen_1.str)`must NOT have ${comp} than ${schemaCode} items`; - }, - params: ({ schemaCode }) => (0, codegen_1._)`{limit: ${schemaCode}}` - }, - code(cxt) { - const { keyword, data, schemaCode } = cxt; - const op = keyword === "maxItems" ? codegen_1.operators.GT : codegen_1.operators.LT; - cxt.fail$data((0, codegen_1._)`${data}.length ${op} ${schemaCode}`); - } - }; - exports.default = def; -})); - -//#endregion -//#region ../../node_modules/.pnpm/ajv@8.18.0/node_modules/ajv/dist/runtime/equal.js -var require_equal = /* @__PURE__ */ __commonJSMin(((exports) => { - Object.defineProperty(exports, "__esModule", { value: true }); - const equal = require_fast_deep_equal(); - equal.code = "require(\"ajv/dist/runtime/equal\").default"; - exports.default = equal; -})); - -//#endregion -//#region ../../node_modules/.pnpm/ajv@8.18.0/node_modules/ajv/dist/vocabularies/validation/uniqueItems.js -var require_uniqueItems = /* @__PURE__ */ __commonJSMin(((exports) => { - Object.defineProperty(exports, "__esModule", { value: true }); - const dataType_1 = require_dataType(); - const codegen_1 = require_codegen(); - const util_1 = require_util(); - const equal_1 = require_equal(); - const def = { - keyword: "uniqueItems", - type: "array", - schemaType: "boolean", - $data: true, - error: { - message: ({ params: { i, j } }) => (0, codegen_1.str)`must NOT have duplicate items (items ## ${j} and ${i} are identical)`, - params: ({ params: { i, j } }) => (0, codegen_1._)`{i: ${i}, j: ${j}}` - }, - code(cxt) { - const { gen, data, $data, schema, parentSchema, schemaCode, it } = cxt; - if (!$data && !schema) return; - const valid = gen.let("valid"); - const itemTypes = parentSchema.items ? (0, dataType_1.getSchemaTypes)(parentSchema.items) : []; - cxt.block$data(valid, validateUniqueItems, (0, codegen_1._)`${schemaCode} === false`); - cxt.ok(valid); - function validateUniqueItems() { - const i = gen.let("i", (0, codegen_1._)`${data}.length`); - const j = gen.let("j"); - cxt.setParams({ - i, - j - }); - gen.assign(valid, true); - gen.if((0, codegen_1._)`${i} > 1`, () => (canOptimize() ? loopN : loopN2)(i, j)); - } - function canOptimize() { - return itemTypes.length > 0 && !itemTypes.some((t) => t === "object" || t === "array"); - } - function loopN(i, j) { - const item = gen.name("item"); - const wrongType = (0, dataType_1.checkDataTypes)(itemTypes, item, it.opts.strictNumbers, dataType_1.DataType.Wrong); - const indices = gen.const("indices", (0, codegen_1._)`{}`); - gen.for((0, codegen_1._)`;${i}--;`, () => { - gen.let(item, (0, codegen_1._)`${data}[${i}]`); - gen.if(wrongType, (0, codegen_1._)`continue`); - if (itemTypes.length > 1) gen.if((0, codegen_1._)`typeof ${item} == "string"`, (0, codegen_1._)`${item} += "_"`); - gen.if((0, codegen_1._)`typeof ${indices}[${item}] == "number"`, () => { - gen.assign(j, (0, codegen_1._)`${indices}[${item}]`); - cxt.error(); - gen.assign(valid, false).break(); - }).code((0, codegen_1._)`${indices}[${item}] = ${i}`); - }); - } - function loopN2(i, j) { - const eql = (0, util_1.useFunc)(gen, equal_1.default); - const outer = gen.name("outer"); - gen.label(outer).for((0, codegen_1._)`;${i}--;`, () => gen.for((0, codegen_1._)`${j} = ${i}; ${j}--;`, () => gen.if((0, codegen_1._)`${eql}(${data}[${i}], ${data}[${j}])`, () => { - cxt.error(); - gen.assign(valid, false).break(outer); - }))); - } - } - }; - exports.default = def; -})); - -//#endregion -//#region ../../node_modules/.pnpm/ajv@8.18.0/node_modules/ajv/dist/vocabularies/validation/const.js -var require_const = /* @__PURE__ */ __commonJSMin(((exports) => { - Object.defineProperty(exports, "__esModule", { value: true }); - const codegen_1 = require_codegen(); - const util_1 = require_util(); - const equal_1 = require_equal(); - const def = { - keyword: "const", - $data: true, - error: { - message: "must be equal to constant", - params: ({ schemaCode }) => (0, codegen_1._)`{allowedValue: ${schemaCode}}` - }, - code(cxt) { - const { gen, data, $data, schemaCode, schema } = cxt; - if ($data || schema && typeof schema == "object") cxt.fail$data((0, codegen_1._)`!${(0, util_1.useFunc)(gen, equal_1.default)}(${data}, ${schemaCode})`); - else cxt.fail((0, codegen_1._)`${schema} !== ${data}`); - } - }; - exports.default = def; -})); - -//#endregion -//#region ../../node_modules/.pnpm/ajv@8.18.0/node_modules/ajv/dist/vocabularies/validation/enum.js -var require_enum = /* @__PURE__ */ __commonJSMin(((exports) => { - Object.defineProperty(exports, "__esModule", { value: true }); - const codegen_1 = require_codegen(); - const util_1 = require_util(); - const equal_1 = require_equal(); - const def = { - keyword: "enum", - schemaType: "array", - $data: true, - error: { - message: "must be equal to one of the allowed values", - params: ({ schemaCode }) => (0, codegen_1._)`{allowedValues: ${schemaCode}}` - }, - code(cxt) { - const { gen, data, $data, schema, schemaCode, it } = cxt; - if (!$data && schema.length === 0) throw new Error("enum must have non-empty array"); - const useLoop = schema.length >= it.opts.loopEnum; - let eql; - const getEql = () => eql !== null && eql !== void 0 ? eql : eql = (0, util_1.useFunc)(gen, equal_1.default); - let valid; - if (useLoop || $data) { - valid = gen.let("valid"); - cxt.block$data(valid, loopEnum); - } else { - /* istanbul ignore if */ - if (!Array.isArray(schema)) throw new Error("ajv implementation error"); - const vSchema = gen.const("vSchema", schemaCode); - valid = (0, codegen_1.or)(...schema.map((_x, i) => equalCode(vSchema, i))); - } - cxt.pass(valid); - function loopEnum() { - gen.assign(valid, false); - gen.forOf("v", schemaCode, (v) => gen.if((0, codegen_1._)`${getEql()}(${data}, ${v})`, () => gen.assign(valid, true).break())); - } - function equalCode(vSchema, i) { - const sch = schema[i]; - return typeof sch === "object" && sch !== null ? (0, codegen_1._)`${getEql()}(${data}, ${vSchema}[${i}])` : (0, codegen_1._)`${data} === ${sch}`; - } - } - }; - exports.default = def; -})); - -//#endregion -//#region ../../node_modules/.pnpm/ajv@8.18.0/node_modules/ajv/dist/vocabularies/validation/index.js -var require_validation$2 = /* @__PURE__ */ __commonJSMin(((exports) => { - Object.defineProperty(exports, "__esModule", { value: true }); - const limitNumber_1 = require_limitNumber(); - const multipleOf_1 = require_multipleOf(); - const limitLength_1 = require_limitLength(); - const pattern_1 = require_pattern(); - const limitProperties_1 = require_limitProperties(); - const required_1 = require_required(); - const limitItems_1 = require_limitItems(); - const uniqueItems_1 = require_uniqueItems(); - const const_1 = require_const(); - const enum_1 = require_enum(); - const validation = [ - limitNumber_1.default, - multipleOf_1.default, - limitLength_1.default, - pattern_1.default, - limitProperties_1.default, - required_1.default, - limitItems_1.default, - uniqueItems_1.default, - { - keyword: "type", - schemaType: ["string", "array"] - }, - { - keyword: "nullable", - schemaType: "boolean" - }, - const_1.default, - enum_1.default - ]; - exports.default = validation; -})); - -//#endregion -//#region ../../node_modules/.pnpm/ajv@8.18.0/node_modules/ajv/dist/vocabularies/applicator/additionalItems.js -var require_additionalItems = /* @__PURE__ */ __commonJSMin(((exports) => { - Object.defineProperty(exports, "__esModule", { value: true }); - exports.validateAdditionalItems = void 0; - const codegen_1 = require_codegen(); - const util_1 = require_util(); - const def = { - keyword: "additionalItems", - type: "array", - schemaType: ["boolean", "object"], - before: "uniqueItems", - error: { - message: ({ params: { len } }) => (0, codegen_1.str)`must NOT have more than ${len} items`, - params: ({ params: { len } }) => (0, codegen_1._)`{limit: ${len}}` - }, - code(cxt) { - const { parentSchema, it } = cxt; - const { items } = parentSchema; - if (!Array.isArray(items)) { - (0, util_1.checkStrictMode)(it, "\"additionalItems\" is ignored when \"items\" is not an array of schemas"); - return; - } - validateAdditionalItems(cxt, items); - } - }; - function validateAdditionalItems(cxt, items) { - const { gen, schema, data, keyword, it } = cxt; - it.items = true; - const len = gen.const("len", (0, codegen_1._)`${data}.length`); - if (schema === false) { - cxt.setParams({ len: items.length }); - cxt.pass((0, codegen_1._)`${len} <= ${items.length}`); - } else if (typeof schema == "object" && !(0, util_1.alwaysValidSchema)(it, schema)) { - const valid = gen.var("valid", (0, codegen_1._)`${len} <= ${items.length}`); - gen.if((0, codegen_1.not)(valid), () => validateItems(valid)); - cxt.ok(valid); - } - function validateItems(valid) { - gen.forRange("i", items.length, len, (i) => { - cxt.subschema({ - keyword, - dataProp: i, - dataPropType: util_1.Type.Num - }, valid); - if (!it.allErrors) gen.if((0, codegen_1.not)(valid), () => gen.break()); - }); - } - } - exports.validateAdditionalItems = validateAdditionalItems; - exports.default = def; -})); - -//#endregion -//#region ../../node_modules/.pnpm/ajv@8.18.0/node_modules/ajv/dist/vocabularies/applicator/items.js -var require_items = /* @__PURE__ */ __commonJSMin(((exports) => { - Object.defineProperty(exports, "__esModule", { value: true }); - exports.validateTuple = void 0; - const codegen_1 = require_codegen(); - const util_1 = require_util(); - const code_1 = require_code(); - const def = { - keyword: "items", - type: "array", - schemaType: [ - "object", - "array", - "boolean" - ], - before: "uniqueItems", - code(cxt) { - const { schema, it } = cxt; - if (Array.isArray(schema)) return validateTuple(cxt, "additionalItems", schema); - it.items = true; - if ((0, util_1.alwaysValidSchema)(it, schema)) return; - cxt.ok((0, code_1.validateArray)(cxt)); - } - }; - function validateTuple(cxt, extraItems, schArr = cxt.schema) { - const { gen, parentSchema, data, keyword, it } = cxt; - checkStrictTuple(parentSchema); - if (it.opts.unevaluated && schArr.length && it.items !== true) it.items = util_1.mergeEvaluated.items(gen, schArr.length, it.items); - const valid = gen.name("valid"); - const len = gen.const("len", (0, codegen_1._)`${data}.length`); - schArr.forEach((sch, i) => { - if ((0, util_1.alwaysValidSchema)(it, sch)) return; - gen.if((0, codegen_1._)`${len} > ${i}`, () => cxt.subschema({ - keyword, - schemaProp: i, - dataProp: i - }, valid)); - cxt.ok(valid); - }); - function checkStrictTuple(sch) { - const { opts, errSchemaPath } = it; - const l = schArr.length; - const fullTuple = l === sch.minItems && (l === sch.maxItems || sch[extraItems] === false); - if (opts.strictTuples && !fullTuple) { - const msg = `"${keyword}" is ${l}-tuple, but minItems or maxItems/${extraItems} are not specified or different at path "${errSchemaPath}"`; - (0, util_1.checkStrictMode)(it, msg, opts.strictTuples); - } - } - } - exports.validateTuple = validateTuple; - exports.default = def; -})); - -//#endregion -//#region ../../node_modules/.pnpm/ajv@8.18.0/node_modules/ajv/dist/vocabularies/applicator/prefixItems.js -var require_prefixItems = /* @__PURE__ */ __commonJSMin(((exports) => { - Object.defineProperty(exports, "__esModule", { value: true }); - const items_1 = require_items(); - const def = { - keyword: "prefixItems", - type: "array", - schemaType: ["array"], - before: "uniqueItems", - code: (cxt) => (0, items_1.validateTuple)(cxt, "items") - }; - exports.default = def; -})); - -//#endregion -//#region ../../node_modules/.pnpm/ajv@8.18.0/node_modules/ajv/dist/vocabularies/applicator/items2020.js -var require_items2020 = /* @__PURE__ */ __commonJSMin(((exports) => { - Object.defineProperty(exports, "__esModule", { value: true }); - const codegen_1 = require_codegen(); - const util_1 = require_util(); - const code_1 = require_code(); - const additionalItems_1 = require_additionalItems(); - const def = { - keyword: "items", - type: "array", - schemaType: ["object", "boolean"], - before: "uniqueItems", - error: { - message: ({ params: { len } }) => (0, codegen_1.str)`must NOT have more than ${len} items`, - params: ({ params: { len } }) => (0, codegen_1._)`{limit: ${len}}` - }, - code(cxt) { - const { schema, parentSchema, it } = cxt; - const { prefixItems } = parentSchema; - it.items = true; - if ((0, util_1.alwaysValidSchema)(it, schema)) return; - if (prefixItems) (0, additionalItems_1.validateAdditionalItems)(cxt, prefixItems); - else cxt.ok((0, code_1.validateArray)(cxt)); - } - }; - exports.default = def; -})); - -//#endregion -//#region ../../node_modules/.pnpm/ajv@8.18.0/node_modules/ajv/dist/vocabularies/applicator/contains.js -var require_contains = /* @__PURE__ */ __commonJSMin(((exports) => { - Object.defineProperty(exports, "__esModule", { value: true }); - const codegen_1 = require_codegen(); - const util_1 = require_util(); - const def = { - keyword: "contains", - type: "array", - schemaType: ["object", "boolean"], - before: "uniqueItems", - trackErrors: true, - error: { - message: ({ params: { min, max } }) => max === void 0 ? (0, codegen_1.str)`must contain at least ${min} valid item(s)` : (0, codegen_1.str)`must contain at least ${min} and no more than ${max} valid item(s)`, - params: ({ params: { min, max } }) => max === void 0 ? (0, codegen_1._)`{minContains: ${min}}` : (0, codegen_1._)`{minContains: ${min}, maxContains: ${max}}` - }, - code(cxt) { - const { gen, schema, parentSchema, data, it } = cxt; - let min; - let max; - const { minContains, maxContains } = parentSchema; - if (it.opts.next) { - min = minContains === void 0 ? 1 : minContains; - max = maxContains; - } else min = 1; - const len = gen.const("len", (0, codegen_1._)`${data}.length`); - cxt.setParams({ - min, - max - }); - if (max === void 0 && min === 0) { - (0, util_1.checkStrictMode)(it, `"minContains" == 0 without "maxContains": "contains" keyword ignored`); - return; - } - if (max !== void 0 && min > max) { - (0, util_1.checkStrictMode)(it, `"minContains" > "maxContains" is always invalid`); - cxt.fail(); - return; - } - if ((0, util_1.alwaysValidSchema)(it, schema)) { - let cond = (0, codegen_1._)`${len} >= ${min}`; - if (max !== void 0) cond = (0, codegen_1._)`${cond} && ${len} <= ${max}`; - cxt.pass(cond); - return; - } - it.items = true; - const valid = gen.name("valid"); - if (max === void 0 && min === 1) validateItems(valid, () => gen.if(valid, () => gen.break())); - else if (min === 0) { - gen.let(valid, true); - if (max !== void 0) gen.if((0, codegen_1._)`${data}.length > 0`, validateItemsWithCount); - } else { - gen.let(valid, false); - validateItemsWithCount(); - } - cxt.result(valid, () => cxt.reset()); - function validateItemsWithCount() { - const schValid = gen.name("_valid"); - const count = gen.let("count", 0); - validateItems(schValid, () => gen.if(schValid, () => checkLimits(count))); - } - function validateItems(_valid, block) { - gen.forRange("i", 0, len, (i) => { - cxt.subschema({ - keyword: "contains", - dataProp: i, - dataPropType: util_1.Type.Num, - compositeRule: true - }, _valid); - block(); - }); - } - function checkLimits(count) { - gen.code((0, codegen_1._)`${count}++`); - if (max === void 0) gen.if((0, codegen_1._)`${count} >= ${min}`, () => gen.assign(valid, true).break()); - else { - gen.if((0, codegen_1._)`${count} > ${max}`, () => gen.assign(valid, false).break()); - if (min === 1) gen.assign(valid, true); - else gen.if((0, codegen_1._)`${count} >= ${min}`, () => gen.assign(valid, true)); - } - } - } - }; - exports.default = def; -})); - -//#endregion -//#region ../../node_modules/.pnpm/ajv@8.18.0/node_modules/ajv/dist/vocabularies/applicator/dependencies.js -var require_dependencies = /* @__PURE__ */ __commonJSMin(((exports) => { - Object.defineProperty(exports, "__esModule", { value: true }); - exports.validateSchemaDeps = exports.validatePropertyDeps = exports.error = void 0; - const codegen_1 = require_codegen(); - const util_1 = require_util(); - const code_1 = require_code(); - exports.error = { - message: ({ params: { property, depsCount, deps } }) => { - const property_ies = depsCount === 1 ? "property" : "properties"; - return (0, codegen_1.str)`must have ${property_ies} ${deps} when property ${property} is present`; - }, - params: ({ params: { property, depsCount, deps, missingProperty } }) => (0, codegen_1._)`{property: ${property}, - missingProperty: ${missingProperty}, - depsCount: ${depsCount}, - deps: ${deps}}` - }; - const def = { - keyword: "dependencies", - type: "object", - schemaType: "object", - error: exports.error, - code(cxt) { - const [propDeps, schDeps] = splitDependencies(cxt); - validatePropertyDeps(cxt, propDeps); - validateSchemaDeps(cxt, schDeps); - } - }; - function splitDependencies({ schema }) { - const propertyDeps = {}; - const schemaDeps = {}; - for (const key in schema) { - if (key === "__proto__") continue; - const deps = Array.isArray(schema[key]) ? propertyDeps : schemaDeps; - deps[key] = schema[key]; - } - return [propertyDeps, schemaDeps]; - } - function validatePropertyDeps(cxt, propertyDeps = cxt.schema) { - const { gen, data, it } = cxt; - if (Object.keys(propertyDeps).length === 0) return; - const missing = gen.let("missing"); - for (const prop in propertyDeps) { - const deps = propertyDeps[prop]; - if (deps.length === 0) continue; - const hasProperty = (0, code_1.propertyInData)(gen, data, prop, it.opts.ownProperties); - cxt.setParams({ - property: prop, - depsCount: deps.length, - deps: deps.join(", ") - }); - if (it.allErrors) gen.if(hasProperty, () => { - for (const depProp of deps) (0, code_1.checkReportMissingProp)(cxt, depProp); - }); - else { - gen.if((0, codegen_1._)`${hasProperty} && (${(0, code_1.checkMissingProp)(cxt, deps, missing)})`); - (0, code_1.reportMissingProp)(cxt, missing); - gen.else(); - } - } - } - exports.validatePropertyDeps = validatePropertyDeps; - function validateSchemaDeps(cxt, schemaDeps = cxt.schema) { - const { gen, data, keyword, it } = cxt; - const valid = gen.name("valid"); - for (const prop in schemaDeps) { - if ((0, util_1.alwaysValidSchema)(it, schemaDeps[prop])) continue; - gen.if((0, code_1.propertyInData)(gen, data, prop, it.opts.ownProperties), () => { - const schCxt = cxt.subschema({ - keyword, - schemaProp: prop - }, valid); - cxt.mergeValidEvaluated(schCxt, valid); - }, () => gen.var(valid, true)); - cxt.ok(valid); - } - } - exports.validateSchemaDeps = validateSchemaDeps; - exports.default = def; -})); - -//#endregion -//#region ../../node_modules/.pnpm/ajv@8.18.0/node_modules/ajv/dist/vocabularies/applicator/propertyNames.js -var require_propertyNames = /* @__PURE__ */ __commonJSMin(((exports) => { - Object.defineProperty(exports, "__esModule", { value: true }); - const codegen_1 = require_codegen(); - const util_1 = require_util(); - const def = { - keyword: "propertyNames", - type: "object", - schemaType: ["object", "boolean"], - error: { - message: "property name must be valid", - params: ({ params }) => (0, codegen_1._)`{propertyName: ${params.propertyName}}` - }, - code(cxt) { - const { gen, schema, data, it } = cxt; - if ((0, util_1.alwaysValidSchema)(it, schema)) return; - const valid = gen.name("valid"); - gen.forIn("key", data, (key) => { - cxt.setParams({ propertyName: key }); - cxt.subschema({ - keyword: "propertyNames", - data: key, - dataTypes: ["string"], - propertyName: key, - compositeRule: true - }, valid); - gen.if((0, codegen_1.not)(valid), () => { - cxt.error(true); - if (!it.allErrors) gen.break(); - }); - }); - cxt.ok(valid); - } - }; - exports.default = def; -})); - -//#endregion -//#region ../../node_modules/.pnpm/ajv@8.18.0/node_modules/ajv/dist/vocabularies/applicator/additionalProperties.js -var require_additionalProperties = /* @__PURE__ */ __commonJSMin(((exports) => { - Object.defineProperty(exports, "__esModule", { value: true }); - const code_1 = require_code(); - const codegen_1 = require_codegen(); - const names_1 = require_names(); - const util_1 = require_util(); - const def = { - keyword: "additionalProperties", - type: ["object"], - schemaType: ["boolean", "object"], - allowUndefined: true, - trackErrors: true, - error: { - message: "must NOT have additional properties", - params: ({ params }) => (0, codegen_1._)`{additionalProperty: ${params.additionalProperty}}` - }, - code(cxt) { - const { gen, schema, parentSchema, data, errsCount, it } = cxt; - /* istanbul ignore if */ - if (!errsCount) throw new Error("ajv implementation error"); - const { allErrors, opts } = it; - it.props = true; - if (opts.removeAdditional !== "all" && (0, util_1.alwaysValidSchema)(it, schema)) return; - const props = (0, code_1.allSchemaProperties)(parentSchema.properties); - const patProps = (0, code_1.allSchemaProperties)(parentSchema.patternProperties); - checkAdditionalProperties(); - cxt.ok((0, codegen_1._)`${errsCount} === ${names_1.default.errors}`); - function checkAdditionalProperties() { - gen.forIn("key", data, (key) => { - if (!props.length && !patProps.length) additionalPropertyCode(key); - else gen.if(isAdditional(key), () => additionalPropertyCode(key)); - }); - } - function isAdditional(key) { - let definedProp; - if (props.length > 8) { - const propsSchema = (0, util_1.schemaRefOrVal)(it, parentSchema.properties, "properties"); - definedProp = (0, code_1.isOwnProperty)(gen, propsSchema, key); - } else if (props.length) definedProp = (0, codegen_1.or)(...props.map((p) => (0, codegen_1._)`${key} === ${p}`)); - else definedProp = codegen_1.nil; - if (patProps.length) definedProp = (0, codegen_1.or)(definedProp, ...patProps.map((p) => (0, codegen_1._)`${(0, code_1.usePattern)(cxt, p)}.test(${key})`)); - return (0, codegen_1.not)(definedProp); - } - function deleteAdditional(key) { - gen.code((0, codegen_1._)`delete ${data}[${key}]`); - } - function additionalPropertyCode(key) { - if (opts.removeAdditional === "all" || opts.removeAdditional && schema === false) { - deleteAdditional(key); - return; - } - if (schema === false) { - cxt.setParams({ additionalProperty: key }); - cxt.error(); - if (!allErrors) gen.break(); - return; - } - if (typeof schema == "object" && !(0, util_1.alwaysValidSchema)(it, schema)) { - const valid = gen.name("valid"); - if (opts.removeAdditional === "failing") { - applyAdditionalSchema(key, valid, false); - gen.if((0, codegen_1.not)(valid), () => { - cxt.reset(); - deleteAdditional(key); - }); - } else { - applyAdditionalSchema(key, valid); - if (!allErrors) gen.if((0, codegen_1.not)(valid), () => gen.break()); - } - } - } - function applyAdditionalSchema(key, valid, errors) { - const subschema = { - keyword: "additionalProperties", - dataProp: key, - dataPropType: util_1.Type.Str - }; - if (errors === false) Object.assign(subschema, { - compositeRule: true, - createErrors: false, - allErrors: false - }); - cxt.subschema(subschema, valid); - } - } - }; - exports.default = def; -})); - -//#endregion -//#region ../../node_modules/.pnpm/ajv@8.18.0/node_modules/ajv/dist/vocabularies/applicator/properties.js -var require_properties = /* @__PURE__ */ __commonJSMin(((exports) => { - Object.defineProperty(exports, "__esModule", { value: true }); - const validate_1 = require_validate(); - const code_1 = require_code(); - const util_1 = require_util(); - const additionalProperties_1 = require_additionalProperties(); - const def = { - keyword: "properties", - type: "object", - schemaType: "object", - code(cxt) { - const { gen, schema, parentSchema, data, it } = cxt; - if (it.opts.removeAdditional === "all" && parentSchema.additionalProperties === void 0) additionalProperties_1.default.code(new validate_1.KeywordCxt(it, additionalProperties_1.default, "additionalProperties")); - const allProps = (0, code_1.allSchemaProperties)(schema); - for (const prop of allProps) it.definedProperties.add(prop); - if (it.opts.unevaluated && allProps.length && it.props !== true) it.props = util_1.mergeEvaluated.props(gen, (0, util_1.toHash)(allProps), it.props); - const properties = allProps.filter((p) => !(0, util_1.alwaysValidSchema)(it, schema[p])); - if (properties.length === 0) return; - const valid = gen.name("valid"); - for (const prop of properties) { - if (hasDefault(prop)) applyPropertySchema(prop); - else { - gen.if((0, code_1.propertyInData)(gen, data, prop, it.opts.ownProperties)); - applyPropertySchema(prop); - if (!it.allErrors) gen.else().var(valid, true); - gen.endIf(); - } - cxt.it.definedProperties.add(prop); - cxt.ok(valid); - } - function hasDefault(prop) { - return it.opts.useDefaults && !it.compositeRule && schema[prop].default !== void 0; - } - function applyPropertySchema(prop) { - cxt.subschema({ - keyword: "properties", - schemaProp: prop, - dataProp: prop - }, valid); - } - } - }; - exports.default = def; -})); - -//#endregion -//#region ../../node_modules/.pnpm/ajv@8.18.0/node_modules/ajv/dist/vocabularies/applicator/patternProperties.js -var require_patternProperties = /* @__PURE__ */ __commonJSMin(((exports) => { - Object.defineProperty(exports, "__esModule", { value: true }); - const code_1 = require_code(); - const codegen_1 = require_codegen(); - const util_1 = require_util(); - const util_2 = require_util(); - const def = { - keyword: "patternProperties", - type: "object", - schemaType: "object", - code(cxt) { - const { gen, schema, data, parentSchema, it } = cxt; - const { opts } = it; - const patterns = (0, code_1.allSchemaProperties)(schema); - const alwaysValidPatterns = patterns.filter((p) => (0, util_1.alwaysValidSchema)(it, schema[p])); - if (patterns.length === 0 || alwaysValidPatterns.length === patterns.length && (!it.opts.unevaluated || it.props === true)) return; - const checkProperties = opts.strictSchema && !opts.allowMatchingProperties && parentSchema.properties; - const valid = gen.name("valid"); - if (it.props !== true && !(it.props instanceof codegen_1.Name)) it.props = (0, util_2.evaluatedPropsToName)(gen, it.props); - const { props } = it; - validatePatternProperties(); - function validatePatternProperties() { - for (const pat of patterns) { - if (checkProperties) checkMatchingProperties(pat); - if (it.allErrors) validateProperties(pat); - else { - gen.var(valid, true); - validateProperties(pat); - gen.if(valid); - } - } - } - function checkMatchingProperties(pat) { - for (const prop in checkProperties) if (new RegExp(pat).test(prop)) (0, util_1.checkStrictMode)(it, `property ${prop} matches pattern ${pat} (use allowMatchingProperties)`); - } - function validateProperties(pat) { - gen.forIn("key", data, (key) => { - gen.if((0, codegen_1._)`${(0, code_1.usePattern)(cxt, pat)}.test(${key})`, () => { - const alwaysValid = alwaysValidPatterns.includes(pat); - if (!alwaysValid) cxt.subschema({ - keyword: "patternProperties", - schemaProp: pat, - dataProp: key, - dataPropType: util_2.Type.Str - }, valid); - if (it.opts.unevaluated && props !== true) gen.assign((0, codegen_1._)`${props}[${key}]`, true); - else if (!alwaysValid && !it.allErrors) gen.if((0, codegen_1.not)(valid), () => gen.break()); - }); - }); - } - } - }; - exports.default = def; -})); - -//#endregion -//#region ../../node_modules/.pnpm/ajv@8.18.0/node_modules/ajv/dist/vocabularies/applicator/not.js -var require_not = /* @__PURE__ */ __commonJSMin(((exports) => { - Object.defineProperty(exports, "__esModule", { value: true }); - const util_1 = require_util(); - const def = { - keyword: "not", - schemaType: ["object", "boolean"], - trackErrors: true, - code(cxt) { - const { gen, schema, it } = cxt; - if ((0, util_1.alwaysValidSchema)(it, schema)) { - cxt.fail(); - return; - } - const valid = gen.name("valid"); - cxt.subschema({ - keyword: "not", - compositeRule: true, - createErrors: false, - allErrors: false - }, valid); - cxt.failResult(valid, () => cxt.reset(), () => cxt.error()); - }, - error: { message: "must NOT be valid" } - }; - exports.default = def; -})); - -//#endregion -//#region ../../node_modules/.pnpm/ajv@8.18.0/node_modules/ajv/dist/vocabularies/applicator/anyOf.js -var require_anyOf = /* @__PURE__ */ __commonJSMin(((exports) => { - Object.defineProperty(exports, "__esModule", { value: true }); - const def = { - keyword: "anyOf", - schemaType: "array", - trackErrors: true, - code: require_code().validateUnion, - error: { message: "must match a schema in anyOf" } - }; - exports.default = def; -})); - -//#endregion -//#region ../../node_modules/.pnpm/ajv@8.18.0/node_modules/ajv/dist/vocabularies/applicator/oneOf.js -var require_oneOf = /* @__PURE__ */ __commonJSMin(((exports) => { - Object.defineProperty(exports, "__esModule", { value: true }); - const codegen_1 = require_codegen(); - const util_1 = require_util(); - const def = { - keyword: "oneOf", - schemaType: "array", - trackErrors: true, - error: { - message: "must match exactly one schema in oneOf", - params: ({ params }) => (0, codegen_1._)`{passingSchemas: ${params.passing}}` - }, - code(cxt) { - const { gen, schema, parentSchema, it } = cxt; - /* istanbul ignore if */ - if (!Array.isArray(schema)) throw new Error("ajv implementation error"); - if (it.opts.discriminator && parentSchema.discriminator) return; - const schArr = schema; - const valid = gen.let("valid", false); - const passing = gen.let("passing", null); - const schValid = gen.name("_valid"); - cxt.setParams({ passing }); - gen.block(validateOneOf); - cxt.result(valid, () => cxt.reset(), () => cxt.error(true)); - function validateOneOf() { - schArr.forEach((sch, i) => { - let schCxt; - if ((0, util_1.alwaysValidSchema)(it, sch)) gen.var(schValid, true); - else schCxt = cxt.subschema({ - keyword: "oneOf", - schemaProp: i, - compositeRule: true - }, schValid); - if (i > 0) gen.if((0, codegen_1._)`${schValid} && ${valid}`).assign(valid, false).assign(passing, (0, codegen_1._)`[${passing}, ${i}]`).else(); - gen.if(schValid, () => { - gen.assign(valid, true); - gen.assign(passing, i); - if (schCxt) cxt.mergeEvaluated(schCxt, codegen_1.Name); - }); - }); - } - } - }; - exports.default = def; -})); - -//#endregion -//#region ../../node_modules/.pnpm/ajv@8.18.0/node_modules/ajv/dist/vocabularies/applicator/allOf.js -var require_allOf = /* @__PURE__ */ __commonJSMin(((exports) => { - Object.defineProperty(exports, "__esModule", { value: true }); - const util_1 = require_util(); - const def = { - keyword: "allOf", - schemaType: "array", - code(cxt) { - const { gen, schema, it } = cxt; - /* istanbul ignore if */ - if (!Array.isArray(schema)) throw new Error("ajv implementation error"); - const valid = gen.name("valid"); - schema.forEach((sch, i) => { - if ((0, util_1.alwaysValidSchema)(it, sch)) return; - const schCxt = cxt.subschema({ - keyword: "allOf", - schemaProp: i - }, valid); - cxt.ok(valid); - cxt.mergeEvaluated(schCxt); - }); - } - }; - exports.default = def; -})); - -//#endregion -//#region ../../node_modules/.pnpm/ajv@8.18.0/node_modules/ajv/dist/vocabularies/applicator/if.js -var require_if = /* @__PURE__ */ __commonJSMin(((exports) => { - Object.defineProperty(exports, "__esModule", { value: true }); - const codegen_1 = require_codegen(); - const util_1 = require_util(); - const def = { - keyword: "if", - schemaType: ["object", "boolean"], - trackErrors: true, - error: { - message: ({ params }) => (0, codegen_1.str)`must match "${params.ifClause}" schema`, - params: ({ params }) => (0, codegen_1._)`{failingKeyword: ${params.ifClause}}` - }, - code(cxt) { - const { gen, parentSchema, it } = cxt; - if (parentSchema.then === void 0 && parentSchema.else === void 0) (0, util_1.checkStrictMode)(it, "\"if\" without \"then\" and \"else\" is ignored"); - const hasThen = hasSchema(it, "then"); - const hasElse = hasSchema(it, "else"); - if (!hasThen && !hasElse) return; - const valid = gen.let("valid", true); - const schValid = gen.name("_valid"); - validateIf(); - cxt.reset(); - if (hasThen && hasElse) { - const ifClause = gen.let("ifClause"); - cxt.setParams({ ifClause }); - gen.if(schValid, validateClause("then", ifClause), validateClause("else", ifClause)); - } else if (hasThen) gen.if(schValid, validateClause("then")); - else gen.if((0, codegen_1.not)(schValid), validateClause("else")); - cxt.pass(valid, () => cxt.error(true)); - function validateIf() { - const schCxt = cxt.subschema({ - keyword: "if", - compositeRule: true, - createErrors: false, - allErrors: false - }, schValid); - cxt.mergeEvaluated(schCxt); - } - function validateClause(keyword, ifClause) { - return () => { - const schCxt = cxt.subschema({ keyword }, schValid); - gen.assign(valid, schValid); - cxt.mergeValidEvaluated(schCxt, valid); - if (ifClause) gen.assign(ifClause, (0, codegen_1._)`${keyword}`); - else cxt.setParams({ ifClause: keyword }); - }; - } - } - }; - function hasSchema(it, keyword) { - const schema = it.schema[keyword]; - return schema !== void 0 && !(0, util_1.alwaysValidSchema)(it, schema); - } - exports.default = def; -})); - -//#endregion -//#region ../../node_modules/.pnpm/ajv@8.18.0/node_modules/ajv/dist/vocabularies/applicator/thenElse.js -var require_thenElse = /* @__PURE__ */ __commonJSMin(((exports) => { - Object.defineProperty(exports, "__esModule", { value: true }); - const util_1 = require_util(); - const def = { - keyword: ["then", "else"], - schemaType: ["object", "boolean"], - code({ keyword, parentSchema, it }) { - if (parentSchema.if === void 0) (0, util_1.checkStrictMode)(it, `"${keyword}" without "if" is ignored`); - } - }; - exports.default = def; -})); - -//#endregion -//#region ../../node_modules/.pnpm/ajv@8.18.0/node_modules/ajv/dist/vocabularies/applicator/index.js -var require_applicator$2 = /* @__PURE__ */ __commonJSMin(((exports) => { - Object.defineProperty(exports, "__esModule", { value: true }); - const additionalItems_1 = require_additionalItems(); - const prefixItems_1 = require_prefixItems(); - const items_1 = require_items(); - const items2020_1 = require_items2020(); - const contains_1 = require_contains(); - const dependencies_1 = require_dependencies(); - const propertyNames_1 = require_propertyNames(); - const additionalProperties_1 = require_additionalProperties(); - const properties_1 = require_properties(); - const patternProperties_1 = require_patternProperties(); - const not_1 = require_not(); - const anyOf_1 = require_anyOf(); - const oneOf_1 = require_oneOf(); - const allOf_1 = require_allOf(); - const if_1 = require_if(); - const thenElse_1 = require_thenElse(); - function getApplicator(draft2020 = false) { - const applicator = [ - not_1.default, - anyOf_1.default, - oneOf_1.default, - allOf_1.default, - if_1.default, - thenElse_1.default, - propertyNames_1.default, - additionalProperties_1.default, - dependencies_1.default, - properties_1.default, - patternProperties_1.default - ]; - if (draft2020) applicator.push(prefixItems_1.default, items2020_1.default); - else applicator.push(additionalItems_1.default, items_1.default); - applicator.push(contains_1.default); - return applicator; - } - exports.default = getApplicator; -})); - -//#endregion -//#region ../../node_modules/.pnpm/ajv@8.18.0/node_modules/ajv/dist/vocabularies/format/format.js -var require_format$2 = /* @__PURE__ */ __commonJSMin(((exports) => { - Object.defineProperty(exports, "__esModule", { value: true }); - const codegen_1 = require_codegen(); - const def = { - keyword: "format", - type: ["number", "string"], - schemaType: "string", - $data: true, - error: { - message: ({ schemaCode }) => (0, codegen_1.str)`must match format "${schemaCode}"`, - params: ({ schemaCode }) => (0, codegen_1._)`{format: ${schemaCode}}` - }, - code(cxt, ruleType) { - const { gen, data, $data, schema, schemaCode, it } = cxt; - const { opts, errSchemaPath, schemaEnv, self } = it; - if (!opts.validateFormats) return; - if ($data) validate$DataFormat(); - else validateFormat(); - function validate$DataFormat() { - const fmts = gen.scopeValue("formats", { - ref: self.formats, - code: opts.code.formats - }); - const fDef = gen.const("fDef", (0, codegen_1._)`${fmts}[${schemaCode}]`); - const fType = gen.let("fType"); - const format = gen.let("format"); - gen.if((0, codegen_1._)`typeof ${fDef} == "object" && !(${fDef} instanceof RegExp)`, () => gen.assign(fType, (0, codegen_1._)`${fDef}.type || "string"`).assign(format, (0, codegen_1._)`${fDef}.validate`), () => gen.assign(fType, (0, codegen_1._)`"string"`).assign(format, fDef)); - cxt.fail$data((0, codegen_1.or)(unknownFmt(), invalidFmt())); - function unknownFmt() { - if (opts.strictSchema === false) return codegen_1.nil; - return (0, codegen_1._)`${schemaCode} && !${format}`; - } - function invalidFmt() { - const callFormat = schemaEnv.$async ? (0, codegen_1._)`(${fDef}.async ? await ${format}(${data}) : ${format}(${data}))` : (0, codegen_1._)`${format}(${data})`; - const validData = (0, codegen_1._)`(typeof ${format} == "function" ? ${callFormat} : ${format}.test(${data}))`; - return (0, codegen_1._)`${format} && ${format} !== true && ${fType} === ${ruleType} && !${validData}`; - } - } - function validateFormat() { - const formatDef = self.formats[schema]; - if (!formatDef) { - unknownFormat(); - return; - } - if (formatDef === true) return; - const [fmtType, format, fmtRef] = getFormat(formatDef); - if (fmtType === ruleType) cxt.pass(validCondition()); - function unknownFormat() { - if (opts.strictSchema === false) { - self.logger.warn(unknownMsg()); - return; - } - throw new Error(unknownMsg()); - function unknownMsg() { - return `unknown format "${schema}" ignored in schema at path "${errSchemaPath}"`; - } - } - function getFormat(fmtDef) { - const code = fmtDef instanceof RegExp ? (0, codegen_1.regexpCode)(fmtDef) : opts.code.formats ? (0, codegen_1._)`${opts.code.formats}${(0, codegen_1.getProperty)(schema)}` : void 0; - const fmt = gen.scopeValue("formats", { - key: schema, - ref: fmtDef, - code - }); - if (typeof fmtDef == "object" && !(fmtDef instanceof RegExp)) return [ - fmtDef.type || "string", - fmtDef.validate, - (0, codegen_1._)`${fmt}.validate` - ]; - return [ - "string", - fmtDef, - fmt - ]; - } - function validCondition() { - if (typeof formatDef == "object" && !(formatDef instanceof RegExp) && formatDef.async) { - if (!schemaEnv.$async) throw new Error("async format in sync schema"); - return (0, codegen_1._)`await ${fmtRef}(${data})`; - } - return typeof format == "function" ? (0, codegen_1._)`${fmtRef}(${data})` : (0, codegen_1._)`${fmtRef}.test(${data})`; - } - } - } - }; - exports.default = def; -})); - -//#endregion -//#region ../../node_modules/.pnpm/ajv@8.18.0/node_modules/ajv/dist/vocabularies/format/index.js -var require_format$1 = /* @__PURE__ */ __commonJSMin(((exports) => { - Object.defineProperty(exports, "__esModule", { value: true }); - const format = [require_format$2().default]; - exports.default = format; -})); - -//#endregion -//#region ../../node_modules/.pnpm/ajv@8.18.0/node_modules/ajv/dist/vocabularies/metadata.js -var require_metadata = /* @__PURE__ */ __commonJSMin(((exports) => { - Object.defineProperty(exports, "__esModule", { value: true }); - exports.contentVocabulary = exports.metadataVocabulary = void 0; - exports.metadataVocabulary = [ - "title", - "description", - "default", - "deprecated", - "readOnly", - "writeOnly", - "examples" - ]; - exports.contentVocabulary = [ - "contentMediaType", - "contentEncoding", - "contentSchema" - ]; -})); - -//#endregion -//#region ../../node_modules/.pnpm/ajv@8.18.0/node_modules/ajv/dist/vocabularies/draft7.js -var require_draft7 = /* @__PURE__ */ __commonJSMin(((exports) => { - Object.defineProperty(exports, "__esModule", { value: true }); - const core_1 = require_core$2(); - const validation_1 = require_validation$2(); - const applicator_1 = require_applicator$2(); - const format_1 = require_format$1(); - const metadata_1 = require_metadata(); - const draft7Vocabularies = [ - core_1.default, - validation_1.default, - (0, applicator_1.default)(), - format_1.default, - metadata_1.metadataVocabulary, - metadata_1.contentVocabulary - ]; - exports.default = draft7Vocabularies; -})); - -//#endregion -//#region ../../node_modules/.pnpm/ajv@8.18.0/node_modules/ajv/dist/vocabularies/discriminator/types.js -var require_types = /* @__PURE__ */ __commonJSMin(((exports) => { - Object.defineProperty(exports, "__esModule", { value: true }); - exports.DiscrError = void 0; - var DiscrError; - (function(DiscrError) { - DiscrError["Tag"] = "tag"; - DiscrError["Mapping"] = "mapping"; - })(DiscrError || (exports.DiscrError = DiscrError = {})); -})); - -//#endregion -//#region ../../node_modules/.pnpm/ajv@8.18.0/node_modules/ajv/dist/vocabularies/discriminator/index.js -var require_discriminator = /* @__PURE__ */ __commonJSMin(((exports) => { - Object.defineProperty(exports, "__esModule", { value: true }); - const codegen_1 = require_codegen(); - const types_1 = require_types(); - const compile_1 = require_compile(); - const ref_error_1 = require_ref_error(); - const util_1 = require_util(); - const def = { - keyword: "discriminator", - type: "object", - schemaType: "object", - error: { - message: ({ params: { discrError, tagName } }) => discrError === types_1.DiscrError.Tag ? `tag "${tagName}" must be string` : `value of tag "${tagName}" must be in oneOf`, - params: ({ params: { discrError, tag, tagName } }) => (0, codegen_1._)`{error: ${discrError}, tag: ${tagName}, tagValue: ${tag}}` - }, - code(cxt) { - const { gen, data, schema, parentSchema, it } = cxt; - const { oneOf } = parentSchema; - if (!it.opts.discriminator) throw new Error("discriminator: requires discriminator option"); - const tagName = schema.propertyName; - if (typeof tagName != "string") throw new Error("discriminator: requires propertyName"); - if (schema.mapping) throw new Error("discriminator: mapping is not supported"); - if (!oneOf) throw new Error("discriminator: requires oneOf keyword"); - const valid = gen.let("valid", false); - const tag = gen.const("tag", (0, codegen_1._)`${data}${(0, codegen_1.getProperty)(tagName)}`); - gen.if((0, codegen_1._)`typeof ${tag} == "string"`, () => validateMapping(), () => cxt.error(false, { - discrError: types_1.DiscrError.Tag, - tag, - tagName - })); - cxt.ok(valid); - function validateMapping() { - const mapping = getMapping(); - gen.if(false); - for (const tagValue in mapping) { - gen.elseIf((0, codegen_1._)`${tag} === ${tagValue}`); - gen.assign(valid, applyTagSchema(mapping[tagValue])); - } - gen.else(); - cxt.error(false, { - discrError: types_1.DiscrError.Mapping, - tag, - tagName - }); - gen.endIf(); - } - function applyTagSchema(schemaProp) { - const _valid = gen.name("valid"); - const schCxt = cxt.subschema({ - keyword: "oneOf", - schemaProp - }, _valid); - cxt.mergeEvaluated(schCxt, codegen_1.Name); - return _valid; - } - function getMapping() { - var _a; - const oneOfMapping = {}; - const topRequired = hasRequired(parentSchema); - let tagRequired = true; - for (let i = 0; i < oneOf.length; i++) { - let sch = oneOf[i]; - if ((sch === null || sch === void 0 ? void 0 : sch.$ref) && !(0, util_1.schemaHasRulesButRef)(sch, it.self.RULES)) { - const ref = sch.$ref; - sch = compile_1.resolveRef.call(it.self, it.schemaEnv.root, it.baseId, ref); - if (sch instanceof compile_1.SchemaEnv) sch = sch.schema; - if (sch === void 0) throw new ref_error_1.default(it.opts.uriResolver, it.baseId, ref); - } - const propSch = (_a = sch === null || sch === void 0 ? void 0 : sch.properties) === null || _a === void 0 ? void 0 : _a[tagName]; - if (typeof propSch != "object") throw new Error(`discriminator: oneOf subschemas (or referenced schemas) must have "properties/${tagName}"`); - tagRequired = tagRequired && (topRequired || hasRequired(sch)); - addMappings(propSch, i); - } - if (!tagRequired) throw new Error(`discriminator: "${tagName}" must be required`); - return oneOfMapping; - function hasRequired({ required }) { - return Array.isArray(required) && required.includes(tagName); - } - function addMappings(sch, i) { - if (sch.const) addMapping(sch.const, i); - else if (sch.enum) for (const tagValue of sch.enum) addMapping(tagValue, i); - else throw new Error(`discriminator: "properties/${tagName}" must have "const" or "enum"`); - } - function addMapping(tagValue, i) { - if (typeof tagValue != "string" || tagValue in oneOfMapping) throw new Error(`discriminator: "${tagName}" values must be unique strings`); - oneOfMapping[tagValue] = i; - } - } - } - }; - exports.default = def; -})); - -//#endregion -//#region ../../node_modules/.pnpm/ajv@8.18.0/node_modules/ajv/dist/refs/json-schema-draft-07.json -var require_json_schema_draft_07 = /* @__PURE__ */ __commonJSMin(((exports, module) => { - module.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": true, - "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": true, - "readOnly": { - "type": "boolean", - "default": false - }, - "examples": { - "type": "array", - "items": true - }, - "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": true - }, - "maxItems": { "$ref": "#/definitions/nonNegativeInteger" }, - "minItems": { "$ref": "#/definitions/nonNegativeIntegerDefault0" }, - "uniqueItems": { - "type": "boolean", - "default": false - }, - "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": true, - "enum": { - "type": "array", - "items": true, - "minItems": 1, - "uniqueItems": true - }, - "type": { "anyOf": [{ "$ref": "#/definitions/simpleTypes" }, { - "type": "array", - "items": { "$ref": "#/definitions/simpleTypes" }, - "minItems": 1, - "uniqueItems": true - }] }, - "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": true - }; -})); - -//#endregion -//#region ../../node_modules/.pnpm/ajv@8.18.0/node_modules/ajv/dist/ajv.js -var require_ajv = /* @__PURE__ */ __commonJSMin(((exports, module) => { - Object.defineProperty(exports, "__esModule", { value: true }); - exports.MissingRefError = exports.ValidationError = exports.CodeGen = exports.Name = exports.nil = exports.stringify = exports.str = exports._ = exports.KeywordCxt = exports.Ajv = void 0; - const core_1 = require_core$3(); - const draft7_1 = require_draft7(); - const discriminator_1 = require_discriminator(); - const draft7MetaSchema = require_json_schema_draft_07(); - const META_SUPPORT_DATA = ["/properties"]; - const META_SCHEMA_ID = "http://json-schema.org/draft-07/schema"; - var Ajv = class extends core_1.default { - _addVocabularies() { - super._addVocabularies(); - draft7_1.default.forEach((v) => this.addVocabulary(v)); - if (this.opts.discriminator) this.addKeyword(discriminator_1.default); - } - _addDefaultMetaSchema() { - super._addDefaultMetaSchema(); - if (!this.opts.meta) return; - const metaSchema = this.opts.$data ? this.$dataMetaSchema(draft7MetaSchema, META_SUPPORT_DATA) : draft7MetaSchema; - this.addMetaSchema(metaSchema, META_SCHEMA_ID, false); - this.refs["http://json-schema.org/schema"] = META_SCHEMA_ID; - } - defaultMeta() { - return this.opts.defaultMeta = super.defaultMeta() || (this.getSchema(META_SCHEMA_ID) ? META_SCHEMA_ID : void 0); - } - }; - exports.Ajv = Ajv; - module.exports = exports = Ajv; - module.exports.Ajv = Ajv; - Object.defineProperty(exports, "__esModule", { value: true }); - exports.default = Ajv; - var validate_1 = require_validate(); - Object.defineProperty(exports, "KeywordCxt", { - enumerable: true, - get: function() { - return validate_1.KeywordCxt; - } - }); - var codegen_1 = require_codegen(); - Object.defineProperty(exports, "_", { - enumerable: true, - get: function() { - return codegen_1._; - } - }); - Object.defineProperty(exports, "str", { - enumerable: true, - get: function() { - return codegen_1.str; - } - }); - Object.defineProperty(exports, "stringify", { - enumerable: true, - get: function() { - return codegen_1.stringify; - } - }); - Object.defineProperty(exports, "nil", { - enumerable: true, - get: function() { - return codegen_1.nil; - } - }); - Object.defineProperty(exports, "Name", { - enumerable: true, - get: function() { - return codegen_1.Name; - } - }); - Object.defineProperty(exports, "CodeGen", { - enumerable: true, - get: function() { - return codegen_1.CodeGen; - } - }); - var validation_error_1 = require_validation_error(); - Object.defineProperty(exports, "ValidationError", { - enumerable: true, - get: function() { - return validation_error_1.default; - } - }); - var ref_error_1 = require_ref_error(); - Object.defineProperty(exports, "MissingRefError", { - enumerable: true, - get: function() { - return ref_error_1.default; - } - }); -})); - -//#endregion -//#region ../../node_modules/.pnpm/ajv@8.18.0/node_modules/ajv/dist/vocabularies/dynamic/dynamicAnchor.js -var require_dynamicAnchor = /* @__PURE__ */ __commonJSMin(((exports) => { - Object.defineProperty(exports, "__esModule", { value: true }); - exports.dynamicAnchor = void 0; - const codegen_1 = require_codegen(); - const names_1 = require_names(); - const compile_1 = require_compile(); - const ref_1 = require_ref(); - const def = { - keyword: "$dynamicAnchor", - schemaType: "string", - code: (cxt) => dynamicAnchor(cxt, cxt.schema) - }; - function dynamicAnchor(cxt, anchor) { - const { gen, it } = cxt; - it.schemaEnv.root.dynamicAnchors[anchor] = true; - const v = (0, codegen_1._)`${names_1.default.dynamicAnchors}${(0, codegen_1.getProperty)(anchor)}`; - const validate = it.errSchemaPath === "#" ? it.validateName : _getValidate(cxt); - gen.if((0, codegen_1._)`!${v}`, () => gen.assign(v, validate)); - } - exports.dynamicAnchor = dynamicAnchor; - function _getValidate(cxt) { - const { schemaEnv, schema, self } = cxt.it; - const { root, baseId, localRefs, meta } = schemaEnv.root; - const { schemaId } = self.opts; - const sch = new compile_1.SchemaEnv({ - schema, - schemaId, - root, - baseId, - localRefs, - meta - }); - compile_1.compileSchema.call(self, sch); - return (0, ref_1.getValidate)(cxt, sch); - } - exports.default = def; -})); - -//#endregion -//#region ../../node_modules/.pnpm/ajv@8.18.0/node_modules/ajv/dist/vocabularies/dynamic/dynamicRef.js -var require_dynamicRef = /* @__PURE__ */ __commonJSMin(((exports) => { - Object.defineProperty(exports, "__esModule", { value: true }); - exports.dynamicRef = void 0; - const codegen_1 = require_codegen(); - const names_1 = require_names(); - const ref_1 = require_ref(); - const def = { - keyword: "$dynamicRef", - schemaType: "string", - code: (cxt) => dynamicRef(cxt, cxt.schema) - }; - function dynamicRef(cxt, ref) { - const { gen, keyword, it } = cxt; - if (ref[0] !== "#") throw new Error(`"${keyword}" only supports hash fragment reference`); - const anchor = ref.slice(1); - if (it.allErrors) _dynamicRef(); - else { - const valid = gen.let("valid", false); - _dynamicRef(valid); - cxt.ok(valid); - } - function _dynamicRef(valid) { - if (it.schemaEnv.root.dynamicAnchors[anchor]) { - const v = gen.let("_v", (0, codegen_1._)`${names_1.default.dynamicAnchors}${(0, codegen_1.getProperty)(anchor)}`); - gen.if(v, _callRef(v, valid), _callRef(it.validateName, valid)); - } else _callRef(it.validateName, valid)(); - } - function _callRef(validate, valid) { - return valid ? () => gen.block(() => { - (0, ref_1.callRef)(cxt, validate); - gen.let(valid, true); - }) : () => (0, ref_1.callRef)(cxt, validate); - } - } - exports.dynamicRef = dynamicRef; - exports.default = def; -})); - -//#endregion -//#region ../../node_modules/.pnpm/ajv@8.18.0/node_modules/ajv/dist/vocabularies/dynamic/recursiveAnchor.js -var require_recursiveAnchor = /* @__PURE__ */ __commonJSMin(((exports) => { - Object.defineProperty(exports, "__esModule", { value: true }); - const dynamicAnchor_1 = require_dynamicAnchor(); - const util_1 = require_util(); - const def = { - keyword: "$recursiveAnchor", - schemaType: "boolean", - code(cxt) { - if (cxt.schema) (0, dynamicAnchor_1.dynamicAnchor)(cxt, ""); - else (0, util_1.checkStrictMode)(cxt.it, "$recursiveAnchor: false is ignored"); - } - }; - exports.default = def; -})); - -//#endregion -//#region ../../node_modules/.pnpm/ajv@8.18.0/node_modules/ajv/dist/vocabularies/dynamic/recursiveRef.js -var require_recursiveRef = /* @__PURE__ */ __commonJSMin(((exports) => { - Object.defineProperty(exports, "__esModule", { value: true }); - const dynamicRef_1 = require_dynamicRef(); - const def = { - keyword: "$recursiveRef", - schemaType: "string", - code: (cxt) => (0, dynamicRef_1.dynamicRef)(cxt, cxt.schema) - }; - exports.default = def; -})); - -//#endregion -//#region ../../node_modules/.pnpm/ajv@8.18.0/node_modules/ajv/dist/vocabularies/dynamic/index.js -var require_dynamic = /* @__PURE__ */ __commonJSMin(((exports) => { - Object.defineProperty(exports, "__esModule", { value: true }); - const dynamicAnchor_1 = require_dynamicAnchor(); - const dynamicRef_1 = require_dynamicRef(); - const recursiveAnchor_1 = require_recursiveAnchor(); - const recursiveRef_1 = require_recursiveRef(); - const dynamic = [ - dynamicAnchor_1.default, - dynamicRef_1.default, - recursiveAnchor_1.default, - recursiveRef_1.default - ]; - exports.default = dynamic; -})); - -//#endregion -//#region ../../node_modules/.pnpm/ajv@8.18.0/node_modules/ajv/dist/vocabularies/validation/dependentRequired.js -var require_dependentRequired = /* @__PURE__ */ __commonJSMin(((exports) => { - Object.defineProperty(exports, "__esModule", { value: true }); - const dependencies_1 = require_dependencies(); - const def = { - keyword: "dependentRequired", - type: "object", - schemaType: "object", - error: dependencies_1.error, - code: (cxt) => (0, dependencies_1.validatePropertyDeps)(cxt) - }; - exports.default = def; -})); - -//#endregion -//#region ../../node_modules/.pnpm/ajv@8.18.0/node_modules/ajv/dist/vocabularies/applicator/dependentSchemas.js -var require_dependentSchemas = /* @__PURE__ */ __commonJSMin(((exports) => { - Object.defineProperty(exports, "__esModule", { value: true }); - const dependencies_1 = require_dependencies(); - const def = { - keyword: "dependentSchemas", - type: "object", - schemaType: "object", - code: (cxt) => (0, dependencies_1.validateSchemaDeps)(cxt) - }; - exports.default = def; -})); - -//#endregion -//#region ../../node_modules/.pnpm/ajv@8.18.0/node_modules/ajv/dist/vocabularies/validation/limitContains.js -var require_limitContains = /* @__PURE__ */ __commonJSMin(((exports) => { - Object.defineProperty(exports, "__esModule", { value: true }); - const util_1 = require_util(); - const def = { - keyword: ["maxContains", "minContains"], - type: "array", - schemaType: "number", - code({ keyword, parentSchema, it }) { - if (parentSchema.contains === void 0) (0, util_1.checkStrictMode)(it, `"${keyword}" without "contains" is ignored`); - } - }; - exports.default = def; -})); - -//#endregion -//#region ../../node_modules/.pnpm/ajv@8.18.0/node_modules/ajv/dist/vocabularies/next.js -var require_next = /* @__PURE__ */ __commonJSMin(((exports) => { - Object.defineProperty(exports, "__esModule", { value: true }); - const dependentRequired_1 = require_dependentRequired(); - const dependentSchemas_1 = require_dependentSchemas(); - const limitContains_1 = require_limitContains(); - const next = [ - dependentRequired_1.default, - dependentSchemas_1.default, - limitContains_1.default - ]; - exports.default = next; -})); - -//#endregion -//#region ../../node_modules/.pnpm/ajv@8.18.0/node_modules/ajv/dist/vocabularies/unevaluated/unevaluatedProperties.js -var require_unevaluatedProperties = /* @__PURE__ */ __commonJSMin(((exports) => { - Object.defineProperty(exports, "__esModule", { value: true }); - const codegen_1 = require_codegen(); - const util_1 = require_util(); - const names_1 = require_names(); - const def = { - keyword: "unevaluatedProperties", - type: "object", - schemaType: ["boolean", "object"], - trackErrors: true, - error: { - message: "must NOT have unevaluated properties", - params: ({ params }) => (0, codegen_1._)`{unevaluatedProperty: ${params.unevaluatedProperty}}` - }, - code(cxt) { - const { gen, schema, data, errsCount, it } = cxt; - /* istanbul ignore if */ - if (!errsCount) throw new Error("ajv implementation error"); - const { allErrors, props } = it; - if (props instanceof codegen_1.Name) gen.if((0, codegen_1._)`${props} !== true`, () => gen.forIn("key", data, (key) => gen.if(unevaluatedDynamic(props, key), () => unevaluatedPropCode(key)))); - else if (props !== true) gen.forIn("key", data, (key) => props === void 0 ? unevaluatedPropCode(key) : gen.if(unevaluatedStatic(props, key), () => unevaluatedPropCode(key))); - it.props = true; - cxt.ok((0, codegen_1._)`${errsCount} === ${names_1.default.errors}`); - function unevaluatedPropCode(key) { - if (schema === false) { - cxt.setParams({ unevaluatedProperty: key }); - cxt.error(); - if (!allErrors) gen.break(); - return; - } - if (!(0, util_1.alwaysValidSchema)(it, schema)) { - const valid = gen.name("valid"); - cxt.subschema({ - keyword: "unevaluatedProperties", - dataProp: key, - dataPropType: util_1.Type.Str - }, valid); - if (!allErrors) gen.if((0, codegen_1.not)(valid), () => gen.break()); - } - } - function unevaluatedDynamic(evaluatedProps, key) { - return (0, codegen_1._)`!${evaluatedProps} || !${evaluatedProps}[${key}]`; - } - function unevaluatedStatic(evaluatedProps, key) { - const ps = []; - for (const p in evaluatedProps) if (evaluatedProps[p] === true) ps.push((0, codegen_1._)`${key} !== ${p}`); - return (0, codegen_1.and)(...ps); - } - } - }; - exports.default = def; -})); - -//#endregion -//#region ../../node_modules/.pnpm/ajv@8.18.0/node_modules/ajv/dist/vocabularies/unevaluated/unevaluatedItems.js -var require_unevaluatedItems = /* @__PURE__ */ __commonJSMin(((exports) => { - Object.defineProperty(exports, "__esModule", { value: true }); - const codegen_1 = require_codegen(); - const util_1 = require_util(); - const def = { - keyword: "unevaluatedItems", - type: "array", - schemaType: ["boolean", "object"], - error: { - message: ({ params: { len } }) => (0, codegen_1.str)`must NOT have more than ${len} items`, - params: ({ params: { len } }) => (0, codegen_1._)`{limit: ${len}}` - }, - code(cxt) { - const { gen, schema, data, it } = cxt; - const items = it.items || 0; - if (items === true) return; - const len = gen.const("len", (0, codegen_1._)`${data}.length`); - if (schema === false) { - cxt.setParams({ len: items }); - cxt.fail((0, codegen_1._)`${len} > ${items}`); - } else if (typeof schema == "object" && !(0, util_1.alwaysValidSchema)(it, schema)) { - const valid = gen.var("valid", (0, codegen_1._)`${len} <= ${items}`); - gen.if((0, codegen_1.not)(valid), () => validateItems(valid, items)); - cxt.ok(valid); - } - it.items = true; - function validateItems(valid, from) { - gen.forRange("i", from, len, (i) => { - cxt.subschema({ - keyword: "unevaluatedItems", - dataProp: i, - dataPropType: util_1.Type.Num - }, valid); - if (!it.allErrors) gen.if((0, codegen_1.not)(valid), () => gen.break()); - }); - } - } - }; - exports.default = def; -})); - -//#endregion -//#region ../../node_modules/.pnpm/ajv@8.18.0/node_modules/ajv/dist/vocabularies/unevaluated/index.js -var require_unevaluated$1 = /* @__PURE__ */ __commonJSMin(((exports) => { - Object.defineProperty(exports, "__esModule", { value: true }); - const unevaluatedProperties_1 = require_unevaluatedProperties(); - const unevaluatedItems_1 = require_unevaluatedItems(); - const unevaluated = [unevaluatedProperties_1.default, unevaluatedItems_1.default]; - exports.default = unevaluated; -})); - -//#endregion -//#region ../../node_modules/.pnpm/ajv@8.18.0/node_modules/ajv/dist/refs/json-schema-2019-09/schema.json -var require_schema$1 = /* @__PURE__ */ __commonJSMin(((exports, module) => { - module.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": true, - "https://json-schema.org/draft/2019-09/vocab/applicator": true, - "https://json-schema.org/draft/2019-09/vocab/validation": true, - "https://json-schema.org/draft/2019-09/vocab/meta-data": true, - "https://json-schema.org/draft/2019-09/vocab/format": false, - "https://json-schema.org/draft/2019-09/vocab/content": true - }, - "$recursiveAnchor": true, - "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" }] } - } - } - }; -})); - -//#endregion -//#region ../../node_modules/.pnpm/ajv@8.18.0/node_modules/ajv/dist/refs/json-schema-2019-09/meta/applicator.json -var require_applicator$1 = /* @__PURE__ */ __commonJSMin(((exports, module) => { - module.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": true }, - "$recursiveAnchor": true, - "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": "#" } - } } - }; -})); - -//#endregion -//#region ../../node_modules/.pnpm/ajv@8.18.0/node_modules/ajv/dist/refs/json-schema-2019-09/meta/content.json -var require_content$1 = /* @__PURE__ */ __commonJSMin(((exports, module) => { - module.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": true }, - "$recursiveAnchor": true, - "title": "Content vocabulary meta-schema", - "type": ["object", "boolean"], - "properties": { - "contentMediaType": { "type": "string" }, - "contentEncoding": { "type": "string" }, - "contentSchema": { "$recursiveRef": "#" } - } - }; -})); - -//#endregion -//#region ../../node_modules/.pnpm/ajv@8.18.0/node_modules/ajv/dist/refs/json-schema-2019-09/meta/core.json -var require_core$1 = /* @__PURE__ */ __commonJSMin(((exports, module) => { - module.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": true }, - "$recursiveAnchor": true, - "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": false - }, - "$vocabulary": { - "type": "object", - "propertyNames": { - "type": "string", - "format": "uri" - }, - "additionalProperties": { "type": "boolean" } - }, - "$comment": { "type": "string" }, - "$defs": { - "type": "object", - "additionalProperties": { "$recursiveRef": "#" }, - "default": {} - } - } - }; -})); - -//#endregion -//#region ../../node_modules/.pnpm/ajv@8.18.0/node_modules/ajv/dist/refs/json-schema-2019-09/meta/format.json -var require_format = /* @__PURE__ */ __commonJSMin(((exports, module) => { - module.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": true }, - "$recursiveAnchor": true, - "title": "Format vocabulary meta-schema", - "type": ["object", "boolean"], - "properties": { "format": { "type": "string" } } - }; -})); - -//#endregion -//#region ../../node_modules/.pnpm/ajv@8.18.0/node_modules/ajv/dist/refs/json-schema-2019-09/meta/meta-data.json -var require_meta_data$1 = /* @__PURE__ */ __commonJSMin(((exports, module) => { - module.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": true }, - "$recursiveAnchor": true, - "title": "Meta-data vocabulary meta-schema", - "type": ["object", "boolean"], - "properties": { - "title": { "type": "string" }, - "description": { "type": "string" }, - "default": true, - "deprecated": { - "type": "boolean", - "default": false - }, - "readOnly": { - "type": "boolean", - "default": false - }, - "writeOnly": { - "type": "boolean", - "default": false - }, - "examples": { - "type": "array", - "items": true - } - } - }; -})); - -//#endregion -//#region ../../node_modules/.pnpm/ajv@8.18.0/node_modules/ajv/dist/refs/json-schema-2019-09/meta/validation.json -var require_validation$1 = /* @__PURE__ */ __commonJSMin(((exports, module) => { - module.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": true }, - "$recursiveAnchor": true, - "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": false - }, - "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": true, - "enum": { - "type": "array", - "items": true - }, - "type": { "anyOf": [{ "$ref": "#/$defs/simpleTypes" }, { - "type": "array", - "items": { "$ref": "#/$defs/simpleTypes" }, - "minItems": 1, - "uniqueItems": true - }] } - }, - "$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": true, - "default": [] - } - } - }; -})); - -//#endregion -//#region ../../node_modules/.pnpm/ajv@8.18.0/node_modules/ajv/dist/refs/json-schema-2019-09/index.js -var require_json_schema_2019_09 = /* @__PURE__ */ __commonJSMin(((exports) => { - Object.defineProperty(exports, "__esModule", { value: true }); - const metaSchema = require_schema$1(); - const applicator = require_applicator$1(); - const content = require_content$1(); - const core = require_core$1(); - const format = require_format(); - const metadata = require_meta_data$1(); - const validation = require_validation$1(); - const META_SUPPORT_DATA = ["/properties"]; - function addMetaSchema2019($data) { - [ - metaSchema, - applicator, - content, - core, - with$data(this, format), - metadata, - with$data(this, validation) - ].forEach((sch) => this.addMetaSchema(sch, void 0, false)); - return this; - function with$data(ajv, sch) { - return $data ? ajv.$dataMetaSchema(sch, META_SUPPORT_DATA) : sch; - } - } - exports.default = addMetaSchema2019; -})); - -//#endregion -//#region ../../node_modules/.pnpm/ajv@8.18.0/node_modules/ajv/dist/2019.js -var require__2019 = /* @__PURE__ */ __commonJSMin(((exports, module) => { - Object.defineProperty(exports, "__esModule", { value: true }); - exports.MissingRefError = exports.ValidationError = exports.CodeGen = exports.Name = exports.nil = exports.stringify = exports.str = exports._ = exports.KeywordCxt = exports.Ajv2019 = void 0; - const core_1 = require_core$3(); - const draft7_1 = require_draft7(); - const dynamic_1 = require_dynamic(); - const next_1 = require_next(); - const unevaluated_1 = require_unevaluated$1(); - const discriminator_1 = require_discriminator(); - const json_schema_2019_09_1 = require_json_schema_2019_09(); - const META_SCHEMA_ID = "https://json-schema.org/draft/2019-09/schema"; - var Ajv2019 = class extends core_1.default { - constructor(opts = {}) { - super({ - ...opts, - dynamicRef: true, - next: true, - unevaluated: true - }); - } - _addVocabularies() { - super._addVocabularies(); - this.addVocabulary(dynamic_1.default); - draft7_1.default.forEach((v) => this.addVocabulary(v)); - this.addVocabulary(next_1.default); - this.addVocabulary(unevaluated_1.default); - if (this.opts.discriminator) this.addKeyword(discriminator_1.default); - } - _addDefaultMetaSchema() { - super._addDefaultMetaSchema(); - const { $data, meta } = this.opts; - if (!meta) return; - json_schema_2019_09_1.default.call(this, $data); - this.refs["http://json-schema.org/schema"] = META_SCHEMA_ID; - } - defaultMeta() { - return this.opts.defaultMeta = super.defaultMeta() || (this.getSchema(META_SCHEMA_ID) ? META_SCHEMA_ID : void 0); - } - }; - exports.Ajv2019 = Ajv2019; - module.exports = exports = Ajv2019; - module.exports.Ajv2019 = Ajv2019; - Object.defineProperty(exports, "__esModule", { value: true }); - exports.default = Ajv2019; - var validate_1 = require_validate(); - Object.defineProperty(exports, "KeywordCxt", { - enumerable: true, - get: function() { - return validate_1.KeywordCxt; - } - }); - var codegen_1 = require_codegen(); - Object.defineProperty(exports, "_", { - enumerable: true, - get: function() { - return codegen_1._; - } - }); - Object.defineProperty(exports, "str", { - enumerable: true, - get: function() { - return codegen_1.str; - } - }); - Object.defineProperty(exports, "stringify", { - enumerable: true, - get: function() { - return codegen_1.stringify; - } - }); - Object.defineProperty(exports, "nil", { - enumerable: true, - get: function() { - return codegen_1.nil; - } - }); - Object.defineProperty(exports, "Name", { - enumerable: true, - get: function() { - return codegen_1.Name; - } - }); - Object.defineProperty(exports, "CodeGen", { - enumerable: true, - get: function() { - return codegen_1.CodeGen; - } - }); - var validation_error_1 = require_validation_error(); - Object.defineProperty(exports, "ValidationError", { - enumerable: true, - get: function() { - return validation_error_1.default; - } - }); - var ref_error_1 = require_ref_error(); - Object.defineProperty(exports, "MissingRefError", { - enumerable: true, - get: function() { - return ref_error_1.default; - } - }); -})); - -//#endregion -//#region ../../node_modules/.pnpm/ajv@8.18.0/node_modules/ajv/dist/vocabularies/draft2020.js -var require_draft2020 = /* @__PURE__ */ __commonJSMin(((exports) => { - Object.defineProperty(exports, "__esModule", { value: true }); - const core_1 = require_core$2(); - const validation_1 = require_validation$2(); - const applicator_1 = require_applicator$2(); - const dynamic_1 = require_dynamic(); - const next_1 = require_next(); - const unevaluated_1 = require_unevaluated$1(); - const format_1 = require_format$1(); - const metadata_1 = require_metadata(); - const draft2020Vocabularies = [ - dynamic_1.default, - core_1.default, - validation_1.default, - (0, applicator_1.default)(true), - format_1.default, - metadata_1.metadataVocabulary, - metadata_1.contentVocabulary, - next_1.default, - unevaluated_1.default - ]; - exports.default = draft2020Vocabularies; -})); - -//#endregion -//#region ../../node_modules/.pnpm/ajv@8.18.0/node_modules/ajv/dist/refs/json-schema-2020-12/schema.json -var require_schema = /* @__PURE__ */ __commonJSMin(((exports, module) => { - module.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": true, - "https://json-schema.org/draft/2020-12/vocab/applicator": true, - "https://json-schema.org/draft/2020-12/vocab/unevaluated": true, - "https://json-schema.org/draft/2020-12/vocab/validation": true, - "https://json-schema.org/draft/2020-12/vocab/meta-data": true, - "https://json-schema.org/draft/2020-12/vocab/format-annotation": true, - "https://json-schema.org/draft/2020-12/vocab/content": true - }, - "$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": true, - "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": true, - "default": {} - }, - "$recursiveAnchor": { - "$comment": "\"$recursiveAnchor\" has been replaced by \"$dynamicAnchor\".", - "$ref": "meta/core#/$defs/anchorString", - "deprecated": true - }, - "$recursiveRef": { - "$comment": "\"$recursiveRef\" has been replaced by \"$dynamicRef\".", - "$ref": "meta/core#/$defs/uriReferenceString", - "deprecated": true - } - } - }; -})); - -//#endregion -//#region ../../node_modules/.pnpm/ajv@8.18.0/node_modules/ajv/dist/refs/json-schema-2020-12/meta/applicator.json -var require_applicator = /* @__PURE__ */ __commonJSMin(((exports, module) => { - module.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": true }, - "$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" } - } } - }; -})); - -//#endregion -//#region ../../node_modules/.pnpm/ajv@8.18.0/node_modules/ajv/dist/refs/json-schema-2020-12/meta/unevaluated.json -var require_unevaluated = /* @__PURE__ */ __commonJSMin(((exports, module) => { - module.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": true }, - "$dynamicAnchor": "meta", - "title": "Unevaluated applicator vocabulary meta-schema", - "type": ["object", "boolean"], - "properties": { - "unevaluatedItems": { "$dynamicRef": "#meta" }, - "unevaluatedProperties": { "$dynamicRef": "#meta" } - } - }; -})); - -//#endregion -//#region ../../node_modules/.pnpm/ajv@8.18.0/node_modules/ajv/dist/refs/json-schema-2020-12/meta/content.json -var require_content = /* @__PURE__ */ __commonJSMin(((exports, module) => { - module.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": true }, - "$dynamicAnchor": "meta", - "title": "Content vocabulary meta-schema", - "type": ["object", "boolean"], - "properties": { - "contentEncoding": { "type": "string" }, - "contentMediaType": { "type": "string" }, - "contentSchema": { "$dynamicRef": "#meta" } - } - }; -})); - -//#endregion -//#region ../../node_modules/.pnpm/ajv@8.18.0/node_modules/ajv/dist/refs/json-schema-2020-12/meta/core.json -var require_core = /* @__PURE__ */ __commonJSMin(((exports, module) => { - module.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": true }, - "$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" - } - } - }; -})); - -//#endregion -//#region ../../node_modules/.pnpm/ajv@8.18.0/node_modules/ajv/dist/refs/json-schema-2020-12/meta/format-annotation.json -var require_format_annotation = /* @__PURE__ */ __commonJSMin(((exports, module) => { - module.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": true }, - "$dynamicAnchor": "meta", - "title": "Format vocabulary meta-schema for annotation results", - "type": ["object", "boolean"], - "properties": { "format": { "type": "string" } } - }; -})); - -//#endregion -//#region ../../node_modules/.pnpm/ajv@8.18.0/node_modules/ajv/dist/refs/json-schema-2020-12/meta/meta-data.json -var require_meta_data = /* @__PURE__ */ __commonJSMin(((exports, module) => { - module.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": true }, - "$dynamicAnchor": "meta", - "title": "Meta-data vocabulary meta-schema", - "type": ["object", "boolean"], - "properties": { - "title": { "type": "string" }, - "description": { "type": "string" }, - "default": true, - "deprecated": { - "type": "boolean", - "default": false - }, - "readOnly": { - "type": "boolean", - "default": false - }, - "writeOnly": { - "type": "boolean", - "default": false - }, - "examples": { - "type": "array", - "items": true - } - } - }; -})); - -//#endregion -//#region ../../node_modules/.pnpm/ajv@8.18.0/node_modules/ajv/dist/refs/json-schema-2020-12/meta/validation.json -var require_validation = /* @__PURE__ */ __commonJSMin(((exports, module) => { - module.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": true }, - "$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": true - }] }, - "const": true, - "enum": { - "type": "array", - "items": true - }, - "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": false - }, - "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": true, - "default": [] - } - } - }; -})); - -//#endregion -//#region ../../node_modules/.pnpm/ajv@8.18.0/node_modules/ajv/dist/refs/json-schema-2020-12/index.js -var require_json_schema_2020_12 = /* @__PURE__ */ __commonJSMin(((exports) => { - Object.defineProperty(exports, "__esModule", { value: true }); - const metaSchema = require_schema(); - const applicator = require_applicator(); - const unevaluated = require_unevaluated(); - const content = require_content(); - const core = require_core(); - const format = require_format_annotation(); - const metadata = require_meta_data(); - const validation = require_validation(); - const META_SUPPORT_DATA = ["/properties"]; - function addMetaSchema2020($data) { - [ - metaSchema, - applicator, - unevaluated, - content, - core, - with$data(this, format), - metadata, - with$data(this, validation) - ].forEach((sch) => this.addMetaSchema(sch, void 0, false)); - return this; - function with$data(ajv, sch) { - return $data ? ajv.$dataMetaSchema(sch, META_SUPPORT_DATA) : sch; - } - } - exports.default = addMetaSchema2020; -})); - -//#endregion -//#region ../../node_modules/.pnpm/ajv@8.18.0/node_modules/ajv/dist/2020.js -var require__2020 = /* @__PURE__ */ __commonJSMin(((exports, module) => { - Object.defineProperty(exports, "__esModule", { value: true }); - exports.MissingRefError = exports.ValidationError = exports.CodeGen = exports.Name = exports.nil = exports.stringify = exports.str = exports._ = exports.KeywordCxt = exports.Ajv2020 = void 0; - const core_1 = require_core$3(); - const draft2020_1 = require_draft2020(); - const discriminator_1 = require_discriminator(); - const json_schema_2020_12_1 = require_json_schema_2020_12(); - const META_SCHEMA_ID = "https://json-schema.org/draft/2020-12/schema"; - var Ajv2020 = class extends core_1.default { - constructor(opts = {}) { - super({ - ...opts, - dynamicRef: true, - next: true, - unevaluated: true - }); - } - _addVocabularies() { - super._addVocabularies(); - draft2020_1.default.forEach((v) => this.addVocabulary(v)); - if (this.opts.discriminator) this.addKeyword(discriminator_1.default); - } - _addDefaultMetaSchema() { - super._addDefaultMetaSchema(); - const { $data, meta } = this.opts; - if (!meta) return; - json_schema_2020_12_1.default.call(this, $data); - this.refs["http://json-schema.org/schema"] = META_SCHEMA_ID; - } - defaultMeta() { - return this.opts.defaultMeta = super.defaultMeta() || (this.getSchema(META_SCHEMA_ID) ? META_SCHEMA_ID : void 0); - } - }; - exports.Ajv2020 = Ajv2020; - module.exports = exports = Ajv2020; - module.exports.Ajv2020 = Ajv2020; - Object.defineProperty(exports, "__esModule", { value: true }); - exports.default = Ajv2020; - var validate_1 = require_validate(); - Object.defineProperty(exports, "KeywordCxt", { - enumerable: true, - get: function() { - return validate_1.KeywordCxt; - } - }); - var codegen_1 = require_codegen(); - Object.defineProperty(exports, "_", { - enumerable: true, - get: function() { - return codegen_1._; - } - }); - Object.defineProperty(exports, "str", { - enumerable: true, - get: function() { - return codegen_1.str; - } - }); - Object.defineProperty(exports, "stringify", { - enumerable: true, - get: function() { - return codegen_1.stringify; - } - }); - Object.defineProperty(exports, "nil", { - enumerable: true, - get: function() { - return codegen_1.nil; - } - }); - Object.defineProperty(exports, "Name", { - enumerable: true, - get: function() { - return codegen_1.Name; - } - }); - Object.defineProperty(exports, "CodeGen", { - enumerable: true, - get: function() { - return codegen_1.CodeGen; - } - }); - var validation_error_1 = require_validation_error(); - Object.defineProperty(exports, "ValidationError", { - enumerable: true, - get: function() { - return validation_error_1.default; - } - }); - var ref_error_1 = require_ref_error(); - Object.defineProperty(exports, "MissingRefError", { - enumerable: true, - get: function() { - return ref_error_1.default; - } - }); -})); - -//#endregion -//#region ../../node_modules/.pnpm/ajv-formats@3.0.1_ajv@8.18.0/node_modules/ajv-formats/dist/formats.js -var require_formats = /* @__PURE__ */ __commonJSMin(((exports) => { - Object.defineProperty(exports, "__esModule", { value: true }); - exports.formatNames = exports.fastFormats = exports.fullFormats = void 0; - function fmtDef(validate, compare) { - return { - validate, - compare - }; - } - exports.fullFormats = { - date: fmtDef(date, compareDate), - time: fmtDef(getTime(true), compareTime), - "date-time": fmtDef(getDateTime(true), compareDateTime), - "iso-time": fmtDef(getTime(), compareIsoTime), - "iso-date-time": fmtDef(getDateTime(), compareIsoDateTime), - duration: /^P(?!$)((\d+Y)?(\d+M)?(\d+D)?(T(?=\d)(\d+H)?(\d+M)?(\d+S)?)?|(\d+W)?)$/, - uri, - "uri-reference": /^(?:[a-z][a-z0-9+\-.]*:)?(?:\/?\/(?:(?:[a-z0-9\-._~!$&'()*+,;=:]|%[0-9a-f]{2})*@)?(?:\[(?:(?:(?:(?:[0-9a-f]{1,4}:){6}|::(?:[0-9a-f]{1,4}:){5}|(?:[0-9a-f]{1,4})?::(?:[0-9a-f]{1,4}:){4}|(?:(?:[0-9a-f]{1,4}:){0,1}[0-9a-f]{1,4})?::(?:[0-9a-f]{1,4}:){3}|(?:(?:[0-9a-f]{1,4}:){0,2}[0-9a-f]{1,4})?::(?:[0-9a-f]{1,4}:){2}|(?:(?:[0-9a-f]{1,4}:){0,3}[0-9a-f]{1,4})?::[0-9a-f]{1,4}:|(?:(?:[0-9a-f]{1,4}:){0,4}[0-9a-f]{1,4})?::)(?:[0-9a-f]{1,4}:[0-9a-f]{1,4}|(?:(?:25[0-5]|2[0-4]\d|[01]?\d\d?)\.){3}(?:25[0-5]|2[0-4]\d|[01]?\d\d?))|(?:(?:[0-9a-f]{1,4}:){0,5}[0-9a-f]{1,4})?::[0-9a-f]{1,4}|(?:(?:[0-9a-f]{1,4}:){0,6}[0-9a-f]{1,4})?::)|[Vv][0-9a-f]+\.[a-z0-9\-._~!$&'()*+,;=:]+)\]|(?:(?:25[0-5]|2[0-4]\d|[01]?\d\d?)\.){3}(?:25[0-5]|2[0-4]\d|[01]?\d\d?)|(?:[a-z0-9\-._~!$&'"()*+,;=]|%[0-9a-f]{2})*)(?::\d*)?(?:\/(?:[a-z0-9\-._~!$&'"()*+,;=:@]|%[0-9a-f]{2})*)*|\/(?:(?:[a-z0-9\-._~!$&'"()*+,;=:@]|%[0-9a-f]{2})+(?:\/(?:[a-z0-9\-._~!$&'"()*+,;=:@]|%[0-9a-f]{2})*)*)?|(?:[a-z0-9\-._~!$&'"()*+,;=:@]|%[0-9a-f]{2})+(?:\/(?:[a-z0-9\-._~!$&'"()*+,;=:@]|%[0-9a-f]{2})*)*)?(?:\?(?:[a-z0-9\-._~!$&'"()*+,;=:@/?]|%[0-9a-f]{2})*)?(?:#(?:[a-z0-9\-._~!$&'"()*+,;=:@/?]|%[0-9a-f]{2})*)?$/i, - "uri-template": /^(?:(?:[^\x00-\x20"'<>%\\^`{|}]|%[0-9a-f]{2})|\{[+#./;?&=,!@|]?(?:[a-z0-9_]|%[0-9a-f]{2})+(?::[1-9][0-9]{0,3}|\*)?(?:,(?:[a-z0-9_]|%[0-9a-f]{2})+(?::[1-9][0-9]{0,3}|\*)?)*\})*$/i, - url: /^(?:https?|ftp):\/\/(?:\S+(?::\S*)?@)?(?:(?!(?:10|127)(?:\.\d{1,3}){3})(?!(?:169\.254|192\.168)(?:\.\d{1,3}){2})(?!172\.(?:1[6-9]|2\d|3[0-1])(?:\.\d{1,3}){2})(?:[1-9]\d?|1\d\d|2[01]\d|22[0-3])(?:\.(?:1?\d{1,2}|2[0-4]\d|25[0-5])){2}(?:\.(?:[1-9]\d?|1\d\d|2[0-4]\d|25[0-4]))|(?:(?:[a-z0-9\u{00a1}-\u{ffff}]+-)*[a-z0-9\u{00a1}-\u{ffff}]+)(?:\.(?:[a-z0-9\u{00a1}-\u{ffff}]+-)*[a-z0-9\u{00a1}-\u{ffff}]+)*(?:\.(?:[a-z\u{00a1}-\u{ffff}]{2,})))(?::\d{2,5})?(?:\/[^\s]*)?$/iu, - email: /^[a-z0-9!#$%&'*+/=?^_`{|}~-]+(?:\.[a-z0-9!#$%&'*+/=?^_`{|}~-]+)*@(?:[a-z0-9](?:[a-z0-9-]*[a-z0-9])?\.)+[a-z0-9](?:[a-z0-9-]*[a-z0-9])?$/i, - hostname: /^(?=.{1,253}\.?$)[a-z0-9](?:[a-z0-9-]{0,61}[a-z0-9])?(?:\.[a-z0-9](?:[-0-9a-z]{0,61}[0-9a-z])?)*\.?$/i, - ipv4: /^(?:(?:25[0-5]|2[0-4]\d|1\d\d|[1-9]?\d)\.){3}(?:25[0-5]|2[0-4]\d|1\d\d|[1-9]?\d)$/, - ipv6: /^((([0-9a-f]{1,4}:){7}([0-9a-f]{1,4}|:))|(([0-9a-f]{1,4}:){6}(:[0-9a-f]{1,4}|((25[0-5]|2[0-4]\d|1\d\d|[1-9]?\d)(\.(25[0-5]|2[0-4]\d|1\d\d|[1-9]?\d)){3})|:))|(([0-9a-f]{1,4}:){5}(((:[0-9a-f]{1,4}){1,2})|:((25[0-5]|2[0-4]\d|1\d\d|[1-9]?\d)(\.(25[0-5]|2[0-4]\d|1\d\d|[1-9]?\d)){3})|:))|(([0-9a-f]{1,4}:){4}(((:[0-9a-f]{1,4}){1,3})|((:[0-9a-f]{1,4})?:((25[0-5]|2[0-4]\d|1\d\d|[1-9]?\d)(\.(25[0-5]|2[0-4]\d|1\d\d|[1-9]?\d)){3}))|:))|(([0-9a-f]{1,4}:){3}(((:[0-9a-f]{1,4}){1,4})|((:[0-9a-f]{1,4}){0,2}:((25[0-5]|2[0-4]\d|1\d\d|[1-9]?\d)(\.(25[0-5]|2[0-4]\d|1\d\d|[1-9]?\d)){3}))|:))|(([0-9a-f]{1,4}:){2}(((:[0-9a-f]{1,4}){1,5})|((:[0-9a-f]{1,4}){0,3}:((25[0-5]|2[0-4]\d|1\d\d|[1-9]?\d)(\.(25[0-5]|2[0-4]\d|1\d\d|[1-9]?\d)){3}))|:))|(([0-9a-f]{1,4}:){1}(((:[0-9a-f]{1,4}){1,6})|((:[0-9a-f]{1,4}){0,4}:((25[0-5]|2[0-4]\d|1\d\d|[1-9]?\d)(\.(25[0-5]|2[0-4]\d|1\d\d|[1-9]?\d)){3}))|:))|(:(((:[0-9a-f]{1,4}){1,7})|((:[0-9a-f]{1,4}){0,5}:((25[0-5]|2[0-4]\d|1\d\d|[1-9]?\d)(\.(25[0-5]|2[0-4]\d|1\d\d|[1-9]?\d)){3}))|:)))$/i, - regex, - 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, - int32: { - type: "number", - validate: validateInt32 - }, - int64: { - type: "number", - validate: validateInt64 - }, - float: { - type: "number", - validate: validateNumber - }, - double: { - type: "number", - validate: validateNumber - }, - password: true, - binary: true - }; - exports.fastFormats = { - ...exports.fullFormats, - date: fmtDef(/^\d\d\d\d-[0-1]\d-[0-3]\d$/, compareDate), - time: fmtDef(/^(?:[0-2]\d:[0-5]\d:[0-5]\d|23:59:60)(?:\.\d+)?(?:z|[+-]\d\d(?::?\d\d)?)$/i, compareTime), - "date-time": fmtDef(/^\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, compareDateTime), - "iso-time": fmtDef(/^(?:[0-2]\d:[0-5]\d:[0-5]\d|23:59:60)(?:\.\d+)?(?:z|[+-]\d\d(?::?\d\d)?)?$/i, compareIsoTime), - "iso-date-time": fmtDef(/^\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, compareIsoDateTime), - uri: /^(?:[a-z][a-z0-9+\-.]*:)(?:\/?\/)?[^\s]*$/i, - "uri-reference": /^(?:(?:[a-z][a-z0-9+\-.]*:)?\/?\/)?(?:[^\\\s#][^\s#]*)?(?:#[^\\\s]*)?$/i, - email: /^[a-z0-9.!#$%&'*+/=?^_`{|}~-]+@[a-z0-9](?:[a-z0-9-]{0,61}[a-z0-9])?(?:\.[a-z0-9](?:[a-z0-9-]{0,61}[a-z0-9])?)*$/i - }; - exports.formatNames = Object.keys(exports.fullFormats); - function isLeapYear(year) { - return year % 4 === 0 && (year % 100 !== 0 || year % 400 === 0); - } - const DATE = /^(\d\d\d\d)-(\d\d)-(\d\d)$/; - const DAYS = [ - 0, - 31, - 28, - 31, - 30, - 31, - 30, - 31, - 31, - 30, - 31, - 30, - 31 - ]; - function date(str) { - const matches = DATE.exec(str); - if (!matches) return false; - const year = +matches[1]; - const month = +matches[2]; - const day = +matches[3]; - return month >= 1 && month <= 12 && day >= 1 && day <= (month === 2 && isLeapYear(year) ? 29 : DAYS[month]); - } - function compareDate(d1, d2) { - if (!(d1 && d2)) return void 0; - if (d1 > d2) return 1; - if (d1 < d2) return -1; - return 0; - } - const TIME = /^(\d\d):(\d\d):(\d\d(?:\.\d+)?)(z|([+-])(\d\d)(?::?(\d\d))?)?$/i; - function getTime(strictTimeZone) { - return function time(str) { - const matches = TIME.exec(str); - if (!matches) return false; - const hr = +matches[1]; - const min = +matches[2]; - const sec = +matches[3]; - const tz = matches[4]; - const tzSign = matches[5] === "-" ? -1 : 1; - const tzH = +(matches[6] || 0); - const tzM = +(matches[7] || 0); - if (tzH > 23 || tzM > 59 || strictTimeZone && !tz) return false; - if (hr <= 23 && min <= 59 && sec < 60) return true; - const utcMin = min - tzM * tzSign; - const utcHr = hr - tzH * tzSign - (utcMin < 0 ? 1 : 0); - return (utcHr === 23 || utcHr === -1) && (utcMin === 59 || utcMin === -1) && sec < 61; - }; - } - function compareTime(s1, s2) { - if (!(s1 && s2)) return void 0; - const t1 = (/* @__PURE__ */ new Date("2020-01-01T" + s1)).valueOf(); - const t2 = (/* @__PURE__ */ new Date("2020-01-01T" + s2)).valueOf(); - if (!(t1 && t2)) return void 0; - return t1 - t2; - } - function compareIsoTime(t1, t2) { - if (!(t1 && t2)) return void 0; - const a1 = TIME.exec(t1); - const a2 = TIME.exec(t2); - if (!(a1 && a2)) return void 0; - t1 = a1[1] + a1[2] + a1[3]; - t2 = a2[1] + a2[2] + a2[3]; - if (t1 > t2) return 1; - if (t1 < t2) return -1; - return 0; - } - const DATE_TIME_SEPARATOR = /t|\s/i; - function getDateTime(strictTimeZone) { - const time = getTime(strictTimeZone); - return function date_time(str) { - const dateTime = str.split(DATE_TIME_SEPARATOR); - return dateTime.length === 2 && date(dateTime[0]) && time(dateTime[1]); - }; - } - function compareDateTime(dt1, dt2) { - if (!(dt1 && dt2)) return void 0; - const d1 = new Date(dt1).valueOf(); - const d2 = new Date(dt2).valueOf(); - if (!(d1 && d2)) return void 0; - return d1 - d2; - } - function compareIsoDateTime(dt1, dt2) { - if (!(dt1 && dt2)) return void 0; - const [d1, t1] = dt1.split(DATE_TIME_SEPARATOR); - const [d2, t2] = dt2.split(DATE_TIME_SEPARATOR); - const res = compareDate(d1, d2); - if (res === void 0) return void 0; - return res || compareTime(t1, t2); - } - const NOT_URI_FRAGMENT = /\/|:/; - const URI = /^(?:[a-z][a-z0-9+\-.]*:)(?:\/?\/(?:(?:[a-z0-9\-._~!$&'()*+,;=:]|%[0-9a-f]{2})*@)?(?:\[(?:(?:(?:(?:[0-9a-f]{1,4}:){6}|::(?:[0-9a-f]{1,4}:){5}|(?:[0-9a-f]{1,4})?::(?:[0-9a-f]{1,4}:){4}|(?:(?:[0-9a-f]{1,4}:){0,1}[0-9a-f]{1,4})?::(?:[0-9a-f]{1,4}:){3}|(?:(?:[0-9a-f]{1,4}:){0,2}[0-9a-f]{1,4})?::(?:[0-9a-f]{1,4}:){2}|(?:(?:[0-9a-f]{1,4}:){0,3}[0-9a-f]{1,4})?::[0-9a-f]{1,4}:|(?:(?:[0-9a-f]{1,4}:){0,4}[0-9a-f]{1,4})?::)(?:[0-9a-f]{1,4}:[0-9a-f]{1,4}|(?:(?:25[0-5]|2[0-4]\d|[01]?\d\d?)\.){3}(?:25[0-5]|2[0-4]\d|[01]?\d\d?))|(?:(?:[0-9a-f]{1,4}:){0,5}[0-9a-f]{1,4})?::[0-9a-f]{1,4}|(?:(?:[0-9a-f]{1,4}:){0,6}[0-9a-f]{1,4})?::)|[Vv][0-9a-f]+\.[a-z0-9\-._~!$&'()*+,;=:]+)\]|(?:(?:25[0-5]|2[0-4]\d|[01]?\d\d?)\.){3}(?:25[0-5]|2[0-4]\d|[01]?\d\d?)|(?:[a-z0-9\-._~!$&'()*+,;=]|%[0-9a-f]{2})*)(?::\d*)?(?:\/(?:[a-z0-9\-._~!$&'()*+,;=:@]|%[0-9a-f]{2})*)*|\/(?:(?:[a-z0-9\-._~!$&'()*+,;=:@]|%[0-9a-f]{2})+(?:\/(?:[a-z0-9\-._~!$&'()*+,;=:@]|%[0-9a-f]{2})*)*)?|(?:[a-z0-9\-._~!$&'()*+,;=:@]|%[0-9a-f]{2})+(?:\/(?:[a-z0-9\-._~!$&'()*+,;=:@]|%[0-9a-f]{2})*)*)(?:\?(?:[a-z0-9\-._~!$&'()*+,;=:@/?]|%[0-9a-f]{2})*)?(?:#(?:[a-z0-9\-._~!$&'()*+,;=:@/?]|%[0-9a-f]{2})*)?$/i; - function uri(str) { - return NOT_URI_FRAGMENT.test(str) && URI.test(str); - } - const BYTE = /^(?:[A-Za-z0-9+/]{4})*(?:[A-Za-z0-9+/]{2}==|[A-Za-z0-9+/]{3}=)?$/gm; - function byte(str) { - BYTE.lastIndex = 0; - return BYTE.test(str); - } - const MIN_INT32 = -(2 ** 31); - const MAX_INT32 = 2 ** 31 - 1; - function validateInt32(value) { - return Number.isInteger(value) && value <= MAX_INT32 && value >= MIN_INT32; - } - function validateInt64(value) { - return Number.isInteger(value); - } - function validateNumber() { - return true; - } - const Z_ANCHOR = /[^\\]\\Z/; - function regex(str) { - if (Z_ANCHOR.test(str)) return false; - try { - new RegExp(str); - return true; - } catch (e) { - return false; - } - } -})); - -//#endregion -//#region ../../node_modules/.pnpm/ajv-formats@3.0.1_ajv@8.18.0/node_modules/ajv-formats/dist/limit.js -var require_limit = /* @__PURE__ */ __commonJSMin(((exports) => { - Object.defineProperty(exports, "__esModule", { value: true }); - exports.formatLimitDefinition = void 0; - const ajv_1 = require_ajv(); - const codegen_1 = require_codegen(); - const ops = codegen_1.operators; - const KWDs = { - formatMaximum: { - okStr: "<=", - ok: ops.LTE, - fail: ops.GT - }, - formatMinimum: { - okStr: ">=", - ok: ops.GTE, - fail: ops.LT - }, - formatExclusiveMaximum: { - okStr: "<", - ok: ops.LT, - fail: ops.GTE - }, - formatExclusiveMinimum: { - okStr: ">", - ok: ops.GT, - fail: ops.LTE - } - }; - const error = { - message: ({ keyword, schemaCode }) => (0, codegen_1.str)`should be ${KWDs[keyword].okStr} ${schemaCode}`, - params: ({ keyword, schemaCode }) => (0, codegen_1._)`{comparison: ${KWDs[keyword].okStr}, limit: ${schemaCode}}` - }; - exports.formatLimitDefinition = { - keyword: Object.keys(KWDs), - type: "string", - schemaType: "string", - $data: true, - error, - code(cxt) { - const { gen, data, schemaCode, keyword, it } = cxt; - const { opts, self } = it; - if (!opts.validateFormats) return; - const fCxt = new ajv_1.KeywordCxt(it, self.RULES.all.format.definition, "format"); - if (fCxt.$data) validate$DataFormat(); - else validateFormat(); - function validate$DataFormat() { - const fmts = gen.scopeValue("formats", { - ref: self.formats, - code: opts.code.formats - }); - const fmt = gen.const("fmt", (0, codegen_1._)`${fmts}[${fCxt.schemaCode}]`); - cxt.fail$data((0, codegen_1.or)((0, codegen_1._)`typeof ${fmt} != "object"`, (0, codegen_1._)`${fmt} instanceof RegExp`, (0, codegen_1._)`typeof ${fmt}.compare != "function"`, compareCode(fmt))); - } - function validateFormat() { - const format = fCxt.schema; - const fmtDef = self.formats[format]; - if (!fmtDef || fmtDef === true) return; - if (typeof fmtDef != "object" || fmtDef instanceof RegExp || typeof fmtDef.compare != "function") throw new Error(`"${keyword}": format "${format}" does not define "compare" function`); - const fmt = gen.scopeValue("formats", { - key: format, - ref: fmtDef, - code: opts.code.formats ? (0, codegen_1._)`${opts.code.formats}${(0, codegen_1.getProperty)(format)}` : void 0 - }); - cxt.fail$data(compareCode(fmt)); - } - function compareCode(fmt) { - return (0, codegen_1._)`${fmt}.compare(${data}, ${schemaCode}) ${KWDs[keyword].fail} 0`; - } - }, - dependencies: ["format"] - }; - const formatLimitPlugin = (ajv) => { - ajv.addKeyword(exports.formatLimitDefinition); - return ajv; - }; - exports.default = formatLimitPlugin; -})); - -//#endregion -//#region ../../node_modules/.pnpm/ajv-formats@3.0.1_ajv@8.18.0/node_modules/ajv-formats/dist/index.js -var require_dist = /* @__PURE__ */ __commonJSMin(((exports, module) => { - Object.defineProperty(exports, "__esModule", { value: true }); - const formats_1 = require_formats(); - const limit_1 = require_limit(); - const codegen_1 = require_codegen(); - const fullName = new codegen_1.Name("fullFormats"); - const fastName = new codegen_1.Name("fastFormats"); - const formatsPlugin = (ajv, opts = { keywords: true }) => { - if (Array.isArray(opts)) { - addFormats(ajv, opts, formats_1.fullFormats, fullName); - return ajv; - } - const [formats, exportName] = opts.mode === "fast" ? [formats_1.fastFormats, fastName] : [formats_1.fullFormats, fullName]; - addFormats(ajv, opts.formats || formats_1.formatNames, formats, exportName); - if (opts.keywords) (0, limit_1.default)(ajv); - return ajv; - }; - formatsPlugin.get = (name, mode = "full") => { - const f = (mode === "fast" ? formats_1.fastFormats : formats_1.fullFormats)[name]; - if (!f) throw new Error(`Unknown format "${name}"`); - return f; - }; - function addFormats(ajv, list, fs, exportName) { - var _a; - var _b; - (_a = (_b = ajv.opts.code).formats) !== null && _a !== void 0 || (_b.formats = (0, codegen_1._)`require("ajv-formats/dist/formats").${exportName}`); - for (const f of list) ajv.addFormat(f, fs[f]); - } - module.exports = exports = formatsPlugin; - Object.defineProperty(exports, "__esModule", { value: true }); - exports.default = formatsPlugin; -})); - -//#endregion -//#region ../core-internal/src/validators/ajvProvider.ts -var import_ajv = require_ajv(); -var import__2019 = require__2019(); -var import__2020 = require__2020(); -var import_dist = /* @__PURE__ */ __toESM(require_dist(), 1); -/** `ajv-formats` default export, normalised through the CJS/ESM interop wrapper. */ -const ajvProvider_CEoC_sr_addFormats = import_dist.default; -function createDefaultAjvInstance(engineClass) { - const ajv = new engineClass({ - strict: false, - validateFormats: true, - validateSchema: false, - allErrors: true - }); - ajvProvider_CEoC_sr_addFormats(ajv); - return ajv; -} -/** -* AJV-backed JSON Schema validator. See `@modelcontextprotocol/{client,server}/validators/ajv` -* for the customisation entry point (re-exports `Ajv` and `addFormats` from the bundled copy). -* -* Default dispatches on the schema's declared dialect: no `$schema` or 2020-12 → `Ajv2020` -* (SEP-1613); 2019-09 → `Ajv2019`; draft-07 or draft-06 → the classic draft-07 `Ajv` class -* (draft-07's changes over draft-06 are additive, so one engine covers both). Known draft-07 deviation: classic Ajv -* evaluates keywords adjacent to `$ref` (stricter than draft-07's ignore-siblings rule, matching -* v1's default engine), while the cfworker provider ignores them per spec. -* Schemas declaring any other `$schema` are -* rejected with a plain `Error`; pass a pre-configured Ajv instance to validate -* other dialects. The SDK bundles ajv internally but does not re-export `Ajv2020` (its type -* graph tips downstream declaration bundling — see #2339). To construct a custom 2020-12 -* instance, add `ajv` to your own dependencies (matching the SDK's pinned version) and -* `import { Ajv2020 } from 'ajv/dist/2020.js'` — `new Ajv(...)` is the draft-07 class and would -* silently downgrade dialect. -* -* @example Use with default configuration -* ```ts source="./ajvProvider.examples.ts#AjvJsonSchemaValidator_default" -* const validator = new AjvJsonSchemaValidator(); -* ``` -* -* @example Use with a custom AJV instance -* ```ts source="./ajvProvider.examples.ts#AjvJsonSchemaValidator_customInstance" -* // import { Ajv2020 } from 'ajv/dist/2020.js'; -* const ajv = new Ajv2020({ strict: false, validateSchema: false, allErrors: true }); -* const validator = new AjvJsonSchemaValidator(ajv); -* ``` -* -* @example Register ajv-formats -* ```ts source="./ajvProvider.examples.ts#AjvJsonSchemaValidator_withFormats" -* // import { Ajv2020 } from 'ajv/dist/2020.js'; -* const ajv = new Ajv2020({ strict: false, validateSchema: false, allErrors: true }); -* addFormats(ajv); -* const validator = new AjvJsonSchemaValidator(ajv); -* ``` -*/ -var AjvJsonSchemaValidator = class { - _ajv; - /** Lazy classic (draft-07) engine, built on the first draft-07/draft-06-declared schema. */ - _ajvDraft7; - /** Lazy 2019-09 engine, built on the first 2019-09-declared schema. */ - _ajv2019; - /** True iff the constructor received a caller-supplied engine; the `$schema` dispatch is skipped. */ - _userAjv; - /** - * @param ajv - Optional pre-configured AJV-compatible instance. When supplied, this instance is - * used for **every** schema regardless of its declared `$schema` (the caller owns dialect - * choice). When omitted, the provider constructs per-dialect engines (`Ajv2020`, `Ajv2019`, - * and the classic draft-07 `Ajv` for draft-07/06-declared schemas) with - * `strict: false`, `validateFormats: true`, `validateSchema: false`, `allErrors: true`, and - * `ajv-formats` registered — **lazily, on the first {@linkcode getValidator} call needing each**, so - * constructing the provider (e.g. as the default validator of a `Client`/`Server` that never - * validates a JSON Schema) does not pay the ajv + ajv-formats instantiation cost. The parameter - * is typed structurally so consumers who don't pass an instance need not have `ajv` installed. - */ - constructor(ajv) { - this._userAjv = ajv !== void 0; - this._ajv = ajv; - } - /** The underlying 2020-12 engine — the default instance is created on first use. */ - get ajv() { - return this._ajv ??= createDefaultAjvInstance(import__2020.Ajv2020); - } - /** - * Pick the engine for a schema's declared dialect. A caller-supplied engine is used for - * every schema — do not second-guess by `$schema` (bring-your-own-validator means - * bring-your-own-dialect). Otherwise: no `$schema` or 2020-12 → `Ajv2020`; 2019-09 → - * `Ajv2019`; draft-07 or draft-06 → classic `Ajv`; anything else → `Error`. - */ - _engineFor(schema) { - if (this._userAjv) return this.ajv; - const dialect = declaredDialect(schema, "pass a pre-configured Ajv instance to AjvJsonSchemaValidator(ajv) to validate other dialects."); - if (dialect === "2020-12") return this.ajv; - if (dialect === "2019-09") return this._ajv2019 ??= createDefaultAjvInstance(import__2019.Ajv2019); - return this._ajvDraft7 ??= createDefaultAjvInstance(import_ajv.Ajv); - } - getValidator(schema) { - const engine = this._engineFor(schema); - const ajvValidator = "$id" in schema && typeof schema.$id === "string" ? engine.getSchema(schema.$id) ?? engine.compile(schema) : engine.compile(schema); - return (input) => { - return ajvValidator(input) ? { - valid: true, - data: input, - errorMessage: void 0 - } : { - valid: false, - data: void 0, - errorMessage: engine.errorsText(ajvValidator.errors) - }; - }; - } -}; -/** -* Draft-07 AJV class, re-exported for consumers who need to opt back to the pre-SEP-1613 default. -* The full v1-equivalent construction is: -* -* ```ts -* const ajv = new Ajv({ strict: false, validateFormats: true, validateSchema: false, allErrors: true }); -* addFormats(ajv); -* new AjvJsonSchemaValidator(ajv); -* ``` -* -* (omitting `validateSchema: false` makes a 2020-12-stamped `$schema` fail with an opaque -* "no schema with key or ref …" engine error; omitting `addFormats` silently drops `format` -* validation that the v1 default had). -* -* The SDK bundles ajv internally but does not re-export `Ajv2020` (its type graph tips downstream -* declaration bundling — see #2339). To construct a custom 2020-12 instance, add `ajv` to your own -* dependencies (matching the SDK's pinned version) and `import { Ajv2020 } from 'ajv/dist/2020.js'`. -*/ -const ajvProvider_CEoC_sr_Ajv = import_ajv.Ajv; - -//#endregion - -//# sourceMappingURL=ajvProvider-CEoC__sr.mjs.map - - - - - - - - -//#region src/server/completable.ts -const COMPLETABLE_SYMBOL = Symbol.for("mcp.completable"); -/** -* Wraps a schema to provide autocompletion capabilities. Useful for, e.g., prompt arguments in MCP. -* -* @example -* ```ts source="./completable.examples.ts#completable_basicUsage" -* server.registerPrompt( -* 'review-code', -* { -* title: 'Code Review', -* argsSchema: z.object({ -* language: completable(z.string().describe('Programming language'), value => -* ['typescript', 'javascript', 'python', 'rust', 'go'].filter(lang => lang.startsWith(value)) -* ) -* }) -* }, -* ({ language }) => ({ -* messages: [ -* { -* role: 'user' as const, -* content: { -* type: 'text' as const, -* text: `Review this ${language} code.` -* } -* } -* ] -* }) -* ); -* ``` -* -* @see {@linkcode server/mcp.McpServer.registerPrompt | McpServer.registerPrompt} for using completable schemas in prompt argument definitions -*/ -function completable(schema, complete) { - Object.defineProperty(schema, COMPLETABLE_SYMBOL, { - value: { complete }, - enumerable: false, - writable: false, - configurable: false - }); - return schema; -} -/** -* Checks if a schema is completable (has completion metadata). -*/ -function isCompletable(schema) { - return !!schema && typeof schema === "object" && COMPLETABLE_SYMBOL in schema; -} -/** -* Gets the completer callback from a completable schema, if it exists. -*/ -function getCompleter(schema) { - return schema[COMPLETABLE_SYMBOL]?.complete; -} - -//#endregion -//#region src/server/sseKeepAlive.ts -/** Default interval between SSE keep-alive comment frames. */ -const mcp_DXXb3Vv3_DEFAULT_SSE_KEEP_ALIVE_MS = 15e3; -const MAX_TIMER_DELAY_MS = (/* unused pure expression or super */ null && (2 ** 31 - 1)); -/** Arms an unref'd timer, or disables keep-alive for invalid delays. */ -function mcp_DXXb3Vv3_armSseKeepAlive(intervalMs, onTick) { - if (!Number.isFinite(intervalMs) || intervalMs < 1) return; - const timer = setInterval(onTick, Math.min(intervalMs, MAX_TIMER_DELAY_MS)); - timer.unref?.(); - return timer; -} - -//#endregion -//#region src/server/serverEventBus.ts -/** -* A `ServerEventBus` backed by an in-process listener set. -* -* `publish()` delivers synchronously to the live listener set (a listener -* unsubscribing itself mid-dispatch is safe; the entry's listen-router -* listeners never unsubscribe peers). A throwing listener does not stop -* delivery to the others. -*/ -var mcp_DXXb3Vv3_InMemoryServerEventBus = class { - _listeners = /* @__PURE__ */ new Set(); - /** - * @param onerror - Optional callback for errors thrown by listeners - * during dispatch. - */ - constructor(onerror) { - this.onerror = onerror; - } - publish(event) { - for (const listener of this._listeners) try { - listener(event); - } catch (error) { - this.onerror?.(error instanceof Error ? error : new Error(String(error))); - } - } - subscribe(listener) { - this._listeners.add(listener); - let live = true; - return () => { - if (!live) return; - live = false; - this._listeners.delete(listener); - }; - } - /** The number of currently registered listeners (test/introspection only — the routers track capacity via their own open-subscription set). */ - get listenerCount() { - return this._listeners.size; - } -}; -/** Build a {@linkcode ServerNotifier} over a bus. */ -function mcp_DXXb3Vv3_createServerNotifier(bus) { - return { - toolsChanged: () => bus.publish({ kind: "tools_list_changed" }), - promptsChanged: () => bus.publish({ kind: "prompts_list_changed" }), - resourcesChanged: () => bus.publish({ kind: "resources_list_changed" }), - resourceUpdated: (uri) => bus.publish({ - kind: "resource_updated", - uri - }) - }; -} -/** -* Whether a `subscriptions/listen` filter accepts a given change event. -* -* Pure: no I/O, no mutation. The filter governs ONLY the four -* subscription-gated change types — non-gated notifications never reach the -* bus and are not modeled here. -* -* `resource_updated` matches only when `resourceSubscriptions` is present and -* contains the event's URI exactly (per the spec: "for these resource URIs"). -*/ -function listenFilterAccepts(filter, event) { - switch (event.kind) { - case "tools_list_changed": return filter.toolsListChanged === true; - case "prompts_list_changed": return filter.promptsListChanged === true; - case "resources_list_changed": return filter.resourcesListChanged === true; - case "resource_updated": return filter.resourceSubscriptions !== void 0 && filter.resourceSubscriptions.includes(event.uri); - } -} -/** -* The honored subset of a requested filter: keeps only the fields the client -* explicitly opted in to (drops `false` and absent fields), narrowed against -* the server's declared capabilities when supplied. The serving entry sends -* this back in `notifications/subscriptions/acknowledged` so the ack reflects -* what the server can actually deliver. -* -* - `toolsListChanged` is honored only when `capabilities.tools.listChanged` -* is advertised; likewise `promptsListChanged` / `resourcesListChanged`. -* - `resourceSubscriptions` is honored only when -* `capabilities.resources.subscribe` is advertised. -* -* `capabilities` is optional on this pure helper for test convenience only — -* both wired routers REQUIRE capabilities at the call site (the HTTP router's -* `serve()` takes a required parameter; `StdioListenRouter.serve()` throws -* before `setServerCapabilities()` was called), so the fail-open -* `undefined → honor everything` branch is never reachable on a wired entry. -*/ -function honoredSubset(requested, capabilities) { - const honored = {}; - const allow = (bit) => capabilities === void 0 || bit === true; - if (requested.toolsListChanged === true && allow(capabilities?.tools?.listChanged)) honored.toolsListChanged = true; - if (requested.promptsListChanged === true && allow(capabilities?.prompts?.listChanged)) honored.promptsListChanged = true; - if (requested.resourcesListChanged === true && allow(capabilities?.resources?.listChanged)) honored.resourcesListChanged = true; - if (requested.resourceSubscriptions !== void 0 && requested.resourceSubscriptions.length > 0 && allow(capabilities?.resources?.subscribe)) honored.resourceSubscriptions = [...requested.resourceSubscriptions]; - return honored; -} -/** Map a {@linkcode ServerEvent} onto its wire notification `{method, params}`. */ -function serverEventToNotification(event) { - switch (event.kind) { - case "tools_list_changed": return { method: "notifications/tools/list_changed" }; - case "prompts_list_changed": return { method: "notifications/prompts/list_changed" }; - case "resources_list_changed": return { method: "notifications/resources/list_changed" }; - case "resource_updated": return { - method: "notifications/resources/updated", - params: { uri: event.uri } - }; - } -} - -//#endregion -//#region src/server/listenRouter.ts -/** Default capacity guard: refuse a new subscription when this many are already open. */ -const mcp_DXXb3Vv3_DEFAULT_MAX_SUBSCRIPTIONS = 1024; -function jsonRpcError(id, code, message) { - return Response.json({ - jsonrpc: "2.0", - error: { - code, - message - }, - id - }, { status: 200 }); -} -/** Stamp the subscription id onto a notification's `_meta`. Non-mutating. */ -function stampSubscriptionId(notification, subscriptionId) { - return { - method: notification.method, - params: { - ...notification.params, - _meta: { - ...notification.params?._meta, - [SUBSCRIPTION_ID_META_KEY]: subscriptionId - } - } - }; -} -/** -* Read the requested filter off a `subscriptions/listen` request body. -* Returns the validated filter, or `undefined` when `params.notifications` -* is absent or fails the schema (the caller answers `-32602` — the spec -* marks `notifications` REQUIRED on the listen request). -*/ -function parseListenFilter(message) { - const outcome = codecForVersion(MODERN_WIRE_REVISION).validateRequest("subscriptions/listen", message); - return outcome.ok ? outcome.value.params?.notifications : void 0; -} -function mcp_DXXb3Vv3_createListenRouter(options) { - const { bus, onerror } = options; - const maxSubscriptions = options.maxSubscriptions ?? mcp_DXXb3Vv3_DEFAULT_MAX_SUBSCRIPTIONS; - const keepAliveMs = options.keepAliveMs ?? mcp_DXXb3Vv3_DEFAULT_SSE_KEEP_ALIVE_MS; - const open = /* @__PURE__ */ new Set(); - function serve(message, signal, capabilities, serverInfo) { - if (open.size >= maxSubscriptions) { - onerror?.(/* @__PURE__ */ new Error(`subscriptions/listen refused: subscription limit reached (${maxSubscriptions})`)); - return jsonRpcError(message.id, -32603, "Subscription limit reached"); - } - const filter = parseListenFilter(message); - if (filter === void 0) return jsonRpcError(message.id, -32602, "Invalid params: 'notifications' is required and must be a valid SubscriptionFilter"); - const honored = honoredSubset(filter, capabilities); - const subscriptionId = message.id; - const encoder = new TextEncoder(); - let controller; - let closed = false; - let unsubscribe; - let keepAliveTimer; - let abortCleanup; - const writeFrame = (frame) => { - if (closed) return; - try { - controller.enqueue(encoder.encode(frame)); - } catch (error) { - onerror?.(error instanceof Error ? error : new Error(String(error))); - } - }; - const writeNotification = (method, params) => { - writeFrame(`event: message\ndata: ${JSON.stringify({ - jsonrpc: "2.0", - method, - params - })}\n\n`); - }; - const teardown = (graceful) => { - if (closed) return; - if (graceful) writeFrame(`event: message\ndata: ${JSON.stringify({ - jsonrpc: "2.0", - id: subscriptionId, - result: { - resultType: "complete", - _meta: { - [SUBSCRIPTION_ID_META_KEY]: subscriptionId, - [SERVER_INFO_META_KEY]: serverInfo - } - } - })}\n\n`); - closed = true; - try { - unsubscribe?.(); - } catch (error) { - onerror?.(error instanceof Error ? error : new Error(String(error))); - } - if (keepAliveTimer !== void 0) clearInterval(keepAliveTimer); - abortCleanup?.(); - open.delete(teardown); - try { - controller.close(); - } catch {} - }; - const readable = new ReadableStream({ - start(streamController) { - controller = streamController; - const ack = stampSubscriptionId({ - method: "notifications/subscriptions/acknowledged", - params: { notifications: honored } - }, subscriptionId); - writeNotification(ack.method, ack.params); - unsubscribe = bus.subscribe((event) => { - if (closed || !listenFilterAccepts(honored, event)) return; - const note = stampSubscriptionId(serverEventToNotification(event), subscriptionId); - writeNotification(note.method, note.params); - }); - keepAliveTimer = mcp_DXXb3Vv3_armSseKeepAlive(keepAliveMs, () => writeFrame(": keepalive\n\n")); - open.add(teardown); - }, - cancel() { - teardown(false); - } - }); - if (signal !== void 0) if (signal.aborted) teardown(false); - else { - const onAbort = () => teardown(false); - signal.addEventListener("abort", onAbort, { once: true }); - abortCleanup = () => signal.removeEventListener("abort", onAbort); - } - return new Response(readable, { - status: 200, - headers: { - "Content-Type": "text/event-stream", - "Cache-Control": "no-cache, no-transform", - Connection: "keep-alive", - "X-Accel-Buffering": "no" - } - }); - } - return { - serve, - closeAll() { - for (const teardown of open) teardown(true); - }, - get openCount() { - return open.size; - } - }; -} -const CHANGE_NOTIFICATION_METHODS = new Set([ - "notifications/tools/list_changed", - "notifications/prompts/list_changed", - "notifications/resources/list_changed", - "notifications/resources/updated" -]); -/** -* Per-connection listen state for the stdio entry. One instance is held by -* `serveStdio` for the connection lifetime; it routes inbound -* `subscriptions/listen` / `notifications/cancelled` and rewrites outbound -* change notifications onto the active subscriptions. No bus — the long-lived -* pinned instance's existing `send*ListChanged()` calls feed straight into -* `routeOutbound()`. -*/ -var mcp_DXXb3Vv3_StdioListenRouter = class { - /** Active subscriptions, keyed by the listen request's JSON-RPC id verbatim. */ - _subs = /* @__PURE__ */ new Map(); - /** - * The serving instance's declared capabilities. Filled in by the entry - * once the modern instance is constructed (the router is created before - * the instance exists), so the acknowledged filter is narrowed against - * what the server can actually deliver. - */ - _serverCapabilities; - /** - * The serving instance's identity, stamped onto the graceful-close - * results' `_meta` (the spec's `SubscriptionsListenResultMeta` extends - * `ResultMetaObject`). Handed over together with the capabilities. - */ - _serverInfo; - constructor(_maxSubscriptions = mcp_DXXb3Vv3_DEFAULT_MAX_SUBSCRIPTIONS, serverCapabilities, serverInfo) { - this._maxSubscriptions = _maxSubscriptions; - this._serverCapabilities = serverCapabilities; - this._serverInfo = serverInfo; - } - /** - * Record the serving instance's declared capabilities and identity once - * it has been constructed. Called by `serveStdio`'s connect path; - * subsequent `serve()` calls narrow the honored filter against the - * capabilities, and `teardownAll()` stamps the identity. - */ - setServerCapabilities(capabilities, serverInfo) { - this._serverCapabilities = capabilities; - if (serverInfo !== void 0) this._serverInfo = serverInfo; - } - /** Whether `id` is an active listen subscription on this connection. */ - has(id) { - return this._subs.has(id); - } - /** - * Serve one inbound `subscriptions/listen` request: registers the - * subscription and returns the stamped acknowledged notification (or, on - * capacity / params rejection, the in-band JSON-RPC error response). - * - * @throws when called before {@linkcode setServerCapabilities} (or the - * constructor) has supplied the serving instance's capabilities. Honoring a - * filter without knowing the server's advertised capabilities would fail - * open (deliver unadvertised types); the entry guarantees capabilities are - * set before any listen request is routed here. - */ - serve(message) { - if (this._serverCapabilities === void 0) throw new Error("StdioListenRouter.serve() called before setServerCapabilities(); refusing to honor a filter without capabilities"); - if (this._subs.size >= this._maxSubscriptions) return { - jsonrpc: "2.0", - id: message.id, - error: { - code: -32603, - message: "Subscription limit reached" - } - }; - const filter = parseListenFilter(message); - if (filter === void 0) return { - jsonrpc: "2.0", - id: message.id, - error: { - code: -32602, - message: "Invalid params: 'notifications' is required and must be a valid SubscriptionFilter" - } - }; - const honored = honoredSubset(filter, this._serverCapabilities); - this._subs.set(message.id, honored); - return stampSubscriptionId({ - method: "notifications/subscriptions/acknowledged", - params: { notifications: honored } - }, message.id); - } - /** - * Tear down one subscription (inbound `notifications/cancelled`). Returns - * `true` when a subscription was removed. After this call NOTHING further - * is delivered for that subscription id (the post-cancel hardening). - */ - cancel(id) { - return this._subs.delete(id); - } - /** - * Route an outbound notification through the active subscriptions. - * - * - For a subscription-gated change notification, returns one stamped copy - * per subscription that opted in to it (an empty array means it is - * dropped — the modern era never delivers an un-requested change type). - * - For any other outbound message, returns `'passthrough'` (the entry - * forwards it as-is). - */ - routeOutbound(message) { - if (!CHANGE_NOTIFICATION_METHODS.has(message.method)) return "passthrough"; - const uriParam = message.params?.["uri"]; - const uri = typeof uriParam === "string" ? uriParam : void 0; - const event = notificationToServerEvent(message.method, uri); - const out = []; - for (const [subscriptionId, filter] of this._subs) if (listenFilterAccepts(filter, event)) out.push(stampSubscriptionId({ - method: message.method, - params: message.params ?? {} - }, subscriptionId)); - return out; - } - /** - * Server-side graceful teardown of every active subscription: returns the - * empty `subscriptions/listen` JSON-RPC result for each subscription id — - * the spec's graceful-close signal, `_meta` carrying the subscription id - * and the serving instance's identity — for the entry to emit before - * closing the wire. Clears the set so nothing further is delivered. - */ - teardownAll() { - const out = []; - for (const id of this._subs.keys()) out.push({ - jsonrpc: "2.0", - id, - result: { - resultType: "complete", - _meta: { - [SUBSCRIPTION_ID_META_KEY]: id, - ...this._serverInfo !== void 0 && { [SERVER_INFO_META_KEY]: this._serverInfo } - } - } - }); - this._subs.clear(); - return out; - } -}; -function notificationToServerEvent(method, uri) { - switch (method) { - case "notifications/tools/list_changed": return { kind: "tools_list_changed" }; - case "notifications/prompts/list_changed": return { kind: "prompts_list_changed" }; - case "notifications/resources/list_changed": return { kind: "resources_list_changed" }; - default: return { - kind: "resource_updated", - uri: uri ?? "" - }; - } -} - -//#endregion -//#region src/server/legacyInputRequiredShim.ts -/** -* Default handler re-entries per originating request — tighter than the -* client driver's 10 because the shim holds a live wire request open. -*/ -const DEFAULT_LEGACY_SHIM_MAX_ROUNDS = 8; -/** Default per-leg timeout: legs are human-paced, so the 60s protocol default is wrong. */ -const DEFAULT_LEGACY_SHIM_ROUND_TIMEOUT_MS = 6e5; -/** Resolves and validates `ServerOptions.inputRequired`, failing loudly at construction time. */ -function resolveLegacyShimOptions(options) { - if (options?.maxRounds !== void 0 && (!Number.isInteger(options.maxRounds) || options.maxRounds < 1)) throw new RangeError(`inputRequired.maxRounds must be a positive integer (got ${options.maxRounds})`); - if (options?.roundTimeoutMs !== void 0 && (!Number.isFinite(options.roundTimeoutMs) || options.roundTimeoutMs <= 0)) throw new RangeError(`inputRequired.roundTimeoutMs must be a positive number (got ${options.roundTimeoutMs})`); - return { - maxRounds: options?.maxRounds ?? DEFAULT_LEGACY_SHIM_MAX_ROUNDS, - roundTimeoutMs: options?.roundTimeoutMs ?? DEFAULT_LEGACY_SHIM_ROUND_TIMEOUT_MS, - legacyShim: options?.legacyShim ?? true - }; -} -/** -* Validates one `inputRequests` entry: malformed or unknown kinds are server -* bugs and fail loudly on both eras. Shared by the modern seam's capability -* check and the shim's gate. -*/ -function coerceEmbeddedInputRequest(method, key, entry) { - if (entry === null || typeof entry !== "object" || typeof entry.method !== "string") throw new src_CX2iR2pK_ProtocolError(src_CX2iR2pK_ProtocolErrorCode.InternalError, `Handler for ${method} returned an invalid input request '${key}': each inputRequests entry must be an embedded elicitation/create, sampling/createMessage, or roots/list request`); - const embedded = entry; - const required = requiredClientCapabilitiesForInputRequest(embedded); - if (required === void 0) throw new src_CX2iR2pK_ProtocolError(src_CX2iR2pK_ProtocolErrorCode.InternalError, `Handler for ${method} returned an input request '${key}' of kind '${embedded.method}', which is not an embedded request the 2026-07-28 revision defines`); - return { - embedded, - required - }; -} -/** -* The 2025-11-25 URL-mode wire shape requires an `elicitationId`; the 2026 -* in-band shape has none, so URL legs mint one (CSPRNG-backed, with a -* getRandomValues fallback for runtimes without `randomUUID`). -*/ -function syntheticElicitationId() { - const webCrypto = globalThis.crypto; - if (webCrypto?.randomUUID !== void 0) return webCrypto.randomUUID(); - const bytes = new Uint8Array(16); - webCrypto.getRandomValues(bytes); - bytes[6] = bytes[6] & 15 | 64; - bytes[8] = bytes[8] & 63 | 128; - const hex = [...bytes].map((byte) => byte.toString(16).padStart(2, "0")).join(""); - return `${hex.slice(0, 8)}-${hex.slice(8, 12)}-${hex.slice(12, 16)}-${hex.slice(16, 20)}-${hex.slice(20)}`; -} -/** Per-family surfacing: tools/call → isError result (the 2025 idiom); prompts/resources → JSON-RPC error. */ -function legacyShimFailure(method, message) { - if (method === "tools/call") return { - content: [{ - type: "text", - text: message - }], - isError: true - }; - throw new src_CX2iR2pK_ProtocolError(src_CX2iR2pK_ProtocolErrorCode.InternalError, message); -} -/** The fulfilment loop — see the module doc for the contract. */ -var LegacyInputRequiredShim = class { - constructor(_host) { - this._host = _host; - } - async fulfill(method, handler, request, ctx, firstResult) { - const { maxRounds, roundTimeoutMs } = this._host; - const outerSignal = ctx.mcpReq.signal; - let current = firstResult; - let round = 0; - while (true) { - round += 1; - if (round > maxRounds) return legacyShimFailure(method, inputRequiredRoundsExceededMessage(method, maxRounds)); - const inputRequests = current.inputRequests; - const hasInputRequests = inputRequests != null && Object.keys(inputRequests).length > 0; - const requestState = typeof current.requestState === "string" ? current.requestState : void 0; - if (!hasInputRequests && requestState === void 0) throw new src_CX2iR2pK_ProtocolError(src_CX2iR2pK_ProtocolErrorCode.InternalError, `Handler for ${method} returned an input-required result with neither inputRequests nor requestState (every InputRequiredResult must include at least one of the two)`); - let responses; - if (hasInputRequests) { - const declared = this._host.resolvedClientCapabilities(ctx); - const coerced = []; - for (const [key, entry] of Object.entries(inputRequests)) { - const { embedded, required } = coerceEmbeddedInputRequest(method, key, entry); - if (embedded.method !== "roots/list" && embedded.params === void 0) throw new src_CX2iR2pK_ProtocolError(src_CX2iR2pK_ProtocolErrorCode.InternalError, `Handler for ${method} returned an input request '${key}' of kind '${embedded.method}' without params`); - if (src_CX2iR2pK_missingClientCapabilities(required, declared) !== void 0) return legacyShimFailure(method, `Cannot request input '${key}' (${embedded.method}): the client on this 2025-era connection did not declare the required capability${declared === void 0 ? " (no client capabilities are available on this connection — per-request legacy serving cannot receive server-to-client requests)" : ""}`); - coerced.push([key, embedded]); - } - const roundAbort = linkedRoundAbort(outerSignal); - try { - const legOptions = { - relatedRequestId: ctx.mcpReq.id, - timeout: roundTimeoutMs, - resetTimeoutOnProgress: true, - onprogress: () => {}, - signal: roundAbort.signal - }; - const fulfilled = await Promise.all(coerced.map(async ([key, embedded]) => { - try { - return [key, await this._dispatchLeg(embedded, legOptions)]; - } catch (error) { - roundAbort.abort(error); - throw error; - } - })); - responses = Object.fromEntries(fulfilled); - } catch (error) { - if (outerSignal.aborted) throw error; - return legacyShimFailure(method, `Fulfilling input required by '${method}' failed: ${error instanceof Error ? error.message : String(error)}`); - } finally { - roundAbort.dispose(); - } - } else await sleep((/* inlined export .C */250), outerSignal); - let ctxNext = { - ...ctx, - mcpReq: { - ...ctx.mcpReq, - inputResponses: responses, - droppedInputResponseKeys: void 0, - requestState: requestStateAccessor(requestState) - } - }; - if (requestState !== void 0) { - const decoded = await this._host.verifyRequestState(requestState, ctxNext, method); - if (decoded !== void 0) ctxNext = withRequestStateValue(ctxNext, decoded); - } - const next = await handler(request, ctxNext); - if (!isInputRequiredResult(next)) return next; - current = next; - } - } - /** Routes one embedded request through the host's existing 2025-era senders (gate already ran). */ - async _dispatchLeg(embedded, options) { - switch (embedded.method) { - case "elicitation/create": { - let params = embedded.params; - if (params.mode === "url" && params.elicitationId === void 0) params = { - ...params, - elicitationId: syntheticElicitationId() - }; - return await this._host.sendElicitation(params, options); - } - case "sampling/createMessage": return await this._host.sendSampling(embedded.params, options); - case "roots/list": return await this._host.listRoots(embedded.params, options); - } - } -}; - -//#endregion -//#region src/server/server.ts -/** -* The request methods whose 2026-07-28 result vocabulary includes -* `input_required` (the multi round-trip methods). Returning an -* input-required result from any other handler is a server bug. -*/ -const INPUT_REQUIRED_CAPABLE_METHODS = new Set([ - "tools/call", - "prompts/get", - "resources/read" -]); -let writeClientIdentity; -let installDiscoverHandler; -let readServerIdentity; -/** -* Package-internal: backfills the connection-scoped client-identity fields of a -* per-request server instance from the request's validated `_meta` envelope, so the -* (deprecated) {@linkcode Server.getClientCapabilities} / {@linkcode Server.getClientVersion} -* accessors keep answering on instances that never see an `initialize` handshake. -* Not public API. -*/ -function mcp_DXXb3Vv3_seedClientIdentityFromEnvelope(server, identity) { - writeClientIdentity(server, identity); -} -/** -* Package-internal: installs the modern-only `server/discover` handler on an instance -* the HTTP entry has marked as serving the 2026-07-28 era, and makes sure the modern -* revisions the entry serves appear in the instance's supported-versions list (so the -* discover advertisement and version-mismatch errors name them). Idempotent. -* Hand-constructed instances are unaffected: nothing else calls this, so they keep -* answering `-32601` unless their own supported-versions list opts into a modern -* revision. Not public API. -*/ -function mcp_DXXb3Vv3_installModernOnlyHandlers(server, servedModernVersions) { - installDiscoverHandler(server, servedModernVersions); -} -/** -* Package-internal: the instance's implementation identity, for the serving -* entries to stamp onto entry-built results (the `subscriptions/listen` -* graceful-close result — built outside the encode seam, but the spec's -* `SubscriptionsListenResultMeta` extends `ResultMetaObject`, so it carries -* the serverInfo SHOULD like every other result). Not public API. -*/ -function mcp_DXXb3Vv3_serverIdentityOf(server) { - return readServerIdentity(server); -} -/** -* An MCP server on top of a pluggable transport. -* -* This server will automatically respond to the initialization flow as initiated from the client. -* -* @deprecated Use {@linkcode server/mcp.McpServer | McpServer} instead for the high-level API. Only use `Server` for advanced use cases. -*/ -var Server = class extends Protocol { - _clientCapabilities; - _clientVersion; - static { - writeClientIdentity = (server, identity) => { - if (identity.clientCapabilities !== void 0) server._clientCapabilities = identity.clientCapabilities; - if (identity.clientInfo !== void 0) server._clientVersion = identity.clientInfo; - }; - installDiscoverHandler = (server, servedModernVersions) => { - const missing = servedModernVersions.filter((version) => !server._supportedProtocolVersions.includes(version)); - if (missing.length > 0) server._supportedProtocolVersions = [...server._supportedProtocolVersions, ...missing]; - server.setRequestHandler("server/discover", () => server._ondiscover()); - }; - readServerIdentity = (server) => server._serverInfo; - } - _capabilities; - _instructions; - _jsonSchemaValidator; - _cacheHints; - _requestStateVerify; - _inputRequiredServing; - _legacyShim; - /** Lazily-built legacy shim; the loop lives in legacyInputRequiredShim.ts behind a narrow host contract. */ - _legacyInputRequiredShim() { - return this._legacyShim ??= new LegacyInputRequiredShim({ - maxRounds: this._inputRequiredServing.maxRounds, - roundTimeoutMs: this._inputRequiredServing.roundTimeoutMs, - resolvedClientCapabilities: (ctx) => this._inputRequestCapabilityView(ctx), - verifyRequestState: (state, ctx, method) => this._verifyRequestState(state, ctx, method), - sendElicitation: (params, options) => this._sendElicitationLeg(params, options, { validateAcceptedContent: false }), - sendSampling: (params, options) => this.createMessage(params, options), - listRoots: (params, options) => this.listRoots(params, options) - }); - } - /** - * Callback for when initialization has fully completed (i.e., the client has sent an `notifications/initialized` notification). - */ - oninitialized; - /** - * Initializes this server with the given name and version information. - */ - constructor(_serverInfo, options) { - super(options); - this._serverInfo = _serverInfo; - this._capabilities = options?.capabilities ? { ...options.capabilities } : {}; - this._instructions = options?.instructions; - this._jsonSchemaValidator = options?.jsonSchemaValidator ?? new AjvJsonSchemaValidator(); - this._requestStateVerify = options?.requestState?.verify; - this._inputRequiredServing = resolveLegacyShimOptions(options?.inputRequired); - if (options?.cacheHints !== void 0) { - for (const [operation, hint] of Object.entries(options.cacheHints)) if (hint !== void 0) assertValidCacheHint(hint, `cacheHints['${operation}']`); - this._cacheHints = options.cacheHints; - } - this.setRequestHandler("initialize", (request) => this._oninitialize(request)); - this.setNotificationHandler("notifications/initialized", () => this.oninitialized?.()); - if (modernProtocolVersions(this._supportedProtocolVersions).length > 0) this.setRequestHandler("server/discover", () => this._ondiscover()); - if (this._capabilities.logging) this._registerLoggingHandler(); - } - /** - * Registers the built-in `logging/setLevel` request handler. - * - * @deprecated Deprecated as of protocol version 2026-07-28 (SEP-2577). - * Remains functional during the deprecation window (at least twelve months). - * Migrate to stderr logging (STDIO servers) or OpenTelemetry. - */ - _registerLoggingHandler() { - this.setRequestHandler("logging/setLevel", async (request, ctx) => { - const transportSessionId = ctx.sessionId || ctx.http?.req?.headers.get("mcp-session-id") || void 0; - const { level } = request.params; - const parseResult = parseSchema(LoggingLevelSchema, level); - if (parseResult.success) this._loggingLevels.set(transportSessionId, parseResult.data); - return {}; - }); - } - buildContext(ctx, transportInfo) { - const hasHttpInfo = ctx.http || transportInfo?.request || transportInfo?.closeSSEStream || transportInfo?.closeStandaloneSSEStream; - return { - ...ctx, - mcpReq: { - ...ctx.mcpReq, - log: (level, data, logger) => { - if (!this._capabilities.logging) return Promise.resolve(); - let threshold; - if (this._servedModernEra()) { - threshold = ctx.mcpReq.envelope?.[LOG_LEVEL_META_KEY]; - if (threshold === void 0) return Promise.resolve(); - } else threshold = this._loggingLevels.get(ctx.sessionId) ?? this._loggingLevels.get(void 0); - if (threshold !== void 0 && this.LOG_LEVEL_SEVERITY.get(level) < this.LOG_LEVEL_SEVERITY.get(threshold)) return Promise.resolve(); - return ctx.mcpReq.notify({ - method: "notifications/message", - params: { - level, - data, - logger - } - }); - }, - elicitInput: (params, options) => this.elicitInput(params, options), - requestSampling: (params, options) => this.createMessage(params, options) - }, - http: hasHttpInfo ? { - ...ctx.http, - req: transportInfo?.request, - closeSSE: transportInfo?.closeSSEStream, - closeStandaloneSSE: transportInfo?.closeStandaloneSSEStream - } : void 0 - }; - } - _loggingLevels = /* @__PURE__ */ new Map(); - LOG_LEVEL_SEVERITY = new Map(LoggingLevelSchema.options.map((level, index) => [level, index])); - isMessageIgnored = (level, sessionId) => { - const currentLevel = this._loggingLevels.get(sessionId); - return currentLevel ? this.LOG_LEVEL_SEVERITY.get(level) < this.LOG_LEVEL_SEVERITY.get(currentLevel) : false; - }; - /** - * Registers new capabilities. This can only be called before connecting to a transport. - * - * The new capabilities will be merged with any existing capabilities previously given (e.g., at initialization). - */ - registerCapabilities(capabilities) { - if (this.transport) throw new src_CX2iR2pK_SdkError(src_CX2iR2pK_SdkErrorCode.AlreadyConnected, "Cannot register capabilities after connecting to transport"); - const hadLogging = !!this._capabilities.logging; - this._capabilities = mergeCapabilities(this._capabilities, capabilities); - if (!hadLogging && this._capabilities.logging) this._registerLoggingHandler(); - } - /** - * Enforces server-side validation for `tools/call` results regardless of how the - * handler was registered, attaches the configured per-operation cache hint - * (when one exists) so the 2026-07-28 encode seam can fill `ttlMs`/`cacheScope` - * for results that do not provide their own, and owns the multi-round-trip - * seam: on the methods whose 2026-07-28 result vocabulary includes - * `input_required` (`tools/call`, `prompts/get`, `resources/read`) an - * input-required return skips result-schema validation and is checked - * against the served era, the at-least-one rule, and the request's own - * declared client capabilities; on every other method an input-required - * return is a server bug and fails loudly. The hint rides a symbol-keyed - * property that is never serialized, so 2025-era responses are unaffected. - */ - _wrapHandler(method, handler) { - if (method !== "tools/call") { - const cacheHint = this._cacheHints?.[method]; - const isInputRequiredCapable = INPUT_REQUIRED_CAPABLE_METHODS.has(method); - if (cacheHint === void 0 && !isInputRequiredCapable) return async (request, ctx) => { - const result = await handler(request, ctx); - if (isInputRequiredResult(result)) throw new src_CX2iR2pK_ProtocolError(src_CX2iR2pK_ProtocolErrorCode.InternalError, `Handler for ${method} returned an input-required result, but only tools/call, prompts/get and resources/read support input_required (protocol revision 2026-07-28)`); - return result; - }; - return async (request, ctx) => { - const result = isInputRequiredCapable ? await this._invokeInputRequiredCapableHandler(method, handler, request, ctx) : await handler(request, ctx); - if (isInputRequiredResult(result)) { - if (!isInputRequiredCapable) throw new src_CX2iR2pK_ProtocolError(src_CX2iR2pK_ProtocolErrorCode.InternalError, `Handler for ${method} returned an input-required result, but only tools/call, prompts/get and resources/read support input_required (protocol revision 2026-07-28)`); - return result; - } - return cacheHint === void 0 ? result : attachCacheHintFallback(result, cacheHint); - }; - } - return async (request, ctx) => { - const codec = src_CX2iR2pK_codecForVersion(this._negotiatedProtocolVersion); - const validatedRequest = codec.validateRequest("tools/call", request); - if (!validatedRequest.ok) throw new src_CX2iR2pK_ProtocolError(validatedRequest.reason === "not-in-era" ? src_CX2iR2pK_ProtocolErrorCode.InternalError : src_CX2iR2pK_ProtocolErrorCode.InvalidParams, validatedRequest.reason === "not-in-era" ? "No wire schema for tools/call in the resolved era" : `Invalid tools/call request: ${validatedRequest.message}`); - const result = await this._invokeInputRequiredCapableHandler("tools/call", handler, request, ctx); - if (isInputRequiredResult(result)) return result; - const normalizedResult = normalizeContentlessToolResult(result); - const validationResult = codec.validateResult("tools/call", normalizedResult); - if (!validationResult.ok) throw new src_CX2iR2pK_ProtocolError(validationResult.reason === "not-in-era" ? src_CX2iR2pK_ProtocolErrorCode.InternalError : src_CX2iR2pK_ProtocolErrorCode.InvalidParams, validationResult.reason === "not-in-era" ? "No wire schema for tools/call in the resolved era" : `Invalid tools/call result: ${validationResult.message}`); - return validationResult.value; - }; - } - /** - * Whether this instance is bound to a 2026-07-28-or-later protocol - * revision. Era is instance state — a serving entry (`createMcpHandler`, - * `serveStdio`) marks the instance modern at construction; a 2025-era - * `initialize` handshake binds it legacy. The multi-round-trip seam reads - * this directly: there is no per-request era consult. - */ - _servedModernEra() { - return this._negotiatedProtocolVersion !== void 0 && isModernProtocolVersion(this._negotiatedProtocolVersion); - } - /** - * Invokes a handler for one of the multi-round-trip methods and applies - * the input-required seam: - * - * - a `UrlElicitationRequiredError` (or any 2025-style server→client - * request idiom) escaping the handler on a request served on the - * 2026-07-28 era fails LOUDLY with a clear steer to - * `inputRequired.elicitUrl(...)` — the `-32042` error never reaches the - * 2026-07-28 wire and the throw is not silently converted. Requests - * served on the 2025 era keep today's `-32042` behavior byte-exact (the - * error is rethrown unchanged). - * - an input-required RETURN toward a 2026-07-28 request must satisfy - * the at-least-one rule, and every embedded request must be covered by - * the capabilities declared on the request's envelope (violations - * answer the typed `-32021` error). Toward a 2025-era request the - * return is fulfilled by the default-on legacy shim, whose own gate - * consults the initialize-declared capabilities and surfaces - * violations per family; `inputRequired.legacyShim: false` restores - * the pre-shim loud failure. - */ - async _invokeInputRequiredCapableHandler(method, handler, request, ctx) { - const servedModern = this._servedModernEra(); - const rawRequestState = ctx.mcpReq.requestState(); - if (rawRequestState !== void 0 && typeof rawRequestState !== "string") throw new src_CX2iR2pK_ProtocolError(src_CX2iR2pK_ProtocolErrorCode.InvalidParams, "Invalid or expired requestState", { reason: "invalid_request_state" }); - let ctxForHandler = ctx; - if (typeof rawRequestState === "string") { - const decoded = await this._verifyRequestState(rawRequestState, ctx, method); - if (decoded !== void 0) ctxForHandler = withRequestStateValue(ctx, decoded); - } - let result; - try { - result = await handler(request, ctxForHandler); - } catch (error) { - if (error instanceof src_CX2iR2pK_ProtocolError && error.code === src_CX2iR2pK_ProtocolErrorCode.UrlElicitationRequired) { - if (!servedModern) throw error; - throw new src_CX2iR2pK_ProtocolError(src_CX2iR2pK_ProtocolErrorCode.InternalError, `URL elicitation cannot be signalled by throwing UrlElicitationRequiredError on protocol revision ${this._negotiatedProtocolVersion}: return inputRequired({ inputRequests: { …: inputRequired.elicitUrl(...) } }) from the handler instead. The urlElicitationRequired error (-32042) of earlier revisions is not available on this revision.`); - } - throw error; - } - if (!isInputRequiredResult(result)) return result; - if (!servedModern) { - if (!this._inputRequiredServing.legacyShim) throw new src_CX2iR2pK_ProtocolError(src_CX2iR2pK_ProtocolErrorCode.InternalError, `Handler for ${method} returned an input-required result, but this request is served on protocol revision ${this._negotiatedProtocolVersion ?? LATEST_PROTOCOL_VERSION}, which has no input_required vocabulary`); - return await this._legacyInputRequiredShim().fulfill(method, handler, request, ctxForHandler, result); - } - const inputRequests = result.inputRequests; - const hasInputRequests = inputRequests != null && Object.keys(inputRequests).length > 0; - const hasRequestState = typeof result.requestState === "string"; - if (!hasInputRequests && !hasRequestState) throw new src_CX2iR2pK_ProtocolError(src_CX2iR2pK_ProtocolErrorCode.InternalError, `Handler for ${method} returned an input-required result with neither inputRequests nor requestState (every InputRequiredResult must include at least one of the two)`); - if (hasInputRequests) { - const declared = this._inputRequestCapabilityView(ctx); - for (const [key, entry] of Object.entries(inputRequests)) { - const { embedded, required } = coerceEmbeddedInputRequest(method, key, entry); - const missing = src_CX2iR2pK_missingClientCapabilities(required, declared); - if (missing !== void 0) throw new src_CX2iR2pK_MissingRequiredClientCapabilityError({ requiredCapabilities: missing }, `Cannot request input '${key}' (${embedded.method}): the request's client capabilities do not declare the required capability`); - } - } - return result; - } - /** - * Runs the configured `requestState.verify` hook and returns its - * resolved value (`undefined` when unconfigured or the hook returns - * nothing). Deny-on-error: any hook failure answers the frozen `-32602`; - * the reason goes to `onerror` only. - */ - async _verifyRequestState(state, ctx, method) { - if (this._requestStateVerify === void 0) return; - try { - return await this._requestStateVerify(state, ctx); - } catch (error) { - this.onerror?.(/* @__PURE__ */ new Error(`requestState verification rejected ${method}: ${error instanceof Error ? error.message : String(error)}`)); - throw new src_CX2iR2pK_ProtocolError(src_CX2iR2pK_ProtocolErrorCode.InvalidParams, "Invalid or expired requestState", { reason: "invalid_request_state" }); - } - } - /** - * The per-request resolved client-capabilities view: the request's own - * `_meta` envelope on the 2026 era; the `initialize`-declared state on a - * 2025-era connection. Per-request instances that never saw an - * initialize (stateless legacy) hold nothing, so gates refuse there. - */ - _inputRequestCapabilityView(ctx) { - return this._servedModernEra() ? ctx.mcpReq.envelope?.[auth_CUe6YdwF_CLIENT_CAPABILITIES_META_KEY] : this._clientCapabilities; - } - /** - * Guard for the push-style server→client request APIs ({@linkcode createMessage}, - * {@linkcode elicitInput}, {@linkcode listRoots}, {@linkcode ping}) on a - * modern-era instance: the 2026-07-28 revision has no server→client request - * channel, so the call fails before any wire traffic with a typed error - * whose message steers to `inputRequired(...)`. The base era gate would - * also reject it; this guard runs first to carry the steer. - */ - _assertPushApiInServedEra(method) { - if (this._servedModernEra()) throw new src_CX2iR2pK_SdkError(src_CX2iR2pK_SdkErrorCode.MethodNotSupportedByProtocolVersion, `Server-to-client requests are not available on protocol revision ${this._negotiatedProtocolVersion}: '${method}' cannot be sent while serving a request on that revision. Return inputRequired({ ... }) from the handler instead — the client fulfils the embedded requests and retries the original request (multi round-trip requests).`, { - method, - era: "2026-07-28" - }); - } - assertCapabilityForMethod(method) { - switch (method) { - case "sampling/createMessage": - if (!this._clientCapabilities?.sampling) throw new src_CX2iR2pK_SdkError(src_CX2iR2pK_SdkErrorCode.CapabilityNotSupported, `Client does not support sampling (required for ${method})`); - break; - case "elicitation/create": - if (!this._clientCapabilities?.elicitation) throw new src_CX2iR2pK_SdkError(src_CX2iR2pK_SdkErrorCode.CapabilityNotSupported, `Client does not support elicitation (required for ${method})`); - break; - case "roots/list": - if (!this._clientCapabilities?.roots) throw new src_CX2iR2pK_SdkError(src_CX2iR2pK_SdkErrorCode.CapabilityNotSupported, `Client does not support listing roots (required for ${method})`); - break; - case "ping": break; - } - } - assertNotificationCapability(method) { - switch (method) { - case "notifications/message": - if (!this._capabilities.logging) throw new src_CX2iR2pK_SdkError(src_CX2iR2pK_SdkErrorCode.CapabilityNotSupported, `Server does not support logging (required for ${method})`); - break; - case "notifications/resources/updated": - case "notifications/resources/list_changed": - if (!this._capabilities.resources) throw new src_CX2iR2pK_SdkError(src_CX2iR2pK_SdkErrorCode.CapabilityNotSupported, `Server does not support notifying about resources (required for ${method})`); - break; - case "notifications/tools/list_changed": - if (!this._capabilities.tools) throw new src_CX2iR2pK_SdkError(src_CX2iR2pK_SdkErrorCode.CapabilityNotSupported, `Server does not support notifying of tool list changes (required for ${method})`); - break; - case "notifications/prompts/list_changed": - if (!this._capabilities.prompts) throw new src_CX2iR2pK_SdkError(src_CX2iR2pK_SdkErrorCode.CapabilityNotSupported, `Server does not support notifying of prompt list changes (required for ${method})`); - break; - case "notifications/elicitation/complete": - if (!this._clientCapabilities?.elicitation?.url) throw new src_CX2iR2pK_SdkError(src_CX2iR2pK_SdkErrorCode.CapabilityNotSupported, `Client does not support URL elicitation (required for ${method})`); - break; - case "notifications/cancelled": break; - case "notifications/progress": break; - } - } - assertRequestHandlerCapability(method) { - switch (method) { - case "completion/complete": - if (!this._capabilities.completions) throw new src_CX2iR2pK_SdkError(src_CX2iR2pK_SdkErrorCode.CapabilityNotSupported, `Server does not support completions (required for ${method})`); - break; - case "logging/setLevel": - if (!this._capabilities.logging) throw new src_CX2iR2pK_SdkError(src_CX2iR2pK_SdkErrorCode.CapabilityNotSupported, `Server does not support logging (required for ${method})`); - break; - case "prompts/get": - case "prompts/list": - if (!this._capabilities.prompts) throw new src_CX2iR2pK_SdkError(src_CX2iR2pK_SdkErrorCode.CapabilityNotSupported, `Server does not support prompts (required for ${method})`); - break; - case "resources/list": - case "resources/templates/list": - case "resources/read": - if (!this._capabilities.resources) throw new src_CX2iR2pK_SdkError(src_CX2iR2pK_SdkErrorCode.CapabilityNotSupported, `Server does not support resources (required for ${method})`); - break; - case "tools/call": - case "tools/list": - if (!this._capabilities.tools) throw new src_CX2iR2pK_SdkError(src_CX2iR2pK_SdkErrorCode.CapabilityNotSupported, `Server does not support tools (required for ${method})`); - break; - case "ping": - case "initialize": break; - } - } - async _oninitialize(request) { - const requestedVersion = request.params.protocolVersion; - this._clientCapabilities = request.params.capabilities; - this._clientVersion = request.params.clientInfo; - const legacyVersions = legacyProtocolVersions(this._supportedProtocolVersions); - const protocolVersion = legacyVersions.includes(requestedVersion) ? requestedVersion : legacyVersions[0] ?? LATEST_PROTOCOL_VERSION; - this._negotiatedProtocolVersion = protocolVersion; - this.transport?.setProtocolVersion?.(protocolVersion); - return { - protocolVersion, - capabilities: this.getCapabilities(), - serverInfo: this._serverInfo, - ...this._instructions && { instructions: this._instructions } - }; - } - /** - * Answers `server/discover` (protocol revision 2026-07-28). `supportedVersions` - * lists only modern revisions (2025-era versions are negotiated via `initialize`); - * the capabilities are advertised as-is, listChanged/subscribe bits included - * (see {@linkcode discoverAdvertisedCapabilities}). - */ - _ondiscover() { - return { - supportedVersions: modernProtocolVersions(this._supportedProtocolVersions), - capabilities: discoverAdvertisedCapabilities(this.getCapabilities()), - ...this._instructions && { instructions: this._instructions } - }; - } - /** - * The identity the 2026-era encode seam stamps into every outbound - * result's `_meta` under `io.modelcontextprotocol/serverInfo` (spec PR - * #3002: servers SHOULD identify themselves on every response). - */ - _outboundServerInfo() { - return this._serverInfo; - } - /** - * After initialization has completed, this will be populated with the client's reported capabilities. - * - * @deprecated Read client identity from the per-request handler context instead: on - * 2026-07-28 (per-request envelope) requests `ctx.mcpReq.envelope` carries the client's - * declared capabilities, while on 2025-era connections this accessor keeps returning the - * `initialize`-scoped value. The accessor remains functional — instances serving the - * 2026-07-28 era are backfilled per request from the validated envelope. - */ - getClientCapabilities() { - return this._clientCapabilities; - } - /** - * After initialization has completed, this will be populated with information about the client's name and version. - * - * @deprecated Read client identity from the per-request handler context instead: on - * 2026-07-28 (per-request envelope) requests `ctx.mcpReq.envelope` carries the client's - * name and version, while on 2025-era connections this accessor keeps returning the - * `initialize`-scoped value. The accessor remains functional — instances serving the - * 2026-07-28 era are backfilled per request from the validated envelope. - */ - getClientVersion() { - return this._clientVersion; - } - /** - * After initialization has completed, this will be populated with the protocol version negotiated - * with the client (the version the server responded with during the initialize handshake), or - * `undefined` before initialization. - * - * @deprecated Read the protocol revision from the per-request handler context instead: on - * 2026-07-28 (per-request envelope) requests `ctx.mcpReq.envelope` names the revision the - * request was sent for, while on 2025-era connections this accessor keeps returning the - * `initialize`-negotiated version. The accessor remains functional — instances serving the - * 2026-07-28 era report that revision. - */ - getNegotiatedProtocolVersion() { - return this._negotiatedProtocolVersion; - } - /** - * Project a `tools/call` result through this instance's negotiated wire - * codec — the era-agnostic SEP-2106 §4.3 TextContent auto-append, plus on - * the 2025 era the `{result:…}` wrap when `structuredContent` is a - * non-object value or the advertised `outputSchema` had a non-object root. - * Identity for object-shaped `structuredContent` on the 2026 era. - * - * `McpServer`'s built-in `tools/call` handler routes through this method. - * Low-level `setRequestHandler('tools/call', …)` authors call it - * themselves so the projection lives in one place (the codec) and the - * server-side handler stays era-blind. - * - * This is the only codec function exposed on `Server` — the full - * `WireCodec` is intentionally not part of the public surface. - */ - projectCallToolResult(result, advertisedOutputSchema) { - return this._wireCodec().projectCallToolResult(result, advertisedOutputSchema); - } - /** - * Returns the current server capabilities. - */ - getCapabilities() { - return this._capabilities; - } - /** - * Sends a `ping` request to the connected client. - * - * @deprecated The 2026-07-28 protocol removed ping; it throws on a 2026-07-28-era instance. - * If your factory serves both eras, this only works on the legacy path. - */ - async ping() { - this._assertPushApiInServedEra("ping"); - return this.request({ method: "ping" }); - } - async createMessage(params, options) { - this._assertPushApiInServedEra("sampling/createMessage"); - if ((params.tools || params.toolChoice) && !this._clientCapabilities?.sampling?.tools) throw new src_CX2iR2pK_SdkError(src_CX2iR2pK_SdkErrorCode.CapabilityNotSupported, "Client does not support sampling tools capability."); - if (params.messages.length > 0) { - const lastMessage = params.messages.at(-1); - const lastContent = Array.isArray(lastMessage.content) ? lastMessage.content : [lastMessage.content]; - const hasToolResults = lastContent.some((c) => c.type === "tool_result"); - const previousMessage = params.messages.length > 1 ? params.messages.at(-2) : void 0; - const previousContent = previousMessage ? Array.isArray(previousMessage.content) ? previousMessage.content : [previousMessage.content] : []; - const hasPreviousToolUse = previousContent.some((c) => c.type === "tool_use"); - if (hasToolResults) { - if (lastContent.some((c) => c.type !== "tool_result")) throw new src_CX2iR2pK_ProtocolError(src_CX2iR2pK_ProtocolErrorCode.InvalidParams, "The last message must contain only tool_result content if any is present"); - if (!hasPreviousToolUse) throw new src_CX2iR2pK_ProtocolError(src_CX2iR2pK_ProtocolErrorCode.InvalidParams, "tool_result blocks are not matching any tool_use from the previous message"); - } - if (hasPreviousToolUse) { - const toolUseIds = new Set(previousContent.filter((c) => c.type === "tool_use").map((c) => c.id)); - const toolResultIds = new Set(lastContent.filter((c) => c.type === "tool_result").map((c) => c.toolUseId)); - if (toolUseIds.size !== toolResultIds.size || ![...toolUseIds].every((id) => toolResultIds.has(id))) throw new src_CX2iR2pK_ProtocolError(src_CX2iR2pK_ProtocolErrorCode.InvalidParams, "ids of tool_result blocks and tool_use blocks from previous message do not match"); - } - } - const hasTools = Boolean(params.tools || params.toolChoice); - const wide = await this.request({ - method: "sampling/createMessage", - params - }, options); - const outcome = this._wireCodec().samplingResultVariant(hasTools, wide); - if (!outcome.ok) throw new src_CX2iR2pK_SdkError(src_CX2iR2pK_SdkErrorCode.InvalidResult, `Invalid sampling/createMessage result: ${outcome.reason === "invalid" ? outcome.message : outcome.reason}`); - return outcome.value; - } - /** - * Creates an elicitation request for the given parameters. - * For backwards compatibility, `mode` may be omitted for form requests and will default to `"form"`. - * @param params The parameters for the elicitation request. - * @param options Optional request options. - * @returns The result of the elicitation request. - * - * @deprecated Throws on a 2026-07-28-era request — use {@link index.inputRequired | inputRequired} (multi-round-trip) - * instead. The 2025 push-style server-to-client request model is replaced by input_required - * results in the 2026-07-28 protocol. If your factory serves both eras, this only works on the - * legacy path. - */ - async elicitInput(params, options) { - this._assertPushApiInServedEra("elicitation/create"); - switch (params.mode ?? "form") { - case "url": - if (!this._clientCapabilities?.elicitation?.url) throw new src_CX2iR2pK_SdkError(src_CX2iR2pK_SdkErrorCode.CapabilityNotSupported, "Client does not support url elicitation."); - break; - case "form": - if (!this._clientCapabilities?.elicitation?.form) throw new src_CX2iR2pK_SdkError(src_CX2iR2pK_SdkErrorCode.CapabilityNotSupported, "Client does not support form elicitation."); - break; - } - return this._sendElicitationLeg(params, options); - } - /** - * The capability-check-free core of {@linkcode elicitInput}. The shim - * uses it because its gate differs from the public checks: a bare - * `elicitation: {}` counts as form support (the pre-mode rule), and - * accepted content passes through unvalidated for parity with the - * modern client driver (handlers validate via the schema-aware - * `acceptedContent` overload and can re-ask). - */ - async _sendElicitationLeg(params, options, behavior) { - const mode = params.mode ?? "form"; - const validateAcceptedContent = behavior?.validateAcceptedContent ?? true; - switch (mode) { - case "url": { - const urlParams = params; - return this.request({ - method: "elicitation/create", - params: urlParams - }, options); - } - case "form": { - const formParams = params.mode === "form" ? params : { - ...params, - mode: "form" - }; - const result = await this.request({ - method: "elicitation/create", - params: formParams - }, options); - if (validateAcceptedContent && result.action === "accept" && result.content && formParams.requestedSchema) try { - const validationResult = this._jsonSchemaValidator.getValidator(formParams.requestedSchema)(result.content); - if (!validationResult.valid) throw new src_CX2iR2pK_ProtocolError(src_CX2iR2pK_ProtocolErrorCode.InvalidParams, `Elicitation response content does not match requested schema: ${validationResult.errorMessage}`); - } catch (error) { - if (error instanceof src_CX2iR2pK_ProtocolError) throw error; - throw new src_CX2iR2pK_ProtocolError(src_CX2iR2pK_ProtocolErrorCode.InternalError, `Error validating elicitation response: ${error instanceof Error ? error.message : String(error)}`); - } - return result; - } - } - } - /** - * Creates a reusable callback that, when invoked, will send a `notifications/elicitation/complete` - * notification for the specified elicitation ID. - * - * The notification (and the `elicitationId` it references) exists only on protocol revision - * 2025-11-25 — the 2026-07-28 revision removed both. On a connection negotiated at 2026-07-28 the - * returned callback rejects with a typed local error before anything reaches the transport - * (the method is not part of that revision's wire registry). - * - * @param elicitationId The ID of the elicitation to mark as complete. - * @param options Optional notification options. Useful when the completion notification should be related to a prior request. - * @returns A function that emits the completion notification when awaited. - */ - createElicitationCompletionNotifier(elicitationId, options) { - if (!this._clientCapabilities?.elicitation?.url) throw new src_CX2iR2pK_SdkError(src_CX2iR2pK_SdkErrorCode.CapabilityNotSupported, "Client does not support URL elicitation (required for notifications/elicitation/complete)"); - return () => this.notification({ - method: "notifications/elicitation/complete", - params: { elicitationId } - }, options); - } - /** - * Requests the list of roots from the client. - * - * @deprecated Deprecated as of protocol version 2026-07-28 (SEP-2577). - * Throws on a 2026-07-28-era request — use {@link index.inputRequired | inputRequired} (multi-round-trip) instead, - * or migrate to passing paths via tool parameters, resource URIs, or configuration. The 2025 - * push-style server-to-client request model is replaced by input_required results in the - * 2026-07-28 protocol. If your factory serves both eras, this only works on the legacy path. - */ - async listRoots(params, options) { - this._assertPushApiInServedEra("roots/list"); - return this.request({ - method: "roots/list", - params - }, options); - } - /** - * Sends a logging message to the client, if connected. - * Note: You only need to send the parameters object, not the entire JSON-RPC message. - * @see {@linkcode LoggingMessageNotification} - * @param params - * @param sessionId Optional for stateless transports and backward compatibility. - * - * @deprecated Deprecated as of protocol version 2026-07-28 (SEP-2577). - * Remains functional during the deprecation window (at least twelve months). - * Migrate to stderr logging (STDIO servers) or OpenTelemetry. - */ - async sendLoggingMessage(params, sessionId) { - if (this._capabilities.logging && !this.isMessageIgnored(params.level, sessionId)) return this.notification({ - method: "notifications/message", - params - }); - } - async sendResourceUpdated(params) { - return this.notification({ - method: "notifications/resources/updated", - params - }); - } - 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" }); - } -}; -/** -* The capability set a server advertises on `server/discover`. Pure — never -* mutates the input; the legacy `initialize` advertisement is untouched. -* -* The serving entries serve `subscriptions/listen` themselves, so the -* `listChanged` and `resources.subscribe` capability bits are advertised -* as-is: a modern-era client uses them to decide which notification types to -* request on its listen filter. -*/ -function discoverAdvertisedCapabilities(capabilities) { - return { ...capabilities }; -} - -//#endregion -//#region src/server/mcp.ts -/** -* High-level MCP server that provides a simpler API for working with resources, tools, and prompts. -* For advanced usage (like sending notifications or setting custom request handlers), use the underlying -* {@linkcode Server} instance available via the {@linkcode McpServer.server | server} property. -* -* @example -* ```ts source="./mcp.examples.ts#McpServer_basicUsage" -* const server = new McpServer({ -* name: 'my-server', -* version: '1.0.0' -* }); -* ``` -*/ -var mcp_DXXb3Vv3_McpServer = class { - /** - * The underlying {@linkcode Server} instance, useful for advanced operations like sending notifications. - */ - server; - _registeredResources = {}; - _registeredResourceTemplates = {}; - _registeredTools = {}; - _registeredPrompts = {}; - /** - * Per-tool JSON-converted `inputSchema`, memoized so the SEP-2243 - * registration-time scan and the pre-dispatch validation step share one - * conversion instead of paying it twice per request under the - * per-request-factory `createMcpHandler` model. - */ - _toolInputSchemaJson = {}; - /** - * The JSON-serialized `inputSchema` of a registered tool, or `undefined` - * when no such tool is registered. Used by the HTTP entry's pre-dispatch - * SEP-2243 `Mcp-Param-*` validation step (which needs the same JSON Schema - * `tools/list` would emit, before dispatch reaches the handler). - * - * @internal - */ - toolInputSchemaJson(name) { - const tool = this._registeredTools[name]; - if (tool === void 0 || !tool.enabled) return void 0; - if (Object.hasOwn(this._toolInputSchemaJson, name)) return this._toolInputSchemaJson[name]; - if (tool.inputSchema === void 0) return EMPTY_OBJECT_JSON_SCHEMA; - try { - const json = standardSchemaToJsonSchema(tool.inputSchema, "input"); - this._toolInputSchemaJson[name] = json; - return json; - } catch { - return; - } - } - constructor(serverInfo, options) { - this.server = new Server(serverInfo, options); - if (options?.capabilities?.tools) this.setToolRequestHandlers(); - if (options?.capabilities?.resources) this.setResourceRequestHandlers(); - if (options?.capabilities?.prompts) this.setPromptRequestHandlers(); - } - /** - * Attaches to the given transport, starts it, and starts listening for messages. - * - * The `server` object assumes ownership of the {@linkcode Transport}, replacing any callbacks that have already been set, and expects that it is the only user of the {@linkcode Transport} instance going forward. - * - * @example - * ```ts source="./mcp.examples.ts#McpServer_connect_stdio" - * const server = new McpServer({ name: 'my-server', version: '1.0.0' }); - * const transport = new StdioServerTransport(); - * await server.connect(transport); - * ``` - */ - async connect(transport) { - return await this.server.connect(transport); - } - /** - * Closes the connection. - */ - async close() { - await this.server.close(); - } - _toolHandlersInitialized = false; - setToolRequestHandlers() { - if (this._toolHandlersInitialized) return; - this.server.assertCanSetRequestHandler("tools/list"); - this.server.assertCanSetRequestHandler("tools/call"); - this.server.registerCapabilities({ tools: { listChanged: this.server.getCapabilities().tools?.listChanged ?? true } }); - this.server.setRequestHandler("tools/list", () => ({ tools: Object.entries(this._registeredTools).filter(([, tool]) => tool.enabled).map(([name, tool]) => { - const toolDefinition = { - name, - title: tool.title, - description: tool.description, - inputSchema: tool.inputSchema ? standardSchemaToJsonSchema(tool.inputSchema, "input") : EMPTY_OBJECT_JSON_SCHEMA, - annotations: tool.annotations, - icons: tool.icons, - execution: tool.execution, - _meta: tool._meta - }; - if (tool.outputSchema) toolDefinition.outputSchema = standardSchemaToJsonSchema(tool.outputSchema, "output"); - return toolDefinition; - }) })); - this.server.setRequestHandler("tools/call", async (request, ctx) => { - const tool = this._registeredTools[request.params.name]; - if (!tool) throw new src_CX2iR2pK_ProtocolError(src_CX2iR2pK_ProtocolErrorCode.InvalidParams, `Tool ${request.params.name} not found`); - if (!tool.enabled) throw new src_CX2iR2pK_ProtocolError(src_CX2iR2pK_ProtocolErrorCode.InvalidParams, `Tool ${request.params.name} disabled`); - try { - const args = await this.validateToolInput(tool, request.params.arguments, request.params.name); - const result = await this.executeToolHandler(tool, args, ctx); - await this.validateToolOutput(tool, result, request.params.name); - if (isInputRequiredResult(result)) return result; - return this.server.projectCallToolResult(result, tool.outputSchemaJson); - } catch (error) { - if (error instanceof src_CX2iR2pK_ProtocolError && error.code === src_CX2iR2pK_ProtocolErrorCode.UrlElicitationRequired) throw error; - return this.createToolError(error instanceof Error ? error.message : String(error)); - } - }); - this._toolHandlersInitialized = true; - } - /** - * Creates a tool error result. - * - * @param errorMessage - The error message. - * @returns The tool error result. - */ - createToolError(errorMessage) { - return { - content: [{ - type: "text", - text: errorMessage - }], - isError: true - }; - } - /** - * Validates tool input arguments against the tool's input schema. - */ - async validateToolInput(tool, args, toolName) { - if (!tool.inputSchema) return; - const parseResult = await validateStandardSchema(tool.inputSchema, args ?? {}); - if (!parseResult.success) throw new src_CX2iR2pK_ProtocolError(src_CX2iR2pK_ProtocolErrorCode.InvalidParams, `Input validation error: Invalid arguments for tool ${toolName}: ${parseResult.error}`); - return parseResult.data; - } - /** - * Validates tool output against the tool's output schema. - */ - async validateToolOutput(tool, result, toolName) { - if (!tool.outputSchema) return; - if (isInputRequiredResult(result)) return; - if (result.isError) return; - if (result.structuredContent === void 0) throw new src_CX2iR2pK_ProtocolError(src_CX2iR2pK_ProtocolErrorCode.InvalidParams, `Output validation error: Tool ${toolName} has an output schema but no structured content was provided`); - const parseResult = await validateStandardSchema(tool.outputSchema, result.structuredContent); - if (!parseResult.success) throw new src_CX2iR2pK_ProtocolError(src_CX2iR2pK_ProtocolErrorCode.InvalidParams, `Output validation error: Invalid structured content for tool ${toolName}: ${parseResult.error}`); - } - /** - * Executes a tool handler. - */ - async executeToolHandler(tool, args, ctx) { - return tool.executor(args, ctx); - } - _completionHandlerInitialized = false; - setCompletionRequestHandler() { - if (this._completionHandlerInitialized) return; - this.server.assertCanSetRequestHandler("completion/complete"); - this.server.registerCapabilities({ completions: {} }); - this.server.setRequestHandler("completion/complete", async (request) => { - switch (request.params.ref.type) { - case "ref/prompt": - assertCompleteRequestPrompt(request); - return this.handlePromptCompletion(request, request.params.ref); - case "ref/resource": - assertCompleteRequestResourceTemplate(request); - return this.handleResourceCompletion(request, request.params.ref); - default: throw new src_CX2iR2pK_ProtocolError(src_CX2iR2pK_ProtocolErrorCode.InvalidParams, `Invalid completion reference: ${request.params.ref}`); - } - }); - this._completionHandlerInitialized = true; - } - async handlePromptCompletion(request, ref) { - const prompt = this._registeredPrompts[ref.name]; - if (!prompt) throw new src_CX2iR2pK_ProtocolError(src_CX2iR2pK_ProtocolErrorCode.InvalidParams, `Prompt ${ref.name} not found`); - if (!prompt.enabled) throw new src_CX2iR2pK_ProtocolError(src_CX2iR2pK_ProtocolErrorCode.InvalidParams, `Prompt ${ref.name} disabled`); - if (!prompt.argsSchema) return EMPTY_COMPLETION_RESULT; - const field = unwrapOptionalSchema(getSchemaShape(prompt.argsSchema)?.[request.params.argument.name]); - if (!isCompletable(field)) return EMPTY_COMPLETION_RESULT; - const completer = getCompleter(field); - if (!completer) return EMPTY_COMPLETION_RESULT; - return createCompletionResult(await completer(request.params.argument.value, request.params.context)); - } - async handleResourceCompletion(request, ref) { - const template = Object.values(this._registeredResourceTemplates).find((t) => t.resourceTemplate.uriTemplate.toString() === ref.uri); - if (!template) { - if (this._registeredResources[ref.uri]) return EMPTY_COMPLETION_RESULT; - throw new src_CX2iR2pK_ProtocolError(src_CX2iR2pK_ProtocolErrorCode.InvalidParams, `Resource template ${request.params.ref.uri} not found`); - } - const completer = template.resourceTemplate.completeCallback(request.params.argument.name); - if (!completer) return EMPTY_COMPLETION_RESULT; - return createCompletionResult(await completer(request.params.argument.value, request.params.context)); - } - _resourceHandlersInitialized = false; - setResourceRequestHandlers() { - if (this._resourceHandlersInitialized) return; - this.server.assertCanSetRequestHandler("resources/list"); - this.server.assertCanSetRequestHandler("resources/templates/list"); - this.server.assertCanSetRequestHandler("resources/read"); - this.server.registerCapabilities({ resources: { listChanged: this.server.getCapabilities().resources?.listChanged ?? true } }); - this.server.setRequestHandler("resources/list", async (_request, ctx) => { - const resources = Object.entries(this._registeredResources).filter(([_, resource]) => resource.enabled).map(([uri, resource]) => ({ - uri, - name: resource.name, - ...resource.metadata - })); - const templateResources = []; - for (const template of Object.values(this._registeredResourceTemplates)) { - if (!template.resourceTemplate.listCallback) continue; - const result = await template.resourceTemplate.listCallback(ctx); - for (const resource of result.resources) templateResources.push({ - ...template.metadata, - ...resource - }); - } - return { resources: [...resources, ...templateResources] }; - }); - this.server.setRequestHandler("resources/templates/list", async () => { - return { resourceTemplates: Object.entries(this._registeredResourceTemplates).map(([name, template]) => ({ - name, - uriTemplate: template.resourceTemplate.uriTemplate.toString(), - ...template.metadata - })) }; - }); - this.server.setRequestHandler("resources/read", async (request, ctx) => { - let uri; - try { - uri = new URL(request.params.uri); - } catch { - throw new src_CX2iR2pK_ProtocolError(src_CX2iR2pK_ProtocolErrorCode.InvalidParams, `Resource URI ${request.params.uri} is invalid`, { - uri: request.params.uri, - reason: "invalid_uri" - }); - } - const resource = this._registeredResources[uri.toString()]; - if (resource) { - if (!resource.enabled) throw new src_CX2iR2pK_ProtocolError(src_CX2iR2pK_ProtocolErrorCode.InvalidParams, `Resource ${uri} disabled`); - return attachCacheHintFallback(await resource.readCallback(uri, ctx), resource.cacheHint); - } - for (const template of Object.values(this._registeredResourceTemplates)) { - const variables = template.resourceTemplate.uriTemplate.match(uri.toString()); - if (variables) return attachCacheHintFallback(await template.readCallback(uri, variables, ctx), template.cacheHint); - } - throw new ResourceNotFoundError(request.params.uri); - }); - this._resourceHandlersInitialized = true; - } - _promptHandlersInitialized = false; - setPromptRequestHandlers() { - if (this._promptHandlersInitialized) return; - this.server.assertCanSetRequestHandler("prompts/list"); - this.server.assertCanSetRequestHandler("prompts/get"); - this.server.registerCapabilities({ prompts: { listChanged: this.server.getCapabilities().prompts?.listChanged ?? true } }); - this.server.setRequestHandler("prompts/list", () => ({ prompts: Object.entries(this._registeredPrompts).filter(([, prompt]) => prompt.enabled).map(([name, prompt]) => { - return { - name, - title: prompt.title, - description: prompt.description, - arguments: prompt.argsSchema ? promptArgumentsFromStandardSchema(prompt.argsSchema) : void 0, - icons: prompt.icons, - _meta: prompt._meta - }; - }) })); - this.server.setRequestHandler("prompts/get", async (request, ctx) => { - const prompt = this._registeredPrompts[request.params.name]; - if (!prompt) throw new src_CX2iR2pK_ProtocolError(src_CX2iR2pK_ProtocolErrorCode.InvalidParams, `Prompt ${request.params.name} not found`); - if (!prompt.enabled) throw new src_CX2iR2pK_ProtocolError(src_CX2iR2pK_ProtocolErrorCode.InvalidParams, `Prompt ${request.params.name} disabled`); - return prompt.handler(request.params.arguments, ctx); - }); - this._promptHandlersInitialized = true; - } - registerResource(name, uriOrTemplate, config, readCallback) { - const cacheHint = config.cacheHint; - let metadata = config; - if (cacheHint !== void 0) { - assertValidCacheHint(cacheHint, `resource ${name}`); - const rest = { ...config }; - delete rest.cacheHint; - metadata = rest; - } - if (typeof uriOrTemplate === "string") { - if (this._registeredResources[uriOrTemplate]) throw new Error(`Resource ${uriOrTemplate} is already registered`); - const registeredResource = this._createRegisteredResource(name, config.title, uriOrTemplate, metadata, readCallback); - if (cacheHint !== void 0) registeredResource.cacheHint = cacheHint; - this.setResourceRequestHandlers(); - this.sendResourceListChanged(); - return registeredResource; - } else { - if (this._registeredResourceTemplates[name]) throw new Error(`Resource template ${name} is already registered`); - const registeredResourceTemplate = this._createRegisteredResourceTemplate(name, config.title, uriOrTemplate, metadata, readCallback); - if (cacheHint !== void 0) registeredResourceTemplate.cacheHint = cacheHint; - this.setResourceRequestHandlers(); - this.sendResourceListChanged(); - return registeredResourceTemplate; - } - } - _createRegisteredResource(name, title, uri, metadata, readCallback) { - const registeredResource = { - name, - title, - metadata, - readCallback, - enabled: true, - disable: () => registeredResource.update({ enabled: false }), - enable: () => registeredResource.update({ enabled: true }), - remove: () => registeredResource.update({ uri: null }), - update: (updates) => { - if (updates.uri !== void 0 && updates.uri !== uri) { - delete this._registeredResources[uri]; - if (updates.uri) this._registeredResources[updates.uri] = registeredResource; - } - if (updates.name !== void 0) registeredResource.name = updates.name; - if (updates.title !== void 0) registeredResource.title = updates.title; - if (updates.metadata !== void 0) registeredResource.metadata = updates.metadata; - if (updates.callback !== void 0) registeredResource.readCallback = updates.callback; - if (updates.enabled !== void 0) registeredResource.enabled = updates.enabled; - this.sendResourceListChanged(); - } - }; - this._registeredResources[uri] = registeredResource; - return registeredResource; - } - _createRegisteredResourceTemplate(name, title, template, metadata, readCallback) { - const registeredResourceTemplate = { - resourceTemplate: template, - title, - metadata, - readCallback, - enabled: true, - disable: () => registeredResourceTemplate.update({ enabled: false }), - enable: () => registeredResourceTemplate.update({ enabled: true }), - remove: () => registeredResourceTemplate.update({ name: null }), - update: (updates) => { - if (updates.name !== void 0 && updates.name !== name) { - delete this._registeredResourceTemplates[name]; - if (updates.name) this._registeredResourceTemplates[updates.name] = registeredResourceTemplate; - } - if (updates.title !== void 0) registeredResourceTemplate.title = updates.title; - if (updates.template !== void 0) registeredResourceTemplate.resourceTemplate = updates.template; - if (updates.metadata !== void 0) registeredResourceTemplate.metadata = updates.metadata; - if (updates.callback !== void 0) registeredResourceTemplate.readCallback = updates.callback; - if (updates.enabled !== void 0) registeredResourceTemplate.enabled = updates.enabled; - this.sendResourceListChanged(); - } - }; - this._registeredResourceTemplates[name] = registeredResourceTemplate; - const variableNames = template.uriTemplate.variableNames; - if (Array.isArray(variableNames) && variableNames.some((v) => !!template.completeCallback(v))) this.setCompletionRequestHandler(); - return registeredResourceTemplate; - } - _createRegisteredPrompt(name, title, description, argsSchema, callback, icons, _meta) { - let currentArgsSchema = argsSchema; - let currentCallback = callback; - const registeredPrompt = { - title, - description, - argsSchema, - icons, - _meta, - handler: createPromptHandler(name, argsSchema, callback), - enabled: true, - disable: () => registeredPrompt.update({ enabled: false }), - enable: () => registeredPrompt.update({ enabled: true }), - remove: () => registeredPrompt.update({ name: null }), - update: (updates) => { - if (updates.name !== void 0 && updates.name !== name) { - delete this._registeredPrompts[name]; - if (updates.name) this._registeredPrompts[updates.name] = registeredPrompt; - } - if (updates.title !== void 0) registeredPrompt.title = updates.title; - if (updates.description !== void 0) registeredPrompt.description = updates.description; - if (updates.icons !== void 0) registeredPrompt.icons = updates.icons; - if (updates._meta !== void 0) registeredPrompt._meta = updates._meta; - let needsHandlerRegen = false; - if (updates.argsSchema !== void 0) { - registeredPrompt.argsSchema = updates.argsSchema; - currentArgsSchema = updates.argsSchema; - needsHandlerRegen = true; - } - if (updates.callback !== void 0) { - currentCallback = updates.callback; - needsHandlerRegen = true; - } - if (needsHandlerRegen) registeredPrompt.handler = createPromptHandler(name, currentArgsSchema, currentCallback); - if (updates.enabled !== void 0) registeredPrompt.enabled = updates.enabled; - this.sendPromptListChanged(); - } - }; - this._registeredPrompts[name] = registeredPrompt; - if (argsSchema) { - const shape = getSchemaShape(argsSchema); - if (shape) { - if (Object.values(shape).some((field) => { - return isCompletable(unwrapOptionalSchema(field)); - })) this.setCompletionRequestHandler(); - } - } - return registeredPrompt; - } - _createRegisteredTool(name, title, description, inputSchema, outputSchema, annotations, icons, execution, _meta, handler) { - validateAndWarnToolName(name); - if (inputSchema !== void 0) try { - const json = standardSchemaToJsonSchema(inputSchema, "input"); - this._toolInputSchemaJson[name] = json; - const scan = src_CX2iR2pK_scanXMcpHeaderDeclarations(json); - if (!scan.valid) console.warn(`[mcp-sdk] tool '${name}' carries an invalid x-mcp-header declaration and will be excluded by conforming Streamable HTTP clients: ${scan.reason}`); - } catch {} - let currentHandler = handler; - const registeredTool = { - title, - description, - inputSchema, - outputSchema, - outputSchemaJson: convertOutputSchemaJson(outputSchema), - annotations, - icons, - execution, - _meta, - handler, - executor: createToolExecutor(inputSchema, handler), - enabled: true, - disable: () => registeredTool.update({ enabled: false }), - enable: () => registeredTool.update({ enabled: true }), - remove: () => registeredTool.update({ name: null }), - update: (updates) => { - if (updates.name !== void 0 && updates.name !== name) { - if (typeof updates.name === "string") validateAndWarnToolName(updates.name); - delete this._registeredTools[name]; - delete this._toolInputSchemaJson[name]; - if (updates.name) { - delete this._toolInputSchemaJson[updates.name]; - this._registeredTools[updates.name] = registeredTool; - name = updates.name; - } - } - if (updates.title !== void 0) registeredTool.title = updates.title; - if (updates.description !== void 0) registeredTool.description = updates.description; - let needsExecutorRegen = false; - if (updates.paramsSchema !== void 0) { - registeredTool.inputSchema = updates.paramsSchema; - delete this._toolInputSchemaJson[name]; - needsExecutorRegen = true; - } - if (updates.callback !== void 0) { - registeredTool.handler = updates.callback; - currentHandler = updates.callback; - needsExecutorRegen = true; - } - if (needsExecutorRegen) registeredTool.executor = createToolExecutor(registeredTool.inputSchema, currentHandler); - if (updates.outputSchema !== void 0) { - registeredTool.outputSchema = updates.outputSchema; - registeredTool.outputSchemaJson = convertOutputSchemaJson(updates.outputSchema); - } - if (updates.annotations !== void 0) registeredTool.annotations = updates.annotations; - if (updates.icons !== void 0) registeredTool.icons = updates.icons; - if (updates._meta !== void 0) registeredTool._meta = updates._meta; - if (updates.enabled !== void 0) registeredTool.enabled = updates.enabled; - this.sendToolListChanged(); - } - }; - this._registeredTools[name] = registeredTool; - this.setToolRequestHandlers(); - this.sendToolListChanged(); - return registeredTool; - } - registerTool(name, config, cb) { - if (this._registeredTools[name]) throw new Error(`Tool ${name} is already registered`); - const { title, description, inputSchema, outputSchema, annotations, icons, _meta } = config; - return this._createRegisteredTool(name, title, description, normalizeRawShapeSchema(inputSchema), normalizeRawShapeSchema(outputSchema), annotations, icons, void 0, _meta, cb); - } - registerPrompt(name, config, cb) { - if (this._registeredPrompts[name]) throw new Error(`Prompt ${name} is already registered`); - const { title, description, argsSchema, icons, _meta } = config; - const registeredPrompt = this._createRegisteredPrompt(name, title, description, normalizeRawShapeSchema(argsSchema), cb, icons, _meta); - this.setPromptRequestHandlers(); - this.sendPromptListChanged(); - return registeredPrompt; - } - /** - * Checks if the server is connected to a transport. - * @returns `true` if the server is connected - */ - isConnected() { - return this.server.transport !== void 0; - } - /** - * Sends a logging message to the client, if connected. - * Note: You only need to send the parameters object, not the entire JSON-RPC message. - * @see {@linkcode LoggingMessageNotification} - * @param params - * @param sessionId Optional for stateless transports and backward compatibility. - * - * @example - * ```ts source="./mcp.examples.ts#McpServer_sendLoggingMessage_basic" - * await server.sendLoggingMessage({ - * level: 'info', - * data: 'Processing complete' - * }); - * ``` - * - * @deprecated Deprecated as of protocol version 2026-07-28 (SEP-2577). - * Remains functional during the deprecation window (at least twelve months). - * Migrate to stderr logging (STDIO servers) or OpenTelemetry. - */ - async sendLoggingMessage(params, sessionId) { - return this.server.sendLoggingMessage(params, sessionId); - } - /** - * Sends a resource list changed event to the client, if connected. - */ - sendResourceListChanged() { - if (this.isConnected()) this.server.sendResourceListChanged(); - } - /** - * Sends a tool list changed event to the client, if connected. - */ - sendToolListChanged() { - if (this.isConnected()) this.server.sendToolListChanged(); - } - /** - * Sends a prompt list changed event to the client, if connected. - */ - sendPromptListChanged() { - if (this.isConnected()) this.server.sendPromptListChanged(); - } -}; -/** -* A resource template combines a URI pattern with optional functionality to enumerate -* all resources matching that pattern. -*/ -var ResourceTemplate = class { - _uriTemplate; - constructor(uriTemplate, _callbacks) { - this._callbacks = _callbacks; - this._uriTemplate = typeof uriTemplate === "string" ? new UriTemplate(uriTemplate) : uriTemplate; - } - /** - * Gets the URI template pattern. - */ - get uriTemplate() { - return this._uriTemplate; - } - /** - * Gets the list callback, if one was provided. - */ - get listCallback() { - return this._callbacks.list; - } - /** - * Gets the callback for completing a specific URI template variable, if one was provided. - */ - completeCallback(variable) { - return this._callbacks.complete?.[variable]; - } -}; -/** -* Creates an executor that invokes the handler with the appropriate arguments. -* When `inputSchema` is defined, the handler is called with `(args, ctx)`. -* When `inputSchema` is undefined, the handler is called with just `(ctx)`. -*/ -function createToolExecutor(inputSchema, handler) { - if (inputSchema) { - const callback$1 = handler; - return async (args, ctx) => callback$1(args, ctx); - } - const callback = handler; - return async (_args, ctx) => callback(ctx); -} -const EMPTY_OBJECT_JSON_SCHEMA = { - type: "object", - properties: {} -}; -/** -* Convert a registered `outputSchema` to JSON Schema, memoised on {@link RegisteredTool.outputSchemaJson} -* so `tools/call` passes the SAME advertised schema to the wire codec's `projectCallToolResult` that -* `tools/list` emits (and that the 2025 codec's `encodeResult('tools/list', …)` may wrap). A conversion -* failure yields `undefined` so the failure surfaces where it always has (`tools/list`). -*/ -function convertOutputSchemaJson(outputSchema) { - if (outputSchema === void 0) return void 0; - try { - return standardSchemaToJsonSchema(outputSchema, "output"); - } catch { - return; - } -} -/** -* Creates a type-safe prompt handler that captures the schema and callback in a closure. -* This eliminates the need for type assertions at the call site. -*/ -function createPromptHandler(name, argsSchema, callback) { - if (argsSchema) { - const typedCallback = callback; - return async (args, ctx) => { - const parseResult = await validateStandardSchema(argsSchema, args); - if (!parseResult.success) throw new src_CX2iR2pK_ProtocolError(src_CX2iR2pK_ProtocolErrorCode.InvalidParams, `Invalid arguments for prompt ${name}: ${parseResult.error}`); - return typedCallback(parseResult.data, ctx); - }; - } else { - const typedCallback = callback; - return async (_args, ctx) => { - return typedCallback(ctx); - }; - } -} -function createCompletionResult(suggestions) { - return { completion: { - values: suggestions.map(String).slice(0, 100), - total: suggestions.length, - hasMore: suggestions.length > 100 - } }; -} -const EMPTY_COMPLETION_RESULT = { completion: { - values: [], - hasMore: false -} }; -/** @internal Gets the shape of a Zod object schema */ -function getSchemaShape(schema) { - const candidate = schema; - if (candidate.shape && typeof candidate.shape === "object") return candidate.shape; -} -/** @internal Checks if a Zod schema is optional */ -function isOptionalSchema(schema) { - return schema?.type === "optional"; -} -/** @internal Unwraps an optional Zod schema */ -function unwrapOptionalSchema(schema) { - if (!isOptionalSchema(schema)) return schema; - return schema.def?.innerType ?? schema; -} - -//#endregion - -//# sourceMappingURL=mcp-DXXb3Vv3.mjs.map - - - - -//#region src/server/perRequestTransport.ts -/** -* The per-request micro-transport: a real, connected `Transport` whose whole -* lifetime is one HTTP exchange. See the module documentation for the -* response shapes it produces. -*/ -var PerRequestHTTPServerTransport = class { - onclose; - onerror; - onmessage; - _classification; - _responseMode; - _started = false; - _used = false; - _closed = false; - _terminalDelivered = false; - /** - * `true` only while the inbound message is being delivered synchronously - * to the connected protocol layer. The pre-handler gates (the era - * registry gate, the edge→instance handoff check, the missing-handler - * rejection) answer inside this window; request handlers always run - * after it (the protocol layer defers them to a microtask). An error - * sent inside the window is therefore ladder-originated, and an error - * sent after it is handler-produced. - */ - _dispatchWindowOpen = false; - _requestId; - _deferredResponse; - _sse; - _abortCleanup; - _keepAliveMs; - constructor(options) { - this._classification = options.classification; - this._responseMode = options.responseMode ?? "auto"; - this._keepAliveMs = options.keepAliveMs ?? DEFAULT_SSE_KEEP_ALIVE_MS; - } - async start() { - if (this._started) throw new Error("PerRequestHTTPServerTransport is already started"); - this._started = true; - } - /** - * Serves the single exchange: delivers the classified message to the - * connected server instance and resolves with the HTTP response. - * - * Throws when called a second time (the transport is strictly - * single-use), or before a server has been connected to the transport. - * The returned promise rejects with a connection-closed error when the - * transport is closed before a response was produced (for example because - * the client disconnected). - */ - async handleMessage(message, extra) { - if (this._used) throw new Error("PerRequestHTTPServerTransport serves exactly one exchange; construct a new transport per request"); - if (!this._started || this.onmessage === void 0) throw new Error("PerRequestHTTPServerTransport is not connected: connect a server to this transport before handling a message"); - if (this._closed) throw new Error("PerRequestHTTPServerTransport is closed"); - this._used = true; - const signal = extra?.request?.signal; - if (signal?.aborted) { - await this.close(); - throw new SdkError(SdkErrorCode.ConnectionClosed, "The request was aborted before it could be handled"); - } - const messageExtra = { - classification: this._classification, - ...extra?.request !== void 0 && { request: extra.request }, - ...extra?.authInfo !== void 0 && { authInfo: extra.authInfo } - }; - if (isJSONRPCRequest(message)) { - this._requestId = message.id; - let resolve; - let reject; - const promise = new Promise((promiseResolve, promiseReject) => { - resolve = promiseResolve; - reject = promiseReject; - }); - this._deferredResponse = { - promise, - resolve, - reject, - settled: false - }; - if (signal !== void 0) { - const onAbort = () => void this.close(); - signal.addEventListener("abort", onAbort, { once: true }); - this._abortCleanup = () => signal.removeEventListener("abort", onAbort); - } - this._dispatchWindowOpen = true; - try { - this.onmessage(message, messageExtra); - } finally { - this._dispatchWindowOpen = false; - } - if (this._responseMode === "sse" && !this._closed && !this._deferredResponse.settled) this.upgradeToSse(); - return promise; - } - this.onmessage(message, messageExtra); - return new Response(null, { status: 202 }); - } - async send(message, options) { - if (this._closed) return; - const isResponse = isJSONRPCResultResponse(message) || isJSONRPCErrorResponse(message); - const relatedId = isResponse ? message.id : options?.relatedRequestId; - if (this._requestId === void 0 || relatedId === void 0 || relatedId !== this._requestId) { - if (isResponse) this.onerror?.(/* @__PURE__ */ new Error(`Received a response for an unknown request id: ${String(message.id)}`)); - return; - } - if (isResponse) { - if (this._terminalDelivered) return; - this._terminalDelivered = true; - const errorCode = isJSONRPCErrorResponse(message) ? message.error.code : void 0; - const ladderStatus = errorCode !== void 0 && (this._dispatchWindowOpen || errorCode === ProtocolErrorCode.MissingRequiredClientCapability) ? LADDER_ERROR_HTTP_STATUS[errorCode] : void 0; - if (ladderStatus !== void 0 && this._sse === void 0) { - this.settleResponse(Response.json(message, { - status: ladderStatus, - headers: { "Content-Type": "application/json" } - })); - queueMicrotask(() => void this.close()); - return; - } - if (this._sse !== void 0 || this._responseMode === "sse") { - if (this._sse === void 0) this.upgradeToSse(); - this.writeMessageFrame(message); - this.finalizeStream(); - return; - } - this.settleResponse(Response.json(message, { - status: 200, - headers: { "Content-Type": "application/json" } - })); - queueMicrotask(() => void this.close()); - return; - } - if (this._responseMode === "json") return; - if (this._sse === void 0) this.upgradeToSse(); - this.writeMessageFrame(message); - } - /** - * Writes an SSE comment frame (a keep-alive heartbeat). Dropped when the - * exchange is not currently streaming. - */ - writeCommentFrame(comment) { - if (this._closed || this._sse === void 0 || this._sse.closed) return; - const frame = comment.split("\n").map((line) => `: ${line}`).join("\n"); - this.writeFrame(`${frame}\n\n`); - } - async close() { - if (this._closed) return; - this._closed = true; - this._abortCleanup?.(); - this._abortCleanup = void 0; - if (this._sse?.keepAliveTimer !== void 0) clearInterval(this._sse.keepAliveTimer); - if (this._sse !== void 0 && !this._sse.closed) { - this._sse.closed = true; - try { - this._sse.controller.close(); - } catch {} - } - if (this._deferredResponse !== void 0 && !this._deferredResponse.settled) { - this._deferredResponse.settled = true; - this._deferredResponse.reject(new SdkError(SdkErrorCode.ConnectionClosed, "Connection closed before a response was produced")); - } - this.onclose?.(); - } - settleResponse(response) { - if (this._deferredResponse === void 0 || this._deferredResponse.settled) return; - this._deferredResponse.settled = true; - this._deferredResponse.resolve(response); - } - upgradeToSse() { - let controller; - const readable = new ReadableStream({ - start: (streamController) => { - controller = streamController; - }, - cancel: () => { - this.close(); - } - }); - this._sse = { - controller, - encoder: new TextEncoder(), - closed: false - }; - this._sse.keepAliveTimer = armSseKeepAlive(this._keepAliveMs, () => this.writeCommentFrame("keepalive")); - this.settleResponse(new Response(readable, { - status: 200, - headers: { - "Content-Type": "text/event-stream", - "Cache-Control": "no-cache, no-transform", - Connection: "keep-alive", - "X-Accel-Buffering": "no" - } - })); - } - finalizeStream() { - if (this._sse?.keepAliveTimer !== void 0) clearInterval(this._sse.keepAliveTimer); - if (this._sse !== void 0 && !this._sse.closed) { - this._sse.closed = true; - try { - this._sse.controller.close(); - } catch {} - } - queueMicrotask(() => void this.close()); - } - writeMessageFrame(message) { - this.writeFrame(`event: message\ndata: ${JSON.stringify(message)}\n\n`); - } - writeFrame(frame) { - if (this._sse === void 0 || this._sse.closed) return; - try { - this._sse.controller.enqueue(this._sse.encoder.encode(frame)); - } catch (error) { - this.onerror?.(/* @__PURE__ */ new Error(`Failed to write to the response stream: ${error}`)); - } - } -}; - -//#endregion -//#region src/server/invoke.ts -/** -* Serves one classified inbound message on the given server instance and -* returns the HTTP response for the exchange. -* -* The instance is connected to a fresh single-exchange transport, the message -* is injected through the normal transport message path, and whatever the -* dispatch layer produces (the handler result, a protocol-level rejection, or -* streamed related messages followed by the result) is captured as the -* returned `Response`. For request exchanges, teardown rides the transport's -* close chain once the terminal response has been delivered; notification -* exchanges resolve with the 202 response immediately and do NOT run the -* close chain — the transport stays connected until the caller closes it or -* drops the per-request instance, which is the caller's choice either way. -*/ -async function invoke(server, message, ctx) { - const transport = new PerRequestHTTPServerTransport({ - classification: ctx.classification, - ...ctx.responseMode !== void 0 && { responseMode: ctx.responseMode }, - ...ctx.keepAliveMs !== void 0 && { keepAliveMs: ctx.keepAliveMs } - }); - await server.connect(transport); - return transport.handleMessage(message, { - ...ctx.request !== void 0 && { request: ctx.request }, - ...ctx.authInfo !== void 0 && { authInfo: ctx.authInfo } - }); -} - -//#endregion -//#region src/server/streamableHttp.ts -/** -* Server transport for Web Standards Streamable HTTP: this implements the MCP Streamable HTTP transport specification -* using Web Standard APIs (`Request`, `Response`, `ReadableStream`). -* -* This transport works on any runtime that supports Web Standards: Node.js 18+, Cloudflare Workers, Deno, Bun, etc. -* -* In stateful mode: -* - Session ID is generated and included in response headers -* - Session ID is always included in initialization responses -* - Requests with invalid session IDs are rejected with `404 Not Found` -* - Non-initialization requests without a session ID are rejected with `400 Bad Request` -* - State is maintained in-memory (connections, message history) -* -* In stateless mode: -* - No Session ID is included in any responses -* - No session validation is performed -* -* @example Stateful setup -* ```ts source="./streamableHttp.examples.ts#WebStandardStreamableHTTPServerTransport_stateful" -* const server = new McpServer({ name: 'my-server', version: '1.0.0' }); -* -* const transport = new WebStandardStreamableHTTPServerTransport({ -* sessionIdGenerator: () => crypto.randomUUID() -* }); -* -* await server.connect(transport); -* ``` -* -* @example Stateless setup -* ```ts source="./streamableHttp.examples.ts#WebStandardStreamableHTTPServerTransport_stateless" -* const transport = new WebStandardStreamableHTTPServerTransport({ -* sessionIdGenerator: undefined -* }); -* ``` -* -* @example Hono.js -* ```ts source="./streamableHttp.examples.ts#WebStandardStreamableHTTPServerTransport_hono" -* app.all('/mcp', async c => { -* return transport.handleRequest(c.req.raw); -* }); -* ``` -* -* @example Cloudflare Workers -* ```ts source="./streamableHttp.examples.ts#WebStandardStreamableHTTPServerTransport_workers" -* const worker = { -* async fetch(request: Request): Promise { -* return transport.handleRequest(request); -* } -* }; -* ``` -*/ -var WebStandardStreamableHTTPServerTransport = class { - sessionIdGenerator; - _started = false; - _closed = false; - _streamMapping = /* @__PURE__ */ new Map(); - _requestToStreamMapping = /* @__PURE__ */ new Map(); - _requestResponseMap = /* @__PURE__ */ new Map(); - _initialized = false; - _enableJsonResponse = false; - _standaloneSseStreamId = "_GET_stream"; - _eventStore; - _onsessioninitialized; - _onsessionclosed; - _allowedHosts; - _allowedOrigins; - _enableDnsRebindingProtection; - _retryInterval; - _supportedProtocolVersions; - _keepAliveMs; - sessionId; - onclose; - onerror; - onmessage; - constructor(options = {}) { - this.sessionIdGenerator = options.sessionIdGenerator; - this._enableJsonResponse = options.enableJsonResponse ?? false; - this._eventStore = options.eventStore; - this._onsessioninitialized = options.onsessioninitialized; - this._onsessionclosed = options.onsessionclosed; - this._allowedHosts = options.allowedHosts; - this._allowedOrigins = options.allowedOrigins; - this._enableDnsRebindingProtection = options.enableDnsRebindingProtection ?? false; - this._retryInterval = options.retryInterval; - this._supportedProtocolVersions = options.supportedProtocolVersions ?? SUPPORTED_PROTOCOL_VERSIONS; - this._keepAliveMs = options.keepAliveMs ?? DEFAULT_SSE_KEEP_ALIVE_MS; - } - startKeepAlive(controller, encoder) { - if (this._closed) return void 0; - const timer = armSseKeepAlive(this._keepAliveMs, () => { - try { - controller.enqueue(encoder.encode(": keepalive\n\n")); - } catch { - if (timer !== void 0) clearInterval(timer); - } - }); - return timer; - } - /** - * Starts the transport. This is required by the {@linkcode Transport} interface but is a no-op - * for the Streamable HTTP transport as connections are managed per-request. - */ - async start() { - if (this._started) throw new Error("Transport already started"); - this._started = true; - } - /** - * Sets the supported protocol versions for header validation. - * Called by the server during {@linkcode server/server.Server.connect | connect()} to pass its supported versions. - */ - setSupportedProtocolVersions(versions) { - this._supportedProtocolVersions = versions; - } - /** - * Helper to create a JSON error response - */ - createJsonErrorResponse(status, code, message, options) { - const error = { - code, - message - }; - if (options?.data !== void 0) error.data = options.data; - return Response.json({ - jsonrpc: "2.0", - error, - id: null - }, { - status, - headers: { - "Content-Type": "application/json", - ...options?.headers - } - }); - } - /** - * Validates request headers for DNS rebinding protection. - * @returns Error response if validation fails, `undefined` if validation passes. - */ - validateRequestHeaders(req) { - if (!this._enableDnsRebindingProtection) return; - if (this._allowedHosts && this._allowedHosts.length > 0) { - const hostHeader = req.headers.get("host"); - if (!hostHeader || !this._allowedHosts.includes(hostHeader)) { - const error = `Invalid Host header: ${hostHeader}`; - this.onerror?.(new Error(error)); - return this.createJsonErrorResponse(403, -32e3, error); - } - } - if (this._allowedOrigins && this._allowedOrigins.length > 0) { - const originHeader = req.headers.get("origin"); - if (originHeader && !this._allowedOrigins.includes(originHeader)) { - const error = `Invalid Origin header: ${originHeader}`; - this.onerror?.(new Error(error)); - return this.createJsonErrorResponse(403, -32e3, error); - } - } - } - /** - * Handles an incoming HTTP request, whether `GET`, `POST`, or `DELETE` - * Returns a `Response` object (Web Standard) - */ - async handleRequest(req, options) { - if (this._closed) return this.createJsonErrorResponse(404, -32001, "Session not found"); - const validationError = this.validateRequestHeaders(req); - if (validationError) return validationError; - switch (req.method) { - case "POST": return this.handlePostRequest(req, options); - case "GET": return this.handleGetRequest(req); - case "DELETE": return this.handleDeleteRequest(req); - default: return this.handleUnsupportedRequest(); - } - } - /** - * Returns true if the client's protocol version supports empty SSE data in - * priming events (the fix shipped with protocol version `2025-11-25`). - * - * The version is checked for membership in this transport instance's - * supported protocol versions rather than with an open-ended - * `>= '2025-11-25'` comparison: the value may come from an `initialize` - * request body, which (unlike the `MCP-Protocol-Version` header) is not - * validated against `supportedProtocolVersions` before reaching this - * check. An unknown future version string must not silently enable - * behavior reserved for versions this transport actually supports. - */ - supportsEmptySSEData(protocolVersion) { - return this._supportedProtocolVersions.includes(protocolVersion) && protocolVersion >= "2025-11-25"; - } - /** - * Writes a priming event to establish resumption capability. - * Only sends if `eventStore` is configured (opt-in for resumability) and - * the client's protocol version supports empty SSE data (a supported - * version that is >= `2025-11-25`). - */ - async writePrimingEvent(controller, encoder, streamId, protocolVersion) { - if (!this._eventStore) return; - if (!this.supportsEmptySSEData(protocolVersion)) return; - const primingEventId = await this._eventStore.storeEvent(streamId, {}); - let primingEvent = `id: ${primingEventId}\ndata: \n\n`; - if (this._retryInterval !== void 0) primingEvent = `id: ${primingEventId}\nretry: ${this._retryInterval}\ndata: \n\n`; - controller.enqueue(encoder.encode(primingEvent)); - } - /** - * Handles `GET` requests for SSE stream - */ - async handleGetRequest(req) { - if (!req.headers.get("accept")?.includes("text/event-stream")) { - this.onerror?.(/* @__PURE__ */ new Error("Not Acceptable: Client must accept text/event-stream")); - return this.createJsonErrorResponse(406, -32e3, "Not Acceptable: Client must accept text/event-stream"); - } - const sessionError = this.validateSession(req); - if (sessionError) return sessionError; - const protocolError = this.validateProtocolVersion(req); - if (protocolError) return protocolError; - if (this._eventStore) { - const lastEventId = req.headers.get("last-event-id"); - if (lastEventId) return this.replayEvents(lastEventId); - } - if (this._streamMapping.get(this._standaloneSseStreamId) !== void 0) { - this.onerror?.(/* @__PURE__ */ new Error("Conflict: Only one SSE stream is allowed per session")); - return this.createJsonErrorResponse(409, -32e3, "Conflict: Only one SSE stream is allowed per session"); - } - const encoder = new TextEncoder(); - let streamController; - let keepAliveTimer; - const readable = new ReadableStream({ - start: (controller) => { - streamController = controller; - }, - cancel: () => { - if (keepAliveTimer !== void 0) clearInterval(keepAliveTimer); - if (this._streamMapping.get(this._standaloneSseStreamId)?.controller === streamController) this._streamMapping.delete(this._standaloneSseStreamId); - } - }); - const headers = { - "Content-Type": "text/event-stream", - "Cache-Control": "no-cache, no-transform", - Connection: "keep-alive", - "X-Accel-Buffering": "no" - }; - if (this.sessionId !== void 0) headers["mcp-session-id"] = this.sessionId; - this._streamMapping.set(this._standaloneSseStreamId, { - controller: streamController, - encoder, - cleanup: () => { - if (keepAliveTimer !== void 0) clearInterval(keepAliveTimer); - this._streamMapping.delete(this._standaloneSseStreamId); - try { - streamController.close(); - } catch {} - } - }); - keepAliveTimer = this.startKeepAlive(streamController, encoder); - return new Response(readable, { headers }); - } - /** - * Replays events that would have been sent after the specified event ID - * Only used when resumability is enabled - */ - async replayEvents(lastEventId) { - if (!this._eventStore) { - this.onerror?.(/* @__PURE__ */ new Error("Event store not configured")); - return this.createJsonErrorResponse(400, -32e3, "Event store not configured"); - } - try { - let streamId; - if (this._eventStore.getStreamIdForEventId) { - streamId = await this._eventStore.getStreamIdForEventId(lastEventId); - if (!streamId) { - this.onerror?.(/* @__PURE__ */ new Error("Invalid event ID format")); - return this.createJsonErrorResponse(400, -32e3, "Invalid event ID format"); - } - if (this._streamMapping.get(streamId) !== void 0) { - this.onerror?.(/* @__PURE__ */ new Error("Conflict: Stream already has an active connection")); - return this.createJsonErrorResponse(409, -32e3, "Conflict: Stream already has an active connection"); - } - } - const headers = { - "Content-Type": "text/event-stream", - "Cache-Control": "no-cache, no-transform", - Connection: "keep-alive", - "X-Accel-Buffering": "no" - }; - if (this.sessionId !== void 0) headers["mcp-session-id"] = this.sessionId; - const encoder = new TextEncoder(); - let streamController; - let keepAliveTimer; - let cancelled = false; - let replayedStreamId; - const readable = new ReadableStream({ - start: (controller) => { - streamController = controller; - }, - cancel: () => { - cancelled = true; - if (keepAliveTimer !== void 0) clearInterval(keepAliveTimer); - if (replayedStreamId !== void 0 && this._streamMapping.get(replayedStreamId)?.controller === streamController) this._streamMapping.delete(replayedStreamId); - } - }); - const replayedEventIds = /* @__PURE__ */ new Set(); - replayedStreamId = await this._eventStore.replayEventsAfter(lastEventId, { send: async (eventId, message) => { - replayedEventIds.add(eventId); - if (!this.writeSSEEvent(streamController, encoder, message, eventId)) try { - streamController.close(); - } catch {} - } }); - if (this._closed || cancelled) { - try { - streamController.close(); - } catch {} - return this.createJsonErrorResponse(404, -32001, "Session not found"); - } - this._streamMapping.get(replayedStreamId)?.cleanup(); - this._streamMapping.set(replayedStreamId, { - controller: streamController, - encoder, - replayedEventIds, - cleanup: () => { - if (keepAliveTimer !== void 0) clearInterval(keepAliveTimer); - this._streamMapping.delete(replayedStreamId); - try { - streamController.close(); - } catch {} - } - }); - if (replayedStreamId !== this._standaloneSseStreamId) { - if (![...this._requestToStreamMapping.values()].includes(replayedStreamId)) { - this._streamMapping.delete(replayedStreamId); - try { - streamController.close(); - } catch {} - } - } - if (this._streamMapping.get(replayedStreamId)?.controller === streamController) keepAliveTimer = this.startKeepAlive(streamController, encoder); - return new Response(readable, { headers }); - } catch (error) { - this.onerror?.(error); - return this.createJsonErrorResponse(500, -32e3, "Error replaying events"); - } - } - /** - * Writes an event to an SSE stream via controller with proper formatting - */ - writeSSEEvent(controller, encoder, message, eventId) { - try { - let eventData = `event: message\n`; - if (eventId) eventData += `id: ${eventId}\n`; - eventData += `data: ${JSON.stringify(message)}\n\n`; - controller.enqueue(encoder.encode(eventData)); - return true; - } catch (error) { - this.onerror?.(error); - return false; - } - } - /** - * Handles unsupported requests (`PUT`, `PATCH`, etc.) - */ - handleUnsupportedRequest() { - this.onerror?.(/* @__PURE__ */ new Error("Method not allowed.")); - return Response.json({ - jsonrpc: "2.0", - error: { - code: -32e3, - message: "Method not allowed." - }, - id: null - }, { - status: 405, - headers: { - Allow: "GET, POST, DELETE", - "Content-Type": "application/json" - } - }); - } - /** - * Handles `POST` requests containing JSON-RPC messages - */ - async handlePostRequest(req, options) { - try { - const acceptHeader = req.headers.get("accept"); - if (!acceptHeader?.includes("application/json") || !acceptHeader.includes("text/event-stream")) { - this.onerror?.(/* @__PURE__ */ new Error("Not Acceptable: Client must accept both application/json and text/event-stream")); - return this.createJsonErrorResponse(406, -32e3, "Not Acceptable: Client must accept both application/json and text/event-stream"); - } - if (!isJsonContentType(req.headers.get("content-type"))) { - this.onerror?.(/* @__PURE__ */ new Error("Unsupported Media Type: Content-Type must be application/json")); - return this.createJsonErrorResponse(415, -32e3, "Unsupported Media Type: Content-Type must be application/json"); - } - const request = req; - let rawMessage; - if (options?.parsedBody === void 0) try { - rawMessage = await req.json(); - } catch (error) { - this.onerror?.(error); - return this.createJsonErrorResponse(400, -32700, "Parse error: Invalid JSON"); - } - else rawMessage = options.parsedBody; - let messages; - try { - messages = Array.isArray(rawMessage) ? rawMessage.map((msg) => JSONRPCMessageSchema.parse(msg)) : [JSONRPCMessageSchema.parse(rawMessage)]; - } catch (error) { - this.onerror?.(error); - return this.createJsonErrorResponse(400, -32700, "Parse error: Invalid JSON-RPC message"); - } - if (this._closed) return this.createJsonErrorResponse(404, -32001, "Session not found"); - const isInitializationRequest = messages.some((element) => isInitializeRequest(element)); - if (isInitializationRequest) { - if (this._initialized && this.sessionId !== void 0) { - this.onerror?.(/* @__PURE__ */ new Error("Invalid Request: Server already initialized")); - return this.createJsonErrorResponse(400, -32600, "Invalid Request: Server already initialized"); - } - if (messages.length > 1) { - this.onerror?.(/* @__PURE__ */ new Error("Invalid Request: Only one initialization request is allowed")); - return this.createJsonErrorResponse(400, -32600, "Invalid Request: Only one initialization request is allowed"); - } - this.sessionId = this.sessionIdGenerator?.(); - this._initialized = true; - if (this.sessionId && this._onsessioninitialized) await Promise.resolve(this._onsessioninitialized(this.sessionId)); - } - if (!isInitializationRequest) { - const sessionError = this.validateSession(req); - if (sessionError) return sessionError; - const protocolError = this.validateProtocolVersion(req); - if (protocolError) return protocolError; - } - if (this._closed) return this.createJsonErrorResponse(404, -32001, "Session not found"); - if (!messages.some((element) => isJSONRPCRequest(element))) { - for (const message of messages) this.onmessage?.(message, { - authInfo: options?.authInfo, - request - }); - return new Response(null, { status: 202 }); - } - const streamId = crypto.randomUUID(); - const initRequest = messages.find((m) => isInitializeRequest(m)); - const clientProtocolVersion = initRequest ? initRequest.params.protocolVersion : req.headers.get("mcp-protocol-version") ?? DEFAULT_NEGOTIATED_PROTOCOL_VERSION; - if (this._enableJsonResponse) return new Promise((resolve) => { - this._streamMapping.set(streamId, { - resolveJson: resolve, - cleanup: () => { - this._streamMapping.delete(streamId); - } - }); - for (const message of messages) if (isJSONRPCRequest(message)) this._requestToStreamMapping.set(message.id, streamId); - for (const message of messages) this.onmessage?.(message, { - authInfo: options?.authInfo, - request - }); - }); - const encoder = new TextEncoder(); - let streamController; - let keepAliveTimer; - const readable = new ReadableStream({ - start: (controller) => { - streamController = controller; - }, - cancel: () => { - if (keepAliveTimer !== void 0) clearInterval(keepAliveTimer); - if (this._streamMapping.get(streamId)?.controller === streamController) this._streamMapping.delete(streamId); - } - }); - const headers = { - "Content-Type": "text/event-stream", - "Cache-Control": "no-cache, no-transform", - Connection: "keep-alive", - "X-Accel-Buffering": "no" - }; - if (this.sessionId !== void 0) headers["mcp-session-id"] = this.sessionId; - for (const message of messages) if (isJSONRPCRequest(message)) { - this._streamMapping.set(streamId, { - controller: streamController, - encoder, - cleanup: () => { - if (keepAliveTimer !== void 0) clearInterval(keepAliveTimer); - this._streamMapping.delete(streamId); - try { - streamController.close(); - } catch {} - } - }); - this._requestToStreamMapping.set(message.id, streamId); - } - await this.writePrimingEvent(streamController, encoder, streamId, clientProtocolVersion); - for (const message of messages) { - let closeSSEStream; - let closeStandaloneSSEStream; - if (isJSONRPCRequest(message) && this._eventStore && this.supportsEmptySSEData(clientProtocolVersion)) { - closeSSEStream = () => { - this.closeSSEStream(message.id); - }; - closeStandaloneSSEStream = () => { - this.closeStandaloneSSEStream(); - }; - } - this.onmessage?.(message, { - authInfo: options?.authInfo, - request, - closeSSEStream, - closeStandaloneSSEStream - }); - } - if (this._streamMapping.get(streamId)?.controller === streamController) keepAliveTimer = this.startKeepAlive(streamController, encoder); - return new Response(readable, { - status: 200, - headers - }); - } catch (error) { - this.onerror?.(error); - return this.createJsonErrorResponse(400, -32700, "Parse error", { data: String(error) }); - } - } - /** - * Handles `DELETE` requests to terminate sessions - */ - async handleDeleteRequest(req) { - const sessionError = this.validateSession(req); - if (sessionError) return sessionError; - const protocolError = this.validateProtocolVersion(req); - if (protocolError) return protocolError; - try { - await Promise.resolve(this._onsessionclosed?.(this.sessionId)); - return new Response(null, { status: 200 }); - } finally { - await this.close(); - } - } - /** - * Validates session ID for non-initialization requests. - * Returns `Response` error if invalid, `undefined` otherwise - */ - validateSession(req) { - if (this.sessionIdGenerator === void 0) return; - if (!this._initialized) { - this.onerror?.(/* @__PURE__ */ new Error("Bad Request: Server not initialized")); - return this.createJsonErrorResponse(400, -32e3, "Bad Request: Server not initialized"); - } - const sessionId = req.headers.get("mcp-session-id"); - if (!sessionId) { - this.onerror?.(/* @__PURE__ */ new Error("Bad Request: Mcp-Session-Id header is required")); - return this.createJsonErrorResponse(400, -32e3, "Bad Request: Mcp-Session-Id header is required"); - } - if (sessionId !== this.sessionId) { - this.onerror?.(/* @__PURE__ */ new Error("Session not found")); - return this.createJsonErrorResponse(404, -32001, "Session not found"); - } - } - /** - * Validates the `MCP-Protocol-Version` header on incoming requests. - * - * For initialization: Version negotiation handles unknown versions gracefully - * (server responds with its supported version). - * - * For subsequent requests with `MCP-Protocol-Version` header: - * - Accept if in supported list - * - 400 if unsupported - * - * For HTTP requests without the `MCP-Protocol-Version` header: - * - Accept and default to the version negotiated at initialization - */ - validateProtocolVersion(req) { - const protocolVersion = req.headers.get("mcp-protocol-version"); - if (protocolVersion !== null && !this._supportedProtocolVersions.includes(protocolVersion)) { - const error = `Bad Request: Unsupported protocol version: ${protocolVersion} (supported versions: ${this._supportedProtocolVersions.join(", ")})`; - this.onerror?.(new Error(error)); - return this.createJsonErrorResponse(400, -32e3, error); - } - } - async close() { - if (this._closed) return; - this._closed = true; - for (const { cleanup } of this._streamMapping.values()) cleanup(); - this._streamMapping.clear(); - this._requestResponseMap.clear(); - this.onclose?.(); - } - /** - * Close an SSE stream for a specific request, triggering client reconnection. - * Use this to implement polling behavior during long-running operations - - * client will reconnect after the retry interval specified in the priming event. - */ - closeSSEStream(requestId) { - const streamId = this._requestToStreamMapping.get(requestId); - if (!streamId) return; - const stream = this._streamMapping.get(streamId); - if (stream) stream.cleanup(); - } - /** - * Close the standalone `GET` SSE stream, triggering client reconnection. - * Use this to implement polling behavior for server-initiated notifications. - */ - closeStandaloneSSEStream() { - const stream = this._streamMapping.get(this._standaloneSseStreamId); - if (stream) stream.cleanup(); - } - async send(message, options) { - let requestId = options?.relatedRequestId; - if (isJSONRPCResultResponse(message) || isJSONRPCErrorResponse(message)) requestId = message.id; - if (requestId === void 0) { - if (isJSONRPCResultResponse(message) || isJSONRPCErrorResponse(message)) throw new Error("Cannot send a response on a standalone SSE stream unless resuming a previous client request"); - let eventId; - if (this._eventStore) eventId = await this._eventStore.storeEvent(this._standaloneSseStreamId, message); - const standaloneSse = this._streamMapping.get(this._standaloneSseStreamId); - if (standaloneSse === void 0) return; - if (standaloneSse.controller && standaloneSse.encoder && (eventId === void 0 || !standaloneSse.replayedEventIds?.has(eventId))) this.writeSSEEvent(standaloneSse.controller, standaloneSse.encoder, message, eventId); - return; - } - const streamId = this._requestToStreamMapping.get(requestId); - if (!streamId) throw new Error(`No connection established for request ID: ${String(requestId)}`); - let stream = this._streamMapping.get(streamId); - if (!this._enableJsonResponse) { - let eventId; - if (this._eventStore) { - eventId = await this._eventStore.storeEvent(streamId, message); - stream = this._streamMapping.get(streamId); - } - if (stream?.controller && stream?.encoder && (eventId === void 0 || !stream.replayedEventIds?.has(eventId))) this.writeSSEEvent(stream.controller, stream.encoder, message, eventId); - } - if (isJSONRPCResultResponse(message) || isJSONRPCErrorResponse(message)) { - this._requestResponseMap.set(requestId, message); - const relatedIds = [...this._requestToStreamMapping.entries()].filter(([_, sid]) => sid === streamId).map(([id]) => id); - if (relatedIds.every((id) => this._requestResponseMap.has(id))) { - if (!stream) { - if (this._enableJsonResponse) throw new Error(`No connection established for request ID: ${String(requestId)}`); - if (!this._eventStore) { - this.onerror?.(/* @__PURE__ */ new Error(`Response for request ID ${String(requestId)} is undeliverable: per-request stream is disconnected and no eventStore is configured`)); - for (const id of relatedIds) { - this._requestResponseMap.delete(id); - this._requestToStreamMapping.delete(id); - } - return; - } - for (const id of relatedIds) { - this._requestResponseMap.delete(id); - this._requestToStreamMapping.delete(id); - } - return; - } - if (this._enableJsonResponse && stream.resolveJson) { - const headers = { "Content-Type": "application/json" }; - if (this.sessionId !== void 0) headers["mcp-session-id"] = this.sessionId; - const responses = relatedIds.map((id) => this._requestResponseMap.get(id)); - if (responses.length === 1) stream.resolveJson(Response.json(responses[0], { - status: 200, - headers - })); - else stream.resolveJson(Response.json(responses, { - status: 200, - headers - })); - stream.cleanup(); - } else stream.cleanup(); - for (const id of relatedIds) { - this._requestResponseMap.delete(id); - this._requestToStreamMapping.delete(id); - } - } - } - } -}; - -//#endregion -//#region src/server/createMcpHandler.ts -/** -* The JSON-RPC id to echo on an entry-built error response: the body's `id` -* when the body is a single JSON-RPC request whose id is a string or number, -* `null` otherwise. Error responses must carry the id of the request they -* correspond to whenever it could be read; `null` is reserved for the cases -* where no single request id is determinable — unparseable bodies, body-less -* methods, notifications, posted responses and batch arrays. -*/ -function echoableRequestId(body) { - if (body === null || typeof body !== "object" || Array.isArray(body)) return null; - const { method, id } = body; - if (typeof method !== "string") return null; - return typeof id === "string" || typeof id === "number" ? id : null; -} -function jsonRpcErrorResponse(httpStatus, code, message, data, id = null) { - return Response.json({ - jsonrpc: "2.0", - error: { - code, - message, - ...data !== void 0 && { data } - }, - id - }, { status: httpStatus }); -} -function rejectionResponse(rejection, id = null) { - return jsonRpcErrorResponse(rejection.httpStatus, rejection.code, rejection.message, rejection.data, id); -} -function toError(value) { - return value instanceof Error ? value : new Error(String(value)); -} -function internalServerErrorResponse(id = null) { - return jsonRpcErrorResponse(500, -32603, "Internal server error", void 0, id); -} -/** -* The entry's default legacy serving (`legacy: 'stateless'`): per-request -* stateless serving of 2025-era traffic using the same factory as the modern -* path. Exported as a standalone building block for hand-wired compositions -* (for example mounting legacy stateless serving on its own route next to a -* strict modern endpoint). -* -* Each POST is served by a fresh instance from the factory connected to a -* fresh streamable HTTP transport constructed with only -* `sessionIdGenerator: undefined` — the established stateless idiom, unchanged. -* Because serving is per-request and stateless, GET and DELETE (2025 session -* operations) are answered with `405` / `Method not allowed.`, exactly like the -* canonical stateless example. -* -* The optional `onerror` callback receives factory and serving failures on -* this leg (reporting only — the response stays the 500 internal-error body). -* The entry passes its own `onerror` here when expanding the default, so -* legacy-leg failures are never silently swallowed. -*/ -function createLegacyStatelessFallback(factory, onerror, keepAliveMs) { - return async (request, options) => { - if (request.method.toUpperCase() !== "POST") return jsonRpcErrorResponse(405, -32e3, "Method not allowed."); - try { - const product = await factory({ - era: "legacy", - ...options?.authInfo !== void 0 && { authInfo: options.authInfo }, - requestInfo: request - }); - const transport = new WebStandardStreamableHTTPServerTransport({ - sessionIdGenerator: void 0, - ...keepAliveMs !== void 0 && { keepAliveMs } - }); - await product.connect(transport); - const teardown = () => { - transport.close().catch(() => {}); - product.close().catch(() => {}); - }; - request.signal?.addEventListener("abort", teardown, { once: true }); - const response = await transport.handleRequest(request, { - ...options?.authInfo !== void 0 && { authInfo: options.authInfo }, - ...options?.parsedBody !== void 0 && { parsedBody: options.parsedBody } - }); - if (response.body === null || mediaTypeEssence(response.headers.get("content-type")) !== "text/event-stream") { - teardown(); - return response; - } - const reader = response.body.getReader(); - let toreDown = false; - const completeExchange = () => { - if (!toreDown) { - toreDown = true; - teardown(); - } - }; - const monitoredBody = new ReadableStream({ - pull: async (controller) => { - try { - const { done, value } = await reader.read(); - if (done) { - completeExchange(); - controller.close(); - return; - } - if (value !== void 0) controller.enqueue(value); - } catch (error) { - completeExchange(); - controller.error(error); - } - }, - cancel: (reason) => { - completeExchange(); - return reader.cancel(reason).catch(() => {}); - } - }); - return new Response(monitoredBody, { - status: response.status, - statusText: response.statusText, - headers: response.headers - }); - } catch (error) { - try { - onerror?.(toError(error)); - } catch {} - return internalServerErrorResponse(echoableRequestId(options?.parsedBody)); - } - }; -} -function legacyStatelessFallback(factory, onerror) { - return createLegacyStatelessFallback(factory, onerror); -} -/** -* The entry's classification step: read the request body exactly once (unless -* a pre-parsed body is supplied) and classify the request with -* {@linkcode classifyInboundRequest}. This is the single code path behind both -* {@linkcode createMcpHandler}'s routing and the exported -* {@linkcode isLegacyRequest} predicate, so the two can never disagree. -* -* Pass `needsForward: false` when the caller never reads `forwardRequest` — -* the body-preserving clone is then skipped and `forwardRequest` is the -* (consumed) input request. -*/ -async function classifyEntryRequest(request, providedParsedBody, needsForward = true) { - const httpMethod = request.method.toUpperCase(); - let body; - let parsedBody = providedParsedBody; - let forwardRequest = request; - let unparseable = false; - if (httpMethod === "POST") { - if (parsedBody === void 0) { - if (needsForward) forwardRequest = request.clone(); - let bodyText; - try { - bodyText = await request.text(); - } catch { - return { step: "unreadable-body" }; - } - try { - body = bodyText.length === 0 ? void 0 : JSON.parse(bodyText); - } catch { - unparseable = true; - } - if (!unparseable && body !== void 0) parsedBody = body; - } else body = parsedBody; - if (unparseable || body === void 0) return { - step: "no-json-body", - forwardRequest - }; - } - return { - step: "classified", - outcome: classifyInboundRequest({ - httpMethod, - protocolVersionHeader: request.headers.get("mcp-protocol-version") ?? void 0, - mcpMethodHeader: request.headers.get("mcp-method") ?? void 0, - mcpNameHeader: request.headers.get("mcp-name") ?? void 0, - ...body !== void 0 && { body } - }), - body, - parsedBody, - forwardRequest - }; -} -/** -* Whether {@linkcode createMcpHandler} would route this request to its legacy -* (2025-era) serving rather than the modern (2026-07-28) path. -* -* Call it with just the request: `await isLegacyRequest(request)`. For a -* `POST` the body is read from an internal clone, so the request you pass -* stays fully readable for whichever handler you route it to — no second -* argument is needed. (In a Node `(req, res)` handler, build that `Request` -* with `toWebRequest(req)` from `@modelcontextprotocol/node`; behind a body -* parser, which has already drained the Node stream, build it as -* `toWebRequest(req, req.body)` so the bytes come from the parsed body — -* either way the predicate still takes just the request.) The optional -* `parsedBody` is a perf escape hatch for a body you already hold parsed: -* pass it and the predicate classifies from the value directly, reading and -* cloning nothing. It is needed, not just faster, when the request's own -* body was already read — the internal clone is then impossible (cloning a -* used body throws a `TypeError`), so such a single-argument call rejects -* instead of guessing. -* -* This is the entry's own classification step exported as a predicate — it -* runs exactly the code `createMcpHandler` runs to make the routing decision, -* not a re-implementation — so a hand-wired composition that branches on it -* can never disagree with the entry. It is classification only: hand-wired -* compositions must validate Content-Type themselves (415 for POSTs whose -* media type is not `application/json`, via {@linkcode isJsonContentType}) -* before dispatching either leg — routing the legacy leg into the SDK -* transports gets their built-in check, but a custom modern leg has none. Use it to keep an existing legacy -* deployment (for example a sessionful streamable HTTP wiring) serving 2025 -* traffic next to a strict modern endpoint, now that the entry has no -* handler-valued `legacy` option: -* -* ```ts -* import { createMcpHandler, isLegacyRequest } from '@modelcontextprotocol/server'; -* -* const modern = createMcpHandler(factory, { legacy: 'reject' }); -* -* export default { -* async fetch(request: Request): Promise { -* if (await isLegacyRequest(request)) { -* // e.g. an existing sessionful WebStandardStreamableHTTPServerTransport wiring -* return myExistingLegacyHandler(request); -* } -* return modern.fetch(request); -* } -* }; -* ``` -* -* Semantics (identical to the entry's routing): -* -* - Returns `true` only for requests with no per-request `_meta` envelope -* claim: claim-less POSTs (including the `initialize` handshake and 2025-era -* notification POSTs without a modern protocol-version header), body-less -* GET/DELETE session operations, all-legacy JSON-RPC batch arrays, posted -* JSON-RPC responses, and POSTs whose body is empty or not valid JSON. -* - Returns `false` for everything the modern path answers, including its -* validation-ladder rejections: a request carrying the envelope claim (even -* one naming a revision the endpoint does not serve — the modern path -* answers it with the unsupported-protocol-version error), a malformed -* envelope behind a present claim (answered `-32602`), a request whose -* `MCP-Protocol-Version` header names a modern revision but that lacks the -* envelope (`-32602`), and header/body mismatches (`-32020`). Consumers -* routing on the predicate must send `false` traffic to the modern handler, -* never to a legacy handler — the modern path owns those error answers. -* - `server/discover` probes sent by negotiating clients always carry the -* envelope claim, so they are never legacy; a hand-built claim-less POST to -* a method named `server/discover` has no claim and classifies legacy, -* exactly as the entry itself routes it. -*/ -async function isLegacyRequest(request, parsedBody) { - const classified = await classifyEntryRequest(parsedBody === void 0 && request.method.toUpperCase() === "POST" ? request.clone() : request, parsedBody, false); - return classified.step === "no-json-body" || classified.step === "classified" && classified.outcome.kind === "legacy"; -} -/** -* Creates an HTTP handler that serves the 2026-07-28 protocol revision from a -* per-request server factory and, by default, falls back to old-school -* stateless serving for 2025-era traffic. Pass `legacy: 'reject'` for a -* modern-only strict endpoint. -* -* Mounting: `handler.fetch` is the web-standard face (Cloudflare Workers, -* Deno, Bun, Hono's `c.req.raw`); for Express/Fastify/plain `node:http`, wrap -* the handler once with `toNodeHandler(handler)` from -* `@modelcontextprotocol/node`. When mounting bare on a fetch-native runtime, -* put Origin/Host validation in front of the handler — the entry itself is -* deliberately validation-free: -* -* ```ts -* import { hostHeaderValidationResponse, originValidationResponse, localhostAllowedHostnames, localhostAllowedOrigins } from '@modelcontextprotocol/server'; -* -* export default { -* async fetch(request: Request): Promise { -* const rejected = -* hostHeaderValidationResponse(request, localhostAllowedHostnames()) ?? -* originValidationResponse(request, localhostAllowedOrigins()); -* return rejected ?? handler.fetch(request); -* } -* }; -* ``` -* -* Use ONE factory for both legs: the same tools/resources/prompts definition -* backs the modern path and the stateless legacy fallback, so the two eras can -* never drift apart. To keep an existing legacy deployment (for example a -* sessionful streamable HTTP wiring) serving 2025 traffic instead of the -* stateless fallback, route in user land with {@linkcode isLegacyRequest} in -* front of a strict handler — see that predicate's documentation for the -* pattern. Power users composing transport-neutral routing can also use the -* exported building blocks directly: {@linkcode classifyInboundRequest} for -* the era decision and `PerRequestHTTPServerTransport` for single-exchange -* serving — such compositions must reject POSTs whose Content-Type media type -* is not `application/json` (415) before parsing the body, using -* {@linkcode isJsonContentType}; neither building block performs this -* validation itself. -* -* The entry performs no token verification: `authInfo` given to `fetch` is -* passed through to handlers and the factory as-is and is never derived from -* request headers. -*/ -function createMcpHandler(factory, options = {}) { - const { legacy, onerror, responseMode } = options; - if (typeof legacy === "function") throw new TypeError("The 'legacy' option only accepts 'stateless' or 'reject', not a handler function. To serve 2025-era traffic with your own handler, route in user land with the exported isLegacyRequest(request) predicate in front of a strict (legacy: 'reject') handler."); - /** Modern per-request instances with an exchange still in flight (close() tears these down). */ - const inflight = /* @__PURE__ */ new Set(); - let closed = false; - const reportError = (error) => { - try { - onerror?.(error); - } catch {} - }; - const bus = options.bus ?? new InMemoryServerEventBus(reportError); - const notify = createServerNotifier(bus); - const listenRouter = createListenRouter({ - bus, - maxSubscriptions: options.maxSubscriptions ?? DEFAULT_MAX_SUBSCRIPTIONS, - keepAliveMs: options.keepAliveMs ?? DEFAULT_SSE_KEEP_ALIVE_MS, - onerror: reportError - }); - if (responseMode === "json") console.warn("responseMode: 'json' drops mid-call notifications. subscriptions/listen streams are always served over SSE regardless; other notifications emitted before a result are dropped."); - const legacyHandler = legacy === "reject" ? void 0 : createLegacyStatelessFallback(factory, reportError, options.keepAliveMs); - async function serveModern(route, request, authInfo) { - const claimedRevision = route.classification.revision; - if (claimedRevision === void 0 || !SUPPORTED_MODERN_PROTOCOL_VERSIONS.includes(claimedRevision)) { - const error = new UnsupportedProtocolVersionError({ - supported: [...SUPPORTED_MODERN_PROTOCOL_VERSIONS], - requested: claimedRevision ?? "unknown" - }); - reportError(error); - return jsonRpcErrorResponse(400, error.code, error.message, error.data, echoableRequestId(route.message)); - } - const stdHeaderRejection = validateStandardRequestHeaders({ - httpMethod: request.method, - mcpMethodHeader: request.headers.get("mcp-method") ?? void 0, - mcpNameHeader: request.headers.get("mcp-name") ?? void 0 - }, route); - if (stdHeaderRejection !== void 0) { - reportError(/* @__PURE__ */ new Error(`Rejected inbound request (${stdHeaderRejection.cell}): ${stdHeaderRejection.message}`)); - return rejectionResponse(stdHeaderRejection, echoableRequestId(route.message)); - } - const meta = route.messageKind === "request" ? requestMetaOf(route.message.params) : void 0; - const declaredClientCapabilities = meta?.[CLIENT_CAPABILITIES_META_KEY]; - if (route.messageKind === "request") { - const required = requiredClientCapabilitiesForRequest(route.message.method); - if (required !== void 0) { - const missing = missingClientCapabilities(required, declaredClientCapabilities); - if (missing !== void 0) { - const error = new MissingRequiredClientCapabilityError({ requiredCapabilities: missing }); - reportError(error); - return jsonRpcErrorResponse(httpStatusForErrorCode(error.code, "ladder"), error.code, error.message, error.data, route.message.id); - } - } - } - const product = await factory({ - era: "modern", - ...authInfo !== void 0 && { authInfo }, - requestInfo: request - }); - const server = product instanceof McpServer ? product.server : product; - if (route.messageKind === "request" && route.message.method === "subscriptions/listen") { - const capabilities = server.getCapabilities(); - const serverInfo = serverIdentityOf(server); - product.close().catch(reportError); - return listenRouter.serve(route.message, request.signal, capabilities, serverInfo); - } - if (route.messageKind === "request" && route.message.method === "tools/call" && product instanceof McpServer) { - const callParams = route.message.params; - const toolName = typeof callParams?.name === "string" ? callParams.name : void 0; - const inputSchema = toolName === void 0 ? void 0 : product.toolInputSchemaJson(toolName); - if (inputSchema !== void 0) { - const scan = scanXMcpHeaderDeclarations(inputSchema); - if (scan.valid && scan.declarations.length > 0) { - const rejection = validateMcpParamHeaders(scan.declarations, callParams?.arguments, request.headers); - if (rejection !== void 0) { - product.close().catch(reportError); - reportError(/* @__PURE__ */ new Error(`Rejected inbound request (${rejection.cell}): ${rejection.message}`)); - return rejectionResponse(rejection, route.message.id); - } - } - } - } - setNegotiatedProtocolVersion(server, claimedRevision); - installModernOnlyHandlers(server, SUPPORTED_MODERN_PROTOCOL_VERSIONS); - if (meta !== void 0) seedClientIdentityFromEnvelope(server, { - clientInfo: meta[CLIENT_INFO_META_KEY], - clientCapabilities: declaredClientCapabilities - }); - const previousOnClose = server.onclose; - inflight.add(server); - server.onclose = () => { - inflight.delete(server); - previousOnClose?.(); - }; - try { - const response = await invoke(product, route.message, { - classification: route.classification, - request, - ...authInfo !== void 0 && { authInfo }, - ...responseMode !== void 0 && { responseMode }, - ...options.keepAliveMs !== void 0 && { keepAliveMs: options.keepAliveMs } - }); - if (route.messageKind === "notification") queueMicrotask(() => void server.close().catch(() => {})); - return response; - } catch (error) { - if (error instanceof SdkError && error.code === SdkErrorCode.ConnectionClosed) return new Response(null, { status: 499 }); - await server.close().catch(() => {}); - inflight.delete(server); - reportError(toError(error)); - return internalServerErrorResponse(echoableRequestId(route.message)); - } - } - async function serveLegacyRoute(route, forwardRequest, authInfo, parsedBody) { - if (legacyHandler !== void 0) return legacyHandler(forwardRequest, { - ...authInfo !== void 0 && { authInfo }, - ...parsedBody !== void 0 && { parsedBody } - }); - const strict = modernOnlyStrictRejection(route, SUPPORTED_MODERN_PROTOCOL_VERSIONS); - if (strict === void 0) return new Response(null, { status: 202 }); - reportError(/* @__PURE__ */ new Error(`Rejected 2025-era request on a modern-only endpoint (${strict.cell}): ${strict.message}`)); - return rejectionResponse(strict, echoableRequestId(parsedBody)); - } - async function handle(request, requestOptions) { - const authInfo = requestOptions?.authInfo; - if (request.method.toUpperCase() === "POST" && !isJsonContentType(request.headers.get("content-type"))) { - reportError(/* @__PURE__ */ new Error("Unsupported Media Type: Content-Type must be application/json")); - return jsonRpcErrorResponse(415, -32e3, "Unsupported Media Type: Content-Type must be application/json"); - } - const classified = await classifyEntryRequest(request, requestOptions?.parsedBody); - if (classified.step === "unreadable-body") return jsonRpcErrorResponse(400, -32700, "Parse error: the request body could not be read"); - if (classified.step === "no-json-body") { - if (legacyHandler !== void 0) return legacyHandler(classified.forwardRequest, { ...authInfo !== void 0 && { authInfo } }); - return jsonRpcErrorResponse(400, -32700, "Parse error: the request body is not valid JSON"); - } - const { outcome, body, parsedBody, forwardRequest } = classified; - try { - switch (outcome.kind) { - case "reject": - reportError(/* @__PURE__ */ new Error(`Rejected inbound request (${outcome.cell}): ${outcome.message}`)); - return rejectionResponse(outcome, echoableRequestId(body)); - case "modern": return await serveModern(outcome, request, authInfo); - case "legacy": return await serveLegacyRoute(outcome, forwardRequest, authInfo, parsedBody); - } - } catch (error) { - reportError(toError(error)); - return internalServerErrorResponse(echoableRequestId(body)); - } - } - const fetchFace = async (request, requestOptions) => { - if (closed) throw new Error("This MCP handler has been closed"); - try { - return await handle(request, requestOptions); - } catch (error) { - reportError(toError(error)); - return internalServerErrorResponse(echoableRequestId(requestOptions?.parsedBody)); - } - }; - return { - fetch: fetchFace, - notify, - bus, - close: async () => { - closed = true; - listenRouter.closeAll(); - const closing = [...inflight].map((server) => server.close().catch(() => {})); - inflight.clear(); - await Promise.all(closing); - } - }; -} - -//#endregion -//#region src/server/middleware/bearerAuth.ts -function headerQuotedValue(value) { - return value.replaceAll(/[\\"]/g, String.raw`\$&`).replaceAll(/[^\u0020-\u007E]/g, " "); -} -function buildWwwAuthenticateHeader(errorCode, description, requiredScopes, resourceMetadataUrl) { - let header = `Bearer error="${headerQuotedValue(errorCode)}", error_description="${headerQuotedValue(description)}"`; - if (requiredScopes.length > 0) header += `, scope="${requiredScopes.join(" ")}"`; - if (resourceMetadataUrl) header += `, resource_metadata="${resourceMetadataUrl}"`; - return header; -} -/** -* Validate a raw `Authorization` header value as a Bearer token and return -* the verified {@link AuthInfo}. -* -* The runtime-neutral core of Bearer authentication: it parses the header, -* runs the verifier, enforces `requiredScopes`, and rejects tokens without an -* expiration or past it. On any failure it throws an {@link OAuthError} — -* pass that to {@link bearerAuthChallengeResponse} for the matching HTTP -* answer, or use {@link requireBearerAuth} to get both steps as one call. -* -* Framework adapters build on this: `requireBearerAuth` from -* `@modelcontextprotocol/express` feeds it `req.headers.authorization`. -*/ -async function verifyBearerToken(authorizationHeader, options) { - const { verifier, requiredScopes = [] } = options; - if (!authorizationHeader) throw new OAuthError(OAuthErrorCode.InvalidToken, "Missing Authorization header"); - const [type, token] = authorizationHeader.split(" "); - if (type?.toLowerCase() !== "bearer" || !token) throw new OAuthError(OAuthErrorCode.InvalidToken, "Invalid Authorization header format, expected 'Bearer TOKEN'"); - const authInfo = await verifier.verifyAccessToken(token); - if (requiredScopes.length > 0) { - if (!requiredScopes.every((scope) => authInfo.scopes.includes(scope))) throw new OAuthError(OAuthErrorCode.InsufficientScope, "Insufficient scope"); - } - if (typeof authInfo.expiresAt !== "number" || Number.isNaN(authInfo.expiresAt)) throw new OAuthError(OAuthErrorCode.InvalidToken, "Token has no expiration time"); - else if (authInfo.expiresAt < Date.now() / 1e3) throw new OAuthError(OAuthErrorCode.InvalidToken, "Token has expired"); - return authInfo; -} -/** -* Build the HTTP answer for a Bearer authentication failure. -* -* Maps an {@link OAuthError} to its status — `401` for `invalid_token` and -* `403` for `insufficient_scope` (both carrying the `WWW-Authenticate: Bearer …` -* challenge, with `resource_metadata` when configured so clients can discover -* the Authorization Server), `500` for `server_error`, `400` for anything -* else. A non-`OAuthError` value answers `500 server_error`. The body is the -* OAuth error JSON. -*/ -function bearerAuthChallengeResponse(error, options) { - const { requiredScopes = [], resourceMetadataUrl } = options ?? {}; - if (!(error instanceof OAuthError)) { - const serverError = new OAuthError(OAuthErrorCode.ServerError, "Internal Server Error"); - return Response.json(serverError.toResponseObject(), { status: 500 }); - } - switch (error.code) { - case OAuthErrorCode.InvalidToken: { - const challenge = buildWwwAuthenticateHeader(error.code, error.message, requiredScopes, resourceMetadataUrl); - return Response.json(error.toResponseObject(), { - status: 401, - headers: { "WWW-Authenticate": challenge } - }); - } - case OAuthErrorCode.InsufficientScope: { - const challenge = buildWwwAuthenticateHeader(error.code, error.message, requiredScopes, resourceMetadataUrl); - return Response.json(error.toResponseObject(), { - status: 403, - headers: { "WWW-Authenticate": challenge } - }); - } - case OAuthErrorCode.ServerError: return Response.json(error.toResponseObject(), { status: 500 }); - default: return Response.json(error.toResponseObject(), { status: 400 }); - } -} -/** -* Require a valid Bearer token on web-standard requests. -* -* The framework-free counterpart of `requireBearerAuth` from -* `@modelcontextprotocol/express`, for hosts whose HTTP surface is a -* `fetch(request)` handler — Cloudflare Workers, Deno, Bun, Hono. The -* returned gate resolves to the verified {@link AuthInfo}, or to the -* ready-to-return challenge `Response` when the request must be refused. -* -* @example -* ```ts source="./bearerAuth.examples.ts#requireBearerAuth_fetchGate" -* const gate = requireBearerAuth({ verifier, requiredScopes: ['mcp'] }); -* -* async function fetchHandler(request: Request): Promise { -* const auth: AuthInfo | Response = await gate(request); -* if (auth instanceof Response) return auth; -* return handler.fetch(request, { authInfo: auth }); -* } -* ``` -*/ -function requireBearerAuth(options) { - const { verifier, requiredScopes = [], resourceMetadataUrl } = options; - const resolved = { - verifier, - requiredScopes, - resourceMetadataUrl - }; - return async (request) => { - const [authorizationHeader] = (request.headers.get("authorization") ?? "").split(","); - try { - return await verifyBearerToken(authorizationHeader || void 0, resolved); - } catch (error) { - return bearerAuthChallengeResponse(error, resolved); - } - }; -} - -//#endregion -//#region src/server/middleware/hostHeaderValidation.ts -/** -* Parse and validate a `Host` header against an allowlist of hostnames (port-agnostic). -* -* - Input host header may include a port (e.g. `localhost:3000`) or IPv6 brackets (e.g. `[::1]:3000`). -* - Allowlist items should be hostnames only (no ports). For IPv6, include brackets (e.g. `[::1]`). -*/ -function validateHostHeader(hostHeader, allowedHostnames) { - if (!hostHeader) return { - ok: false, - errorCode: "missing_host", - message: "Missing Host header" - }; - let hostname; - try { - hostname = new URL(`http://${hostHeader}`).hostname; - } catch { - return { - ok: false, - errorCode: "invalid_host_header", - message: `Invalid Host header: ${hostHeader}`, - hostHeader - }; - } - if (!allowedHostnames.includes(hostname)) return { - ok: false, - errorCode: "invalid_host", - message: `Invalid Host: ${hostname}`, - hostHeader, - hostname - }; - return { - ok: true, - hostname - }; -} -/** -* Convenience allowlist for `localhost` DNS rebinding protection. -*/ -function localhostAllowedHostnames() { - return [ - "localhost", - "127.0.0.1", - "[::1]" - ]; -} -/** -* Web-standard `Request` helper for DNS rebinding protection. -* @example -* ```ts source="./hostHeaderValidation.examples.ts#hostHeaderValidationResponse_basicUsage" -* const result = validateHostHeader(req.headers.get('host'), ['localhost']); -* ``` -*/ -function hostHeaderValidationResponse(req, allowedHostnames) { - const result = validateHostHeader(req.headers.get("host"), allowedHostnames); - if (result.ok) return void 0; - return Response.json({ - jsonrpc: "2.0", - error: { - code: -32e3, - message: result.message - }, - id: null - }, { - status: 403, - headers: { "Content-Type": "application/json" } - }); -} - -//#endregion -//#region src/server/middleware/oauthMetadata.ts -function checkIssuerUrl(issuer, allowInsecure) { - if (issuer.protocol !== "https:" && issuer.hostname !== "localhost" && issuer.hostname !== "127.0.0.1" && !allowInsecure) throw new Error("Issuer URL must be HTTPS"); - if (issuer.hash) throw new Error(`Issuer URL must not have a fragment: ${issuer}`); - if (issuer.search) throw new Error(`Issuer URL must not have a query string: ${issuer}`); -} -/** -* Derive the RFC 9728 Protected Resource Metadata document from -* {@link AuthMetadataOptions}, validating the Authorization Server issuer URL -* (HTTPS required outside localhost) in the process. -* -* `oauthMetadataResponse` and the Express `mcpAuthMetadataRouter` both build -* on this; use it directly when serving the document through your own -* routing — or call it once at startup to fail fast on a misconfigured -* issuer before any request arrives. -*/ -function buildOAuthProtectedResourceMetadata(options) { - checkIssuerUrl(new URL(options.oauthMetadata.issuer), options.dangerouslyAllowInsecureIssuerUrl); - return { - resource: options.resourceServerUrl.href, - authorization_servers: [options.oauthMetadata.issuer], - scopes_supported: options.scopesSupported, - resource_name: options.resourceName, - resource_documentation: options.serviceDocumentationUrl?.href - }; -} -/** -* Builds the RFC 9728 Protected Resource Metadata URL for a given MCP server -* URL by inserting `/.well-known/oauth-protected-resource` ahead of the path. -* -* @example -* ```ts -* getOAuthProtectedResourceMetadataUrl(new URL('https://api.example.com/mcp')) -* // → 'https://api.example.com/.well-known/oauth-protected-resource/mcp' -* ``` -*/ -function getOAuthProtectedResourceMetadataUrl(serverUrl) { - return new URL(protectedResourceMetadataPath(serverUrl), serverUrl).href; -} -/** The RFC 9728 path-aware well-known path for a resource URL. */ -function protectedResourceMetadataPath(resourceServerUrl) { - const rsPath = stripTrailingSlash(resourceServerUrl.pathname); - return `/.well-known/oauth-protected-resource${rsPath === "/" ? "" : rsPath}`; -} -function stripTrailingSlash(path) { - return path.length > 1 && path.endsWith("/") ? path.slice(0, -1) : path; -} -const ALLOWED_METHODS = "GET, HEAD, OPTIONS"; -function metadataDocumentResponse(request, metadata) { - if (request.method === "OPTIONS") { - const requestedHeaders = request.headers.get("access-control-request-headers"); - return new Response(null, { - status: 204, - headers: { - "Access-Control-Allow-Origin": "*", - "Access-Control-Allow-Methods": ALLOWED_METHODS, - ...requestedHeaders === null ? {} : { - "Access-Control-Allow-Headers": requestedHeaders, - Vary: "Access-Control-Request-Headers" - } - } - }); - } - if (request.method !== "GET" && request.method !== "HEAD") { - const error = new OAuthError(OAuthErrorCode.MethodNotAllowed, `The method ${request.method} is not allowed for this endpoint`); - return Response.json(error.toResponseObject(), { - status: 405, - headers: { - Allow: ALLOWED_METHODS, - "Access-Control-Allow-Origin": "*" - } - }); - } - const response = Response.json(metadata, { headers: { "Access-Control-Allow-Origin": "*" } }); - return request.method === "HEAD" ? new Response(null, { - status: response.status, - headers: response.headers - }) : response; -} -/** -* Serve the two OAuth discovery documents an MCP server acting as a Resource -* Server exposes, from a web-standard `fetch(request)` handler: -* -* - `/.well-known/oauth-protected-resource[/]` — RFC 9728 Protected -* Resource Metadata, derived from the supplied options (path-aware: the -* resource URL's path is reflected in the route). -* - `/.well-known/oauth-authorization-server` — RFC 8414 Authorization -* Server Metadata, passed through verbatim. -* -* Returns the matched document `Response` (JSON with permissive CORS, `405` -* with an `Allow` header for non-GET methods, `204` for CORS preflight), or -* `undefined` when the request path is neither well-known route — fall -* through to your own routing. The framework-free counterpart of -* `mcpAuthMetadataRouter` from `@modelcontextprotocol/express`; pair it with -* `requireBearerAuth` and `getOAuthProtectedResourceMetadataUrl` so -* unauthenticated clients can discover the AS from the `401` challenge. -* -* @example -* ```ts source="./oauthMetadata.examples.ts#oauthMetadataResponse_fetchHandler" -* async function fetchHandler(request: Request): Promise { -* return oauthMetadataResponse(request, options) ?? serveMcp(request); -* } -* ``` -*/ -function oauthMetadataResponse(request, options) { - const requestPath = stripTrailingSlash(new URL(request.url).pathname); - if (requestPath === protectedResourceMetadataPath(options.resourceServerUrl)) return metadataDocumentResponse(request, buildOAuthProtectedResourceMetadata(options)); - if (requestPath === "/.well-known/oauth-authorization-server") { - buildOAuthProtectedResourceMetadata(options); - return metadataDocumentResponse(request, options.oauthMetadata); - } -} - -//#endregion -//#region src/server/middleware/originValidation.ts -/** -* Validate an `Origin` header against an allowlist of hostnames (port-agnostic). -* -* - A missing/empty `Origin` header passes: non-browser clients do not send one, -* and only browser-originated requests carry the header this check defends against. -* - Allowlist items are hostnames only (no scheme, no port), the same convention as -* `validateHostHeader`. For IPv6, include brackets (e.g. `[::1]`). -* - Any present value that cannot be parsed as an origin URL — including the literal -* `null` origin browsers send for opaque contexts — is rejected (deny on failure). -*/ -function validateOriginHeader(originHeader, allowedOriginHostnames) { - if (originHeader === null || originHeader === void 0 || originHeader === "") return { ok: true }; - let hostname; - try { - hostname = new URL(originHeader).hostname; - } catch { - return { - ok: false, - errorCode: "invalid_origin_header", - message: `Invalid Origin header: ${originHeader}`, - originHeader - }; - } - if (hostname === "") return { - ok: false, - errorCode: "invalid_origin_header", - message: `Invalid Origin header: ${originHeader}`, - originHeader - }; - if (!allowedOriginHostnames.includes(hostname)) return { - ok: false, - errorCode: "invalid_origin", - message: `Invalid Origin: ${hostname}`, - originHeader, - hostname - }; - return { - ok: true, - origin: originHeader, - hostname - }; -} -/** -* Convenience allowlist of localhost-class origin hostnames, mirroring -* `localhostAllowedHostnames`. -*/ -function localhostAllowedOrigins() { - return [ - "localhost", - "127.0.0.1", - "[::1]" - ]; -} -/** -* Web-standard `Request` helper for Origin validation: returns a `403` JSON-RPC -* error response when the request's `Origin` header is not allowed, and -* `undefined` when the request may proceed. -* -* ```ts -* const rejected = originValidationResponse(request, localhostAllowedOrigins()); -* if (rejected) return rejected; -* ``` -*/ -function originValidationResponse(req, allowedOriginHostnames) { - const result = validateOriginHeader(req.headers.get("origin"), allowedOriginHostnames); - if (result.ok) return void 0; - return Response.json({ - jsonrpc: "2.0", - error: { - code: -32e3, - message: result.message - }, - id: null - }, { - status: 403, - headers: { "Content-Type": "application/json" } - }); -} - -//#endregion -//#region src/server/requestStateCodec.ts -const PREFIX = "v1."; -function bytesToBase64Url(bytes) { - let bin = ""; - for (const b of bytes) bin += String.fromCodePoint(b); - return btoa(bin).replaceAll("+", "-").replaceAll("/", "_").replace(/=+$/, ""); -} -function constantTimeTagEqual(a, b) { - if (a.length !== b.length) return false; - let r = 0; - for (let i = 0; i < a.length; i++) r |= a.codePointAt(i) ^ b.codePointAt(i); - return r === 0; -} -function base64UrlToBytes(s) { - const b64 = s.replaceAll("-", "+").replaceAll("_", "/"); - const bin = atob(b64); - const bytes = new Uint8Array(bin.length); - for (let i = 0; i < bin.length; i++) bytes[i] = bin.codePointAt(i); - return bytes; -} -/** -* Create an opt-in HMAC-SHA256 codec for the multi-round-trip `requestState` -* (protocol revision 2026-07-28). -* -* `requestState` round-trips through the client and is attacker-controlled -* input on re-entry. The SDK applies no protection of its own; this helper is -* the convenience implementation of the spec's integrity MUST so authors don't -* hand-roll HMAC. Wire shape: -* -* "v1." b64url({"p":,"exp":,"b":?}) "." b64url(mac) -* -* where `bindTag` is `b64url(HMAC(key, "mcp.requestState.bind:" + bind(ctx))[:16])` -* — the binding value is never embedded raw. -* -* The codec is **signed, not encrypted**: the body is integrity-protected but -* the client can base64url-decode it and read the payload (`p`) in clear. Do -* not put secrets in the payload; use an AEAD construction if confidentiality -* is required. The handler reads its payload back via the typed -* `ctx.mcpReq.requestState()` accessor — the seam has already run `verify` -* (integrity proven, payload decoded) by the time the handler is entered. -* -* Verification is fail-closed and constant-time (WebCrypto `subtle.verify` for -* the body MAC; a fixed-length XOR-accumulator compare for the bind tag). -* See `examples/mrtr/server.ts` for a worked end-to-end example. -* -* Design comparison (mcp.d `secureRequestState`, the peer SDK's reference -* implementation): mcp.d additionally offers an AES-256-GCM encrypted mode and -* derives independent cipher / bind-HMAC sub-keys from the operator secret via -* HKDF-SHA256, with an auto-generated per-process ephemeral key when none is -* supplied. This codec deliberately ships only the signed mode and a single -* keyed HMAC (domain-separated by input prefix) — HKDF sub-key derivation and -* an encrypted mode are intentionally out of scope for the initial release. -*/ -function createRequestStateCodec(options) { - const subtle = globalThis.crypto?.subtle; - if (subtle === void 0) throw new TypeError("createRequestStateCodec requires the Web Crypto API (globalThis.crypto.subtle); see https://ts.sdk.modelcontextprotocol.io/v2/troubleshooting for the Node.js polyfill instructions"); - const keyBytes = typeof options.key === "string" ? new TextEncoder().encode(options.key) : Uint8Array.from(options.key); - if (keyBytes.byteLength < 32) throw new RangeError(`createRequestStateCodec: key must be at least 32 bytes (got ${keyBytes.byteLength})`); - const ttlSeconds = options.ttlSeconds ?? 600; - if (!Number.isFinite(ttlSeconds)) throw new RangeError("createRequestStateCodec: ttlSeconds must be a finite number"); - const bind = options.bind; - let cryptoKey; - const importedKey = () => cryptoKey ??= subtle.importKey("raw", keyBytes, { - name: "HMAC", - hash: "SHA-256" - }, false, ["sign", "verify"]); - const utf8 = new TextEncoder(); - const BIND_LABEL = "mcp.requestState.bind:"; - const bindTag = async (value) => { - return bytesToBase64Url(new Uint8Array(await subtle.sign("HMAC", await importedKey(), utf8.encode(BIND_LABEL + value))).slice(0, 16)); - }; - return { - async mint(payload, ctx) { - const envelope = { - p: payload, - exp: Math.floor(Date.now() / 1e3) + ttlSeconds - }; - if (bind !== void 0) { - if (ctx === void 0) throw new TypeError("createRequestStateCodec: mint() requires ctx when a bind callback is configured"); - envelope.b = await bindTag(bind(ctx)); - } - const body = bytesToBase64Url(utf8.encode(JSON.stringify(envelope))); - return `${PREFIX}${body}.${bytesToBase64Url(new Uint8Array(await subtle.sign("HMAC", await importedKey(), utf8.encode(PREFIX + body))))}`; - }, - async verify(state, ctx) { - const dot = state.lastIndexOf("."); - if (!state.startsWith(PREFIX) || dot <= 3) throw new Error("malformed"); - const body = state.slice(3, dot); - let macBytes; - try { - macBytes = base64UrlToBytes(state.slice(dot + 1)); - } catch { - throw new Error("malformed"); - } - if (!await subtle.verify("HMAC", await importedKey(), macBytes, utf8.encode(PREFIX + body))) throw new Error("mac"); - let envelope; - try { - envelope = JSON.parse(new TextDecoder("utf-8", { fatal: true }).decode(base64UrlToBytes(body))); - } catch { - throw new Error("malformed"); - } - if (typeof envelope.exp !== "number" || envelope.exp < Math.floor(Date.now() / 1e3)) throw new Error("expired"); - if (bind !== void 0) { - const expected = await bindTag(bind(ctx)); - if (envelope.b === void 0 || !constantTimeTagEqual(envelope.b, expected)) throw new Error("bind"); - } else if (envelope.b !== void 0) throw new Error("bind"); - return envelope.p; - } - }; -} - -//#endregion -//#region src/fromJsonSchema.ts -let _defaultValidator; -function dist_fromJsonSchema(schema, validator) { - return fromJsonSchema$1(schema, validator ?? (_defaultValidator ??= new DefaultJsonSchemaValidator())); -} - -//#endregion - -//# sourceMappingURL=index.mjs.map -const mcpApps = Object.freeze([ - { - "html": "\n\n \n \n \n Service status\n \n \n \n
        \n
        MCP App example
        \n

        No service selected

        \n
        unknown
        \n

        Invoke the readiness tool to inspect a service.

        \n
          \n \n \n \n \n

          \n
          \n \n\n", - "mimeType": "text/html;profile=mcp-app", - "name": "status", - "resourceUri": "ui://mcp-app-example/status.html" - } -]); - -/* export default */ const mcp_status_073c1634_0 = (mcpApps); - -// Generated by agent-bundle. Do not edit. -const meta_name = "mcp-app-example"; -const packageName = "@agent-bundle-example/mcp-app"; -const packageVersion = undefined; -const meta_version = "1.0.0"; -const meta_meta = Object.freeze({ - name: meta_name, - packageName: packageName, - packageVersion: packageVersion, - version: meta_version -}); -/* export default */ const _agent_bundle_virtual_meta = ((/* unused pure expression or super */ null && (meta_meta))); - -const healthyCompilerStatus = Object.freeze({ - checks: Object.freeze([ - Object.freeze({ - label: 'Availability', - status: 'passing' - }), - Object.freeze({ - label: 'Build queue', - status: 'passing' - }) - ]), - service: 'compiler', - status: 'healthy', - summary: 'Compiler service is ready for release.' -}); -const isRecord = (value)=>value !== null && typeof value === 'object' && !Array.isArray(value); -const isHealthyCompilerFixture = (value)=>{ - if (!isRecord(value) || value.service !== healthyCompilerStatus.service || value.status !== healthyCompilerStatus.status || value.summary !== healthyCompilerStatus.summary || !Array.isArray(value.checks) || value.checks.length !== healthyCompilerStatus.checks.length) { - return false; - } - return healthyCompilerStatus.checks.every((expected, index)=>{ - const received = value.checks[index]; - return isRecord(received) && received.label === expected.label && received.status === expected.status; - }); -}; - - - - - - -const app = mcp_status_073c1634_0["0"]; -if (app === undefined) throw new Error('Expected the status MCP App.'); -const serviceCatalog = Object.freeze({ - compiler: healthyCompilerStatus, - 'payments-api': Object.freeze({ - checks: Object.freeze([ - Object.freeze({ - label: 'Availability', - status: 'passing' - }), - Object.freeze({ - label: 'P95 latency', - status: 'failing' - }) - ]), - service: 'payments-api', - status: 'degraded', - summary: 'Payment latency is above the release threshold.' - }) -}); -const createStatusServer = ()=>{ - // The compiler stamps this project's identity into `agent-bundle/meta`, so - // the wire identity cannot drift from the config or package.json. - const server = new mcp_DXXb3Vv3_McpServer({ - name: meta_name, - version: (/* inlined export .version */"1.0.0") - }); - server.registerResource(app.name, app.resourceUri, { - _meta: { - ui: { - resourceUri: app.resourceUri - } - }, - mimeType: app.mimeType - }, async (uri)=>({ - contents: [ - { - mimeType: app.mimeType, - text: app.html, - uri: uri.href - } - ] - })); - server.registerTool('show-status', { - _meta: { - ui: { - resourceUri: app.resourceUri - } - }, - description: 'Show the health of one example service.', - inputSchema: schemas_object({ - service: schemas_enum([ - 'compiler', - 'payments-api' - ]) - }) - }, async ({ service })=>{ - const result = serviceCatalog[service]; - return { - _meta: { - ui: { - resourceUri: app.resourceUri - } - }, - content: [ - { - text: result.summary, - type: 'text' - } - ], - structuredContent: result - }; - }); - return server; -}; -/** - * Default-exported server factory: `agent-bundle build` detects it and wraps - * this entry in the framework stdio lifecycle shell (console-to-stderr guard, - * SIGINT/SIGTERM handling, stdin-EOF exit, bounded shutdown, heartbeat). - */ /* export default */ const mcp_status = (createStatusServer); - - - - - -//#region src/server/stdio.ts -/** -* Server transport for stdio: this communicates with an MCP client by reading from the current process' `stdin` and writing to `stdout`. -* -* This transport is only available in Node.js environments. -* -* @example -* ```ts source="./stdio.examples.ts#StdioServerTransport_basicUsage" -* const server = new McpServer({ name: 'my-server', version: '1.0.0' }); -* const transport = new StdioServerTransport(); -* await server.connect(transport); -* ``` -*/ -var stdio_StdioServerTransport = class { - _readBuffer; - _started = false; - _closed = false; - constructor(_stdin = node_process.stdin, _stdout = node_process.stdout, options) { - this._stdin = _stdin; - this._stdout = _stdout; - this._readBuffer = new ReadBuffer({ maxBufferSize: options?.maxBufferSize }); - } - onclose; - onerror; - onmessage; - _ondata = (chunk) => { - try { - this._readBuffer.append(chunk); - this.processReadBuffer(); - } catch (error) { - this.onerror?.(error); - this.close().catch(() => {}); - } - }; - _onerror = (error) => { - this.onerror?.(error); - }; - _onstdouterror = (error) => { - this.onerror?.(error); - this.close().catch(() => {}); - }; - /** - * Starts listening for messages on `stdin`. - */ - async start() { - if (this._started) throw new Error("StdioServerTransport already started! If using Server class, note that connect() calls start() automatically."); - this._started = true; - this._stdin.on("data", this._ondata); - this._stdin.on("error", this._onerror); - this._stdout.on("error", this._onstdouterror); - } - processReadBuffer() { - while (true) try { - const message = this._readBuffer.readMessage(); - if (message === null) break; - this.onmessage?.(message); - } catch (error) { - this.onerror?.(error); - } - } - async close() { - if (this._closed) return; - this._closed = true; - this._stdin.off("data", this._ondata); - this._stdin.off("error", this._onerror); - this._stdout.off("error", this._onstdouterror); - if (this._stdin.listenerCount("data") === 0) this._stdin.pause(); - this._readBuffer.clear(); - this.onclose?.(); - } - send(message) { - if (this._closed) return Promise.reject(/* @__PURE__ */ new Error("StdioServerTransport is closed")); - return new Promise((resolve, reject) => { - const json = serializeMessage(message); - let settled = false; - const onError = (error) => { - if (settled) return; - settled = true; - this._stdout.off("error", onError); - this._stdout.off("drain", onDrain); - reject(error); - }; - const onDrain = () => { - if (settled) return; - settled = true; - this._stdout.off("error", onError); - this._stdout.off("drain", onDrain); - resolve(); - }; - this._stdout.once("error", onError); - if (this._stdout.write(json)) { - if (settled) return; - settled = true; - this._stdout.off("error", onError); - resolve(); - } else if (!settled) this._stdout.once("drain", onDrain); - }); - } -}; - -//#endregion -//#region src/server/serveStdio.ts -/** -* How long the probe-discard path waits for the probe instance to answer the -* requests it was delivered before closing it. The wait normally settles as -* soon as the DiscoverResult is handed to the wire (or immediately, when a -* delivered cancellation already settled the probe); the bound is a backstop -* so no edge can ever hold the connection's inbound pump indefinitely behind -* the discard. -*/ -const DISCARD_ANSWER_TIMEOUT_MS = 3e3; -/** -* The transport a pinned instance is connected to: a thin channel that writes -* through to the entry-owned wire transport and receives the messages the -* entry forwards. The wire transport itself is never handed to an instance — -* that is what lets the entry discard an optimistic probe instance (close the -* channel) without tearing down the connection. -*/ -var StdioConnectionChannel = class { - onclose; - onerror; - onmessage; - _closed = false; - /** Request ids the entry delivered to the instance that the instance has not yet answered. */ - _pendingRequests = /* @__PURE__ */ new Set(); - _drainWaiters = []; - constructor(_wire, _onInstanceClose, _outboundIntercept) { - this._wire = _wire; - this._onInstanceClose = _onInstanceClose; - this._outboundIntercept = _outboundIntercept; - } - async start() {} - async send(message, options) { - if (isJSONRPCResultResponse(message) || isJSONRPCErrorResponse(message)) { - const { id } = message; - if (id !== void 0) this._settle(id); - } - if (this._closed) return; - if (this._outboundIntercept?.(message) === "handled") return; - return this._wire.send(message, options); - } - setProtocolVersion = (version) => { - this._wire.setProtocolVersion?.(version); - }; - /** Forwards one inbound message to the connected instance. */ - deliver(message, extra) { - if (this._closed) return; - if (isJSONRPCRequest(message)) this._pendingRequests.add(message.id); - else if (isJSONRPCNotification(message) && message.method === "notifications/cancelled") { - const cancelledId = message.params?.requestId; - if (cancelledId !== void 0) this._settle(cancelledId); - } - this.onmessage?.(message, extra); - } - /** - * Resolves once every request delivered to the instance has been answered - * through {@linkcode send}, settled by a delivered cancellation, or the - * channel has been closed and nothing further can be answered. The wait is - * bounded by `timeoutMs` as a backstop so no edge can hold the caller - * indefinitely; resolves `false` only when the bound elapsed with requests - * still unanswered. Used by the probe-discard path so a probe request the - * entry accepted is never silently dropped. - */ - async whenRequestsAnswered(timeoutMs) { - if (this._closed || this._pendingRequests.size === 0) return true; - return await new Promise((resolve) => { - const waiter = () => { - clearTimeout(timer); - resolve(true); - }; - const timer = setTimeout(() => { - this._drainWaiters = this._drainWaiters.filter((pending) => pending !== waiter); - resolve(false); - }, timeoutMs); - this._drainWaiters.push(waiter); - }); - } - async close() { - if (this._closed) return; - this._closed = true; - this._pendingRequests.clear(); - this._releaseDrainWaiters(); - try { - this._onInstanceClose(); - } finally { - this.onclose?.(); - } - } - _settle(id) { - this._pendingRequests.delete(id); - if (this._pendingRequests.size === 0) this._releaseDrainWaiters(); - } - _releaseDrainWaiters() { - const waiters = this._drainWaiters; - this._drainWaiters = []; - for (const waiter of waiters) waiter(); - } -}; -/** -* Classifies one message of the opening exchange with the same body-primary -* rules the HTTP entry applies per request: `initialize` is the legacy -* handshake unless it carries a valid modern envelope claim; a present claim -* is validated (never silently ignored); a claim-less message is 2025-era -* traffic. There is no header layer on stdio, so the body is the only signal. -*/ -function classifyOpeningMessage(message) { - const params = message.params; - if (message.method === "initialize" && !carriesValidModernEnvelopeClaim(params)) { - const requestedVersion = params !== null && typeof params === "object" && typeof params.protocolVersion === "string" ? params.protocolVersion : void 0; - return { - kind: "legacy", - reason: "initialize", - ...requestedVersion !== void 0 && { requestedVersion } - }; - } - if (!hasEnvelopeClaim(params)) return { - kind: "legacy", - reason: "no-claim" - }; - const meta = requestMetaOf(params); - const firstIssue = (meta === void 0 ? [] : validateEnvelopeMeta(meta))[0]; - if (firstIssue !== void 0) return { - kind: "invalid-envelope", - issue: firstIssue - }; - const claimedVersion = envelopeClaimVersion(params); - if (claimedVersion === void 0 || !SUPPORTED_MODERN_PROTOCOL_VERSIONS.includes(claimedVersion)) return { - kind: "unsupported-revision", - requested: claimedVersion ?? "unknown" - }; - return { - kind: "modern", - revision: claimedVersion, - classification: { - era: "modern", - revision: claimedVersion - } - }; -} -/** -* Serves MCP over stdio from a server factory, owning the era decision for -* the connection: the opening exchange selects the era, ONE instance from the -* factory is pinned for the connection lifetime, and everything after passes -* straight through to it. See the module documentation for the opening rules. -* -* ```ts -* import { serveStdio } from '@modelcontextprotocol/server/stdio'; -* -* serveStdio(() => { -* const server = new McpServer({ name: 'my-server', version: '1.0.0' }, { capabilities: { tools: {} } }); -* // register tools/resources/prompts once — the same factory serves both eras -* return server; -* }); -* ``` -*/ -function serveStdio(factory, options = {}) { - const legacyMode = options.legacy ?? "serve"; - const wire = options.transport ?? new stdio_StdioServerTransport(); - let state = { phase: "opening" }; - /** Channel currently being discarded (its close must not tear the connection down). */ - let discarding; - let closing = false; - /** - * Whether the connection has been torn down (`handle.close()` or the wire - * closing). The opening arms re-check this after every await: a close can - * race factory construction, and the continuation must neither resurrect - * the connection state nor keep a late-resolved instance around. - */ - const isTornDown = () => closing || state.phase === "closed"; - const reportError = (error) => { - try { - options.onerror?.(error); - } catch {} - }; - const writeErrorResponse = (id, code, message, data) => wire.send({ - jsonrpc: "2.0", - id, - error: { - code, - message, - ...data !== void 0 && { data } - } - }).catch((error) => reportError(stdio_toError(error))); - /** - * Entry-handled `subscriptions/listen` for this connection: holds the - * active subscriptions, serves inbound listen / cancelled-of-listen - * before the pinned instance is consulted, and rewrites the instance's - * outbound change notifications onto the active subscriptions. Only - * consulted on a modern-pinned connection — on a legacy connection - * change notifications pass straight through (the 2025 unsolicited - * delivery model is unchanged). - */ - const listenRouter = new StdioListenRouter(options.maxSubscriptions ?? DEFAULT_MAX_SUBSCRIPTIONS); - /** Outbound intercept installed on a modern instance's channel. */ - const modernOutboundIntercept = (message) => { - if (!isJSONRPCNotification(message)) return void 0; - const routed = listenRouter.routeOutbound(message); - if (routed === "passthrough") return void 0; - for (const stamped of routed) wire.send({ - jsonrpc: "2.0", - ...stamped - }).catch((error) => reportError(stdio_toError(error))); - return "handled"; - }; - /** - * Entry-handled inbound listen routing for a modern-pinned connection. - * Returns `true` when the message was served at the entry and must NOT - * be delivered to the pinned instance. - */ - const tryServeListen = async (message) => { - if (isJSONRPCRequest(message) && message.method === "subscriptions/listen") { - const meta = requestMetaOf(message.params); - const issue = hasEnvelopeClaim(message.params) ? (meta === void 0 ? [] : validateEnvelopeMeta(meta))[0] : { - key: "_meta", - problem: "the per-request envelope is required on protocol revision 2026-07-28" - }; - const claimedVersion = envelopeClaimVersion(message.params); - let reply; - if (issue !== void 0) reply = { - jsonrpc: "2.0", - id: message.id, - error: { - code: -32602, - message: `Invalid _meta envelope: ${issue.key}: ${issue.problem}` - } - }; - else if (claimedVersion === void 0 || !SUPPORTED_MODERN_PROTOCOL_VERSIONS.includes(claimedVersion)) { - const error = new UnsupportedProtocolVersionError({ - supported: [...SUPPORTED_MODERN_PROTOCOL_VERSIONS], - requested: claimedVersion ?? "unknown" - }); - reply = { - jsonrpc: "2.0", - id: message.id, - error: { - code: error.code, - message: error.message, - data: error.data - } - }; - } else reply = listenRouter.serve(message); - await wire.send("error" in reply ? reply : { - jsonrpc: "2.0", - method: reply.method, - params: reply.params - }).catch((error) => reportError(stdio_toError(error))); - return true; - } - if (isJSONRPCNotification(message) && message.method === "notifications/cancelled") { - const cancelledId = message.params?.requestId; - if (cancelledId !== void 0 && listenRouter.cancel(cancelledId)) return true; - } - return false; - }; - /** Answers a 2025-era request the entry will not serve (the modern-only rejection cells). */ - const answerLegacyRejection = (request, reason, requestedVersion) => { - const rejection = modernOnlyStrictRejection({ - kind: "legacy", - reason, - ...requestedVersion !== void 0 && { requestedVersion } - }, SUPPORTED_MODERN_PROTOCOL_VERSIONS); - if (rejection === void 0) return Promise.resolve(); - reportError(/* @__PURE__ */ new Error(`Rejected 2025-era request on a modern-only stdio connection (${rejection.cell}): ${rejection.message}`)); - return writeErrorResponse(request.id, rejection.code, rejection.message, rejection.data); - }; - const onInstanceClosed = (channel) => { - if (closing || channel === discarding) return; - closeAll(); - }; - const connectInstance = async (era, revision) => { - const product = await factory({ era }); - const server = product instanceof McpServer ? product.server : product; - if (era === "modern") { - setNegotiatedProtocolVersion(server, revision); - installModernOnlyHandlers(server, SUPPORTED_MODERN_PROTOCOL_VERSIONS); - listenRouter.setServerCapabilities(server.getCapabilities(), serverIdentityOf(server)); - } - const channel = new StdioConnectionChannel(wire, () => onInstanceClosed(channel), era === "modern" ? modernOutboundIntercept : void 0); - await product.connect(channel); - return { - product, - channel - }; - }; - /** Closes an instance whose factory resolved only after the connection was torn down. */ - const disposeLateInstance = (instance) => instance.product.close().catch((error) => reportError(stdio_toError(error))); - const discardProbeInstance = async (instance) => { - discarding = instance.channel; - try { - if (!await instance.channel.whenRequestsAnswered(DISCARD_ANSWER_TIMEOUT_MS)) reportError(/* @__PURE__ */ new Error(`Discarded the probe instance with requests still unanswered after ${DISCARD_ANSWER_TIMEOUT_MS}ms; continuing with the fallback`)); - await instance.product.close(); - } catch (error) { - reportError(stdio_toError(error)); - } finally { - discarding = void 0; - } - }; - const processMessage = async (message) => { - if (state.phase === "closed") return; - if (state.phase === "pinned") { - if (state.era === "modern" && isJSONRPCRequest(message) && message.method === "initialize" && !carriesValidModernEnvelopeClaim(message.params)) { - await answerLegacyRejection(message, "initialize", message.params !== null && typeof message.params === "object" && typeof message.params.protocolVersion === "string" ? message.params.protocolVersion : void 0); - return; - } - if (state.era === "modern" && await tryServeListen(message)) return; - state.instance.channel.deliver(message); - return; - } - if (!isJSONRPCRequest(message) && !isJSONRPCNotification(message)) { - reportError(/* @__PURE__ */ new Error("Discarded a JSON-RPC response received before the connection negotiated an era")); - return; - } - const opening = classifyOpeningMessage(message); - switch (opening.kind) { - case "invalid-envelope": { - const detail = `Invalid _meta envelope for protocol revision 2026-07-28: ${opening.issue.key}: ${opening.issue.problem}`; - if (isJSONRPCRequest(message)) await writeErrorResponse(message.id, ProtocolErrorCode.InvalidParams, detail, { envelope: opening.issue }); - else reportError(/* @__PURE__ */ new Error(`Discarded a notification with a malformed envelope: ${detail}`)); - return; - } - case "unsupported-revision": - if (isJSONRPCRequest(message)) { - const error = new UnsupportedProtocolVersionError({ - supported: [...SUPPORTED_MODERN_PROTOCOL_VERSIONS], - requested: opening.requested - }); - reportError(error); - await writeErrorResponse(message.id, error.code, error.message, error.data); - } else reportError(/* @__PURE__ */ new Error(`Discarded a notification claiming unsupported protocol revision ${opening.requested}`)); - return; - case "modern": - if (isJSONRPCRequest(message) && message.method === "server/discover") { - if (state.phase === "probe") { - state.instance.channel.deliver(message, { classification: opening.classification }); - return; - } - const instance = await connectInstance("modern", opening.revision); - if (isTornDown()) { - await disposeLateInstance(instance); - return; - } - state = { - phase: "probe", - instance - }; - instance.channel.deliver(message, { classification: opening.classification }); - return; - } - if (state.phase === "probe") { - if (isJSONRPCNotification(message)) { - state.instance.channel.deliver(message, { classification: opening.classification }); - return; - } - state = { - phase: "pinned", - era: "modern", - instance: state.instance - }; - } else { - const instance = await connectInstance("modern", opening.revision); - if (isTornDown()) { - await disposeLateInstance(instance); - return; - } - state = { - phase: "pinned", - era: "modern", - instance - }; - } - if (await tryServeListen(message)) return; - state.instance.channel.deliver(message, { classification: opening.classification }); - return; - case "legacy": { - if (legacyMode === "reject") { - if (isJSONRPCRequest(message)) await answerLegacyRejection(message, opening.reason, opening.requestedVersion); - return; - } - if (state.phase === "probe") { - await discardProbeInstance(state.instance); - if (isTornDown()) return; - state = { phase: "opening" }; - } - const instance = await connectInstance("legacy"); - if (isTornDown()) { - await disposeLateInstance(instance); - return; - } - state = { - phase: "pinned", - era: "legacy", - instance - }; - state.instance.channel.deliver(message); - return; - } - } - }; - const queue = []; - let pumping = false; - const pump = async () => { - if (pumping) return; - pumping = true; - try { - while (queue.length > 0) { - const message = queue.shift(); - try { - await processMessage(message); - } catch (error) { - if (isJSONRPCRequest(message)) await writeErrorResponse(message.id, ProtocolErrorCode.InternalError, "Internal server error"); - reportError(stdio_toError(error)); - } - } - } finally { - pumping = false; - } - }; - const closeAll = async () => { - if (closing || state.phase === "closed") return; - closing = true; - const current = state; - state = { phase: "closed" }; - for (const result of listenRouter.teardownAll()) await wire.send(result).catch((error) => reportError(stdio_toError(error))); - if (current.phase === "probe" || current.phase === "pinned") await current.instance.product.close().catch((error) => reportError(stdio_toError(error))); - await wire.close().catch((error) => reportError(stdio_toError(error))); - }; - wire.onmessage = (message) => { - queue.push(message); - pump(); - }; - wire.onerror = (error) => { - reportError(error); - if (state.phase === "probe" || state.phase === "pinned") state.instance.channel.onerror?.(error); - }; - wire.onclose = () => { - if (closing || state.phase === "closed") return; - closing = true; - const current = state; - state = { phase: "closed" }; - if (current.phase === "probe" || current.phase === "pinned") current.instance.product.close().catch((error) => reportError(stdio_toError(error))); - }; - const started = wire.start().catch((error) => { - reportError(stdio_toError(error)); - throw error; - }); - started.catch(() => {}); - return { close: async () => { - await started.catch(() => {}); - await closeAll(); - } }; -} -function stdio_toError(value) { - return value instanceof Error ? value : new Error(String(value)); -} - -//#endregion - -//# sourceMappingURL=stdio.mjs.map -const defaultHeartbeatIntervalMs = 300000; -const defaultActivityThrottleMs = 60000; -const defaultShutdownTimeoutMs = 5000; -const defaultHeartbeatName = 'agent-bundle'; -const redirectConsoleToStderr = ()=>{ - const originalStdoutWrite = process.stdout.write.bind(process.stdout); - const stderrConsole = new console.Console({ - stderr: process.stderr, - stdout: process.stderr - }); - const methods = [ - 'debug', - 'dir', - 'error', - 'info', - 'log', - 'trace', - 'warn' - ]; - for (const method of methods)console[method] = stderrConsole[method].bind(stderrConsole); - process.stdout.write = (chunk, encoding, callback)=>process.stderr.write(chunk, encoding, callback); - return Object.freeze({ - restoreProtocolStdout: ()=>{ - process.stdout.write = originalStdoutWrite; - } - }); -}; -const createHeartbeat = ({ activityThrottleMs = defaultActivityThrottleMs, intervalMs = defaultHeartbeatIntervalMs, name = defaultHeartbeatName, writeLine })=>{ - const startedAt = Date.now(); - let lastActivityAt = startedAt; - let lastActivityLogAt = 0; - const log = (reason)=>{ - const uptimeSeconds = Math.round((Date.now() - startedAt) / 1000); - const idleSeconds = Math.round((Date.now() - lastActivityAt) / 1000); - writeLine(`[${name}] stdio heartbeat (${reason}) pid=${process.pid} uptime=${uptimeSeconds}s idle=${idleSeconds}s`); - }; - const timer = setInterval(()=>log('interval'), intervalMs); - timer.unref?.(); - return Object.freeze({ - log, - noteActivity: ()=>{ - lastActivityAt = Date.now(); - if (lastActivityAt - lastActivityLogAt >= activityThrottleMs) { - lastActivityLogAt = lastActivityAt; - log('activity'); - } - }, - stop: ()=>clearInterval(timer) - }); -}; -const runStdioServer = async ({ activityThrottleMs, exit = (code)=>process.exit(code), heartbeat: heartbeatEnabled = true, heartbeatIntervalMs, server, serverName, shutdownTimeoutMs = defaultShutdownTimeoutMs, signals = process, stdin = process.stdin, transport, writeLine = (line)=>void process.stderr.write(`${line}\n`) })=>{ - const heartbeat = createHeartbeat({ - ...void 0 === activityThrottleMs ? {} : { - activityThrottleMs - }, - ...void 0 === heartbeatIntervalMs ? {} : { - intervalMs: heartbeatIntervalMs - }, - ...void 0 === serverName ? {} : { - name: serverName - }, - writeLine: heartbeatEnabled ? writeLine : ()=>void 0 - }); - const keepalive = setInterval(()=>void 0, 60000); - keepalive.unref?.(); - let shuttingDown = false; - const shutdown = async (exitCode = 0)=>{ - if (shuttingDown) return; - shuttingDown = true; - signals.off('SIGINT', handleSigint); - signals.off('SIGTERM', handleSigterm); - stdin.off?.('end', handleStdinEnd); - clearInterval(keepalive); - heartbeat.stop(); - await Promise.race([ - Promise.allSettled([ - Promise.resolve().then(()=>transport.close()), - Promise.resolve().then(()=>server.close()) - ]), - new Promise((resolve)=>setTimeout(resolve, shutdownTimeoutMs)) - ]); - exit(exitCode); - }; - const handleSigint = ()=>{ - shutdown(130); - }; - const handleSigterm = ()=>{ - shutdown(143); - }; - const handleStdinEnd = ()=>{ - shutdown(0); - }; - signals.on('SIGINT', handleSigint); - signals.on('SIGTERM', handleSigterm); - stdin.once?.('end', handleStdinEnd); - transport.onclose = ()=>{ - shutdown(0); - }; - await server.connect(transport); - const originalOnMessage = transport.onmessage; - transport.onmessage = (message, extra)=>{ - heartbeat.noteActivity(); - originalOnMessage?.(message, extra); - }; - return Object.freeze({ - heartbeat, - shutdown - }); -}; -const runGeneratedStdioMcpEntry = async (options)=>{ - const guard = redirectConsoleToStderr(); - const entry = await options.loadEntry(); - const factory = entry.default; - if ('function' != typeof factory) throw new TypeError(`Generated stdio entry for MCP server ${JSON.stringify(options.serverName)} must default-export a server factory.`); - const server = await factory(); - const { StdioServerTransport } = await Promise.resolve(stdio_namespaceObject); - guard.restoreProtocolStdout(); - const transport = new StdioServerTransport(); - return runStdioServer({ - ...options.lifecycle, - server, - serverName: options.serverName, - transport: transport - }); -}; - - - -await runGeneratedStdioMcpEntry({ - loadEntry: ()=>Promise.resolve(status_namespaceObject), - serverName: "status" -}); - -export {}; diff --git a/examples/mcp-app/artifact/portable/plugin.json b/examples/mcp-app/artifact/portable/plugin.json deleted file mode 100644 index e450b6e1e..000000000 --- a/examples/mcp-app/artifact/portable/plugin.json +++ /dev/null @@ -1 +0,0 @@ -{"$schema":"https://agent-plugins.org/schemas/1.0.0/plugin.schema.json","description":"A unified service-readiness assistant with MCP, Skills, Hooks, scripts, and evaluation.","name":"mcp-app-example","version":"1.0.0"} diff --git a/examples/mcp-app/artifact/portable/scripts/check-service-fixture.mjs b/examples/mcp-app/artifact/portable/scripts/check-service-fixture.mjs deleted file mode 100644 index a059060bb..000000000 --- a/examples/mcp-app/artifact/portable/scripts/check-service-fixture.mjs +++ /dev/null @@ -1,60 +0,0 @@ -import { readFile } from "node:fs/promises"; - - - - -const healthyCompilerStatus = Object.freeze({ - checks: Object.freeze([ - Object.freeze({ - label: 'Availability', - status: 'passing' - }), - Object.freeze({ - label: 'Build queue', - status: 'passing' - }) - ]), - service: 'compiler', - status: 'healthy', - summary: 'Compiler service is ready for release.' -}); -const isRecord = (value)=>value !== null && typeof value === 'object' && !Array.isArray(value); -const isHealthyCompilerFixture = (value)=>{ - if (!isRecord(value) || value.service !== healthyCompilerStatus.service || value.status !== healthyCompilerStatus.status || value.summary !== healthyCompilerStatus.summary || !Array.isArray(value.checks) || value.checks.length !== healthyCompilerStatus.checks.length) { - return false; - } - return healthyCompilerStatus.checks.every((expected, index)=>{ - const received = value.checks[index]; - return isRecord(received) && received.label === expected.label && received.status === expected.status; - }); -}; - - - -const fixturePath = new URL('../assets/evals/fixtures/status/result.json', import.meta.url); -/** - * `agent-bundle build` detects the `main` export and generates the process - * envelope (argv, awaiting, numeric-return exit-code adoption) around it. - */ const main = async ()=>{ - try { - const fixture = JSON.parse(await readFile(fixturePath, 'utf8')); - if (!isHealthyCompilerFixture(fixture)) { - throw new Error('compiler fixture must contain the exact healthy compiler status'); - } - process.stdout.write('Compiler fixture is healthy.\n'); - return 0; - } catch (error) { - process.stderr.write(`Unable to verify service fixture: ${error instanceof Error ? error.message : String(error)}\n`); - return 1; - } -}; - - -const check_service_fixture_entry_main = main; -if (typeof check_service_fixture_entry_main !== 'function') { - throw new TypeError('Executable entry must export a main function: ' + "/fast/projects/agent-bundle-worktrees/host-test/examples/mcp-app/src/scripts/check-service-fixture.ts"); -} -const code = await check_service_fixture_entry_main(process.argv.slice(2)); -if (typeof code === 'number') process.exitCode = code; - -export {}; diff --git a/examples/mcp-app/artifact/portable/skills/service-readiness/SKILL.md b/examples/mcp-app/artifact/portable/skills/service-readiness/SKILL.md deleted file mode 100644 index 8f91a79d7..000000000 --- a/examples/mcp-app/artifact/portable/skills/service-readiness/SKILL.md +++ /dev/null @@ -1,33 +0,0 @@ ---- -name: service-readiness -description: Reviews service health evidence and records an auditable readiness decision. ---- -# Service readiness - -## When to use - -Use this Skill when a release, incident decision, or service handoff needs a -clear health verdict backed by named checks and current evidence. - -## Required resources - -- Apply [the service status policy](references/status-policy.md) before - classifying a healthy, degraded, or blocked result. -- Deliver the decision with [the readiness report](assets/readiness-report.md). - -## Workflow - -1. Identify the service and collect its current summary and every labelled - check. Record the command, time, result, and evidence source. -2. Classify any failing check with the status policy. A degraded service is not - release-ready until its failing check has an approved mitigation. -3. State the readiness verdict only after confirming availability and the - service-specific release threshold. -4. Complete the report with the status, checks, evidence, owner, and next - action. Do not omit a failing check from the final decision. - -## Final report requirements - -State `ready`, `degraded`, `blocked`, or `needs evidence`; reproduce the -service summary; list each labelled check and its status; identify the owner -and due date for every non-passing check; and name the next required action. diff --git a/examples/mcp-app/artifact/portable/skills/service-readiness/assets/readiness-report.md b/examples/mcp-app/artifact/portable/skills/service-readiness/assets/readiness-report.md deleted file mode 100644 index 3da5d52ea..000000000 --- a/examples/mcp-app/artifact/portable/skills/service-readiness/assets/readiness-report.md +++ /dev/null @@ -1,22 +0,0 @@ -# Service readiness report - -## Verdict - -State `ready`, `degraded`, `blocked`, or `needs evidence` and name the service. - -## Evidence - -Record the collection time, command or artifact, service summary, and source. - -## Checks - -List every labelled check with its observed status and release threshold. - -## Findings and mitigation - -For each non-passing check, record the impact, owner, mitigation, due date, -and the evidence required to clear it. - -## Next action - -Name the decision owner and the next verification or release action. diff --git a/examples/mcp-app/artifact/portable/skills/service-readiness/references/status-policy.md b/examples/mcp-app/artifact/portable/skills/service-readiness/references/status-policy.md deleted file mode 100644 index 7e5766172..000000000 --- a/examples/mcp-app/artifact/portable/skills/service-readiness/references/status-policy.md +++ /dev/null @@ -1,22 +0,0 @@ -# Service status policy - -## Evidence standard - -Readiness evidence must identify the service, collection time, check label, -observed status, and source command or artifact. Missing or stale evidence is -not a passing check. - -## Status classification - -- **Healthy**: every required release check is passing. -- **Degraded**: availability remains sufficient, but a release threshold such - as P95 latency is failing. Record an owner and mitigation before release. -- **Blocked**: availability or a critical safety check is failing. Do not - release until new passing evidence is collected. -- **Needs evidence**: the service or any required check cannot be verified. - -## Release decision - -Issue `ready` only for a healthy service with current evidence. A degraded -service needs an explicit mitigation decision; a blocked service cannot pass; -and missing evidence requires a new check rather than an assumption. diff --git a/packages/agent-bundle/src/build/entry-shell.ts b/packages/agent-bundle/src/build/entry-shell.ts index 849f598ed..cf4ecae30 100644 --- a/packages/agent-bundle/src/build/entry-shell.ts +++ b/packages/agent-bundle/src/build/entry-shell.ts @@ -952,9 +952,17 @@ export const generatedRouteMcpEntrySource = (options: GeneratedRouteMcpEntryOpti : [eventTarget]; const wiresInbox = wiresInboxRoute(options); const wiresResourceUpdated = wiresResourceUpdatedRoute(options); + // The lineage registry journals durably only where the project already + // accepted the sqlite kernel and its durable anchor (a workspace-durable + // `src/state.ts`); stateless and volatile projects keep a process-lifetime + // registry so `node:sqlite` never loads for them and no `state/` directory + // appears inside an artifact that declared none. + const durableLineage = options.state?.lifetime === 'workspace-durable'; return [ - `import { ${hasEvents ? 'dirname, ' : ''}join, resolve } from 'node:path';`, - "import { fileURLToPath } from 'node:url';", + ...(hasEvents || durableLineage + ? [`import { ${[...(hasEvents ? ['dirname'] : []), ...(durableLineage ? ['join'] : []), 'resolve'].join(', ')} } from 'node:path';`] + : []), + ...(durableLineage ? ["import { fileURLToPath } from 'node:url';"] : []), `import { createFlightWorkerHost, createGeneratedRouteMcpServer } from ${JSON.stringify(mcpServerRuntimeSpecifier)};`, ...(hasEvents ? [ @@ -962,30 +970,36 @@ export const generatedRouteMcpEntrySource = (options: GeneratedRouteMcpEntryOpti `import { createCanonicalEventProps, projectEventDocument } from ${JSON.stringify(eventProjectRuntimeSpecifier)};`, ] : []), - "import { agentLineageStateDefinition, createAgentLineageRegistry } from '@agent-bundle/runtime/lineage';", - "import { createSqliteStateDriver } from '@agent-bundle/runtime/state/sqlite';", + `import { ${durableLineage ? 'agentLineageStateDefinition, ' : ''}createAgentLineageRegistry } from '@agent-bundle/runtime/lineage';`, + ...(durableLineage ? ["import { createSqliteStateDriver } from '@agent-bundle/runtime/state/sqlite';"] : []), "import mcpApps from 'agent-bundle/mcp-apps';", ...noticeDeliveryImports(wiresResourceUpdated), ...noticeInboxImport(wiresInbox), ...routeImports(routes), '', `const ARTIFACT_EPOCH = ${JSON.stringify(artifactEpoch)};`, - // The lineage registry journals beside the project's own durable state so - // a restarted MCP process still knows which subagents are alive. A store - // that cannot open degrades to an in-memory registry rather than failing - // the server: lineage is an observed axis, never a precondition. - "const lineageAnchor = process.env.AGENT_BUNDLE_PLUGIN_ROOT ?? fileURLToPath(new URL('..', import.meta.url));", - 'const openLineage = async () => {', - " const driver = createSqliteStateDriver({ root: join(resolve(lineageAnchor), 'state') });", - ' try {', - ' const store = await driver.open(agentLineageStateDefinition());', - ' return { dispose: async () => { await store.close(); await driver.close(); }, registry: createAgentLineageRegistry({ store }) };', - ' } catch (error) {', - " process.stderr.write(`agent-bundle lineage registry is in-memory only: ${error instanceof Error ? error.message : String(error)}\\n`);", - ' await driver.close().catch(() => undefined);', - ' return { dispose: async () => undefined, registry: createAgentLineageRegistry() };', - ' }', - '};', + ...(durableLineage + ? [ + // Beside the project's own durable state, so a restarted MCP process + // still knows which subagents are alive. A store that cannot open + // degrades to memory rather than failing the server: lineage is an + // observed axis, never a precondition. + "const lineageAnchor = process.env.AGENT_BUNDLE_PLUGIN_ROOT ?? fileURLToPath(new URL('..', import.meta.url));", + 'const openLineage = async () => {', + " const driver = createSqliteStateDriver({ root: join(resolve(lineageAnchor), 'state') });", + ' try {', + ' const store = await driver.open(agentLineageStateDefinition());', + ' return { dispose: async () => { await store.close(); await driver.close(); }, registry: createAgentLineageRegistry({ store }) };', + ' } catch (error) {', + " process.stderr.write(`agent-bundle lineage registry is in-memory only: ${error instanceof Error ? error.message : String(error)}\\n`);", + ' await driver.close().catch(() => undefined);', + ' return { dispose: async () => undefined, registry: createAgentLineageRegistry() };', + ' }', + '};', + ] + : [ + 'const openLineage = async () => ({ dispose: async () => undefined, registry: createAgentLineageRegistry() });', + ]), 'const routes = Object.freeze({', ...routeRecords(routes), ...noticeInboxRecord(wiresInbox), diff --git a/packages/agent-bundle/tests/entry-shell.test.ts b/packages/agent-bundle/tests/entry-shell.test.ts index 12cb6cb4e..9c3c6ff4e 100644 --- a/packages/agent-bundle/tests/entry-shell.test.ts +++ b/packages/agent-bundle/tests/entry-shell.test.ts @@ -235,9 +235,12 @@ it('generates one final-only Flight MCP factory from filesystem routes', () => { // The lineage registry journals through the sqlite kernel beside project // state and degrades to memory when the store cannot open (#host-lineage). expect(source).toContain("from '@agent-bundle/runtime/lineage'"); - expect(source).toContain('createSqliteStateDriver({ root: join(resolve(lineageAnchor), \'state\') })'); expect(source).toContain('lineage: lineage.registry,'); expect(source).toContain('disposeLineage: lineage.dispose,'); + // A project without workspace-durable state keeps a process-lifetime + // registry: no sqlite import, no `state/` directory inside the artifact. + expect(source).not.toContain('node:sqlite'); + expect(source).not.toContain('createSqliteStateDriver'); // The event runtime's modules are aliased into the artifact, so the entry // imports them and hands them to the shared runtime; the wiring itself is // not re-templated here. @@ -332,6 +335,33 @@ it('fails the build on an MCP route the generated server cannot register', () => }); +it('journals the lineage registry through sqlite only for workspace-durable projects', () => { + const source = entryShellModule.generatedRouteMcpEntrySource({ + plugin: { name: 'route-fixture', version: '1.2.3' }, + routes: [{ + config: {}, + id: 'tool:curator/inspect', + kind: 'tool', + provenance: { kind: 'conventional', relativePath: 'src/mcp/curator/tools/inspect.tsx' }, + source: '/project/src/mcp/curator/tools/inspect.tsx', + }], + serverName: 'curator', + state: { + id: 'project/tasks', + lifetime: 'workspace-durable', + provenance: { kind: 'conventional', sourcePath: '/project/src/state.ts' }, + source: '/project/src/state.ts', + }, + workerFile: 'mcp-curator-flight.mjs', + }); + expect(source).toContain("import { agentLineageStateDefinition, createAgentLineageRegistry } from '@agent-bundle/runtime/lineage'"); + expect(source).toContain("import { createSqliteStateDriver } from '@agent-bundle/runtime/state/sqlite'"); + expect(source).toContain("const lineageAnchor = process.env.AGENT_BUNDLE_PLUGIN_ROOT ?? fileURLToPath(new URL('..', import.meta.url));"); + expect(source).toContain("createSqliteStateDriver({ root: join(resolve(lineageAnchor), 'state') })"); + expect(source).toContain('agent-bundle lineage registry is in-memory only'); + expect(source).toContain('disposeLineage: lineage.dispose,'); +}); + it('generates the warm react-server Flight worker separately from the MCP dispatcher', () => { const generate = (entryShellModule as unknown as { readonly generatedRouteFlightWorkerSource?: (options: Readonly>) => string; diff --git a/packages/rsc-runtime/tests/state-packaging.test.ts b/packages/rsc-runtime/tests/state-packaging.test.ts index 7745586ee..e0565aec2 100644 --- a/packages/rsc-runtime/tests/state-packaging.test.ts +++ b/packages/rsc-runtime/tests/state-packaging.test.ts @@ -86,6 +86,7 @@ describe.sequential('state kernel packaging boundaries', () => { './notices', './notices/inbox-route', './mount', + './lineage', ]); for (const subpath of Object.keys(packageJson.exports)) { const target = packageJson.exports[subpath]!; From 29efab46ab3231707ee5345b0bd913481eaa9a9d Mon Sep 17 00:00:00 2001 From: ScriptedAlchemy Date: Thu, 3 Sep 2026 09:46:11 +0000 Subject: [PATCH 04/20] test(mcp): assert the built generated server mounts an honest lineage axis --- .../agent-bundle/tests/generated-route-server.test.ts | 9 ++++++--- 1 file changed, 6 insertions(+), 3 deletions(-) diff --git a/packages/agent-bundle/tests/generated-route-server.test.ts b/packages/agent-bundle/tests/generated-route-server.test.ts index 94fefb1e4..e7a36ace4 100644 --- a/packages/agent-bundle/tests/generated-route-server.test.ts +++ b/packages/agent-bundle/tests/generated-route-server.test.ts @@ -114,11 +114,11 @@ it('lists and calls a generated filesystem tool through final-only Flight', { re "import { z } from 'zod';", "export const config = { annotations: { readOnlyHint: true }, description: 'Inspect one source.' };", "export const inputSchema = z.object({ source: z.string() }).strict();", - "export const resultSchema = z.object({ actor: z.unknown(), host: z.unknown(), invocationKind: z.literal('tool'), session: z.unknown(), source: z.string(), workspace: z.unknown() }).strict();", + "export const resultSchema = z.object({ actor: z.unknown(), host: z.unknown(), invocationKind: z.literal('tool'), lineage: z.unknown(), session: z.unknown(), source: z.string(), workspace: z.unknown() }).strict();", 'export default async function Inspect({ input, signal }) {', " if (signal.aborted) throw new DOMException('aborted', 'AbortError');", ' const context = await agent();', - ' const result = { actor: context.actor, host: context.host, invocationKind: context.invocation.kind, session: context.session, source: input.source, workspace: context.workspace };', + ' const result = { actor: context.actor, host: context.host, invocationKind: context.invocation.kind, lineage: context.lineage, session: context.session, source: input.source, workspace: context.workspace };', ' return (', ' ', ' {`Inspected **${input.source}**.`}', @@ -178,7 +178,10 @@ it('lists and calls a generated filesystem tool through final-only Flight', { re state: 'available', value: { name: 'generated-route-test' }, }, - lineage: { reason: 'not-provided', state: 'unavailable' }, + // The built entry mounts a process-lifetime registry, but a portable + // artifact has no subagent events to feed it and this client name maps + // to no host, so the call is honestly unplaceable. + lineage: { reason: 'id-not-resolvable', state: 'unavailable' }, session: { reason: 'not-provided', state: 'unavailable' }, workspace: { source: 'derived', From 32cd3f547fa1118052e7bd97d08f0ff259e2c4c3 Mon Sep 17 00:00:00 2001 From: ScriptedAlchemy Date: Thu, 3 Sep 2026 10:04:23 +0000 Subject: [PATCH 05/20] fix(lineage): key journal entries by caller key and payload digest, scope spawn claims per root; untrack skills-starter artifact; changeset per repository rules (review) --- .changeset/request-lineage.md | 2 +- .../artifact/agent-bundle.hooks.json | 1 - .../artifact/agent-bundle.manifest.json | 1 - .../claude/.claude-plugin/marketplace.json | 1 - .../claude/.claude-plugin/plugin.json | 1 - .../skills-starter/artifact/claude/INSTALL.md | 18 ---- .../claude/skills/dependency-upgrade/SKILL.md | 33 -------- .../dependency-upgrade/assets/upgrade-plan.md | 21 ----- .../references/compatibility-checklist.md | 9 -- .../claude/skills/incident-triage/SKILL.md | 34 -------- .../incident-triage/assets/incident-update.md | 9 -- .../references/triage-runbook.md | 9 -- .../claude/skills/release-review/SKILL.md | 34 -------- .../release-review/assets/report-template.md | 22 ----- .../release-review/references/checklist.md | 8 -- .../references/release-policy.md | 22 ----- .../codex/.agents/plugins/marketplace.json | 1 - .../artifact/codex/.codex-plugin/plugin.json | 1 - .../skills-starter/artifact/codex/INSTALL.md | 16 ---- .../codex/skills/dependency-upgrade/SKILL.md | 33 -------- .../dependency-upgrade/assets/upgrade-plan.md | 21 ----- .../references/compatibility-checklist.md | 9 -- .../codex/skills/incident-triage/SKILL.md | 34 -------- .../incident-triage/assets/incident-update.md | 9 -- .../references/triage-runbook.md | 9 -- .../codex/skills/release-review/SKILL.md | 34 -------- .../release-review/assets/report-template.md | 22 ----- .../release-review/references/checklist.md | 8 -- .../references/release-policy.md | 22 ----- .../artifact/portable/INSTALL.md | 19 ----- .../artifact/portable/install.mjs | 80 ------------------ .../artifact/portable/plugin.json | 1 - .../skills/dependency-upgrade/SKILL.md | 33 -------- .../dependency-upgrade/assets/upgrade-plan.md | 21 ----- .../references/compatibility-checklist.md | 9 -- .../portable/skills/incident-triage/SKILL.md | 34 -------- .../incident-triage/assets/incident-update.md | 9 -- .../references/triage-runbook.md | 9 -- .../portable/skills/release-review/SKILL.md | 34 -------- .../release-review/assets/report-template.md | 22 ----- .../release-review/references/checklist.md | 8 -- .../references/release-policy.md | 22 ----- packages/rsc-runtime/src/lineage/registry.ts | 84 ++++++++++++------- .../tests/lineage-registry.test.ts | 45 ++++++++++ 44 files changed, 102 insertions(+), 772 deletions(-) delete mode 100644 examples/skills-starter/artifact/agent-bundle.hooks.json delete mode 100644 examples/skills-starter/artifact/agent-bundle.manifest.json delete mode 100644 examples/skills-starter/artifact/claude/.claude-plugin/marketplace.json delete mode 100644 examples/skills-starter/artifact/claude/.claude-plugin/plugin.json delete mode 100644 examples/skills-starter/artifact/claude/INSTALL.md delete mode 100644 examples/skills-starter/artifact/claude/skills/dependency-upgrade/SKILL.md delete mode 100644 examples/skills-starter/artifact/claude/skills/dependency-upgrade/assets/upgrade-plan.md delete mode 100644 examples/skills-starter/artifact/claude/skills/dependency-upgrade/references/compatibility-checklist.md delete mode 100644 examples/skills-starter/artifact/claude/skills/incident-triage/SKILL.md delete mode 100644 examples/skills-starter/artifact/claude/skills/incident-triage/assets/incident-update.md delete mode 100644 examples/skills-starter/artifact/claude/skills/incident-triage/references/triage-runbook.md delete mode 100644 examples/skills-starter/artifact/claude/skills/release-review/SKILL.md delete mode 100644 examples/skills-starter/artifact/claude/skills/release-review/assets/report-template.md delete mode 100644 examples/skills-starter/artifact/claude/skills/release-review/references/checklist.md delete mode 100644 examples/skills-starter/artifact/claude/skills/release-review/references/release-policy.md delete mode 100644 examples/skills-starter/artifact/codex/.agents/plugins/marketplace.json delete mode 100644 examples/skills-starter/artifact/codex/.codex-plugin/plugin.json delete mode 100644 examples/skills-starter/artifact/codex/INSTALL.md delete mode 100644 examples/skills-starter/artifact/codex/skills/dependency-upgrade/SKILL.md delete mode 100644 examples/skills-starter/artifact/codex/skills/dependency-upgrade/assets/upgrade-plan.md delete mode 100644 examples/skills-starter/artifact/codex/skills/dependency-upgrade/references/compatibility-checklist.md delete mode 100644 examples/skills-starter/artifact/codex/skills/incident-triage/SKILL.md delete mode 100644 examples/skills-starter/artifact/codex/skills/incident-triage/assets/incident-update.md delete mode 100644 examples/skills-starter/artifact/codex/skills/incident-triage/references/triage-runbook.md delete mode 100644 examples/skills-starter/artifact/codex/skills/release-review/SKILL.md delete mode 100644 examples/skills-starter/artifact/codex/skills/release-review/assets/report-template.md delete mode 100644 examples/skills-starter/artifact/codex/skills/release-review/references/checklist.md delete mode 100644 examples/skills-starter/artifact/codex/skills/release-review/references/release-policy.md delete mode 100644 examples/skills-starter/artifact/portable/INSTALL.md delete mode 100644 examples/skills-starter/artifact/portable/install.mjs delete mode 100644 examples/skills-starter/artifact/portable/plugin.json delete mode 100644 examples/skills-starter/artifact/portable/skills/dependency-upgrade/SKILL.md delete mode 100644 examples/skills-starter/artifact/portable/skills/dependency-upgrade/assets/upgrade-plan.md delete mode 100644 examples/skills-starter/artifact/portable/skills/dependency-upgrade/references/compatibility-checklist.md delete mode 100644 examples/skills-starter/artifact/portable/skills/incident-triage/SKILL.md delete mode 100644 examples/skills-starter/artifact/portable/skills/incident-triage/assets/incident-update.md delete mode 100644 examples/skills-starter/artifact/portable/skills/incident-triage/references/triage-runbook.md delete mode 100644 examples/skills-starter/artifact/portable/skills/release-review/SKILL.md delete mode 100644 examples/skills-starter/artifact/portable/skills/release-review/assets/report-template.md delete mode 100644 examples/skills-starter/artifact/portable/skills/release-review/references/checklist.md delete mode 100644 examples/skills-starter/artifact/portable/skills/release-review/references/release-policy.md diff --git a/.changeset/request-lineage.md b/.changeset/request-lineage.md index da5045596..768f44487 100644 --- a/.changeset/request-lineage.md +++ b/.changeset/request-lineage.md @@ -3,4 +3,4 @@ 'agent-bundle': patch --- -Add `request.lineage` to `AgentRequestContext` on every surface (event routes, generated MCP tools, routed CLI, rendered scripts): `{ conversation, root, parent?, depth, generation?, subagent?, resolution }` resolved by the new runtime-held agent lineage registry (`@agent-bundle/runtime/lineage`, journaled through the state kernel beside project state) that the `agent/start`/`agent/stop` and `tool/before`/`tool/after` families feed, with hook→MCP correlation from Claude `claudecode/toolUseId`, Codex `x-codex-turn-metadata`, and Cursor's open `MCP:` pre-tool hook. Unavailable lineage carries a typed reason (`no-subagent-events`, `id-not-resolvable`, `cloud-agent-no-user-hooks`, `no-shared-runtime`, `unsupported-surface`, `not-provided`); every pinned capability table gains dated `lineage` rows, the Workbench Lifecycles view shows the lineage axis and chain, `openInMemoryMcpServer` accepts `lineage`/`lineageHost`, and Claude `PostToolUse` hooks now accept the plain-string `tool_response` that MCP tools deliver (any present JSON value, as on Codex) instead of failing the route. +Add `request.lineage` to `AgentRequestContext` on every surface (event routes, generated MCP tools, routed CLI, rendered scripts): `{ conversation, root, parent?, depth, generation?, subagent?, resolution }` resolved by the new runtime-held agent lineage registry (`@agent-bundle/runtime/lineage`, journaled through the state kernel beside workspace-durable project state) that the `agent/start`/`agent/stop` and `tool/before`/`tool/after` families feed, with hook→MCP correlation from Claude `claudecode/toolUseId`, Codex `x-codex-turn-metadata`, and Cursor's open `MCP:` pre-tool hook. Unavailable lineage carries a typed reason (`no-subagent-events`, `id-not-resolvable`, `cloud-agent-no-user-hooks`, `no-shared-runtime`, `unsupported-surface`, `not-provided`); every pinned capability table gains dated `lineage` rows, the Workbench Lifecycles view shows the lineage axis and chain, and `openInMemoryMcpServer` accepts `lineage`/`lineageHost`. Claude `PostToolUse` event routes and `afterTool` hooks now accept the plain-string `tool_response` that MCP tools deliver (any present JSON value, as on Codex) instead of failing with `native tool_response must be an object`; no diagnostic codes are added or changed. (#421) diff --git a/examples/skills-starter/artifact/agent-bundle.hooks.json b/examples/skills-starter/artifact/agent-bundle.hooks.json deleted file mode 100644 index a41e820b1..000000000 --- a/examples/skills-starter/artifact/agent-bundle.hooks.json +++ /dev/null @@ -1 +0,0 @@ -{"hooks":[]} diff --git a/examples/skills-starter/artifact/agent-bundle.manifest.json b/examples/skills-starter/artifact/agent-bundle.manifest.json deleted file mode 100644 index 6104a5852..000000000 --- a/examples/skills-starter/artifact/agent-bundle.manifest.json +++ /dev/null @@ -1 +0,0 @@ -{"agentSkills":{"schemaSha256":"6d06b61e423317421de2295ea1fd0c7b4491bfa36c5b7705c28616dfe76d4047","sourceRevision":"69ef37e9424c0a7ea9dd2293b559e43ec8176379","specification":"https://raw.githubusercontent.com/agentskills/agentskills/69ef37e9424c0a7ea9dd2293b559e43ec8176379/docs/specification.mdx"},"files":[{"bytes":13,"kind":"generated","path":"agent-bundle.hooks.json","sha256":"4df87c0d55ad1cbfddaadb62a690a467c4a2661d5da94697caefe9492a0e01b5","sourceInputs":["agent-bundle.config.ts"]},{"bytes":358,"kind":"generated","path":"claude/.claude-plugin/marketplace.json","sha256":"173c38e9dad7ec0bc9f48f850307206bda76817250f88ee71f8148cf84232013","sourceInputs":["agent-bundle.config.ts"]},{"bytes":187,"kind":"generated","path":"claude/.claude-plugin/plugin.json","sha256":"6c214932fd8a194629570beaf09f03b5674235b3825244e41b94ac85925a17e8","sourceInputs":["agent-bundle.config.ts","src/skills/dependency-upgrade/SKILL.md","src/skills/incident-triage/SKILL.md","src/skills/release-review/SKILL.md"]},{"bytes":473,"kind":"generated","path":"claude/INSTALL.md","sha256":"05237956c42069fe4812a300076665b81926069a77eecf373c4759eb73777a94","sourceInputs":["agent-bundle.config.ts"]},{"bytes":481,"kind":"copy","path":"claude/skills/dependency-upgrade/assets/upgrade-plan.md","sha256":"0312c35a9c04a2ad83b8a4fa522c01fe0834c4b98bf75b3436ce0e89cb8aedff","sourceInputs":["src/skills/dependency-upgrade/assets/upgrade-plan.md","src/skills/dependency-upgrade/SKILL.md"]},{"bytes":516,"kind":"copy","path":"claude/skills/dependency-upgrade/references/compatibility-checklist.md","sha256":"47fea616913afa9e185ef9321b8c7ec7b0c4cf2b7d5c5cfad10af0e9c112d3fb","sourceInputs":["src/skills/dependency-upgrade/references/compatibility-checklist.md","src/skills/dependency-upgrade/SKILL.md"]},{"bytes":1351,"kind":"copy","path":"claude/skills/dependency-upgrade/SKILL.md","sha256":"3528992c76717319c27b32624a3e5ff3d84c61cc35a28bbf297d77819148cf69","sourceInputs":["src/skills/dependency-upgrade/SKILL.md"]},{"bytes":417,"kind":"copy","path":"claude/skills/incident-triage/assets/incident-update.md","sha256":"97b690d6d343ca85c09027cce90482416c69447b9cbfcc76120fefb05ed3e1ce","sourceInputs":["src/skills/incident-triage/assets/incident-update.md","src/skills/incident-triage/SKILL.md"]},{"bytes":461,"kind":"copy","path":"claude/skills/incident-triage/references/triage-runbook.md","sha256":"f9be7c2010d5244e8ed3a00e5df552d52553ea265014c5f3b91f3538922301ea","sourceInputs":["src/skills/incident-triage/references/triage-runbook.md","src/skills/incident-triage/SKILL.md"]},{"bytes":1399,"kind":"copy","path":"claude/skills/incident-triage/SKILL.md","sha256":"255e814c4e04f250d3c0cb7109609baf7be3dceff46ce7584dfdf341f02fa2a7","sourceInputs":["src/skills/incident-triage/SKILL.md"]},{"bytes":484,"kind":"copy","path":"claude/skills/release-review/assets/report-template.md","sha256":"ecb13a7c6a895ec2665035897f32fdec468997a5fa442368e16309683108cf88","sourceInputs":["src/skills/release-review/assets/report-template.md","src/skills/release-review/SKILL.md"]},{"bytes":421,"kind":"copy","path":"claude/skills/release-review/references/checklist.md","sha256":"5ee81fae771e1baef7ef4a11c4abad2d7a06fd29b50aeaab3d09a6189cef13f6","sourceInputs":["src/skills/release-review/references/checklist.md","src/skills/release-review/SKILL.md"]},{"bytes":908,"kind":"copy","path":"claude/skills/release-review/references/release-policy.md","sha256":"50c91759e4c3144e3966e4e599e25aaf291fb6a02515a9639bde189e578bac88","sourceInputs":["src/skills/release-review/references/release-policy.md","src/skills/release-review/SKILL.md"]},{"bytes":1353,"kind":"copy","path":"claude/skills/release-review/SKILL.md","sha256":"d9875fcc1cb9119e8cc9c4e09abf8b31bd011bcf5f77d492aae23fbc6e9e1659","sourceInputs":["src/skills/release-review/SKILL.md"]},{"bytes":255,"kind":"generated","path":"codex/.agents/plugins/marketplace.json","sha256":"92a763708bcf83d61e127c6cb01b53004d73ba77e976b18c0be957d26ec4041e","sourceInputs":["agent-bundle.config.ts"]},{"bytes":611,"kind":"generated","path":"codex/.codex-plugin/plugin.json","sha256":"d1e15bed8bff1408dd3b254473067c0411862584b358eef88ebcbd3cd59472bc","sourceInputs":["agent-bundle.config.ts","src/skills/dependency-upgrade/SKILL.md","src/skills/incident-triage/SKILL.md","src/skills/release-review/SKILL.md"]},{"bytes":361,"kind":"generated","path":"codex/INSTALL.md","sha256":"f67365c3cd57f48d62a2f182fb250b5cd334206100a4cc643e8bdf81a1f1dfe2","sourceInputs":["agent-bundle.config.ts"]},{"bytes":481,"kind":"copy","path":"codex/skills/dependency-upgrade/assets/upgrade-plan.md","sha256":"0312c35a9c04a2ad83b8a4fa522c01fe0834c4b98bf75b3436ce0e89cb8aedff","sourceInputs":["src/skills/dependency-upgrade/assets/upgrade-plan.md","src/skills/dependency-upgrade/SKILL.md"]},{"bytes":516,"kind":"copy","path":"codex/skills/dependency-upgrade/references/compatibility-checklist.md","sha256":"47fea616913afa9e185ef9321b8c7ec7b0c4cf2b7d5c5cfad10af0e9c112d3fb","sourceInputs":["src/skills/dependency-upgrade/references/compatibility-checklist.md","src/skills/dependency-upgrade/SKILL.md"]},{"bytes":1351,"kind":"copy","path":"codex/skills/dependency-upgrade/SKILL.md","sha256":"3528992c76717319c27b32624a3e5ff3d84c61cc35a28bbf297d77819148cf69","sourceInputs":["src/skills/dependency-upgrade/SKILL.md"]},{"bytes":417,"kind":"copy","path":"codex/skills/incident-triage/assets/incident-update.md","sha256":"97b690d6d343ca85c09027cce90482416c69447b9cbfcc76120fefb05ed3e1ce","sourceInputs":["src/skills/incident-triage/assets/incident-update.md","src/skills/incident-triage/SKILL.md"]},{"bytes":461,"kind":"copy","path":"codex/skills/incident-triage/references/triage-runbook.md","sha256":"f9be7c2010d5244e8ed3a00e5df552d52553ea265014c5f3b91f3538922301ea","sourceInputs":["src/skills/incident-triage/references/triage-runbook.md","src/skills/incident-triage/SKILL.md"]},{"bytes":1399,"kind":"copy","path":"codex/skills/incident-triage/SKILL.md","sha256":"255e814c4e04f250d3c0cb7109609baf7be3dceff46ce7584dfdf341f02fa2a7","sourceInputs":["src/skills/incident-triage/SKILL.md"]},{"bytes":484,"kind":"copy","path":"codex/skills/release-review/assets/report-template.md","sha256":"ecb13a7c6a895ec2665035897f32fdec468997a5fa442368e16309683108cf88","sourceInputs":["src/skills/release-review/assets/report-template.md","src/skills/release-review/SKILL.md"]},{"bytes":421,"kind":"copy","path":"codex/skills/release-review/references/checklist.md","sha256":"5ee81fae771e1baef7ef4a11c4abad2d7a06fd29b50aeaab3d09a6189cef13f6","sourceInputs":["src/skills/release-review/references/checklist.md","src/skills/release-review/SKILL.md"]},{"bytes":908,"kind":"copy","path":"codex/skills/release-review/references/release-policy.md","sha256":"50c91759e4c3144e3966e4e599e25aaf291fb6a02515a9639bde189e578bac88","sourceInputs":["src/skills/release-review/references/release-policy.md","src/skills/release-review/SKILL.md"]},{"bytes":1353,"kind":"copy","path":"codex/skills/release-review/SKILL.md","sha256":"d9875fcc1cb9119e8cc9c4e09abf8b31bd011bcf5f77d492aae23fbc6e9e1659","sourceInputs":["src/skills/release-review/SKILL.md"]},{"bytes":704,"kind":"generated","path":"portable/INSTALL.md","sha256":"36fcad70168df8ba84710412655ff3baf636f8228357e31f3f4f22aeea4e2ef4","sourceInputs":["agent-bundle.config.ts"]},{"bytes":3308,"kind":"generated","path":"portable/install.mjs","sha256":"86a297294bf7f79001860d0d2bdd496d7bccf16a94201456f97926c3a8c3eff0","sourceInputs":["agent-bundle.config.ts"]},{"bytes":223,"kind":"generated","path":"portable/plugin.json","sha256":"bf4244be5133884977cdf0b957194f7eae0a0058abeda47916200ffd6c1a303d","sourceInputs":["agent-bundle.config.ts"]},{"bytes":481,"kind":"copy","path":"portable/skills/dependency-upgrade/assets/upgrade-plan.md","sha256":"0312c35a9c04a2ad83b8a4fa522c01fe0834c4b98bf75b3436ce0e89cb8aedff","sourceInputs":["src/skills/dependency-upgrade/assets/upgrade-plan.md","src/skills/dependency-upgrade/SKILL.md"]},{"bytes":516,"kind":"copy","path":"portable/skills/dependency-upgrade/references/compatibility-checklist.md","sha256":"47fea616913afa9e185ef9321b8c7ec7b0c4cf2b7d5c5cfad10af0e9c112d3fb","sourceInputs":["src/skills/dependency-upgrade/references/compatibility-checklist.md","src/skills/dependency-upgrade/SKILL.md"]},{"bytes":1351,"kind":"copy","path":"portable/skills/dependency-upgrade/SKILL.md","sha256":"3528992c76717319c27b32624a3e5ff3d84c61cc35a28bbf297d77819148cf69","sourceInputs":["src/skills/dependency-upgrade/SKILL.md"]},{"bytes":417,"kind":"copy","path":"portable/skills/incident-triage/assets/incident-update.md","sha256":"97b690d6d343ca85c09027cce90482416c69447b9cbfcc76120fefb05ed3e1ce","sourceInputs":["src/skills/incident-triage/assets/incident-update.md","src/skills/incident-triage/SKILL.md"]},{"bytes":461,"kind":"copy","path":"portable/skills/incident-triage/references/triage-runbook.md","sha256":"f9be7c2010d5244e8ed3a00e5df552d52553ea265014c5f3b91f3538922301ea","sourceInputs":["src/skills/incident-triage/references/triage-runbook.md","src/skills/incident-triage/SKILL.md"]},{"bytes":1399,"kind":"copy","path":"portable/skills/incident-triage/SKILL.md","sha256":"255e814c4e04f250d3c0cb7109609baf7be3dceff46ce7584dfdf341f02fa2a7","sourceInputs":["src/skills/incident-triage/SKILL.md"]},{"bytes":484,"kind":"copy","path":"portable/skills/release-review/assets/report-template.md","sha256":"ecb13a7c6a895ec2665035897f32fdec468997a5fa442368e16309683108cf88","sourceInputs":["src/skills/release-review/assets/report-template.md","src/skills/release-review/SKILL.md"]},{"bytes":421,"kind":"copy","path":"portable/skills/release-review/references/checklist.md","sha256":"5ee81fae771e1baef7ef4a11c4abad2d7a06fd29b50aeaab3d09a6189cef13f6","sourceInputs":["src/skills/release-review/references/checklist.md","src/skills/release-review/SKILL.md"]},{"bytes":908,"kind":"copy","path":"portable/skills/release-review/references/release-policy.md","sha256":"50c91759e4c3144e3966e4e599e25aaf291fb6a02515a9639bde189e578bac88","sourceInputs":["src/skills/release-review/references/release-policy.md","src/skills/release-review/SKILL.md"]},{"bytes":1353,"kind":"copy","path":"portable/skills/release-review/SKILL.md","sha256":"d9875fcc1cb9119e8cc9c4e09abf8b31bd011bcf5f77d492aae23fbc6e9e1659","sourceInputs":["src/skills/release-review/SKILL.md"]}],"producer":{"name":"agent-bundle","version":"0.1.0"},"project":{"configDigest":"0f589d1a9536e55632bad273cce4d1b41007531a2e6868df0a687ae1a5b0893a","configPath":"agent-bundle.config.ts","modelDigest":"2c1281c98b2a03bbb8d8584df134d7acce0047f52a3f7abbad5b7239577cbc7a","packageName":"@agent-bundle-example/skills-starter","revision":"7e7f9288d2d0cda787fc3c585e47f7a4dcd4a273186817e63b723333d8d76822","sourceInputs":[{"executable":false,"path":"agent-bundle.config.ts","sha256":"0f589d1a9536e55632bad273cce4d1b41007531a2e6868df0a687ae1a5b0893a"},{"executable":false,"path":"evals/engineering-operations.eval.ts","sha256":"60882b3746d4cd258d66d579757935f39666a6e610e86a3dbf7858807a516d69"},{"executable":false,"path":"evals/fixtures/incident/result.json","sha256":"57431bcbff2673ff2cf95f1a1dbccd063b2293b8be8bbc47b235d46f0686659d"},{"executable":false,"path":"evals/fixtures/release/result.json","sha256":"c2a2ddd2207fe2f6da264310c508d1d0384abf76d49ad796fbefcc10eb336905"},{"executable":false,"path":"evals/fixtures/upgrade/result.json","sha256":"9442378ddea4c0880d7a920ee575ed4d06cddae4b305ec403e5d95d03a4a6021"},{"executable":false,"path":"evals/graders/operations-result.ts","sha256":"476c2ca6d8937b8240384af2de0cb2036fc1a72d7cbf715f33142a6427d34471"},{"executable":false,"path":"evals/graders/release-result.ts","sha256":"c9cfcc05e760c5d672685a0a79ccbf96f532674d3e044fbce78328413f0ae06b"},{"executable":false,"path":"evals/release-readiness.eval.ts","sha256":"aa76a5bd2a0c88c0a66952d273cf8c3dd6858598eeea38853123b7b853b1fe1b"},{"executable":false,"path":"package.json","sha256":"fbc2da06b1077164d928667663a8b18f7a6cabae3252118af2b1d62695073ee7"},{"executable":false,"path":"README.md","sha256":"99f3588b978f59fd41971fd15911426da8d1cdff98fa531bb1f6c1e80b23c744"},{"executable":false,"path":"src/skills/dependency-upgrade/assets/upgrade-plan.md","sha256":"0312c35a9c04a2ad83b8a4fa522c01fe0834c4b98bf75b3436ce0e89cb8aedff"},{"executable":false,"path":"src/skills/dependency-upgrade/references/compatibility-checklist.md","sha256":"47fea616913afa9e185ef9321b8c7ec7b0c4cf2b7d5c5cfad10af0e9c112d3fb"},{"executable":false,"path":"src/skills/dependency-upgrade/SKILL.md","sha256":"3528992c76717319c27b32624a3e5ff3d84c61cc35a28bbf297d77819148cf69"},{"executable":false,"path":"src/skills/incident-triage/assets/incident-update.md","sha256":"97b690d6d343ca85c09027cce90482416c69447b9cbfcc76120fefb05ed3e1ce"},{"executable":false,"path":"src/skills/incident-triage/references/triage-runbook.md","sha256":"f9be7c2010d5244e8ed3a00e5df552d52553ea265014c5f3b91f3538922301ea"},{"executable":false,"path":"src/skills/incident-triage/SKILL.md","sha256":"255e814c4e04f250d3c0cb7109609baf7be3dceff46ce7584dfdf341f02fa2a7"},{"executable":false,"path":"src/skills/release-review/assets/report-template.md","sha256":"ecb13a7c6a895ec2665035897f32fdec468997a5fa442368e16309683108cf88"},{"executable":false,"path":"src/skills/release-review/references/checklist.md","sha256":"5ee81fae771e1baef7ef4a11c4abad2d7a06fd29b50aeaab3d09a6189cef13f6"},{"executable":false,"path":"src/skills/release-review/references/release-policy.md","sha256":"50c91759e4c3144e3966e4e599e25aaf291fb6a02515a9639bde189e578bac88"},{"executable":false,"path":"src/skills/release-review/SKILL.md","sha256":"d9875fcc1cb9119e8cc9c4e09abf8b31bd011bcf5f77d492aae23fbc6e9e1659"}]},"runtime":{"node":"22.12.0"},"targets":[{"adapterRevision":"1.22.0","name":"claude","observedVersion":"2.1.250","schemas":[{"name":"hooks","revision":"2.1.250","sha256":"3c6f3e4391f3dca939d75bd0b200ea88e68db939a2cb885d46f0b143293efb84"},{"name":"lsp","revision":"2.1.250","sha256":"c81fd2f57c410f70f8e5c3f84483f5ec1b575ee02802b424977826f757dccd8e"},{"name":"marketplace","revision":"2.1.250","sha256":"4ffa94e8024966e8080b9d3b338c9612bdfa255802a8491b43f74f90427bc988"},{"name":"mcp","revision":"2.1.250","sha256":"76ccf02c7bfe2d57945ba18e84da8d655529bd68b4d692f72bce28238c99067e"},{"name":"monitors","revision":"2.1.250","sha256":"d45abdf7561e4316ba217ce9c2ac84f32e1049622b74abb081693b479a54b48d"},{"name":"plugin","revision":"2.1.250","sha256":"3c9943237da86fd08ae82f698cde36dbef2ecf742098c6961cedf481fe435c12"},{"name":"settings","revision":"2.1.250","sha256":"9e86d8c5e4053e8de0e468d349e2c3dde5834d22d6769372b88570e301700073"},{"name":"theme","revision":"2.1.250","sha256":"721aa9b0bc7c60cd9359343e5c7205ffbdfea82da312f601720c9dfaa2d8cf0d"}]},{"adapterRevision":"1.8.0","name":"codex","observedVersion":"0.147.0","schemas":[{"name":"app","revision":"0.147.0","sha256":"01c720a645e437bf0c4f8c26fd4cb5a13988e5649e4a8562ee23a1d4b7355c6a"},{"name":"hooks","revision":"0.147.0","sha256":"175b859eb8e85bd287d85ee840d97c3f5c2d0dda3223507a796d158e3770eeba"},{"name":"marketplace","revision":"0.147.0","sha256":"fbccce3ade39e1b077fcb440e60260de6e811e8c2d222b2ae0fe8fe47706b470"},{"name":"mcp","revision":"0.147.0","sha256":"75bd50f9fcb85c2e8d43bc132d61c172a02f28ea8bb77389816ae77b14a4257e"},{"name":"plugin","revision":"0.147.0","sha256":"4ad476545c96c83d899c4524dcccd4eb4fe7d3299c307878a0cd46a237f48d58"}]},{"adapterRevision":"1.6.0","name":"portable","observedVersion":"1.0.0","schemas":[{"name":"mcp","revision":"1.0.0","sha256":"6539175bfcdf43085855183e86da40ea94b166547a72b47ae9a0a390516d3acb"},{"name":"plugin","revision":"1.0.0","sha256":"0a4aad95ce337878ad38802ebf0daa3fde76abe3f65400c86bcbb1ec0b3ab883"}]}],"validation":{"artifact":{"status":"passed"},"source":{"status":"passed"},"targets":[{"name":"claude","status":"passed"},{"name":"codex","status":"passed"},{"name":"portable","status":"passed"}]}} diff --git a/examples/skills-starter/artifact/claude/.claude-plugin/marketplace.json b/examples/skills-starter/artifact/claude/.claude-plugin/marketplace.json deleted file mode 100644 index 24cb4579e..000000000 --- a/examples/skills-starter/artifact/claude/.claude-plugin/marketplace.json +++ /dev/null @@ -1 +0,0 @@ -{"description":"A practical engineering operations bundle for incidents, dependency upgrades, and releases.","name":"skills-starter-marketplace","owner":{"name":"skills-starter"},"plugins":[{"description":"A practical engineering operations bundle for incidents, dependency upgrades, and releases.","name":"skills-starter","source":"./","version":"1.0.0"}]} diff --git a/examples/skills-starter/artifact/claude/.claude-plugin/plugin.json b/examples/skills-starter/artifact/claude/.claude-plugin/plugin.json deleted file mode 100644 index 0ef4b4869..000000000 --- a/examples/skills-starter/artifact/claude/.claude-plugin/plugin.json +++ /dev/null @@ -1 +0,0 @@ -{"author":{"name":"skills-starter"},"description":"A practical engineering operations bundle for incidents, dependency upgrades, and releases.","name":"skills-starter","version":"1.0.0"} diff --git a/examples/skills-starter/artifact/claude/INSTALL.md b/examples/skills-starter/artifact/claude/INSTALL.md deleted file mode 100644 index e5e449b39..000000000 --- a/examples/skills-starter/artifact/claude/INSTALL.md +++ /dev/null @@ -1,18 +0,0 @@ -# Install skills-starter - -A practical engineering operations bundle for incidents, dependency upgrades, and releases. - -Version: `1.0.0` - -Run these commands from this bundle directory. - -## Claude Code - -Claude Code installs this bundle through its local marketplace contract: - -```sh -claude plugin marketplace add ./ -claude plugin install skills-starter@skills-starter-marketplace --scope user -``` - -Replace `user` with `project` or `local` when that Claude scope is intended. diff --git a/examples/skills-starter/artifact/claude/skills/dependency-upgrade/SKILL.md b/examples/skills-starter/artifact/claude/skills/dependency-upgrade/SKILL.md deleted file mode 100644 index 5f91ab96e..000000000 --- a/examples/skills-starter/artifact/claude/skills/dependency-upgrade/SKILL.md +++ /dev/null @@ -1,33 +0,0 @@ ---- -name: dependency-upgrade -description: Plans and verifies dependency upgrades with compatibility, rollout, and rollback evidence. ---- -# Dependency upgrade - -## When to use - -Use this Skill for a library, runtime, toolchain, or platform upgrade that can -change public APIs, generated output, operational behavior, or support policy. - -## Required resources - -- Apply [the compatibility checklist](references/compatibility-checklist.md). -- Write the proposal with [the upgrade plan template](assets/upgrade-plan.md). - -## Workflow - -1. Record the current and proposed versions, why the change is needed, and the - supported runtime/package-manager matrix. -2. Read primary release notes and migration guides. List removed APIs, default - changes, peer requirements, and known regressions that intersect this repo. -3. Map affected imports, configuration, generated artifacts, consumers, and - CI/release surfaces before editing. -4. Implement the smallest coherent increment and run focused contract tests, - type checks, production builds, and packed-consumer checks. -5. Define rollout signals and a tested rollback path. Do not call the upgrade - complete until shipped output and a real consumer both pass. - -## Final answer - -State the compatibility decision, changed surfaces, evidence run, remaining -risk, rollout signal, and exact rollback trigger. diff --git a/examples/skills-starter/artifact/claude/skills/dependency-upgrade/assets/upgrade-plan.md b/examples/skills-starter/artifact/claude/skills/dependency-upgrade/assets/upgrade-plan.md deleted file mode 100644 index 15ed88f24..000000000 --- a/examples/skills-starter/artifact/claude/skills/dependency-upgrade/assets/upgrade-plan.md +++ /dev/null @@ -1,21 +0,0 @@ -# Dependency upgrade plan - -## Decision - -Current version, target version, motivation, and compatibility verdict. - -## Affected surfaces - -Imports, configuration, generated output, consumers, CI, and release tooling. - -## Implementation increments - -Each increment, its tests, and its reversible boundary. - -## Verification - -Commands, observed results, and packed or browser consumer evidence. - -## Rollout and rollback - -Owner, monitored signals, rollback trigger, and rollback procedure. diff --git a/examples/skills-starter/artifact/claude/skills/dependency-upgrade/references/compatibility-checklist.md b/examples/skills-starter/artifact/claude/skills/dependency-upgrade/references/compatibility-checklist.md deleted file mode 100644 index 51ac5226a..000000000 --- a/examples/skills-starter/artifact/claude/skills/dependency-upgrade/references/compatibility-checklist.md +++ /dev/null @@ -1,9 +0,0 @@ -# Compatibility checklist - -- Runtime and package-manager support matrix is explicit. -- Direct, peer, optional, and transitive dependency effects are understood. -- Configuration defaults and removed/deprecated APIs are accounted for. -- Generated files and package exports remain deterministic. -- Type checks, focused tests, production builds, and packed consumers pass. -- CI caches, lockfiles, SBOM, license, and provenance checks remain valid. -- Rollout ownership, telemetry, and rollback conditions are documented. diff --git a/examples/skills-starter/artifact/claude/skills/incident-triage/SKILL.md b/examples/skills-starter/artifact/claude/skills/incident-triage/SKILL.md deleted file mode 100644 index e91f53773..000000000 --- a/examples/skills-starter/artifact/claude/skills/incident-triage/SKILL.md +++ /dev/null @@ -1,34 +0,0 @@ ---- -name: incident-triage -description: Triages production incidents with evidence-first containment and a clear operational handoff. ---- -# Incident triage - -## When to use - -Use this Skill when an alert, customer report, or operator observation suggests -an active production incident and the team needs a fast, auditable first pass. - -## Required resources - -- Follow [the triage runbook](references/triage-runbook.md) for the first 30 minutes. -- Record the handoff with [the incident update template](assets/incident-update.md). - -## Workflow - -1. Establish impact: affected users, services, regions, start time, and the - strongest known symptom. Separate observed facts from hypotheses. -2. Preserve evidence before changing the system: relevant request IDs, logs, - metrics, deploys, feature flags, and dependency health. -3. Choose the smallest reversible containment action. State its expected signal - and rollback condition before executing it. -4. Re-evaluate impact after containment. Escalate when severity, ownership, or - blast radius remains uncertain. -5. Produce an incident update with timeline, current impact, actions, owners, - open questions, and the next update time. - -## Guardrails - -- Never claim root cause from correlation alone. -- Never expose credentials, customer payloads, or private identifiers. -- Never make a destructive or irreversible change without explicit authority. diff --git a/examples/skills-starter/artifact/claude/skills/incident-triage/assets/incident-update.md b/examples/skills-starter/artifact/claude/skills/incident-triage/assets/incident-update.md deleted file mode 100644 index 1e2b7529f..000000000 --- a/examples/skills-starter/artifact/claude/skills/incident-triage/assets/incident-update.md +++ /dev/null @@ -1,9 +0,0 @@ -# Incident update - -- **Status:** investigating | identified | monitoring | resolved -- **Impact:** users, services, regions, and start time -- **Observed evidence:** metrics, logs, requests, and recent changes -- **Actions taken:** action, owner, result, and rollback state -- **Current hypothesis:** clearly marked as confirmed or unconfirmed -- **Next steps:** owner and expected completion -- **Next update:** timestamp diff --git a/examples/skills-starter/artifact/claude/skills/incident-triage/references/triage-runbook.md b/examples/skills-starter/artifact/claude/skills/incident-triage/references/triage-runbook.md deleted file mode 100644 index d98d8a283..000000000 --- a/examples/skills-starter/artifact/claude/skills/incident-triage/references/triage-runbook.md +++ /dev/null @@ -1,9 +0,0 @@ -# First 30 minutes - -1. Acknowledge the incident and name an incident lead. -2. Capture the first known bad time and a comparable known-good baseline. -3. Check recent deploys, configuration changes, dependency status, and capacity. -4. Identify one measurable containment hypothesis and its rollback signal. -5. Update stakeholders with facts, uncertainty, owners, and the next checkpoint. - -Severity is driven by user impact and recovery risk, not by alert volume. diff --git a/examples/skills-starter/artifact/claude/skills/release-review/SKILL.md b/examples/skills-starter/artifact/claude/skills/release-review/SKILL.md deleted file mode 100644 index 085376189..000000000 --- a/examples/skills-starter/artifact/claude/skills/release-review/SKILL.md +++ /dev/null @@ -1,34 +0,0 @@ ---- -name: release-review -description: Reviews release evidence and issues an auditable readiness verdict. ---- -# Release review - -## When to use - -Use this Skill when a release candidate needs a go/no-go verdict supported by -checked, reproducible evidence. - -## Required resources - -- Read [the release checklist](references/checklist.md) to inspect the artifact. -- Apply [the release readiness policy](references/release-policy.md) to classify findings. -- Deliver the result with [the release readiness report template](assets/report-template.md). - -## Workflow - -1. Gather evidence for each checklist item. Cite the command, artifact path, - observed result, and reproduction steps for every finding. -2. Classify each finding using the policy severity. A blocker prevents a - `ready` verdict; unresolved non-blockers must still be disclosed. -3. Decide the verdict only after all required evidence is recorded. Use - `ready` only when there are no blockers. -4. Complete every section of the report template: verdict, evidence, findings, - blockers, and required follow-up. - -## Final report requirements - -The final report must state `ready`, `not ready`, or `needs evidence`; list -all evidence reviewed; give each finding a severity and reproduction; and make -the blocker count explicit. Do not issue `ready` when evidence is missing or a -blocker remains. diff --git a/examples/skills-starter/artifact/claude/skills/release-review/assets/report-template.md b/examples/skills-starter/artifact/claude/skills/release-review/assets/report-template.md deleted file mode 100644 index 76fb83fc7..000000000 --- a/examples/skills-starter/artifact/claude/skills/release-review/assets/report-template.md +++ /dev/null @@ -1,22 +0,0 @@ -# Release readiness report - -## Verdict - -State `ready`, `not ready`, or `needs evidence`, and give the blocker count. - -## Evidence reviewed - -For each check, record the command, artifact path, observed result, and date. - -## Findings - -List each concrete issue, its severity, impact, owner, and reproduction. - -## Blockers - -List every unresolved blocker, or state `None`. - -## Required follow-up - -Record the owner, mitigation, and decision date for every unresolved Major or -Minor finding. diff --git a/examples/skills-starter/artifact/claude/skills/release-review/references/checklist.md b/examples/skills-starter/artifact/claude/skills/release-review/references/checklist.md deleted file mode 100644 index 823e865a9..000000000 --- a/examples/skills-starter/artifact/claude/skills/release-review/references/checklist.md +++ /dev/null @@ -1,8 +0,0 @@ -# Release checklist - -1. Confirm the release artifact contains the documented public entrypoints. -2. Confirm generated files are reproducible from the checked-in sources. -3. Run the documented validation, build, and deterministic evaluation commands. -4. Record the command, artifact path, observed output, and reproduction for - every defect. -5. Classify every defect with the severity from the release readiness policy. diff --git a/examples/skills-starter/artifact/claude/skills/release-review/references/release-policy.md b/examples/skills-starter/artifact/claude/skills/release-review/references/release-policy.md deleted file mode 100644 index 09ceb86ba..000000000 --- a/examples/skills-starter/artifact/claude/skills/release-review/references/release-policy.md +++ /dev/null @@ -1,22 +0,0 @@ -# Release readiness policy - -## Evidence standard - -Release evidence must be specific, reproducible, and tied to the candidate: -record the command, artifact path, observed result, and reproduction steps. -Missing or stale evidence is not proof of readiness. - -## Severity - -- **Blocker**: prevents safe release, violates a documented contract, or has no - viable mitigation. Any blocker requires a `not ready` verdict. -- **Major**: materially degrades a supported workflow. It must have an owner, - mitigation, and release decision recorded in the report. -- **Minor**: limited-scope issue with an agreed follow-up. It does not prevent - `ready` when its evidence and owner are recorded. - -## Verdict policy - -Issue `ready` only when all required evidence is current and the blocker list -is empty. Issue `needs evidence` when required evidence is absent, stale, or -cannot be reproduced. Otherwise issue `not ready`. diff --git a/examples/skills-starter/artifact/codex/.agents/plugins/marketplace.json b/examples/skills-starter/artifact/codex/.agents/plugins/marketplace.json deleted file mode 100644 index b3a1fadbc..000000000 --- a/examples/skills-starter/artifact/codex/.agents/plugins/marketplace.json +++ /dev/null @@ -1 +0,0 @@ -{"interface":{"displayName":"skills-starter"},"name":"skills-starter-marketplace","plugins":[{"category":"Productivity","name":"skills-starter","policy":{"authentication":"ON_INSTALL","installation":"AVAILABLE"},"source":{"path":"./","source":"local"}}]} diff --git a/examples/skills-starter/artifact/codex/.codex-plugin/plugin.json b/examples/skills-starter/artifact/codex/.codex-plugin/plugin.json deleted file mode 100644 index 44161e85b..000000000 --- a/examples/skills-starter/artifact/codex/.codex-plugin/plugin.json +++ /dev/null @@ -1 +0,0 @@ -{"author":{"name":"skills-starter"},"description":"A practical engineering operations bundle for incidents, dependency upgrades, and releases.","interface":{"capabilities":["skills"],"category":"Productivity","defaultPrompt":["Help me use skills-starter."],"developerName":"skills-starter","displayName":"skills-starter","longDescription":"A practical engineering operations bundle for incidents, dependency upgrades, and releases.","shortDescription":"A practical engineering operations bundle for incidents, dependency upgrades, and releases."},"name":"skills-starter","skills":"./skills/","version":"1.0.0"} diff --git a/examples/skills-starter/artifact/codex/INSTALL.md b/examples/skills-starter/artifact/codex/INSTALL.md deleted file mode 100644 index 0c56ee69d..000000000 --- a/examples/skills-starter/artifact/codex/INSTALL.md +++ /dev/null @@ -1,16 +0,0 @@ -# Install skills-starter - -A practical engineering operations bundle for incidents, dependency upgrades, and releases. - -Version: `1.0.0` - -Run these commands from this bundle directory. - -## Codex - -Codex installs this bundle from its local marketplace snapshot: - -```sh -codex plugin marketplace add ./ -codex plugin add skills-starter@skills-starter-marketplace -``` diff --git a/examples/skills-starter/artifact/codex/skills/dependency-upgrade/SKILL.md b/examples/skills-starter/artifact/codex/skills/dependency-upgrade/SKILL.md deleted file mode 100644 index 5f91ab96e..000000000 --- a/examples/skills-starter/artifact/codex/skills/dependency-upgrade/SKILL.md +++ /dev/null @@ -1,33 +0,0 @@ ---- -name: dependency-upgrade -description: Plans and verifies dependency upgrades with compatibility, rollout, and rollback evidence. ---- -# Dependency upgrade - -## When to use - -Use this Skill for a library, runtime, toolchain, or platform upgrade that can -change public APIs, generated output, operational behavior, or support policy. - -## Required resources - -- Apply [the compatibility checklist](references/compatibility-checklist.md). -- Write the proposal with [the upgrade plan template](assets/upgrade-plan.md). - -## Workflow - -1. Record the current and proposed versions, why the change is needed, and the - supported runtime/package-manager matrix. -2. Read primary release notes and migration guides. List removed APIs, default - changes, peer requirements, and known regressions that intersect this repo. -3. Map affected imports, configuration, generated artifacts, consumers, and - CI/release surfaces before editing. -4. Implement the smallest coherent increment and run focused contract tests, - type checks, production builds, and packed-consumer checks. -5. Define rollout signals and a tested rollback path. Do not call the upgrade - complete until shipped output and a real consumer both pass. - -## Final answer - -State the compatibility decision, changed surfaces, evidence run, remaining -risk, rollout signal, and exact rollback trigger. diff --git a/examples/skills-starter/artifact/codex/skills/dependency-upgrade/assets/upgrade-plan.md b/examples/skills-starter/artifact/codex/skills/dependency-upgrade/assets/upgrade-plan.md deleted file mode 100644 index 15ed88f24..000000000 --- a/examples/skills-starter/artifact/codex/skills/dependency-upgrade/assets/upgrade-plan.md +++ /dev/null @@ -1,21 +0,0 @@ -# Dependency upgrade plan - -## Decision - -Current version, target version, motivation, and compatibility verdict. - -## Affected surfaces - -Imports, configuration, generated output, consumers, CI, and release tooling. - -## Implementation increments - -Each increment, its tests, and its reversible boundary. - -## Verification - -Commands, observed results, and packed or browser consumer evidence. - -## Rollout and rollback - -Owner, monitored signals, rollback trigger, and rollback procedure. diff --git a/examples/skills-starter/artifact/codex/skills/dependency-upgrade/references/compatibility-checklist.md b/examples/skills-starter/artifact/codex/skills/dependency-upgrade/references/compatibility-checklist.md deleted file mode 100644 index 51ac5226a..000000000 --- a/examples/skills-starter/artifact/codex/skills/dependency-upgrade/references/compatibility-checklist.md +++ /dev/null @@ -1,9 +0,0 @@ -# Compatibility checklist - -- Runtime and package-manager support matrix is explicit. -- Direct, peer, optional, and transitive dependency effects are understood. -- Configuration defaults and removed/deprecated APIs are accounted for. -- Generated files and package exports remain deterministic. -- Type checks, focused tests, production builds, and packed consumers pass. -- CI caches, lockfiles, SBOM, license, and provenance checks remain valid. -- Rollout ownership, telemetry, and rollback conditions are documented. diff --git a/examples/skills-starter/artifact/codex/skills/incident-triage/SKILL.md b/examples/skills-starter/artifact/codex/skills/incident-triage/SKILL.md deleted file mode 100644 index e91f53773..000000000 --- a/examples/skills-starter/artifact/codex/skills/incident-triage/SKILL.md +++ /dev/null @@ -1,34 +0,0 @@ ---- -name: incident-triage -description: Triages production incidents with evidence-first containment and a clear operational handoff. ---- -# Incident triage - -## When to use - -Use this Skill when an alert, customer report, or operator observation suggests -an active production incident and the team needs a fast, auditable first pass. - -## Required resources - -- Follow [the triage runbook](references/triage-runbook.md) for the first 30 minutes. -- Record the handoff with [the incident update template](assets/incident-update.md). - -## Workflow - -1. Establish impact: affected users, services, regions, start time, and the - strongest known symptom. Separate observed facts from hypotheses. -2. Preserve evidence before changing the system: relevant request IDs, logs, - metrics, deploys, feature flags, and dependency health. -3. Choose the smallest reversible containment action. State its expected signal - and rollback condition before executing it. -4. Re-evaluate impact after containment. Escalate when severity, ownership, or - blast radius remains uncertain. -5. Produce an incident update with timeline, current impact, actions, owners, - open questions, and the next update time. - -## Guardrails - -- Never claim root cause from correlation alone. -- Never expose credentials, customer payloads, or private identifiers. -- Never make a destructive or irreversible change without explicit authority. diff --git a/examples/skills-starter/artifact/codex/skills/incident-triage/assets/incident-update.md b/examples/skills-starter/artifact/codex/skills/incident-triage/assets/incident-update.md deleted file mode 100644 index 1e2b7529f..000000000 --- a/examples/skills-starter/artifact/codex/skills/incident-triage/assets/incident-update.md +++ /dev/null @@ -1,9 +0,0 @@ -# Incident update - -- **Status:** investigating | identified | monitoring | resolved -- **Impact:** users, services, regions, and start time -- **Observed evidence:** metrics, logs, requests, and recent changes -- **Actions taken:** action, owner, result, and rollback state -- **Current hypothesis:** clearly marked as confirmed or unconfirmed -- **Next steps:** owner and expected completion -- **Next update:** timestamp diff --git a/examples/skills-starter/artifact/codex/skills/incident-triage/references/triage-runbook.md b/examples/skills-starter/artifact/codex/skills/incident-triage/references/triage-runbook.md deleted file mode 100644 index d98d8a283..000000000 --- a/examples/skills-starter/artifact/codex/skills/incident-triage/references/triage-runbook.md +++ /dev/null @@ -1,9 +0,0 @@ -# First 30 minutes - -1. Acknowledge the incident and name an incident lead. -2. Capture the first known bad time and a comparable known-good baseline. -3. Check recent deploys, configuration changes, dependency status, and capacity. -4. Identify one measurable containment hypothesis and its rollback signal. -5. Update stakeholders with facts, uncertainty, owners, and the next checkpoint. - -Severity is driven by user impact and recovery risk, not by alert volume. diff --git a/examples/skills-starter/artifact/codex/skills/release-review/SKILL.md b/examples/skills-starter/artifact/codex/skills/release-review/SKILL.md deleted file mode 100644 index 085376189..000000000 --- a/examples/skills-starter/artifact/codex/skills/release-review/SKILL.md +++ /dev/null @@ -1,34 +0,0 @@ ---- -name: release-review -description: Reviews release evidence and issues an auditable readiness verdict. ---- -# Release review - -## When to use - -Use this Skill when a release candidate needs a go/no-go verdict supported by -checked, reproducible evidence. - -## Required resources - -- Read [the release checklist](references/checklist.md) to inspect the artifact. -- Apply [the release readiness policy](references/release-policy.md) to classify findings. -- Deliver the result with [the release readiness report template](assets/report-template.md). - -## Workflow - -1. Gather evidence for each checklist item. Cite the command, artifact path, - observed result, and reproduction steps for every finding. -2. Classify each finding using the policy severity. A blocker prevents a - `ready` verdict; unresolved non-blockers must still be disclosed. -3. Decide the verdict only after all required evidence is recorded. Use - `ready` only when there are no blockers. -4. Complete every section of the report template: verdict, evidence, findings, - blockers, and required follow-up. - -## Final report requirements - -The final report must state `ready`, `not ready`, or `needs evidence`; list -all evidence reviewed; give each finding a severity and reproduction; and make -the blocker count explicit. Do not issue `ready` when evidence is missing or a -blocker remains. diff --git a/examples/skills-starter/artifact/codex/skills/release-review/assets/report-template.md b/examples/skills-starter/artifact/codex/skills/release-review/assets/report-template.md deleted file mode 100644 index 76fb83fc7..000000000 --- a/examples/skills-starter/artifact/codex/skills/release-review/assets/report-template.md +++ /dev/null @@ -1,22 +0,0 @@ -# Release readiness report - -## Verdict - -State `ready`, `not ready`, or `needs evidence`, and give the blocker count. - -## Evidence reviewed - -For each check, record the command, artifact path, observed result, and date. - -## Findings - -List each concrete issue, its severity, impact, owner, and reproduction. - -## Blockers - -List every unresolved blocker, or state `None`. - -## Required follow-up - -Record the owner, mitigation, and decision date for every unresolved Major or -Minor finding. diff --git a/examples/skills-starter/artifact/codex/skills/release-review/references/checklist.md b/examples/skills-starter/artifact/codex/skills/release-review/references/checklist.md deleted file mode 100644 index 823e865a9..000000000 --- a/examples/skills-starter/artifact/codex/skills/release-review/references/checklist.md +++ /dev/null @@ -1,8 +0,0 @@ -# Release checklist - -1. Confirm the release artifact contains the documented public entrypoints. -2. Confirm generated files are reproducible from the checked-in sources. -3. Run the documented validation, build, and deterministic evaluation commands. -4. Record the command, artifact path, observed output, and reproduction for - every defect. -5. Classify every defect with the severity from the release readiness policy. diff --git a/examples/skills-starter/artifact/codex/skills/release-review/references/release-policy.md b/examples/skills-starter/artifact/codex/skills/release-review/references/release-policy.md deleted file mode 100644 index 09ceb86ba..000000000 --- a/examples/skills-starter/artifact/codex/skills/release-review/references/release-policy.md +++ /dev/null @@ -1,22 +0,0 @@ -# Release readiness policy - -## Evidence standard - -Release evidence must be specific, reproducible, and tied to the candidate: -record the command, artifact path, observed result, and reproduction steps. -Missing or stale evidence is not proof of readiness. - -## Severity - -- **Blocker**: prevents safe release, violates a documented contract, or has no - viable mitigation. Any blocker requires a `not ready` verdict. -- **Major**: materially degrades a supported workflow. It must have an owner, - mitigation, and release decision recorded in the report. -- **Minor**: limited-scope issue with an agreed follow-up. It does not prevent - `ready` when its evidence and owner are recorded. - -## Verdict policy - -Issue `ready` only when all required evidence is current and the blocker list -is empty. Issue `needs evidence` when required evidence is absent, stale, or -cannot be reproduced. Otherwise issue `not ready`. diff --git a/examples/skills-starter/artifact/portable/INSTALL.md b/examples/skills-starter/artifact/portable/INSTALL.md deleted file mode 100644 index bf452980c..000000000 --- a/examples/skills-starter/artifact/portable/INSTALL.md +++ /dev/null @@ -1,19 +0,0 @@ -# Install skills-starter - -A practical engineering operations bundle for incidents, dependency upgrades, and releases. - -Version: `1.0.0` - -Run these commands from this bundle directory. - -## Portable Agent Plugin - -Portable is a distribution profile, not a host runtime with one universal install location. -This bundle follows the Agent Plugins open standard (Agent Plugins 1.0.0, https://agent-plugins.org). -Cursor loads this format natively from `~/.cursor/plugins/local/`; restart Cursor or run -`Developer: Reload Window` after copying it. Codex, VS Code, GitHub Copilot, Kiro, and ChatGPT -are also native clients. The bundled installer provides the Cursor local copy: - -```sh -node ./install.mjs -``` diff --git a/examples/skills-starter/artifact/portable/install.mjs b/examples/skills-starter/artifact/portable/install.mjs deleted file mode 100644 index 51b9b39a7..000000000 --- a/examples/skills-starter/artifact/portable/install.mjs +++ /dev/null @@ -1,80 +0,0 @@ -#!/usr/bin/env node -import { createHash } from 'node:crypto'; -import { cp, lstat, mkdir, mkdtemp, readFile, readdir, rename, rm } from 'node:fs/promises'; -import { homedir } from 'node:os'; -import { basename, join, resolve } from 'node:path'; -import { fileURLToPath } from 'node:url'; - -const pluginName = "skills-starter"; -const pluginVersion = "1.0.0"; -const source = resolve(fileURLToPath(new URL('.', import.meta.url))); -const cursorRoot = join(homedir(), '.cursor'); -const installRoot = join(cursorRoot, 'plugins', 'local'); -const destination = join(installRoot, pluginName); - -const exists = async (path) => { - try { await lstat(path); return true; } - catch (error) { if (error?.code === 'ENOENT') return false; throw error; } -}; - -const treeHash = async (root, prefix = '') => { - const rootMetadata = await lstat(root); - if (rootMetadata.isSymbolicLink() || !rootMetadata.isDirectory()) { - throw new Error('Refusing unsupported filesystem entry ".".'); - } - const hash = createHash('sha256'); - const visit = async (relative) => { - const absolute = join(root, relative); - const metadata = await lstat(absolute); - if (metadata.isSymbolicLink() || (!metadata.isDirectory() && !metadata.isFile())) { - throw new Error(`Refusing unsupported filesystem entry ${JSON.stringify(relative || '.')}.`); - } - if (metadata.isDirectory()) { - for (const name of (await readdir(absolute)).sort()) await visit(join(relative, name)); - return; - } - hash.update(relative.replaceAll('\\', '/')); - hash.update('\0'); - hash.update(await readFile(absolute)); - hash.update('\0'); - }; - for (const name of (await readdir(root)).sort()) await visit(join(prefix, name)); - return hash.digest('hex'); -}; - -const installedVersion = async () => { - for (const manifest of ['.cursor-plugin/plugin.json', 'plugin.json']) { - try { - const value = JSON.parse(await readFile(join(destination, manifest), 'utf8')); - if (typeof value.version === 'string') return value.version; - } catch (error) { if (error?.code !== 'ENOENT') throw error; } - } - return undefined; -}; - -if (!(await exists(cursorRoot)) || !(await lstat(cursorRoot)).isDirectory()) { - throw new Error(`Cursor is not installed in ${cursorRoot}.`); -} -await mkdir(installRoot, { recursive: true }); -if (await exists(destination)) { - const currentVersion = await installedVersion(); - if (currentVersion !== undefined && currentVersion !== pluginVersion) { - throw new Error(`Refusing version collision at ${destination}: found ${currentVersion}, requested ${pluginVersion}.`); - } - if (source === destination || await treeHash(source) === await treeHash(destination)) { - console.log(`Already installed ${pluginName}@${pluginVersion} at ${destination}`); - process.exit(0); - } - throw new Error(`Refusing content collision at ${destination}.`); -} - -const stageParent = await mkdtemp(join(installRoot, `.${basename(destination)}.stage-`)); -const stage = join(stageParent, 'bundle'); -try { - await cp(source, stage, { errorOnExist: true, force: false, recursive: true, verbatimSymlinks: true }); - await treeHash(stage); - await rename(stage, destination); - console.log(`Installed ${pluginName}@${pluginVersion} at ${destination}`); -} finally { - await rm(stageParent, { force: true, recursive: true }); -} diff --git a/examples/skills-starter/artifact/portable/plugin.json b/examples/skills-starter/artifact/portable/plugin.json deleted file mode 100644 index 42585f082..000000000 --- a/examples/skills-starter/artifact/portable/plugin.json +++ /dev/null @@ -1 +0,0 @@ -{"$schema":"https://agent-plugins.org/schemas/1.0.0/plugin.schema.json","description":"A practical engineering operations bundle for incidents, dependency upgrades, and releases.","name":"skills-starter","version":"1.0.0"} diff --git a/examples/skills-starter/artifact/portable/skills/dependency-upgrade/SKILL.md b/examples/skills-starter/artifact/portable/skills/dependency-upgrade/SKILL.md deleted file mode 100644 index 5f91ab96e..000000000 --- a/examples/skills-starter/artifact/portable/skills/dependency-upgrade/SKILL.md +++ /dev/null @@ -1,33 +0,0 @@ ---- -name: dependency-upgrade -description: Plans and verifies dependency upgrades with compatibility, rollout, and rollback evidence. ---- -# Dependency upgrade - -## When to use - -Use this Skill for a library, runtime, toolchain, or platform upgrade that can -change public APIs, generated output, operational behavior, or support policy. - -## Required resources - -- Apply [the compatibility checklist](references/compatibility-checklist.md). -- Write the proposal with [the upgrade plan template](assets/upgrade-plan.md). - -## Workflow - -1. Record the current and proposed versions, why the change is needed, and the - supported runtime/package-manager matrix. -2. Read primary release notes and migration guides. List removed APIs, default - changes, peer requirements, and known regressions that intersect this repo. -3. Map affected imports, configuration, generated artifacts, consumers, and - CI/release surfaces before editing. -4. Implement the smallest coherent increment and run focused contract tests, - type checks, production builds, and packed-consumer checks. -5. Define rollout signals and a tested rollback path. Do not call the upgrade - complete until shipped output and a real consumer both pass. - -## Final answer - -State the compatibility decision, changed surfaces, evidence run, remaining -risk, rollout signal, and exact rollback trigger. diff --git a/examples/skills-starter/artifact/portable/skills/dependency-upgrade/assets/upgrade-plan.md b/examples/skills-starter/artifact/portable/skills/dependency-upgrade/assets/upgrade-plan.md deleted file mode 100644 index 15ed88f24..000000000 --- a/examples/skills-starter/artifact/portable/skills/dependency-upgrade/assets/upgrade-plan.md +++ /dev/null @@ -1,21 +0,0 @@ -# Dependency upgrade plan - -## Decision - -Current version, target version, motivation, and compatibility verdict. - -## Affected surfaces - -Imports, configuration, generated output, consumers, CI, and release tooling. - -## Implementation increments - -Each increment, its tests, and its reversible boundary. - -## Verification - -Commands, observed results, and packed or browser consumer evidence. - -## Rollout and rollback - -Owner, monitored signals, rollback trigger, and rollback procedure. diff --git a/examples/skills-starter/artifact/portable/skills/dependency-upgrade/references/compatibility-checklist.md b/examples/skills-starter/artifact/portable/skills/dependency-upgrade/references/compatibility-checklist.md deleted file mode 100644 index 51ac5226a..000000000 --- a/examples/skills-starter/artifact/portable/skills/dependency-upgrade/references/compatibility-checklist.md +++ /dev/null @@ -1,9 +0,0 @@ -# Compatibility checklist - -- Runtime and package-manager support matrix is explicit. -- Direct, peer, optional, and transitive dependency effects are understood. -- Configuration defaults and removed/deprecated APIs are accounted for. -- Generated files and package exports remain deterministic. -- Type checks, focused tests, production builds, and packed consumers pass. -- CI caches, lockfiles, SBOM, license, and provenance checks remain valid. -- Rollout ownership, telemetry, and rollback conditions are documented. diff --git a/examples/skills-starter/artifact/portable/skills/incident-triage/SKILL.md b/examples/skills-starter/artifact/portable/skills/incident-triage/SKILL.md deleted file mode 100644 index e91f53773..000000000 --- a/examples/skills-starter/artifact/portable/skills/incident-triage/SKILL.md +++ /dev/null @@ -1,34 +0,0 @@ ---- -name: incident-triage -description: Triages production incidents with evidence-first containment and a clear operational handoff. ---- -# Incident triage - -## When to use - -Use this Skill when an alert, customer report, or operator observation suggests -an active production incident and the team needs a fast, auditable first pass. - -## Required resources - -- Follow [the triage runbook](references/triage-runbook.md) for the first 30 minutes. -- Record the handoff with [the incident update template](assets/incident-update.md). - -## Workflow - -1. Establish impact: affected users, services, regions, start time, and the - strongest known symptom. Separate observed facts from hypotheses. -2. Preserve evidence before changing the system: relevant request IDs, logs, - metrics, deploys, feature flags, and dependency health. -3. Choose the smallest reversible containment action. State its expected signal - and rollback condition before executing it. -4. Re-evaluate impact after containment. Escalate when severity, ownership, or - blast radius remains uncertain. -5. Produce an incident update with timeline, current impact, actions, owners, - open questions, and the next update time. - -## Guardrails - -- Never claim root cause from correlation alone. -- Never expose credentials, customer payloads, or private identifiers. -- Never make a destructive or irreversible change without explicit authority. diff --git a/examples/skills-starter/artifact/portable/skills/incident-triage/assets/incident-update.md b/examples/skills-starter/artifact/portable/skills/incident-triage/assets/incident-update.md deleted file mode 100644 index 1e2b7529f..000000000 --- a/examples/skills-starter/artifact/portable/skills/incident-triage/assets/incident-update.md +++ /dev/null @@ -1,9 +0,0 @@ -# Incident update - -- **Status:** investigating | identified | monitoring | resolved -- **Impact:** users, services, regions, and start time -- **Observed evidence:** metrics, logs, requests, and recent changes -- **Actions taken:** action, owner, result, and rollback state -- **Current hypothesis:** clearly marked as confirmed or unconfirmed -- **Next steps:** owner and expected completion -- **Next update:** timestamp diff --git a/examples/skills-starter/artifact/portable/skills/incident-triage/references/triage-runbook.md b/examples/skills-starter/artifact/portable/skills/incident-triage/references/triage-runbook.md deleted file mode 100644 index d98d8a283..000000000 --- a/examples/skills-starter/artifact/portable/skills/incident-triage/references/triage-runbook.md +++ /dev/null @@ -1,9 +0,0 @@ -# First 30 minutes - -1. Acknowledge the incident and name an incident lead. -2. Capture the first known bad time and a comparable known-good baseline. -3. Check recent deploys, configuration changes, dependency status, and capacity. -4. Identify one measurable containment hypothesis and its rollback signal. -5. Update stakeholders with facts, uncertainty, owners, and the next checkpoint. - -Severity is driven by user impact and recovery risk, not by alert volume. diff --git a/examples/skills-starter/artifact/portable/skills/release-review/SKILL.md b/examples/skills-starter/artifact/portable/skills/release-review/SKILL.md deleted file mode 100644 index 085376189..000000000 --- a/examples/skills-starter/artifact/portable/skills/release-review/SKILL.md +++ /dev/null @@ -1,34 +0,0 @@ ---- -name: release-review -description: Reviews release evidence and issues an auditable readiness verdict. ---- -# Release review - -## When to use - -Use this Skill when a release candidate needs a go/no-go verdict supported by -checked, reproducible evidence. - -## Required resources - -- Read [the release checklist](references/checklist.md) to inspect the artifact. -- Apply [the release readiness policy](references/release-policy.md) to classify findings. -- Deliver the result with [the release readiness report template](assets/report-template.md). - -## Workflow - -1. Gather evidence for each checklist item. Cite the command, artifact path, - observed result, and reproduction steps for every finding. -2. Classify each finding using the policy severity. A blocker prevents a - `ready` verdict; unresolved non-blockers must still be disclosed. -3. Decide the verdict only after all required evidence is recorded. Use - `ready` only when there are no blockers. -4. Complete every section of the report template: verdict, evidence, findings, - blockers, and required follow-up. - -## Final report requirements - -The final report must state `ready`, `not ready`, or `needs evidence`; list -all evidence reviewed; give each finding a severity and reproduction; and make -the blocker count explicit. Do not issue `ready` when evidence is missing or a -blocker remains. diff --git a/examples/skills-starter/artifact/portable/skills/release-review/assets/report-template.md b/examples/skills-starter/artifact/portable/skills/release-review/assets/report-template.md deleted file mode 100644 index 76fb83fc7..000000000 --- a/examples/skills-starter/artifact/portable/skills/release-review/assets/report-template.md +++ /dev/null @@ -1,22 +0,0 @@ -# Release readiness report - -## Verdict - -State `ready`, `not ready`, or `needs evidence`, and give the blocker count. - -## Evidence reviewed - -For each check, record the command, artifact path, observed result, and date. - -## Findings - -List each concrete issue, its severity, impact, owner, and reproduction. - -## Blockers - -List every unresolved blocker, or state `None`. - -## Required follow-up - -Record the owner, mitigation, and decision date for every unresolved Major or -Minor finding. diff --git a/examples/skills-starter/artifact/portable/skills/release-review/references/checklist.md b/examples/skills-starter/artifact/portable/skills/release-review/references/checklist.md deleted file mode 100644 index 823e865a9..000000000 --- a/examples/skills-starter/artifact/portable/skills/release-review/references/checklist.md +++ /dev/null @@ -1,8 +0,0 @@ -# Release checklist - -1. Confirm the release artifact contains the documented public entrypoints. -2. Confirm generated files are reproducible from the checked-in sources. -3. Run the documented validation, build, and deterministic evaluation commands. -4. Record the command, artifact path, observed output, and reproduction for - every defect. -5. Classify every defect with the severity from the release readiness policy. diff --git a/examples/skills-starter/artifact/portable/skills/release-review/references/release-policy.md b/examples/skills-starter/artifact/portable/skills/release-review/references/release-policy.md deleted file mode 100644 index 09ceb86ba..000000000 --- a/examples/skills-starter/artifact/portable/skills/release-review/references/release-policy.md +++ /dev/null @@ -1,22 +0,0 @@ -# Release readiness policy - -## Evidence standard - -Release evidence must be specific, reproducible, and tied to the candidate: -record the command, artifact path, observed result, and reproduction steps. -Missing or stale evidence is not proof of readiness. - -## Severity - -- **Blocker**: prevents safe release, violates a documented contract, or has no - viable mitigation. Any blocker requires a `not ready` verdict. -- **Major**: materially degrades a supported workflow. It must have an owner, - mitigation, and release decision recorded in the report. -- **Minor**: limited-scope issue with an agreed follow-up. It does not prevent - `ready` when its evidence and owner are recorded. - -## Verdict policy - -Issue `ready` only when all required evidence is current and the blocker list -is empty. Issue `needs evidence` when required evidence is absent, stale, or -cannot be reproduced. Otherwise issue `not ready`. diff --git a/packages/rsc-runtime/src/lineage/registry.ts b/packages/rsc-runtime/src/lineage/registry.ts index b4fa005a7..e7b56ed27 100644 --- a/packages/rsc-runtime/src/lineage/registry.ts +++ b/packages/rsc-runtime/src/lineage/registry.ts @@ -1,3 +1,5 @@ +import { createHash } from 'node:crypto'; + import { available, unavailable, @@ -7,6 +9,7 @@ import { } from '../agent-request.js'; import { lineageCarrier, type LineageHost } from '../lineage-native.js'; import type { AgentStateStore } from '../state/contract.js'; +import { canonicalJson } from '../state/index.js'; import { initialLineageState, reduceLineage, @@ -86,6 +89,23 @@ const lineageOf = (node: LineageNode, generation: string | undefined, resolution }), }); +/** + * Deterministic journal keys for one observation: the caller's key, the event + * name, and a digest of the canonical payload. A duplicate delivery produces + * the same payloads and therefore the same keys, whatever the registry already + * knew when it arrived. + */ +interface JournalKeys { + next(name: keyof LineageEvents, payload: unknown): string; +} + +const journalKeys = (idempotencyKey: string): JournalKeys => ({ + next(name, payload) { + const digest = createHash('sha256').update(canonicalJson(payload), 'utf8').digest('hex').slice(0, 16); + return `lineage:${idempotencyKey}:${name}:${digest}`; + }, +}); + const rootNode = (conversation: string, generation: string | undefined, startedAt: string): LineageNode => ({ depth: 0, ...(generation === undefined ? {} : { generation }), @@ -100,7 +120,6 @@ export const createAgentLineageRegistry = ( const { store } = options; let state: LineageState = initialLineageState; let hydrated = store === undefined; - let sequence = 0; const hydrate = async (): Promise => { if (hydrated || store === undefined) return; @@ -112,21 +131,27 @@ export const createAgentLineageRegistry = ( } }; + /** + * Journal keys derive from the caller's idempotency key plus the mutation's + * canonical payload, so a host that delivers the same event twice (Cursor + * repeats some `preToolUse` payloads) replays the same committed journal + * entries instead of appending fresh ones. A replayed commit reports the + * historical snapshot, so the head is re-read instead of rewinding the + * in-memory tree to it. + */ const dispatch = async ( name: TName, payload: Parameters[1]['payload'], - idempotencyKey: string, + keys: JournalKeys, ): Promise => { - sequence += 1; + const idempotencyKey = keys.next(name, payload); if (store === undefined) { state = reduceLineage(state, { name, payload }); return; } try { - const committed = await store.dispatch(name, payload as never, { - idempotencyKey: `lineage:${idempotencyKey}:${String(sequence)}`, - }); - state = committed.state; + const committed = await store.dispatch(name, payload as never, { idempotencyKey }); + state = committed.replayed ? (await store.read()).state : committed.state; } catch { state = reduceLineage(state, { name, payload }); } @@ -137,15 +162,18 @@ export const createAgentLineageRegistry = ( /** * The spawn call that produced the subagent starting now: the most recent - * unclaimed one. Claude keeps the call open across `SubagentStart`; Codex - * closes it first, so the claim window is independent of `openCalls`. + * unclaimed one *under the same root*, so two sessions sharing one durable + * registry never claim each other's spawns. Claude keeps the call open + * across `SubagentStart`; Codex closes it first, so the claim window is + * independent of `openCalls`. */ - const claimSpawn = async (host: LineageHost, key: string): Promise => { + const claimSpawn = async (host: LineageHost, root: string, keys: JournalKeys): Promise => { const spawn = SPAWN_TOOLS[host]; for (let index = state.pendingSpawns.length - 1; index >= 0; index -= 1) { const call = state.pendingSpawns[index]!; if (!spawn(call.toolName)) continue; - await dispatch('spawnClaimed', { toolCallId: call.toolCallId }, `${key}:claim`); + if ((nodeFor(call.conversation)?.root ?? call.conversation) !== root) continue; + await dispatch('spawnClaimed', { toolCallId: call.toolCallId }, keys); return call; } return undefined; @@ -156,7 +184,7 @@ export const createAgentLineageRegistry = ( conversation: string, generation: string | undefined, observedAt: string, - key: string, + keys: JournalKeys, ): Promise => { const existing = state.nodes[conversation]; if (existing !== undefined) return existing; @@ -164,12 +192,12 @@ export const createAgentLineageRegistry = ( // A never-seen Cursor conversation while a subagentStart is pending is // that child speaking for the first time. const subagentId = state.pendingChildren[0]!; - await dispatch('childBound', { conversation, subagentId }, key); + await dispatch('childBound', { conversation, subagentId }, keys); const bound = state.nodes[conversation]; if (bound !== undefined) return bound; } const node = rootNode(conversation, generation, observedAt); - await dispatch('nodeStarted', node, key); + await dispatch('nodeStarted', node, keys); return node; }; @@ -188,15 +216,14 @@ export const createAgentLineageRegistry = ( return available(lineageOf(node, carrier.generation, resolution), resolution === 'native' ? 'native' : 'derived'); }; - const observeStart = async (observation: LineageObservation, observedAt: string): Promise => { + const observeStart = async (observation: LineageObservation, observedAt: string, keys: JournalKeys): Promise => { const { host, native } = observation; const carrier = lineageCarrier(host, native); - const key = observation.idempotencyKey; if (host === 'cursor') { const subagentId = nativeString(native, 'subagent_id') ?? nativeString(native, 'tool_call_id'); const parentId = nativeString(native, 'parent_conversation_id') ?? carrier.conversation; if (subagentId === undefined || parentId === undefined) return; - const parent = await ensureRoot(host, parentId, undefined, observedAt, `${key}:parent`); + const parent = await ensureRoot(host, parentId, undefined, observedAt, keys); await dispatch('nodeStarted', { depth: parent.depth + 1, id: subagentId, @@ -207,14 +234,14 @@ export const createAgentLineageRegistry = ( subagentId, ...(nativeString(native, 'tool_call_id') === undefined ? {} : { toolCallId: nativeString(native, 'tool_call_id')! }), ...(nativeString(native, 'subagent_type') === undefined ? {} : { type: nativeString(native, 'subagent_type')! }), - }, key); + }, keys); return; } const agentId = nativeString(native, 'agent_id'); const root = carrier.root; if (agentId === undefined || root === undefined) return; - const rootNodeValue = await ensureRoot(host, root, undefined, observedAt, `${key}:root`); - const spawn = await claimSpawn(host, key); + const rootNodeValue = await ensureRoot(host, root, undefined, observedAt, keys); + const spawn = await claimSpawn(host, rootNodeValue.root, keys); const parent = (spawn === undefined ? undefined : nodeFor(spawn.conversation)) ?? rootNodeValue; await dispatch('nodeStarted', { depth: parent.depth + 1, @@ -225,10 +252,10 @@ export const createAgentLineageRegistry = ( startedAt: observedAt, ...(spawn === undefined ? {} : { toolCallId: spawn.toolCallId }), ...(nativeString(native, 'agent_type') === undefined ? {} : { type: nativeString(native, 'agent_type')! }), - }, key); + }, keys); }; - const observeStop = async (observation: LineageObservation, observedAt: string): Promise => { + const observeStop = async (observation: LineageObservation, observedAt: string, keys: JournalKeys): Promise => { const { host, native } = observation; const stopped = host === 'cursor' ? (() => { @@ -239,21 +266,22 @@ export const createAgentLineageRegistry = ( })() : nativeString(native, 'agent_id'); if (stopped === undefined || state.nodes[stopped] === undefined) return; - await dispatch('nodeStopped', { id: stopped, stoppedAt: observedAt }, observation.idempotencyKey); + await dispatch('nodeStopped', { id: stopped, stoppedAt: observedAt }, keys); }; const registry: AgentLineageRegistry = { async observe(observation) { await hydrate(); + const keys = journalKeys(observation.idempotencyKey); const observedAt = observation.observedAt ?? new Date().toISOString(); const { event, host, native } = observation; const carrier = lineageCarrier(host, native); switch (event) { case 'agent/start': - await observeStart(observation, observedAt); + await observeStart(observation, observedAt, keys); break; case 'agent/stop': - await observeStop(observation, observedAt); + await observeStop(observation, observedAt, keys); break; default: break; @@ -261,7 +289,7 @@ export const createAgentLineageRegistry = ( // Every other carrier is known or becomes a root; Cursor children bind here. if (carrier.conversation !== undefined && nodeFor(carrier.conversation) === undefined) { const rootLike = host === 'cursor' || carrier.conversation === carrier.root; - if (rootLike) await ensureRoot(host, carrier.conversation, carrier.generation, observedAt, `${observation.idempotencyKey}:carrier`); + if (rootLike) await ensureRoot(host, carrier.conversation, carrier.generation, observedAt, keys); } const toolCallId = nativeString(native, 'tool_use_id') ?? nativeString(native, 'tool_call_id'); const toolName = nativeString(native, 'tool_name'); @@ -273,9 +301,9 @@ export const createAgentLineageRegistry = ( ...(SPAWN_TOOLS[host](toolName) ? { spawn: true } : {}), toolCallId, toolName, - }, observation.idempotencyKey); + }, keys); } else if (event === 'tool/after' || event === 'tool/failure') { - await dispatch('toolCallClosed', { conversation: carrier.conversation, toolCallId }, observation.idempotencyKey); + await dispatch('toolCallClosed', { conversation: carrier.conversation, toolCallId }, keys); } } return resolve(host, native, host === 'cursor' ? 'inferred' : 'registry'); diff --git a/packages/rsc-runtime/tests/lineage-registry.test.ts b/packages/rsc-runtime/tests/lineage-registry.test.ts index ff0f4cfc4..fc4178a09 100644 --- a/packages/rsc-runtime/tests/lineage-registry.test.ts +++ b/packages/rsc-runtime/tests/lineage-registry.test.ts @@ -196,6 +196,51 @@ describe('lineage registry replaying the 2026-09-03 host captures', () => { await driver.close(); }); + it('replays a duplicate delivery through the same journal keys without rewinding the tree', async () => { + const driver = createMemoryStateDriver({ lifetime: 'process' }); + const store = await driver.open(agentLineageStateDefinition('process')); + const registry = createAgentLineageRegistry({ store }); + const before = { + hook_event_name: 'preToolUse', conversation_id: 'root-c', tool_input: {}, tool_name: 'Read', tool_use_id: 'call-1', + }; + await registry.observe({ event: 'tool/before', host: 'cursor', idempotencyKey: 'dup', native: before, observedAt: '2026-09-03T00:00:00.000Z' }); + const revisionAfterFirst = (await store.read()).revision; + // A later, unrelated event advances the journal. + await registry.observe({ event: 'tool/after', host: 'cursor', idempotencyKey: 'after', native: { ...before, hook_event_name: 'postToolUse', tool_output: '{}' }, observedAt: '2026-09-03T00:00:01.000Z' }); + const head = (await store.read()).revision; + // Cursor 3.18.25 delivers some preToolUse payloads twice with the same canonical key. + await registry.observe({ event: 'tool/before', host: 'cursor', idempotencyKey: 'dup', native: before, observedAt: '2026-09-03T00:00:00.000Z' }); + expect((await store.read()).revision).toBe(head); + expect(revisionAfterFirst).toBeLessThan(head); + // The in-memory tree stayed at the head: the window that closed stays closed. + expect(registry.snapshot().openCalls).toEqual([]); + await store.close(); + await driver.close(); + }); + + it('scopes spawn claims to the starting subagent\'s root when two sessions share one registry', async () => { + const registry = createAgentLineageRegistry(); + const spawn = (session: string, id: string) => registry.observe({ + event: 'tool/before', + host: 'claude', + idempotencyKey: `${session}:${id}`, + native: { hook_event_name: 'PreToolUse', session_id: session, tool_input: {}, tool_name: 'Agent', tool_use_id: id }, + }); + await registry.observe({ event: 'session/start', host: 'claude', idempotencyKey: 'a', native: { hook_event_name: 'SessionStart', session_id: 'session-a' } }); + await registry.observe({ event: 'session/start', host: 'claude', idempotencyKey: 'b', native: { hook_event_name: 'SessionStart', session_id: 'session-b' } }); + await spawn('session-a', 'spawn-a'); + await spawn('session-b', 'spawn-b'); + // Session A's child starts after B opened its own spawn: it must claim A's call, not the newest one. + const child = await registry.observe({ + event: 'agent/start', + host: 'claude', + idempotencyKey: 'a:start', + native: { agent_id: 'child-a', agent_type: 'general-purpose', hook_event_name: 'SubagentStart', session_id: 'session-a' }, + }); + expect(value(child)).toMatchObject({ parent: 'session-a', root: 'session-a', subagent: { toolCallId: 'spawn-a' } }); + expect(registry.snapshot().pendingSpawns.map((call) => call.toolCallId)).toEqual(['spawn-b']); + }); + it('answers honestly when the registry never saw the subagent start', async () => { const registry = createAgentLineageRegistry(); const lineage = await registry.observe({ From 75715555fdae9887cc82a339271176aefb9a7339 Mon Sep 17 00:00:00 2001 From: ScriptedAlchemy Date: Thu, 3 Sep 2026 10:51:59 +0000 Subject: [PATCH 06/20] fix(lineage): idempotent start replay, unresolved ambiguous Cursor children, no fabricated Codex depth; probe redacts embedded credentials and fails on host exit (review) --- examples/host-test/scripts/probe.mjs | 6 +++ examples/host-test/src/capture.ts | 17 +++++-- packages/rsc-runtime/src/lineage/registry.ts | 29 +++++++++--- .../tests/lineage-registry.test.ts | 46 +++++++++++++++++++ 4 files changed, 89 insertions(+), 9 deletions(-) diff --git a/examples/host-test/scripts/probe.mjs b/examples/host-test/scripts/probe.mjs index 2a2768dd6..fca3b4a90 100644 --- a/examples/host-test/scripts/probe.mjs +++ b/examples/host-test/scripts/probe.mjs @@ -310,6 +310,12 @@ const capture = () => { } else { log(`no capture log was written at ${logFile}: the host dispatched no hook and no MCP call reached the probe`); } + // The artifacts above are kept for inspection, but a failed host session is + // not evidence: automation must see the failure. + if (result.status !== 0) { + log(`host session failed with exit ${String(result.status)}; captures above are partial evidence at best`); + process.exitCode = result.status ?? 1; + } }; const uninstall = () => { diff --git a/examples/host-test/src/capture.ts b/examples/host-test/src/capture.ts index f32b4f4a7..0dc1caee4 100644 --- a/examples/host-test/src/capture.ts +++ b/examples/host-test/src/capture.ts @@ -59,12 +59,23 @@ const ENV_NAME_PREFIXES = Object.freeze([ // `progressToken` is MCP plumbing, not a credential. const SECRET_KEY = /(?:(? { if (typeof value === 'string') { - if (SECRET_KEY.test(key) || SECRET_VALUE.test(value)) return '[redacted]'; - return value; + if (SECRET_KEY.test(key)) return '[redacted]'; + return value.replace(EMBEDDED_SECRET, '[redacted]'); } if (Array.isArray(value)) return value.map((item) => redactSecrets(item, key)); if (value !== null && typeof value === 'object') { diff --git a/packages/rsc-runtime/src/lineage/registry.ts b/packages/rsc-runtime/src/lineage/registry.ts index e7b56ed27..4ce3bd968 100644 --- a/packages/rsc-runtime/src/lineage/registry.ts +++ b/packages/rsc-runtime/src/lineage/registry.ts @@ -179,22 +179,27 @@ export const createAgentLineageRegistry = ( return undefined; }; + /** + * The node for a conversation that speaks for itself, creating it when it is + * new. A never-seen Cursor conversation while exactly one `subagentStart` is + * pending is that child speaking for the first time; with several pending + * children the child payload carries nothing to tell them apart, so the + * conversation stays unresolved rather than being bound arbitrarily. + */ const ensureRoot = async ( host: LineageHost, conversation: string, generation: string | undefined, observedAt: string, keys: JournalKeys, - ): Promise => { + ): Promise => { const existing = state.nodes[conversation]; if (existing !== undefined) return existing; if (host === 'cursor' && state.pendingChildren.length > 0) { - // A never-seen Cursor conversation while a subagentStart is pending is - // that child speaking for the first time. + if (state.pendingChildren.length > 1) return undefined; const subagentId = state.pendingChildren[0]!; await dispatch('childBound', { conversation, subagentId }, keys); - const bound = state.nodes[conversation]; - if (bound !== undefined) return bound; + return state.nodes[conversation]; } const node = rootNode(conversation, generation, observedAt); await dispatch('nodeStarted', node, keys); @@ -223,7 +228,10 @@ export const createAgentLineageRegistry = ( const subagentId = nativeString(native, 'subagent_id') ?? nativeString(native, 'tool_call_id'); const parentId = nativeString(native, 'parent_conversation_id') ?? carrier.conversation; if (subagentId === undefined || parentId === undefined) return; + // A replayed start already registered (or bound) this child. + if (state.nodes[subagentId] !== undefined || Object.values(state.nodes).some((node) => node.subagentId === subagentId)) return; const parent = await ensureRoot(host, parentId, undefined, observedAt, keys); + if (parent === undefined) return; await dispatch('nodeStarted', { depth: parent.depth + 1, id: subagentId, @@ -240,7 +248,10 @@ export const createAgentLineageRegistry = ( const agentId = nativeString(native, 'agent_id'); const root = carrier.root; if (agentId === undefined || root === undefined) return; + // A replayed start must not claim a second spawn or rewrite the node. + if (state.nodes[agentId] !== undefined) return; const rootNodeValue = await ensureRoot(host, root, undefined, observedAt, keys); + if (rootNodeValue === undefined) return; const spawn = await claimSpawn(host, rootNodeValue.root, keys); const parent = (spawn === undefined ? undefined : nodeFor(spawn.conversation)) ?? rootNodeValue; await dispatch('nodeStarted', { @@ -323,9 +334,15 @@ export const createAgentLineageRegistry = ( const known = nodeFor(conversation); const turnId = nativeString(record, 'turn_id'); const subagentKind = nativeString(record, 'subagent_kind'); + // Codex names conversation, parent, and root but no depth: it is + // known for a registered node, zero for a root, one for a direct + // child of the root, and otherwise only through a registered parent. + const parentDepth = parent === undefined ? undefined : parent === root ? 0 : nodeFor(parent)?.depth; + const depth = known?.depth ?? (parent === undefined ? 0 : parentDepth === undefined ? undefined : parentDepth + 1); + if (depth === undefined) return unavailable('id-not-resolvable'); const value: AgentLineage = { conversation, - depth: known?.depth ?? (parent === undefined ? 0 : (nodeFor(parent)?.depth ?? 0) + 1), + depth, ...(turnId === undefined ? {} : { generation: turnId }), ...(parent === undefined ? {} : { parent }), resolution: 'native', diff --git a/packages/rsc-runtime/tests/lineage-registry.test.ts b/packages/rsc-runtime/tests/lineage-registry.test.ts index fc4178a09..4d6b81575 100644 --- a/packages/rsc-runtime/tests/lineage-registry.test.ts +++ b/packages/rsc-runtime/tests/lineage-registry.test.ts @@ -260,3 +260,49 @@ describe('lineage registry replaying the 2026-09-03 host captures', () => { expect(resolveNativeLineage('cursor', { conversation_id: 'c' })).toEqual(unavailable('no-shared-runtime')); }); }); + +describe('lineage registry edge cases raised in review', () => { + it('ignores a replayed SubagentStart instead of claiming a second spawn or rewriting the node', async () => { + const registry = createAgentLineageRegistry(); + const observe = (event: string, key: string, native: Record) => + registry.observe({ event, host: 'claude', idempotencyKey: key, native }); + await observe('session/start', 'start', { hook_event_name: 'SessionStart', session_id: 'root' }); + await observe('tool/before', 'spawn-1', { hook_event_name: 'PreToolUse', session_id: 'root', tool_input: {}, tool_name: 'Agent', tool_use_id: 'spawn-1' }); + await observe('tool/before', 'spawn-2', { hook_event_name: 'PreToolUse', session_id: 'root', tool_input: {}, tool_name: 'Agent', tool_use_id: 'spawn-2' }); + const start = { agent_id: 'child', agent_type: 'general-purpose', hook_event_name: 'SubagentStart', session_id: 'root' }; + const first = await observe('agent/start', 'child-start', start); + expect(value(first).subagent?.toolCallId).toBe('spawn-2'); + const replayed = await observe('agent/start', 'child-start', start); + expect(value(replayed).subagent?.toolCallId).toBe('spawn-2'); + expect(registry.snapshot().pendingSpawns.map((call) => call.toolCallId)).toEqual(['spawn-1']); + }); + + it('leaves a Cursor child unresolved while two subagent starts are pending, then binds once one has stopped', async () => { + const registry = createAgentLineageRegistry(); + const observe = (event: string, key: string, native: Record) => + registry.observe({ event, host: 'cursor', idempotencyKey: key, native }); + await observe('prompt/submit', 'p', { conversation_id: 'root', hook_event_name: 'beforeSubmitPrompt' }); + const start = (id: string) => ({ + conversation_id: 'root', hook_event_name: 'subagentStart', is_parallel_worker: true, parent_conversation_id: 'root', + subagent_id: id, subagent_type: 'general-purpose', tool_call_id: id, + }); + await observe('agent/start', 'a', start('call-a')); + await observe('agent/start', 'b', start('call-b')); + const ambiguous = await observe('tool/before', 'x', { conversation_id: 'child-x', hook_event_name: 'preToolUse', tool_input: {}, tool_name: 'Shell', tool_use_id: 'x' }); + expect(ambiguous).toEqual(unavailable('id-not-resolvable')); + expect(registry.snapshot().nodes['child-x']).toBeUndefined(); + await observe('agent/stop', 'a-stop', { ...start('call-a'), hook_event_name: 'subagentStop', status: 'completed' }); + const bound = await observe('tool/before', 'y', { conversation_id: 'child-y', hook_event_name: 'preToolUse', tool_input: {}, tool_name: 'Shell', tool_use_id: 'y' }); + expect(value(bound)).toMatchObject({ conversation: 'child-y', depth: 1, parent: 'root', subagent: { id: 'call-b' } }); + }); + + it('does not fabricate a Codex depth when neither the thread nor its parent is registered', () => { + const registry = createAgentLineageRegistry(); + const meta = (thread: string, parent: string | undefined) => ({ + 'x-codex-turn-metadata': { session_id: 'root', thread_id: thread, turn_id: 't', ...(parent === undefined ? {} : { parent_thread_id: parent }) }, + }); + expect(registry.resolveToolCall({ host: 'codex', meta: meta('root', undefined), toolName: 'dump' })).toMatchObject({ value: { depth: 0 } }); + expect(registry.resolveToolCall({ host: 'codex', meta: meta('child', 'root'), toolName: 'dump' })).toMatchObject({ value: { depth: 1, parent: 'root' } }); + expect(registry.resolveToolCall({ host: 'codex', meta: meta('grandchild', 'child'), toolName: 'dump' })).toEqual(unavailable('id-not-resolvable')); + }); +}); From 32c266a558cc2c072f5095b014d68919f6ec8288 Mon Sep 17 00:00:00 2001 From: ScriptedAlchemy Date: Thu, 3 Sep 2026 11:11:17 +0000 Subject: [PATCH 07/20] fix(lineage): shared hydration, timestamp-free replay identity, no root promotion for unknown Cursor carriers, session/end retirement, prune on stop (review) --- docs/entry-conventions.md | 9 ++ packages/rsc-runtime/src/lineage/registry.ts | 96 +++++++++++++++---- packages/rsc-runtime/src/lineage/state.ts | 2 +- .../tests/lineage-registry.test.ts | 89 ++++++++++++++++- 4 files changed, 177 insertions(+), 19 deletions(-) diff --git a/docs/entry-conventions.md b/docs/entry-conventions.md index c15cef544..1c770d3c7 100644 --- a/docs/entry-conventions.md +++ b/docs/entry-conventions.md @@ -422,6 +422,15 @@ for every event by the id the payload carries. The observed host vocabulary | Codex | `agent_id`, else `session_id` | `session_id` | the thread whose `spawn_agent` call is the newest unclaimed spawn | `_meta["x-codex-turn-metadata"]` carries `thread_id`, `parent_thread_id`, `session_id`, `turn_id` natively | | Cursor | `conversation_id` | the bound root | `parent_conversation_id` on `subagentStart`; the child's fresh `conversation_id` is bound to the newest pending start when it first speaks | the newest open `preToolUse` whose `tool_name` is `MCP:` | +Only root-shaped Cursor events (`session/start`, `prompt/submit`, `stop`, +`session/end`, `compact/*`, `workspace/open`) may establish a root; a fresh +Cursor conversation seen on a tool event binds to the single pending +`subagentStart`, and stays unresolved while several are pending or after a +registry restart. `session/end` retires the root and every descendant still +marked live; stopped nodes are pruned past the retention bound as they stop. +Redelivered payloads replay their journal entries (keys derive from the +canonical idempotency key and the payload minus receipt timestamps). + `resolution` says which of those paths produced the answer. When none can, the axis is `unavailable` with a typed reason: `no-subagent-events` (the target defines no subagent families — portable), `id-not-resolvable` (the diff --git a/packages/rsc-runtime/src/lineage/registry.ts b/packages/rsc-runtime/src/lineage/registry.ts index 4ce3bd968..b7df5bb01 100644 --- a/packages/rsc-runtime/src/lineage/registry.ts +++ b/packages/rsc-runtime/src/lineage/registry.ts @@ -8,7 +8,7 @@ import { type Observed, } from '../agent-request.js'; import { lineageCarrier, type LineageHost } from '../lineage-native.js'; -import type { AgentStateStore } from '../state/contract.js'; +import { AgentStateError, type AgentStateStore } from '../state/contract.js'; import { canonicalJson } from '../state/index.js'; import { initialLineageState, @@ -70,6 +70,17 @@ const SPAWN_TOOLS: Readonly boolean>> cursor: (toolName) => toolName === 'Task', }); +/** Cursor events only the user-facing conversation emits; a subagent's conversation never carries them. */ +const CURSOR_ROOT_EVENTS: ReadonlySet = new Set([ + 'session/start', + 'session/end', + 'prompt/submit', + 'stop', + 'compact/before', + 'compact/after', + 'workspace/open', +]); + const lineageOf = (node: LineageNode, generation: string | undefined, resolution: AgentLineageResolution): AgentLineage => Object.freeze({ conversation: node.id, depth: node.depth, @@ -99,9 +110,18 @@ interface JournalKeys { next(name: keyof LineageEvents, payload: unknown): string; } +const RECEIPT_TIMESTAMPS = new Set(['openedAt', 'startedAt', 'stoppedAt']); + +/** Receipt timestamps are regenerated per delivery, so they stay out of the replay identity. */ +const replayIdentity = (payload: unknown): string => canonicalJson( + payload !== null && typeof payload === 'object' && !Array.isArray(payload) + ? Object.fromEntries(Object.entries(payload).filter(([key]) => !RECEIPT_TIMESTAMPS.has(key))) + : payload, +); + const journalKeys = (idempotencyKey: string): JournalKeys => ({ next(name, payload) { - const digest = createHash('sha256').update(canonicalJson(payload), 'utf8').digest('hex').slice(0, 16); + const digest = createHash('sha256').update(replayIdentity(payload), 'utf8').digest('hex').slice(0, 16); return `lineage:${idempotencyKey}:${name}:${digest}`; }, }); @@ -119,16 +139,19 @@ export const createAgentLineageRegistry = ( ): AgentLineageRegistry => { const { store } = options; let state: LineageState = initialLineageState; - let hydrated = store === undefined; + let hydration: Promise | undefined; - const hydrate = async (): Promise => { - if (hydrated || store === undefined) return; - hydrated = true; - try { - state = (await store.read()).state; - } catch { - // A cold or unreadable journal degrades to in-memory tracking; resolution stays honest through `inferred`. - } + /** One shared initial read: concurrent observations all wait for it, none mutates the empty state first. */ + const hydrate = (): Promise => { + if (store === undefined) return Promise.resolve(); + hydration ??= (async () => { + try { + state = (await store.read()).state; + } catch { + // A cold or unreadable journal degrades to in-memory tracking; resolution stays honest through `inferred`. + } + })(); + return hydration; }; /** @@ -152,7 +175,17 @@ export const createAgentLineageRegistry = ( try { const committed = await store.dispatch(name, payload as never, { idempotencyKey }); state = committed.replayed ? (await store.read()).state : committed.state; - } catch { + } catch (error) { + // The same key with a payload that differs only in what the digest + // ignores (a receipt timestamp) is a redelivery, not a new fact. + if (error instanceof AgentStateError && error.code === 'idempotency-conflict') { + try { + state = (await store.read()).state; + } catch { + // Keep the head we already hold. + } + return; + } state = reduceLineage(state, { name, payload }); } }; @@ -192,6 +225,7 @@ export const createAgentLineageRegistry = ( generation: string | undefined, observedAt: string, keys: JournalKeys, + allowRoot: boolean, ): Promise => { const existing = state.nodes[conversation]; if (existing !== undefined) return existing; @@ -201,6 +235,10 @@ export const createAgentLineageRegistry = ( await dispatch('childBound', { conversation, subagentId }, keys); return state.nodes[conversation]; } + // An unknown conversation with no pending start is a root only when the + // event itself is root-shaped; a Cursor child's tool event after a registry + // restart carries nothing that distinguishes it from a root. + if (!allowRoot) return undefined; const node = rootNode(conversation, generation, observedAt); await dispatch('nodeStarted', node, keys); return node; @@ -230,7 +268,7 @@ export const createAgentLineageRegistry = ( if (subagentId === undefined || parentId === undefined) return; // A replayed start already registered (or bound) this child. if (state.nodes[subagentId] !== undefined || Object.values(state.nodes).some((node) => node.subagentId === subagentId)) return; - const parent = await ensureRoot(host, parentId, undefined, observedAt, keys); + const parent = await ensureRoot(host, parentId, undefined, observedAt, keys, false); if (parent === undefined) return; await dispatch('nodeStarted', { depth: parent.depth + 1, @@ -250,7 +288,7 @@ export const createAgentLineageRegistry = ( if (agentId === undefined || root === undefined) return; // A replayed start must not claim a second spawn or rewrite the node. if (state.nodes[agentId] !== undefined) return; - const rootNodeValue = await ensureRoot(host, root, undefined, observedAt, keys); + const rootNodeValue = await ensureRoot(host, root, undefined, observedAt, keys, true); if (rootNodeValue === undefined) return; const spawn = await claimSpawn(host, rootNodeValue.root, keys); const parent = (spawn === undefined ? undefined : nodeFor(spawn.conversation)) ?? rootNodeValue; @@ -280,6 +318,21 @@ export const createAgentLineageRegistry = ( await dispatch('nodeStopped', { id: stopped, stoppedAt: observedAt }, keys); }; + /** A finished session retires its root and every descendant still marked live, so roots never accumulate. */ + const observeSessionEnd = async (observation: LineageObservation, observedAt: string, keys: JournalKeys): Promise => { + const carrier = lineageCarrier(observation.host, observation.native); + const rootId = observation.host === 'cursor' ? carrier.conversation : carrier.root; + if (rootId === undefined) return; + const rootNodeValue = state.nodes[rootId]; + const root = rootNodeValue?.root ?? rootId; + const live = Object.values(state.nodes) + .filter((node) => node.root === root && node.stoppedAt === undefined) + .sort((left, right) => right.depth - left.depth); + for (const node of live) { + await dispatch('nodeStopped', { id: node.id, stoppedAt: observedAt }, keys); + } + }; + const registry: AgentLineageRegistry = { async observe(observation) { await hydrate(); @@ -294,13 +347,22 @@ export const createAgentLineageRegistry = ( case 'agent/stop': await observeStop(observation, observedAt, keys); break; + case 'session/end': + await observeSessionEnd(observation, observedAt, keys); + break; default: break; } - // Every other carrier is known or becomes a root; Cursor children bind here. + // Claude and Codex name the root on every payload; Cursor never repeats + // it, so only root-shaped Cursor events may establish a root, and a + // fresh child conversation binds to the single pending start. if (carrier.conversation !== undefined && nodeFor(carrier.conversation) === undefined) { - const rootLike = host === 'cursor' || carrier.conversation === carrier.root; - if (rootLike) await ensureRoot(host, carrier.conversation, carrier.generation, observedAt, keys); + const rootLike = host === 'cursor' + ? CURSOR_ROOT_EVENTS.has(event) + : carrier.conversation === carrier.root; + if (rootLike || host === 'cursor') { + await ensureRoot(host, carrier.conversation, carrier.generation, observedAt, keys, rootLike); + } } const toolCallId = nativeString(native, 'tool_use_id') ?? nativeString(native, 'tool_call_id'); const toolName = nativeString(native, 'tool_name'); diff --git a/packages/rsc-runtime/src/lineage/state.ts b/packages/rsc-runtime/src/lineage/state.ts index 8a2024a3c..3a05e9d23 100644 --- a/packages/rsc-runtime/src/lineage/state.ts +++ b/packages/rsc-runtime/src/lineage/state.ts @@ -111,7 +111,7 @@ export const reduceLineage = ( if (node === undefined) return state; return { ...state, - nodes: { ...state.nodes, [nodeId]: { ...node, stoppedAt } }, + nodes: pruneStopped({ ...state.nodes, [nodeId]: { ...node, stoppedAt } }), pendingChildren: state.pendingChildren.filter((pending) => pending !== nodeId), }; } diff --git a/packages/rsc-runtime/tests/lineage-registry.test.ts b/packages/rsc-runtime/tests/lineage-registry.test.ts index 4d6b81575..9320d5057 100644 --- a/packages/rsc-runtime/tests/lineage-registry.test.ts +++ b/packages/rsc-runtime/tests/lineage-registry.test.ts @@ -7,6 +7,7 @@ import { unavailable } from '../src/agent-request.js'; import { agentLineageStateDefinition, createAgentLineageRegistry, + LINEAGE_STOPPED_RETENTION, lineageHostFromClient, resolveNativeLineage, type AgentLineageRegistry, @@ -108,9 +109,10 @@ describe('lineage registry replaying the 2026-09-03 host captures', () => { // PostToolUse for MCP tools now arrives (string tool_response), so every window closes. expect(registry.snapshot().openCalls).toEqual([]); + // Both subagents stopped on SubagentStop; SessionEnd retired the root. const snapshot = registry.snapshot(); expect(Object.values(snapshot.nodes).filter((node) => node.stoppedAt !== undefined).map((node) => node.id).sort()) - .toEqual([nested, subagent].sort()); + .toEqual([nested, root, subagent].sort()); }); it('Codex 0.147.0: MCP _meta resolves lineage natively including parent_thread_id; hooks agree', async () => { @@ -306,3 +308,88 @@ describe('lineage registry edge cases raised in review', () => { expect(registry.resolveToolCall({ host: 'codex', meta: meta('grandchild', 'child'), toolName: 'dump' })).toEqual(unavailable('id-not-resolvable')); }); }); + +describe('lineage registry durability and retention (review round 3)', () => { + it('shares one hydration so concurrent first observations see the persisted tree', async () => { + const driver = createMemoryStateDriver({ lifetime: 'process' }); + const store = await driver.open(agentLineageStateDefinition('process')); + const seed = createAgentLineageRegistry({ store }); + await seed.observe({ event: 'session/start', host: 'claude', idempotencyKey: 's', native: { hook_event_name: 'SessionStart', session_id: 'root' } }); + await seed.observe({ event: 'tool/before', host: 'claude', idempotencyKey: 'spawn', native: { hook_event_name: 'PreToolUse', session_id: 'root', tool_input: {}, tool_name: 'Agent', tool_use_id: 'spawn-1' } }); + await seed.observe({ event: 'agent/start', host: 'claude', idempotencyKey: 'start', native: { agent_id: 'child', agent_type: 'general-purpose', hook_event_name: 'SubagentStart', session_id: 'root' } }); + + const fresh = createAgentLineageRegistry({ store }); + const [first, second] = await Promise.all([ + fresh.observe({ event: 'tool/before', host: 'claude', idempotencyKey: 'c1', native: { agent_id: 'child', hook_event_name: 'PreToolUse', session_id: 'root', tool_input: {}, tool_name: 'Bash', tool_use_id: 'c1' } }), + fresh.observe({ event: 'tool/before', host: 'claude', idempotencyKey: 'c2', native: { agent_id: 'child', hook_event_name: 'PreToolUse', session_id: 'root', tool_input: {}, tool_name: 'Bash', tool_use_id: 'c2' } }), + ]); + expect(value(first)).toMatchObject({ conversation: 'child', depth: 1, parent: 'root' }); + expect(value(second)).toMatchObject({ conversation: 'child', depth: 1, parent: 'root' }); + expect(Object.keys(fresh.snapshot().nodes).sort()).toEqual(['child', 'root']); + await store.close(); + await driver.close(); + }); + + it('keeps the receipt timestamp out of the replay identity so a redelivered pre-tool hook cannot reopen a closed window', async () => { + const driver = createMemoryStateDriver({ lifetime: 'process' }); + const store = await driver.open(agentLineageStateDefinition('process')); + const registry = createAgentLineageRegistry({ store }); + const before = { conversation_id: 'root', hook_event_name: 'preToolUse', tool_input: {}, tool_name: 'MCP:dump', tool_use_id: 'm1' }; + await registry.observe({ event: 'prompt/submit', host: 'cursor', idempotencyKey: 'p', native: { conversation_id: 'root', hook_event_name: 'beforeSubmitPrompt' } }); + await registry.observe({ event: 'tool/before', host: 'cursor', idempotencyKey: 'open', native: before, observedAt: '2026-09-03T00:00:00.000Z' }); + await registry.observe({ event: 'tool/after', host: 'cursor', idempotencyKey: 'close', native: { ...before, hook_event_name: 'postToolUse', tool_output: '{}' }, observedAt: '2026-09-03T00:00:01.000Z' }); + await registry.observe({ event: 'tool/before', host: 'cursor', idempotencyKey: 'open', native: before, observedAt: '2026-09-03T00:00:02.000Z' }); + expect(registry.snapshot().openCalls).toEqual([]); + expect(registry.resolveToolCall({ host: 'cursor', toolName: 'dump' })).toEqual(unavailable('id-not-resolvable')); + await store.close(); + await driver.close(); + }); + + it('does not promote an unknown Cursor conversation to a root on a tool event', async () => { + const registry = createAgentLineageRegistry(); + const lineage = await registry.observe({ + event: 'tool/before', + host: 'cursor', + idempotencyKey: 'orphan', + native: { conversation_id: 'maybe-a-child', hook_event_name: 'preToolUse', tool_input: {}, tool_name: 'Shell', tool_use_id: 'x' }, + }); + expect(lineage).toEqual(unavailable('id-not-resolvable')); + expect(registry.snapshot().nodes).toEqual({}); + const root = await registry.observe({ + event: 'prompt/submit', + host: 'cursor', + idempotencyKey: 'prompt', + native: { conversation_id: 'a-root', hook_event_name: 'beforeSubmitPrompt' }, + }); + expect(value(root)).toMatchObject({ conversation: 'a-root', depth: 0 }); + }); + + it('retires the root and its live descendants on session/end', async () => { + const registry = createAgentLineageRegistry(); + const observe = (event: string, key: string, native: Record) => + registry.observe({ event, host: 'codex', idempotencyKey: key, native, observedAt: '2026-09-03T00:00:00.000Z' }); + await observe('session/start', 's', { hook_event_name: 'SessionStart', session_id: 'root' }); + await observe('tool/before', 'sp', { hook_event_name: 'PreToolUse', session_id: 'root', tool_input: {}, tool_name: 'collaborationspawn_agent', tool_use_id: 'sp' }); + await observe('agent/start', 'a', { agent_id: 'child', agent_type: 'default', hook_event_name: 'SubagentStart', session_id: 'root' }); + await observe('session/end', 'e', { hook_event_name: 'SessionEnd', reason: 'other', session_id: 'root' }); + const nodes = registry.snapshot().nodes; + expect(nodes['root']?.stoppedAt).toBe('2026-09-03T00:00:00.000Z'); + expect(nodes['child']?.stoppedAt).toBe('2026-09-03T00:00:00.000Z'); + }); + + it('prunes stopped nodes at the moment they stop, never exceeding the retention bound', async () => { + const registry = createAgentLineageRegistry(); + const observe = (event: string, key: string, native: Record, observedAt: string) => + registry.observe({ event, host: 'claude', idempotencyKey: key, native, observedAt }); + await observe('session/start', 's', { hook_event_name: 'SessionStart', session_id: 'root' }, '2026-09-03T00:00:00.000Z'); + const total = LINEAGE_STOPPED_RETENTION + 10; + for (let index = 0; index < total; index += 1) { + await observe('agent/start', `start-${String(index)}`, { agent_id: `agent-${String(index)}`, agent_type: 'general-purpose', hook_event_name: 'SubagentStart', session_id: 'root' }, `2026-09-03T00:00:${String(index % 60).padStart(2, '0')}.000Z`); + } + for (let index = 0; index < total; index += 1) { + await observe('agent/stop', `stop-${String(index)}`, { agent_id: `agent-${String(index)}`, agent_type: 'general-purpose', hook_event_name: 'SubagentStop', session_id: 'root', stop_hook_active: false }, `2026-09-03T01:${String(Math.floor(index / 60)).padStart(2, '0')}:${String(index % 60).padStart(2, '0')}.000Z`); + } + const stopped = Object.values(registry.snapshot().nodes).filter((node) => node.stoppedAt !== undefined); + expect(stopped.length).toBe(LINEAGE_STOPPED_RETENTION); + }); +}); From fd57d1206a35bb6db0a22b125c710ec34baa8afc Mon Sep 17 00:00:00 2001 From: ScriptedAlchemy Date: Thu, 3 Sep 2026 11:30:32 +0000 Subject: [PATCH 08/20] fix(lineage): refuse ambiguous spawn claims and MCP correlations, root-shaped Cursor events bypass pending binding, bump request store version; probe scrubs ambient credentials (review) --- examples/host-test/scripts/probe.mjs | 12 ++- packages/rsc-runtime/src/agent-request.ts | 4 +- packages/rsc-runtime/src/lineage/registry.ts | 74 ++++++++++--------- .../tests/lineage-registry.test.ts | 64 +++++++++++++++- 4 files changed, 113 insertions(+), 41 deletions(-) diff --git a/examples/host-test/scripts/probe.mjs b/examples/host-test/scripts/probe.mjs index fca3b4a90..db66591b4 100644 --- a/examples/host-test/scripts/probe.mjs +++ b/examples/host-test/scripts/probe.mjs @@ -54,9 +54,15 @@ const paths = { }; const realHome = homedir(); -/** The isolated environment every host command runs with. HOME moves; auth is copied opaquely. */ +/** Ambient credentials never reach a host that runs with permission bypasses; the hosts authenticate from the copied sign-in files. */ +const SECRET_SHAPED_NAME = /(?:TOKEN|SECRET|PASSWORD|PASSWD|API_?KEY|CREDENTIAL|PRIVATE_KEY|ACCESS_KEY|SESSION_KEY|AUTH)/iu; +const scrubbedEnvironment = (base) => Object.fromEntries( + Object.entries(base).filter(([name]) => !SECRET_SHAPED_NAME.test(name)), +); + +/** The isolated environment every host command runs with. HOME moves; auth is copied opaquely; ambient secrets are dropped. */ const isolatedEnvironment = () => { - const environment = { ...process.env, HOME: paths.home, HOST_TEST_LOG_DIR: paths.logDir }; + const environment = { ...scrubbedEnvironment(process.env), HOME: paths.home, HOST_TEST_LOG_DIR: paths.logDir }; switch (host) { case 'claude': environment.CLAUDE_CONFIG_DIR = join(paths.home, '.claude'); @@ -71,8 +77,6 @@ const isolatedEnvironment = () => { default: throw new Error(`unreachable host ${host}`); } - // Nothing from the real host homes leaks through inherited variables. - delete environment.ANTHROPIC_API_KEY; return environment; }; diff --git a/packages/rsc-runtime/src/agent-request.ts b/packages/rsc-runtime/src/agent-request.ts index 80438b230..ea48d0132 100644 --- a/packages/rsc-runtime/src/agent-request.ts +++ b/packages/rsc-runtime/src/agent-request.ts @@ -8,7 +8,9 @@ import type { } from './notices/contract.js'; import type { AgentStateHandle } from './state/contract.js'; -export const AGENT_REQUEST_STORE_VERSION = 2; +// Bumped to 3 when `lineage` joined the handle shape: a realm that already +// holds an older store must fail closed rather than hand out handles without it. +export const AGENT_REQUEST_STORE_VERSION = 3; const STORE_SYMBOL = Symbol.for('@agent-bundle/runtime/request-store'); diff --git a/packages/rsc-runtime/src/lineage/registry.ts b/packages/rsc-runtime/src/lineage/registry.ts index b7df5bb01..cfb0097a6 100644 --- a/packages/rsc-runtime/src/lineage/registry.ts +++ b/packages/rsc-runtime/src/lineage/registry.ts @@ -200,16 +200,22 @@ export const createAgentLineageRegistry = ( * across `SubagentStart`; Codex closes it first, so the claim window is * independent of `openCalls`. */ - const claimSpawn = async (host: LineageHost, root: string, keys: JournalKeys): Promise => { + type SpawnClaim = + | { readonly kind: 'ambiguous' } + | { readonly kind: 'claimed'; readonly call: OpenToolCall; readonly toolCallIdCertain: boolean } + | { readonly kind: 'none' }; + + const claimSpawn = async (host: LineageHost, root: string, keys: JournalKeys): Promise => { const spawn = SPAWN_TOOLS[host]; - for (let index = state.pendingSpawns.length - 1; index >= 0; index -= 1) { - const call = state.pendingSpawns[index]!; - if (!spawn(call.toolName)) continue; - if ((nodeFor(call.conversation)?.root ?? call.conversation) !== root) continue; - await dispatch('spawnClaimed', { toolCallId: call.toolCallId }, keys); - return call; - } - return undefined; + const candidates = state.pendingSpawns.filter((call) => + spawn(call.toolName) && (nodeFor(call.conversation)?.root ?? call.conversation) === root); + if (candidates.length === 0) return { kind: 'none' }; + // Several unclaimed spawns from different parents under one root: the + // start payload carries nothing to pick between them, so no guess. + if (new Set(candidates.map((call) => call.conversation)).size > 1) return { kind: 'ambiguous' }; + const call = candidates[candidates.length - 1]!; + await dispatch('spawnClaimed', { toolCallId: call.toolCallId }, keys); + return { call, kind: 'claimed', toolCallIdCertain: candidates.length === 1 }; }; /** @@ -229,19 +235,21 @@ export const createAgentLineageRegistry = ( ): Promise => { const existing = state.nodes[conversation]; if (existing !== undefined) return existing; - if (host === 'cursor' && state.pendingChildren.length > 0) { - if (state.pendingChildren.length > 1) return undefined; + // A root-shaped event is a root: it never binds to a pending child, so an + // unrelated conversation starting beside a pending spawn stays its own root. + if (allowRoot) { + const node = rootNode(conversation, generation, observedAt); + await dispatch('nodeStarted', node, keys); + return node; + } + if (host === 'cursor' && state.pendingChildren.length === 1) { const subagentId = state.pendingChildren[0]!; await dispatch('childBound', { conversation, subagentId }, keys); return state.nodes[conversation]; } - // An unknown conversation with no pending start is a root only when the - // event itself is root-shaped; a Cursor child's tool event after a registry - // restart carries nothing that distinguishes it from a root. - if (!allowRoot) return undefined; - const node = rootNode(conversation, generation, observedAt); - await dispatch('nodeStarted', node, keys); - return node; + // No single pending start and not root-shaped: a Cursor child's tool event + // after a registry restart carries nothing that distinguishes it from a root. + return undefined; }; const resolve = ( @@ -290,8 +298,9 @@ export const createAgentLineageRegistry = ( if (state.nodes[agentId] !== undefined) return; const rootNodeValue = await ensureRoot(host, root, undefined, observedAt, keys, true); if (rootNodeValue === undefined) return; - const spawn = await claimSpawn(host, rootNodeValue.root, keys); - const parent = (spawn === undefined ? undefined : nodeFor(spawn.conversation)) ?? rootNodeValue; + const claim = await claimSpawn(host, rootNodeValue.root, keys); + if (claim.kind === 'ambiguous') return; + const parent = (claim.kind === 'claimed' ? nodeFor(claim.call.conversation) : undefined) ?? rootNodeValue; await dispatch('nodeStarted', { depth: parent.depth + 1, ...(carrier.generation === undefined ? {} : { generation: carrier.generation }), @@ -299,7 +308,7 @@ export const createAgentLineageRegistry = ( parent: parent.id, root: rootNodeValue.root, startedAt: observedAt, - ...(spawn === undefined ? {} : { toolCallId: spawn.toolCallId }), + ...(claim.kind === 'claimed' && claim.toolCallIdCertain ? { toolCallId: claim.call.toolCallId } : {}), ...(nativeString(native, 'agent_type') === undefined ? {} : { type: nativeString(native, 'agent_type')! }), }, keys); }; @@ -423,19 +432,16 @@ export const createAgentLineageRegistry = ( call = state.openCalls.find((open) => open.toolCallId === claudeToolUseId); } if (call === undefined) { - // The most recent open pre-tool hook naming this tool: `MCP:` on - // Cursor, `mcp____` on Codex, `mcp__plugin_

          ___` on Claude. - for (let index = state.openCalls.length - 1; index >= 0; index -= 1) { - const candidate = state.openCalls[index]!; - if ( - candidate.toolName === `MCP:${toolName}` - || candidate.toolName.endsWith(`__${toolName}`) - || candidate.toolName === toolName - ) { - call = candidate; - break; - } - } + // The open pre-tool hooks naming this tool: `MCP:` on Cursor, + // `mcp____` on Codex, `mcp__plugin_

          ___` on + // Claude. Several from one conversation share a lineage; several from + // different conversations cannot be told apart without `_meta`. + const matches = state.openCalls.filter((candidate) => + candidate.toolName === `MCP:${toolName}` + || candidate.toolName.endsWith(`__${toolName}`) + || candidate.toolName === toolName); + if (new Set(matches.map((candidate) => candidate.conversation)).size > 1) return unavailable('id-not-resolvable'); + call = matches[matches.length - 1]; } if (call === undefined) return unavailable('id-not-resolvable'); const node = nodeFor(call.conversation); diff --git a/packages/rsc-runtime/tests/lineage-registry.test.ts b/packages/rsc-runtime/tests/lineage-registry.test.ts index 9320d5057..003b6ca18 100644 --- a/packages/rsc-runtime/tests/lineage-registry.test.ts +++ b/packages/rsc-runtime/tests/lineage-registry.test.ts @@ -273,9 +273,12 @@ describe('lineage registry edge cases raised in review', () => { await observe('tool/before', 'spawn-2', { hook_event_name: 'PreToolUse', session_id: 'root', tool_input: {}, tool_name: 'Agent', tool_use_id: 'spawn-2' }); const start = { agent_id: 'child', agent_type: 'general-purpose', hook_event_name: 'SubagentStart', session_id: 'root' }; const first = await observe('agent/start', 'child-start', start); - expect(value(first).subagent?.toolCallId).toBe('spawn-2'); + // Two sibling spawns from the same parent: the parent is certain, the exact tool call is not. + expect(value(first)).toMatchObject({ depth: 1, parent: 'root' }); + expect(value(first).subagent?.toolCallId).toBeUndefined(); + expect(registry.snapshot().pendingSpawns.map((call) => call.toolCallId)).toEqual(['spawn-1']); const replayed = await observe('agent/start', 'child-start', start); - expect(value(replayed).subagent?.toolCallId).toBe('spawn-2'); + expect(value(replayed)).toMatchObject({ depth: 1, parent: 'root' }); expect(registry.snapshot().pendingSpawns.map((call) => call.toolCallId)).toEqual(['spawn-1']); }); @@ -393,3 +396,60 @@ describe('lineage registry durability and retention (review round 3)', () => { expect(stopped.length).toBe(LINEAGE_STOPPED_RETENTION); }); }); + +describe('lineage registry ambiguity refusals (review round 4)', () => { + it('keeps a root-shaped Cursor conversation a root even while another root has a pending child', async () => { + const registry = createAgentLineageRegistry(); + const observe = (event: string, key: string, native: Record) => + registry.observe({ event, host: 'cursor', idempotencyKey: key, native }); + await observe('prompt/submit', 'a', { conversation_id: 'root-a', hook_event_name: 'beforeSubmitPrompt' }); + await observe('agent/start', 'a-spawn', { + conversation_id: 'root-a', hook_event_name: 'subagentStart', parent_conversation_id: 'root-a', subagent_id: 'call-a', tool_call_id: 'call-a', + }); + const other = await observe('prompt/submit', 'b', { conversation_id: 'root-b', hook_event_name: 'beforeSubmitPrompt' }); + expect(value(other)).toMatchObject({ conversation: 'root-b', depth: 0, root: 'root-b' }); + // The pending child is still waiting for A's real child conversation. + const child = await observe('tool/before', 'c', { conversation_id: 'child-a', hook_event_name: 'preToolUse', tool_input: {}, tool_name: 'Shell', tool_use_id: 'c' }); + expect(value(child)).toMatchObject({ conversation: 'child-a', depth: 1, parent: 'root-a', root: 'root-a' }); + }); + + it('refuses a spawn claim when two different parents under one root have unclaimed spawns', async () => { + const registry = createAgentLineageRegistry(); + const observe = (event: string, key: string, native: Record) => + registry.observe({ event, host: 'claude', idempotencyKey: key, native }); + await observe('session/start', 's', { hook_event_name: 'SessionStart', session_id: 'root' }); + await observe('tool/before', 'sp1', { hook_event_name: 'PreToolUse', session_id: 'root', tool_input: {}, tool_name: 'Agent', tool_use_id: 'sp1' }); + await observe('agent/start', 'p', { agent_id: 'parent-agent', agent_type: 'general-purpose', hook_event_name: 'SubagentStart', session_id: 'root' }); + await observe('tool/before', 'sp2', { hook_event_name: 'PreToolUse', session_id: 'root', tool_input: {}, tool_name: 'Agent', tool_use_id: 'sp2' }); + await observe('tool/before', 'sp3', { agent_id: 'parent-agent', hook_event_name: 'PreToolUse', session_id: 'root', tool_input: {}, tool_name: 'Agent', tool_use_id: 'sp3' }); + const ambiguous = await observe('agent/start', 'n', { agent_id: 'new-agent', agent_type: 'general-purpose', hook_event_name: 'SubagentStart', session_id: 'root' }); + expect(ambiguous).toEqual(unavailable('id-not-resolvable')); + expect(registry.snapshot().pendingSpawns.map((call) => call.toolCallId).sort()).toEqual(['sp2', 'sp3']); + }); + + it('claims siblings from one parent but marks the tool call uncertain', async () => { + const registry = createAgentLineageRegistry(); + const observe = (event: string, key: string, native: Record) => + registry.observe({ event, host: 'claude', idempotencyKey: key, native }); + await observe('session/start', 's', { hook_event_name: 'SessionStart', session_id: 'root' }); + await observe('tool/before', 'sp1', { hook_event_name: 'PreToolUse', session_id: 'root', tool_input: {}, tool_name: 'Agent', tool_use_id: 'sp1' }); + await observe('tool/before', 'sp2', { hook_event_name: 'PreToolUse', session_id: 'root', tool_input: {}, tool_name: 'Agent', tool_use_id: 'sp2' }); + const sibling = await observe('agent/start', 'n', { agent_id: 'sibling', agent_type: 'general-purpose', hook_event_name: 'SubagentStart', session_id: 'root' }); + expect(value(sibling)).toMatchObject({ depth: 1, parent: 'root' }); + expect(value(sibling).subagent?.toolCallId).toBeUndefined(); + }); + + it('refuses to correlate an MCP call when open windows for the tool span several conversations', async () => { + const registry = createAgentLineageRegistry(); + const observe = (event: string, key: string, native: Record) => + registry.observe({ event, host: 'cursor', idempotencyKey: key, native }); + await observe('prompt/submit', 'a', { conversation_id: 'root-a', hook_event_name: 'beforeSubmitPrompt' }); + await observe('prompt/submit', 'b', { conversation_id: 'root-b', hook_event_name: 'beforeSubmitPrompt' }); + await observe('tool/before', 'ma', { conversation_id: 'root-a', hook_event_name: 'preToolUse', tool_input: {}, tool_name: 'MCP:dump', tool_use_id: 'ma' }); + expect(registry.resolveToolCall({ host: 'cursor', toolName: 'dump' })).toMatchObject({ value: { conversation: 'root-a' } }); + await observe('tool/before', 'mb', { conversation_id: 'root-b', hook_event_name: 'preToolUse', tool_input: {}, tool_name: 'MCP:dump', tool_use_id: 'mb' }); + expect(registry.resolveToolCall({ host: 'cursor', toolName: 'dump' })).toEqual(unavailable('id-not-resolvable')); + await observe('tool/after', 'mb-close', { conversation_id: 'root-b', hook_event_name: 'postToolUse', tool_input: {}, tool_name: 'MCP:dump', tool_output: '{}', tool_use_id: 'mb' }); + expect(registry.resolveToolCall({ host: 'cursor', toolName: 'dump' })).toMatchObject({ value: { conversation: 'root-a' } }); + }); +}); From 799f462f716dd7eef88873b86aeafa5af4a433eb Mon Sep 17 00:00:00 2001 From: ScriptedAlchemy Date: Thu, 3 Sep 2026 11:49:31 +0000 Subject: [PATCH 09/20] fix(lineage): keep sibling spawn cohorts uncertain, skip root creation on a cold session/end, release a retired root's correlation windows (review) --- packages/rsc-runtime/src/lineage/registry.ts | 12 ++++-- packages/rsc-runtime/src/lineage/state.ts | 32 +++++++++++++-- .../tests/lineage-registry.test.ts | 40 +++++++++++++++++++ 3 files changed, 77 insertions(+), 7 deletions(-) diff --git a/packages/rsc-runtime/src/lineage/registry.ts b/packages/rsc-runtime/src/lineage/registry.ts index cfb0097a6..22b73fbcc 100644 --- a/packages/rsc-runtime/src/lineage/registry.ts +++ b/packages/rsc-runtime/src/lineage/registry.ts @@ -214,8 +214,11 @@ export const createAgentLineageRegistry = ( // start payload carries nothing to pick between them, so no guess. if (new Set(candidates.map((call) => call.conversation)).size > 1) return { kind: 'ambiguous' }; const call = candidates[candidates.length - 1]!; - await dispatch('spawnClaimed', { toolCallId: call.toolCallId }, keys); - return { call, kind: 'claimed', toolCallIdCertain: candidates.length === 1 }; + // One of several same-parent spawns is picked blind; the whole cohort, + // including the last one left, then stays uncertain. + const cohort = candidates.length > 1; + await dispatch('spawnClaimed', { ...(cohort ? { siblingsUncertain: true } : {}), toolCallId: call.toolCallId }, keys); + return { call, kind: 'claimed', toolCallIdCertain: !cohort && call.uncertain !== true }; }; /** @@ -340,6 +343,7 @@ export const createAgentLineageRegistry = ( for (const node of live) { await dispatch('nodeStopped', { id: node.id, stoppedAt: observedAt }, keys); } + await dispatch('sessionRetired', { root }, keys); }; const registry: AgentLineageRegistry = { @@ -365,7 +369,9 @@ export const createAgentLineageRegistry = ( // Claude and Codex name the root on every payload; Cursor never repeats // it, so only root-shaped Cursor events may establish a root, and a // fresh child conversation binds to the single pending start. - if (carrier.conversation !== undefined && nodeFor(carrier.conversation) === undefined) { + // A session that ends before this registry saw it start leaves no node + // behind: establishing one after retirement would never be pruned. + if (event !== 'session/end' && carrier.conversation !== undefined && nodeFor(carrier.conversation) === undefined) { const rootLike = host === 'cursor' ? CURSOR_ROOT_EVENTS.has(event) : carrier.conversation === carrier.root; diff --git a/packages/rsc-runtime/src/lineage/state.ts b/packages/rsc-runtime/src/lineage/state.ts index 3a05e9d23..a15129f87 100644 --- a/packages/rsc-runtime/src/lineage/state.ts +++ b/packages/rsc-runtime/src/lineage/state.ts @@ -31,6 +31,8 @@ export const OpenToolCallSchema = z.object({ openedAt: timestamp, toolCallId: id, toolName: id, + /** A sibling of this spawn was already claimed blind, so no later start can be matched to it with certainty. */ + uncertain: z.boolean().optional(), }).strict(); export const LineageStateSchema = z.object({ @@ -56,8 +58,10 @@ export const lineageEventSchemas = { childBound: z.object({ conversation: id, subagentId: id }).strict(), nodeStarted: LineageNodeSchema, nodeStopped: z.object({ id, stoppedAt: timestamp }).strict(), - /** A subagent start consumed the spawn call that produced it. */ - spawnClaimed: z.object({ toolCallId: id }).strict(), + /** A finished session releases its correlation windows and pending spawns. */ + sessionRetired: z.object({ root: id }).strict(), + /** A subagent start consumed the spawn call that produced it; `siblingsUncertain` marks the cohort it was picked from. */ + spawnClaimed: z.object({ siblingsUncertain: z.boolean().optional(), toolCallId: id }).strict(), toolCallClosed: z.object({ conversation: id, toolCallId: id }).strict(), toolCallOpened: OpenToolCallSchema.extend({ spawn: z.boolean().optional() }).strict(), } as const; @@ -147,8 +151,28 @@ export const reduceLineage = ( return { ...state, openCalls: state.openCalls.filter((open) => open.toolCallId !== toolCallId) }; } case 'spawnClaimed': { - const { toolCallId } = event.payload as { toolCallId: string }; - return { ...state, pendingSpawns: state.pendingSpawns.filter((open) => open.toolCallId !== toolCallId) }; + const { siblingsUncertain, toolCallId } = event.payload as { siblingsUncertain?: boolean; toolCallId: string }; + const claimed = state.pendingSpawns.find((open) => open.toolCallId === toolCallId); + return { + ...state, + pendingSpawns: state.pendingSpawns + .filter((open) => open.toolCallId !== toolCallId) + .map((open) => siblingsUncertain === true && claimed !== undefined && open.conversation === claimed.conversation + ? { ...open, uncertain: true } + : open), + }; + } + case 'sessionRetired': { + const { root } = event.payload as { root: string }; + const retired = new Set( + Object.values(state.nodes).filter((node) => node.root === root).map((node) => node.id).concat(root), + ); + return { + ...state, + openCalls: state.openCalls.filter((open) => !retired.has(open.conversation)), + pendingChildren: state.pendingChildren.filter((pending) => !retired.has(pending)), + pendingSpawns: state.pendingSpawns.filter((open) => !retired.has(open.conversation)), + }; } default: { const unreachable: never = event.name; diff --git a/packages/rsc-runtime/tests/lineage-registry.test.ts b/packages/rsc-runtime/tests/lineage-registry.test.ts index 003b6ca18..8f6c4c0c9 100644 --- a/packages/rsc-runtime/tests/lineage-registry.test.ts +++ b/packages/rsc-runtime/tests/lineage-registry.test.ts @@ -453,3 +453,43 @@ describe('lineage registry ambiguity refusals (review round 4)', () => { expect(registry.resolveToolCall({ host: 'cursor', toolName: 'dump' })).toMatchObject({ value: { conversation: 'root-a' } }); }); }); + +describe('lineage registry retirement and cohorts (review round 5)', () => { + const claude = (registry: ReturnType) => + (event: string, key: string, native: Record) => + registry.observe({ event, host: 'claude', idempotencyKey: key, native, observedAt: '2026-09-03T00:00:00.000Z' }); + + it('keeps the whole sibling cohort uncertain, including the last spawn left', async () => { + const registry = createAgentLineageRegistry(); + const observe = claude(registry); + await observe('session/start', 's', { hook_event_name: 'SessionStart', session_id: 'root' }); + await observe('tool/before', 'sp1', { hook_event_name: 'PreToolUse', session_id: 'root', tool_input: {}, tool_name: 'Agent', tool_use_id: 'sp1' }); + await observe('tool/before', 'sp2', { hook_event_name: 'PreToolUse', session_id: 'root', tool_input: {}, tool_name: 'Agent', tool_use_id: 'sp2' }); + const first = await observe('agent/start', 'a', { agent_id: 'a', agent_type: 'general-purpose', hook_event_name: 'SubagentStart', session_id: 'root' }); + const second = await observe('agent/start', 'b', { agent_id: 'b', agent_type: 'general-purpose', hook_event_name: 'SubagentStart', session_id: 'root' }); + expect(value(first).subagent?.toolCallId).toBeUndefined(); + expect(value(second).subagent?.toolCallId).toBeUndefined(); + expect(value(second)).toMatchObject({ depth: 1, parent: 'root' }); + expect(registry.snapshot().pendingSpawns).toEqual([]); + }); + + it('does not create a root for a session/end the registry never saw start', async () => { + const registry = createAgentLineageRegistry(); + const observe = claude(registry); + const ended = await observe('session/end', 'e', { hook_event_name: 'SessionEnd', reason: 'other', session_id: 'ghost' }); + expect(ended).toEqual(unavailable('id-not-resolvable')); + expect(registry.snapshot().nodes).toEqual({}); + }); + + it('releases the retired root\'s correlation windows and pending spawns', async () => { + const registry = createAgentLineageRegistry(); + const observe = claude(registry); + await observe('session/start', 's', { hook_event_name: 'SessionStart', session_id: 'root' }); + await observe('tool/before', 'sp', { hook_event_name: 'PreToolUse', session_id: 'root', tool_input: {}, tool_name: 'Agent', tool_use_id: 'sp' }); + await observe('tool/before', 'mcp', { hook_event_name: 'PreToolUse', session_id: 'root', tool_input: {}, tool_name: 'mcp__plugin_x_y__dump', tool_use_id: 'm' }); + await observe('session/end', 'e', { hook_event_name: 'SessionEnd', reason: 'other', session_id: 'root' }); + expect(registry.snapshot().openCalls).toEqual([]); + expect(registry.snapshot().pendingSpawns).toEqual([]); + expect(registry.resolveToolCall({ host: 'claude', toolName: 'dump' })).toEqual(unavailable('id-not-resolvable')); + }); +}); From 927b12cca5d5496fee2ffe1013ea8fba9d9da6df Mon Sep 17 00:00:00 2001 From: ScriptedAlchemy Date: Thu, 3 Sep 2026 12:10:01 +0000 Subject: [PATCH 10/20] fix(lineage): re-read the shared journal on tool calls, treat unmatched Claude ids as misses, dedupe storeless redeliveries (review) --- docs/entry-conventions.md | 8 ++- .../agent-bundle/src/mcp-server-runtime.ts | 6 +- packages/rsc-runtime/src/lineage/registry.ts | 30 +++++++++- .../tests/lineage-registry.test.ts | 57 +++++++++++++++---- 4 files changed, 82 insertions(+), 19 deletions(-) diff --git a/docs/entry-conventions.md b/docs/entry-conventions.md index 1c770d3c7..426fe068a 100644 --- a/docs/entry-conventions.md +++ b/docs/entry-conventions.md @@ -429,7 +429,13 @@ Cursor conversation seen on a tool event binds to the single pending registry restart. `session/end` retires the root and every descendant still marked live; stopped nodes are pruned past the retention bound as they stop. Redelivered payloads replay their journal entries (keys derive from the -canonical idempotency key and the payload minus receipt timestamps). +canonical idempotency key and the payload minus receipt timestamps; a +storeless registry keeps an in-memory ledger of applied keys). A project with +several generated MCP servers attaches its event routes to one of them; the +others resolve tool calls by re-reading the shared journal, so their +`request.lineage` is populated only when the project's state is +workspace-durable — volatile and stateless multi-server projects report +`id-not-resolvable` from the servers that host no event routes. `resolution` says which of those paths produced the answer. When none can, the axis is `unavailable` with a typed reason: `no-subagent-events` (the diff --git a/packages/agent-bundle/src/mcp-server-runtime.ts b/packages/agent-bundle/src/mcp-server-runtime.ts index d4357b600..5b1a94baf 100644 --- a/packages/agent-bundle/src/mcp-server-runtime.ts +++ b/packages/agent-bundle/src/mcp-server-runtime.ts @@ -116,13 +116,13 @@ interface GeneratedRouteIdentity { * registry (a project with no event routes, or the in-memory proof level) the * axis is honestly absent. */ -const toolCallLineage = ( +const toolCallLineage = async ( registry: AgentLineageRegistry | undefined, context: GeneratedRouteRequestContext, toolName: string, clientName: string | undefined, fallbackHost: LineageHost | undefined, -): Observed => { +): Promise> => { if (registry === undefined) return unavailable('not-provided'); return registry.resolveToolCall({ host: lineageHostFromClient(clientName) ?? fallbackHost, @@ -314,7 +314,7 @@ export const registerGeneratedRoutes = ( route, input, context, - { clientName, lineage: toolCallLineage(options.lineage, context, route.name, clientName, options.lineageHost) }, + { clientName, lineage: await toolCallLineage(options.lineage, context, route.name, clientName, options.lineageHost) }, ); return attachMcpStructuredContent(rendered.toolResult, rendered.result); }, options.afterRender)) as never); diff --git a/packages/rsc-runtime/src/lineage/registry.ts b/packages/rsc-runtime/src/lineage/registry.ts index 22b73fbcc..f23d246d5 100644 --- a/packages/rsc-runtime/src/lineage/registry.ts +++ b/packages/rsc-runtime/src/lineage/registry.ts @@ -48,8 +48,13 @@ export interface LineageToolCallQuery { export interface AgentLineageRegistry { /** Feeds the registry with one hook event and resolves the lineage of the conversation that carried it. */ observe(observation: LineageObservation): Promise>; - /** Resolves the lineage of an MCP tool call from `_meta` or from the open pre-tool hook window. */ - resolveToolCall(query: LineageToolCallQuery): Observed; + /** + * Resolves the lineage of an MCP tool call from `_meta` or from the open + * pre-tool hook window. A durable registry re-reads its journal first, so a + * generated server that hosts no event routes still sees what the event-host + * server recorded. + */ + resolveToolCall(query: LineageToolCallQuery): Promise>; /** The current tree, for dumps and the Workbench. */ snapshot(): LineageState; } @@ -111,6 +116,8 @@ interface JournalKeys { } const RECEIPT_TIMESTAMPS = new Set(['openedAt', 'startedAt', 'stoppedAt']); +/** Journal keys a storeless registry remembers to suppress redeliveries. */ +const APPLIED_KEY_RETENTION = 4096; /** Receipt timestamps are regenerated per delivery, so they stay out of the replay identity. */ const replayIdentity = (payload: unknown): string => canonicalJson( @@ -140,6 +147,7 @@ export const createAgentLineageRegistry = ( const { store } = options; let state: LineageState = initialLineageState; let hydration: Promise | undefined; + const applied = new Set(); /** One shared initial read: concurrent observations all wait for it, none mutates the empty state first. */ const hydrate = (): Promise => { @@ -169,6 +177,10 @@ export const createAgentLineageRegistry = ( ): Promise => { const idempotencyKey = keys.next(name, payload); if (store === undefined) { + // No journal: an in-memory ledger of applied keys suppresses redeliveries. + if (applied.has(idempotencyKey)) return; + applied.add(idempotencyKey); + if (applied.size > APPLIED_KEY_RETENTION) applied.delete(applied.values().next().value!); state = reduceLineage(state, { name, payload }); return; } @@ -397,7 +409,17 @@ export const createAgentLineageRegistry = ( return resolve(host, native, host === 'cursor' ? 'inferred' : 'registry'); }, - resolveToolCall(query) { + async resolveToolCall(query) { + await hydrate(); + if (store !== undefined) { + // Another generated server of the same install may hold the event + // routes; its journal is the shared truth. + try { + state = (await store.read()).state; + } catch { + // Keep the head already held. + } + } const { host, meta, toolName } = query; if (host === undefined) return unavailable('id-not-resolvable'); if (host === 'codex') { @@ -435,7 +457,9 @@ export const createAgentLineageRegistry = ( let call: OpenToolCall | undefined; const claudeToolUseId = host === 'claude' ? nativeString(meta ?? {}, 'claudecode/toolUseId') : undefined; if (claudeToolUseId !== undefined) { + // A native id that matches no open window is a miss, never a licence to guess by name. call = state.openCalls.find((open) => open.toolCallId === claudeToolUseId); + if (call === undefined) return unavailable('id-not-resolvable'); } if (call === undefined) { // The open pre-tool hooks naming this tool: `MCP:` on Cursor, diff --git a/packages/rsc-runtime/tests/lineage-registry.test.ts b/packages/rsc-runtime/tests/lineage-registry.test.ts index 8f6c4c0c9..a1ce27424 100644 --- a/packages/rsc-runtime/tests/lineage-registry.test.ts +++ b/packages/rsc-runtime/tests/lineage-registry.test.ts @@ -47,7 +47,7 @@ const replay = async ( }); lineages.push({ index: position + 1, kind: record.event.canonical.event, lineage, native: record.event.native }); } else if (record.kind === 'mcp' && record.observed?.tool !== undefined) { - const lineage = registry.resolveToolCall({ + const lineage = await registry.resolveToolCall({ host: lineageHostFromClient(record.observed.client?.name) ?? host, meta: record.observed.mcpReq?._meta, toolName: record.observed.tool, @@ -252,8 +252,8 @@ describe('lineage registry replaying the 2026-09-03 host captures', () => { native: { agent_id: 'unknown-thread', session_id: 'root-thread', tool_name: 'Bash', tool_use_id: 'x' }, }); expect(lineage).toEqual(unavailable('id-not-resolvable')); - expect(registry.resolveToolCall({ host: 'cursor', toolName: 'dump' })).toEqual(unavailable('id-not-resolvable')); - expect(registry.resolveToolCall({ host: undefined, toolName: 'dump' })).toEqual(unavailable('id-not-resolvable')); + expect(await registry.resolveToolCall({ host: 'cursor', toolName: 'dump' })).toEqual(unavailable('id-not-resolvable')); + expect(await registry.resolveToolCall({ host: undefined, toolName: 'dump' })).toEqual(unavailable('id-not-resolvable')); }); it('standalone hooks state only what the payload proves', () => { @@ -301,14 +301,14 @@ describe('lineage registry edge cases raised in review', () => { expect(value(bound)).toMatchObject({ conversation: 'child-y', depth: 1, parent: 'root', subagent: { id: 'call-b' } }); }); - it('does not fabricate a Codex depth when neither the thread nor its parent is registered', () => { + it('does not fabricate a Codex depth when neither the thread nor its parent is registered', async () => { const registry = createAgentLineageRegistry(); const meta = (thread: string, parent: string | undefined) => ({ 'x-codex-turn-metadata': { session_id: 'root', thread_id: thread, turn_id: 't', ...(parent === undefined ? {} : { parent_thread_id: parent }) }, }); - expect(registry.resolveToolCall({ host: 'codex', meta: meta('root', undefined), toolName: 'dump' })).toMatchObject({ value: { depth: 0 } }); - expect(registry.resolveToolCall({ host: 'codex', meta: meta('child', 'root'), toolName: 'dump' })).toMatchObject({ value: { depth: 1, parent: 'root' } }); - expect(registry.resolveToolCall({ host: 'codex', meta: meta('grandchild', 'child'), toolName: 'dump' })).toEqual(unavailable('id-not-resolvable')); + expect(await registry.resolveToolCall({ host: 'codex', meta: meta('root', undefined), toolName: 'dump' })).toMatchObject({ value: { depth: 0 } }); + expect(await registry.resolveToolCall({ host: 'codex', meta: meta('child', 'root'), toolName: 'dump' })).toMatchObject({ value: { depth: 1, parent: 'root' } }); + expect(await registry.resolveToolCall({ host: 'codex', meta: meta('grandchild', 'child'), toolName: 'dump' })).toEqual(unavailable('id-not-resolvable')); }); }); @@ -343,7 +343,7 @@ describe('lineage registry durability and retention (review round 3)', () => { await registry.observe({ event: 'tool/after', host: 'cursor', idempotencyKey: 'close', native: { ...before, hook_event_name: 'postToolUse', tool_output: '{}' }, observedAt: '2026-09-03T00:00:01.000Z' }); await registry.observe({ event: 'tool/before', host: 'cursor', idempotencyKey: 'open', native: before, observedAt: '2026-09-03T00:00:02.000Z' }); expect(registry.snapshot().openCalls).toEqual([]); - expect(registry.resolveToolCall({ host: 'cursor', toolName: 'dump' })).toEqual(unavailable('id-not-resolvable')); + expect(await registry.resolveToolCall({ host: 'cursor', toolName: 'dump' })).toEqual(unavailable('id-not-resolvable')); await store.close(); await driver.close(); }); @@ -446,11 +446,11 @@ describe('lineage registry ambiguity refusals (review round 4)', () => { await observe('prompt/submit', 'a', { conversation_id: 'root-a', hook_event_name: 'beforeSubmitPrompt' }); await observe('prompt/submit', 'b', { conversation_id: 'root-b', hook_event_name: 'beforeSubmitPrompt' }); await observe('tool/before', 'ma', { conversation_id: 'root-a', hook_event_name: 'preToolUse', tool_input: {}, tool_name: 'MCP:dump', tool_use_id: 'ma' }); - expect(registry.resolveToolCall({ host: 'cursor', toolName: 'dump' })).toMatchObject({ value: { conversation: 'root-a' } }); + expect(await registry.resolveToolCall({ host: 'cursor', toolName: 'dump' })).toMatchObject({ value: { conversation: 'root-a' } }); await observe('tool/before', 'mb', { conversation_id: 'root-b', hook_event_name: 'preToolUse', tool_input: {}, tool_name: 'MCP:dump', tool_use_id: 'mb' }); - expect(registry.resolveToolCall({ host: 'cursor', toolName: 'dump' })).toEqual(unavailable('id-not-resolvable')); + expect(await registry.resolveToolCall({ host: 'cursor', toolName: 'dump' })).toEqual(unavailable('id-not-resolvable')); await observe('tool/after', 'mb-close', { conversation_id: 'root-b', hook_event_name: 'postToolUse', tool_input: {}, tool_name: 'MCP:dump', tool_output: '{}', tool_use_id: 'mb' }); - expect(registry.resolveToolCall({ host: 'cursor', toolName: 'dump' })).toMatchObject({ value: { conversation: 'root-a' } }); + expect(await registry.resolveToolCall({ host: 'cursor', toolName: 'dump' })).toMatchObject({ value: { conversation: 'root-a' } }); }); }); @@ -490,6 +490,39 @@ describe('lineage registry retirement and cohorts (review round 5)', () => { await observe('session/end', 'e', { hook_event_name: 'SessionEnd', reason: 'other', session_id: 'root' }); expect(registry.snapshot().openCalls).toEqual([]); expect(registry.snapshot().pendingSpawns).toEqual([]); - expect(registry.resolveToolCall({ host: 'claude', toolName: 'dump' })).toEqual(unavailable('id-not-resolvable')); + expect(await registry.resolveToolCall({ host: 'claude', toolName: 'dump' })).toEqual(unavailable('id-not-resolvable')); + }); +}); + +describe('lineage registry cross-server and storeless behaviour (review round 6)', () => { + it('re-reads the shared journal so a second registry over the same store resolves what the event host recorded', async () => { + const driver = createMemoryStateDriver({ lifetime: 'process' }); + const store = await driver.open(agentLineageStateDefinition('process')); + const eventHost = createAgentLineageRegistry({ store }); + const otherServer = createAgentLineageRegistry({ store }); + expect(await otherServer.resolveToolCall({ host: 'claude', meta: { 'claudecode/toolUseId': 'm1' }, toolName: 'dump' })).toEqual(unavailable('id-not-resolvable')); + await eventHost.observe({ event: 'session/start', host: 'claude', idempotencyKey: 's', native: { hook_event_name: 'SessionStart', session_id: 'root' } }); + await eventHost.observe({ event: 'tool/before', host: 'claude', idempotencyKey: 'm', native: { hook_event_name: 'PreToolUse', session_id: 'root', tool_input: {}, tool_name: 'mcp__plugin_p_other__dump', tool_use_id: 'm1' } }); + expect(await otherServer.resolveToolCall({ host: 'claude', meta: { 'claudecode/toolUseId': 'm1' }, toolName: 'dump' })).toMatchObject({ value: { conversation: 'root', depth: 0 } }); + await store.close(); + await driver.close(); + }); + + it('treats a supplied but unmatched Claude tool-use id as a miss instead of guessing by name', async () => { + const registry = createAgentLineageRegistry(); + await registry.observe({ event: 'session/start', host: 'claude', idempotencyKey: 's', native: { hook_event_name: 'SessionStart', session_id: 'root' } }); + await registry.observe({ event: 'tool/before', host: 'claude', idempotencyKey: 'm', native: { hook_event_name: 'PreToolUse', session_id: 'root', tool_input: {}, tool_name: 'mcp__plugin_p_s__dump', tool_use_id: 'open-1' } }); + expect(await registry.resolveToolCall({ host: 'claude', meta: { 'claudecode/toolUseId': 'missing' }, toolName: 'dump' })).toEqual(unavailable('id-not-resolvable')); + expect(await registry.resolveToolCall({ host: 'claude', meta: { 'claudecode/toolUseId': 'open-1' }, toolName: 'dump' })).toMatchObject({ value: { conversation: 'root' } }); + }); + + it('suppresses redeliveries in a storeless registry through its in-memory key ledger', async () => { + const registry = createAgentLineageRegistry(); + const before = { conversation_id: 'root', hook_event_name: 'preToolUse', tool_input: {}, tool_name: 'MCP:dump', tool_use_id: 'm1' }; + await registry.observe({ event: 'prompt/submit', host: 'cursor', idempotencyKey: 'p', native: { conversation_id: 'root', hook_event_name: 'beforeSubmitPrompt' } }); + await registry.observe({ event: 'tool/before', host: 'cursor', idempotencyKey: 'open', native: before, observedAt: '2026-09-03T00:00:00.000Z' }); + await registry.observe({ event: 'tool/after', host: 'cursor', idempotencyKey: 'close', native: { ...before, hook_event_name: 'postToolUse', tool_output: '{}' } }); + await registry.observe({ event: 'tool/before', host: 'cursor', idempotencyKey: 'open', native: before, observedAt: '2026-09-03T00:00:05.000Z' }); + expect(registry.snapshot().openCalls).toEqual([]); }); }); From c56430c9eeb63c5f7bc3841cfa36b3e47894c144 Mon Sep 17 00:00:00 2001 From: ScriptedAlchemy Date: Thu, 3 Sep 2026 12:33:26 +0000 Subject: [PATCH 11/20] fix(lineage): serialize observations, root-tag correlation windows, record windows only for placeable carriers (review) --- packages/rsc-runtime/src/lineage/registry.ts | 116 +++++++++++------- packages/rsc-runtime/src/lineage/state.ts | 7 +- .../tests/lineage-registry.test.ts | 44 +++++++ 3 files changed, 118 insertions(+), 49 deletions(-) diff --git a/packages/rsc-runtime/src/lineage/registry.ts b/packages/rsc-runtime/src/lineage/registry.ts index f23d246d5..9008332cf 100644 --- a/packages/rsc-runtime/src/lineage/registry.ts +++ b/packages/rsc-runtime/src/lineage/registry.ts @@ -358,58 +358,80 @@ export const createAgentLineageRegistry = ( await dispatch('sessionRetired', { root }, keys); }; - const registry: AgentLineageRegistry = { - async observe(observation) { - await hydrate(); - const keys = journalKeys(observation.idempotencyKey); - const observedAt = observation.observedAt ?? new Date().toISOString(); - const { event, host, native } = observation; - const carrier = lineageCarrier(host, native); - switch (event) { - case 'agent/start': - await observeStart(observation, observedAt, keys); - break; - case 'agent/stop': - await observeStop(observation, observedAt, keys); - break; - case 'session/end': - await observeSessionEnd(observation, observedAt, keys); - break; - default: - break; - } - // Claude and Codex name the root on every payload; Cursor never repeats - // it, so only root-shaped Cursor events may establish a root, and a - // fresh child conversation binds to the single pending start. - // A session that ends before this registry saw it start leaves no node - // behind: establishing one after retirement would never be pruned. - if (event !== 'session/end' && carrier.conversation !== undefined && nodeFor(carrier.conversation) === undefined) { - const rootLike = host === 'cursor' - ? CURSOR_ROOT_EVENTS.has(event) - : carrier.conversation === carrier.root; - if (rootLike || host === 'cursor') { - await ensureRoot(host, carrier.conversation, carrier.generation, observedAt, keys, rootLike); - } + // Observations mutate the tree in several awaited steps (candidate selection, + // claim, node start); running them one at a time keeps two concurrent hooks + // from selecting the same spawn or binding the same pending child. + let queue: Promise = Promise.resolve(); + const serialized = (work: () => Promise): Promise => { + const run = queue.then(work, work); + queue = run.then(() => undefined, () => undefined); + return run; + }; + + const observeSerialized = async (observation: LineageObservation): Promise> => { + await hydrate(); + const keys = journalKeys(observation.idempotencyKey); + const observedAt = observation.observedAt ?? new Date().toISOString(); + const { event, host, native } = observation; + const carrier = lineageCarrier(host, native); + switch (event) { + case 'agent/start': + await observeStart(observation, observedAt, keys); + break; + case 'agent/stop': + await observeStop(observation, observedAt, keys); + break; + case 'session/end': + await observeSessionEnd(observation, observedAt, keys); + break; + default: + break; + } + // Claude and Codex name the root on every payload; Cursor never repeats + // it, so only root-shaped Cursor events may establish a root, and a + // fresh child conversation binds to the single pending start. + // A session that ends before this registry saw it start leaves no node + // behind: establishing one after retirement would never be pruned. + if (event !== 'session/end' && carrier.conversation !== undefined && nodeFor(carrier.conversation) === undefined) { + const rootLike = host === 'cursor' + ? CURSOR_ROOT_EVENTS.has(event) + : carrier.conversation === carrier.root; + if (rootLike || host === 'cursor') { + await ensureRoot(host, carrier.conversation, carrier.generation, observedAt, keys, rootLike); } - const toolCallId = nativeString(native, 'tool_use_id') ?? nativeString(native, 'tool_call_id'); - const toolName = nativeString(native, 'tool_name'); - if (carrier.conversation !== undefined && toolCallId !== undefined && toolName !== undefined) { - if (event === 'tool/before') { - await dispatch('toolCallOpened', { - conversation: carrier.conversation, - openedAt: observedAt, - ...(SPAWN_TOOLS[host](toolName) ? { spawn: true } : {}), - toolCallId, - toolName, - }, keys); - } else if (event === 'tool/after' || event === 'tool/failure') { - await dispatch('toolCallClosed', { conversation: carrier.conversation, toolCallId }, keys); - } + } + const toolCallId = nativeString(native, 'tool_use_id') ?? nativeString(native, 'tool_call_id'); + const toolName = nativeString(native, 'tool_name'); + // Correlation windows exist only for conversations the tree can place; + // a window for an unplaceable carrier could never resolve and could not + // be retired with its session. + const carrierNode = carrier.conversation === undefined ? undefined : nodeFor(carrier.conversation); + if (carrier.conversation !== undefined && carrierNode !== undefined && toolCallId !== undefined && toolName !== undefined) { + if (event === 'tool/before') { + await dispatch('toolCallOpened', { + conversation: carrier.conversation, + openedAt: observedAt, + root: carrierNode.root, + ...(SPAWN_TOOLS[host](toolName) ? { spawn: true } : {}), + toolCallId, + toolName, + }, keys); + } else if (event === 'tool/after' || event === 'tool/failure') { + await dispatch('toolCallClosed', { conversation: carrier.conversation, toolCallId }, keys); } - return resolve(host, native, host === 'cursor' ? 'inferred' : 'registry'); + } + return resolve(host, native, host === 'cursor' ? 'inferred' : 'registry'); + }; + + const registry: AgentLineageRegistry = { + observe(observation) { + return serialized(() => observeSerialized(observation)); }, async resolveToolCall(query) { + // Observations already accepted settle first, so a call that arrived + // after its pre-tool hook sees that hook's window. + await queue; await hydrate(); if (store !== undefined) { // Another generated server of the same install may hold the event diff --git a/packages/rsc-runtime/src/lineage/state.ts b/packages/rsc-runtime/src/lineage/state.ts index a15129f87..b7e4eb806 100644 --- a/packages/rsc-runtime/src/lineage/state.ts +++ b/packages/rsc-runtime/src/lineage/state.ts @@ -29,6 +29,8 @@ export const LineageNodeSchema = z.object({ export const OpenToolCallSchema = z.object({ conversation: id, openedAt: timestamp, + /** The root the conversation belonged to when the window opened, so retirement finds it even after its node is pruned. */ + root: id.optional(), toolCallId: id, toolName: id, /** A sibling of this spawn was already claimed blind, so no later start can be matched to it with certainty. */ @@ -167,11 +169,12 @@ export const reduceLineage = ( const retired = new Set( Object.values(state.nodes).filter((node) => node.root === root).map((node) => node.id).concat(root), ); + const belongs = (open: OpenToolCall): boolean => open.root === root || retired.has(open.conversation); return { ...state, - openCalls: state.openCalls.filter((open) => !retired.has(open.conversation)), + openCalls: state.openCalls.filter((open) => !belongs(open)), pendingChildren: state.pendingChildren.filter((pending) => !retired.has(pending)), - pendingSpawns: state.pendingSpawns.filter((open) => !retired.has(open.conversation)), + pendingSpawns: state.pendingSpawns.filter((open) => !belongs(open)), }; } default: { diff --git a/packages/rsc-runtime/tests/lineage-registry.test.ts b/packages/rsc-runtime/tests/lineage-registry.test.ts index a1ce27424..a26298112 100644 --- a/packages/rsc-runtime/tests/lineage-registry.test.ts +++ b/packages/rsc-runtime/tests/lineage-registry.test.ts @@ -205,6 +205,7 @@ describe('lineage registry replaying the 2026-09-03 host captures', () => { const before = { hook_event_name: 'preToolUse', conversation_id: 'root-c', tool_input: {}, tool_name: 'Read', tool_use_id: 'call-1', }; + await registry.observe({ event: 'prompt/submit', host: 'cursor', idempotencyKey: 'prompt', native: { conversation_id: 'root-c', hook_event_name: 'beforeSubmitPrompt' } }); await registry.observe({ event: 'tool/before', host: 'cursor', idempotencyKey: 'dup', native: before, observedAt: '2026-09-03T00:00:00.000Z' }); const revisionAfterFirst = (await store.read()).revision; // A later, unrelated event advances the journal. @@ -526,3 +527,46 @@ describe('lineage registry cross-server and storeless behaviour (review round 6) expect(registry.snapshot().openCalls).toEqual([]); }); }); + +describe('lineage registry serialization (review round 7)', () => { + it('serializes concurrent starts so two sibling spawns are claimed once each', async () => { + const driver = createMemoryStateDriver({ lifetime: 'process' }); + const store = await driver.open(agentLineageStateDefinition('process')); + const registry = createAgentLineageRegistry({ store }); + const observe = (event: string, key: string, native: Record) => + registry.observe({ event, host: 'claude', idempotencyKey: key, native, observedAt: '2026-09-03T00:00:00.000Z' }); + await observe('session/start', 's', { hook_event_name: 'SessionStart', session_id: 'root' }); + await Promise.all([ + observe('tool/before', 'sp1', { hook_event_name: 'PreToolUse', session_id: 'root', tool_input: {}, tool_name: 'Agent', tool_use_id: 'sp1' }), + observe('tool/before', 'sp2', { hook_event_name: 'PreToolUse', session_id: 'root', tool_input: {}, tool_name: 'Agent', tool_use_id: 'sp2' }), + ]); + const [a, b] = await Promise.all([ + observe('agent/start', 'a', { agent_id: 'a', agent_type: 'general-purpose', hook_event_name: 'SubagentStart', session_id: 'root' }), + observe('agent/start', 'b', { agent_id: 'b', agent_type: 'general-purpose', hook_event_name: 'SubagentStart', session_id: 'root' }), + ]); + expect(value(a)).toMatchObject({ depth: 1, parent: 'root' }); + expect(value(b)).toMatchObject({ depth: 1, parent: 'root' }); + expect(registry.snapshot().pendingSpawns).toEqual([]); + await store.close(); + await driver.close(); + }); + + it('records no correlation window for a carrier the tree cannot place', async () => { + const registry = createAgentLineageRegistry(); + await registry.observe({ + event: 'tool/before', + host: 'cursor', + idempotencyKey: 'orphan', + native: { conversation_id: 'unknown', hook_event_name: 'preToolUse', tool_input: {}, tool_name: 'MCP:dump', tool_use_id: 'u' }, + }); + expect(registry.snapshot().openCalls).toEqual([]); + await registry.observe({ event: 'prompt/submit', host: 'cursor', idempotencyKey: 'p', native: { conversation_id: 'root', hook_event_name: 'beforeSubmitPrompt' } }); + await registry.observe({ + event: 'tool/before', + host: 'cursor', + idempotencyKey: 'known', + native: { conversation_id: 'root', hook_event_name: 'preToolUse', tool_input: {}, tool_name: 'MCP:dump', tool_use_id: 'k' }, + }); + expect(registry.snapshot().openCalls).toMatchObject([{ conversation: 'root', root: 'root', toolCallId: 'k' }]); + }); +}); From 967b0c4095ab130f8a890db69f458aee781eda4e Mon Sep 17 00:00:00 2001 From: ScriptedAlchemy Date: Thu, 3 Sep 2026 13:11:36 +0000 Subject: [PATCH 12/20] fix(lineage): discard failed spawns, unresolved parentless Codex threads, stay in memory after a durable commit failure, retire the journal from standalone session/end (review) --- .../src/adapters/hook-contract.ts | 42 +++++++++++++++++- packages/rsc-runtime/src/lineage/registry.ts | 36 ++++++++++++---- packages/rsc-runtime/src/lineage/state.ts | 11 ++++- .../tests/lineage-registry.test.ts | 43 +++++++++++++++++++ 4 files changed, 122 insertions(+), 10 deletions(-) diff --git a/packages/agent-bundle/src/adapters/hook-contract.ts b/packages/agent-bundle/src/adapters/hook-contract.ts index df8a2f960..0c6f1beaa 100644 --- a/packages/agent-bundle/src/adapters/hook-contract.ts +++ b/packages/agent-bundle/src/adapters/hook-contract.ts @@ -605,9 +605,14 @@ const eventRouteHookWrapperSource = ( entry: TargetHookWrapper, hostContractRevision: string, concreteTarget?: string, + durableLineage = false, ): string => { const route = entry.hook.eventRoute!; const standalone = route.runtime === 'standalone' || route.fallback === 'standalone'; + // A standalone `session/end` (the warm runtime has usually already exited by + // then) retires the durable lineage journal itself, so roots never outlive + // their session; only projects whose state is workspace-durable have one. + const retiresLineage = standalone && durableLineage && route.event === 'session/end'; const targetSource = concreteTarget !== undefined ? [`const target = ${JSON.stringify(concreteTarget)};`] : entry.target === 'plugin' @@ -624,6 +629,14 @@ const eventRouteHookWrapperSource = ( ...(standalone ? ["import { agent, available, createAgentRenderDispatcher, resolveNativeLineage, runAgentRequest, unavailable } from '@agent-bundle/runtime';"] : []), + ...(retiresLineage + ? [ + "import { join } from 'node:path';", + "import { fileURLToPath } from 'node:url';", + "import { agentLineageStateDefinition, createAgentLineageRegistry } from '@agent-bundle/runtime/lineage';", + "import { createSqliteStateDriver } from '@agent-bundle/runtime/state/sqlite';", + ] + : []), `import { EventRuntimeTransportError, requestEventRuntime } from ${JSON.stringify(eventIpcRuntimeSpecifier)};`, `import { ${standalone ? 'createCanonicalEventProps, projectEventDocument, ' : ''}validateNativeEventEnvelope } from ${JSON.stringify(eventProjectRuntimeSpecifier)};`, '', @@ -691,8 +704,30 @@ const eventRouteHookWrapperSource = ( ' await worker.terminate();', ' }', '};', + ...(retiresLineage + ? [ + 'const retireLineage = async (native, idempotencyKey, observedAt) => {', + " if (target !== 'claude' && target !== 'codex' && target !== 'cursor') return;", + " const anchor = process.env.AGENT_BUNDLE_PLUGIN_ROOT ?? fileURLToPath(new URL('..', import.meta.url));", + " const driver = createSqliteStateDriver({ root: join(anchor, 'state') });", + ' try {', + ' const store = await driver.open(agentLineageStateDefinition());', + ' try {', + ' await createAgentLineageRegistry({ store }).observe({ event: canonicalEvent, host: target, idempotencyKey, native, observedAt });', + ' } finally {', + ' await store.close();', + ' }', + ' } catch (error) {', + ' process.stderr.write(`agent-bundle lineage retirement skipped: ${error instanceof Error ? error.message : String(error)}\\n`);', + ' } finally {', + ' await driver.close().catch(() => undefined);', + ' }', + '};', + ] + : []), 'const runStandalone = async (native, signal) => {', ' const props = createCanonicalEventProps(canonicalEvent, native, target, nativeEvent, capabilityRevision, signal);', + ...(retiresLineage ? [' await retireLineage(native, props.canonical.idempotencyKey, props.canonical.observedAt);'] : []), ' const sessionId = typeof native.session_id === "string" ? native.session_id : typeof native.conversation_id === "string" ? native.conversation_id : undefined;', ' const workspaceRoot = typeof native.cwd === "string" ? native.cwd : Array.isArray(native.workspace_roots) && typeof native.workspace_roots[0] === "string" ? native.workspace_roots[0] : undefined;', // Standalone hooks hold no registry, so lineage is only what the payload proves (docs/audits/2026-09-03-host-lineage-matrix.md). @@ -1105,7 +1140,12 @@ export const planHooks = ( ...wrapper, virtualSource: hook.eventRoute === undefined ? contract.wrapperSource(wrapper) - : eventRouteHookWrapperSource(wrapper, contract.hostContractRevision ?? target, concreteEventTarget), + : eventRouteHookWrapperSource( + wrapper, + contract.hostContractRevision ?? target, + concreteEventTarget, + model.state?.lifetime === 'workspace-durable', + ), }); } diff --git a/packages/rsc-runtime/src/lineage/registry.ts b/packages/rsc-runtime/src/lineage/registry.ts index 9008332cf..b16bc428d 100644 --- a/packages/rsc-runtime/src/lineage/registry.ts +++ b/packages/rsc-runtime/src/lineage/registry.ts @@ -148,6 +148,13 @@ export const createAgentLineageRegistry = ( let state: LineageState = initialLineageState; let hydration: Promise | undefined; const applied = new Set(); + /** + * Once a durable commit fails for any reason other than a redelivery, the + * journal head no longer describes what this registry knows; it stays in + * memory from then on so a later re-read cannot erase local mutations. + */ + let degraded = false; + const journal = (): AgentStateStore | undefined => (degraded ? undefined : store); /** One shared initial read: concurrent observations all wait for it, none mutates the empty state first. */ const hydrate = (): Promise => { @@ -156,7 +163,8 @@ export const createAgentLineageRegistry = ( try { state = (await store.read()).state; } catch { - // A cold or unreadable journal degrades to in-memory tracking; resolution stays honest through `inferred`. + // An unreadable journal degrades to in-memory tracking for good. + degraded = true; } })(); return hydration; @@ -176,7 +184,8 @@ export const createAgentLineageRegistry = ( keys: JournalKeys, ): Promise => { const idempotencyKey = keys.next(name, payload); - if (store === undefined) { + const target = journal(); + if (target === undefined) { // No journal: an in-memory ledger of applied keys suppresses redeliveries. if (applied.has(idempotencyKey)) return; applied.add(idempotencyKey); @@ -185,19 +194,21 @@ export const createAgentLineageRegistry = ( return; } try { - const committed = await store.dispatch(name, payload as never, { idempotencyKey }); - state = committed.replayed ? (await store.read()).state : committed.state; + const committed = await target.dispatch(name, payload as never, { idempotencyKey }); + state = committed.replayed ? (await target.read()).state : committed.state; } catch (error) { // The same key with a payload that differs only in what the digest // ignores (a receipt timestamp) is a redelivery, not a new fact. if (error instanceof AgentStateError && error.code === 'idempotency-conflict') { try { - state = (await store.read()).state; + state = (await target.read()).state; } catch { // Keep the head we already hold. } return; } + degraded = true; + applied.add(idempotencyKey); state = reduceLineage(state, { name, payload }); } }; @@ -418,6 +429,11 @@ export const createAgentLineageRegistry = ( }, keys); } else if (event === 'tool/after' || event === 'tool/failure') { await dispatch('toolCallClosed', { conversation: carrier.conversation, toolCallId }, keys); + // A spawn that failed produced no child; Codex closes a successful + // spawn before SubagentStart, so only failure discards the claim. + if (event === 'tool/failure' && SPAWN_TOOLS[host](toolName)) { + await dispatch('spawnFailed', { toolCallId }, keys); + } } } return resolve(host, native, host === 'cursor' ? 'inferred' : 'registry'); @@ -433,11 +449,12 @@ export const createAgentLineageRegistry = ( // after its pre-tool hook sees that hook's window. await queue; await hydrate(); - if (store !== undefined) { + const target = journal(); + if (target !== undefined) { // Another generated server of the same install may hold the event // routes; its journal is the shared truth. try { - state = (await store.read()).state; + state = (await target.read()).state; } catch { // Keep the head already held. } @@ -459,7 +476,10 @@ export const createAgentLineageRegistry = ( // known for a registered node, zero for a root, one for a direct // child of the root, and otherwise only through a registered parent. const parentDepth = parent === undefined ? undefined : parent === root ? 0 : nodeFor(parent)?.depth; - const depth = known?.depth ?? (parent === undefined ? 0 : parentDepth === undefined ? undefined : parentDepth + 1); + const depth = known?.depth + ?? (parent === undefined + ? (conversation === root ? 0 : undefined) + : parentDepth === undefined ? undefined : parentDepth + 1); if (depth === undefined) return unavailable('id-not-resolvable'); const value: AgentLineage = { conversation, diff --git a/packages/rsc-runtime/src/lineage/state.ts b/packages/rsc-runtime/src/lineage/state.ts index b7e4eb806..4520ac0db 100644 --- a/packages/rsc-runtime/src/lineage/state.ts +++ b/packages/rsc-runtime/src/lineage/state.ts @@ -64,6 +64,8 @@ export const lineageEventSchemas = { sessionRetired: z.object({ root: id }).strict(), /** A subagent start consumed the spawn call that produced it; `siblingsUncertain` marks the cohort it was picked from. */ spawnClaimed: z.object({ siblingsUncertain: z.boolean().optional(), toolCallId: id }).strict(), + /** A spawn call failed before any child started, so no later start may claim it. */ + spawnFailed: z.object({ toolCallId: id }).strict(), toolCallClosed: z.object({ conversation: id, toolCallId: id }).strict(), toolCallOpened: OpenToolCallSchema.extend({ spawn: z.boolean().optional() }).strict(), } as const; @@ -164,6 +166,10 @@ export const reduceLineage = ( : open), }; } + case 'spawnFailed': { + const { toolCallId } = event.payload as { toolCallId: string }; + return { ...state, pendingSpawns: state.pendingSpawns.filter((open) => open.toolCallId !== toolCallId) }; + } case 'sessionRetired': { const { root } = event.payload as { root: string }; const retired = new Set( @@ -190,7 +196,10 @@ export const reduceLineage = ( * the MCP process mid-session does not forget which subagents are alive. */ export const agentLineageStateDefinition = (lifetime: AgentStateLifetime = 'workspace-durable') => defineState({ - budgets: { maxStateBytes: 4 * 1_048_576 }, + // The journal is append-only for the life of an install; the revision cap is + // raised well past the kernel default and the registry degrades to memory + // (never to a stale head) once any durable commit fails. + budgets: { maxRevisions: 5_000_000, maxStateBytes: 4 * 1_048_576 }, events: lineageEventSchemas, id: AGENT_LINEAGE_STATE_ID, initial: initialLineageState, diff --git a/packages/rsc-runtime/tests/lineage-registry.test.ts b/packages/rsc-runtime/tests/lineage-registry.test.ts index a26298112..4ef9f8994 100644 --- a/packages/rsc-runtime/tests/lineage-registry.test.ts +++ b/packages/rsc-runtime/tests/lineage-registry.test.ts @@ -570,3 +570,46 @@ describe('lineage registry serialization (review round 7)', () => { expect(registry.snapshot().openCalls).toMatchObject([{ conversation: 'root', root: 'root', toolCallId: 'k' }]); }); }); + +describe('lineage registry failure handling (review round 8)', () => { + it('discards a spawn whose call failed so a later start is not attributed to it', async () => { + const registry = createAgentLineageRegistry(); + const observe = (event: string, key: string, native: Record) => + registry.observe({ event, host: 'claude', idempotencyKey: key, native }); + await observe('session/start', 's', { hook_event_name: 'SessionStart', session_id: 'root' }); + await observe('tool/before', 'f', { hook_event_name: 'PreToolUse', session_id: 'root', tool_input: {}, tool_name: 'Agent', tool_use_id: 'failed' }); + await observe('tool/failure', 'ff', { error: 'boom', hook_event_name: 'PostToolUseFailure', session_id: 'root', tool_input: {}, tool_name: 'Agent', tool_use_id: 'failed' }); + expect(registry.snapshot().pendingSpawns).toEqual([]); + await observe('agent/start', 'p', { agent_id: 'parent-agent', agent_type: 'general-purpose', hook_event_name: 'SubagentStart', session_id: 'root' }); + await observe('tool/before', 'ok', { agent_id: 'parent-agent', hook_event_name: 'PreToolUse', session_id: 'root', tool_input: {}, tool_name: 'Agent', tool_use_id: 'ok' }); + const child = await observe('agent/start', 'c', { agent_id: 'child', agent_type: 'general-purpose', hook_event_name: 'SubagentStart', session_id: 'root' }); + expect(value(child)).toMatchObject({ depth: 2, parent: 'parent-agent', subagent: { toolCallId: 'ok' } }); + }); + + it('keeps a parentless non-root Codex thread unresolved', async () => { + const registry = createAgentLineageRegistry(); + expect(await registry.resolveToolCall({ + host: 'codex', + meta: { 'x-codex-turn-metadata': { session_id: 'root', thread_id: 'orphan-thread', turn_id: 't' } }, + toolName: 'dump', + })).toEqual(unavailable('id-not-resolvable')); + }); + + it('stays in memory after a durable commit fails instead of re-reading a head that lacks the mutation', async () => { + const driver = createMemoryStateDriver({ lifetime: 'process' }); + const store = await driver.open(agentLineageStateDefinition('process')); + const failing = { + ...store, + dispatch: async (name: string, payload: unknown, options: { idempotencyKey: string }) => { + if (name === 'toolCallOpened') throw new Error('journal full'); + return store.dispatch(name as never, payload as never, options); + }, + } as typeof store; + const registry = createAgentLineageRegistry({ store: failing }); + await registry.observe({ event: 'session/start', host: 'claude', idempotencyKey: 's', native: { hook_event_name: 'SessionStart', session_id: 'root' } }); + await registry.observe({ event: 'tool/before', host: 'claude', idempotencyKey: 'm', native: { hook_event_name: 'PreToolUse', session_id: 'root', tool_input: {}, tool_name: 'mcp__plugin_p_s__dump', tool_use_id: 'm1' } }); + expect(await registry.resolveToolCall({ host: 'claude', meta: { 'claudecode/toolUseId': 'm1' }, toolName: 'dump' })).toMatchObject({ value: { conversation: 'root' } }); + await store.close(); + await driver.close(); + }); +}); From 23361e5f799a4165f2f486f0c3006efe52b4c967 Mon Sep 17 00:00:00 2001 From: ScriptedAlchemy Date: Thu, 3 Sep 2026 13:39:34 +0000 Subject: [PATCH 13/20] fix(lineage): require a claimable spawn for subagent starts, exact native spawn spellings; probe redacts Basic/cookie/header credentials (review) --- docs/entry-conventions.md | 4 +++ examples/host-test/src/capture.ts | 4 +++ packages/rsc-runtime/src/lineage/registry.ts | 14 +++++++-- .../tests/lineage-registry.test.ts | 29 +++++++++++++++++++ 4 files changed, 48 insertions(+), 3 deletions(-) diff --git a/docs/entry-conventions.md b/docs/entry-conventions.md index 426fe068a..e4efba35c 100644 --- a/docs/entry-conventions.md +++ b/docs/entry-conventions.md @@ -422,6 +422,10 @@ for every event by the id the payload carries. The observed host vocabulary | Codex | `agent_id`, else `session_id` | `session_id` | the thread whose `spawn_agent` call is the newest unclaimed spawn | `_meta["x-codex-turn-metadata"]` carries `thread_id`, `parent_thread_id`, `session_id`, `turn_id` natively | | Cursor | `conversation_id` | the bound root | `parent_conversation_id` on `subagentStart`; the child's fresh `conversation_id` is bound to the newest pending start when it first speaks | the newest open `preToolUse` whose `tool_name` is `MCP:` | +A Claude or Codex subagent is placed only when its spawning pre-tool hook +(`Agent`/`Task`, `collaborationspawn_agent`) was observed, so projects that +want `parent`/`depth` for subagents route `tool/before` alongside +`agent/start`; a start with no claimable spawn stays `id-not-resolvable`. Only root-shaped Cursor events (`session/start`, `prompt/submit`, `stop`, `session/end`, `compact/*`, `workspace/open`) may establish a root; a fresh Cursor conversation seen on a tool event binds to the single pending diff --git a/examples/host-test/src/capture.ts b/examples/host-test/src/capture.ts index 0dc1caee4..93bc5c77e 100644 --- a/examples/host-test/src/capture.ts +++ b/examples/host-test/src/capture.ts @@ -66,6 +66,10 @@ const SECRET_KEY = /(?:(?>, key: string): s return typeof value === 'string' && value.trim() !== '' ? value : undefined; }; +/** + * The hosts' own subagent-spawning tools, by exact native spelling (observed + * 2026-09-03: Claude `Agent`, Codex `collaborationspawn_agent`, Cursor + * `Task`). MCP tools are prefixed (`mcp__…`) and never match. + */ const SPAWN_TOOLS: Readonly boolean>> = Object.freeze({ claude: (toolName) => toolName === 'Agent' || toolName === 'Task', - codex: (toolName) => toolName.endsWith('spawn_agent'), + codex: (toolName) => toolName === 'collaborationspawn_agent' || toolName === 'spawn_agent', cursor: (toolName) => toolName === 'Task', }); @@ -325,8 +330,11 @@ export const createAgentLineageRegistry = ( const rootNodeValue = await ensureRoot(host, root, undefined, observedAt, keys, true); if (rootNodeValue === undefined) return; const claim = await claimSpawn(host, rootNodeValue.root, keys); - if (claim.kind === 'ambiguous') return; - const parent = (claim.kind === 'claimed' ? nodeFor(claim.call.conversation) : undefined) ?? rootNodeValue; + // No spawn to claim (the pre-tool hook was missed, or the registry + // restarted) proves nothing about the parent: a nested agent would be + // misfiled under the root, so the start stays unresolved. + if (claim.kind !== 'claimed') return; + const parent = nodeFor(claim.call.conversation) ?? rootNodeValue; await dispatch('nodeStarted', { depth: parent.depth + 1, ...(carrier.generation === undefined ? {} : { generation: carrier.generation }), diff --git a/packages/rsc-runtime/tests/lineage-registry.test.ts b/packages/rsc-runtime/tests/lineage-registry.test.ts index 4ef9f8994..64adac5a4 100644 --- a/packages/rsc-runtime/tests/lineage-registry.test.ts +++ b/packages/rsc-runtime/tests/lineage-registry.test.ts @@ -388,7 +388,9 @@ describe('lineage registry durability and retention (review round 3)', () => { await observe('session/start', 's', { hook_event_name: 'SessionStart', session_id: 'root' }, '2026-09-03T00:00:00.000Z'); const total = LINEAGE_STOPPED_RETENTION + 10; for (let index = 0; index < total; index += 1) { + await observe('tool/before', `spawn-${String(index)}`, { hook_event_name: 'PreToolUse', session_id: 'root', tool_input: {}, tool_name: 'Agent', tool_use_id: `spawn-${String(index)}` }, '2026-09-03T00:00:00.000Z'); await observe('agent/start', `start-${String(index)}`, { agent_id: `agent-${String(index)}`, agent_type: 'general-purpose', hook_event_name: 'SubagentStart', session_id: 'root' }, `2026-09-03T00:00:${String(index % 60).padStart(2, '0')}.000Z`); + await observe('tool/after', `spawned-${String(index)}`, { hook_event_name: 'PostToolUse', session_id: 'root', tool_input: {}, tool_name: 'Agent', tool_response: {}, tool_use_id: `spawn-${String(index)}` }, '2026-09-03T00:00:00.000Z'); } for (let index = 0; index < total; index += 1) { await observe('agent/stop', `stop-${String(index)}`, { agent_id: `agent-${String(index)}`, agent_type: 'general-purpose', hook_event_name: 'SubagentStop', session_id: 'root', stop_hook_active: false }, `2026-09-03T01:${String(Math.floor(index / 60)).padStart(2, '0')}:${String(index % 60).padStart(2, '0')}.000Z`); @@ -580,6 +582,7 @@ describe('lineage registry failure handling (review round 8)', () => { await observe('tool/before', 'f', { hook_event_name: 'PreToolUse', session_id: 'root', tool_input: {}, tool_name: 'Agent', tool_use_id: 'failed' }); await observe('tool/failure', 'ff', { error: 'boom', hook_event_name: 'PostToolUseFailure', session_id: 'root', tool_input: {}, tool_name: 'Agent', tool_use_id: 'failed' }); expect(registry.snapshot().pendingSpawns).toEqual([]); + await observe('tool/before', 'ps', { hook_event_name: 'PreToolUse', session_id: 'root', tool_input: {}, tool_name: 'Agent', tool_use_id: 'ps' }); await observe('agent/start', 'p', { agent_id: 'parent-agent', agent_type: 'general-purpose', hook_event_name: 'SubagentStart', session_id: 'root' }); await observe('tool/before', 'ok', { agent_id: 'parent-agent', hook_event_name: 'PreToolUse', session_id: 'root', tool_input: {}, tool_name: 'Agent', tool_use_id: 'ok' }); const child = await observe('agent/start', 'c', { agent_id: 'child', agent_type: 'general-purpose', hook_event_name: 'SubagentStart', session_id: 'root' }); @@ -613,3 +616,29 @@ describe('lineage registry failure handling (review round 8)', () => { await driver.close(); }); }); + +describe('lineage registry spawn evidence (review round 9)', () => { + it('leaves a subagent start unresolved when no spawn call can be claimed', async () => { + const registry = createAgentLineageRegistry(); + await registry.observe({ event: 'session/start', host: 'claude', idempotencyKey: 's', native: { hook_event_name: 'SessionStart', session_id: 'root' } }); + const start = await registry.observe({ + event: 'agent/start', + host: 'claude', + idempotencyKey: 'orphan', + native: { agent_id: 'orphan', agent_type: 'general-purpose', hook_event_name: 'SubagentStart', session_id: 'root' }, + }); + expect(start).toEqual(unavailable('id-not-resolvable')); + expect(registry.snapshot().nodes['orphan']).toBeUndefined(); + }); + + it('does not mistake a generated MCP tool named spawn_agent for the Codex collaboration spawn', async () => { + const registry = createAgentLineageRegistry(); + const observe = (event: string, key: string, native: Record) => + registry.observe({ event, host: 'codex', idempotencyKey: key, native }); + await observe('session/start', 's', { hook_event_name: 'SessionStart', session_id: 'root' }); + await observe('tool/before', 'mcp', { hook_event_name: 'PreToolUse', session_id: 'root', tool_input: {}, tool_name: 'mcp__server__spawn_agent', tool_use_id: 'm' }); + expect(registry.snapshot().pendingSpawns).toEqual([]); + await observe('tool/before', 'sp', { hook_event_name: 'PreToolUse', session_id: 'root', tool_input: {}, tool_name: 'collaborationspawn_agent', tool_use_id: 'sp' }); + expect(registry.snapshot().pendingSpawns.map((call) => call.toolCallId)).toEqual(['sp']); + }); +}); From 090865a91d0ef42dc65d7bc2232e0aecfbdae3d1 Mon Sep 17 00:00:00 2001 From: ScriptedAlchemy Date: Thu, 3 Sep 2026 14:01:59 +0000 Subject: [PATCH 14/20] fix(lineage): carry the pre-tool generation onto correlated MCP calls, remember start identities past node pruning (review) --- packages/rsc-runtime/src/lineage/index.ts | 1 + packages/rsc-runtime/src/lineage/registry.ts | 12 ++++--- packages/rsc-runtime/src/lineage/state.ts | 18 +++++++++++ .../tests/lineage-registry.test.ts | 31 +++++++++++++++++++ 4 files changed, 57 insertions(+), 5 deletions(-) diff --git a/packages/rsc-runtime/src/lineage/index.ts b/packages/rsc-runtime/src/lineage/index.ts index d7fb168d9..107b4b82d 100644 --- a/packages/rsc-runtime/src/lineage/index.ts +++ b/packages/rsc-runtime/src/lineage/index.ts @@ -18,6 +18,7 @@ export { agentLineageStateDefinition, LINEAGE_OPEN_CALL_RETENTION, LINEAGE_PENDING_SPAWN_RETENTION, + LINEAGE_SEEN_START_RETENTION, LINEAGE_STOPPED_RETENTION, LineageNodeSchema, LineageStateSchema, diff --git a/packages/rsc-runtime/src/lineage/registry.ts b/packages/rsc-runtime/src/lineage/registry.ts index 67bf6ff83..bd4bf8b1f 100644 --- a/packages/rsc-runtime/src/lineage/registry.ts +++ b/packages/rsc-runtime/src/lineage/registry.ts @@ -305,8 +305,8 @@ export const createAgentLineageRegistry = ( const subagentId = nativeString(native, 'subagent_id') ?? nativeString(native, 'tool_call_id'); const parentId = nativeString(native, 'parent_conversation_id') ?? carrier.conversation; if (subagentId === undefined || parentId === undefined) return; - // A replayed start already registered (or bound) this child. - if (state.nodes[subagentId] !== undefined || Object.values(state.nodes).some((node) => node.subagentId === subagentId)) return; + // A replayed start already registered (or bound) this child, even if its node was pruned since. + if (state.seenStarts.includes(subagentId) || state.nodes[subagentId] !== undefined || Object.values(state.nodes).some((node) => node.subagentId === subagentId)) return; const parent = await ensureRoot(host, parentId, undefined, observedAt, keys, false); if (parent === undefined) return; await dispatch('nodeStarted', { @@ -325,8 +325,9 @@ export const createAgentLineageRegistry = ( const agentId = nativeString(native, 'agent_id'); const root = carrier.root; if (agentId === undefined || root === undefined) return; - // A replayed start must not claim a second spawn or rewrite the node. - if (state.nodes[agentId] !== undefined) return; + // A replayed start must not claim a second spawn or rewrite the node — even + // after retention pruned the node, the start identity is remembered. + if (state.seenStarts.includes(agentId) || state.nodes[agentId] !== undefined) return; const rootNodeValue = await ensureRoot(host, root, undefined, observedAt, keys, true); if (rootNodeValue === undefined) return; const claim = await claimSpawn(host, rootNodeValue.root, keys); @@ -429,6 +430,7 @@ export const createAgentLineageRegistry = ( if (event === 'tool/before') { await dispatch('toolCallOpened', { conversation: carrier.conversation, + ...(carrier.generation === undefined ? {} : { generation: carrier.generation }), openedAt: observedAt, root: carrierNode.root, ...(SPAWN_TOOLS[host](toolName) ? { spawn: true } : {}), @@ -527,7 +529,7 @@ export const createAgentLineageRegistry = ( const node = nodeFor(call.conversation); if (node === undefined) return unavailable('id-not-resolvable'); const resolution: AgentLineageResolution = claudeToolUseId !== undefined ? 'registry' : 'inferred'; - return available(lineageOf(node, undefined, resolution), 'derived'); + return available(lineageOf(node, call.generation, resolution), 'derived'); }, snapshot() { diff --git a/packages/rsc-runtime/src/lineage/state.ts b/packages/rsc-runtime/src/lineage/state.ts index 4520ac0db..b1c1b1bf2 100644 --- a/packages/rsc-runtime/src/lineage/state.ts +++ b/packages/rsc-runtime/src/lineage/state.ts @@ -28,6 +28,8 @@ export const LineageNodeSchema = z.object({ /** A pre-tool hook whose post-tool hook has not fired: the correlation window for MCP calls and spawns. */ export const OpenToolCallSchema = z.object({ conversation: id, + /** The carrier's turn-shaped id when the window opened (Cursor `generation_id`, Codex `turn_id`, Claude `prompt_id`). */ + generation: id.optional(), openedAt: timestamp, /** The root the conversation belonged to when the window opened, so retirement finds it even after its node is pruned. */ root: id.optional(), @@ -43,6 +45,12 @@ export const LineageStateSchema = z.object({ openCalls: z.array(OpenToolCallSchema), /** Cursor subagent ids whose child conversation has not been observed yet, oldest first. */ pendingChildren: z.array(id), + /** + * Every start identity ever registered (agent ids, Cursor subagent ids and + * bound conversations), newest last and bounded, so a redelivered start is + * recognized even after its node was pruned. + */ + seenStarts: z.array(id), /** * Spawn tool calls (Claude `Agent`/`Task`, Codex `spawn_agent`) not yet * claimed by a subagent start. Kept apart from `openCalls` because Codex @@ -78,6 +86,8 @@ export const LINEAGE_STOPPED_RETENTION = 256; export const LINEAGE_OPEN_CALL_RETENTION = 512; /** Spawn calls no subagent start ever claimed are dropped past this count, oldest first. */ export const LINEAGE_PENDING_SPAWN_RETENTION = 64; +/** Start identities remembered for replay detection after their nodes are pruned. */ +export const LINEAGE_SEEN_START_RETENTION = 4096; export const AGENT_LINEAGE_STATE_ID = '@agent-bundle/runtime/agent-lineage/v1'; @@ -95,8 +105,14 @@ export const initialLineageState: LineageState = Object.freeze({ openCalls: [], pendingChildren: [], pendingSpawns: [], + seenStarts: [], }); +const remember = (seen: readonly string[], ids: readonly string[]): string[] => { + const next = [...seen.filter((known) => !ids.includes(known)), ...ids]; + return next.length > LINEAGE_SEEN_START_RETENTION ? next.slice(next.length - LINEAGE_SEEN_START_RETENTION) : next; +}; + export const reduceLineage = ( state: LineageState, event: { readonly name: keyof LineageEvents; readonly payload: unknown }, @@ -111,6 +127,7 @@ export const reduceLineage = ( pendingChildren: node.subagentId !== undefined && node.subagentId === node.id ? [...state.pendingChildren.filter((pending) => pending !== node.id), node.id] : state.pendingChildren, + seenStarts: node.depth === 0 ? state.seenStarts : remember(state.seenStarts, [node.id]), }; } case 'nodeStopped': { @@ -132,6 +149,7 @@ export const reduceLineage = ( ...state, nodes: { ...rest, [conversation]: { ...pending, id: conversation } }, pendingChildren: state.pendingChildren.filter((candidate) => candidate !== subagentId), + seenStarts: remember(state.seenStarts, [conversation]), }; } case 'toolCallOpened': { diff --git a/packages/rsc-runtime/tests/lineage-registry.test.ts b/packages/rsc-runtime/tests/lineage-registry.test.ts index 64adac5a4..98c84ced3 100644 --- a/packages/rsc-runtime/tests/lineage-registry.test.ts +++ b/packages/rsc-runtime/tests/lineage-registry.test.ts @@ -642,3 +642,34 @@ describe('lineage registry spawn evidence (review round 9)', () => { expect(registry.snapshot().pendingSpawns.map((call) => call.toolCallId)).toEqual(['sp']); }); }); + +describe('lineage registry generation and replay memory (review round 10)', () => { + it('carries the pre-tool hook generation onto the correlated MCP call', async () => { + const registry = createAgentLineageRegistry(); + await registry.observe({ event: 'prompt/submit', host: 'cursor', idempotencyKey: 'p', native: { conversation_id: 'root', generation_id: 'gen-1', hook_event_name: 'beforeSubmitPrompt' } }); + await registry.observe({ event: 'tool/before', host: 'cursor', idempotencyKey: 'm', native: { conversation_id: 'root', generation_id: 'gen-2', hook_event_name: 'preToolUse', tool_input: {}, tool_name: 'MCP:dump', tool_use_id: 'm' } }); + expect(await registry.resolveToolCall({ host: 'cursor', toolName: 'dump' })).toMatchObject({ value: { conversation: 'root', generation: 'gen-2' } }); + }); + + it('recognizes a redelivered start after its node was pruned', async () => { + const registry = createAgentLineageRegistry(); + const observe = (event: string, key: string, native: Record, observedAt: string) => + registry.observe({ event, host: 'claude', idempotencyKey: key, native, observedAt }); + await observe('session/start', 's', { hook_event_name: 'SessionStart', session_id: 'root' }, '2026-09-03T00:00:00.000Z'); + const spawnAndStart = async (index: number) => { + await observe('tool/before', `spawn-${String(index)}`, { hook_event_name: 'PreToolUse', session_id: 'root', tool_input: {}, tool_name: 'Agent', tool_use_id: `spawn-${String(index)}` }, '2026-09-03T00:00:00.000Z'); + await observe('agent/start', `start-${String(index)}`, { agent_id: `agent-${String(index)}`, agent_type: 'general-purpose', hook_event_name: 'SubagentStart', session_id: 'root' }, '2026-09-03T00:00:01.000Z'); + await observe('tool/after', `spawned-${String(index)}`, { hook_event_name: 'PostToolUse', session_id: 'root', tool_input: {}, tool_name: 'Agent', tool_response: {}, tool_use_id: `spawn-${String(index)}` }, '2026-09-03T00:00:01.000Z'); + await observe('agent/stop', `stop-${String(index)}`, { agent_id: `agent-${String(index)}`, agent_type: 'general-purpose', hook_event_name: 'SubagentStop', session_id: 'root', stop_hook_active: false }, `2026-09-03T01:${String(Math.floor(index / 60)).padStart(2, '0')}:${String(index % 60).padStart(2, '0')}.000Z`); + }; + for (let index = 0; index < LINEAGE_STOPPED_RETENTION + 5; index += 1) await spawnAndStart(index); + expect(registry.snapshot().nodes['agent-0']).toBeUndefined(); + // A fresh spawn is pending for a new child when agent-0's start is redelivered late. + await observe('tool/before', 'spawn-new', { hook_event_name: 'PreToolUse', session_id: 'root', tool_input: {}, tool_name: 'Agent', tool_use_id: 'spawn-new' }, '2026-09-03T02:00:00.000Z'); + const replayed = await observe('agent/start', 'start-0', { agent_id: 'agent-0', agent_type: 'general-purpose', hook_event_name: 'SubagentStart', session_id: 'root' }, '2026-09-03T00:00:01.000Z'); + expect(replayed).toEqual(unavailable('id-not-resolvable')); + expect(registry.snapshot().pendingSpawns.map((call) => call.toolCallId)).toEqual(['spawn-new']); + const fresh = await observe('agent/start', 'start-new', { agent_id: 'agent-new', agent_type: 'general-purpose', hook_event_name: 'SubagentStart', session_id: 'root' }, '2026-09-03T02:00:01.000Z'); + expect(value(fresh)).toMatchObject({ depth: 1, subagent: { toolCallId: 'spawn-new' } }); + }); +}); From 1d55b576e23045200e7bb8a5ba95237b7dae1eb7 Mon Sep 17 00:00:00 2001 From: ScriptedAlchemy Date: Thu, 3 Sep 2026 14:11:59 +0000 Subject: [PATCH 15/20] fix(host-test): allowlist the probe host environment and count only this run's captures as evidence (review) --- examples/host-test/README.md | 11 ++++-- examples/host-test/scripts/probe.mjs | 53 ++++++++++++++++++++-------- 2 files changed, 48 insertions(+), 16 deletions(-) diff --git a/examples/host-test/README.md b/examples/host-test/README.md index 3bbae0699..0357b585b 100644 --- a/examples/host-test/README.md +++ b/examples/host-test/README.md @@ -73,8 +73,15 @@ pnpm --filter @agent-bundle-example/host-test probe:uninstall claude - `probe:capture` runs the scenario prompt through `claude -p`, `codex exec`, or `cursor-agent -p`: a shell command, a file edit, `dump`, `probe`, one subagent that repeats those and tries a nested subagent, then `HOST_TEST_DONE`. The - session transcript and a copy of `captures.ndjson` land in - `/tmp/host-test//`, followed by a rendered `host-test dump`. + session transcript and the records this run appended to `captures.ndjson` + land in `/tmp/host-test//`, followed by a rendered `host-test dump`. + Earlier runs' records are never re-copied, and the command exits non-zero + when the host fails or when the run produced no hook record or no MCP record. +- Host processes get an allowlisted environment (PATH, locale, display, proxy, + TLS plumbing) plus the isolated `HOME`; nothing else from your shell is + inherited, and even allowlisted values are dropped when they carry a + credential (proxy URLs with userinfo, bearer tokens). Hosts authenticate only + from the copied sign-in files. - `probe:uninstall` runs the host's own uninstall (`claude plugin uninstall`, `codex plugin remove`, or removing `~/.cursor/plugins/local/host-test`) and deletes the isolated home. Captures under `/tmp/host-test//` survive. diff --git a/examples/host-test/scripts/probe.mjs b/examples/host-test/scripts/probe.mjs index db66591b4..1050e548e 100644 --- a/examples/host-test/scripts/probe.mjs +++ b/examples/host-test/scripts/probe.mjs @@ -54,15 +54,30 @@ const paths = { }; const realHome = homedir(); -/** Ambient credentials never reach a host that runs with permission bypasses; the hosts authenticate from the copied sign-in files. */ -const SECRET_SHAPED_NAME = /(?:TOKEN|SECRET|PASSWORD|PASSWD|API_?KEY|CREDENTIAL|PRIVATE_KEY|ACCESS_KEY|SESSION_KEY|AUTH)/iu; -const scrubbedEnvironment = (base) => Object.fromEntries( - Object.entries(base).filter(([name]) => !SECRET_SHAPED_NAME.test(name)), +/** + * Ambient credentials never reach a host that runs with permission bypasses; + * the hosts authenticate from the copied sign-in files. The host environment + * is therefore built from an allowlist of process/locale/display plumbing, and + * even allowlisted values are dropped when they carry a credential (a proxy URL + * with userinfo, a bearer token, a key=value assignment with a secret name). + */ +const HOST_ENVIRONMENT_ALLOWLIST = new Set([ + 'PATH', 'SHELL', 'USER', 'LOGNAME', 'TERM', 'COLORTERM', 'TZ', 'TMPDIR', 'TMP', 'TEMP', + 'LANG', 'LANGUAGE', 'LC_ALL', 'LC_CTYPE', 'LC_MESSAGES', + 'DISPLAY', 'XAUTHORITY', 'WAYLAND_DISPLAY', 'XDG_RUNTIME_DIR', 'XDG_SESSION_TYPE', 'XDG_DATA_DIRS', 'XDG_CONFIG_DIRS', 'DBUS_SESSION_BUS_ADDRESS', + 'HTTP_PROXY', 'HTTPS_PROXY', 'NO_PROXY', 'http_proxy', 'https_proxy', 'no_proxy', + 'SSL_CERT_FILE', 'SSL_CERT_DIR', 'NODE_EXTRA_CA_CERTS', 'NODE_OPTIONS', + 'CI', 'NO_COLOR', 'FORCE_COLOR', 'HOST_TEST_ROOT', +]); +const CREDENTIAL_BEARING_VALUE = /(?:\/\/[^/\s:@]+:[^/\s@]+@|\b(?:bearer|basic)\s+[\w\-.=+/]{8,}|(?:^|[;&\s])(?:token|secret|password|passwd|api[_-]?key|access[_-]?key|private[_-]?key)=[^;&\s]+|\bsk-[\w-]{16,}|\bghp_[\w]{20,}|\beyJ[\w-]{10,}\.[\w-]{10,}\.[\w-]{10,})/iu; +const allowlistedEnvironment = (base) => Object.fromEntries( + Object.entries(base).filter(([name, value]) => + HOST_ENVIRONMENT_ALLOWLIST.has(name) && typeof value === 'string' && !CREDENTIAL_BEARING_VALUE.test(value)), ); -/** The isolated environment every host command runs with. HOME moves; auth is copied opaquely; ambient secrets are dropped. */ +/** The isolated environment every host command runs with. HOME moves; auth is copied opaquely; nothing else from the shell survives. */ const isolatedEnvironment = () => { - const environment = { ...scrubbedEnvironment(process.env), HOME: paths.home, HOST_TEST_LOG_DIR: paths.logDir }; + const environment = { ...allowlistedEnvironment(process.env), HOME: paths.home, HOST_TEST_LOG_DIR: paths.logDir }; switch (host) { case 'claude': environment.CLAUDE_CONFIG_DIR = join(paths.home, '.claude'); @@ -292,6 +307,10 @@ const capture = () => { if (!existsSync(paths.home)) throw new Error(`isolated home ${paths.home} missing; run probe:install ${host} first`); mkdirSync(paths.captures, { recursive: true }); const stamp = new Date().toISOString().replaceAll(/[:.]/gu, '-'); + // Only records appended by THIS run count as evidence: remember where the + // live log ends before the host starts. + const logFile = join(paths.logDir, 'captures.ndjson'); + const startOffset = existsSync(logFile) ? statSync(logFile).size : 0; let result; switch (host) { case 'claude': result = captureClaude(); break; @@ -302,23 +321,29 @@ const capture = () => { writeFileSync(join(paths.captures, `session-${stamp}.stdout.txt`), result.stdout ?? ''); writeFileSync(join(paths.captures, `session-${stamp}.stderr.txt`), result.stderr ?? ''); log(`host exit ${result.status}; transcript at ${join(paths.captures, `session-${stamp}.*`)}`); - const logFile = join(paths.logDir, 'captures.ndjson'); - if (existsSync(logFile)) { + const appended = existsSync(logFile) ? readFileSync(logFile).subarray(startOffset).toString('utf8') : ''; + const records = appended.split('\n').filter(Boolean).map((line) => JSON.parse(line)); + const kinds = new Set(records.map((record) => record.kind)); + if (records.length > 0) { const copy = join(paths.captures, `captures-${stamp}.ndjson`); - copyFileSync(logFile, copy); - const lines = readFileSync(copy, 'utf8').split('\n').filter(Boolean).length; - log(`copied ${lines} capture record(s) to ${copy}`); + writeFileSync(copy, appended.endsWith('\n') ? appended : `${appended}\n`); + log(`copied ${String(records.length)} capture record(s) from this run to ${copy}${startOffset > 0 ? ` (${String(startOffset)} bytes of earlier runs left behind)` : ''}`); const dump = run(process.execPath, [join(exampleRoot, 'dist', 'bin', 'host-test.js'), 'dump', '--log', copy], { env: process.env }); process.stdout.write(dump.stdout); process.stderr.write(dump.stderr); } else { - log(`no capture log was written at ${logFile}: the host dispatched no hook and no MCP call reached the probe`); + log(`no capture record was appended to ${logFile} by this run: the host dispatched no hook and no MCP call reached the probe`); } - // The artifacts above are kept for inspection, but a failed host session is - // not evidence: automation must see the failure. + // The artifacts above are kept for inspection, but neither a failed host + // session nor a session that produced no hook AND no MCP evidence is a + // capture: automation must see the failure. + const missing = ['event', 'mcp'].filter((kind) => !kinds.has(kind)); if (result.status !== 0) { log(`host session failed with exit ${String(result.status)}; captures above are partial evidence at best`); process.exitCode = result.status ?? 1; + } else if (missing.length > 0) { + log(`host session exited 0 but produced no ${missing.join(' and no ')} record; the scenario requires both`); + process.exitCode = 1; } }; From e0cfff96a85460d54c9732e6dbafe423f0df173d Mon Sep 17 00:00:00 2001 From: ScriptedAlchemy Date: Thu, 3 Sep 2026 14:43:29 +0000 Subject: [PATCH 16/20] test(build): refresh the Flight worker source hash after rebasing onto main --- packages/agent-bundle/tests/entry-shell.test.ts | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/packages/agent-bundle/tests/entry-shell.test.ts b/packages/agent-bundle/tests/entry-shell.test.ts index 9c3c6ff4e..18139c372 100644 --- a/packages/agent-bundle/tests/entry-shell.test.ts +++ b/packages/agent-bundle/tests/entry-shell.test.ts @@ -404,7 +404,7 @@ it('generates the warm react-server Flight worker separately from the MCP dispat ); expect(source).toContain("lineage: message.lineage ?? unavailable('not-provided'),"); expect(createHash('sha256').update(source).digest('hex')).toBe( - 'e9126849e5ad955dbd1f3d56ccdcb0eabe1293d265f861dd5a10339c1e2a3bfb', + '7544ab8820a0784210464d71bb15f6de7999f521a6dc35a920136db613cbcd66', ); expect(generate({ artifactEpoch: 'route-fixture@1.2.3', From 45d421aef5070bfe9251f4d0c4b0d800613d5604 Mon Sep 17 00:00:00 2001 From: ScriptedAlchemy Date: Thu, 3 Sep 2026 14:58:27 +0000 Subject: [PATCH 17/20] fix(lineage): record every applied journal key in the replay ledger so degradation keeps suppressing redeliveries (review) --- packages/rsc-runtime/src/lineage/registry.ts | 17 +++++++---- .../tests/lineage-registry.test.ts | 30 +++++++++++++++++++ 2 files changed, 42 insertions(+), 5 deletions(-) diff --git a/packages/rsc-runtime/src/lineage/registry.ts b/packages/rsc-runtime/src/lineage/registry.ts index bd4bf8b1f..c609a72f6 100644 --- a/packages/rsc-runtime/src/lineage/registry.ts +++ b/packages/rsc-runtime/src/lineage/registry.ts @@ -189,22 +189,29 @@ export const createAgentLineageRegistry = ( keys: JournalKeys, ): Promise => { const idempotencyKey = keys.next(name, payload); - const target = journal(); - if (target === undefined) { - // No journal: an in-memory ledger of applied keys suppresses redeliveries. - if (applied.has(idempotencyKey)) return; + // Every key this registry has applied — durably or in memory — lands in + // one bounded ledger, so a redelivery is still suppressed after the + // journal degrades mid-session (the durable head is no longer consulted). + if (applied.has(idempotencyKey)) return; + const remember = (): void => { applied.add(idempotencyKey); if (applied.size > APPLIED_KEY_RETENTION) applied.delete(applied.values().next().value!); + }; + const target = journal(); + if (target === undefined) { + remember(); state = reduceLineage(state, { name, payload }); return; } try { const committed = await target.dispatch(name, payload as never, { idempotencyKey }); + remember(); state = committed.replayed ? (await target.read()).state : committed.state; } catch (error) { // The same key with a payload that differs only in what the digest // ignores (a receipt timestamp) is a redelivery, not a new fact. if (error instanceof AgentStateError && error.code === 'idempotency-conflict') { + remember(); try { state = (await target.read()).state; } catch { @@ -213,7 +220,7 @@ export const createAgentLineageRegistry = ( return; } degraded = true; - applied.add(idempotencyKey); + remember(); state = reduceLineage(state, { name, payload }); } }; diff --git a/packages/rsc-runtime/tests/lineage-registry.test.ts b/packages/rsc-runtime/tests/lineage-registry.test.ts index 98c84ced3..e1b9a0b2d 100644 --- a/packages/rsc-runtime/tests/lineage-registry.test.ts +++ b/packages/rsc-runtime/tests/lineage-registry.test.ts @@ -673,3 +673,33 @@ describe('lineage registry generation and replay memory (review round 10)', () = expect(value(fresh)).toMatchObject({ depth: 1, subagent: { toolCallId: 'spawn-new' } }); }); }); + +describe('lineage registry replay ledger across degradation (review round 11)', () => { + it('keeps suppressing a redelivered durable commit after the journal degrades to memory', async () => { + const driver = createMemoryStateDriver({ lifetime: 'process' }); + const store = await driver.open(agentLineageStateDefinition('process')); + let fail = false; + const flaky = { + ...store, + dispatch: async (name: string, payload: unknown, options: { idempotencyKey: string }) => { + if (fail) throw new Error('journal full'); + return store.dispatch(name as never, payload as never, options); + }, + } as typeof store; + const registry = createAgentLineageRegistry({ store: flaky }); + const open = { event: 'tool/before', host: 'claude', idempotencyKey: 'm', native: { hook_event_name: 'PreToolUse', session_id: 'root', tool_input: {}, tool_name: 'mcp__plugin_p_s__dump', tool_use_id: 'm1' } } as const; + await registry.observe({ event: 'session/start', host: 'claude', idempotencyKey: 's', native: { hook_event_name: 'SessionStart', session_id: 'root' } }); + await registry.observe(open); + await registry.observe({ event: 'tool/after', host: 'claude', idempotencyKey: 'm-after', native: { hook_event_name: 'PostToolUse', session_id: 'root', tool_input: {}, tool_name: 'mcp__plugin_p_s__dump', tool_response: 'ok', tool_use_id: 'm1' } }); + expect(registry.snapshot().openCalls).toEqual([]); + // An unrelated commit fails: the registry degrades to memory for good. + fail = true; + await registry.observe({ event: 'prompt/submit', host: 'claude', idempotencyKey: 'p', native: { hook_event_name: 'UserPromptSubmit', prompt: 'again', session_id: 'root' } }); + // The earlier `tool/before` is redelivered: the closed window must stay closed. + await registry.observe(open); + expect(registry.snapshot().openCalls).toEqual([]); + expect(await registry.resolveToolCall({ host: 'claude', meta: { 'claudecode/toolUseId': 'm1' }, toolName: 'dump' })).toEqual(unavailable('id-not-resolvable')); + await store.close(); + await driver.close(); + }); +}); From b5f362b357c2bb9d049279d79c293834583ceb56 Mon Sep 17 00:00:00 2001 From: ScriptedAlchemy Date: Thu, 3 Sep 2026 15:27:27 +0000 Subject: [PATCH 18/20] fix(build): pass notice delivery and lineage through the generated MCP server together after rebasing onto main --- packages/agent-bundle/src/mcp-server-runtime.ts | 5 ++++- 1 file changed, 4 insertions(+), 1 deletion(-) diff --git a/packages/agent-bundle/src/mcp-server-runtime.ts b/packages/agent-bundle/src/mcp-server-runtime.ts index 5b1a94baf..223182151 100644 --- a/packages/agent-bundle/src/mcp-server-runtime.ts +++ b/packages/agent-bundle/src/mcp-server-runtime.ts @@ -611,7 +611,9 @@ const installNoticeInboxSubscriptions = ( context: GeneratedRouteRequestContext, ) => { assertInboxUri(request.params.uri); - const identity = requestIdentity(context, protocol.getClientVersion()?.name); + // Subscriptions are not tool calls: no pre-tool hook precedes them, so + // there is no correlation window to resolve lineage through. + const identity = requestIdentity(context, protocol.getClientVersion()?.name, unavailable('not-provided')); try { await notices.subscribe({ actor: identity.actor ?? unavailable(), @@ -676,6 +678,7 @@ const installNoticeInboxSubscriptions = ( else owed = true; return Promise.resolve(); }; +}; const lineageHostFor = (target: string): LineageHost | undefined => target === 'claude' || target === 'codex' || target === 'cursor' ? target : undefined; From 369f0ca84ab2bf1aeb0b0a8e950b5947a7a04823 Mon Sep 17 00:00:00 2001 From: ScriptedAlchemy Date: Thu, 3 Sep 2026 15:50:59 +0000 Subject: [PATCH 19/20] build(docs): resolve @agent-bundle/runtime/lineage from source in the TypeDoc program --- website/tsconfig.typedoc.json | 1 + 1 file changed, 1 insertion(+) diff --git a/website/tsconfig.typedoc.json b/website/tsconfig.typedoc.json index 44af7e068..ab430c930 100644 --- a/website/tsconfig.typedoc.json +++ b/website/tsconfig.typedoc.json @@ -14,6 +14,7 @@ "@agent-bundle/runtime": ["../packages/rsc-runtime/src/index.ts"], "@agent-bundle/runtime/plugin": ["../packages/rsc-runtime/src/plugin.ts"], "@agent-bundle/runtime/flight/server": ["../packages/rsc-runtime/src/flight/server.ts"], + "@agent-bundle/runtime/lineage": ["../packages/rsc-runtime/src/lineage/index.ts"], "@agent-bundle/runtime/mount": ["../packages/rsc-runtime/src/mount/index.ts"], "@agent-bundle/runtime/notices": ["../packages/rsc-runtime/src/notices/index.ts"], "@agent-bundle/runtime/notices/inbox-route": ["../packages/rsc-runtime/src/notices/inbox-route.ts"], From cdb5b31032e5d7c890e29b163a12fd130fe39969 Mon Sep 17 00:00:00 2001 From: ScriptedAlchemy Date: Thu, 3 Sep 2026 16:02:43 +0000 Subject: [PATCH 20/20] test(build): a durable project without resources/updated still journals lineage through sqlite --- packages/agent-bundle/tests/entry-shell.test.ts | 6 +++++- 1 file changed, 5 insertions(+), 1 deletion(-) diff --git a/packages/agent-bundle/tests/entry-shell.test.ts b/packages/agent-bundle/tests/entry-shell.test.ts index 18139c372..cef08cc97 100644 --- a/packages/agent-bundle/tests/entry-shell.test.ts +++ b/packages/agent-bundle/tests/entry-shell.test.ts @@ -1050,14 +1050,18 @@ it('conditionally emits generated state mounting without leaking sqlite into vol workerFile: 'mcp-curator-flight.mjs', }); expect(unsupportedEntry).toContain('noticeInboxRoute.noticeInboxRouteRecord(noticeInboxRoute)'); + // The sqlite driver itself stays: a workspace-durable project journals its + // lineage registry through it regardless of notice delivery. Only the notice + // runtime and its own durable store must be absent. for (const identifier of [ 'createGeneratedNoticeRuntime', 'createNoticeInboxSignaller', - '@agent-bundle/runtime/state/sqlite', + 'durableAnchor', 'notices: noticeDelivery', ]) { expect(unsupportedEntry).not.toContain(identifier); } + expect(unsupportedEntry).toContain('agentLineageStateDefinition'); // The inbox is a route of its own: a host that marks `mcp-inbox` unavailable, // or a target with no advertisement at all, exposes no inbox resource — and